levix-bot 4.9.1 → 5.0.0

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.
Files changed (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -0,0 +1,458 @@
1
+ var rd=Object.defineProperty;var id=(t,s,n)=>s in t?rd(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var $r=(t,s,n)=>id(t,typeof s!="symbol"?s+"":s,n);import{r as o,j as e,d as ce,u as me,e as ol,f as jr,g as xe,X as yt,h as Ue,B as U,C as he,i as ld,k as Ce,l as wr,m as cl,L as Kr,p as Ms,n as At,F as re,o as gn,M as Xa,q as _e,s as Q,b as od,t as cd,v as dl,w as Hr,x as Vr,y as qr,z as dd,A as He,U as ze,T as Je,D as ud,E as md,G as Za,H as ts,J as Kt,P as dt,I as be,K as Re,N as wt,O as It,Q as mt,R as et,V as ul,W as Ks,Y as st,Z as bn,_ as ml,$ as xd,S as xn,a0 as kr,a1 as ht,a2 as cn,a3 as Ts,a4 as xl,a5 as pl,a6 as Wr,a7 as Gr,a8 as pd,a9 as hd,aa as fd,ab as gd,ac as bd,ad as Hs,ae as Yt,af as ws,ag as yd,ah as hl,ai as vd,aj as pn,ak as Jr,al as jd,am as ps,an as wd,ao as kd,ap as Nd,aq as Sd,ar as Cd,a as Ed,as as Ad,at as Rd,au as _d,av as Ld}from"./index-DWcQmu0_.js";function er({src:t,name:s,icon:n}){var l;const[r,a]=o.useState(!1),i=(l=Array.from(s.trim())[0])==null?void 0:l.toUpperCase();return e.jsxs("span",{className:"relative inline-flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-brand-blue/10 text-lg font-bold text-brand-cyan",children:[e.jsx("span",{"aria-hidden":!0,children:i||n}),t&&!r&&e.jsx("img",{src:t,alt:"",loading:"lazy",onError:()=>a(!0),className:"absolute inset-0 size-full object-cover"})]})}/**
2
+ * @license lucide-react v1.46.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const fl={name:"arrow-down",size:24,node:[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]};fl.node;const Md=ce(fl);/**
7
+ * @license lucide-react v1.46.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const gl={name:"arrow-left",size:24,node:[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]};gl.node;const Td=ce(gl);/**
12
+ * @license lucide-react v1.46.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const bl={name:"arrow-up-down",size:24,node:[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]};bl.node;const Pd=ce(bl);/**
17
+ * @license lucide-react v1.46.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const yl={name:"book-user",size:24,node:[["path",{d:"M15 13a3 3 0 1 0-6 0",key:"10j68g"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}]]};yl.node;const Dd=ce(yl);/**
22
+ * @license lucide-react v1.46.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const vl={name:"bot",size:24,node:[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]};vl.node;const Cn=ce(vl);/**
27
+ * @license lucide-react v1.46.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const jl={name:"bug",size:24,node:[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]]};jl.node;const Id=ce(jl);/**
32
+ * @license lucide-react v1.46.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const wl={name:"calendar",size:24,node:[["path",{d:"M8 2v3",key:"1ioesn"}],["path",{d:"M16 2v3",key:"otl347"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}],["path",{d:"M3 9h18",key:"1pudct"}]]};wl.node;const tr=ce(wl);/**
37
+ * @license lucide-react v1.46.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const kl={name:"chevron-down",size:24,node:[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]};kl.node;const Dt=ce(kl);/**
42
+ * @license lucide-react v1.46.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const Nl={name:"chevron-left",size:24,node:[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]};Nl.node;const Xn=ce(Nl);/**
47
+ * @license lucide-react v1.46.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const Sl={name:"chevron-right",size:24,node:[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]};Sl.node;const Ps=ce(Sl);/**
52
+ * @license lucide-react v1.46.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const Cl={name:"chevron-up",size:24,node:[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]};Cl.node;const zd=ce(Cl);/**
57
+ * @license lucide-react v1.46.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */const El={name:"circle-alert",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],aliases:["alert-circle"]};El.node;const Wt=ce(El);/**
62
+ * @license lucide-react v1.46.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */const Al={name:"circle-check",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 9-5.5 5.5L8 12",key:"xofnsj"}]],aliases:["check-circle-2"]};Al.node;const Qt=ce(Al);/**
67
+ * @license lucide-react v1.46.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */const Rl={name:"circle-play",size:24,node:[["path",{d:"M9 9.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997A1 1 0 0 1 9 14.996z",key:"kmsa83"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],aliases:["play-circle"]};Rl.node;const Yr=ce(Rl);/**
72
+ * @license lucide-react v1.46.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const _l={name:"circle-plus",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],aliases:["plus-circle"]};_l.node;const Od=ce(_l);/**
77
+ * @license lucide-react v1.46.0 - ISC
78
+ *
79
+ * This source code is licensed under the ISC license.
80
+ * See the LICENSE file in the root directory of this source tree.
81
+ */const Ll={name:"circle-question-mark",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],aliases:["help-circle","circle-help"]};Ll.node;const nr=ce(Ll);/**
82
+ * @license lucide-react v1.46.0 - ISC
83
+ *
84
+ * This source code is licensed under the ISC license.
85
+ * See the LICENSE file in the root directory of this source tree.
86
+ */const Ml={name:"circle-x",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],aliases:["x-circle"]};Ml.node;const Fd=ce(Ml);/**
87
+ * @license lucide-react v1.46.0 - ISC
88
+ *
89
+ * This source code is licensed under the ISC license.
90
+ * See the LICENSE file in the root directory of this source tree.
91
+ */const Tl={name:"clock",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]]};Tl.node;const Pl=ce(Tl);/**
92
+ * @license lucide-react v1.46.0 - ISC
93
+ *
94
+ * This source code is licensed under the ISC license.
95
+ * See the LICENSE file in the root directory of this source tree.
96
+ */const Dl={name:"compass",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]]};Dl.node;const Bd=ce(Dl);/**
97
+ * @license lucide-react v1.46.0 - ISC
98
+ *
99
+ * This source code is licensed under the ISC license.
100
+ * See the LICENSE file in the root directory of this source tree.
101
+ */const Il={name:"copy",size:24,node:[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]};Il.node;const Nr=ce(Il);/**
102
+ * @license lucide-react v1.46.0 - ISC
103
+ *
104
+ * This source code is licensed under the ISC license.
105
+ * See the LICENSE file in the root directory of this source tree.
106
+ */const zl={name:"database",size:24,node:[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]};zl.node;const Qr=ce(zl);/**
107
+ * @license lucide-react v1.46.0 - ISC
108
+ *
109
+ * This source code is licensed under the ISC license.
110
+ * See the LICENSE file in the root directory of this source tree.
111
+ */const Ol={name:"download",size:24,node:[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]};Ol.node;const ns=ce(Ol);/**
112
+ * @license lucide-react v1.46.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const Fl={name:"eraser",size:24,node:[["path",{d:"M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21",key:"g5wo59"}],["path",{d:"m5.082 11.09 8.828 8.828",key:"1wx5vj"}]]};Fl.node;const Ud=ce(Fl);/**
117
+ * @license lucide-react v1.46.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const Bl={name:"external-link",size:24,node:[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]};Bl.node;const Ds=ce(Bl);/**
122
+ * @license lucide-react v1.46.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const Ul={name:"face-slightly-smiling-plus",size:24,node:[["path",{d:"M13.267 2.08a10 10 0 108.653 8.653",key:"1wbpyh"}],["path",{d:"M15 10V9",key:"4dkmfx"}],["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M16.472 15a6 6 0 01-8.943 0",key:"7qomzy"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M9 10V9",key:"1lazqi"}]],aliases:["smile-plus"]};Ul.node;const ks=ce(Ul);/**
127
+ * @license lucide-react v1.46.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const $l={name:"file-text",size:24,node:[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]};$l.node;const ss=ce($l);/**
132
+ * @license lucide-react v1.46.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const Kl={name:"funnel",size:24,node:[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],aliases:["filter"]};Kl.node;const $d=ce(Kl);/**
137
+ * @license lucide-react v1.46.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const Hl={name:"globe",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]};Hl.node;const Is=ce(Hl);/**
142
+ * @license lucide-react v1.46.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const Vl={name:"grip-vertical",size:24,node:[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]};Vl.node;const Xr=ce(Vl);/**
147
+ * @license lucide-react v1.46.0 - ISC
148
+ *
149
+ * This source code is licensed under the ISC license.
150
+ * See the LICENSE file in the root directory of this source tree.
151
+ */const ql={name:"hard-drive",size:24,node:[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]]};ql.node;const Ns=ce(ql);/**
152
+ * @license lucide-react v1.46.0 - ISC
153
+ *
154
+ * This source code is licensed under the ISC license.
155
+ * See the LICENSE file in the root directory of this source tree.
156
+ */const Wl={name:"heart-handshake",size:24,node:[["path",{d:"M19.414 14.414C21 12.828 22 11.5 22 9.5a5.5 5.5 0 0 0-9.591-3.676.6.6 0 0 1-.818.001A5.5 5.5 0 0 0 2 9.5c0 2.3 1.5 4 3 5.5l5.535 5.362a2 2 0 0 0 2.879.052 2.12 2.12 0 0 0-.004-3 2.124 2.124 0 1 0 3-3 2.124 2.124 0 0 0 3.004 0 2 2 0 0 0 0-2.828l-1.881-1.882a2.41 2.41 0 0 0-3.409 0l-1.71 1.71a2 2 0 0 1-2.828 0 2 2 0 0 1 0-2.828l2.823-2.762",key:"17lmqv"}]]};Wl.node;const Kd=ce(Wl);/**
157
+ * @license lucide-react v1.46.0 - ISC
158
+ *
159
+ * This source code is licensed under the ISC license.
160
+ * See the LICENSE file in the root directory of this source tree.
161
+ */const Gl={name:"images",size:24,node:[["path",{d:"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16",key:"9kzy35"}],["path",{d:"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2",key:"1t0f0t"}],["circle",{cx:"13",cy:"7",r:"1",fill:"currentColor",key:"1obus6"}],["rect",{x:"8",y:"2",width:"14",height:"14",rx:"2",key:"1gvhby"}]]};Gl.node;const Hd=ce(Gl);/**
162
+ * @license lucide-react v1.46.0 - ISC
163
+ *
164
+ * This source code is licensed under the ISC license.
165
+ * See the LICENSE file in the root directory of this source tree.
166
+ */const Jl={name:"info",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]};Jl.node;const Vd=ce(Jl);/**
167
+ * @license lucide-react v1.46.0 - ISC
168
+ *
169
+ * This source code is licensed under the ISC license.
170
+ * See the LICENSE file in the root directory of this source tree.
171
+ */const Yl={name:"key",size:24,node:[["path",{d:"m2 21 9.6-9.6",key:"9l79m3"}],["path",{d:"m7.5 15.5 2.3 2.3a1 1 0 0 1 0 1.4l-2.1 2.1a1 1 0 0 1-1.4 0L4 19",key:"fw8biw"}],["circle",{cx:"15.5",cy:"7.5",r:"5.5",key:"4wxmhb"}]]};Yl.node;const sr=ce(Yl);/**
172
+ * @license lucide-react v1.46.0 - ISC
173
+ *
174
+ * This source code is licensed under the ISC license.
175
+ * See the LICENSE file in the root directory of this source tree.
176
+ */const Ql={name:"layout-grid",size:24,node:[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]};Ql.node;const qd=ce(Ql);/**
177
+ * @license lucide-react v1.46.0 - ISC
178
+ *
179
+ * This source code is licensed under the ISC license.
180
+ * See the LICENSE file in the root directory of this source tree.
181
+ */const Xl={name:"lightbulb",size:24,node:[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]};Xl.node;const Wd=ce(Xl);/**
182
+ * @license lucide-react v1.46.0 - ISC
183
+ *
184
+ * This source code is licensed under the ISC license.
185
+ * See the LICENSE file in the root directory of this source tree.
186
+ */const Zl={name:"lock",size:24,node:[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]};Zl.node;const Sr=ce(Zl);/**
187
+ * @license lucide-react v1.46.0 - ISC
188
+ *
189
+ * This source code is licensed under the ISC license.
190
+ * See the LICENSE file in the root directory of this source tree.
191
+ */const eo={name:"log-out",size:24,node:[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]};eo.node;const Gd=ce(eo);/**
192
+ * @license lucide-react v1.46.0 - ISC
193
+ *
194
+ * This source code is licensed under the ISC license.
195
+ * See the LICENSE file in the root directory of this source tree.
196
+ */const to={name:"mail",size:24,node:[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]]};to.node;const Jd=ce(to);/**
197
+ * @license lucide-react v1.46.0 - ISC
198
+ *
199
+ * This source code is licensed under the ISC license.
200
+ * See the LICENSE file in the root directory of this source tree.
201
+ */const no={name:"menu",size:24,node:[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]};no.node;const Yd=ce(no);/**
202
+ * @license lucide-react v1.46.0 - ISC
203
+ *
204
+ * This source code is licensed under the ISC license.
205
+ * See the LICENSE file in the root directory of this source tree.
206
+ */const so={name:"merge",size:24,node:[["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22",key:"1hyw0i"}],["path",{d:"m20 22-5-5",key:"1m27yz"}]]};so.node;const Qd=ce(so);/**
207
+ * @license lucide-react v1.46.0 - ISC
208
+ *
209
+ * This source code is licensed under the ISC license.
210
+ * See the LICENSE file in the root directory of this source tree.
211
+ */const ao={name:"message-square-heart",size:24,node:[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5",key:"1faxuh"}]]};ao.node;const zs=ce(ao);/**
212
+ * @license lucide-react v1.46.0 - ISC
213
+ *
214
+ * This source code is licensed under the ISC license.
215
+ * See the LICENSE file in the root directory of this source tree.
216
+ */const ro={name:"message-square",size:24,node:[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]]};ro.node;const Ss=ce(ro);/**
217
+ * @license lucide-react v1.46.0 - ISC
218
+ *
219
+ * This source code is licensed under the ISC license.
220
+ * See the LICENSE file in the root directory of this source tree.
221
+ */const io={name:"message-square-x",size:24,node:[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"m14.5 8.5-5 5",key:"19tnj2"}],["path",{d:"m9.5 8.5 5 5",key:"1oa8ql"}]]};io.node;const Cs=ce(io);/**
222
+ * @license lucide-react v1.46.0 - ISC
223
+ *
224
+ * This source code is licensed under the ISC license.
225
+ * See the LICENSE file in the root directory of this source tree.
226
+ */const lo={name:"mic",size:24,node:[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]};lo.node;const oo=ce(lo);/**
227
+ * @license lucide-react v1.46.0 - ISC
228
+ *
229
+ * This source code is licensed under the ISC license.
230
+ * See the LICENSE file in the root directory of this source tree.
231
+ */const co={name:"moon",size:24,node:[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]]};co.node;const Xd=ce(co);/**
232
+ * @license lucide-react v1.46.0 - ISC
233
+ *
234
+ * This source code is licensed under the ISC license.
235
+ * See the LICENSE file in the root directory of this source tree.
236
+ */const uo={name:"package",size:24,node:[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]};uo.node;const ar=ce(uo);/**
237
+ * @license lucide-react v1.46.0 - ISC
238
+ *
239
+ * This source code is licensed under the ISC license.
240
+ * See the LICENSE file in the root directory of this source tree.
241
+ */const mo={name:"paperclip",size:24,node:[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]};mo.node;const Hn=ce(mo);/**
242
+ * @license lucide-react v1.46.0 - ISC
243
+ *
244
+ * This source code is licensed under the ISC license.
245
+ * See the LICENSE file in the root directory of this source tree.
246
+ */const xo={name:"pen-line",size:24,node:[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],aliases:["edit-3"]};xo.node;const Zd=ce(xo);/**
247
+ * @license lucide-react v1.46.0 - ISC
248
+ *
249
+ * This source code is licensed under the ISC license.
250
+ * See the LICENSE file in the root directory of this source tree.
251
+ */const po={name:"pencil",size:24,node:[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]};po.node;const as=ce(po);/**
252
+ * @license lucide-react v1.46.0 - ISC
253
+ *
254
+ * This source code is licensed under the ISC license.
255
+ * See the LICENSE file in the root directory of this source tree.
256
+ */const ho={name:"phone",size:24,node:[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384",key:"9njp5v"}]]};ho.node;const eu=ce(ho);/**
257
+ * @license lucide-react v1.46.0 - ISC
258
+ *
259
+ * This source code is licensed under the ISC license.
260
+ * See the LICENSE file in the root directory of this source tree.
261
+ */const fo={name:"play",size:24,node:[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]};fo.node;const go=ce(fo);/**
262
+ * @license lucide-react v1.46.0 - ISC
263
+ *
264
+ * This source code is licensed under the ISC license.
265
+ * See the LICENSE file in the root directory of this source tree.
266
+ */const bo={name:"plus",size:24,node:[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]};bo.node;const _t=ce(bo);/**
267
+ * @license lucide-react v1.46.0 - ISC
268
+ *
269
+ * This source code is licensed under the ISC license.
270
+ * See the LICENSE file in the root directory of this source tree.
271
+ */const yo={name:"qr-code",size:24,node:[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]]};yo.node;const Zs=ce(yo);/**
272
+ * @license lucide-react v1.46.0 - ISC
273
+ *
274
+ * This source code is licensed under the ISC license.
275
+ * See the LICENSE file in the root directory of this source tree.
276
+ */const vo={name:"radio",size:24,node:[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]};vo.node;const Cr=ce(vo);/**
277
+ * @license lucide-react v1.46.0 - ISC
278
+ *
279
+ * This source code is licensed under the ISC license.
280
+ * See the LICENSE file in the root directory of this source tree.
281
+ */const jo={name:"refresh-cw",size:24,node:[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]};jo.node;const it=ce(jo);/**
282
+ * @license lucide-react v1.46.0 - ISC
283
+ *
284
+ * This source code is licensed under the ISC license.
285
+ * See the LICENSE file in the root directory of this source tree.
286
+ */const wo={name:"rotate-ccw-clock",size:24,node:[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],aliases:["history"]};wo.node;const tu=ce(wo);/**
287
+ * @license lucide-react v1.46.0 - ISC
288
+ *
289
+ * This source code is licensed under the ISC license.
290
+ * See the LICENSE file in the root directory of this source tree.
291
+ */const ko={name:"rotate-ccw",size:24,node:[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]};ko.node;const ft=ce(ko);/**
292
+ * @license lucide-react v1.46.0 - ISC
293
+ *
294
+ * This source code is licensed under the ISC license.
295
+ * See the LICENSE file in the root directory of this source tree.
296
+ */const No={name:"save",size:24,node:[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]};No.node;const yn=ce(No);/**
297
+ * @license lucide-react v1.46.0 - ISC
298
+ *
299
+ * This source code is licensed under the ISC license.
300
+ * See the LICENSE file in the root directory of this source tree.
301
+ */const So={name:"search",size:24,node:[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]};So.node;const Er=ce(So);/**
302
+ * @license lucide-react v1.46.0 - ISC
303
+ *
304
+ * This source code is licensed under the ISC license.
305
+ * See the LICENSE file in the root directory of this source tree.
306
+ */const Co={name:"send",size:24,node:[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]};Co.node;const vn=ce(Co);/**
307
+ * @license lucide-react v1.46.0 - ISC
308
+ *
309
+ * This source code is licensed under the ISC license.
310
+ * See the LICENSE file in the root directory of this source tree.
311
+ */const Eo={name:"settings-2",size:24,node:[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]};Eo.node;const nu=ce(Eo);/**
312
+ * @license lucide-react v1.46.0 - ISC
313
+ *
314
+ * This source code is licensed under the ISC license.
315
+ * See the LICENSE file in the root directory of this source tree.
316
+ */const Ao={name:"settings",size:24,node:[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]};Ao.node;const su=ce(Ao);/**
317
+ * @license lucide-react v1.46.0 - ISC
318
+ *
319
+ * This source code is licensed under the ISC license.
320
+ * See the LICENSE file in the root directory of this source tree.
321
+ */const Ro={name:"share-2",size:24,node:[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]};Ro.node;const rs=ce(Ro);/**
322
+ * @license lucide-react v1.46.0 - ISC
323
+ *
324
+ * This source code is licensed under the ISC license.
325
+ * See the LICENSE file in the root directory of this source tree.
326
+ */const _o={name:"shield-alert",size:24,node:[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]};_o.node;const Zr=ce(_o);/**
327
+ * @license lucide-react v1.46.0 - ISC
328
+ *
329
+ * This source code is licensed under the ISC license.
330
+ * See the LICENSE file in the root directory of this source tree.
331
+ */const Lo={name:"shield",size:24,node:[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]};Lo.node;const Ar=ce(Lo);/**
332
+ * @license lucide-react v1.46.0 - ISC
333
+ *
334
+ * This source code is licensed under the ISC license.
335
+ * See the LICENSE file in the root directory of this source tree.
336
+ */const Mo={name:"sliders-vertical",size:24,node:[["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M12 21v-9",key:"17s77i"}],["path",{d:"M12 8V3",key:"13r4qs"}],["path",{d:"M17 16h4",key:"h1uq16"}],["path",{d:"M19 12V3",key:"o1uvq1"}],["path",{d:"M19 21v-5",key:"qua636"}],["path",{d:"M3 14h4",key:"bcjad9"}],["path",{d:"M5 10V3",key:"cb8scm"}],["path",{d:"M5 21v-7",key:"1w1uti"}]],aliases:["sliders"]};Mo.node;const To=ce(Mo);/**
337
+ * @license lucide-react v1.46.0 - ISC
338
+ *
339
+ * This source code is licensed under the ISC license.
340
+ * See the LICENSE file in the root directory of this source tree.
341
+ */const Po={name:"smartphone",size:24,node:[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]};Po.node;const hn=ce(Po);/**
342
+ * @license lucide-react v1.46.0 - ISC
343
+ *
344
+ * This source code is licensed under the ISC license.
345
+ * See the LICENSE file in the root directory of this source tree.
346
+ */const Do={name:"sparkles",size:24,node:[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],aliases:["stars"]};Do.node;const Vs=ce(Do);/**
347
+ * @license lucide-react v1.46.0 - ISC
348
+ *
349
+ * This source code is licensed under the ISC license.
350
+ * See the LICENSE file in the root directory of this source tree.
351
+ */const Io={name:"square",size:24,node:[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]};Io.node;const au=ce(Io);/**
352
+ * @license lucide-react v1.46.0 - ISC
353
+ *
354
+ * This source code is licensed under the ISC license.
355
+ * See the LICENSE file in the root directory of this source tree.
356
+ */const zo={name:"star",size:24,node:[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]};zo.node;const qs=ce(zo);/**
357
+ * @license lucide-react v1.46.0 - ISC
358
+ *
359
+ * This source code is licensed under the ISC license.
360
+ * See the LICENSE file in the root directory of this source tree.
361
+ */const Oo={name:"sticker",size:24,node:[["path",{d:"M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z",key:"1dfntj"}],["path",{d:"M15 3v5a1 1 0 0 0 1 1h5",key:"6s6qgf"}],["path",{d:"M8 13h.01",key:"1sbv64"}],["path",{d:"M16 13h.01",key:"wip0gl"}],["path",{d:"M10 16s.8 1 2 1c1.3 0 2-1 2-1",key:"1vvgv3"}]]};Oo.node;const Rr=ce(Oo);/**
362
+ * @license lucide-react v1.46.0 - ISC
363
+ *
364
+ * This source code is licensed under the ISC license.
365
+ * See the LICENSE file in the root directory of this source tree.
366
+ */const Fo={name:"sun",size:24,node:[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]};Fo.node;const ru=ce(Fo);/**
367
+ * @license lucide-react v1.46.0 - ISC
368
+ *
369
+ * This source code is licensed under the ISC license.
370
+ * See the LICENSE file in the root directory of this source tree.
371
+ */const Bo={name:"tag",size:24,node:[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]};Bo.node;const iu=ce(Bo);/**
372
+ * @license lucide-react v1.46.0 - ISC
373
+ *
374
+ * This source code is licensed under the ISC license.
375
+ * See the LICENSE file in the root directory of this source tree.
376
+ */const Uo={name:"terminal",size:24,node:[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]};Uo.node;const en=ce(Uo);/**
377
+ * @license lucide-react v1.46.0 - ISC
378
+ *
379
+ * This source code is licensed under the ISC license.
380
+ * See the LICENSE file in the root directory of this source tree.
381
+ */const $o={name:"trash",size:24,node:[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],aliases:["trash-2"]};$o.node;const lt=ce($o);/**
382
+ * @license lucide-react v1.46.0 - ISC
383
+ *
384
+ * This source code is licensed under the ISC license.
385
+ * See the LICENSE file in the root directory of this source tree.
386
+ */const Ko={name:"triangle-alert",size:24,node:[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],aliases:["alert-triangle"]};Ko.node;const tn=ce(Ko);/**
387
+ * @license lucide-react v1.46.0 - ISC
388
+ *
389
+ * This source code is licensed under the ISC license.
390
+ * See the LICENSE file in the root directory of this source tree.
391
+ */const Ho={name:"type",size:24,node:[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]]};Ho.node;const lu=ce(Ho);/**
392
+ * @license lucide-react v1.46.0 - ISC
393
+ *
394
+ * This source code is licensed under the ISC license.
395
+ * See the LICENSE file in the root directory of this source tree.
396
+ */const Vo={name:"undo-2",size:24,node:[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]};Vo.node;const qo=ce(Vo);/**
397
+ * @license lucide-react v1.46.0 - ISC
398
+ *
399
+ * This source code is licensed under the ISC license.
400
+ * See the LICENSE file in the root directory of this source tree.
401
+ */const Wo={name:"unlink",size:24,node:[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]]};Wo.node;const ou=ce(Wo);/**
402
+ * @license lucide-react v1.46.0 - ISC
403
+ *
404
+ * This source code is licensed under the ISC license.
405
+ * See the LICENSE file in the root directory of this source tree.
406
+ */const Go={name:"upload",size:24,node:[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]]};Go.node;const _r=ce(Go);/**
407
+ * @license lucide-react v1.46.0 - ISC
408
+ *
409
+ * This source code is licensed under the ISC license.
410
+ * See the LICENSE file in the root directory of this source tree.
411
+ */const Jo={name:"user-x",size:24,node:[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]};Jo.node;const cu=ce(Jo);/**
412
+ * @license lucide-react v1.46.0 - ISC
413
+ *
414
+ * This source code is licensed under the ISC license.
415
+ * See the LICENSE file in the root directory of this source tree.
416
+ */const Yo={name:"user",size:24,node:[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]};Yo.node;const Lr=ce(Yo);/**
417
+ * @license lucide-react v1.46.0 - ISC
418
+ *
419
+ * This source code is licensed under the ISC license.
420
+ * See the LICENSE file in the root directory of this source tree.
421
+ */const Qo={name:"users",size:24,node:[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]]};Qo.node;const En=ce(Qo);/**
422
+ * @license lucide-react v1.46.0 - ISC
423
+ *
424
+ * This source code is licensed under the ISC license.
425
+ * See the LICENSE file in the root directory of this source tree.
426
+ */const Xo={name:"video",size:24,node:[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]};Xo.node;const du=ce(Xo);/**
427
+ * @license lucide-react v1.46.0 - ISC
428
+ *
429
+ * This source code is licensed under the ISC license.
430
+ * See the LICENSE file in the root directory of this source tree.
431
+ */const Zo={name:"volume-2",size:24,node:[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]};Zo.node;const uu=ce(Zo);/**
432
+ * @license lucide-react v1.46.0 - ISC
433
+ *
434
+ * This source code is licensed under the ISC license.
435
+ * See the LICENSE file in the root directory of this source tree.
436
+ */const ec={name:"wrench",size:24,node:[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]};ec.node;const tc=ce(ec),mu={default:{overlay:"items-center overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))]",panel:"my-auto max-h-[var(--dialog-max-height)] max-w-[var(--dialog-max-width)] rounded-2xl",header:""},mobileFullscreen:{overlay:"items-stretch p-0 sm:items-center sm:overflow-y-auto sm:p-4 sm:pb-[max(1rem,env(safe-area-inset-bottom))]",panel:"h-dvh max-h-dvh max-w-none rounded-none sm:my-auto sm:h-auto sm:max-h-[var(--dialog-max-height)] sm:max-w-[var(--dialog-max-width)] sm:rounded-2xl",header:"pt-[max(1rem,env(safe-area-inset-top))] sm:pt-4 md:pt-5"}};function Ye({isOpen:t,onClose:s,title:n,children:r,footer:a,maxWidth:i,description:l,className:d,variant:c="default"}){const{t:m}=me(),u=o.useRef(null),p=o.useId(),h=o.useId();if(ol(u,t,s),!t)return null;const g={paddingBottom:"max(1rem, env(safe-area-inset-bottom))"},x=mu[c];return jr.createPortal(e.jsxs("div",{className:Ue("fixed inset-0 z-50 flex justify-center",x.overlay),children:[e.jsx("button",{type:"button",className:"fixed inset-0 cursor-default border-0 bg-black/65 p-0 backdrop-blur-sm",onClick:s,"aria-label":m("close")}),e.jsxs("div",{ref:u,role:"dialog","aria-modal":"true","aria-labelledby":p,"aria-describedby":l?h:void 0,tabIndex:-1,"data-overlay":"dialog",className:Ue("relative z-10 flex w-full flex-col overflow-hidden border border-line bg-panel shadow-2xl outline-none",x.panel,d),style:{"--dialog-max-width":i||"32.5rem","--dialog-max-height":"calc(100dvh - 1rem - max(1rem, env(safe-area-inset-bottom)))",animation:"modal-enter 150ms ease-out"},children:[e.jsxs("div",{className:Ue("flex shrink-0 items-center justify-between gap-3 border-b border-line p-4 md:p-5",x.header),children:[e.jsx("h2",{id:p,className:"min-w-0 text-base font-bold text-text-main md:text-lg",children:n}),e.jsx(xe,{label:m("close"),icon:e.jsx(yt,{size:18}),onClick:s})]}),e.jsxs("div",{className:Ue("min-h-0 flex-1 overflow-y-auto p-4 md:p-5",!a&&"pb-[max(1rem,env(safe-area-inset-bottom))]"),style:a?void 0:g,children:[l&&e.jsx("p",{id:h,className:"mb-3 text-sm text-muted",children:l}),r]}),a&&e.jsx("div",{className:"sticky bottom-0 flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-line bg-panel-raised/50 p-4 pb-[max(1rem,env(safe-area-inset-bottom))]",style:g,children:a})]})]}),document.body)}function ut({isOpen:t,onClose:s,onConfirm:n,title:r,description:a,confirmLabel:i,cancelLabel:l,variant:d="danger",loading:c=!1,children:m,maxWidth:u}){return e.jsx(Ye,{isOpen:t,onClose:s,title:r,description:a,maxWidth:u,footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:s,disabled:c,children:l}),e.jsx(U,{variant:d==="danger"?"danger":"primary",onClick:n,loading:c,children:i})]}),children:m})}function is({summary:t,children:s}){const[n,r]=o.useState(!1),a=o.useId();return e.jsxs(he,{padded:!1,className:"min-w-0 self-start overflow-hidden",children:[e.jsxs(U,{variant:"ghost",className:"h-auto w-full justify-between gap-3 p-4 text-start","aria-expanded":n,"aria-controls":a,id:`${a}-trigger`,onClick:()=>r(i=>!i),children:[e.jsx("span",{className:"min-w-0 flex-1",children:t}),e.jsx(Dt,{size:18,"aria-hidden":!0,className:`shrink-0 transition-transform motion-reduce:transition-none ${n?"rotate-180":""}`})]}),e.jsx("section",{id:a,"aria-labelledby":`${a}-trigger`,"aria-hidden":!n,inert:!n,className:`grid transition-[grid-template-rows] duration-200 motion-reduce:transition-none ${n?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:e.jsx("div",{className:"min-h-0 overflow-hidden",children:e.jsx("div",{className:"border-t border-line p-4",children:s})})})]})}function nt({className:t,label:s}){return e.jsxs("span",{role:s?"status":void 0,className:Ue("inline-flex items-center gap-2",s&&"text-muted"),children:[e.jsx("span",{"aria-hidden":!0,className:Ue("size-4 shrink-0 rounded-full border-2 border-brand-blue border-t-transparent animate-spin",t)}),s&&e.jsx("span",{className:"text-xs",children:s})]})}function vt({text:t}){return e.jsx("div",{className:"flex flex-col items-center justify-center gap-2 py-16",children:e.jsx(nt,{className:"size-6",label:t})})}function Ve({className:t}){return e.jsx("div",{"aria-hidden":!0,className:Ue("animate-pulse rounded-lg bg-panel-hover",t)})}function Pe({kind:t,icon:s,title:n,text:r,description:a,action:i,className:l}){const{t:d}=me(),c=t==="empty"?d("emptyRecords"):t==="no-results"?d("emptyMatches"):t==="error"?d("loadError"):null;return e.jsxs("div",{role:t==="error"?"alert":void 0,className:Ue("flex flex-col items-center justify-center gap-2 px-4 py-12 text-center sm:py-16",l),children:[s&&e.jsx("div",{className:"text-muted",children:s}),(n||c)&&e.jsx("p",{className:"text-base font-bold text-text-main",children:n??c}),(r||a)&&e.jsx("p",{className:"max-w-md text-sm text-muted",children:a??r}),i]})}function zt({label:t,resetLabel:s,activeCount:n=0,onReset:r,children:a}){const[i,l]=o.useState(!1),d=n>0?`${t} (${n})`:t;return e.jsxs(ld,{open:i,onOpenChange:l,align:"end",label:t,haspopup:"dialog",className:"w-[min(20rem,calc(100vw-1rem))] p-3",badge:n>0?e.jsx(Ce,{tone:"info",className:"pointer-events-none absolute -top-1 -end-1 z-10 h-5 min-w-5 justify-center px-1 tabular-nums",children:n}):null,trigger:e.jsx(xe,{label:d,icon:e.jsx($d,{size:18}),pressed:n>0}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-sm font-bold text-text-main",children:t}),r&&e.jsx(U,{variant:"ghost",size:"sm",onClick:r,disabled:n===0,children:s})]}),e.jsx("div",{className:"flex flex-col gap-3",children:a})]})}function rr({label:t,content:s,children:n,className:r}){const[a,i]=o.useState(!1),[l,d]=o.useState(null),c=o.useRef(null),m=o.useRef(null),u=o.useRef(!1),p=o.useId();return o.useLayoutEffect(()=>{if(!a)return;const h=()=>{var S,b;const g=(S=c.current)==null?void 0:S.getBoundingClientRect(),x=(b=m.current)==null?void 0:b.getBoundingClientRect();if(!g||!x)return;const f=8,k=Math.max(f,Math.min(g.left+g.width/2-x.width/2,window.innerWidth-f-x.width)),N=g.top>=x.height+f+6?g.top-x.height-6:g.bottom+6,w=Math.max(f,Math.min(N,window.innerHeight-f-x.height));d({top:w,left:k})};return h(),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0),()=>{window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0)}},[a]),o.useEffect(()=>{if(!a)return;const h=x=>{var f,k;x.target instanceof Node&&!((f=c.current)!=null&&f.contains(x.target))&&!((k=m.current)!=null&&k.contains(x.target))&&i(!1)},g=x=>{x.key==="Escape"&&i(!1)};return document.addEventListener("pointerdown",h),document.addEventListener("keydown",g),()=>{document.removeEventListener("pointerdown",h),document.removeEventListener("keydown",g)}},[a]),e.jsxs(e.Fragment,{children:[e.jsx(xe,{ref:c,label:t,title:"",icon:n,variant:"ghost",className:r,"aria-describedby":a?p:void 0,onPointerDown:h=>{u.current=h.pointerType==="touch"},onPointerEnter:h=>{h.pointerType==="mouse"&&i(!0)},onPointerLeave:h=>{h.pointerType==="mouse"&&document.activeElement!==c.current&&i(!1)},onFocus:()=>{u.current||i(!0)},onBlur:()=>{u.current=!1,i(!1)},onClick:()=>{u.current&&i(h=>!h)}}),a&&jr.createPortal(e.jsx("div",{ref:m,id:p,role:"tooltip",className:"fixed z-[80] max-h-[calc(100dvh-1rem)] w-max max-w-[calc(100vw-1rem)] overflow-y-auto rounded-lg border border-line bg-panel-solid px-3 py-2 text-xs leading-relaxed text-text-main shadow-lg",style:{top:(l==null?void 0:l.top)??0,left:(l==null?void 0:l.left)??0,visibility:l?"visible":"hidden"},children:s}),document.body)]})}function Ht({page:t,pageCount:s,total:n,onPageChange:r,label:a,className:i}){const{t:l,direction:d}=me(),c=Math.max(1,s),m=Math.min(Math.max(1,t),c),u=d==="rtl"?e.jsx(Ps,{size:18}):e.jsx(Xn,{size:18}),p=d==="rtl"?e.jsx(Xn,{size:18}):e.jsx(Ps,{size:18});return e.jsxs("nav",{"aria-label":a??l("pagination"),className:Ue("flex min-w-0 flex-wrap items-center justify-between gap-2 text-sm",i),children:[e.jsx("span",{className:"text-muted tabular-nums",children:l("resultCount").replace("{n}",String(n))}),s>1&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xe,{label:l("previousPage"),icon:u,disabled:m<=1,onClick:()=>r(m-1)}),e.jsx("span",{className:"min-w-0 px-1 text-center text-xs font-medium text-text-main tabular-nums sm:text-sm",children:l("pageOf").replace("{page}",String(m)).replace("{count}",String(c))}),e.jsx(xe,{label:l("nextPage"),icon:p,disabled:m>=c,onClick:()=>r(m+1)})]})]})}function An(t,s=20,n){const r=Math.max(1,Math.floor(s)||20),a=t.length,i=Math.max(1,Math.ceil(a/r)),[l,d]=o.useState({page:1,resetKey:n}),c=Object.is(l.resetKey,n)?Math.min(l.page,i):1;o.useEffect(()=>{(!Object.is(l.resetKey,n)||l.page!==c)&&d({page:c,resetKey:n})},[c,n,l]);const m=u=>{d({page:Math.min(Math.max(1,Math.floor(u)||1),i),resetKey:n})};return{page:c,pageCount:i,pageItems:t.slice((c-1)*r,c*r),setPage:m,total:a}}function ir({size:t=16,className:s,...n}){return e.jsxs("svg",{"aria-hidden":"true",focusable:"false",viewBox:"0 0 24 24",width:t,height:t,fill:"currentColor",className:Ue("shrink-0",s),...n,children:[e.jsx("path",{d:"M3 7.5l4.6 4.1L12 4.5l4.4 7.1L21 7.5l-1.7 9H4.7z"}),e.jsx("rect",{x:"5",y:"18.2",width:"14",height:"2.3",rx:"1.15"})]})}const ea={base:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-bold",tone:{active:"border-brand-purple/40 bg-panel-raised text-text-main",muted:"border-line bg-panel-raised text-muted"},crown:{active:"text-brand-purple",muted:"text-faint"}};function nc({tone:t="active",crown:s=!1,className:n,children:r,...a}){return e.jsxs("span",{className:Ue(ea.base,ea.tone[t],n),...a,children:[s&&e.jsx(ir,{size:12,className:ea.crown[t]}),r]})}function sc({title:t,benefit:s,tab:n,className:r}){const{t:a}=me(),{status:i,available:l}=wr(),d=o.useId(),c=o.useId(),m=cl(i,l);return m==="unavailable"?null:e.jsxs(he,{className:Ue("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-plus-access":m,children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(nc,{crown:!0,children:a("plusTitle")}),m==="locked"&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold text-muted",children:[e.jsx(Sr,{"aria-hidden":!0,size:13}),a("plusRowLocked")]})]}),e.jsx("p",{id:d,className:"text-sm font-bold text-text-main",children:t}),e.jsx("p",{className:"text-xs text-muted",children:m==="unknown"?a("plusRowChecking"):s})]}),m==="active"&&e.jsx(Kr,{href:Ms(n),size:"sm",className:"self-start sm:self-center","aria-describedby":d,children:a("plusRowOpen")}),m==="locked"&&e.jsx(Kr,{href:Ms(),size:"sm",className:"self-start sm:self-center","aria-describedby":d,children:a("plusRowLearnMore")}),m==="unknown"&&e.jsxs(e.Fragment,{children:[e.jsx(U,{size:"sm",className:"self-start sm:self-center",disabled:!0,"aria-describedby":c,title:a("plusRowCheckingReason"),children:a("plusRowOpen")}),e.jsx("span",{id:c,className:"sr-only",children:a("plusRowCheckingReason")})]})]})}const hs=new Set;let In=null;function xu(t){return hs.add(t),In===null&&(In=window.setInterval(()=>{for(const s of hs)s()},3e4)),()=>{hs.delete(t),hs.size===0&&In!==null&&(window.clearInterval(In),In=null)}}function ac(t){return At(t,{ar:"ar",en:"en"})}function pu(t){const s=t instanceof Date?t.getTime():typeof t=="number"?t:Date.parse(t);return Number.isFinite(s)?s:null}const ta=[{unit:"year",ms:1e3*60*60*24*365},{unit:"month",ms:1e3*60*60*24*30},{unit:"week",ms:1e3*60*60*24*7},{unit:"day",ms:1e3*60*60*24},{unit:"hour",ms:1e3*60*60},{unit:"minute",ms:1e3*60},{unit:"second",ms:1e3}];function hu(t,s,n){const r=t-s,a=Math.abs(r),i=new Intl.RelativeTimeFormat(ac(n),{numeric:"auto"}),l=ta.find(c=>a>=c.ms)??ta[ta.length-1],d=Math.round(r/l.ms);return i.format(d,l.unit)}function jn({value:t,className:s}){const{language:n}=me(),[r,a]=o.useState(()=>Date.now());o.useEffect(()=>xu(()=>a(Date.now())),[]);const i=pu(t);if(i===null)return null;const l=ac(n),d=new Intl.DateTimeFormat(l,{dateStyle:"medium",timeStyle:"short"}).format(i);return e.jsx("time",{dateTime:new Date(i).toISOString(),title:d,className:Ue("whitespace-nowrap",s),children:hu(i,r,n)})}const ei={REACTION_RULE_INVALID:"reactionErrorRuleInvalid",REACTION_RULE_MISSING:"reactionErrorRuleMissing",REACTION_RULE_CHANGED:"reactionErrorRuleChanged",REACTION_AUTOMATION_CHANGED:"reactionAutomationChanged",REACTION_SWITCH_INVALID:"reactionErrorSwitchInvalid",INTERNAL:"reactionErrorInternal",DELAY_RANGE_INVALID:"delayRangeError",TERMS_CHANGED:"legalChangedReview",CONSENT_REQUIRED:"legalReasonNotAccepted",UNLINK_INCOMPLETE:"connectionUnlinkIncomplete",wrong_password:"recoveryErrWrongPassword",invalid_email:"recoveryErrInvalidEmail",wrong_code:"recoveryErrWrongCode",expired:"recoveryErrExpired",no_pending:"recoveryErrExpired",too_many_attempts:"userErrorRateLimited",throttled:"userErrorRateLimited",rate_limited:"userErrorRateLimited",inactive:"plusExtErrorInactive",BAD_REQUEST:"plusExtErrorBadRequest",INVALID_TEMPLATE:"plusExtErrorInvalidTemplate",UNKNOWN_PLACEHOLDER:"plusExtErrorUnknownPlaceholder",NOT_CUSTOMIZABLE:"plusExtErrorNotCustomizable",TOO_LONG:"plusExtErrorTooLong",INVALID_CHAT:"plusExtErrorInvalidChat",LIMIT:"plusExtErrorLimit",NOT_FOUND:"plusExtErrorNotFound",TRANSLATE_FAILED:"plusExtErrorTranslateFailed"};function ti(t){return t!==null&&typeof t=="object"?t:null}function je(t,s,n){const r=ti(s),a=ti(r==null?void 0:r.data),i=[r==null?void 0:r.code,a==null?void 0:a.error].find(c=>typeof c=="string"&&Object.hasOwn(ei,c)),l=typeof(r==null?void 0:r.status)=="number"&&Number.isInteger(r.status)&&r.status>=0&&r.status<=599?r.status:void 0;let d=i?ei[i]:void 0;return d||(l===401?d="userErrorSession":l===403?d="userErrorPermission":l===404?d="plusExtErrorNotFound":l===409?d="userErrorConflict":l===413?d="userErrorTooLarge":l===429?d="userErrorRateLimited":l!==void 0&&l>=500?d="userErrorServer":(s instanceof TypeError||l===0||(r==null?void 0:r.name)==="ApiError"&&l===void 0)&&(d="userErrorUnreachable")),t(d??n)}const fu=1500;function Os(t,s){if(Object.is(t,s))return!0;if(typeof t!="object"||typeof s!="object"||t===null||s===null)return!1;const n=t,r=s,a=Object.keys(n);return a.length!==Object.keys(r).length?!1:a.every(i=>Object.is(n[i],r[i]))}function rc(t,s){o.useEffect(()=>{if(t!=="saved")return;const n=window.setTimeout(()=>{s(r=>r==="saved"?"idle":r)},fu);return()=>window.clearTimeout(n)},[t,s])}function We(t,s="saveFailed"){const{t:n}=me(),[r,a]=o.useState(t),[i,l]=o.useState("idle"),[d,c]=o.useState(null),m=o.useRef(t);o.useEffect(()=>{i!=="saving"&&(Os(t,m.current)||(m.current=t,a(t)))},[t,i]),rc(i,l);const u=!Os(r,t),p=o.useCallback(async g=>{if(!(!u||i==="saving")){l("saving"),c(null);try{await g(r),l("saved")}catch(x){l("idle"),c(je(n,x,s))}}},[u,i,r,n,s]),h=o.useCallback(()=>{a(t),c(null),l("idle")},[t]);return{value:r,setValue:a,dirty:u,status:i,error:d,save:p,revert:h}}function wn(t,s="saveFailed",n=je){const{t:r}=me(),[a,i]=o.useState(t),[l,d]=o.useState("idle"),[c,m]=o.useState(null),u=o.useRef(t);o.useEffect(()=>{l!=="saving"&&(Os(t,u.current)||(u.current=t,i(t)))},[t,l]),rc(l,d);const p=!Os(a,t),h=o.useCallback((f,k)=>{i(N=>({...N,[f]:k}))},[]),g=o.useCallback(async f=>{if(!(!p||l==="saving")){d("saving"),m(null);try{await f(a),d("saved")}catch(k){d("idle"),m(n(r,k,s))}}},[p,l,a,r,s,n]),x=o.useCallback(()=>{i(t),m(null),d("idle")},[t]);return{draft:a,setDraft:i,setField:h,dirty:p,status:l,error:c,save:g,revert:x}}function Ge({label:t,description:s,error:n,htmlFor:r,className:a,dirty:i,saving:l,justSaved:d,onSave:c,onRevert:m,saveLabel:u,savedLabel:p,actions:h,children:g}){const x=k=>{var w;const N=(w=k.target)==null?void 0:w.tagName;k.key==="Enter"&&N==="INPUT"&&!k.nativeEvent.isComposing&&(k.preventDefault(),i&&!l&&c()),k.key==="Escape"&&(k.preventDefault(),m())},f=o.isValidElement(g)?o.cloneElement(g,{onKeyDown:k=>{var N,w;(w=(N=g.props).onKeyDown)==null||w.call(N,k),x(k)}}):g;return e.jsx(re,{label:t,description:s,error:n,htmlFor:r,className:a,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1",children:f}),h,e.jsx(xe,{type:"button",label:d?p??u:u,icon:d?e.jsx(gn,{size:16}):e.jsx(yn,{size:16}),loading:l,disabled:!i&&!d||l,onClick:()=>{i&&!l&&c()},className:d?"text-ok":void 0})]})})}function kn({dirty:t,saving:s,justSaved:n,error:r,onDiscard:a,saveLabel:i,discardLabel:l,unsavedLabel:d,savedLabel:c,className:m}){return e.jsxs("div",{className:Ue("flex flex-wrap items-center gap-2",m),children:[e.jsx("div",{className:"min-w-0 flex-1",children:r?e.jsx("p",{role:"alert",className:"text-xs text-danger",children:r}):t?e.jsx("p",{className:"text-xs text-warn",children:d}):n&&c?e.jsx("p",{className:"text-xs text-ok",children:c}):null}),e.jsx(U,{type:"button",variant:"ghost",disabled:!t||s,onClick:a,children:l}),e.jsx(U,{type:"submit",variant:"primary",icon:e.jsx(yn,{size:16}),disabled:!t,loading:s,children:i})]})}function Rn({label:t,value:s,options:n,onChange:r}){var i;const a=(i=n.find(l=>l.value===s))==null?void 0:i.label;return e.jsx(Xa,{label:t,trigger:e.jsx(xe,{label:a?`${t}: ${a}`:t,icon:e.jsx(Pd,{size:18})}),children:n.map(l=>e.jsx(_e,{checked:l.value===s,onSelect:()=>r(l.value),children:l.label},l.value))})}function ic(t){var i,l;if(!(t.target instanceof HTMLButtonElement))return;const s=Array.from(t.currentTarget.querySelectorAll('[role="tab"]')),n=s.indexOf(t.target);if(n<0)return;const r=getComputedStyle(t.currentTarget).direction==="rtl";let a;switch(t.key){case"ArrowRight":a=(n+(r?-1:1)+s.length)%s.length;break;case"ArrowLeft":a=(n+(r?1:-1)+s.length)%s.length;break;case"Home":a=0;break;case"End":a=s.length-1;break;default:return}t.preventDefault(),s[a].focus({preventScroll:!0}),(l=(i=s[a]).scrollIntoView)==null||l.call(i,{block:"nearest",inline:"nearest"}),s[a].click()}function lc(t){const s=o.useRef(null);return o.useEffect(()=>{var n,r;(r=(n=s.current)==null?void 0:n.scrollIntoView)==null||r.call(n,{block:"nearest",inline:"nearest"})},[t]),s}function Rt({value:t,onChange:s,options:n,"aria-label":r,className:a}){var d;const i=lc(t),l=n.some(c=>c.value===t)?t:(d=n[0])==null?void 0:d.value;return e.jsx("div",{role:"tablist","aria-label":r,onKeyDown:ic,className:Ue("inline-flex max-w-full flex-nowrap overflow-x-auto no-scrollbar rounded-xl border border-line bg-panel-raised p-1",a),children:n.map(c=>{const m=c.value===t;return e.jsxs("button",{ref:m?i:void 0,type:"button",role:"tab","aria-selected":m,tabIndex:c.value===l?0:-1,onClick:()=>s(c.value),className:Ue("inline-flex min-h-10 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg px-3 text-xs font-semibold transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-blue/50",m?"bg-brand-blue text-white":"text-muted hover:text-text-main"),children:[c.icon,c.label]},c.value)})})}function ls({value:t,onChange:s,options:n,"aria-label":r,className:a}){var d;const i=lc(t),l=n.some(c=>c.value===t)?t:(d=n[0])==null?void 0:d.value;return e.jsx("div",{role:"tablist","aria-label":r,onKeyDown:ic,className:Ue("flex items-center gap-1 sm:gap-2",a),children:n.map(c=>{const m=c.value===t,u=!!c.icon&&!m;return e.jsxs("button",{ref:m?i:void 0,type:"button",role:"tab","aria-selected":m,tabIndex:c.value===l?0:-1,title:u&&typeof c.label=="string"?c.label:void 0,onClick:()=>s(c.value),className:Ue("inline-flex min-h-10 min-w-10 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-xl text-sm font-bold transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-blue/50",u?"px-2.5 sm:px-4":"px-4",m?"bg-brand-blue text-white shadow-md shadow-brand-blue/25":"text-muted hover:bg-panel-hover hover:text-text-main"),children:[c.icon,e.jsx("span",{className:Ue(u&&"sr-only sm:not-sr-only"),children:c.label})]},c.value)})})}const gu=1500,ni=120,oc=8,Bt=12,bu=320,si=640,ai="color-mix(in srgb, var(--panel-solid) 62%, transparent)",yu="0 0 0 1px color-mix(in srgb, var(--brand-cyan) 55%, transparent)",vu="0 0 20px 3px color-mix(in srgb, var(--brand-cyan) 30%, transparent)",fs=(t,s,n)=>Math.min(Math.max(t,s),n);function ju({rect:t,pad:s=oc}){if(!t||t.width<=0&&t.height<=0)return e.jsx("div",{className:"absolute inset-0",style:{backgroundColor:ai}});const n={top:t.top-s,left:t.left-s,width:t.width+s*2,height:t.height+s*2};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute rounded-2xl transition-[top,left,width,height] duration-150 ease-out",style:{...n,boxShadow:`0 0 0 9999px ${ai}`}}),e.jsx("div",{className:"tour-glow absolute rounded-2xl",style:{...n,boxShadow:`${yu}, ${vu}`}})]})}function wu({open:t,steps:s,index:n,onAdvance:r,onBack:a,onClose:i,labels:l}){const{direction:d}=me(),c=o.useId(),m=s[n],[u,p]=o.useState(null),[h,g]=o.useState(null),[x,f]=o.useState(0),[k,N]=o.useState(()=>window.innerWidth<si),w=o.useRef(null),S=o.useRef(null),b=o.useRef(r);if(b.current=r,o.useEffect(()=>{const A=()=>N(window.innerWidth<si);return window.addEventListener("resize",A),window.addEventListener("orientationchange",A),()=>{window.removeEventListener("resize",A),window.removeEventListener("orientationchange",A)}},[]),o.useEffect(()=>{if(!t||(p(null),g(null),!m))return;const A=`[data-tour="${m.target}"]`;let D=0;const I=window.setInterval(()=>{const F=document.querySelector(A),E=F==null?void 0:F.getBoundingClientRect();if(F&&E&&(E.width>0||E.height>0)){window.clearInterval(I),F.scrollIntoView({block:"center",inline:"nearest"}),p(F);return}D+=ni,D>=gu&&(window.clearInterval(I),b.current())},ni);return()=>window.clearInterval(I)},[t,m]),o.useEffect(()=>{if(!t||!u)return;let A=0,D=null;const I=()=>{const F=w.current;if(F){const $=F.offsetHeight;f(G=>Math.abs(G-$)>1?$:G)}const E=u.getBoundingClientRect(),P={top:E.top,left:E.left,width:E.width,height:E.height,bottom:E.bottom,right:E.right};(!D||Math.abs(P.top-D.top)>.5||Math.abs(P.left-D.left)>.5||Math.abs(P.width-D.width)>.5||Math.abs(P.height-D.height)>.5)&&(D=P,g(P)),A=window.requestAnimationFrame(I)};return A=window.requestAnimationFrame(I),()=>window.cancelAnimationFrame(A)},[t,u]),o.useEffect(()=>{var P;const A=w.current;if(!t||!u||!k||!A)return;const D=(((P=document.querySelector("header"))==null?void 0:P.getBoundingClientRect().bottom)??0)+Bt,I=window.innerHeight-A.offsetHeight-Bt-D,F=u.getBoundingClientRect(),E=F.height>=I?D:D+(I-F.height)/2;window.scrollBy({top:F.top-E})},[t,u,k]),ol(w,t&&!!u,i),o.useEffect(()=>{var A;t&&u&&((A=S.current)==null||A.focus({preventScroll:!0}))},[t,u]),!t||!m)return null;const R=n===s.length-1,j=A=>{const D=d==="rtl"?"ArrowLeft":"ArrowRight",I=d==="rtl"?"ArrowRight":"ArrowLeft";A.key===D?(A.preventDefault(),r()):A.key===I&&(A.preventDefault(),a())};let y,_;if(k)_="fixed inset-x-0 bottom-0 rounded-t-2xl border-t p-4",y={paddingBottom:"max(1rem, env(safe-area-inset-bottom))",animation:"modal-enter 150ms ease-out"};else if(h){const A=window.innerWidth,D=window.innerHeight,I=Math.min(bu,A-24),F=x||170,E=A-h.left-h.width,P=h.left,M=I+Bt+oc;let $,G;E>=P&&E>=M?($=fs(h.top+h.height/2-F/2,8,Math.max(8,D-F-8)),G=h.left+h.width+Bt):P>=M?($=fs(h.top+h.height/2-F/2,8,Math.max(8,D-F-8)),G=h.left-Bt-I):h.bottom+Bt+F<=D-8?($=h.bottom+Bt,G=fs(h.left+h.width/2-I/2,8,A-I-8)):($=Math.max(8,h.top-Bt-F),G=fs(h.left+h.width/2-I/2,8,A-I-8)),_="fixed rounded-2xl border p-4",y={top:$,left:G,width:I,maxHeight:`calc(100dvh - ${$}px - 8px)`,overflowY:"auto",animation:"modal-enter 150ms ease-out"}}else _="fixed inset-x-0 bottom-0 rounded-t-2xl border-t p-4",y={paddingBottom:"max(1rem, env(safe-area-inset-bottom))",animation:"modal-enter 150ms ease-out"};return jr.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-50"}),e.jsx("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 z-50",children:e.jsx(ju,{rect:h})}),e.jsxs("div",{ref:w,role:"dialog","aria-modal":"true","aria-labelledby":c,tabIndex:-1,"data-overlay":"dialog",className:Ue("z-50 flex w-full flex-col gap-2 border-line bg-panel shadow-2xl outline-none",_),style:y,onKeyDown:j,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider text-faint",children:l.stepOf}),e.jsx("span",{className:"ms-auto"}),e.jsx(xe,{size:"sm",variant:"ghost",label:l.skip,icon:e.jsx(yt,{size:16}),onClick:i})]}),e.jsx("h2",{id:c,className:"text-base font-bold text-text-main",children:m.title}),e.jsx("p",{className:"text-sm leading-relaxed text-muted",children:m.body}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{variant:"secondary",size:"md",disabled:n===0,icon:e.jsx(Xn,{size:16,className:"rtl:-scale-x-100"}),onClick:a,children:l.back}),e.jsx(U,{ref:S,variant:"primary",size:"md",className:"ms-auto",icon:R?void 0:e.jsx(Ps,{size:16,className:"rtl:-scale-x-100"}),onClick:r,children:R?l.done:l.next})]})]})]}),document.body)}function ot({children:t,className:s,copy:n=!1,copyLabel:r}){const{t:a}=me(),[i,l]=o.useState(!1),d=e.jsx("bdi",{dir:"ltr",className:Ue("min-w-0 break-words font-mono",s),children:t});if(!n)return d;async function c(){var m;try{if(!((m=navigator.clipboard)!=null&&m.writeText))throw new Error("clipboard unavailable");await navigator.clipboard.writeText(t),l(!1)}catch{l(!0)}}return e.jsxs("span",{className:"inline-flex max-w-full items-center gap-1",children:[d,e.jsx(xe,{variant:"ghost",label:r??a("copy"),icon:e.jsx(Nr,{size:16}),onClick:()=>void c()}),i&&e.jsx("span",{role:"status",className:"text-xs text-danger",children:a("copyFailed")})]})}const cc=o.createContext(null),ku=({children:t})=>{const{t:s}=me(),[n,r]=o.useState([]),a=o.useCallback(l=>{r(d=>d.filter(c=>c.id!==l))},[]),i=o.useCallback((l,d="info",c=4e3)=>{const m=Math.random().toString(36).slice(2,9);r(u=>[...u,{id:m,message:l,type:d,duration:c}]),setTimeout(()=>a(m),c)},[a]);return e.jsxs(cc.Provider,{value:{toast:i},children:[t,e.jsx("div",{className:"fixed bottom-5 end-5 z-50 flex flex-col gap-2.5 max-w-sm w-full px-4 pointer-events-none","aria-live":"polite",children:n.map(l=>e.jsxs("div",{className:`pointer-events-auto flex items-center gap-3 rounded-xl border bg-panel-raised/95 px-4 py-3 text-xs text-text-main shadow-xl backdrop-blur-md md:text-sm ${l.type==="success"?"border-ok/35":l.type==="error"?"border-danger/35":l.type==="warning"?"border-warn/35":"border-line"}`,children:[l.type==="success"&&e.jsx(Qt,{size:18,className:"shrink-0 text-ok"}),l.type==="error"&&e.jsx(Fd,{size:18,className:"shrink-0 text-danger"}),l.type==="warning"&&e.jsx(tn,{size:18,className:"shrink-0 text-warn"}),l.type==="info"&&e.jsx(Vd,{size:18,className:"shrink-0 text-info"}),e.jsx("span",{className:"flex-1 font-medium",children:l.message}),e.jsx(xe,{variant:"ghost",label:s("dismiss"),icon:e.jsx(yt,{size:16}),onClick:()=>a(l.id)})]},l.id))})]})},qe=()=>{const t=o.useContext(cc);if(!t)throw new Error("useToast must be used within a ToastProvider");return t};let ri=!1;const Nu=()=>{const{t}=me(),{toast:s}=qe(),[n,r]=o.useState(!1),[a,i]=o.useState(!1),[l,d]=o.useState(!1);if(o.useEffect(()=>{typeof window>"u"||window.LevixHost||ri||(ri=!0,Q.getCrashReports().then(u=>{u!=null&&u.reports&&u.reports.length>0&&r(!0)}).catch(()=>{}))},[]),!n)return null;const c=()=>{r(!1),window.location.hash="settings/diagnostics"},m=async()=>{d(!0);try{await Q.deleteAllCrashReports(),s(t("allReportsDeleted"),"success"),r(!1)}catch(u){s(je(t,u,"reportsDeleteError"),"error")}finally{d(!1),i(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-4",children:e.jsx(he,{className:"border-warn/30 bg-warn/5 p-4",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-9 shrink-0 items-center justify-center rounded-xl bg-warn/15 text-warn",children:e.jsx(tn,{size:18})}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("h4",{className:"text-sm font-bold text-text-main",children:t("crashBannerTitle")}),e.jsx("p",{className:"text-xs leading-relaxed text-muted",children:t("crashBannerDesc")})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 self-end sm:self-auto shrink-0",children:[e.jsx(U,{variant:"primary",size:"sm",onClick:c,icon:e.jsx(tc,{size:14}),children:t("crashBannerReview")}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>r(!1),children:t("crashBannerNotNow")}),e.jsx(U,{variant:"danger",size:"sm",onClick:()=>i(!0),icon:e.jsx(lt,{size:14}),children:t("crashBannerDelete")})]})]})})}),e.jsx(ut,{isOpen:a,onClose:()=>i(!1),onConfirm:m,loading:l,title:t("confirmDeleteAllReports"),description:t("confirmDeleteAllDesc"),confirmLabel:t("deleteAllReports"),cancelLabel:t("cancel"),variant:"danger"})]})};function lr(t,s){const n=od(t||document.documentElement.lang),r=s||(document.documentElement.getAttribute("data-theme")==="light"?"light":"dark"),a=`${window.innerWidth}x${window.innerHeight}@${Number(window.devicePixelRatio||1).toFixed(2)}`,i={screen:a.length>24?a.slice(0,24):a,language:n,theme:r},l=window.LevixHost;if(l&&typeof l.getDiagnostics=="function")try{const d=l.getDiagnostics();if(d){const c=JSON.parse(d);if(c&&typeof c=="object"){const m=["nativeApp","android","device","abi","webview","connectivity","memory","storage"];for(const u of m)typeof c[u]=="string"&&(i[u]=c[u])}}}catch{}return i}const Su=3,Cu=20;let ii=0;const li=new Set;let or=!1;const Es=[];function cr(){try{const t=window.location.hash.replace(/^#\/?/,"").split("/")[0];return(t?t.trim():"overview").slice(0,40)||"overview"}catch{return"overview"}}function oi(t){try{const s=(t||"overview").slice(0,60);Es.push({at:new Date().toISOString(),kind:"nav",name:s}),Es.length>Cu&&Es.shift()}catch{}}if(typeof window<"u")try{window.addEventListener("beforeunload",()=>{or=!0}),window.addEventListener("pagehide",()=>{or=!0}),oi(cr()),window.addEventListener("hashchange",()=>{oi(cr())})}catch{}function dr(t,s,n){try{if(or||ii>=Su)return;let r=n||"Error",a="Unknown error",i=[];if(s instanceof Error)r=n||s.name||"Error",a=s.message||"Unknown error",s.stack&&(i=s.stack.split(`
437
+ `).map(c=>c.trim().slice(0,200)).filter(Boolean).slice(0,20));else if(typeof s=="string")a=s;else if(s&&typeof s=="object"){const c=s;typeof c.message=="string"&&(a=c.message),typeof c.name=="string"&&(r=n||c.name),typeof c.stack=="string"&&(i=c.stack.split(`
438
+ `).map(m=>m.trim().slice(0,200)).filter(Boolean).slice(0,20))}r=r.slice(0,120),a=a.slice(0,300);const l=`${r}|${a}`;if(li.has(l))return;li.add(l),ii++;const d={category:t,error:{type:r,message:a,stack:i},screen:cr(),breadcrumbs:[...Es],device:lr()};Q.submitCrashReport(d).catch(()=>{})}catch{}}function Eu(){if(typeof window>"u")return()=>{};const t=n=>{try{dr("web-error",n.error||n.message)}catch{}},s=n=>{try{dr("web-rejection",n.reason)}catch{}};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",s),()=>{window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",s)}}class dc extends o.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){try{dr("react-render",s)}catch{}}render(){var s;if(this.state.hasError){const n=((s=this.context)==null?void 0:s.t)||(r=>dl.en[r]);return e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center p-4",children:e.jsxs(he,{className:"max-w-md w-full text-center border-danger/30",children:[e.jsx("div",{className:"mx-auto flex size-12 items-center justify-center rounded-full bg-danger/10 text-danger",children:e.jsx(tn,{size:24})}),e.jsx("h2",{className:"mt-4 text-lg font-bold text-text-main",children:n("errorBoundaryTitle")}),e.jsx("p",{className:"mt-2 text-xs leading-relaxed text-muted sm:text-sm",children:n("errorBoundaryDesc")}),e.jsxs("div",{className:"mt-6 flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsx(U,{variant:"primary",onClick:()=>window.location.reload(),icon:e.jsx(it,{size:16}),className:"w-full sm:w-auto",children:n("errorBoundaryReload")}),e.jsx(U,{variant:"secondary",onClick:()=>{window.location.hash="settings/diagnostics",this.setState({hasError:!1,error:null})},icon:e.jsx(tc,{size:16}),className:"w-full sm:w-auto",children:n("errorBoundaryGoDiagnostics")})]})]})})}return this.props.children}}$r(dc,"contextType",cd);function de(t,s){return t.replace(/\{([A-Za-z0-9_]+)\}/g,(n,r)=>Object.hasOwn(s,r)?String(s[r]):n)}const na=[{id:"sidebar",target:"sidebar-nav",screen:"sidebar",desktopOnly:!0,titleKey:"tourSidebarTitle",bodyKey:"tourSidebarBody"},{id:"connection-start",target:"connection-start",screen:"connection",hash:"connection",titleKey:"tourConnectionStartTitle",bodyKey:"tourConnectionStartBody"},{id:"connection-pairing",target:"connection-pairing",screen:"connection",hash:"connection",titleKey:"tourConnectionPairingTitle",bodyKey:"tourConnectionPairingBody"},{id:"overview-stats",target:"overview-stats",screen:"overview",hash:"overview",titleKey:"tourOverviewStatsTitle",bodyKey:"tourOverviewStatsBody"},{id:"commands-list",target:"commands-list",screen:"commands",hash:"commands",titleKey:"tourCommandsTitle",bodyKey:"tourCommandsBody"},{id:"ai-agent",target:"ai-agent",screen:"ai",hash:"ai",inMainTour:!1,titleKey:"tourAiAgentTitle",bodyKey:"tourAiAgentBody"},{id:"ai-provider",target:"ai-provider",screen:"ai",hash:"ai",titleKey:"tourAiProviderTitle",bodyKey:"tourAiProviderBody"},{id:"ai-memory",target:"ai-memory",screen:"ai",hash:"ai",titleKey:"tourAiMemoryTitle",bodyKey:"tourAiMemoryBody"},{id:"groups-list",target:"groups-list",screen:"groups",hash:"groups",titleKey:"tourGroupsTitle",bodyKey:"tourGroupsBody"},{id:"stickers-tabs",target:"stickers-tabs",screen:"stickers",hash:"stickers",titleKey:"tourStickersTitle",bodyKey:"tourStickersBody"},{id:"schedules-list",target:"schedules-list",screen:"schedules",hash:"schedules",titleKey:"tourSchedulesTitle",bodyKey:"tourSchedulesBody"},{id:"logs-stream",target:"logs-stream",screen:"logs",hash:"logs",titleKey:"tourLogsTitle",bodyKey:"tourLogsBody"},{id:"settings-general",target:"settings-general",screen:"settings",hash:"settings",titleKey:"tourSettingsTitle",bodyKey:"tourSettingsBody"},{id:"settings-password",target:"settings-password",screen:"settings",hash:"settings/security",inMainTour:!1,titleKey:"tourSettingsPasswordTitle",bodyKey:"tourSettingsPasswordBody"},{id:"settings-feedback",target:"settings-feedback",screen:"settings",hash:"settings/feedback",inMainTour:!1,titleKey:"tourSettingsFeedbackTitle",bodyKey:"tourSettingsFeedbackBody"},{id:"settings-diagnostics",target:"settings-diagnostics",screen:"settings",hash:"settings/diagnostics",inMainTour:!1,titleKey:"tourSettingsDiagnosticsTitle",bodyKey:"tourSettingsDiagnosticsBody"}],uc="levix_tour_v1_done",Au=768,Ru=()=>{try{return window.localStorage.getItem(uc)==="1"}catch{return!1}},_u=()=>{try{window.localStorage.setItem(uc,"1")}catch{}},mc=o.createContext(null),xc=()=>o.useContext(mc),sa=()=>!!document.querySelector('[role="dialog"]'),aa=()=>window.innerWidth>=Au,Lu=({children:t})=>{const{t:s}=me(),[n,r]=o.useState(null),[a,i]=o.useState(0),l=o.useRef(n);l.current=n;const d=o.useRef(a);d.current=a;const c=o.useCallback(w=>{r(w),i(0)},[]),m=o.useCallback(()=>{sa()||l.current||c(na.filter(w=>w.inMainTour!==!1&&(!w.desktopOnly||aa())))},[c]),u=o.useCallback(w=>{if(sa()||l.current)return;const S=na.filter(b=>b.screen===w&&(!b.desktopOnly||aa()));S.length!==0&&c(S)},[c]),p=o.useCallback(w=>na.some(S=>S.screen===w&&(!S.desktopOnly||aa())),[]),h=o.useCallback(()=>{_u(),r(null),i(0)},[]),g=o.useCallback(()=>{const w=l.current;if(!w)return;const S=d.current+1;S>=w.length?h():i(S)},[h]),x=o.useCallback(()=>{d.current>0&&i(d.current-1)},[]);o.useEffect(()=>{if(!n)return;const w=n[a];w!=null&&w.hash&&window.location.hash!==`#${w.hash}`&&(window.location.hash=w.hash)},[n,a]),o.useEffect(()=>{let w=0,S;const b=()=>{if(w+=1,!l.current&&!Ru()){if(sa()){w<5&&(S=window.setTimeout(b,600));return}m()}};return S=window.setTimeout(b,1200),()=>window.clearTimeout(S)},[m]);const f=o.useMemo(()=>(n??[]).map(w=>({target:w.target,title:s(w.titleKey),body:s(w.bodyKey)})),[n,s]),k=o.useMemo(()=>({back:s("tourBack"),next:s("tourNext"),done:s("tourDone"),skip:s("tourSkip"),stepOf:n?de(s("tourStepOf"),{n:a+1,total:n.length}):""}),[s,n,a]),N=o.useMemo(()=>({startMainTour:m,startScreenTour:u,hasScreenSteps:p}),[m,u,p]);return e.jsxs(mc.Provider,{value:N,children:[t,e.jsx(wu,{open:!!n,steps:f,index:a,onAdvance:g,onBack:x,onClose:h,labels:k})]})},ct=Object.freeze({website:"https://levix.leviro.net",docs:"https://levix.leviro.net/docs",support:"https://levix.leviro.net/feedback",github:"https://github.com/Abdodiab2005/levix",releases:"https://github.com/Abdodiab2005/levix/releases",play:"https://play.google.com/store/apps/details?id=net.leviro.levix",portfolio:"https://abdelrhman.leviro.net",studio:"https://leviro.net"});function pc(t){return Object.values(ct).some(s=>s===t)?!0:/^https:\/\/github\.com\/Abdodiab2005\/levix\/releases\/tag\/v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/.test(t)}function Zn(t){var s,n;return pc(t)?window.LevixHost?((n=(s=window.LevixHost).openOfficialLink)==null?void 0:n.call(s,t))===!0:(window.open(t,"_blank","noopener,noreferrer"),!0):!1}function hc(){const{t}=me(),[s,n]=o.useState(null),[r,a]=o.useState(""),[i,l]=o.useState(null),[d,c]=o.useState(!1),[m,u]=o.useState(Hr),[p,h]=o.useState(!1),g=o.useRef(!0),x=o.useRef(0),f=o.useRef(!1),k=o.useRef(!1),N=Vr()||(s==null?void 0:s.channel)||"github";o.useEffect(()=>{g.current=!0;const y=x.current;return Q.get("/updates").then(_=>{g.current&&a(_.update.currentVersion),g.current&&x.current===y&&n(_.update)}).catch(()=>{}),()=>{g.current=!1}},[]),o.useEffect(()=>{const y=()=>u(Hr());return window.addEventListener("levix-review-prefs",y),()=>window.removeEventListener("levix-review-prefs",y)},[]);const w=o.useCallback(async function y(_="check",A=!1){if(f.current){A&&(k.current=!0);return}f.current=!0,x.current+=1,c(!0);try{if(N==="play"){const D=await qr(_);if(!g.current)return;l(D.ok?D.status||"unavailable":D.cancelled?"cancelled":"unavailable"),!A&&_==="check"&&D.ok&&D.status==="up_to_date"&&qr("review")}else{const D=await Q.post("/updates/check",{});g.current&&n(D.update)}}catch{g.current&&(N==="play"?l("unavailable"):n(D=>({channel:"github",currentVersion:(D==null?void 0:D.currentVersion)||"",url:ct.releases,status:"unavailable"})))}finally{f.current=!1,g.current&&c(!1),g.current&&k.current&&(k.current=!1,y("check",!0))}},[N]);o.useEffect(()=>{Vr()==="play"&&dd()&&w("check",!0)},[w]),o.useEffect(()=>{const y=()=>{w("check",!0)};return window.addEventListener("levix-play-update",y),()=>window.removeEventListener("levix-play-update",y)},[w]);function S(y){h(!Zn(y))}const b=[["officialDocs",ct.docs],["officialWebsite",ct.website],["officialSupport",ct.support],["officialPortfolio",ct.portfolio],["officialStudio",ct.studio]],R=N==="play"?i||"idle":(s==null?void 0:s.status)||"idle",j={idle:t("updateIdle"),available:N==="play"?t("updateAvailablePlay"):de(t("updateAvailable"),{version:(s==null?void 0:s.latestVersion)||""}),up_to_date:t("updateCurrent"),unavailable:t("updateUnavailable"),play:t("updateIdle"),downloading:t("updateDownloading"),downloaded:t("updateDownloaded"),started:t("updateDownloading"),cancelled:t("updateCancelled")}[R];return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{title:t("aboutLevix"),description:t("aboutLevixDesc")}),e.jsx("p",{className:"text-sm text-muted",children:t("aboutCredit")}),e.jsx("div",{className:"flex flex-col gap-2",children:b.map(([y,_])=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:t(y)}),e.jsx(xe,{label:t(y),icon:e.jsx(Ds,{size:18}),onClick:()=>S(_)})]},y))}),p&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:t("officialLinkUnavailable")})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{title:t("updatesTitle"),actions:e.jsx(xe,{label:t("checkUpdates"),disabled:d,icon:e.jsx(it,{size:18}),onClick:()=>void w()})}),e.jsxs("p",{className:"text-sm text-muted",children:[t("currentVersion"),":"," ",e.jsx("bdi",{dir:"ltr",children:r||(s==null?void 0:s.currentVersion)||"—"})]}),e.jsx("p",{role:"status","aria-live":"polite",children:d?t("updateChecking"):j}),e.jsx("p",{className:"text-sm text-muted",children:t(N==="play"?"updatePlayHint":"updateGithubHint")}),N==="play"&&R==="available"&&e.jsx(U,{variant:"primary",loading:d,onClick:()=>void w("start"),children:t("updateStart")}),N==="play"&&R==="downloaded"&&e.jsx(U,{variant:"primary",loading:d,onClick:()=>void w("complete"),children:t("updateComplete")}),N==="github"&&(s==null?void 0:s.status)==="available"&&pc(s.url)&&e.jsx(U,{onClick:()=>S(s.url),children:t("updateRelease")}),(s==null?void 0:s.releaseNotes)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("h3",{className:"font-bold",children:t("updateNotes")}),e.jsx(ze,{className:"whitespace-pre-wrap break-words text-sm text-muted",children:s.releaseNotes})]})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{title:t("supportLevix"),description:t("supportLevixDesc")}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:t(N==="play"?"rateLevix":"starGithub")}),e.jsx(xe,{label:t(N==="play"?"rateLevix":"starGithub"),icon:e.jsx(Ds,{size:18}),onClick:()=>S(N==="play"?ct.play:ct.github)})]}),N==="play"&&e.jsx(Je,{checked:m,label:t("reviewPrompts"),description:t("reviewPromptsDesc"),onChange:y=>{ud(y)&&u(y)}})]})]})}const Mu=({onToggleMobileMenu:t,title:s,view:n,status:r})=>{const{language:a,setLanguage:i,theme:l,setTheme:d,t:c}=me(),m=xc(),[u,p]=o.useState(!1),h=()=>{d(l==="dark"?"light":"dark")};return e.jsxs("header",{className:"sticky top-0 z-30 flex h-16 items-center justify-between border-b border-line bg-panel/85 px-4 backdrop-blur-md md:px-6",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(xe,{id:"mobile-menu-btn",className:"md:hidden",label:c("openNavigation"),icon:e.jsx(Yd,{size:20}),onClick:t}),e.jsx("h1",{className:"truncate text-lg font-bold tracking-tight text-text-main md:text-xl",title:s,children:s})]}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-3",children:[e.jsxs(Xa,{label:c("officialHelp"),trigger:e.jsx(xe,{id:"btn-header-guide",label:c("officialHelp"),icon:e.jsx(nr,{size:18,className:"text-brand-cyan"})}),children:[(m==null?void 0:m.hasScreenSteps(n))&&e.jsx(_e,{onSelect:()=>m.startScreenTour(n),children:c("tourScreenHelp")}),e.jsx(_e,{onSelect:()=>Zn(ct.docs),children:c("officialDocs")}),e.jsx(_e,{onSelect:()=>Zn(ct.support),children:c("officialSupport")}),e.jsx(_e,{onSelect:()=>p(!0),children:c("aboutLevix")})]}),e.jsxs(Xa,{label:c("chooseLanguage"),trigger:e.jsx(xe,{id:"btn-header-lang",label:c("chooseLanguage"),icon:e.jsx(Is,{size:18,className:"text-brand-cyan"})}),children:[e.jsx(md,{children:c("chooseLanguage")}),Za.map(g=>e.jsx(_e,{checked:a===g.code,onSelect:()=>i(g.code),children:g.name},g.code))]}),e.jsx(xe,{id:"btn-header-theme",label:c(l==="dark"?"lightMode":"darkMode"),icon:l==="dark"?e.jsx(ru,{size:18,className:"text-brand-cyan"}):e.jsx(Xd,{size:18,className:"text-brand-cyan"}),onClick:h})]}),e.jsx(Ye,{isOpen:u,onClose:()=>p(!1),title:c("aboutLevix"),children:u&&e.jsx(hc,{})})]})},Tu=({currentView:t,onSelectView:s,isOpenMobile:n,onCloseMobile:r})=>{var p;const{t:a}=me(),{available:i,status:l}=wr(),d=cl(l,i)==="active",c=typeof((p=window.LevixHost)==null?void 0:p.closePanel)=="function",m=window.__BRAND__||{name:"Levix",tagline:"Private control room",version:"",developer:"Abdelrhman Diab",studio:"Leviro"},u=[{id:"overview",label:a("overview"),icon:qd},{id:"connection",label:a("connection"),icon:Cr},{labelCategory:a("control")},{id:"commands",label:a("commands"),icon:en},{id:"ai",label:a("ai"),icon:Cn},{id:"groups",label:a("groups"),icon:En},{id:"autodelete",label:a("autoDelete"),icon:Cs},{id:"reactions",label:a("reaction"),icon:ks},{id:"schedules",label:a("schedules"),icon:tr},{id:"stickers",label:a("stickers"),icon:Rr},...i===!0?[{plusItem:!0}]:[],{labelCategory:a("settings")},{id:"settings",label:a("settings"),icon:su},{id:"logs",label:a("logs"),icon:ss}];return e.jsxs(e.Fragment,{children:[n&&e.jsx("button",{type:"button",className:"fixed inset-0 z-40 cursor-default border-0 bg-black/60 p-0 backdrop-blur-sm md:hidden",onClick:r,"aria-label":a("closeNavigation")}),e.jsxs("aside",{className:Ue("fixed start-0 top-0 bottom-0 z-50 flex w-72 flex-col border-e border-line bg-panel transition-transform duration-200 ease-out md:static md:z-auto md:w-64",n?"translate-x-0":"max-md:-translate-x-full rtl:max-md:translate-x-full"),"aria-label":"Main Navigation",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-line p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs("div",{className:"relative flex size-10 shrink-0 items-center justify-center rounded-xl border border-line bg-panel-raised shadow-md",children:[e.jsx("img",{src:"/brand/mark.svg",alt:m.name,className:"size-6"}),d&&e.jsx("span",{role:"img","aria-label":a("navPlusActiveLabel"),title:a("navPlusActiveLabel"),className:"absolute -top-1.5 -end-1.5 flex size-5 items-center justify-center rounded-full border border-line bg-panel text-brand-purple shadow-sm",children:e.jsx(ir,{size:12})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-base font-extrabold leading-tight tracking-tight text-text-main",children:m.name}),e.jsx("div",{className:"mt-0.5 truncate text-xs leading-none text-muted",children:m.tagline})]})]}),e.jsx(xe,{className:"md:hidden",label:a("closeNavigation"),icon:e.jsx(yt,{size:18}),onClick:r})]}),e.jsx("nav",{className:"flex-1 space-y-1 overflow-y-auto p-3","data-tour":"sidebar-nav",children:u.map(h=>{if(h.plusItem){const k=t==="plus";return e.jsx("div",{className:"mt-2 border-t border-line pt-2",children:e.jsxs(U,{variant:k?"primary":"ghost",className:"w-full justify-start",icon:e.jsx(ir,{size:20}),"aria-current":k?"page":void 0,onClick:()=>{s("plus"),r()},children:[e.jsx("span",{className:"truncate",children:a("plusTitle")}),d&&e.jsx(nc,{className:"ms-auto shrink-0",children:a("plusStateActive")})]})},"plus-group")}if(h.labelCategory)return e.jsx("div",{className:"px-3 pt-3 pb-1 text-[11px] font-bold uppercase tracking-wider text-faint",children:h.labelCategory},`cat-${h.labelCategory}`);const g=h.id;if(!h.icon||!g)return null;const x=h.icon,f=t===g;return e.jsx(U,{variant:f?"primary":"ghost",className:"w-full justify-start",icon:e.jsx(x,{size:20}),onClick:()=>{s(g),r()},children:e.jsx("span",{className:"truncate",children:h.label})},g)})}),e.jsxs("div",{className:"flex flex-col gap-1 border-t border-line p-3",children:[c&&e.jsx(U,{variant:"ghost",className:"w-full justify-start",icon:e.jsx(Td,{size:20,className:"rtl:-scale-x-100"}),onClick:()=>window.LevixHost.closePanel(),children:e.jsx("span",{className:"truncate",children:a("backToApp")})}),e.jsx("form",{action:"/logout",method:"POST",className:"m-0",children:e.jsx(U,{type:"submit",variant:"ghost",className:"w-full justify-start text-danger hover:bg-danger/10 hover:text-danger",icon:e.jsx(Gd,{size:20,className:"rtl:-scale-x-100"}),children:e.jsx("span",{className:"truncate",children:a("logout")})})})]}),e.jsxs("div",{className:"flex flex-col gap-2.5 border-t border-line p-4 text-xs text-faint",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-muted",children:[e.jsx("span",{className:"font-mono",children:m.version?`v${m.version}`:""}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ar,{size:14,className:"text-brand-cyan"})," Local-first"]})]}),e.jsxs("div",{className:"truncate text-[11px] text-muted",children:["© ",m.copyrightYear||2026," ",e.jsx("a",{href:ct.portfolio,onClick:h=>{h.preventDefault(),Zn(ct.portfolio)},target:"_blank",rel:"noopener noreferrer",className:"text-brand-cyan hover:underline",children:m.developer})," ","(",e.jsx("a",{href:ct.studio,onClick:h=>{h.preventDefault(),Zn(ct.studio)},target:"_blank",rel:"noopener noreferrer",className:"text-brand-cyan hover:underline",children:m.studio}),")"]})]})]})]})},Pu=()=>({tone:"neutral",labelKey:"accountCardLoading",showProfile:!1,action:"manage",loading:!0,pulsing:!1,attempt:null,maxAttempts:null}),ci=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):null;function fc(t){if(!t)return Pu();const s=ci(t.attempt),n=ci(t.maxAttempts),r={attempt:s,maxAttempts:n,loading:!1};switch(t.state){case"connected":return{...r,tone:"ok",labelKey:"connected",showProfile:!0,action:"manage",pulsing:!1};case"starting":case"linking":return{...r,tone:"neutral",labelKey:"accountCardConnecting",showProfile:!1,action:"manage",pulsing:!0};case"waiting_for_qr":return{...r,tone:"warn",labelKey:"accountCardWaitingQr",showProfile:!1,action:"manage",pulsing:!0};case"reconnecting":return{...r,tone:"warn",labelKey:"accountCardReconnecting",showProfile:!1,action:"reconnect",pulsing:!0};case"idle":case"disconnected":return{...r,tone:"neutral",labelKey:"accountCardNotConnected",showProfile:!1,action:"connect",pulsing:!1};case"paused":return{...r,tone:"neutral",labelKey:"accountCardPaused",showProfile:!1,action:"connect",pulsing:!1};case"retry_exhausted":return{...r,tone:"danger",labelKey:"accountCardRetryExhausted",showProfile:!1,action:"connect",pulsing:!1};case"logged_out":return{...r,tone:"danger",labelKey:"accountCardLoggedOut",showProfile:!1,action:"connect",pulsing:!1};case"consent_required":return{...r,tone:"warn",labelKey:"accountCardConsentRequired",showProfile:!1,action:"connect",pulsing:!1};case"error":return{...r,tone:"danger",labelKey:"accountCardError",showProfile:!1,action:"connect",pulsing:!1};default:return{...r,tone:"neutral",labelKey:"accountCardNotConnected",showProfile:!1,action:"connect",pulsing:!1}}}const Du=[{key:"text",icon:lu,labelKey:"capText",supportedDescKey:"capSupportedDesc",unsupportedDescKey:"capUnsupportedDesc",getValue:t=>(t==null?void 0:t.textInput)!=null&&(t==null?void 0:t.textOutput)!=null?!!(t.textInput&&t.textOutput):null},{key:"vision",icon:ts,labelKey:"capVision",supportedDescKey:"capSupportedDesc",unsupportedDescKey:"capUnsupportedDesc",getValue:t=>t==null?void 0:t.vision},{key:"audioInput",icon:uu,labelKey:"capAudio",supportedDescKey:"capSupportedDesc",unsupportedDescKey:"capUnsupportedDesc",getValue:t=>t==null?void 0:t.audioInput},{key:"stt",icon:oo,labelKey:"capStt",supportedDescKey:"capSupportedDesc",unsupportedDescKey:"capUnsupportedDesc",getValue:t=>t==null?void 0:t.stt},{key:"pdfInput",icon:ss,labelKey:"capPdf",supportedDescKey:"capSupportedDesc",unsupportedDescKey:"capUnsupportedDesc",getValue:t=>t==null?void 0:t.pdfInput},{key:"videoInput",icon:du,labelKey:"capVideo",supportedDescKey:"capSupportedDesc",unsupportedDescKey:"capUnsupportedDesc",getValue:t=>t==null?void 0:t.videoInput}];function Iu(t,s){return s==="unknown"||!s||t==null?"unknown":t?"supported":"unsupported"}function zu({capabilities:t,capabilitySource:s}){const{t:n}=me(),r=s==="provider"?"ok":s==="seed"?"info":"neutral",a=n(s==="provider"?"sourceLive":s==="seed"?"sourceSeed":"sourceUnknown");return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1 sm:gap-1.5",children:Du.map(i=>{const l=i.getValue(t),d=Iu(l,s),c=i.icon,m=n(d==="supported"?"supported":d==="unsupported"?"unsupported":"sourceUnknown"),u=`${n(i.labelKey)}: ${m}`,p=e.jsxs("span",{className:"flex flex-col gap-1 text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-bold text-text-main",children:[d==="supported"&&e.jsx(gn,{size:13,strokeWidth:2.5,className:"text-ok shrink-0"}),d==="unsupported"&&e.jsx(yt,{size:13,strokeWidth:2.5,className:"text-danger shrink-0"}),d==="unknown"&&e.jsx("span",{className:"font-mono text-faint shrink-0",children:"?"}),e.jsx("span",{children:u})]}),e.jsx("span",{className:"text-[11px] text-muted",children:n(d==="supported"?i.supportedDescKey:d==="unsupported"?i.unsupportedDescKey:"capUnknownDesc")})]});return e.jsx(rr,{label:u,content:p,className:"size-10 min-h-10 min-w-10 rounded-lg p-0",children:e.jsxs("span",{className:"relative inline-flex size-5 items-center justify-center",children:[e.jsx(c,{size:18,className:d==="supported"?"text-ok":d==="unsupported"?"text-muted/60":"text-muted/40"}),d==="supported"&&e.jsx("span",{"aria-hidden":!0,className:"absolute -bottom-1 -end-1 flex size-3.5 items-center justify-center rounded-full bg-panel-raised text-ok ring-1 ring-line",children:e.jsx(gn,{size:9,strokeWidth:3})}),d==="unsupported"&&e.jsx("span",{"aria-hidden":!0,className:"absolute -bottom-1 -end-1 flex size-3.5 items-center justify-center rounded-full bg-panel-raised text-danger ring-1 ring-line",children:e.jsx(yt,{size:9,strokeWidth:3})}),d==="unknown"&&e.jsx("span",{"aria-hidden":!0,className:"absolute -bottom-1 -end-1 flex size-3.5 items-center justify-center rounded-full bg-panel-raised text-faint ring-1 ring-line font-mono text-[9px] font-bold leading-none",children:"?"})]})},i.key)})}),e.jsx(Ce,{tone:r,children:a})]})}const Gt=[{id:"gemini",name:"Google Gemini",descKey:"providerGeminiDesc",provider:"gemini",defaultModel:"gemini-3.7-flash",defaultBaseUrl:"",keySetting:"gemini_api_key",modelSetting:"gemini_model",baseUrlSetting:"gemini_base_url"},{id:"groq",name:"Groq Cloud",descKey:"providerGroqDesc",provider:"openai",defaultModel:"llama-3.3-70b-versatile",defaultBaseUrl:"https://api.groq.com/openai/v1",keySetting:"openai_api_key",modelSetting:"openai_model",baseUrlSetting:"openai_base_url"},{id:"openai",name:"OpenAI",descKey:"providerOpenAIDesc",provider:"openai",defaultModel:"gpt-4o-mini",defaultBaseUrl:"https://api.openai.com/v1",keySetting:"openai_api_key",modelSetting:"openai_model",baseUrlSetting:"openai_base_url"},{id:"ollama",name:"Ollama (Local)",descKey:"providerOllamaDesc",provider:"openai",defaultModel:"llama3.2",defaultBaseUrl:"http://localhost:11434/v1",keySetting:"openai_api_key",modelSetting:"openai_model",baseUrlSetting:"openai_base_url"},{id:"anthropic",name:"Anthropic Claude",descKey:"providerAnthropicDesc",provider:"anthropic",defaultModel:"claude-sonnet-4-5",defaultBaseUrl:"https://api.anthropic.com",keySetting:"anthropic_api_key",modelSetting:"anthropic_model",baseUrlSetting:"anthropic_base_url"}];function Ou(t){const s=t.ai_provider||"gemini";return Gt.find(n=>{var r,a;return n.provider!==s?!1:!!(n.id==="gemini"||n.id==="anthropic"||n.id==="groq"&&((r=t.openai_base_url)!=null&&r.includes("groq.com"))||n.id==="ollama"&&((a=t.openai_base_url)!=null&&a.includes("11434"))||n.id==="openai"&&(!t.openai_base_url||t.openai_base_url.includes("api.openai.com")))})||Gt[0]}const Fu=()=>{var us,Tn,ms,Pn,xs,Ot;const{t,language:s}=me(),{toast:n}=qe(),[r,a]=o.useState({}),[i,l]=o.useState({}),[d,c]=o.useState(!0),[m,u]=o.useState({}),[p,h]=o.useState(!1),[g,x]=o.useState(!1),[f,k]=o.useState(!1),[N,w]=o.useState(""),[S,b]=o.useState(!1),[R,j]=o.useState([]),[y,_]=o.useState(null),[A,D]=o.useState(""),[I,F]=o.useState(!1),[E,P]=o.useState(!1),[M,$]=o.useState([]),[G,ne]=o.useState(null),[se,V]=o.useState(null),[q,C]=o.useState(!1),O=Ou(r),J=wn({presetId:O.id,apiKey:"",baseUrl:O.baseUrlSetting?String(r[O.baseUrlSetting]||O.defaultBaseUrl):"",model:String(r[O.modelSetting]||O.defaultModel)}),Y=We(String(r.ai_stt_provider||"auto")),L=We(String(r.bot_language||"auto")),v=We(String(r.ai_reply_language||"follow_bot")),T=We(String(r.translate_engine||"ai")),te=We(String(r.google_translate_api_key||"")),oe=We(String(r.ai_global_memory_read||"privileged")),ye=We(String(r.ai_global_memory_write||"off")),fe=We(String(r.ai_global_memory_where||"own_chat")),we=Gt.find(H=>H.id===J.draft.presetId)||O,Le=async()=>{try{const H=await Q.getSettings();if(H!=null&&H.settings){const ge={},Ie={};H.settings.forEach(Ze=>{ge[Ze.key]=Ze.value,Ze.type==="secret"&&(Ie[Ze.key]=!!Ze.configured,ge[Ze.key]="")}),a(ge),l(Ie)}}catch(H){n(je(t,H,"settingsLoadError"),"error")}finally{c(!1)}};o.useEffect(()=>{Le()},[]);const ee=async(H,ge,Ie=!1)=>{a(Ze=>({...Ze,[H]:ge}));try{await Q.updateSetting(H,ge),Ie||n(t("savedSuccessfully"),"success")}catch(Ze){n(je(t,Ze,"saveFailed"),"error")}},le=async(H,ge)=>{await Q.updateSetting(H,ge),H.endsWith("_api_key")?(a(Ie=>({...Ie,[H]:""})),l(Ie=>({...Ie,[H]:!!ge}))):a(Ie=>({...Ie,[H]:ge}))},Se=H=>{const ge=Gt.find(Ze=>Ze.id===H);if(!ge)return;const Ie=Gt.find(Ze=>Ze.id===J.draft.presetId)||O;J.setDraft({presetId:ge.id,apiKey:ge.keySetting===Ie.keySetting?J.draft.apiKey:"",baseUrl:ge.defaultBaseUrl,model:ge.defaultModel})},X=async(H=!1,ge=!1)=>{h(!0);const Ie=String(J.draft.apiKey||"").trim(),Ze=!!i[we.keySetting];try{const Nt={provider:we.provider,refresh:H,cacheOnly:ge};Ie&&(Nt.apiKey=Ie),we.baseUrlSetting&&J.draft.baseUrl&&(Nt.baseUrl=J.draft.baseUrl);const Ke=await Q.fetchAiModels(Nt);Ke&&(Ke.success||Ke.fallback)?(u(an=>({...an,[we.id]:{live:!!Ke.live,requiresApiKey:!!Ke.requiresApiKey,fallback:!!Ke.fallback,models:Ke.models||[],cached:!!Ke.cached,error:Ke.success?void 0:je(t,Ke.error,"aiModelsLoadError")}})),!Ke.live&&Ke.requiresApiKey&&H?n(t("connectKeyFirstPrompt"),"info"):!Ke.success&&Ke.error&&n(je(t,Ke.error,"aiModelsLoadError"),"error")):Ke&&!Ke.success&&Ke.error&&(u(an=>({...an,[we.id]:{live:!1,requiresApiKey:!(Ze||Ie),fallback:!0,models:Ke.models||[],error:je(t,Ke.error,"aiModelsLoadError")}})),n(je(t,Ke.error,"aiModelsLoadError"),"error"))}catch(Nt){ge||n(je(t,Nt,"aiModelsLoadError"),"error")}finally{h(!1)}};o.useEffect(()=>{d||X(!1,!0)},[we.id,d]);const ve=((us=m[we.id])==null?void 0:us.models)||[],ue=!!((Tn=m[we.id])!=null&&Tn.live),ke=!!(((ms=m[we.id])==null?void 0:ms.requiresApiKey)??!i[we.keySetting]),Me=r[O.modelSetting]||O.defaultModel,Te=J.draft.model||we.defaultModel,ae=H=>ve.find(ge=>ge.id.toLowerCase()===H.toLowerCase())||{id:H,displayName:H,provider:we.provider,recommended:!1,capabilities:{textInput:!0,textOutput:!0,vision:!1,audioInput:!1,stt:!1,videoInput:!1,pdfInput:!1},capabilitySource:"unknown"},K=ae(Te),pe=ae(Me),Ae=!!pe.capabilities.vision,Fe=!!pe.capabilities.stt,$e=pe.capabilitySource==="provider"||pe.capabilitySource==="seed",Be=r.ai_auto_detect_capabilities!==!1,z=$e&&Be&&!Ae,B=$e&&Be&&!Fe;o.useEffect(()=>{d||(z&&r.ai_vision_enabled&&ee("ai_vision_enabled",!1,!0),B&&r.ai_stt_enabled&&ee("ai_stt_enabled",!1,!0))},[Me,z,B,d]);const Z=async()=>{k(!0),b(!0);try{const H=await Q.getPersona(),ge=H==null?void 0:H.persona;w(typeof ge=="string"?ge:(ge==null?void 0:ge.body)||"")}catch(H){n(je(t,H,"aiPersonaLoadError"),"error")}finally{b(!1)}},ie=async()=>{try{await Q.updatePersona(N),n(t("aiPersonaUpdated"),"success"),k(!1)}catch(H){n(je(t,H,"aiPersonaSaveError"),"error")}},Ne=async()=>{try{const H=await Q.getMemoryFiles(),ge=((H==null?void 0:H.scopes)||[]).map(Ie=>({scope:Ie.scope,label:Ie.label,entries:Ie.entries??0}));j(ge.some(Ie=>Ie.scope==="global")?ge:[{scope:"global",label:"Global memory",entries:0},...ge])}catch(H){j([{scope:"global",label:"Global memory",entries:0}]),n(je(t,H,"aiMemoryLoadError"),"error")}},Qe=async H=>{_(H),D(""),F(!0);try{const ge=await Q.getMemoryFile(H);D((ge==null?void 0:ge.content)||"")}catch(ge){n(je(t,ge,"aiMemoryLoadError"),"error")}finally{F(!1)}},at=async()=>{_("global"),F(!0),await Ne();try{const H=await Q.getMemoryFile("global");D((H==null?void 0:H.content)||"")}catch(H){n(je(t,H,"aiMemoryLoadError"),"error")}finally{F(!1)}},Vt=async()=>{if(y)try{await Q.updateMemoryFile(y,A),n(t("aiMemoryUpdated"),"success"),Ne(),_(null)}catch(H){n(je(t,H,"aiMemorySaveError"),"error")}},jt=async()=>{P(!0),ne(null),V(null),C(!0);try{const H=await Q.getAiConversations();$((H==null?void 0:H.conversations)||[])}catch(H){n(je(t,H,"aiConversationsLoadError"),"error")}finally{C(!1)}},Ln=async H=>{ne(H),V(null),C(!0);try{const ge=await Q.getAiConversation(H);V(ge||null)}catch(ge){n(je(t,ge,"aiConversationLoadError"),"error")}finally{C(!1)}},Mn=H=>H?new Date(H).toLocaleString(At(s,{ar:"ar-EG",en:"en-GB"}),{dateStyle:"medium",timeStyle:"short"}):"—",kt={saveLabel:t("save"),savedLabel:t("saved")},cs={saveLabel:t("save"),discardLabel:t("discard"),unsavedLabel:t("unsavedChanges"),savedLabel:t("saved")};if(d)return e.jsx(vt,{text:t("starting")});const ds=!!r.ai_agent;return e.jsxs("div",{className:"flex flex-col gap-3 sm:gap-4",children:[e.jsx(Kt,{icon:e.jsx(Cn,{size:20}),title:t("aiTitle"),description:t("aiSubtitle")}),e.jsx(sc,{tab:"autoReply",title:t("plusRowAutoReplyTitle"),benefit:t("plusRowAutoReplyBenefit")}),e.jsx(he,{"data-tour":"ai-agent",children:e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-4",children:[e.jsx("span",{className:"text-sm font-semibold text-text-main",children:t("aiAgentEnabled")}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xs font-bold text-muted",children:t(ds?"toggleOn":"toggleOff")}),e.jsx(Je,{checked:ds,onChange:H=>ee("ai_agent",H),"aria-label":t("aiAgentEnabled")})]})]})}),e.jsxs(he,{className:"flex flex-col gap-3","data-tour":"ai-provider",children:[e.jsx(He,{icon:e.jsx(Vs,{size:18}),title:t("aiProvider")}),e.jsx(Rt,{"aria-label":t("aiProvider"),value:J.draft.presetId,onChange:H=>Se(H),options:Gt.map(H=>({value:H.id,label:H.name})),className:"w-full"}),e.jsx("p",{className:"text-xs text-muted",children:t(we.descKey)}),ke&&e.jsx("p",{className:"text-xs text-warn",children:t("connectKeyFirstPrompt")}),e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:H=>{H.preventDefault(),J.save(async ge=>{const Ie=Gt.find(Ze=>Ze.id===ge.presetId)||we;await le("ai_provider",Ie.provider),Ie.baseUrlSetting&&await le(Ie.baseUrlSetting,ge.baseUrl),await le(Ie.modelSetting,ge.model),ge.apiKey.trim()&&await le(Ie.keySetting,ge.apiKey.trim()),J.setDraft({...ge,apiKey:""})})},onKeyDown:H=>{H.key==="Escape"&&J.revert()},children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[e.jsx(re,{className:"min-w-0",htmlFor:"input-api-key",label:e.jsxs("span",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{children:t("apiKey")}),i[we.keySetting]&&e.jsxs(Ce,{tone:"ok",children:[e.jsx(Qt,{size:11}),t("saved")]})]}),children:e.jsx(dt,{id:"input-api-key",className:"font-mono",value:J.draft.apiKey,onChange:H=>J.setField("apiKey",H.target.value),placeholder:i[we.keySetting]?"••••••••••••":t("enterApiKey")})}),we.baseUrlSetting&&e.jsx(re,{className:"min-w-0",label:t("baseUrl"),htmlFor:"input-base-url",children:e.jsx(be,{id:"input-base-url",technical:!0,className:"font-mono",value:J.draft.baseUrl,onChange:H=>J.setField("baseUrl",H.target.value),placeholder:we.defaultBaseUrl})}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("label",{htmlFor:"input-model-name",className:"text-xs font-bold text-text-main",children:t("modelName")}),e.jsx(Ce,{tone:ue?"ok":"info",children:t(ue?"sourceLive":"sourceSeed")})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>x(!g),children:t(g?"modelListToggle":"modelCustomToggle")}),e.jsx(xe,{type:"button",variant:"ghost",label:t("refreshModels"),icon:e.jsx(it,{size:16}),onClick:()=>X(!0),loading:p})]})]}),((Pn=m[we.id])==null?void 0:Pn.error)&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-xl border border-danger/30 bg-danger/10 p-2 text-xs text-danger",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(Wt,{size:15,className:"shrink-0"}),e.jsx("span",{className:"min-w-0 break-words",children:(xs=m[we.id])==null?void 0:xs.error})]}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",icon:e.jsx(it,{size:14}),onClick:()=>X(!0),loading:p,children:t("retry")})]}),p?e.jsx("div",{className:"flex min-h-10 items-center gap-2 rounded-xl border border-line bg-panel-raised px-3",children:e.jsx(nt,{label:t("fetchingModels")})}):g?e.jsx(be,{id:"input-model-name",technical:!0,className:"font-mono",value:J.draft.model,onChange:H=>J.setField("model",H.target.value),placeholder:we.defaultModel}):ve.length===0?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-xl border border-line bg-panel-raised p-2 text-xs text-muted",children:[e.jsx("span",{children:t(ke?"connectKeyFirstPrompt":"noModelsFound")}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",icon:e.jsx(it,{size:14}),onClick:()=>X(!0),loading:p,children:t("retry")})]}):e.jsxs(Re,{id:"input-model-name",dir:"ltr",className:"font-mono text-start",value:Te,onChange:H=>J.setField("model",H.target.value),children:[e.jsx("optgroup",{label:t(ue?"modelsAvailableLive":"modelsRecommendedSeed"),children:ve.map(H=>e.jsxs("option",{value:H.id,dir:"ltr",children:[H.displayName&&H.displayName!==H.id?H.displayName:H.id,H.recommended?" ★":""]},H.id))}),!ve.some(H=>H.id.toLowerCase()===Te.toLowerCase())&&e.jsx("option",{value:Te,dir:"ltr",children:Te})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-xs text-muted",dir:"ltr",title:Te,children:[e.jsx("span",{className:"shrink-0 text-faint",children:"ID:"}),e.jsx("span",{className:"truncate font-mono",children:Te})]})]})]}),e.jsx(kn,{dirty:J.dirty,saving:J.status==="saving",justSaved:J.status==="saved",error:J.error,onDiscard:J.revert,...cs})]}),e.jsx(zu,{capabilities:K.capabilities,capabilitySource:K.capabilitySource})]}),e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx(He,{title:t("capabilities")}),e.jsxs("div",{className:"flex flex-col divide-y divide-line",children:[e.jsxs("div",{className:"py-2",children:[e.jsx(Je,{checked:z?!1:!!r.ai_vision_enabled,disabled:z,onChange:H=>{z||ee("ai_vision_enabled",H)},label:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(ts,{size:17,className:z?"shrink-0 text-muted":"shrink-0 text-brand-cyan"}),t("aiVision")]}),description:t("aiVisionDesc")}),z&&e.jsxs("p",{className:"mt-1 flex items-center gap-1 text-[11px] font-semibold text-warn",children:[e.jsx(tn,{size:13,className:"shrink-0"}),e.jsx("span",{children:t("visionUnsupportedNotice")})]})]}),e.jsxs("div",{className:"py-2",children:[e.jsx(Je,{checked:B?!1:!!(r.ai_stt_enabled??!0),disabled:B,onChange:H=>{B||ee("ai_stt_enabled",H)},label:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(oo,{size:17,className:B?"shrink-0 text-muted":"shrink-0 text-brand-purple"}),t("aiSttEnabled")]}),description:t("aiSttEnabledDesc")}),B&&e.jsxs("p",{className:"mt-1 flex items-center gap-1 text-[11px] font-semibold text-warn",children:[e.jsx(tn,{size:13,className:"shrink-0"}),e.jsx("span",{children:t("sttUnsupportedNotice")})]})]}),e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("aiStt"),description:t("sttDesc"),htmlFor:"ai-stt-provider",dirty:Y.dirty,saving:Y.status==="saving",justSaved:Y.status==="saved",error:Y.error,onSave:()=>Y.save(H=>le("ai_stt_provider",H)),onRevert:Y.revert,...kt,children:e.jsxs(Re,{id:"ai-stt-provider","aria-label":t("aiStt"),value:Y.value,disabled:B,onChange:H=>Y.setValue(H.target.value),children:[e.jsx("option",{value:"auto",children:t("sttAuto")}),e.jsx("option",{value:"gemini",children:t("sttGemini")}),e.jsx("option",{value:"openai",children:t("sttOpenAI")})]})})}),e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("botLanguage"),description:t("botLanguageDesc"),htmlFor:"ai-bot-language",dirty:L.dirty,saving:L.status==="saving",justSaved:L.status==="saved",error:L.error,onSave:()=>L.save(H=>le("bot_language",H)),onRevert:L.revert,...kt,children:e.jsxs(Re,{id:"ai-bot-language","aria-label":t("botLanguage"),value:L.value,onChange:H=>L.setValue(H.target.value),children:[e.jsx("option",{value:"auto",children:t("langAuto")}),e.jsx("option",{value:"ar",children:t("langAr")}),e.jsx("option",{value:"en",children:t("langEn")}),e.jsx("option",{value:"pt-BR",children:t("langPtBr")}),e.jsx("option",{value:"es-419",children:t("langEs419")})]})})}),e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("aiReplyLanguage"),description:t("aiReplyLanguageDesc"),htmlFor:"ai-reply-language",dirty:v.dirty,saving:v.status==="saving",justSaved:v.status==="saved",error:v.error,onSave:()=>v.save(H=>le("ai_reply_language",H)),onRevert:v.revert,...kt,children:e.jsxs(Re,{id:"ai-reply-language","aria-label":t("aiReplyLanguage"),value:v.value,onChange:H=>v.setValue(H.target.value),children:[e.jsx("option",{value:"follow_bot",children:t("aiLangFollowBot")}),e.jsx("option",{value:"auto",children:t("langAuto")}),e.jsx("option",{value:"ar",children:t("langAr")}),e.jsx("option",{value:"en",children:t("langEn")}),e.jsx("option",{value:"pt-BR",children:t("langPtBr")}),e.jsx("option",{value:"es-419",children:t("langEs419")})]})})}),e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("translateEngine"),description:t("translateEngineDesc"),htmlFor:"ai-translate-engine",dirty:T.dirty,saving:T.status==="saving",justSaved:T.status==="saved",error:T.error,onSave:()=>T.save(H=>le("translate_engine",H)),onRevert:T.revert,...kt,children:e.jsxs(Re,{id:"ai-translate-engine","aria-label":t("translateEngine"),value:T.value,onChange:H=>T.setValue(H.target.value),children:[e.jsx("option",{value:"ai",children:t("translateEngineAi")}),e.jsx("option",{value:"google",children:t("translateEngineGoogle")})]})})}),e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("googleTranslateApiKey"),description:t("googleTranslateApiKeyDesc"),htmlFor:"ai-google-translate-key",dirty:te.dirty,saving:te.status==="saving",justSaved:te.status==="saved",error:te.error,onSave:()=>te.save(async H=>{await le("google_translate_api_key",H),te.setValue("")}),onRevert:te.revert,...kt,children:e.jsx(dt,{id:"ai-google-translate-key",className:"font-mono",placeholder:i.google_translate_api_key?"••••••••••••":t("enterApiKey"),value:te.value,onChange:H=>te.setValue(H.target.value)})})})]})]}),e.jsxs(he,{className:"grid grid-cols-1 gap-2 sm:grid-cols-2","data-tour":"ai-memory",children:[e.jsx(U,{variant:"secondary",icon:e.jsx(ss,{size:16}),onClick:Z,title:t("personaDesc"),children:t("editPersona")}),e.jsx(U,{variant:"secondary",icon:e.jsx(Qr,{size:16}),onClick:at,title:t("memoryDesc"),children:t("manageMemory")}),e.jsx(U,{variant:"secondary",icon:e.jsx(tu,{size:16}),onClick:jt,title:t("aiInspectorDesc"),children:t("openInspector")})]}),e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx(He,{icon:e.jsx(Qr,{size:18}),title:t("aiGlobalMemoryAccess"),description:t("aiGlobalMemoryAccessDesc")}),e.jsxs("div",{className:"flex flex-col divide-y divide-line",children:[e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("aiGlobalMemoryRead"),description:t("aiGlobalMemoryReadDesc"),htmlFor:"ai-global-memory-read",dirty:oe.dirty,saving:oe.status==="saving",justSaved:oe.status==="saved",error:oe.error,onSave:()=>oe.save(H=>le("ai_global_memory_read",H)),onRevert:oe.revert,...kt,children:e.jsxs(Re,{id:"ai-global-memory-read","aria-label":t("aiGlobalMemoryRead"),value:oe.value,onChange:H=>oe.setValue(H.target.value),children:[e.jsx("option",{value:"off",children:t("aiGlobalMemoryOff")}),e.jsx("option",{value:"owner",children:t("aiGlobalMemoryOwner")}),e.jsx("option",{value:"privileged",children:t("aiGlobalMemoryPrivileged")}),e.jsx("option",{value:"everyone",children:t("aiGlobalMemoryEveryone")})]})})}),e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("aiGlobalMemoryWrite"),description:t("aiGlobalMemoryWriteDesc"),htmlFor:"ai-global-memory-write",dirty:ye.dirty,saving:ye.status==="saving",justSaved:ye.status==="saved",error:ye.error,onSave:()=>ye.save(H=>le("ai_global_memory_write",H)),onRevert:ye.revert,...kt,children:e.jsxs(Re,{id:"ai-global-memory-write","aria-label":t("aiGlobalMemoryWrite"),value:ye.value,onChange:H=>ye.setValue(H.target.value),children:[e.jsx("option",{value:"off",children:t("aiGlobalMemoryOff")}),e.jsx("option",{value:"owner",children:t("aiGlobalMemoryOwner")}),e.jsx("option",{value:"privileged",children:t("aiGlobalMemoryPrivileged")})]})})}),e.jsx("div",{className:"py-2",children:e.jsx(Ge,{label:t("aiGlobalMemoryWhere"),description:t("aiGlobalMemoryWhereDesc"),htmlFor:"ai-global-memory-where",dirty:fe.dirty,saving:fe.status==="saving",justSaved:fe.status==="saved",error:fe.error,onSave:()=>fe.save(H=>le("ai_global_memory_where",H)),onRevert:fe.revert,...kt,children:e.jsxs(Re,{id:"ai-global-memory-where","aria-label":t("aiGlobalMemoryWhere"),value:fe.value,onChange:H=>fe.setValue(H.target.value),children:[e.jsx("option",{value:"own_chat",children:t("aiGlobalMemoryWhereOwnChat")}),e.jsx("option",{value:"private",children:t("aiGlobalMemoryWherePrivate")}),e.jsx("option",{value:"all",children:t("aiGlobalMemoryWhereAll")})]})})})]})]}),e.jsx(Ye,{isOpen:f,onClose:()=>k(!1),title:t("personaPrompt"),maxWidth:"750px",footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:()=>k(!1),children:t("cancel")}),e.jsx(U,{variant:"primary",icon:e.jsx(yn,{size:16}),onClick:ie,disabled:S,children:t("save")})]}),children:S?e.jsx("div",{className:"flex min-h-[280px] items-center justify-center",children:e.jsx(nt,{className:"size-6",label:t("starting")})}):e.jsx(wt,{className:"font-mono",rows:12,value:N,onChange:H=>w(H.target.value)})}),e.jsx(Ye,{isOpen:!!y,onClose:()=>_(null),title:t("memoryFiles"),maxWidth:"900px",footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:()=>_(null),children:t("cancel")}),e.jsx(U,{variant:"primary",icon:e.jsx(yn,{size:16}),onClick:Vt,disabled:I,children:t("save")})]}),children:e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row",children:[e.jsx("div",{className:"flex shrink-0 flex-col gap-1.5 md:max-h-[420px] md:w-60 md:overflow-y-auto",children:R.length===0?e.jsx(Pe,{kind:"empty",text:t("noMemoryFiles"),className:"py-6"}):R.map(H=>{const ge=H.scope==="global",Ie=y===H.scope;return e.jsxs(U,{variant:Ie?"primary":"secondary","aria-pressed":Ie,onClick:()=>Qe(H.scope),className:"h-auto w-full flex-col items-stretch gap-1 px-2.5 py-2.5",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2 text-xs font-bold",children:[ge?e.jsx(Is,{size:14,className:"shrink-0"}):e.jsx(Ss,{size:14,className:"shrink-0"}),e.jsx("span",{className:"truncate",children:ge?t("memoryGlobalScope"):H.label||t(H.scope.endsWith("@g.us")?"unnamedGroup":"unknownContact")})]}),e.jsxs("span",{className:"block text-start text-[10px] opacity-80",children:[t(ge?"memoryGlobalScopeHint":"memoryChatScopeHint")," · ",t("memoryEntriesCount").replace("{n}",String(H.entries))]})]},H.scope)})}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[e.jsx("p",{className:"text-[11px] leading-relaxed text-muted",children:t("memoryProseHint")}),I?e.jsx("div",{className:"flex min-h-[340px] items-center justify-center",children:e.jsx(nt,{className:"size-6",label:t("starting")})}):e.jsx(wt,{className:"min-h-[340px] flex-1 font-mono",rows:12,value:A,onChange:H=>D(H.target.value),placeholder:t("memoryEditorPlaceholder")})]})]})}),e.jsx(Ye,{isOpen:E,onClose:()=>P(!1),title:t("aiInspector"),maxWidth:"750px",footer:e.jsx(U,{variant:"secondary",onClick:()=>P(!1),children:t("cancel")}),children:q?e.jsx("div",{className:"flex min-h-[280px] items-center justify-center",children:e.jsx(nt,{className:"size-6",label:t("starting")})}):G?e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(U,{variant:"ghost",size:"sm",icon:e.jsx(Xn,{size:16,className:"rtl:rotate-180"}),onClick:()=>ne(null),children:t("backToList")}),e.jsx(ze,{lines:2,className:"text-xs text-muted",children:(se==null?void 0:se.name)||((Ot=M.find(H=>H.chatId===G))==null?void 0:Ot.name)||t((se==null?void 0:se.kind)==="group"?"unnamedGroup":"unknownContact")})]}),(se==null?void 0:se.truncated)&&e.jsx("p",{className:"text-[11px] font-semibold text-warn",children:t("convTruncated")}),e.jsxs("div",{className:"flex max-h-[420px] flex-col gap-1.5 overflow-y-auto",children:[(se==null?void 0:se.messages.length)===0&&e.jsx(Pe,{kind:"empty",text:t("noConversations"),className:"py-6"}),se==null?void 0:se.messages.map((H,ge)=>e.jsxs("div",{className:`rounded-xl border p-2.5 text-xs ${H.kind==="tool"||H.kind==="toolResult"?"border-line bg-panel font-mono text-muted":H.role==="model"?"border-brand-blue/25 bg-brand-blue/10 text-text-main":"border-line bg-panel-raised text-text-main"}`,children:[H.kind==="text"&&e.jsx("p",{className:"whitespace-pre-wrap break-words leading-relaxed",children:H.text}),H.kind==="media"&&e.jsxs("span",{children:["📎 ",H.mimeType||t("convMedia")]}),H.kind==="tool"&&e.jsxs("span",{children:["⚙️ ",H.name]}),H.kind==="toolResult"&&e.jsxs("span",{children:["↩️ ",H.name]})]},ge))]})]}):M.length===0?e.jsx(Pe,{kind:"empty",icon:e.jsx(Ss,{size:20}),text:t("noConversations"),className:"py-8"}):e.jsx("div",{className:"flex flex-col gap-1.5",children:M.map(H=>e.jsxs(U,{variant:"secondary",onClick:()=>Ln(H.chatId),className:"h-auto w-full flex-col items-stretch gap-1 px-3 py-3",children:[e.jsxs("span",{className:"flex items-center gap-2 text-xs font-bold",children:[e.jsx(Ss,{size:14,className:"shrink-0 text-brand-blue"}),e.jsx(ze,{lines:2,children:H.name||t(H.kind==="group"?"unnamedGroup":"unknownContact")})]}),e.jsxs("span",{className:"block text-start text-[10px] text-muted",children:[t("convTurns").replace("{n}",String(H.turns))," ·"," ",Mn(H.updatedAt)]})]},H.chatId))})})]})},gt={rules:100,keywords:50,keywordChars:100,nameChars:60,senders:200,phoneMin:8,phoneMax:15},Bu=/[\u064B-\u065F\u0670\u0640]/g,Uu=/[\u0622\u0623\u0625\u0671]/g,$u=/\u0649/g,ra={enabled:"any",chatScope:"any",senders:"any"};function ur(t){let s=String(t??"");return s=s.normalize("NFKC"),s=s.replace(Bu,""),s=s.replace(Uu,"ا"),s=s.replace($u,"ي"),s=s.toLowerCase(),s=s.replace(/\s+/g," ").trim(),s}function Ku(t){const s=String(t??"").normalize("NFC").replace(/\s+/g," ").trim();return s?s.length>gt.keywordChars?{error:"long"}:ur(s)?{value:s}:{error:"empty"}:{error:"empty"}}class dn extends Error{constructor(s){super(s),this.reason=s,this.name="SenderInputError"}}function Hu(t){var a;const s=String(t??"").trim();if(!s)throw new dn("invalid");const n=s.toLowerCase();if(n.endsWith("@g.us")||n.endsWith("@broadcast")||n.endsWith("@newsletter"))throw new dn("group");if(s.includes("@")){if(n.includes("@lid")){const i=(a=s.split("@")[0])==null?void 0:a.split(":")[0];if(!i)throw new dn("invalid");return`${i}@lid`}if(s.includes(":")){const i=s.split(":")[0],l=s.split("@")[1];if(!i||!l)throw new dn("invalid");return`${i}@${l}`}return s}const r=s.replace(/\D/g,"");if(r.length>=gt.phoneMin&&r.length<=gt.phoneMax)return`${r}@s.whatsapp.net`;throw new dn("invalid")}function Nn(t){var n;const s=(n=t.name)==null?void 0:n.trim();return s||t.keywords[0]||""}function Fs(t,s){if(!t)return"";const n=s==null?void 0:s.get(t);if(n)return n;const r=/^(\d+)@s\.whatsapp\.net$/i.exec(t);return r?`+${r[1]}`:t}function mr(t,s){return t&&(s!=null&&s.has(t))?"auto":"ltr"}function Vu(t){const s={};return t.name.trim().length>gt.nameChars&&(s.name="long"),t.keywords.length<1?s.keywords="required":t.keywords.length>gt.keywords&&(s.keywords="max"),t.sendersMode==="selected"&&(t.senders.length<1?s.senders="required":t.senders.length>gt.senders&&(s.senders="max")),s}function qu(t,s){return{name:t.name.trim()||null,keywords:t.keywords,match:t.match,chatScope:t.chatScope,senders:{mode:t.sendersMode,list:t.sendersMode==="everyone"?[]:t.senders},includeOwn:t.includeOwn,forEveryone:t.forEveryone,keepCopy:t.keepCopy,...s===void 0?{}:{enabled:s}}}function Wu(t,s,n){const r=ur(s);return!(r&&!ur(`${t.name??""} ${t.keywords.join(" ")}`).includes(r)||n.enabled==="on"&&!t.enabled||n.enabled==="off"&&t.enabled||n.chatScope!=="any"&&t.chatScope!==n.chatScope||n.senders!=="any"&&t.senders.mode!==n.senders)}function Gu(t,s,n){const r=[...t],a=(i,l)=>Nn(i).localeCompare(Nn(l),n,{sensitivity:"base"});return s==="name"?r.sort(a):s==="deleted"?r.sort((i,l)=>l.deletedCount-i.deletedCount||a(i,l)):s==="last"?r.sort((i,l)=>(l.lastDeletedAt??-1)-(i.lastDeletedAt??-1)||a(i,l)):r.sort((i,l)=>l.createdAt-i.createdAt||l.id-i.id),r}function Ju(t){return[t.enabled,t.chatScope,t.senders].filter(s=>s!=="any").length}const ia=20,Yu=({rules:t,names:s,ruleId:n,onRuleIdChange:r})=>{const{t:a}=me(),{toast:i}=qe(),[l,d]=o.useState([]),[c,m]=o.useState(0),[u,p]=o.useState(1),[h,g]=o.useState(!0),[x,f]=o.useState(null),[k,N]=o.useState(0),[w,S]=o.useState(null),[b,R]=o.useState(!1),j=o.useRef(0),y=`${n}|${k}`,[_,A]=o.useState(y);_!==y&&(A(y),p(1)),o.useEffect(()=>{const M=++j.current;g(!0),f(null),Q.listAutoDeleteLog({ruleId:n||void 0,limit:ia,offset:(u-1)*ia}).then($=>{j.current===M&&(d($.log),m($.total))}).catch($=>{if(j.current!==M)return;const G=je(a,$,"copiesLoadFailed");f(G),i(G,"error")}).finally(()=>{j.current===M&&g(!1)})},[n,k,u,a,i]);const D=async()=>{R(!0);try{await Q.clearAutoDeleteLog(w==="rule"?n:void 0),i(a("copiesCleared"),"success"),S(null),N(M=>M+1)}catch(M){i(je(a,M,"copiesClearError"),"error")}finally{R(!1)}},I=o.useCallback(M=>{if(!M)return a("mediaText");const G={image:"mediaImage",video:"mediaVideo",audio:"mediaAudio",sticker:"mediaSticker",document:"mediaDocument"}[M];return G?a(G):M},[a]),F=t.find(M=>String(M.id)===n),E=Math.max(1,Math.ceil(c/ia)),P=Math.min(u,E);return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs(It,{children:[e.jsx(zt,{label:a("filter"),resetLabel:a("reset"),activeCount:n?1:0,onReset:()=>r(""),children:e.jsx(re,{label:a("filterByRule"),children:e.jsxs(Re,{"aria-label":a("filterByRule"),value:n,onChange:M=>r(M.target.value),children:[e.jsx("option",{value:"",children:a("allRules")}),t.map(M=>e.jsx("option",{value:String(M.id),children:Nn(M)},M.id))]})})}),e.jsx("span",{className:"ms-auto",children:e.jsxs(mt,{label:a("more"),children:[n&&e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>S("rule"),children:a("clearCopiesForRule")}),e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>S("all"),children:a("clearCopies")})]})})]}),h&&e.jsx("div",{className:"flex flex-col gap-3","aria-busy":"true",children:["s1","s2","s3"].map(M=>e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx(Ve,{className:"h-4 w-40"}),e.jsx(Ve,{className:"h-12 w-full"}),e.jsx(Ve,{className:"h-5 w-24"})]},M))}),!h&&x&&e.jsx(Pe,{kind:"error",icon:e.jsx(ft,{size:28}),description:x,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>N(M=>M+1),children:a("retryLoad")})}),!h&&!x&&l.length===0&&n&&e.jsx(Pe,{kind:"no-results",description:a("noCopiesForRule"),action:e.jsx(U,{variant:"secondary",onClick:()=>r(""),children:a("clearFilters")})}),!h&&!x&&l.length===0&&!n&&e.jsx(Pe,{kind:"empty",title:a("noCopiesTitle"),description:a("noCopiesBody")}),!h&&!x&&l.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-col gap-3",children:l.map(M=>{const $=Fs(M.chatJid,s)||"—",G=Fs(M.sender,s)||"—",ne=M.mode==="revoke"?a("modeRevoke"):M.mode==="deleteForMe"?a("modeForMe"):M.mode;return e.jsxs(he,{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] font-bold text-faint",children:a("copyChat")}),e.jsx("p",{dir:mr(M.chatJid,s),className:"truncate text-sm font-semibold",children:$})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] font-bold text-faint",children:a("copySender")}),e.jsx("p",{dir:mr(M.sender,s),className:"truncate text-sm",children:G})]}),e.jsx(jn,{value:M.createdAt,className:"ms-auto text-xs text-muted"})]}),e.jsx("p",{dir:"auto",className:"whitespace-pre-wrap break-words text-sm text-text-main",children:M.text||"—"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(Ce,{children:I(M.mediaType)}),e.jsx(Ce,{tone:M.mode==="revoke"?"info":"neutral",children:ne})]})]},M.id)})}),e.jsx(Ht,{page:P,pageCount:E,total:c,onPageChange:p})]}),e.jsx(ut,{isOpen:w!==null,onClose:()=>S(null),onConfirm:()=>void D(),title:a("clearCopiesTitle"),description:w==="rule"?de(a("clearCopiesRuleBody"),{name:F?Nn(F):""}):a("clearCopiesBody"),confirmLabel:a("clearCopies"),cancelLabel:a("cancel"),loading:b})]})},Qu=new Set(["Contact","Group"]);function di(t){return t==="saved"||t==="push"||t==="subject"||t==="phone"||t==="none"?t:null}function Bs(t){return String(t||"").replace(/\D/g,"").replace(/^0+/,"")}function Xu(t){const s=String(t||"").replace(/\D/g,"");if(!s)return"";const n=s.match(/.{1,3}/g);return`+${n?n.join(" "):s}`}function gc(t){const s=t.type||t.targetKind||"",n=String(t.id||t.targetJid||"");return s==="group"||n.endsWith("@g.us")?"group":"contact"}function bc(t){const s=di(t.nameSource)||di(t.targetNameSource);if(s)return s;const n=gc(t);return pt(t.savedName)?"saved":pt(t.pushName)?"push":n==="group"&&(pt(t.name,!0)||pt(t.targetLabel,!0))?"subject":t.phone||t.targetPhone?"phone":"none"}function pt(t,s=!1){const n=String(t||"").trim();return!n||n.includes("@")||/^\d{8,}$/.test(n)||s&&Qu.has(n)?null:n}function yc(t){const s=String(t||"").split("@")[0].split(":")[0],r=s.replace(/\D/g,"")||s;return r?r.slice(-4):""}function vc(t){return String(t.id||t.targetJid||"")}function Zu(t,s){return s==="saved"?pt(t.savedName)||pt(t.name,!0)||pt(t.targetLabel,!0):s==="push"?pt(t.pushName)||pt(t.name,!0)||pt(t.targetLabel,!0):s==="subject"?pt(t.name)||pt(t.targetLabel):null}function em(t,s,n){let r="other";try{r=new Intl.PluralRules(n).select(t)}catch{r="other"}const a=`recipientMembers_${r}`,i=s(a),l=i&&i!==a?i:s("recipientMembers_other");return de(l,{count:t})}function tm(t,s){const n=yc(t);return n?de(s("recipientIdTail"),{tail:n}):""}function xr(t,s,n="en"){const r=gc(t),a=bc(t),i=vc(t),l=tm(i,s),d=Zu(t,a),c=Xu(t.phone||t.targetPhone);if(a==="phone"&&c)return{title:c,subtitle:"",kind:r,distinguisher:l};if(a==="none"||!d)return{title:s(r==="group"?"recipientUnnamedGroup":"recipientUnknownContact"),subtitle:l,kind:r,distinguisher:l};let m="";if(r==="group"){const u=t.memberCount;typeof u=="number"&&Number.isFinite(u)&&u>=0&&(m=em(Math.trunc(u),s,n))}else c&&Bs(c)!==Bs(d)&&(m=c);return{title:d,subtitle:m,kind:r,distinguisher:l}}function la(t){return`${t.title}
439
+ ${t.subtitle}`}function nm(t){const s=new Map;for(const n of t)s.set(la(n),(s.get(la(n))||0)+1);return t.map(n=>{if((s.get(la(n))||0)<2||!n.distinguisher||n.subtitle.includes(n.distinguisher)||n.title.includes(n.distinguisher))return n;const r=n.subtitle?`${n.subtitle} · ${n.distinguisher}`:n.distinguisher;return{...n,subtitle:r}})}function pr(t,s,n="en"){return nm(t.map(r=>xr(r,s,n)))}function sm(t){const s=bc(t),n=s==="none"||s==="phone",r=[t.savedName,t.pushName,t.name,t.targetLabel],a=[];for(const i of r){const l=pt(i,n);l&&!a.includes(l)&&a.push(l)}return a}function Mr(t,s){const n=s.trim().toLowerCase();if(!n||sm(t).some(l=>l.toLowerCase().includes(n)))return!0;const r=Bs(s);if(!r)return!1;const a=[t.phone,t.targetPhone],i=vc(t);return i.endsWith("@s.whatsapp.net")&&a.push(i),a.some(l=>Bs(l).includes(r))?!0:yc(i)===r}function am(t){const s=[],n=/\+?\d[\d\u00a0 ]*/g;let r=0;for(const a of t.matchAll(n)){const i=a.index??0;i>r&&s.push({text:t.slice(r,i),ltr:!1});const l=a[0].trimEnd(),d=a[0].slice(l.length);l&&s.push({text:l,ltr:!0}),d&&s.push({text:d,ltr:!1}),r=i+a[0].length}return r<t.length&&s.push({text:t.slice(r),ltr:!1}),s.length||s.push({text:t,ltr:!1}),s}function rm(t,s,n=new Date){var a;const r=t;try{return((a=new Intl.DateTimeFormat(s,{timeZone:r,timeZoneName:"long"}).formatToParts(n).find(l=>l.type==="timeZoneName"))==null?void 0:a.value)||r}catch{return r}}function im(t,s,n){const r=s;try{return new Intl.DateTimeFormat(n,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",timeZoneName:"long"}).format(new Date(t))}catch{return new Intl.DateTimeFormat(n,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}}const lm={NO_MEDIA:"stickerErr_NO_MEDIA",UNSUPPORTED_TYPE:"stickerErr_UNSUPPORTED_TYPE",TOO_LARGE:"stickerErr_TOO_LARGE",DIMENSIONS_TOO_LARGE:"stickerErr_DIMENSIONS_TOO_LARGE",VIDEO_TOO_LONG:"stickerErr_VIDEO_TOO_LONG",CORRUPT:"stickerErr_CORRUPT",CONVERSION_FAILED:"stickerErr_CONVERSION_FAILED",OUTPUT_TOO_LARGE:"stickerErr_OUTPUT_TOO_LARGE",ENCODER_MISSING:"stickerErr_ENCODER_MISSING",TIMEOUT:"stickerErr_TIMEOUT",BUSY:"stickerErr_BUSY",NOT_FOUND:"stickerErr_NOT_FOUND",PACK_NOT_FOUND:"stickerErr_PACK_NOT_FOUND",PACK_EXISTS:"stickerErr_PACK_EXISTS",INVALID_NAME:"stickerErr_INVALID_NAME",INVALID_OPTIONS:"stickerErr_INVALID_OPTIONS",LIBRARY_FULL:"stickerErr_LIBRARY_FULL",PACK_LIMIT:"stickerErr_PACK_LIMIT",IN_USE:"stickerErr_IN_USE",STORAGE_UNAVAILABLE:"stickerErr_STORAGE_UNAVAILABLE",NOT_CONNECTED:"stickerErr_NOT_CONNECTED",CANCELLED:"stickerErr_CANCELLED",INTERNAL:"stickerErr_INTERNAL"};function Tr(t){return t?lm[t]??null:null}function Pr(t,s){const n=Tr(s);return t(n||"stickerErr_INTERNAL")}function hr(t,s){return s instanceof et?Pr(t,s.code):t("stickerErr_INTERNAL")}function om(t,s){const r=s?{probing:"jobStage_probing",decoding:"jobStage_decoding",encoding:"jobStage_encoding",optimizing:"jobStage_optimizing",queued:"jobQueued"}[s]:null;return t(r||"jobQueued")}function Dr({text:t,className:s}){const n=am(t);return e.jsx("span",{dir:"auto",className:s,children:n.map(r=>r.ltr?e.jsx("bdi",{dir:"ltr",children:r.text},`ltr:${r.text}`):e.jsx("span",{children:r.text},`txt:${r.text}`))})}function cm({kind:t}){const s=t==="group"?En:Lr,n=t==="group"?"bg-brand-blue/10 text-brand-cyan":"bg-ok/10 text-ok";return e.jsx("span",{className:`flex size-10 shrink-0 items-center justify-center rounded-xl ${n}`,"aria-hidden":!0,children:e.jsx(s,{size:18})})}const es=({open:t,busy:s=!1,onClose:n,onPick:r,title:a,includeGroups:i=!0,selectedIds:l,emptyText:d})=>{const{t:c,language:m}=me(),[u,p]=o.useState([]),[h,g]=o.useState(""),[x,f]=o.useState(!1),[k,N]=o.useState(null);o.useEffect(()=>{if(!t)return;let b=!1;return f(!0),N(null),Q.getRecipients().then(R=>{b||p(R.recipients)}).catch(R=>{b||(R instanceof et&&Tr(R.code)?N(hr(c,R)):N(je(c,R,"recipientsLoadFailed")))}).finally(()=>{b||f(!1)}),()=>{b=!0}},[t,c]);const w=o.useMemo(()=>{const b=i?u:u.filter(j=>j.type==="contact"),R=h.trim();return R?b.filter(j=>Mr(j,R)):b},[i,u,h]),S=o.useMemo(()=>pr(w,b=>c(b),m),[w,m,c]);return e.jsx(Ye,{isOpen:t,onClose:n,title:a??c("sendViaWhatsapp"),footer:e.jsx(U,{onClick:n,disabled:s,children:c("cancel")}),children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Er,{size:16,className:"pointer-events-none absolute start-3 top-3 text-muted"}),e.jsx(be,{type:"search",value:h,onChange:b=>g(b.target.value),placeholder:c("searchRecipients"),"aria-label":c("searchRecipients"),className:"ps-9"})]}),x&&e.jsx(vt,{text:c("loading")}),k&&e.jsx("p",{className:"text-sm text-danger",role:"alert",children:k}),!x&&!k&&w.length===0&&e.jsx("p",{className:"text-sm text-muted",children:d??c("noRecipients")}),!x&&!k&&w.length>0&&e.jsx("p",{className:"text-xs text-muted","aria-live":"polite",children:de(c("recipientResultCount"),{count:w.length})}),e.jsx("div",{className:"flex max-h-72 flex-col gap-1 overflow-y-auto",children:w.map((b,R)=>{const j=S[R],y=(l==null?void 0:l.includes(b.id))??!1;return e.jsxs(U,{variant:"secondary",disabled:s||y,"aria-pressed":y,onClick:()=>r(b.id),className:`h-auto min-h-14 w-full items-center justify-start gap-3 px-3 py-1.5 text-start ${y?"border-brand-blue/40 bg-brand-blue/10":""}`,children:[e.jsx(cm,{kind:j.kind}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx(ze,{lines:1,className:"block text-sm font-semibold text-text-main",children:j.title}),j.subtitle?e.jsx(Dr,{text:j.subtitle,className:"block truncate text-[11px] text-muted"}):null]}),y&&e.jsxs("span",{className:"inline-flex shrink-0 items-center text-brand-blue",children:[e.jsx(gn,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sr-only",children:c("contactAdded")})]})]},b.id)})}),s&&e.jsx("p",{className:"text-xs text-muted",children:c("sending")})]})})},dm=["contains","word","exact"],um=["all","groups","private"],mm=({open:t,rule:s,names:n,onClose:r,onSaved:a})=>{const{t:i}=me(),l=o.useRef(s);l.current=s;const d=(s==null?void 0:s.id)??null,[c,m]=o.useState(""),[u,p]=o.useState([]),[h,g]=o.useState("contains"),[x,f]=o.useState("all"),[k,N]=o.useState("everyone"),[w,S]=o.useState([]),[b,R]=o.useState(!1),[j,y]=o.useState(!0),[_,A]=o.useState(!1),[D,I]=o.useState(""),[F,E]=o.useState(!1),[P,M]=o.useState(!1),[$,G]=o.useState(null),[ne,se]=o.useState(null),[V,q]=o.useState(null),[C,O]=o.useState(null);o.useEffect(()=>{if(!t)return;const T=l.current;((T==null?void 0:T.id)??null)===d&&(m((T==null?void 0:T.name)??""),p((T==null?void 0:T.keywords)??[]),g((T==null?void 0:T.match)??"contains"),f((T==null?void 0:T.chatScope)??"all"),N((T==null?void 0:T.senders.mode)??"everyone"),S((T==null?void 0:T.senders.list)??[]),R((T==null?void 0:T.includeOwn)??!1),y((T==null?void 0:T.forEveryone)??!0),A((T==null?void 0:T.keepCopy)??!1),I(""),E(!1),M(!1),G(null),se(null),q(null),O(null))},[t,d]);const J=i(h==="word"?"matchWordHint":h==="exact"?"matchExactHint":"matchContainsHint"),Y=T=>{q(T==="long"?i("keywordTooLong"):T==="max"?i("keywordsMax"):T==="empty"?i("keywordEmpty"):T==="duplicate"?i("keywordDuplicate"):null)},L=T=>{try{const te=Hu(T);if(w.includes(te)){I(""),O(null);return}if(w.length>=gt.senders){O(i("tooManySenders"));return}S(oe=>oe.includes(te)?oe:[...oe,te]),I(""),O(null)}catch(te){O(te instanceof dn&&te.reason==="group"?i("groupSenderRejected"):i("invalidPhone"))}},v=async T=>{var ye;T.preventDefault();const te={name:c,keywords:u,match:h,chatScope:x,sendersMode:k,senders:w,includeOwn:b,forEveryone:j,keepCopy:_},oe=Vu(te);if(se(oe.name?i("nameTooLong"):null),q(oe.keywords==="required"?i("keywordsRequired"):oe.keywords==="max"?i("keywordsMax"):null),O(oe.senders==="required"?i("sendersRequired"):oe.senders==="max"?i("tooManySenders"):null),!(oe.name||oe.keywords||oe.senders)){M(!0),G(null);try{const fe=qu(te,(ye=l.current)==null?void 0:ye.enabled),we=l.current?await Q.updateAutoDeleteRule(l.current.id,fe):await Q.createAutoDeleteRule(fe);a(we.rule)}catch(fe){const we=je(i,fe,"ruleSaveFailed");G(we)}finally{M(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(Ye,{isOpen:t,onClose:r,title:i(s?"editRule":"newRule"),maxWidth:"40rem",footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:r,disabled:P,children:i("cancel")}),e.jsx(U,{variant:"primary",type:"submit",form:"auto-delete-rule-form",loading:P,children:i("saveRule")})]}),children:e.jsxs("form",{id:"auto-delete-rule-form",className:"flex flex-col gap-4",onSubmit:T=>void v(T),children:[$&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:$}),e.jsx(re,{label:i("ruleName"),htmlFor:"ad-rule-name",error:ne,children:e.jsx(be,{id:"ad-rule-name",name:"rule-name",dir:"auto",value:c,"aria-invalid":ne?!0:void 0,placeholder:i("ruleNamePlaceholder"),onChange:T=>{m(T.target.value),ne&&T.target.value.trim().length<=gt.nameChars&&se(null)},onBlur:()=>{c.trim().length>gt.nameChars&&se(i("nameTooLong"))}})}),e.jsx(re,{label:i("keywordsLabel"),error:V,children:e.jsx(ul,{id:"ad-keywords",value:u,onChange:p,max:gt.keywords,prepare:Ku,onReject:Y,removeLabel:T=>de(i("removeKeyword"),{word:T}),countLabel:de(i("keywordCount"),{n:u.length,max:gt.keywords}),placeholder:i("keywordsPlaceholder"),"aria-label":i("keywordsLabel"),"aria-invalid":V?!0:void 0,disabled:P})}),e.jsx(re,{label:i("matchMode"),description:J,children:e.jsx(Rt,{"aria-label":i("matchMode"),className:"flex w-full flex-wrap",value:h,onChange:g,options:dm.map(T=>({value:T,label:i(T==="contains"?"matchContains":T==="word"?"matchWord":"matchExact")}))})}),e.jsx(re,{label:i("chatScopeLabel"),children:e.jsx(Rt,{"aria-label":i("chatScopeLabel"),className:"flex w-full flex-wrap",value:x,onChange:f,options:um.map(T=>({value:T,label:i(T==="all"?"chatsAll":T==="groups"?"chatsGroups":"chatsPrivate")}))})}),e.jsxs(re,{label:i("filterSender"),error:k==="selected"?C:null,children:[e.jsx(Rt,{"aria-label":i("filterSender"),className:"flex w-full flex-wrap",value:k,onChange:N,options:[{value:"everyone",label:i("sendersEveryone")},{value:"selected",label:i("sendersSelected")}]}),k==="selected"&&e.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[e.jsx("p",{className:"text-xs text-muted",children:i("sendersHelp")}),w.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:w.map(T=>e.jsx(Ks,{dir:mr(T,n),removeLabel:de(i("removeContact"),{name:Fs(T,n)}),onRemove:()=>S(te=>te.filter(oe=>oe!==T)),children:Fs(T,n)},T))}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(be,{type:"tel",inputMode:"tel",name:"phone",autoComplete:"tel",dir:"ltr",value:D,placeholder:i("phonePlaceholder"),"aria-label":i("phonePlaceholder"),className:"min-w-0 flex-1",onChange:T=>I(T.target.value),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),L(D))}}),e.jsx(U,{type:"button",variant:"secondary",onClick:()=>L(D),children:i("addPhone")})]}),e.jsx(U,{type:"button",variant:"secondary",onClick:()=>E(!0),children:i("selectContacts")})]})]}),e.jsx(Je,{checked:b,onChange:R,label:i("includeOwn"),description:i("includeOwnHint")}),e.jsx(Je,{checked:j,onChange:y,label:i("forEveryone"),description:i("forEveryoneHint")}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(Je,{checked:_,onChange:A,label:i("keepCopy"),description:i("keepCopyHint")}),e.jsx("p",{className:"text-xs text-faint",children:i("keepCopyPrivacy")})]})]})}),e.jsx(es,{open:F,onClose:()=>E(!1),title:i("selectContacts"),includeGroups:!1,selectedIds:w,emptyText:i("noContacts"),onPick:T=>L(T)})]})},ui=4,xm={contains:"matchContains",word:"matchWord",exact:"matchExact"},pm=()=>{const{t,language:s}=me(),{toast:n}=qe(),[r,a]=o.useState("rules"),[i,l]=o.useState([]),[d,c]=o.useState(()=>new Map),[m,u]=o.useState(!0),[p,h]=o.useState(null),[g,x]=o.useState(0),[f,k]=o.useState(""),[N,w]=o.useState("newest"),[S,b]=o.useState(ra),[R,j]=o.useState(!1),[y,_]=o.useState(null),[A,D]=o.useState(null),[I,F]=o.useState(!1),[E,P]=o.useState(""),M=o.useRef(new Set),$=o.useRef(new Map),G=o.useRef(0),ne=o.useRef(!0),se=o.useRef(0),V=o.useMemo(()=>new Intl.NumberFormat(At(s,{ar:"ar",en:"en"})),[s]),q=o.useCallback(X=>{l(ve=>X.map(ue=>{if(!M.current.has(ue.id))return ue;const ke=ve.find(Me=>Me.id===ue.id);return ke?{...ue,enabled:ke.enabled}:ue}))},[]);o.useEffect(()=>{const X=++G.current;return u(!0),Q.listAutoDeleteRules().then(ve=>{!ne.current||G.current!==X||(q(ve.rules),h(null))}).catch(ve=>{if(!ne.current||G.current!==X)return;const ue=je(t,ve,"rulesLoadFailed");h(ue),n(ue,"error")}).finally(()=>{ne.current&&G.current===X&&u(!1)}),()=>{G.current+=1}},[g,t,n,q]),o.useEffect(()=>(ne.current=!0,()=>{ne.current=!1}),[]);const C=o.useCallback(async()=>{const X=++G.current,ve=se.current;try{const ue=await Q.listAutoDeleteRules();if(!ne.current||G.current!==X||se.current!==ve)return;q(ue.rules),h(null)}catch{}},[q]);o.useEffect(()=>{if(m)return;const X=()=>{document.visibilityState!=="hidden"&&C()};window.addEventListener("focus",X),document.addEventListener("visibilitychange",X);const ve=window.setInterval(X,3e4);return()=>{window.removeEventListener("focus",X),document.removeEventListener("visibilitychange",X),window.clearInterval(ve)}},[m,C]),o.useEffect(()=>{let X=!1;return Q.getRecipients().then(ve=>{if(X)return;const ue=new Map;for(const ke of ve.recipients)ke.name&&ue.set(ke.id,ke.name);c(ue)}).catch(ve=>{X||n(je(t,ve,"recipientsLoadFailed"),"error")}),()=>{X=!0}},[t,n]);const O=o.useMemo(()=>Gu(i.filter(X=>Wu(X,f,S)),N,s),[i,f,S,N,s]),J=`${f}|${N}|${S.enabled}|${S.chatScope}|${S.senders}`,{page:Y,pageCount:L,pageItems:v,setPage:T,total:te}=An(O,20,J),oe=()=>{k(""),b(ra)},ye=y?i.find(X=>X.id===y.id)??y:null,fe=()=>{if(i.length>=gt.rules){n(t("rulesLimit"),"warning");return}_(null),j(!0)},we=async(X,ve)=>{se.current+=1;const ue=X.enabled,ke=($.current.get(X.id)??0)+1;$.current.set(X.id,ke),M.current.add(X.id),l(Me=>Me.map(Te=>Te.id===X.id?{...Te,enabled:ve}:Te));try{const Me=await Q.updateAutoDeleteRule(X.id,{enabled:ve});if($.current.get(X.id)!==ke)return;l(Te=>Te.map(ae=>ae.id===X.id?Me.rule:ae))}catch(Me){$.current.get(X.id)===ke&&(l(Te=>Te.map(ae=>ae.id===X.id?{...ae,enabled:ue}:ae)),n(je(t,Me,"toggleFailed"),"error"))}finally{se.current+=1,$.current.get(X.id)===ke&&M.current.delete(X.id)}},Le=async X=>{se.current+=1;try{const ve=await Q.resetAutoDeleteRule(X.id);l(ue=>ue.map(ke=>ke.id===X.id?ve.rule:ke)),n(t("counterReset"),"success")}catch(ve){n(je(t,ve,"counterResetError"),"error")}finally{se.current+=1}},ee=async()=>{if(A){se.current+=1,F(!0);try{await Q.deleteAutoDeleteRule(A.id),l(X=>X.filter(ve=>ve.id!==A.id)),E===String(A.id)&&P(""),n(t("ruleDeleted"),"success"),D(null)}catch(X){n(je(t,X,"ruleDeleteError"),"error")}finally{se.current+=1,F(!1)}}},le=X=>X.chatScope==="groups"?t("chatsGroups"):X.chatScope==="private"?t("chatsPrivate"):t("chatsAll"),Se=X=>X.senders.mode==="everyone"?t("sendersEveryone"):X.senders.list.length===1?t("oneContact"):de(t("sendersCount"),{n:X.senders.list.length});return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Kt,{icon:e.jsx(Cs,{size:24}),title:t("autoDelete"),description:t("autoDeleteSubtitle"),actions:i.length>0||r==="copies"?e.jsx(U,{variant:"primary",icon:e.jsx(_t,{size:16}),onClick:fe,children:t("newRule")}):void 0}),e.jsx(ls,{"aria-label":t("autoDelete"),className:"overflow-x-auto no-scrollbar",value:r,onChange:a,options:[{value:"rules",label:t("rulesTab")},{value:"copies",label:t("copiesTab")}]}),r==="rules"&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!m&&!p&&i.length>0&&e.jsxs(It,{children:[e.jsx(be,{type:"search",name:"q",autoComplete:"off",value:f,onChange:X=>k(X.target.value),placeholder:t("searchRules"),"aria-label":t("searchRules"),className:"min-w-48 flex-1"}),e.jsx(Rn,{label:t("sort"),value:N,onChange:w,options:[{value:"newest",label:t("sortNewest")},{value:"name",label:t("sortByName")},{value:"deleted",label:t("sortMostDeleted")},{value:"last",label:t("sortLastDeleted")}]}),e.jsxs(zt,{label:t("filter"),resetLabel:t("reset"),activeCount:Ju(S),onReset:()=>b(ra),children:[e.jsx(st,{label:t("filterStatus"),name:"ad-status",value:S.enabled,onChange:X=>b(ve=>({...ve,enabled:X})),options:[{value:"any",label:t("statusAny")},{value:"on",label:t("statusEnabled")},{value:"off",label:t("statusDisabled")}]}),e.jsx(st,{label:t("filterChat"),name:"ad-scope",value:S.chatScope,onChange:X=>b(ve=>({...ve,chatScope:X})),options:[{value:"any",label:t("statusAny")},{value:"all",label:t("chatsAll")},{value:"groups",label:t("chatsGroups")},{value:"private",label:t("chatsPrivate")}]}),e.jsx(st,{label:t("filterSender"),name:"ad-senders",value:S.senders,onChange:X=>b(ve=>({...ve,senders:X})),options:[{value:"any",label:t("statusAny")},{value:"everyone",label:t("sendersEveryone")},{value:"selected",label:t("sendersSelected")}]})]})]}),m&&e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2","aria-busy":"true",children:["s1","s2","s3","s4"].map(X=>e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx(Ve,{className:"h-5 w-40"}),e.jsx(Ve,{className:"h-6 w-full"}),e.jsx(Ve,{className:"h-8 w-24"})]},X))}),!m&&p&&i.length===0&&e.jsx(Pe,{kind:"error",icon:e.jsx(Cs,{size:28}),description:p,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>x(X=>X+1),children:t("retryLoad")})}),!m&&!p&&i.length===0&&e.jsx(Pe,{kind:"empty",icon:e.jsx(Cs,{size:28}),title:t("noRulesTitle"),description:t("noRulesBody"),action:e.jsx(U,{variant:"primary",icon:e.jsx(_t,{size:16}),onClick:fe,children:t("newRule")})}),!m&&!p&&i.length>0&&O.length===0&&e.jsx(Pe,{kind:"no-results",action:e.jsx(U,{variant:"secondary",onClick:oe,children:t("clearFilters")})}),!m&&!p&&O.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:v.map(X=>{const ve=Nn(X),ue=Math.max(0,X.keywords.length-ui);return e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("h3",{dir:"auto",className:"min-w-0 flex-1 truncate text-sm font-bold",children:ve||"—"}),e.jsx(Je,{checked:X.enabled,"aria-label":t("ruleEnabled"),onChange:ke=>void we(X,ke)}),e.jsxs(mt,{label:t("more"),children:[e.jsx(_e,{icon:e.jsx(as,{size:16}),onSelect:()=>{_(X),j(!0)},children:t("edit")}),e.jsx(_e,{icon:e.jsx(ft,{size:16}),onSelect:()=>void Le(X),children:t("resetCounter")}),X.keepCopy&&e.jsx(_e,{icon:e.jsx(ts,{size:16}),onSelect:()=>{P(String(X.id)),a("copies")},children:t("viewCopies")}),e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>D(X),children:t("delete")})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[X.keywords.slice(0,ui).map(ke=>e.jsx(Ks,{children:ke},ke)),ue>0&&e.jsx(Ce,{children:de(t("moreKeywords"),{n:ue})})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(Ce,{children:t(xm[X.match])}),e.jsx(Ce,{children:le(X)}),e.jsx(Ce,{children:Se(X)})]}),e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-2xl font-bold tabular-nums text-text-main",children:V.format(X.deletedCount)}),e.jsx("span",{className:"text-xs text-muted",children:t("deletedLabel")}),e.jsx("span",{className:"ms-auto text-xs text-muted",children:X.lastDeletedAt?e.jsxs(e.Fragment,{children:[t("lastDeleted")," ",e.jsx(jn,{value:X.lastDeletedAt})]}):t("neverDeleted")})]})]},X.id)})}),e.jsx(Ht,{page:Y,pageCount:L,total:te,onPageChange:T})]})]}),r==="copies"&&e.jsx(Yu,{rules:i,names:d,ruleId:E,onRuleIdChange:P}),e.jsx(mm,{open:R,rule:ye,names:d,onClose:()=>j(!1),onSaved:X=>{se.current+=1,l(ve=>{const ue=ve.findIndex(Me=>Me.id===X.id);if(ue===-1)return[X,...ve];const ke=ve.slice();return ke[ue]=X,ke}),n(t("ruleSaved"),"success"),j(!1)}}),e.jsx(ut,{isOpen:A!==null,onClose:()=>D(null),onConfirm:()=>void ee(),title:t("deleteRuleTitle"),description:e.jsx("span",{dir:"auto",children:de(t("deleteRuleBody"),{name:A?Nn(A):""})}),confirmLabel:t("delete"),cancelLabel:t("cancel"),loading:I})]})};function As(t,s){return t instanceof TypeError||t instanceof et&&t.status===0?"networkError":s}const hm=/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;function Pt(t){return t.key??t.name}function jc(t){return`cmd-details-${Pt(t).replace(/[^a-zA-Z0-9_-]+/g,"-")}`}const fm={MEMBERS:"permMembers",ALL:"permMembers",ADMINS_ONLY:"permAdminsOnly",ADMINS_OWNER:"permAdminsOwner",OWNER_ONLY:"permOwnerOnly"},gm={all:"scopeAll",group:"scopeGroup",private:"scopePrivate"};function _n(){const{t,language:s}=me(),n=d=>{const c=fm[d];return t(c||"commandPermissionUnknown")},r=d=>{const c=gm[d];return t(c||"commandScopeUnknown")},a=d=>bn(d.descriptions,s)||d.description||"",i=d=>bn(d.usages,s)||d.usage||"";return{t,language:s,permissionLabel:n,scopeLabel:r,describe:a,usageOf:i,usageLines:(d,c)=>i(d).split(`
440
+ `).map(m=>m.trim()).filter(Boolean).map(m=>`${c}${m}`)}}function Ir({alias:t,prefix:s,onRemove:n,removeLabel:r}){const{t:a,language:i}=me(),l=hm.test(t),d=l!==(i==="ar");return e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg border border-line bg-panel-raised px-2 py-0.5 text-[11px] text-muted",children:[e.jsx(ot,{className:"text-[11px]",children:`${s}${t}`}),d&&e.jsx("span",{className:"font-sans text-[9px] font-bold uppercase tracking-wide text-brand-cyan/80",children:l?"AR":"EN"}),n&&e.jsx(xe,{variant:"ghost",label:r??a("delete"),icon:e.jsx(yt,{size:14}),onMouseDown:c=>c.preventDefault(),onClick:n})]})}function bm({command:t,prefix:s,onClose:n,onSaved:r}){const{t:a}=me(),{toast:i}=qe(),[l,d]=o.useState([]),[c,m]=o.useState(""),[u,p]=o.useState(!1);o.useEffect(()=>{t&&(d(Array.isArray(t.aliases)?[...t.aliases]:[]),m(""),p(!1))},[t]);const h=()=>{const f=c.trim().replace(/^[!/#.?$]+/,"").toLowerCase();if(f){if(l.includes(f)){i(a("aliasAlreadyAdded"),"warning");return}d([...l,f]),m("")}},g=f=>{d(l.filter(k=>k!==f))},x=async()=>{if(t){p(!0);try{await Q.updateCommand(t.name,{aliases:l}),r(t,l),i(a("savedSuccessfully"),"success"),n()}catch(f){i(a(As(f,"commandUpdateFailed")),"error")}finally{p(!1)}}};return e.jsx(Ye,{isOpen:!!t,onClose:n,title:t?e.jsxs(e.Fragment,{children:[a("aliasesFor")," ",e.jsx(ot,{children:`${s}${t.name}`})]}):a("aliasesFor"),footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:n,children:a("cancel")}),e.jsx(U,{variant:"primary",onClick:x,loading:u,children:a(u?"saving":"save")})]}),children:e.jsxs("div",{className:"flex flex-col gap-4 py-1",children:[e.jsx("p",{className:"text-xs text-muted sm:text-sm",children:a("aliasesHelp")}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs font-bold text-muted",children:a("thAliases")}),e.jsx("div",{className:"flex min-h-[42px] flex-wrap items-center gap-2 rounded-xl border border-line bg-panel-raised p-2",children:l.length>0?l.map(f=>e.jsx(Ir,{alias:f,prefix:s,removeLabel:a("delete"),onRemove:()=>g(f)},f)):e.jsx("span",{className:"px-1 text-xs text-faint",children:a("noAliases")})})]}),e.jsx(re,{label:a("addAlias"),htmlFor:"new-alias-input",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(iu,{size:16,className:"pointer-events-none absolute start-3 top-3 text-muted"}),e.jsx(be,{id:"new-alias-input",type:"text",value:c,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),h())},placeholder:a("newAliasPlaceholder"),className:"ps-10"})]}),e.jsx(U,{variant:"secondary",icon:e.jsx(_t,{size:16}),onClick:h,className:"shrink-0",children:a("add")})]})})]})})}function wc({command:t,levels:s,actions:n}){const{t:r,permissionLabel:a}=_n(),i=We(t.permission,"commandUpdateFailed");return t.permissionLocked?e.jsxs(ml,{padded:!1,role:"group","aria-label":`${r("thRequiredRole")}: ${t.name}`,className:"flex min-h-11 items-center gap-2.5 px-3 py-3",children:[e.jsx(Sr,{size:16,className:"shrink-0 text-muted","aria-hidden":!0}),e.jsx("span",{className:"min-w-0 whitespace-normal break-words text-sm text-text-main",children:a(t.permission)})]}):e.jsx(Ge,{dirty:i.dirty,saving:i.status==="saving",justSaved:i.status==="saved",error:i.error,onSave:()=>i.save(l=>n.onSavePermission(t,l)),onRevert:i.revert,saveLabel:r("save"),savedLabel:r("saved"),children:e.jsx(Re,{"aria-label":`${r("thRequiredRole")}: ${t.name}`,value:i.value,onChange:l=>i.setValue(l.target.value),children:s.map(l=>e.jsx("option",{value:l,children:a(l)},l))})})}function zn({label:t,children:s}){return e.jsxs("section",{className:"flex min-w-0 flex-col gap-2.5",children:[e.jsx("p",{className:"text-xs font-bold text-muted",children:t}),s]})}function kc({command:t,prefix:s,levels:n,actions:r}){var p;const{t:a,describe:i,scopeLabel:l,permissionLabel:d,usageLines:c}=_n(),m=i(t),u=c(t,s);return e.jsxs("div",{className:"flex flex-col gap-5",children:[m&&e.jsx("p",{dir:"auto",className:"min-w-0 break-words text-sm leading-relaxed text-muted",children:m}),e.jsxs("div",{className:"grid grid-cols-1 gap-x-5 gap-y-5 sm:grid-cols-2",children:[e.jsx(zn,{label:a("thAliases"),children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[(p=t.aliases)!=null&&p.length?t.aliases.map(h=>e.jsx(Ir,{alias:h,prefix:s},h)):e.jsx("span",{className:"text-xs text-faint",children:a("noAliases")}),e.jsx(xe,{label:a("editAliases"),icon:e.jsx(Zd,{size:16}),onClick:()=>r.onEditAliases(t)})]})}),e.jsxs(zn,{label:a("thRequiredRole"),children:[e.jsx(wc,{command:t,levels:n,actions:r}),t.permissionLocked&&e.jsx("p",{className:"text-xs text-muted",children:a("permissionLockedReason")})]}),e.jsx(zn,{label:a("thScope"),children:e.jsx("div",{children:e.jsx(Ce,{tone:"info",children:l(t.chat)})})}),e.jsxs(zn,{label:a("thStatus"),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(Ce,{tone:t.enabled?"ok":"neutral",children:t.enabled?a("statusEnabled"):a("statusDisabled")}),t.overridden&&e.jsx(Ce,{tone:"info",children:a("overridden")})]}),e.jsxs("p",{className:"text-xs text-muted",children:[a("defaultLabel"),": ",d(t.defaultPermission)]})]})]}),u.length>0&&e.jsx(zn,{label:a("usage"),children:e.jsx("ul",{className:"m-0 flex list-none flex-col gap-2 p-0",children:u.map(h=>e.jsx("li",{children:e.jsxs(ml,{padded:!1,className:"flex min-h-11 items-center gap-2 px-3 py-2",children:[e.jsx(ot,{className:"min-w-0 flex-1 whitespace-pre-wrap break-words text-xs leading-relaxed text-muted",children:h}),e.jsx(xe,{label:a("copyCommand"),variant:"ghost",icon:e.jsx(Nr,{size:16}),onClick:()=>r.onCopy(h)})]})},h))})})]})}function ym({commands:t,prefix:s,levels:n,expanded:r,onToggleDetails:a,actions:i}){const{t:l}=me(),{describe:d,permissionLabel:c}=_n();return e.jsx("ul",{className:"divide-y divide-line/50",children:t.map(m=>{const u=Pt(m),p=r===u,h=jc(m),g=d(m),x=`${s}${m.name}`;return e.jsxs("li",{children:[e.jsxs("div",{className:"flex items-start gap-2 px-3 py-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx(ot,{copy:!0,copyLabel:l("copyCommand"),className:"text-sm font-bold text-brand-cyan",children:x}),g&&e.jsx(ze,{lines:2,className:"text-xs text-muted",children:g})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(Ce,{tone:"neutral",className:"min-w-0 max-w-full whitespace-normal break-words text-start",children:c(m.permission)}),e.jsx(Ce,{tone:m.enabled?"ok":"neutral",className:"whitespace-normal",children:m.enabled?l("statusEnabled"):l("statusDisabled")})]})]}),e.jsx(Je,{checked:m.enabled,"aria-label":`${l("thStatus")}: ${x}`,onChange:f=>i.onToggleEnabled(m,f)}),e.jsx(xe,{size:"md",variant:"ghost",label:l(p?"hideDetails":"details"),"aria-expanded":p,"aria-controls":h,icon:e.jsx(Dt,{size:18,className:Ue("transition-transform",p&&"rotate-180")}),onClick:()=>a(u)})]}),p&&e.jsx("div",{id:h,className:"border-t border-line/40 bg-panel-raised/40 px-4 py-4",children:e.jsx(kc,{command:m,prefix:s,levels:n,actions:i})})]},u)})})}const mi=2;function vm({command:t,prefix:s}){const n=t.aliases||[];if(n.length===0)return e.jsx("span",{className:"text-xs text-faint",children:"—"});const r=n.length-mi;return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[n.slice(0,mi).map(a=>e.jsx(Ir,{alias:a,prefix:s},a)),r>0&&e.jsxs(Ce,{tone:"neutral",children:["+",r]})]})}function jm({commands:t,prefix:s,levels:n,expanded:r,onToggleDetails:a,actions:i}){const{t:l}=me(),{describe:d,permissionLabel:c}=_n();return e.jsx("div",{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full table-fixed border-collapse text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-line bg-panel-raised text-xs font-bold uppercase tracking-wider text-muted",children:[e.jsx("th",{className:"w-[26%] px-3 py-3 text-start",children:l("thCommand")}),e.jsx("th",{className:"px-3 py-3 text-start",children:l("thDescription")}),e.jsx("th",{className:"hidden px-3 py-3 text-start lg:table-cell lg:w-[16%]",children:l("thAliases")}),e.jsx("th",{className:"hidden px-3 py-3 text-start sm:table-cell sm:w-[26%] md:table-cell",children:l("thRequiredRole")}),e.jsx("th",{className:"px-3 py-3 text-center",children:l("thStatus")}),e.jsx("th",{className:"w-14 px-3 py-3 text-end",children:e.jsx("span",{className:"sr-only",children:l("details")})})]})}),e.jsx("tbody",{className:"divide-y divide-line/40",children:t.map(m=>{const u=Pt(m),p=r===u,h=jc(m),g=`${s}${m.name}`;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"hover:bg-panel-hover/40",children:[e.jsx("td",{className:"min-w-0 px-3 py-2.5",children:e.jsx(ot,{copy:!0,copyLabel:l("copyCommand"),className:"font-bold text-brand-cyan",children:g})}),e.jsx("td",{className:"min-w-0 px-3 py-2.5",children:e.jsx(ze,{as:"p",lines:1,className:"text-xs text-text-main md:text-sm",children:d(m)})}),e.jsx("td",{className:"hidden min-w-0 px-3 py-2.5 lg:table-cell",children:e.jsx(vm,{command:m,prefix:s})}),e.jsx("td",{className:"min-w-0 px-3 py-2.5 whitespace-normal",children:e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[e.jsx(Ce,{tone:"neutral",className:"min-w-0 max-w-full whitespace-normal break-words text-start",children:c(m.permission)}),e.jsx(wc,{command:m,levels:n,actions:i})]})}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx(Ce,{tone:m.enabled?"ok":"neutral",className:"whitespace-normal text-center",children:m.enabled?l("statusEnabled"):l("statusDisabled")}),e.jsx(Je,{checked:m.enabled,"aria-label":`${l("thStatus")}: ${g}`,onChange:x=>i.onToggleEnabled(m,x)})]})}),e.jsx("td",{className:"px-3 py-2.5 text-end",children:e.jsx(xe,{size:"md",variant:"ghost",label:l(p?"hideDetails":"details"),"aria-expanded":p,"aria-controls":h,icon:e.jsx(Dt,{size:18,className:Ue("transition-transform",p&&"rotate-180")}),onClick:()=>a(u)})})]}),p&&e.jsx("tr",{className:"bg-panel-raised/40",children:e.jsx("td",{colSpan:6,className:"border-t border-line/40 px-3 py-4",children:e.jsx(kc,{command:m,prefix:s,levels:n,actions:i})})})]},u)})})]})})}const xi={status:"all",scope:"all",permission:"all"};function wm(t){let s=0;return t.status!=="all"&&(s+=1),t.scope!=="all"&&(s+=1),t.permission!=="all"&&(s+=1),s}function pi(t){return t?Object.values(t).filter(s=>typeof s=="string"&&s!==""):[]}function km(t,s,n){return!(s&&![t.name,...t.aliases||[],t.description,...pi(t.descriptions),t.usage,...pi(t.usages)].filter(Boolean).join(" ").toLowerCase().includes(s)||n.status==="on"&&!t.enabled||n.status==="off"&&t.enabled||n.scope==="allChats"&&t.chat!=="all"||n.scope==="groups"&&t.chat!=="group"||n.scope==="private"&&t.chat!=="private"||n.scope==="groupSub"&&t.category!=="group"||n.scope==="general"&&t.category==="group"||n.permission==="overridden"&&!t.overridden||n.permission==="locked"&&!t.permissionLocked||n.permission!=="all"&&n.permission!=="overridden"&&n.permission!=="locked"&&t.permission!==n.permission)}function Nm(t,s,n){const r=(i,l)=>n.compare(i.name,l.name),a=[...t];return s==="status"?a.sort((i,l)=>i.enabled===l.enabled?r(i,l):i.enabled?-1:1):a.sort(r),a}const Sm=["MEMBERS","ADMINS_ONLY","ADMINS_OWNER","OWNER_ONLY"],Cm=["s1","s2","s3","s4","s5"],Em=()=>{const{t,language:s}=me(),{toast:n}=qe(),{permissionLabel:r}=_n(),[a,i]=o.useState([]),[l,d]=o.useState(Sm),[c,m]=o.useState("!"),[u,p]=o.useState(!1),[h,g]=o.useState("!"),[x,f]=o.useState(""),[k,N]=o.useState(xi),[w,S]=o.useState("name"),[b,R]=o.useState(!0),[j,y]=o.useState(null),[_,A]=o.useState(null),[D,I]=o.useState(null),F=o.useCallback(async()=>{R(!0);try{const L=await Q.getCommands();L!=null&&L.commands&&i(L.commands),L!=null&&L.prefix&&(m(L.prefix),g(L.prefix)),Array.isArray(L==null?void 0:L.levels)&&L.levels.length&&d(L.levels),y(null)}catch(L){const v=t(As(L,"loadError"));y(v),n(v,"error")}finally{R(!1)}},[t,n]);o.useEffect(()=>{F()},[F]);const E=async()=>{const L=h.trim();if(!L||L.length>3){n(t("prefixValidation"),"error");return}try{await Q.updatePrefix(L),m(L),p(!1),n(`${t("prefixUpdated")} (${L})`,"success")}catch(v){n(t(As(v,"commandUpdateFailed")),"error")}},P=async(L,v)=>{i(T=>T.map(te=>Pt(te)===Pt(L)?{...te,enabled:v,overridden:!0}:te));try{await Q.updateCommand(L.name,{enabled:v}),n(t(v?"commandEnabled":"commandDisabled").replace("{name}",L.name),"success")}catch(T){n(t(As(T,"commandUpdateFailed")),"error"),F()}},M=async(L,v)=>{await Q.updateCommand(L.name,{permission:v}),i(T=>T.map(te=>Pt(te)===Pt(L)?{...te,permission:v,overridden:!0}:te))},$=async L=>{try{await navigator.clipboard.writeText(L),n(t("copied"),"success")}catch{n(t("copyFailed"),"error")}},G=L=>{A(v=>v===L?null:L)},ne=(L,v)=>{i(T=>T.map(te=>Pt(te)===Pt(L)?{...te,aliases:v}:te))},se=()=>{f(""),N(xi)},V=o.useMemo(()=>new Intl.Collator(At(s,{ar:"ar",en:"en"})),[s]),q=x.trim().toLowerCase(),C=o.useMemo(()=>Nm(a.filter(L=>km(L,q,k)),w,V),[a,q,k,w,V]),O=wm(k),J=q.length>0||O>0,Y={onToggleEnabled:(L,v)=>void P(L,v),onEditAliases:L=>I(L),onSavePermission:M,onCopy:L=>void $(L)};return e.jsxs("div",{className:"flex flex-col gap-5 sm:gap-6",children:[e.jsx(Kt,{icon:e.jsx(en,{size:20}),title:t("commands"),description:t("commandsSub"),actions:e.jsxs("div",{className:"inline-flex flex-wrap items-center gap-2 rounded-xl border border-line bg-panel-raised px-3 py-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-muted",children:[t("activePrefix"),":"]}),u?e.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[e.jsx(be,{type:"text",technical:!0,maxLength:3,value:h,onChange:L=>g(L.target.value),className:"w-14 text-center font-mono",onKeyDown:L=>{L.key==="Enter"&&E(),L.key==="Escape"&&p(!1)}}),e.jsx(U,{variant:"primary",size:"sm",onClick:E,children:t("save")}),e.jsx(U,{variant:"secondary",size:"sm",onClick:()=>p(!1),children:t("cancel")})]}):e.jsx(U,{variant:"ghost",size:"sm",title:t("editPrefixHint"),onClick:()=>{g(c),p(!0)},children:e.jsx(ot,{children:c})})]})}),e.jsx(sc,{tab:"messages",title:t("plusRowCommandsTitle"),benefit:t("plusRowCommandsBenefit")}),e.jsxs("div",{className:"flex flex-col gap-3","data-tour":"commands-list",children:[e.jsxs(It,{children:[e.jsxs("div",{className:"relative min-w-48 flex-1",children:[e.jsx(Er,{size:18,className:"pointer-events-none absolute start-3.5 top-3 text-muted"}),e.jsx(be,{type:"search",value:x,onChange:L=>f(L.target.value),placeholder:t("searchPlaceholder"),"aria-label":t("searchPlaceholder"),className:"ps-10"})]}),e.jsx(Rn,{label:t("sort"),value:w,onChange:S,options:[{value:"name",label:t("sortByName")},{value:"status",label:t("sortStatus")}]}),e.jsxs(zt,{label:t("filter"),resetLabel:t("clearFilters"),activeCount:O,onReset:se,children:[e.jsx(st,{label:t("filterStatus"),name:"cmd-status",value:k.status,onChange:L=>N(v=>({...v,status:L})),options:[{value:"all",label:t("statusAny")},{value:"on",label:t("statusEnabled")},{value:"off",label:t("statusDisabled")}]}),e.jsx(st,{label:t("filterScope"),name:"cmd-scope",value:k.scope,onChange:L=>N(v=>({...v,scope:L})),options:[{value:"all",label:t("statusAny")},{value:"allChats",label:t("scopeAllChats")},{value:"groups",label:t("scopeGroupsOnly")},{value:"private",label:t("scopePrivateOnly")},{value:"groupSub",label:t("scopeGroupSub")},{value:"general",label:t("scopeGeneral")}]}),e.jsx(st,{label:t("filterPermission"),name:"cmd-permission",value:k.permission,onChange:L=>N(v=>({...v,permission:L})),options:[{value:"all",label:t("statusAny")},...l.map(L=>({value:L,label:r(L)})),{value:"overridden",label:t("overriddenOnly")},{value:"locked",label:t("lockedOnly")}]})]})]}),!b&&!j&&e.jsx("p",{"aria-live":"polite",className:"text-xs text-muted",children:de(t("resultCountOf"),{n:C.length,total:a.length})})]}),b?e.jsx(he,{padded:!1,className:"overflow-hidden",children:e.jsx("div",{className:"divide-y divide-line/40","aria-busy":"true",children:Cm.map(L=>e.jsxs("div",{className:"flex min-h-12 items-center gap-3 px-4 py-2.5",children:[e.jsx(Ve,{className:"h-4 w-28"}),e.jsx(Ve,{className:"ms-auto h-4 w-14"}),e.jsx(Ve,{className:"h-8 w-10"})]},L))})}):j&&a.length===0?e.jsx(Pe,{kind:"error",description:j,action:e.jsx(U,{variant:"primary",onClick:()=>void F(),children:t("retryLoad")})}):a.length===0?e.jsx(Pe,{kind:"empty"}):C.length===0?e.jsx(Pe,{kind:"no-results",description:t("noMatchingCommands"),action:J?e.jsx(U,{variant:"secondary",onClick:se,children:t("clearFilters")}):void 0}):e.jsxs(he,{padded:!1,className:"overflow-hidden",children:[e.jsx("div",{className:"md:hidden",children:e.jsx(ym,{commands:C,prefix:c,levels:l,expanded:_,onToggleDetails:G,actions:Y})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(jm,{commands:C,prefix:c,levels:l,expanded:_,onToggleDetails:G,actions:Y})})]}),e.jsx(bm,{command:D,prefix:c,onClose:()=>I(null),onSaved:ne})]})};var rn={},oa,hi;function Am(){return hi||(hi=1,oa=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),oa}var ca={},Ut={},fi;function nn(){if(fi)return Ut;fi=1;let t;const s=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ut.getSymbolSize=function(r){if(!r)throw new Error('"version" cannot be null or undefined');if(r<1||r>40)throw new Error('"version" should be in range from 1 to 40');return r*4+17},Ut.getSymbolTotalCodewords=function(r){return s[r]},Ut.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},Ut.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},Ut.isKanjiModeEnabled=function(){return typeof t<"u"},Ut.toSJIS=function(r){return t(r)},Ut}var da={},gi;function zr(){return gi||(gi=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function s(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,a){if(t.isValid(r))return r;try{return s(r)}catch{return a}}})(da)),da}var ua,bi;function Rm(){if(bi)return ua;bi=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(s){const n=Math.floor(s/8);return(this.buffer[n]>>>7-s%8&1)===1},put:function(s,n){for(let r=0;r<n;r++)this.putBit((s>>>n-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(s){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),s&&(this.buffer[n]|=128>>>this.length%8),this.length++}},ua=t,ua}var ma,yi;function _m(){if(yi)return ma;yi=1;function t(s){if(!s||s<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=s,this.data=new Uint8Array(s*s),this.reservedBit=new Uint8Array(s*s)}return t.prototype.set=function(s,n,r,a){const i=s*this.size+n;this.data[i]=r,a&&(this.reservedBit[i]=!0)},t.prototype.get=function(s,n){return this.data[s*this.size+n]},t.prototype.xor=function(s,n,r){this.data[s*this.size+n]^=r},t.prototype.isReserved=function(s,n){return this.reservedBit[s*this.size+n]},ma=t,ma}var xa={},vi;function Lm(){return vi||(vi=1,(function(t){const s=nn().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const a=Math.floor(r/7)+2,i=s(r),l=i===145?26:Math.ceil((i-13)/(2*a-2))*2,d=[i-7];for(let c=1;c<a-1;c++)d[c]=d[c-1]-l;return d.push(6),d.reverse()},t.getPositions=function(r){const a=[],i=t.getRowColCoords(r),l=i.length;for(let d=0;d<l;d++)for(let c=0;c<l;c++)d===0&&c===0||d===0&&c===l-1||d===l-1&&c===0||a.push([i[d],i[c]]);return a}})(xa)),xa}var pa={},ji;function Mm(){if(ji)return pa;ji=1;const t=nn().getSymbolSize,s=7;return pa.getPositions=function(r){const a=t(r);return[[0,0],[a-s,0],[0,a-s]]},pa}var ha={},wi;function Tm(){return wi||(wi=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const s={N1:3,N2:3,N3:40,N4:10};t.isValid=function(a){return a!=null&&a!==""&&!isNaN(a)&&a>=0&&a<=7},t.from=function(a){return t.isValid(a)?parseInt(a,10):void 0},t.getPenaltyN1=function(a){const i=a.size;let l=0,d=0,c=0,m=null,u=null;for(let p=0;p<i;p++){d=c=0,m=u=null;for(let h=0;h<i;h++){let g=a.get(p,h);g===m?d++:(d>=5&&(l+=s.N1+(d-5)),m=g,d=1),g=a.get(h,p),g===u?c++:(c>=5&&(l+=s.N1+(c-5)),u=g,c=1)}d>=5&&(l+=s.N1+(d-5)),c>=5&&(l+=s.N1+(c-5))}return l},t.getPenaltyN2=function(a){const i=a.size;let l=0;for(let d=0;d<i-1;d++)for(let c=0;c<i-1;c++){const m=a.get(d,c)+a.get(d,c+1)+a.get(d+1,c)+a.get(d+1,c+1);(m===4||m===0)&&l++}return l*s.N2},t.getPenaltyN3=function(a){const i=a.size;let l=0,d=0,c=0;for(let m=0;m<i;m++){d=c=0;for(let u=0;u<i;u++)d=d<<1&2047|a.get(m,u),u>=10&&(d===1488||d===93)&&l++,c=c<<1&2047|a.get(u,m),u>=10&&(c===1488||c===93)&&l++}return l*s.N3},t.getPenaltyN4=function(a){let i=0;const l=a.data.length;for(let c=0;c<l;c++)i+=a.data[c];return Math.abs(Math.ceil(i*100/l/5)-10)*s.N4};function n(r,a,i){switch(r){case t.Patterns.PATTERN000:return(a+i)%2===0;case t.Patterns.PATTERN001:return a%2===0;case t.Patterns.PATTERN010:return i%3===0;case t.Patterns.PATTERN011:return(a+i)%3===0;case t.Patterns.PATTERN100:return(Math.floor(a/2)+Math.floor(i/3))%2===0;case t.Patterns.PATTERN101:return a*i%2+a*i%3===0;case t.Patterns.PATTERN110:return(a*i%2+a*i%3)%2===0;case t.Patterns.PATTERN111:return(a*i%3+(a+i)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(a,i){const l=i.size;for(let d=0;d<l;d++)for(let c=0;c<l;c++)i.isReserved(c,d)||i.xor(c,d,n(a,c,d))},t.getBestMask=function(a,i){const l=Object.keys(t.Patterns).length;let d=0,c=1/0;for(let m=0;m<l;m++){i(m),t.applyMask(m,a);const u=t.getPenaltyN1(a)+t.getPenaltyN2(a)+t.getPenaltyN3(a)+t.getPenaltyN4(a);t.applyMask(m,a),u<c&&(c=u,d=m)}return d}})(ha)),ha}var gs={},ki;function Nc(){if(ki)return gs;ki=1;const t=zr(),s=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return gs.getBlocksCount=function(a,i){switch(i){case t.L:return s[(a-1)*4+0];case t.M:return s[(a-1)*4+1];case t.Q:return s[(a-1)*4+2];case t.H:return s[(a-1)*4+3];default:return}},gs.getTotalCodewordsCount=function(a,i){switch(i){case t.L:return n[(a-1)*4+0];case t.M:return n[(a-1)*4+1];case t.Q:return n[(a-1)*4+2];case t.H:return n[(a-1)*4+3];default:return}},gs}var fa={},On={},Ni;function Pm(){if(Ni)return On;Ni=1;const t=new Uint8Array(512),s=new Uint8Array(256);return(function(){let r=1;for(let a=0;a<255;a++)t[a]=r,s[r]=a,r<<=1,r&256&&(r^=285);for(let a=255;a<512;a++)t[a]=t[a-255]})(),On.log=function(r){if(r<1)throw new Error("log("+r+")");return s[r]},On.exp=function(r){return t[r]},On.mul=function(r,a){return r===0||a===0?0:t[s[r]+s[a]]},On}var Si;function Dm(){return Si||(Si=1,(function(t){const s=Pm();t.mul=function(r,a){const i=new Uint8Array(r.length+a.length-1);for(let l=0;l<r.length;l++)for(let d=0;d<a.length;d++)i[l+d]^=s.mul(r[l],a[d]);return i},t.mod=function(r,a){let i=new Uint8Array(r);for(;i.length-a.length>=0;){const l=i[0];for(let c=0;c<a.length;c++)i[c]^=s.mul(a[c],l);let d=0;for(;d<i.length&&i[d]===0;)d++;i=i.slice(d)}return i},t.generateECPolynomial=function(r){let a=new Uint8Array([1]);for(let i=0;i<r;i++)a=t.mul(a,new Uint8Array([1,s.exp(i)]));return a}})(fa)),fa}var ga,Ci;function Im(){if(Ci)return ga;Ci=1;const t=Dm();function s(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return s.prototype.initialize=function(r){this.degree=r,this.genPoly=t.generateECPolynomial(this.degree)},s.prototype.encode=function(r){if(!this.genPoly)throw new Error("Encoder not initialized");const a=new Uint8Array(r.length+this.degree);a.set(r);const i=t.mod(a,this.genPoly),l=this.degree-i.length;if(l>0){const d=new Uint8Array(this.degree);return d.set(i,l),d}return i},ga=s,ga}var ba={},ya={},va={},Ei;function Sc(){return Ei||(Ei=1,va.isValid=function(s){return!isNaN(s)&&s>=1&&s<=40}),va}var St={},Ai;function Cc(){if(Ai)return St;Ai=1;const t="[0-9]+",s="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const r="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
441
+ ]))+`;St.KANJI=new RegExp(n,"g"),St.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),St.BYTE=new RegExp(r,"g"),St.NUMERIC=new RegExp(t,"g"),St.ALPHANUMERIC=new RegExp(s,"g");const a=new RegExp("^"+n+"$"),i=new RegExp("^"+t+"$"),l=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return St.testKanji=function(c){return a.test(c)},St.testNumeric=function(c){return i.test(c)},St.testAlphanumeric=function(c){return l.test(c)},St}var Ri;function sn(){return Ri||(Ri=1,(function(t){const s=Sc(),n=Cc();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(i,l){if(!i.ccBits)throw new Error("Invalid mode: "+i);if(!s.isValid(l))throw new Error("Invalid version: "+l);return l>=1&&l<10?i.ccBits[0]:l<27?i.ccBits[1]:i.ccBits[2]},t.getBestModeForData=function(i){return n.testNumeric(i)?t.NUMERIC:n.testAlphanumeric(i)?t.ALPHANUMERIC:n.testKanji(i)?t.KANJI:t.BYTE},t.toString=function(i){if(i&&i.id)return i.id;throw new Error("Invalid mode")},t.isValid=function(i){return i&&i.bit&&i.ccBits};function r(a){if(typeof a!="string")throw new Error("Param is not a string");switch(a.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+a)}}t.from=function(i,l){if(t.isValid(i))return i;try{return r(i)}catch{return l}}})(ya)),ya}var _i;function zm(){return _i||(_i=1,(function(t){const s=nn(),n=Nc(),r=zr(),a=sn(),i=Sc(),l=7973,d=s.getBCHDigit(l);function c(h,g,x){for(let f=1;f<=40;f++)if(g<=t.getCapacity(f,x,h))return f}function m(h,g){return a.getCharCountIndicator(h,g)+4}function u(h,g){let x=0;return h.forEach(function(f){const k=m(f.mode,g);x+=k+f.getBitsLength()}),x}function p(h,g){for(let x=1;x<=40;x++)if(u(h,x)<=t.getCapacity(x,g,a.MIXED))return x}t.from=function(g,x){return i.isValid(g)?parseInt(g,10):x},t.getCapacity=function(g,x,f){if(!i.isValid(g))throw new Error("Invalid QR Code version");typeof f>"u"&&(f=a.BYTE);const k=s.getSymbolTotalCodewords(g),N=n.getTotalCodewordsCount(g,x),w=(k-N)*8;if(f===a.MIXED)return w;const S=w-m(f,g);switch(f){case a.NUMERIC:return Math.floor(S/10*3);case a.ALPHANUMERIC:return Math.floor(S/11*2);case a.KANJI:return Math.floor(S/13);case a.BYTE:default:return Math.floor(S/8)}},t.getBestVersionForData=function(g,x){let f;const k=r.from(x,r.M);if(Array.isArray(g)){if(g.length>1)return p(g,k);if(g.length===0)return 1;f=g[0]}else f=g;return c(f.mode,f.getLength(),k)},t.getEncodedBits=function(g){if(!i.isValid(g)||g<7)throw new Error("Invalid QR Code version");let x=g<<12;for(;s.getBCHDigit(x)-d>=0;)x^=l<<s.getBCHDigit(x)-d;return g<<12|x}})(ba)),ba}var ja={},Li;function Om(){if(Li)return ja;Li=1;const t=nn(),s=1335,n=21522,r=t.getBCHDigit(s);return ja.getEncodedBits=function(i,l){const d=i.bit<<3|l;let c=d<<10;for(;t.getBCHDigit(c)-r>=0;)c^=s<<t.getBCHDigit(c)-r;return(d<<10|c)^n},ja}var wa={},ka,Mi;function Fm(){if(Mi)return ka;Mi=1;const t=sn();function s(n){this.mode=t.NUMERIC,this.data=n.toString()}return s.getBitsLength=function(r){return 10*Math.floor(r/3)+(r%3?r%3*3+1:0)},s.prototype.getLength=function(){return this.data.length},s.prototype.getBitsLength=function(){return s.getBitsLength(this.data.length)},s.prototype.write=function(r){let a,i,l;for(a=0;a+3<=this.data.length;a+=3)i=this.data.substr(a,3),l=parseInt(i,10),r.put(l,10);const d=this.data.length-a;d>0&&(i=this.data.substr(a),l=parseInt(i,10),r.put(l,d*3+1))},ka=s,ka}var Na,Ti;function Bm(){if(Ti)return Na;Ti=1;const t=sn(),s=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(r){this.mode=t.ALPHANUMERIC,this.data=r}return n.getBitsLength=function(a){return 11*Math.floor(a/2)+6*(a%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(a){let i;for(i=0;i+2<=this.data.length;i+=2){let l=s.indexOf(this.data[i])*45;l+=s.indexOf(this.data[i+1]),a.put(l,11)}this.data.length%2&&a.put(s.indexOf(this.data[i]),6)},Na=n,Na}var Sa,Pi;function Um(){if(Pi)return Sa;Pi=1;const t=sn();function s(n){this.mode=t.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return s.getBitsLength=function(r){return r*8},s.prototype.getLength=function(){return this.data.length},s.prototype.getBitsLength=function(){return s.getBitsLength(this.data.length)},s.prototype.write=function(n){for(let r=0,a=this.data.length;r<a;r++)n.put(this.data[r],8)},Sa=s,Sa}var Ca,Di;function $m(){if(Di)return Ca;Di=1;const t=sn(),s=nn();function n(r){this.mode=t.KANJI,this.data=r}return n.getBitsLength=function(a){return a*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(r){let a;for(a=0;a<this.data.length;a++){let i=s.toSJIS(this.data[a]);if(i>=33088&&i<=40956)i-=33088;else if(i>=57408&&i<=60351)i-=49472;else throw new Error("Invalid SJIS character: "+this.data[a]+`
442
+ Make sure your charset is UTF-8`);i=(i>>>8&255)*192+(i&255),r.put(i,13)}},Ca=n,Ca}var Ea={exports:{}},Ii;function Km(){return Ii||(Ii=1,(function(t){var s={single_source_shortest_paths:function(n,r,a){var i={},l={};l[r]=0;var d=s.PriorityQueue.make();d.push(r,0);for(var c,m,u,p,h,g,x,f,k;!d.empty();){c=d.pop(),m=c.value,p=c.cost,h=n[m]||{};for(u in h)h.hasOwnProperty(u)&&(g=h[u],x=p+g,f=l[u],k=typeof l[u]>"u",(k||f>x)&&(l[u]=x,d.push(u,x),i[u]=m))}if(typeof a<"u"&&typeof l[a]>"u"){var N=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(N)}return i},extract_shortest_path_from_predecessor_list:function(n,r){for(var a=[],i=r;i;)a.push(i),n[i],i=n[i];return a.reverse(),a},find_path:function(n,r,a){var i=s.single_source_shortest_paths(n,r,a);return s.extract_shortest_path_from_predecessor_list(i,a)},PriorityQueue:{make:function(n){var r=s.PriorityQueue,a={},i;n=n||{};for(i in r)r.hasOwnProperty(i)&&(a[i]=r[i]);return a.queue=[],a.sorter=n.sorter||r.default_sorter,a},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var a={value:n,cost:r};this.queue.push(a),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=s})(Ea)),Ea.exports}var zi;function Hm(){return zi||(zi=1,(function(t){const s=sn(),n=Fm(),r=Bm(),a=Um(),i=$m(),l=Cc(),d=nn(),c=Km();function m(N){return unescape(encodeURIComponent(N)).length}function u(N,w,S){const b=[];let R;for(;(R=N.exec(S))!==null;)b.push({data:R[0],index:R.index,mode:w,length:R[0].length});return b}function p(N){const w=u(l.NUMERIC,s.NUMERIC,N),S=u(l.ALPHANUMERIC,s.ALPHANUMERIC,N);let b,R;return d.isKanjiModeEnabled()?(b=u(l.BYTE,s.BYTE,N),R=u(l.KANJI,s.KANJI,N)):(b=u(l.BYTE_KANJI,s.BYTE,N),R=[]),w.concat(S,b,R).sort(function(y,_){return y.index-_.index}).map(function(y){return{data:y.data,mode:y.mode,length:y.length}})}function h(N,w){switch(w){case s.NUMERIC:return n.getBitsLength(N);case s.ALPHANUMERIC:return r.getBitsLength(N);case s.KANJI:return i.getBitsLength(N);case s.BYTE:return a.getBitsLength(N)}}function g(N){return N.reduce(function(w,S){const b=w.length-1>=0?w[w.length-1]:null;return b&&b.mode===S.mode?(w[w.length-1].data+=S.data,w):(w.push(S),w)},[])}function x(N){const w=[];for(let S=0;S<N.length;S++){const b=N[S];switch(b.mode){case s.NUMERIC:w.push([b,{data:b.data,mode:s.ALPHANUMERIC,length:b.length},{data:b.data,mode:s.BYTE,length:b.length}]);break;case s.ALPHANUMERIC:w.push([b,{data:b.data,mode:s.BYTE,length:b.length}]);break;case s.KANJI:w.push([b,{data:b.data,mode:s.BYTE,length:m(b.data)}]);break;case s.BYTE:w.push([{data:b.data,mode:s.BYTE,length:m(b.data)}])}}return w}function f(N,w){const S={},b={start:{}};let R=["start"];for(let j=0;j<N.length;j++){const y=N[j],_=[];for(let A=0;A<y.length;A++){const D=y[A],I=""+j+A;_.push(I),S[I]={node:D,lastCount:0},b[I]={};for(let F=0;F<R.length;F++){const E=R[F];S[E]&&S[E].node.mode===D.mode?(b[E][I]=h(S[E].lastCount+D.length,D.mode)-h(S[E].lastCount,D.mode),S[E].lastCount+=D.length):(S[E]&&(S[E].lastCount=D.length),b[E][I]=h(D.length,D.mode)+4+s.getCharCountIndicator(D.mode,w))}}R=_}for(let j=0;j<R.length;j++)b[R[j]].end=0;return{map:b,table:S}}function k(N,w){let S;const b=s.getBestModeForData(N);if(S=s.from(w,b),S!==s.BYTE&&S.bit<b.bit)throw new Error('"'+N+'" cannot be encoded with mode '+s.toString(S)+`.
443
+ Suggested mode is: `+s.toString(b));switch(S===s.KANJI&&!d.isKanjiModeEnabled()&&(S=s.BYTE),S){case s.NUMERIC:return new n(N);case s.ALPHANUMERIC:return new r(N);case s.KANJI:return new i(N);case s.BYTE:return new a(N)}}t.fromArray=function(w){return w.reduce(function(S,b){return typeof b=="string"?S.push(k(b,null)):b.data&&S.push(k(b.data,b.mode)),S},[])},t.fromString=function(w,S){const b=p(w,d.isKanjiModeEnabled()),R=x(b),j=f(R,S),y=c.find_path(j.map,"start","end"),_=[];for(let A=1;A<y.length-1;A++)_.push(j.table[y[A]].node);return t.fromArray(g(_))},t.rawSplit=function(w){return t.fromArray(p(w,d.isKanjiModeEnabled()))}})(wa)),wa}var Oi;function Vm(){if(Oi)return ca;Oi=1;const t=nn(),s=zr(),n=Rm(),r=_m(),a=Lm(),i=Mm(),l=Tm(),d=Nc(),c=Im(),m=zm(),u=Om(),p=sn(),h=Hm();function g(j,y){const _=j.size,A=i.getPositions(y);for(let D=0;D<A.length;D++){const I=A[D][0],F=A[D][1];for(let E=-1;E<=7;E++)if(!(I+E<=-1||_<=I+E))for(let P=-1;P<=7;P++)F+P<=-1||_<=F+P||(E>=0&&E<=6&&(P===0||P===6)||P>=0&&P<=6&&(E===0||E===6)||E>=2&&E<=4&&P>=2&&P<=4?j.set(I+E,F+P,!0,!0):j.set(I+E,F+P,!1,!0))}}function x(j){const y=j.size;for(let _=8;_<y-8;_++){const A=_%2===0;j.set(_,6,A,!0),j.set(6,_,A,!0)}}function f(j,y){const _=a.getPositions(y);for(let A=0;A<_.length;A++){const D=_[A][0],I=_[A][1];for(let F=-2;F<=2;F++)for(let E=-2;E<=2;E++)F===-2||F===2||E===-2||E===2||F===0&&E===0?j.set(D+F,I+E,!0,!0):j.set(D+F,I+E,!1,!0)}}function k(j,y){const _=j.size,A=m.getEncodedBits(y);let D,I,F;for(let E=0;E<18;E++)D=Math.floor(E/3),I=E%3+_-8-3,F=(A>>E&1)===1,j.set(D,I,F,!0),j.set(I,D,F,!0)}function N(j,y,_){const A=j.size,D=u.getEncodedBits(y,_);let I,F;for(I=0;I<15;I++)F=(D>>I&1)===1,I<6?j.set(I,8,F,!0):I<8?j.set(I+1,8,F,!0):j.set(A-15+I,8,F,!0),I<8?j.set(8,A-I-1,F,!0):I<9?j.set(8,15-I-1+1,F,!0):j.set(8,15-I-1,F,!0);j.set(A-8,8,1,!0)}function w(j,y){const _=j.size;let A=-1,D=_-1,I=7,F=0;for(let E=_-1;E>0;E-=2)for(E===6&&E--;;){for(let P=0;P<2;P++)if(!j.isReserved(D,E-P)){let M=!1;F<y.length&&(M=(y[F]>>>I&1)===1),j.set(D,E-P,M),I--,I===-1&&(F++,I=7)}if(D+=A,D<0||_<=D){D-=A,A=-A;break}}}function S(j,y,_){const A=new n;_.forEach(function(P){A.put(P.mode.bit,4),A.put(P.getLength(),p.getCharCountIndicator(P.mode,j)),P.write(A)});const D=t.getSymbolTotalCodewords(j),I=d.getTotalCodewordsCount(j,y),F=(D-I)*8;for(A.getLengthInBits()+4<=F&&A.put(0,4);A.getLengthInBits()%8!==0;)A.putBit(0);const E=(F-A.getLengthInBits())/8;for(let P=0;P<E;P++)A.put(P%2?17:236,8);return b(A,j,y)}function b(j,y,_){const A=t.getSymbolTotalCodewords(y),D=d.getTotalCodewordsCount(y,_),I=A-D,F=d.getBlocksCount(y,_),E=A%F,P=F-E,M=Math.floor(A/F),$=Math.floor(I/F),G=$+1,ne=M-$,se=new c(ne);let V=0;const q=new Array(F),C=new Array(F);let O=0;const J=new Uint8Array(j.buffer);for(let te=0;te<F;te++){const oe=te<P?$:G;q[te]=J.slice(V,V+oe),C[te]=se.encode(q[te]),V+=oe,O=Math.max(O,oe)}const Y=new Uint8Array(A);let L=0,v,T;for(v=0;v<O;v++)for(T=0;T<F;T++)v<q[T].length&&(Y[L++]=q[T][v]);for(v=0;v<ne;v++)for(T=0;T<F;T++)Y[L++]=C[T][v];return Y}function R(j,y,_,A){let D;if(Array.isArray(j))D=h.fromArray(j);else if(typeof j=="string"){let M=y;if(!M){const $=h.rawSplit(j);M=m.getBestVersionForData($,_)}D=h.fromString(j,M||40)}else throw new Error("Invalid data");const I=m.getBestVersionForData(D,_);if(!I)throw new Error("The amount of data is too big to be stored in a QR Code");if(!y)y=I;else if(y<I)throw new Error(`
444
+ The chosen QR Code version cannot contain this amount of data.
445
+ Minimum version required to store current data is: `+I+`.
446
+ `);const F=S(y,_,D),E=t.getSymbolSize(y),P=new r(E);return g(P,y),x(P),f(P,y),N(P,_,0),y>=7&&k(P,y),w(P,F),isNaN(A)&&(A=l.getBestMask(P,N.bind(null,P,_))),l.applyMask(A,P),N(P,_,A),{modules:P,version:y,errorCorrectionLevel:_,maskPattern:A,segments:D}}return ca.create=function(y,_){if(typeof y>"u"||y==="")throw new Error("No input text");let A=s.M,D,I;return typeof _<"u"&&(A=s.from(_.errorCorrectionLevel,s.M),D=m.from(_.version),I=l.from(_.maskPattern),_.toSJISFunc&&t.setToSJISFunction(_.toSJISFunc)),R(y,D,A,I)},ca}var Aa={},Ra={},Fi;function Ec(){return Fi||(Fi=1,(function(t){function s(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(i){return[i,i]}))),r.length===6&&r.push("F","F");const a=parseInt(r.join(""),16);return{r:a>>24&255,g:a>>16&255,b:a>>8&255,a:a&255,hex:"#"+r.slice(0,6).join("")}}t.getOptions=function(r){r||(r={}),r.color||(r.color={});const a=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,i=r.width&&r.width>=21?r.width:void 0,l=r.scale||4;return{width:i,scale:i?4:l,margin:a,color:{dark:s(r.color.dark||"#000000ff"),light:s(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},t.getScale=function(r,a){return a.width&&a.width>=r+a.margin*2?a.width/(r+a.margin*2):a.scale},t.getImageWidth=function(r,a){const i=t.getScale(r,a);return Math.floor((r+a.margin*2)*i)},t.qrToImageData=function(r,a,i){const l=a.modules.size,d=a.modules.data,c=t.getScale(l,i),m=Math.floor((l+i.margin*2)*c),u=i.margin*c,p=[i.color.light,i.color.dark];for(let h=0;h<m;h++)for(let g=0;g<m;g++){let x=(h*m+g)*4,f=i.color.light;if(h>=u&&g>=u&&h<m-u&&g<m-u){const k=Math.floor((h-u)/c),N=Math.floor((g-u)/c);f=p[d[k*l+N]?1:0]}r[x++]=f.r,r[x++]=f.g,r[x++]=f.b,r[x]=f.a}}})(Ra)),Ra}var Bi;function qm(){return Bi||(Bi=1,(function(t){const s=Ec();function n(a,i,l){a.clearRect(0,0,i.width,i.height),i.style||(i.style={}),i.height=l,i.width=l,i.style.height=l+"px",i.style.width=l+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(i,l,d){let c=d,m=l;typeof c>"u"&&(!l||!l.getContext)&&(c=l,l=void 0),l||(m=r()),c=s.getOptions(c);const u=s.getImageWidth(i.modules.size,c),p=m.getContext("2d"),h=p.createImageData(u,u);return s.qrToImageData(h.data,i,c),n(p,m,u),p.putImageData(h,0,0),m},t.renderToDataURL=function(i,l,d){let c=d;typeof c>"u"&&(!l||!l.getContext)&&(c=l,l=void 0),c||(c={});const m=t.render(i,l,c),u=c.type||"image/png",p=c.rendererOpts||{};return m.toDataURL(u,p.quality)}})(Aa)),Aa}var _a={},Ui;function Wm(){if(Ui)return _a;Ui=1;const t=Ec();function s(a,i){const l=a.a/255,d=i+'="'+a.hex+'"';return l<1?d+" "+i+'-opacity="'+l.toFixed(2).slice(1)+'"':d}function n(a,i,l){let d=a+i;return typeof l<"u"&&(d+=" "+l),d}function r(a,i,l){let d="",c=0,m=!1,u=0;for(let p=0;p<a.length;p++){const h=Math.floor(p%i),g=Math.floor(p/i);!h&&!m&&(m=!0),a[p]?(u++,p>0&&h>0&&a[p-1]||(d+=m?n("M",h+l,.5+g+l):n("m",c,0),c=0,m=!1),h+1<i&&a[p+1]||(d+=n("h",u),u=0)):c++}return d}return _a.render=function(i,l,d){const c=t.getOptions(l),m=i.modules.size,u=i.modules.data,p=m+c.margin*2,h=c.color.light.a?"<path "+s(c.color.light,"fill")+' d="M0 0h'+p+"v"+p+'H0z"/>':"",g="<path "+s(c.color.dark,"stroke")+' d="'+r(u,m,c.margin)+'"/>',x='viewBox="0 0 '+p+" "+p+'"',k='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+x+' shape-rendering="crispEdges">'+h+g+`</svg>
447
+ `;return typeof d=="function"&&d(null,k),k},_a}var $i;function Gm(){if($i)return rn;$i=1;const t=Am(),s=Vm(),n=qm(),r=Wm();function a(i,l,d,c,m){const u=[].slice.call(arguments,1),p=u.length,h=typeof u[p-1]=="function";if(!h&&!t())throw new Error("Callback required as last argument");if(h){if(p<2)throw new Error("Too few arguments provided");p===2?(m=d,d=l,l=c=void 0):p===3&&(l.getContext&&typeof m>"u"?(m=c,c=void 0):(m=c,c=d,d=l,l=void 0))}else{if(p<1)throw new Error("Too few arguments provided");return p===1?(d=l,l=c=void 0):p===2&&!l.getContext&&(c=d,d=l,l=void 0),new Promise(function(g,x){try{const f=s.create(d,c);g(i(f,l,c))}catch(f){x(f)}})}try{const g=s.create(d,c);m(null,i(g,l,c))}catch(g){m(g)}}return rn.create=s.create,rn.toCanvas=a.bind(null,n.render),rn.toDataURL=a.bind(null,n.renderToDataURL),rn.toString=a.bind(null,function(i,l,d){return r.render(i,d)}),rn}var Ac=Gm();const La=xd(Ac),Ki={manage:e.jsx(nu,{size:16}),connect:e.jsx(go,{size:16}),reconnect:e.jsx(it,{size:16})};function Rc({status:t,variant:s="full",onManage:n,onStart:r,starting:a=!1}){var F,E,P;const{t:i}=me(),l=fc(t),d=(t==null?void 0:t.state)==="connected"&&t.connected!==!1,c=d?`${((F=t==null?void 0:t.user)==null?void 0:F.id)||"connected"}|${(t==null?void 0:t.since)??""}`:"",[m,u]=o.useState(null),[p,h]=o.useState(null),g=!!((E=t==null?void 0:t.user)!=null&&E.id&&p===t.user.id);o.useEffect(()=>{(t==null?void 0:t.state)!=="connected"&&h(null)},[t==null?void 0:t.state]);const[x,f]=o.useState(!1),[k,N]=o.useState(!1),w=o.useRef(0),S=o.useRef(!1),b=o.useRef(null),R=d&&(m==null?void 0:m.identity)===c?m.profile:null,j=o.useCallback(async M=>{if(!c||S.current)return;const $=++w.current;S.current=!0,f(!0);try{const G=M?await Q.post("/account/profile/refresh",{}):await Q.get("/account/profile");if($!==w.current)return;u({identity:c,profile:G.profile});const ne=Math.max(0,Math.min(1e4,G.profile.refreshAfterMs||0));b.current&&clearTimeout(b.current),N(ne>0),ne&&(b.current=setTimeout(()=>N(!1),ne))}catch{}finally{$===w.current&&(S.current=!1,f(!1))}},[c]);o.useEffect(()=>(w.current+=1,S.current=!1,u(null),f(!1),N(!1),b.current&&clearTimeout(b.current),c&&j(!1),()=>{w.current+=1,S.current=!1,b.current&&clearTimeout(b.current)}),[c,j]);const y=l.showProfile&&(R!=null&&R.connected)?R:null,_=l.showProfile&&!y&&!x,A=l.attempt!==null&&l.maxAttempts!==null?de(i("accountCardAttempt"),{attempt:l.attempt,max:l.maxAttempts}):null,D=l.loading?null:e.jsx(xn,{tone:l.tone,dot:!0,pulse:l.pulsing,children:i(l.labelKey)});if(s==="compact"){const M=i("accountCardTitle"),$=!!(t&&["idle","disconnected","retry_exhausted","error"].includes(t.state)),G=!!((P=t==null?void 0:t.user)!=null&&P.id||t!=null&&t.linked),ne=!!(r&&$&&G);return e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[l.loading?e.jsx(Ve,{className:"size-12 shrink-0 rounded-xl"}):e.jsx(er,{src:(y==null?void 0:y.photoUrl)||void 0,name:(y==null?void 0:y.name)||"",icon:e.jsx(hn,{size:22})},(y==null?void 0:y.photoUrl)||c||"none"),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[l.loading?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"h-4 w-32 max-w-full"}),e.jsx(Ve,{className:"h-3 w-24 max-w-full"})]}):e.jsxs(e.Fragment,{children:[y!=null&&y.name?e.jsx(ze,{lines:2,className:"text-sm font-bold text-text-main",children:y.name}):e.jsx("p",{className:"text-sm font-bold text-text-main",children:M}),y!=null&&y.phone?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ze,{as:"bdi",dir:"ltr",className:"text-xs text-muted",children:g?y.phone:"••• ••• ••••"}),e.jsx(xe,{label:i(g?"hideNumber":"showNumber"),pressed:g,variant:"ghost",icon:g?e.jsx(kr,{size:16}):e.jsx(ts,{size:16}),onClick:()=>{var se;return h(g?null:((se=t==null?void 0:t.user)==null?void 0:se.id)||null)}})]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[D,A&&e.jsx("span",{className:"text-xs text-muted",children:A}),x&&e.jsx(nt,{label:i("loading")})]})]})]}),_?e.jsx("p",{role:"status",className:"text-xs text-muted",children:i("accountCardProfileUnavailable")}):null,n||ne?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[ne?e.jsx(U,{variant:"primary",icon:e.jsx(go,{size:16}),onClick:r,loading:a,className:"w-full sm:w-auto",children:i("start")}):null,n?e.jsx(U,{variant:l.tone==="ok"||ne?"secondary":"primary",icon:ne?Ki.manage:Ki[l.action],onClick:n,className:"w-full sm:w-auto sm:self-start",children:i("accountCardManageSession")}):null]}):null]})}const I=[["accountProfileName",y==null?void 0:y.name],["accountProfilePhone",y==null?void 0:y.phone],["accountProfileAbout",y==null?void 0:y.about]];return e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{title:i("accountCardTitle"),actions:e.jsx(xe,{label:i(k?"accountProfileRefreshSoon":"accountProfileRefresh"),icon:e.jsx(it,{size:18}),disabled:!d||x||k,onClick:()=>void j(!0)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(er,{src:(y==null?void 0:y.photoUrl)||void 0,name:(y==null?void 0:y.name)||i("accountCardTitle")},(y==null?void 0:y.photoUrl)||c||"none"),D,A&&e.jsx("span",{className:"text-xs text-muted",children:A}),x&&e.jsx(nt,{label:i("loading")})]}),d?e.jsxs(e.Fragment,{children:[_&&e.jsx("p",{role:"status",className:"text-sm text-muted",children:i("accountProfileUnavailable")}),e.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:I.map(([M,$])=>e.jsxs("div",{className:`flex min-w-0 flex-col gap-1 ${M==="accountProfileAbout"?"sm:col-span-2":""}`,children:[e.jsx("dt",{className:"text-xs text-muted",children:i(M)}),e.jsx("dd",{className:"min-w-0",children:e.jsx(ze,{as:"bdi",dir:M==="accountProfilePhone"&&$?"ltr":"auto",children:$||i("accountProfileMissing")})})]},M))})]}):e.jsx("p",{className:"text-sm text-muted",children:i("accountProfileDisconnected")})]})}const Jm=/https?:\/\/[A-Za-z0-9._~:/?#@!$&'*+,;=%()[\]-]+/y,Ym=/[.,;:)"'\u2019\u201d\u00bb\u203a\u00ab]+$/,Qm=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/y,Xm=/\d{4}-\d{2}-\d{2}(?:\.\d+)?/y,Zm=/\d+\.\d+\.\d+(?:\.\d+)*(?:\+[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)*)?/y,ex=/[A-Za-z0-9._%+-]/;function bs(t,s,n){t.lastIndex=n;const r=t.exec(s);return r?r[0]:""}function tx(t,s){const n=bs(Jm,t,s);if(n){const a=n.replace(Ym,"");if(a)return a}const r=s>0?t[s-1]:"";if(!ex.test(r)){const a=bs(Qm,t,s),i=t[s+a.length]??"";if(a&&!/[A-Za-z0-9]/.test(i))return a}if(!/\d/.test(r)){const a=bs(Xm,t,s),i=t[s+a.length]??"";if(a&&!/\d/.test(i))return a}if(!/[\d.]/.test(r)){const a=bs(Zm,t,s),i=t[s+a.length]??"";if(a&&!/\d/.test(i))return a}return""}function Ma(t){const s=[];let n=0,r=0;for(;n<t.length;){const a=tx(t,n);if(!a){n+=1;continue}n>r&&s.push({text:t.slice(r,n),ltr:!1}),s.push({text:a,ltr:!0}),n+=a.length,r=n}return r<t.length&&s.push({text:t.slice(r),ltr:!1}),s}const Ta=/\{([A-Za-z0-9_]+)\}/g;function _c(t,s){const n=[],r=String(t);let a=0;Ta.lastIndex=0;let i=Ta.exec(r);for(;i;){i.index>a&&n.push({text:r.slice(a,i.index),ltr:!1});const l=i[1];Object.hasOwn(s,l)?n.push({text:String(s[l]),ltr:!0}):n.push({text:i[0],ltr:!1}),a=i.index+i[0].length,i=Ta.exec(r)}return a<r.length&&n.push({text:r.slice(a),ltr:!1}),n}function Lc(t,s){switch(t){case"terms_changed":return s("legalReasonChanged");case"app_updated":return s("legalReasonUpdated");case"consent_unreadable":return s("legalReasonUnreadable");default:return s("legalReasonNotAccepted")}}function Gn(t){return t.map((s,n)=>s.ltr?e.jsx("bdi",{dir:"ltr",children:s.text},n):e.jsx(o.Fragment,{children:s.text},n))}function Us({part:t,dir:s}){return e.jsxs("section",{dir:s,className:"space-y-3",children:[e.jsx("h3",{className:"text-base font-bold text-text-main",children:Gn(Ma(t.title))}),t.sections.map((n,r)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-text-main",children:Gn(Ma(n.heading))}),n.paragraphs.map((a,i)=>e.jsx("p",{className:"text-sm leading-relaxed text-muted whitespace-pre-wrap",children:Gn(Ma(a))},i))]},r))]})}function nx({isOpen:t,onClose:s,onAccepted:n}){const{language:r,t:a}=me(),[i,l]=o.useState(null),[d,c]=o.useState(!1),[m,u]=o.useState(!1),[p,h]=o.useState(!1),[g,x]=o.useState(!1),[f,k]=o.useState(null),N=o.useRef(0),w=o.useRef(!1),S=o.useCallback(()=>{const j=++N.current;w.current||l(null),c(!1),x(!1),k(null),h(!0),Q.getLegalTerms(r).then(y=>{j===N.current&&!w.current&&l(y)}).catch(()=>{j===N.current&&!w.current&&k(a("legalLoadError"))}).finally(()=>{j===N.current&&h(!1)})},[r,a]);o.useEffect(()=>{if(t)return S(),()=>{N.current++}},[t,S]);const b=async()=>{if(!(!i||!d||m)){N.current++,w.current=!0,u(!0),h(!1),k(null);try{const j=await Q.acceptLegalTerms({version:i.version,sha256:i.sha256,locale:i.locale});n(j.session),s()}catch(j){j instanceof et&&j.status===409&&j.code==="TERMS_CHANGED"?(l(j.data),c(!1),x(!0)):k(a("legalAcceptError"))}finally{N.current++,w.current=!1,h(!1),u(!1)}}},R=(i==null?void 0:i.locale)==="ar"?"rtl":"ltr";return e.jsxs(Ye,{isOpen:t,onClose:s,title:a("legalConsentTitle"),maxWidth:"44rem",footer:e.jsxs("div",{className:"flex w-full flex-col items-end gap-2",children:[e.jsx(U,{variant:"primary",onClick:b,disabled:!i||!d||m,loading:m,children:a("legalAccept")}),f&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:f})]}),children:[p?e.jsx(nt,{label:a("loading")}):null,!p&&!i&&f&&e.jsx(U,{variant:"secondary",icon:e.jsx(it,{size:16}),onClick:S,children:a("retry")}),!p&&i&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-text-main",role:g?"alert":void 0,children:g?a("legalChangedReview"):Lc(i.consent.reason,a)}),i.locale!==r&&e.jsx("p",{className:"text-sm text-muted",children:a("legalEnglishFallback")}),e.jsx("p",{className:"text-xs text-muted",children:Gn(_c(a("legalVersionEffective"),{version:i.version,date:i.effective}))}),e.jsxs("div",{lang:i.locale,dir:R,className:"max-h-[50dvh] space-y-6 overflow-y-auto rounded-xl border border-line bg-panel-raised p-4",children:[e.jsx(Us,{part:i.terms,dir:R}),e.jsx(Us,{part:i.privacy,dir:R})]}),e.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[["privacyPolicy","legalFullPrivacy"],["license","legalLicense"],["website","legalWebsite"]].map(([j,y])=>e.jsx("a",{href:i.links[j],target:"_blank",rel:"noopener noreferrer",className:"inline-flex min-h-10 items-center text-sm text-brand-blue underline",children:a(y)},j))}),e.jsx(ht,{label:a("legalReadAccept"),checked:d,onChange:j=>c(j.target.checked)})]})]})}function sx({isOpen:t,onClose:s}){const{language:n,t:r}=me(),[a,i]=o.useState(null),[l,d]=o.useState(!1),[c,m]=o.useState(null),u=o.useCallback(()=>{m(null),d(!0),Q.getLegalTerms(n).then(h=>i(h)).catch(()=>m(r("legalLoadError"))).finally(()=>d(!1))},[n,r]);o.useEffect(()=>{t&&u()},[t,u]);const p=(a==null?void 0:a.locale)==="ar"?"rtl":"ltr";return e.jsxs(Ye,{isOpen:t,onClose:s,title:r("legalConsentTitle"),maxWidth:"44rem",footer:e.jsx(U,{variant:"secondary",onClick:s,children:r("close")}),children:[l?e.jsx(nt,{label:r("loading")}):null,!l&&!a&&c&&e.jsx(U,{variant:"secondary",icon:e.jsx(it,{size:16}),onClick:u,children:r("retry")}),!l&&a&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted",children:Gn(_c(r("legalVersionEffective"),{version:a.version,date:a.effective}))}),e.jsxs("div",{lang:a.locale,dir:p,className:"max-h-[50dvh] space-y-6 overflow-y-auto rounded-xl border border-line bg-panel-raised p-4",children:[e.jsx(Us,{part:a.terms,dir:p}),e.jsx(Us,{part:a.privacy,dir:p})]}),e.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[["privacyPolicy","legalFullPrivacy"],["license","legalLicense"],["website","legalWebsite"]].map(([h,g])=>e.jsx("a",{href:a.links[h],target:"_blank",rel:"noopener noreferrer",className:"inline-flex min-h-10 items-center text-sm text-brand-blue underline",children:r(g)},h))})]})]})}function ax(){return typeof window<"u"&&!!window.LevixHost}const rx=({status:t,onRefresh:s,onStatusUpdate:n,onReviewTerms:r})=>{const{t:a}=me(),{toast:i}=qe(),[l,d]=o.useState(!1),[c,m]=o.useState(!1),[u,p]=o.useState(null),[h,g]=o.useState("pairing"),[x,f]=o.useState(""),[k,N]=o.useState(!1),w=(t==null?void 0:t.state)||"idle",S=w==="connected",b=w==="waiting_for_qr",R=w==="starting"||w==="linking",j=w==="reconnecting",y=w==="consent_required",_=w==="paused",A=w==="logged_out",D=S||R||b||j,I=!!(t!=null&&t.linked)&&!A,F=!I,E=w==="error"&&(t==null?void 0:t.reason)==="unlink_incomplete",P=!S&&!R&&!b&&!j&&!y&&F&&!E,M=!!(t!=null&&t.canUnlink),$=(t==null?void 0:t.isOnline)!==!1,G=a(_||w==="disconnected"||w==="retry_exhausted"?"connectionResumeSession":"connectionConnect");o.useEffect(()=>{if(t!=null&&t.qr){const L=Ac.toDataURL||(La==null?void 0:La.toDataURL);if(typeof L=="function"){const v=getComputedStyle(document.documentElement),T=document.documentElement.getAttribute("data-theme")==="light",te=(T?v.getPropertyValue("--text"):v.getPropertyValue("--bg")).trim(),oe=(T?v.getPropertyValue("--panel"):v.getPropertyValue("--text")).trim();L(t.qr,{width:280,margin:2,color:{dark:te,light:oe}}).then(ye=>p(ye)).catch(()=>p(null))}}else p(null)},[t==null?void 0:t.qr]),o.useEffect(()=>{if(b&&!(t!=null&&t.qr)&&!(t!=null&&t.pairingCode)){const L=setInterval(()=>{s==null||s()},1500);return()=>clearInterval(L)}},[b,t==null?void 0:t.qr,t==null?void 0:t.pairingCode,s]);const ne=async(L,v,T)=>{m(!0);try{const te=await L();te&&typeof te=="object"&&"session"in te&&(n==null||n(te.session)),i(v,"success"),await(s==null?void 0:s())}catch(te){i(je(a,te,T),"error")}finally{m(!1)}},se=async L=>{L&&L.preventDefault();const v=x.replace(/\D/g,"");if(!v){i(a("connectionPhoneRequired"),"error");return}if(v.startsWith("0")){i(a("connectionDropLeadingZero"),"error");return}await ne(()=>Q.startSession({method:"pairing",phone:v}),a("connectionRequestingPairing"),"sessionStartError")},V=async()=>{await ne(()=>Q.startSession({method:"qr"}),a("connectionStartingQr"),"sessionStartError")},q=async()=>{await ne(Q.stopSession,a("connectionCancelledEnterPhone"),"sessionStopError"),g("pairing")},C=()=>{t!=null&&t.pairingCode&&(navigator.clipboard.writeText(t.pairingCode.replace(/\s+/g,"")),N(!0),i(a("connectionPairingCopied"),"success"),setTimeout(()=>N(!1),2500))},O=async()=>{d(!1),m(!0);try{const L=await Q.unlinkSession(),v=L&&typeof L=="object"&&"session"in L?L.session:null;v&&(n==null||n(v)),(v==null?void 0:v.state)==="error"&&v.reason==="unlink_incomplete"?i(a("connectionUnlinkIncomplete"),"error"):i(a("connectionUnlinked"),"success"),await(s==null?void 0:s())}catch(L){i(je(a,L,"sessionUnlinkError"),"error")}finally{m(!1)}},Y=ax()?null:e.jsx(xe,{label:a("restart"),icon:e.jsx(ft,{size:16}),onClick:()=>ne(Q.restartBot,a("restart"),"sessionRestartError"),disabled:c});return e.jsxs("div",{className:"flex flex-col gap-4 sm:gap-5",children:[e.jsx(Rc,{status:t}),e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-xs text-muted sm:text-sm",children:a(S?"sessionActive":_?"paused":I?"connectionSavedReady":"sessionOffline")}),t!=null&&t.retryInSeconds?e.jsxs("div",{className:"flex items-center gap-2.5 rounded-xl border border-warn/30 bg-warn/10 p-3 text-warn",children:[e.jsx(Wt,{size:18,className:"shrink-0"}),e.jsxs("div",{className:"text-xs sm:text-sm",children:[e.jsx("span",{className:"font-bold",children:a("connectionReconnectingSoon")})," •"," ",e.jsx("span",{children:de(a("connectionNextAttempt"),{seconds:t.retryInSeconds})})]})]}):null,S&&e.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[e.jsx(U,{variant:"secondary",icon:e.jsx(it,{size:16}),onClick:()=>ne(Q.reconnectSession,a("reconnecting"),"sessionReconnectError"),disabled:c,className:"flex-1 whitespace-nowrap sm:flex-none",children:a("reconnect")}),Y]}),!S&&D&&Y?e.jsx("div",{className:"flex w-full items-center gap-2.5",children:Y}):null,!D&&!y&&I&&e.jsxs("div",{className:"flex w-full flex-col gap-3 sm:max-w-xl",children:[_&&e.jsx("p",{className:"text-xs leading-relaxed text-muted sm:text-sm",children:a($?"connectionPausedResume":"connectionPausedOffline")}),e.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[e.jsx(U,{variant:"primary",icon:e.jsx(Cr,{size:16}),onClick:()=>ne(Q.startSession,G,"sessionStartError"),disabled:c,className:"flex-1 whitespace-nowrap sm:flex-none","data-tour":"connection-start",children:G}),Y]})]}),P&&e.jsxs("div",{className:"flex w-full flex-col gap-4","data-tour":"connection-pairing",children:[e.jsx(Rt,{"aria-label":a("connection"),value:h,onChange:g,className:"w-full sm:w-fit",options:[{value:"pairing",label:a("connectionPairingCodePhone"),icon:e.jsx(hn,{size:16})},{value:"qr",label:a("connectionQrScan"),icon:e.jsx(Zs,{size:16})}]}),h==="pairing"&&e.jsxs("form",{onSubmit:se,className:"flex w-full flex-col gap-3 sm:max-w-xl",children:[e.jsxs("div",{className:"relative",children:[e.jsx(eu,{size:17,className:"pointer-events-none absolute start-3.5 top-1/2 -translate-y-1/2 text-muted"}),e.jsx(be,{type:"tel",value:x,onChange:L=>f(L.target.value),placeholder:a("connectionPhonePlaceholder"),dir:"ltr",className:"ps-10"})]}),e.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[e.jsx(U,{type:"submit",variant:"primary",icon:e.jsx(sr,{size:16}),disabled:c,className:"flex-1 whitespace-nowrap sm:flex-none","data-tour":"connection-start",children:a("connectionGetPairingCode")}),Y]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted",children:a("connectionPairingHint")})]}),h==="qr"&&e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xl",children:[e.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[e.jsx(U,{variant:"primary",icon:e.jsx(Zs,{size:18}),onClick:V,disabled:c,className:"flex-1 whitespace-nowrap sm:flex-none","data-tour":"connection-start",children:a("connectionStartQr")}),Y]}),e.jsx("p",{className:"text-xs text-muted",children:a("connectionQrHint")})]})]})]}),E&&e.jsxs(he,{className:"flex flex-col items-start gap-4",children:[e.jsx("p",{className:"text-sm text-text-main",children:a("connectionUnlinkIncompleteHint")}),e.jsx(U,{variant:"primary",onClick:()=>d(!0),disabled:c,children:a("connectionUnlinkRetry")})]}),y&&e.jsxs(he,{className:"flex flex-col items-start gap-4",children:[e.jsx("p",{className:"text-sm text-text-main",children:Lc(t==null?void 0:t.reason,a)}),e.jsx(U,{variant:"primary",onClick:r,children:a("legalReviewTerms")})]}),R&&e.jsxs(he,{className:"flex items-center gap-3",children:[e.jsx(it,{size:20,className:"shrink-0 animate-spin text-brand-blue","aria-hidden":!0}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-bold text-text-main",children:a(w==="linking"?"connectionFinishingLink":"connectionInitializing")}),e.jsx("p",{className:"text-xs text-muted",children:a("connectionCreatingSocket")})]})]}),b&&e.jsx(he,{className:"mx-auto flex w-full max-w-2xl flex-col items-center text-center",children:t!=null&&t.pairingCode?e.jsxs("div",{className:"flex flex-col items-center w-full animate-in fade-in zoom-in-95 duration-300",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-brand-cyan/15 text-brand-cyan flex items-center justify-center mb-4 border border-brand-cyan/30",children:e.jsx(hn,{size:26})}),e.jsx("h3",{className:"text-lg sm:text-xl font-bold text-text-main mb-1.5",children:a("connectionPairingCodeTitle")}),e.jsx("p",{className:"text-xs sm:text-sm text-muted max-w-md mb-6",children:a("connectionPairingCodeBody")}),e.jsxs("div",{className:"rounded-2xl border-2 border-brand-cyan/40 bg-brand-cyan/10 p-5 sm:p-6 w-full max-w-md flex flex-col items-center gap-4 shadow-lg shadow-brand-cyan/10",children:[e.jsx("div",{className:"text-xs font-bold text-brand-cyan uppercase tracking-wider",children:a("connectionEightDigit")}),e.jsx("div",{className:"text-3xl sm:text-4xl font-mono font-extrabold tracking-widest text-brand-cyan select-all",dir:"ltr",children:t.pairingCode.length===8?`${t.pairingCode.slice(0,4)} - ${t.pairingCode.slice(4)}`:t.pairingCode}),e.jsx(U,{variant:"primary",icon:k?e.jsx(gn,{size:18}):e.jsx(Nr,{size:18}),onClick:C,children:a(k?"connectionCopied":"connectionCopyCode")})]}),e.jsxs("div",{className:"mt-6 p-4 rounded-xl border border-line bg-panel-raised text-start w-full max-w-md",children:[e.jsx("div",{className:"text-xs font-bold text-text-main mb-3",children:a("connectionStepsTitle")}),e.jsxs("ol",{className:"text-xs text-muted space-y-2 list-decimal list-inside leading-relaxed",children:[e.jsx("li",{children:a("connectionStepOpen")}),e.jsx("li",{children:a("connectionStepLinkedDevices")}),e.jsx("li",{children:e.jsx("strong",{className:"text-text-main",children:a("connectionStepLinkWithPhone")})}),e.jsx("li",{children:a("connectionStepEnterCode")})]})]})]}):u?e.jsxs("div",{className:"flex flex-col items-center w-full",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-brand-cyan/15 text-brand-cyan flex items-center justify-center mb-4 border border-brand-cyan/30",children:e.jsx(Zs,{size:26})}),e.jsx("h3",{className:"text-lg font-bold text-text-main mb-1.5",children:a("connectionQrScan")}),e.jsx("p",{className:"text-xs sm:text-sm text-muted max-w-md mb-6",children:a("connectionScanHint")}),e.jsx("div",{className:"p-3 sm:p-4 bg-panel rounded-2xl shadow-xl border border-line animate-in fade-in zoom-in-95 duration-300",children:e.jsx("img",{src:u,alt:"WhatsApp QR Code",className:"w-56 h-56 sm:w-64 sm:h-64 block rounded-lg"})}),e.jsxs("div",{className:"mt-6 pt-5 border-t border-line w-full max-w-md flex flex-col items-center gap-2.5",children:[e.jsx("p",{className:"text-xs text-muted text-center",children:a("connectionSamePhone")}),e.jsx(U,{variant:"secondary",icon:e.jsx(hn,{size:16}),onClick:q,disabled:c,className:"w-full",children:a("connectionLinkWithPhoneInstead")})]})]}):e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8",children:[e.jsx(nt,{className:"size-8"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-muted animate-pulse",children:a("connectionPreparing")})]})}),(D||M)&&e.jsxs(he,{className:"flex flex-col gap-3 border-danger/30",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-bold text-danger",children:a("connectionDangerZone")}),e.jsx("p",{className:"mt-0.5 text-xs leading-relaxed text-muted",children:a("connectionDangerZoneDesc")})]}),e.jsxs("div",{className:"flex flex-col gap-2.5 sm:flex-row sm:flex-wrap",children:[D&&e.jsx(U,{variant:"danger",icon:e.jsx(au,{size:16}),onClick:()=>ne(Q.stopSession,a("stop"),"sessionStopError"),disabled:c,className:"w-full sm:w-auto",children:a(S?"connectionStopSession":"connectionCancelAttempt")}),M&&e.jsx(U,{variant:"danger",icon:e.jsx(ou,{size:16}),onClick:()=>d(!0),disabled:c,className:"w-full sm:w-auto",children:a("unlink")})]})]}),e.jsxs(Ye,{isOpen:l,onClose:()=>d(!1),title:a("unlink"),footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:()=>d(!1),children:a("cancel")}),e.jsx(U,{variant:"danger",onClick:O,children:a("unlink")})]}),children:[e.jsx("p",{className:"text-xs sm:text-sm text-text-main leading-relaxed",children:a("connectionUnlinkConfirm")}),e.jsx("p",{className:"text-xs sm:text-sm text-muted leading-relaxed mt-2",children:a("unlinkStickersWarning")})]})]})},ix=["zero","one","two","few","many","other"];function Tt(t,s){return t.replace(/\{([A-Za-z0-9_]+)\}/g,(n,r)=>Object.hasOwn(s,r)?String(s[r]):n)}function lx(t){if(!t)return[];const s=[];let n="";const r=()=>{if(!n)return;const i=s.at(-1);i&&i.type==="text"?i.text+=n:s.push({type:"text",text:n}),n=""};let a=0;for(;a<t.length;){if(t.startsWith("```",a)){const l=t.indexOf("```",a+3);if(l>a+3){r(),s.push({type:"mono",text:t.slice(a+3,l)}),a=l+3;continue}n+="```",a+=3;continue}const i=t[a];if(i==="*"||i==="_"||i==="~"){const l=t.indexOf(`
448
+ `,a+1),d=l===-1?t.length:l,c=t[a+1];if(a+1<d&&c!==i&&!/\s/.test(c)){let m=-1;for(let u=a+2;u<d;u+=1)if(t[u]===i&&!/\s/.test(t[u-1])){m=u;break}if(m!==-1){r();const u=i==="*"?"bold":i==="_"?"italic":"strike";s.push({type:u,text:t.slice(a+1,m)}),a=m+1;continue}}}n+=i,a+=1}return r(),s}function ox(t,s){const n=Number.isFinite(t)?Math.max(0,Math.trunc(t)):0;let r="other";try{const a=new Intl.PluralRules(s).select(n);ix.includes(a)&&(r=a)}catch{r=n===1?"one":"other"}return`groupMembers_${r}`}function cx(t,s,n){if(t==null||!Number.isFinite(t))return n("groupMembersUnknown");const r=Math.max(0,Math.trunc(t)),a=ox(r,s);return Tt(n(a),{n:r})}function un(t){return t==="DELETE"?"moderationActionDelete":t==="KICK"?"moderationActionKick":t==="FLAG"?"actionFlag":"moderationActionWarn"}function dx(t){return t==="KICK"?"danger":t==="DELETE"?"neutral":"warn"}function Pa(t,s){return Tt(s("presetSummaryLine"),{limit:t.limit,limitAction:s(un(t.limitAction)),linkAction:s(un(t.features.antilink??"WARN")),mediaAction:s(un(t.features.media??"WARN")),forbiddenAction:s(un(t.features.forbidden??"WARN")),spamAction:s(un(t.features.antispam??"WARN"))})}function ux(t,s){const n=[];return t.mode==="severity"?(n.push(Tt(s(t.hitMerge==="sum"?"warnExplainAddSeveritySum":"warnExplainAddSeverityMax"),{link:t.weights.antilink,media:t.weights.media,forbidden:t.weights.forbidden,spam:t.weights.antispam,manual:t.weights.manual})),n.push(Tt(s("warnExplainLimitSeverity"),{flagAt:t.flagAt,kickAt:t.kickAt}))):(n.push(s(t.hitMerge==="sum"?"warnExplainAddSimpleSum":"warnExplainAddSimpleMax")),t.limitAction==="FLAG"?t.flag.whileFlagged==="escalate"?n.push(Tt(s("warnExplainLimitFlagEscalate"),{limit:t.limit,extra:t.flag.escalateAfter})):n.push(Tt(s("warnExplainLimitFlag"),{limit:t.limit})):n.push(Tt(s("warnExplainLimitKick"),{limit:t.limit}))),t.decay.mode==="expire"?n.push(Tt(s("warnExplainDecayExpire"),{days:t.decay.days})):t.decay.mode==="step"&&n.push(Tt(s("warnExplainDecayStep"),{days:t.decay.days})),n}function mx(t,s,n,r){const a=JSON.stringify(t);return a===JSON.stringify(n)?!1:r||a!==JSON.stringify(s)}const Vn={mode:"simple",limit:3,limitAction:"KICK",features:{antilink:null,media:null,forbidden:null,antispam:null},hitMerge:"max",weights:{antilink:1,media:1,forbidden:1,antispam:1,manual:1},flagAt:3,kickAt:5,decay:{mode:"off",days:30},membership:"clear",flag:{notify:"group",mentionAdmins:!0,cooldownMinutes:0,whileFlagged:"record",escalateAfter:3}},Jt={relaxed:{...Vn,limit:5,limitAction:"FLAG",decay:{mode:"expire",days:14},flag:{...Vn.flag,cooldownMinutes:60,whileFlagged:"hold"}},standard:Vn,strict:{...Vn,limit:2,features:{antilink:"KICK",media:"WARN",forbidden:"WARN",antispam:"KICK"}}};function Da(t){return{policyMode:t.mode,policyLimit:t.limit,policyLimitAction:t.limitAction,policyLinkAction:t.features.antilink,policyMediaAction:t.features.media,policyForbiddenAction:t.features.forbidden,policySpamAction:t.features.antispam,policyHitMerge:t.hitMerge,policyWeightLink:t.weights.antilink,policyWeightMedia:t.weights.media,policyWeightForbidden:t.weights.forbidden,policyWeightSpam:t.weights.antispam,policyWeightManual:t.weights.manual,policyFlagAt:t.flagAt,policyKickAt:t.kickAt,policyDecayMode:t.decay.mode,policyDecayDays:t.decay.days,policyMembership:t.membership,policyNotify:t.flag.notify,policyMentionAdmins:t.flag.mentionAdmins,policyCooldown:t.flag.cooldownMinutes,policyWhileFlagged:t.flag.whileFlagged,policyEscalateAfter:t.flag.escalateAfter}}function Mc(t){return{mode:t.policyMode,limit:t.policyLimit,limitAction:t.policyLimitAction,features:{antilink:t.policyLinkAction,media:t.policyMediaAction,forbidden:t.policyForbiddenAction,antispam:t.policySpamAction},hitMerge:t.policyHitMerge,weights:{antilink:t.policyWeightLink,media:t.policyWeightMedia,forbidden:t.policyWeightForbidden,antispam:t.policyWeightSpam,manual:t.policyWeightManual},flagAt:t.policyFlagAt,kickAt:t.policyKickAt,decay:{mode:t.policyDecayMode,days:t.policyDecayDays},membership:t.policyMembership,flag:{notify:t.policyNotify,mentionAdmins:t.policyMentionAdmins,cooldownMinutes:t.policyCooldown,whileFlagged:t.policyWhileFlagged,escalateAfter:t.policyEscalateAfter}}}function Ia(t,s){return JSON.stringify(t)===JSON.stringify(s)}function xx(t){return Ia(t,Jt.relaxed)?"relaxed":Ia(t,Jt.standard)?"standard":Ia(t,Jt.strict)?"strict":"custom"}function px(t,s){const n=Mc(t),r=[["mode",n.mode],["limit",n.limit],["limitAction",n.limitAction],["features.antilink",n.features.antilink],["features.media",n.features.media],["features.forbidden",n.features.forbidden],["features.antispam",n.features.antispam],["hitMerge",n.hitMerge],["weights.antilink",n.weights.antilink],["weights.media",n.weights.media],["weights.forbidden",n.weights.forbidden],["weights.antispam",n.weights.antispam],["weights.manual",n.weights.manual],["flagAt",n.flagAt],["kickAt",n.kickAt],["decay.mode",n.decay.mode],["decay.days",n.decay.days],["membership",n.membership],["flag.notify",n.flag.notify],["flag.mentionAdmins",n.flag.mentionAdmins],["flag.cooldownMinutes",n.flag.cooldownMinutes],["flag.whileFlagged",n.flag.whileFlagged],["flag.escalateAfter",n.flag.escalateAfter]],a={};let i=!1;for(const[l,d]of r){if(s[l]===!1)continue;i=!0;const c=l.split(".");let m=a;for(let u=0;u<c.length-1;u+=1){const p=m[c[u]];(typeof p!="object"||p===null)&&(m[c[u]]={}),m=m[c[u]]}m[c.at(-1)]=d}return i?a:void 0}function za(t,s){const n={};for(const r of s||[])r!=null&&r.field&&!(r.field in n)&&(n[r.field]=je(t,r,"groupValidationError"));return n}const Oa={antilink:"any",welcome:"any",media:"any"};function hx(t,s,n){const r=s.trim().toLowerCase();if(r&&!`${t.subject||""} ${t.jid}`.toLowerCase().includes(r))return!1;const a=!!t.antilink.enabled;if(n.antilink==="on"&&!a||n.antilink==="off"&&a)return!1;const i=!!t.welcomeEnabled;return!(n.welcome==="on"&&!i||n.welcome==="off"&&i||n.media!=="any"&&(t.mediaRestriction||"none")!==n.media)}function ln({label:t,action:s,t:n}){return e.jsxs("span",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:t}),e.jsx(Ce,{tone:dx(s),children:n(un(s))})]})}const fx=()=>{const{t,language:s}=me(),{toast:n}=qe(),[r,a]=o.useState([]),[i,l]=o.useState(!0),[d,c]=o.useState(null),[m,u]=o.useState(0),[p,h]=o.useState(""),[g,x]=o.useState("name"),[f,k]=o.useState(Oa),[N,w]=o.useState([]),[S,b]=o.useState("!"),R=o.useRef(new Set),[j,y]=o.useState(new Set),_=o.useCallback(async()=>{l(!0);try{const C=await Q.getGroups();C!=null&&C.groups&&a(C.groups),c(null)}catch(C){const O=je(t,C,"groupsLoadError");c(O),n(O,"error")}finally{l(!1)}},[t,n]);o.useEffect(()=>{_()},[m,_]),o.useEffect(()=>{let C=!0;return Q.getCommands().then(O=>{C&&(w(O.commands.filter(J=>J.chat==="group")),b(O.prefix||"!"))}).catch(()=>{}),()=>{C=!1}},[]);const A=C=>{a(O=>O.map(J=>J.jid===C.jid?C:J))},D=async(C,O,J)=>{if(R.current.has(C))throw new Error(t("saving"));R.current.add(C),y(new Set(R.current));try{const Y=J==="kick"?await Q.kickFlagged(C,O):J==="clear"?await Q.clearFlagged(C,O):await Q.dismissFlagged(C,O);Y!=null&&Y.group&&A(Y.group),n(t("savedSuccessfully"),"success")}catch(Y){throw n(je(t,Y,"groupUpdateError"),"error"),Y}finally{R.current.delete(C),y(new Set(R.current))}},I=async(C,O)=>{if(R.current.has(C))throw new Error(t("saving"));R.current.add(C),y(new Set(R.current));try{const J=await Q.updateGroup(C,O);J!=null&&J.group&&A(J.group),n(t("savedSuccessfully"),"success")}catch(J){throw n(je(t,J,"groupUpdateError"),"error"),J}finally{R.current.delete(C),y(new Set(R.current))}},F=o.useMemo(()=>{const C=r.filter(O=>hx(O,p,f));return C.sort((O,J)=>{const Y=(O.subject||O.jid).localeCompare(J.subject||J.jid,s,{sensitivity:"base"});return g==="members"&&(J.memberCount||0)-(O.memberCount||0)||Y}),C},[r,p,f,g,s]),E=`${p}|${g}|${f.antilink}|${f.welcome}|${f.media}`,{page:P,pageCount:M,pageItems:$,setPage:G,total:ne}=An(F,20,E),se=(f.antilink!=="any"?1:0)+(f.welcome!=="any"?1:0)+(f.media!=="any"?1:0),V=()=>{h(""),k(Oa)},q=!i&&!d&&r.length>0;return e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsx(Kt,{icon:e.jsx(En,{size:24}),title:e.jsxs("span",{className:"inline-flex flex-wrap items-center gap-2",children:[t("groups"),e.jsx(Ce,{tone:"info",children:de(t("groupsCount"),{n:r.length})})]}),description:t("groupsSubtitle")}),q&&e.jsxs(It,{"data-tour":"groups-list",children:[e.jsx(be,{type:"search",name:"group-search",autoComplete:"off",value:p,onChange:C=>h(C.target.value),placeholder:t("searchGroups"),"aria-label":t("searchGroups"),className:"min-w-40 flex-1"}),e.jsx(Rn,{label:t("sort"),value:g,onChange:x,options:[{value:"name",label:t("sortByName")},{value:"members",label:t("sortByMembers")}]}),e.jsxs(zt,{label:t("filter"),resetLabel:t("reset"),activeCount:se,onReset:()=>k(Oa),children:[e.jsx(st,{label:t("thAntiLink"),name:"group-antilink",value:f.antilink,onChange:C=>k(O=>({...O,antilink:C})),options:[{value:"any",label:t("statusAny")},{value:"on",label:t("statusEnabled")},{value:"off",label:t("statusDisabled")}]}),e.jsx(st,{label:t("thWelcome"),name:"group-welcome",value:f.welcome,onChange:C=>k(O=>({...O,welcome:C})),options:[{value:"any",label:t("statusAny")},{value:"on",label:t("statusEnabled")},{value:"off",label:t("statusDisabled")}]}),e.jsx(st,{label:t("thMedia"),name:"group-media",value:f.media,onChange:C=>k(O=>({...O,media:C})),options:[{value:"any",label:t("statusAny")},{value:"none",label:t("mediaNone")},{value:"block_all",label:t("mediaBlockAll")},{value:"custom",label:t("mediaCustom")}]})]})]}),i&&e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2","aria-busy":"true",children:["g1","g2","g3","g4"].map(C=>e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ve,{className:"size-10 rounded-xl"}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[e.jsx(Ve,{className:"h-5 w-40"}),e.jsx(Ve,{className:"h-4 w-28"})]})]}),e.jsx(Ve,{className:"h-10 w-full"}),e.jsx(Ve,{className:"h-10 w-full"})]},C))}),!i&&d&&e.jsx(Pe,{kind:"error",icon:e.jsx(Zr,{size:28}),description:d,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>u(C=>C+1),children:t("retryLoad")})}),!i&&!d&&r.length===0&&e.jsx(Pe,{kind:"empty",icon:e.jsx(Zr,{size:28}),title:t("noGroupsTitle"),description:t("noGroupsBody")}),!i&&!d&&r.length>0&&F.length===0&&e.jsx(Pe,{kind:"no-results",action:e.jsx(U,{variant:"secondary",onClick:V,children:t("clearFilters")})}),!i&&!d&&F.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 items-start gap-3 xl:grid-cols-2",children:$.map(C=>e.jsx(gx,{group:C,pending:j.has(C.jid),onSave:O=>I(C.jid,O),onFlagged:(O,J)=>D(C.jid,O,J),commands:N,prefix:S},C.jid))}),e.jsx(Ht,{page:P,pageCount:M,total:ne,onPageChange:G})]})]})};function gx({group:t,pending:s,onSave:n,onFlagged:r,commands:a,prefix:i}){const{t:l,language:d}=me(),c=l,[m,u]=o.useState(!1),[p,h]=o.useState(!1),[g,x]=o.useState(!1),f=o.useRef(null),k=o.useId(),N=()=>{if(!m){u(!0);return}if(p){x(!0);return}u(!1)};return e.jsxs(he,{padded:!1,className:"min-w-0 self-start overflow-hidden",children:[e.jsxs(U,{variant:"ghost",className:"h-auto min-h-12 w-full justify-between gap-3 p-4 text-start","aria-expanded":m,"aria-controls":k,id:`${k}-trigger`,onClick:N,children:[e.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsx(er,{src:`/dashboard/api/groups/${encodeURIComponent(t.jid)}/photo`,name:t.subject||c("unnamedGroup")}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx(ze,{lines:2,className:"block font-bold text-text-main",children:t.subject||c("unnamedGroup")}),e.jsxs("span",{className:"mt-1 flex flex-wrap gap-1.5",children:[e.jsx(Ce,{children:cx(t.memberCount,d,c)}),t.antilink.enabled&&e.jsx(Ce,{tone:"info",children:c("thAntiLink")}),t.antispam.enabled&&e.jsx(Ce,{tone:"ok",children:c("antiSpam")}),p&&e.jsx(Ce,{tone:"warn",children:c("unsavedChanges")})]})]})]}),e.jsx(Dt,{size:18,"aria-hidden":!0,className:`shrink-0 transition-transform motion-reduce:transition-none ${m?"rotate-180":""}`})]}),e.jsx("section",{id:k,"aria-labelledby":`${k}-trigger`,"aria-hidden":!m,inert:!m,className:`grid transition-[grid-template-rows] duration-200 motion-reduce:transition-none ${m?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:e.jsx("div",{className:"min-h-0 overflow-hidden",children:e.jsx("div",{className:"border-t border-line p-4",children:e.jsx(bx,{group:t,pending:s,onSave:n,onFlagged:r,commands:a,prefix:i,onDirtyChange:h,registerDiscard:w=>{f.current=w}})})})}),e.jsx(ut,{isOpen:g,onClose:()=>x(!1),onConfirm:()=>{var w;(w=f.current)==null||w.call(f),x(!1),u(!1)},title:c("groupUnsavedCloseTitle"),description:c("groupUnsavedCloseBody"),confirmLabel:c("discard"),cancelLabel:c("cancel"),variant:"danger"})]})}function bx({group:t,pending:s,onSave:n,onFlagged:r,commands:a,prefix:i,onDirtyChange:l,registerDiscard:d}){var L;const{t:c,language:m}=me(),u=c,{permissionLabel:p,describe:h}=_n(),g={...Vn,...t.moderation_policy},x=wn({linkMode:t.antilink.mode,domains:t.antilink.allowed_domains.join(`
449
+ `),spamWindow:t.antispam.time_window,spamLimit:t.antispam.message_count,rules:t.rules,welcome:t.welcome_system.messages.join(`
450
+ `),...Da(g)},"groupUpdateError"),[f,k]=o.useState(!1),[N,w]=o.useState(null),[S,b]=o.useState(t.moderation_policy_visibility??{}),[R,j]=o.useState({});o.useEffect(()=>{b(t.moderation_policy_visibility??{}),j({})},[t.moderation_policy_visibility]);const y=o.useCallback(()=>{x.revert(),w(null),k(!1),j({})},[x.revert]);o.useEffect(()=>{l(x.dirty)},[x.dirty,l]),o.useEffect(()=>{d(y)},[d,y]);const _=v=>S[v]!==!1,A=v=>R[v],D=o.useMemo(()=>Mc(x.draft),[x.draft]),I=xx(D),F=f?"custom":I,E=(v,T)=>{k(!1),w(null),x.setField(v,T)},P=v=>{if(v==="custom"){k(!0);return}const T=Jt[v];mx(D,g,T,I==="custom")?w(Da(D)):w(null),k(!1),x.setDraft(te=>({...te,...Da(T)}))},M=()=>{N&&(x.setDraft(v=>({...v,...N})),w(null),k(!1))},$=v=>{n(v).catch(()=>{})},G=(v,T,te,oe)=>e.jsx(Je,{label:v,description:oe,checked:T,disabled:s,onChange:ye=>$(te(ye))}),ne=o.useMemo(()=>{var v,T;return{antilink:{enabled:t.antilink.enabled,mode:x.draft.linkMode,allowed_domains:x.draft.domains.split(`
451
+ `).map(te=>te.trim()).filter(Boolean)},antispam:{enabled:t.antispam.enabled,time_window:x.draft.spamWindow,message_count:x.draft.spamLimit},media_control:{enabled:t.media_control.enabled,blocked_types:t.media_control.blocked_types},forbidden_words:{enabled:!!((v=t.forbidden_words)!=null&&v.enabled),count:((T=t.forbidden_words)==null?void 0:T.count)||0},moderation_policy:D}},[D,x.draft.domains,x.draft.linkMode,x.draft.spamLimit,x.draft.spamWindow,t.antilink.enabled,t.antispam.enabled,t.media_control,t.forbidden_words]),se=bn(t.moderation_summary,m),[V,q]=o.useState(se||""),C=JSON.stringify(ne);o.useEffect(()=>{let v=!1;const T=window.setTimeout(()=>{Q.previewModeration(ne).then(te=>{v||(q(bn(te,m)),te.visibility&&b(te.visibility),j(za(u,te.errors)))}).catch(te=>{var oe;v||(Array.isArray((oe=te==null?void 0:te.data)==null?void 0:oe.errors)?j(za(u,te.data.errors)):se&&q(se))})},200);return()=>{v=!0,window.clearTimeout(T)}},[C,m,se,ne,u]);const O=V||se||"",J=o.useMemo(()=>{let v=0;return lx(O).map(T=>{const te=`${v}:${T.type}`;return v+=T.text.length,{...T,key:te}})},[O]),Y=o.useMemo(()=>ux(D,u),[D,u]);return e.jsxs("div",{className:"flex min-w-0 flex-col gap-4",children:[e.jsx("form",{className:"flex min-w-0 flex-col gap-4",onSubmit:v=>{v.preventDefault(),x.save(async T=>{var te,oe,ye;try{const fe=px(T,S);await n({antilink:{enabled:t.antilink.enabled,mode:T.linkMode,allowed_domains:T.domains.split(`
452
+ `).map(we=>we.trim()).filter(Boolean)},antispam:{enabled:t.antispam.enabled,time_window:T.spamWindow,message_count:T.spamLimit},media_control:{enabled:t.media_control.enabled,blocked_types:t.media_control.blocked_types},forbidden_words:{enabled:!!((te=t.forbidden_words)!=null&&te.enabled),count:((oe=t.forbidden_words)==null?void 0:oe.count)||0},welcome_system:{...t.welcome_system,messages:T.welcome===t.welcome_system.messages.join(`
453
+ `)?t.welcome_system.messages:T.welcome.split(`
454
+ `).filter(Boolean)},rules:T.rules,moderation_policy:fe}),j({}),w(null),k(!1)}catch(fe){throw Array.isArray((ye=fe==null?void 0:fe.data)==null?void 0:ye.errors)&&j(za(u,fe.data.errors)),fe}})},children:e.jsxs("fieldset",{disabled:s,className:"flex min-w-0 flex-col gap-4",children:[e.jsxs(cn,{title:u("groupModeration"),description:u("botAdminHint"),children:[G(u("thAntiLink"),t.antilink.enabled,v=>({antilink:{...t.antilink,enabled:v}})),e.jsx(re,{label:u("linkMode"),children:e.jsxs(Re,{"aria-label":u("linkMode"),value:x.draft.linkMode,onChange:v=>x.setField("linkMode",v.target.value),children:[e.jsx("option",{value:"ALL",children:u("linkAll")}),e.jsx("option",{value:"WHITELIST",children:u("linkWhitelist")}),e.jsx("option",{value:"BLACKLIST",children:u("linkBlacklist")})]})}),e.jsx(re,{label:u("allowedDomains"),children:e.jsx(wt,{"aria-label":u("allowedDomains"),dir:"ltr",value:x.draft.domains,onChange:v=>x.setField("domains",v.target.value)})}),G(u("antiSpam"),t.antispam.enabled,v=>({antispam:{...t.antispam,enabled:v}})),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(re,{label:u("spamWindow"),children:e.jsx(be,{"aria-label":u("spamWindow"),type:"number",min:1,max:600,required:!0,value:x.draft.spamWindow,onChange:v=>x.setField("spamWindow",Number(v.target.value))})}),e.jsx(re,{label:u("spamLimit"),children:e.jsx(be,{"aria-label":u("spamLimit"),type:"number",min:2,max:100,required:!0,value:x.draft.spamLimit,onChange:v=>x.setField("spamLimit",Number(v.target.value))})})]}),G(u("forbiddenWords"),!!((L=t.forbidden_words)!=null&&L.enabled),v=>{var T;return{forbidden_words:{...t.forbidden_words,enabled:v,count:((T=t.forbidden_words)==null?void 0:T.count)||0}}}),e.jsx("div",{className:"grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-2",children:[["image","blockImages"],["video","blockVideos"],["audio","blockAudio"],["sticker","blockStickers"]].map(([v,T])=>e.jsx(Je,{label:u(T),disabled:s,checked:t.media_control.enabled&&t.media_control.blocked_types.includes(v),onChange:te=>{const oe=t.media_control.enabled?t.media_control.blocked_types:[],ye=te?[...new Set([...oe,v])]:oe.filter(fe=>fe!==v);$({media_control:{enabled:ye.length>0,blocked_types:ye}})}},v))})]}),e.jsxs(cn,{title:u("policyBlockTitle"),className:"border-t border-line pt-4",children:[e.jsxs(re,{label:u("policyPreset"),children:[e.jsx(st,{name:`policy-preset-${t.jid}`,value:F,onChange:P,options:[{value:"relaxed",label:u("presetRelaxed"),description:Pa(Jt.relaxed,u)},{value:"standard",label:u("presetStandard"),description:Pa(Jt.standard,u)},{value:"strict",label:u("presetStrict"),description:Pa(Jt.strict,u)},{value:"custom",label:u("presetCustom"),description:u("presetCustomDesc")}]}),N&&e.jsxs("div",{role:"status",className:"flex flex-wrap items-center justify-between gap-2 rounded-xl border border-warn/30 bg-warn/10 px-3 py-2 text-xs text-text-main",children:[e.jsx("span",{className:"min-w-0 flex-1 text-muted",children:u("presetReplacedNotice")}),e.jsx(U,{type:"button",variant:"secondary",size:"sm",icon:e.jsx(qo,{size:14}),onClick:M,children:u("presetUndo")})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[_("features.antilink")&&e.jsx(re,{label:e.jsx(ln,{label:u("policyLinkLabel"),action:x.draft.policyLinkAction??"WARN",t:u}),error:A("features.antilink"),children:e.jsxs(Re,{"aria-label":u("policyLinkLabel"),value:x.draft.policyLinkAction??"DEFAULT",onChange:v=>E("policyLinkAction",v.target.value==="DEFAULT"?null:v.target.value),children:[e.jsx("option",{value:"DEFAULT",children:u("moderationActionDefault")}),e.jsx("option",{value:"DELETE",children:u("moderationActionDelete")}),e.jsx("option",{value:"WARN",children:u("moderationActionWarn")}),e.jsx("option",{value:"KICK",children:u("moderationActionKick")})]})}),_("features.media")&&e.jsx(re,{label:e.jsx(ln,{label:u("policyMediaLabel"),action:x.draft.policyMediaAction??"WARN",t:u}),error:A("features.media"),children:e.jsxs(Re,{"aria-label":u("policyMediaLabel"),value:x.draft.policyMediaAction??"DEFAULT",onChange:v=>E("policyMediaAction",v.target.value==="DEFAULT"?null:v.target.value),children:[e.jsx("option",{value:"DEFAULT",children:u("moderationActionDefault")}),e.jsx("option",{value:"DELETE",children:u("moderationActionDelete")}),e.jsx("option",{value:"WARN",children:u("moderationActionWarn")}),e.jsx("option",{value:"KICK",children:u("moderationActionKick")})]})}),_("features.forbidden")&&e.jsx(re,{label:e.jsx(ln,{label:u("policyForbiddenLabel"),action:x.draft.policyForbiddenAction??"WARN",t:u}),error:A("features.forbidden"),children:e.jsxs(Re,{"aria-label":u("policyForbiddenLabel"),value:x.draft.policyForbiddenAction??"DEFAULT",onChange:v=>E("policyForbiddenAction",v.target.value==="DEFAULT"?null:v.target.value),children:[e.jsx("option",{value:"DEFAULT",children:u("moderationActionDefault")}),e.jsx("option",{value:"DELETE",children:u("moderationActionDelete")}),e.jsx("option",{value:"WARN",children:u("moderationActionWarn")}),e.jsx("option",{value:"KICK",children:u("moderationActionKick")})]})}),_("features.antispam")&&e.jsx(re,{label:e.jsx(ln,{label:u("policySpamLabel"),action:x.draft.policySpamAction??"WARN",t:u}),error:A("features.antispam"),children:e.jsxs(Re,{"aria-label":u("policySpamLabel"),value:x.draft.policySpamAction??"DEFAULT",onChange:v=>E("policySpamAction",v.target.value==="DEFAULT"?null:v.target.value),children:[e.jsx("option",{value:"DEFAULT",children:u("moderationActionDefault")}),e.jsx("option",{value:"WARN",children:u("moderationActionWarn")}),e.jsx("option",{value:"KICK",children:u("moderationActionKick")})]})})]})]}),e.jsxs(cn,{title:u("warnSectionTitle"),className:"border-t border-line pt-4",children:[e.jsx("div",{className:"flex flex-col gap-1 rounded-xl border border-line bg-bg p-3 text-xs text-muted",children:Y.map(v=>e.jsx("p",{dir:"auto",children:v},v))}),e.jsx(re,{label:u("policyMode"),error:A("mode"),children:e.jsxs(Re,{"aria-label":u("policyMode"),value:x.draft.policyMode,onChange:v=>{const T=v.target.value==="severity"?"severity":"simple";E("policyMode",T),T==="severity"&&x.draft.policyWhileFlagged==="escalate"&&E("policyWhileFlagged","record")},children:[e.jsx("option",{value:"simple",children:u("policyModeSimple")}),e.jsx("option",{value:"severity",children:u("policyModeSeverity")})]})}),_("limit")&&e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(re,{label:u("warningLimit"),error:A("limit"),children:e.jsx(be,{"aria-label":u("warningLimit"),type:"number",min:1,max:50,required:!0,value:x.draft.policyLimit,onChange:v=>E("policyLimit",Number(v.target.value))})}),e.jsx(re,{label:e.jsx(ln,{label:u("warningAction"),action:x.draft.policyLimitAction,t:u}),error:A("limitAction"),children:e.jsxs(Re,{"aria-label":u("warningAction"),value:x.draft.policyLimitAction,onChange:v=>E("policyLimitAction",v.target.value==="FLAG"?"FLAG":"KICK"),children:[e.jsx("option",{value:"KICK",children:u("moderationActionKick")}),e.jsx("option",{value:"FLAG",children:u("actionFlag")})]})})]}),_("flagAt")&&e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(re,{label:u("policyFlagAt"),error:A("flagAt"),children:e.jsx(be,{"aria-label":u("policyFlagAt"),type:"number",min:1,max:49,required:!0,value:x.draft.policyFlagAt,onChange:v=>E("policyFlagAt",Number(v.target.value))})}),e.jsx(re,{label:e.jsx(ln,{label:u("policyKickAt"),action:"KICK",t:u}),error:A("kickAt"),children:e.jsx(be,{"aria-label":u("policyKickAt"),type:"number",min:2,max:50,required:!0,value:x.draft.policyKickAt,onChange:v=>E("policyKickAt",Number(v.target.value))})})]}),_("hitMerge")&&e.jsx(re,{label:u("policyHitMerge"),error:A("hitMerge"),children:e.jsxs(Re,{"aria-label":u("policyHitMerge"),value:x.draft.policyHitMerge,onChange:v=>E("policyHitMerge",v.target.value==="sum"?"sum":"max"),children:[e.jsx("option",{value:"max",children:u("policyHitMergeMax")}),e.jsx("option",{value:"sum",children:u("policyHitMergeSum")})]})}),_("weights.antilink")&&e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(re,{label:u("policyWeightLink"),error:A("weights.antilink"),children:e.jsx(be,{"aria-label":u("policyWeightLink"),type:"number",min:1,max:10,required:!0,value:x.draft.policyWeightLink,onChange:v=>E("policyWeightLink",Number(v.target.value))})}),e.jsx(re,{label:u("policyWeightMedia"),error:A("weights.media"),children:e.jsx(be,{"aria-label":u("policyWeightMedia"),type:"number",min:1,max:10,required:!0,value:x.draft.policyWeightMedia,onChange:v=>E("policyWeightMedia",Number(v.target.value))})}),e.jsx(re,{label:u("policyWeightForbidden"),error:A("weights.forbidden"),children:e.jsx(be,{"aria-label":u("policyWeightForbidden"),type:"number",min:1,max:10,required:!0,value:x.draft.policyWeightForbidden,onChange:v=>E("policyWeightForbidden",Number(v.target.value))})}),e.jsx(re,{label:u("policyWeightSpam"),error:A("weights.antispam"),children:e.jsx(be,{"aria-label":u("policyWeightSpam"),type:"number",min:1,max:10,required:!0,value:x.draft.policyWeightSpam,onChange:v=>E("policyWeightSpam",Number(v.target.value))})}),e.jsx(re,{label:u("policyWeightManual"),error:A("weights.manual"),children:e.jsx(be,{"aria-label":u("policyWeightManual"),type:"number",min:1,max:10,required:!0,value:x.draft.policyWeightManual,onChange:v=>E("policyWeightManual",Number(v.target.value))})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(re,{label:u("policyDecay"),error:A("decay.mode"),children:e.jsxs(Re,{"aria-label":u("policyDecay"),value:x.draft.policyDecayMode,onChange:v=>E("policyDecayMode",v.target.value==="expire"?"expire":v.target.value==="step"?"step":"off"),children:[e.jsx("option",{value:"off",children:u("policyDecayOff")}),e.jsx("option",{value:"expire",children:u("policyDecayExpire")}),e.jsx("option",{value:"step",children:u("policyDecayStep")})]})}),_("decay.days")&&e.jsx(re,{label:u("policyDecayDays"),error:A("decay.days"),children:e.jsx(be,{"aria-label":u("policyDecayDays"),type:"number",min:1,max:365,required:!0,value:x.draft.policyDecayDays,onChange:v=>E("policyDecayDays",Number(v.target.value))})}),e.jsx(re,{label:u("policyMembership"),error:A("membership"),children:e.jsxs(Re,{"aria-label":u("policyMembership"),value:x.draft.policyMembership,onChange:v=>E("policyMembership",v.target.value==="clear"?"clear":"keep"),children:[e.jsx("option",{value:"keep",children:u("policyMembershipKeep")}),e.jsx("option",{value:"clear",children:u("policyMembershipClear")})]})})]}),_("flag.notify")&&e.jsx(re,{label:u("policyFlagNotify"),error:A("flag.notify"),children:e.jsxs(Re,{"aria-label":u("policyFlagNotify"),value:x.draft.policyNotify,onChange:v=>E("policyNotify",v.target.value==="silent"?"silent":"group"),children:[e.jsx("option",{value:"group",children:u("policyNotifyGroup")}),e.jsx("option",{value:"silent",children:u("policyNotifySilent")})]})}),_("flag.mentionAdmins")&&e.jsx(ht,{label:u("policyMentionAdmins"),checked:x.draft.policyMentionAdmins,disabled:s,onChange:v=>E("policyMentionAdmins",v.target.checked)}),_("flag.cooldownMinutes")&&e.jsx(re,{label:u("policyCooldown"),description:u("policyCooldownHint"),error:A("flag.cooldownMinutes"),children:e.jsx(be,{"aria-label":u("policyCooldown"),type:"number",min:0,max:10080,required:!0,value:x.draft.policyCooldown,onChange:v=>E("policyCooldown",Number(v.target.value))})}),_("flag.whileFlagged")&&e.jsx(re,{label:u("policyWhileFlagged"),error:A("flag.whileFlagged"),children:e.jsxs(Re,{"aria-label":u("policyWhileFlagged"),value:x.draft.policyWhileFlagged,onChange:v=>{const T=v.target.value==="hold"?"hold":v.target.value==="escalate"?"escalate":"record";E("policyWhileFlagged",T)},children:[e.jsx("option",{value:"record",children:u("policyWhileFlaggedRecord")}),e.jsx("option",{value:"hold",children:u("policyWhileFlaggedHold")}),x.draft.policyMode==="simple"&&e.jsx("option",{value:"escalate",children:u("policyWhileFlaggedEscalate")})]})}),_("flag.escalateAfter")&&x.draft.policyWhileFlagged==="escalate"&&e.jsx(re,{label:u("policyEscalateAfter"),error:A("flag.escalateAfter"),children:e.jsx(be,{"aria-label":u("policyEscalateAfter"),type:"number",min:1,max:50,required:!0,value:x.draft.policyEscalateAfter,onChange:v=>E("policyEscalateAfter",Number(v.target.value))})})]}),e.jsxs(cn,{title:u("rulesAndModeration"),className:"border-t border-line pt-4",children:[e.jsx(re,{label:u("groupRules"),children:e.jsx(wt,{"aria-label":u("groupRules"),dir:"auto",maxLength:4e3,value:x.draft.rules,onChange:v=>x.setField("rules",v.target.value)})}),e.jsx(re,{label:u("moderationPreview"),description:u("moderationPreviewHint"),children:e.jsx("div",{dir:"auto",className:"min-h-10 whitespace-pre-wrap break-words rounded-xl border border-line bg-bg p-3 text-sm text-text-main",children:J.map(v=>v.type==="bold"?e.jsx("strong",{className:"font-bold",children:v.text},v.key):v.type==="italic"?e.jsx("em",{className:"italic",children:v.text},v.key):v.type==="strike"?e.jsx("del",{className:"line-through",children:v.text},v.key):v.type==="mono"?e.jsx("code",{className:"rounded bg-panel px-1 py-0.5 font-mono text-xs",children:v.text},v.key):e.jsx("span",{children:v.text},v.key))})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:"text-sm font-bold text-text-main",children:u("flaggedMembers")}),(t.flagged_members||[]).length===0?e.jsx("p",{className:"text-sm text-muted",children:u("flaggedEmpty")}):e.jsx("ul",{className:"m-0 flex list-none flex-col gap-2 p-0",children:(t.flagged_members||[]).map(v=>e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 rounded-xl border border-line bg-bg px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(ze,{className:"block text-sm font-bold text-text-main",children:v.name}),e.jsxs("p",{className:"mt-0.5 truncate text-xs text-muted",dir:"ltr",children:[v.warn_count," · ",v.last_rule||"—",v.flagged_at?e.jsxs(e.Fragment,{children:[" · ",e.jsx(jn,{value:v.flagged_at})]}):null]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(U,{variant:"danger",size:"sm",icon:e.jsx(cu,{size:16}),disabled:s,onClick:()=>{r(v.user_id,"kick")},children:u("moderationActionKick")}),e.jsxs(mt,{label:u("moreActions"),children:[e.jsx(_e,{icon:e.jsx(Ud,{size:16}),onSelect:()=>{r(v.user_id,"clear")},children:u("clearWarnings")}),e.jsx(_e,{onSelect:()=>{r(v.user_id,"dismiss")},children:u("dismissFlag")})]})]})]},v.user_id))})]})]}),e.jsxs(cn,{title:u("thWelcome"),className:"border-t border-line pt-4",children:[G(u("welcomeToggleLabel"),t.welcome_system.enabled,v=>({welcome_system:{...t.welcome_system,enabled:v}})),G(u("autoApprove"),t.join_requests.auto_approve_enabled,v=>({join_requests:{auto_approve_enabled:v}}),u("welcomeAutoApproveHint")),e.jsx(re,{label:e.jsxs("span",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:u("welcomeMessages")}),!t.welcome_system.enabled&&e.jsx(Ce,{tone:"warn",children:u("welcomeOffNotice")})]}),description:t.welcome_system.enabled?u("welcomeMessagesHint"):`${u("welcomeOffNotice")} — ${u("welcomeMessagesHint")}`,children:e.jsx(wt,{"aria-label":u("welcomeMessages"),dir:"auto",value:x.draft.welcome,onChange:v=>x.setField("welcome",v.target.value)})})]}),e.jsx(kn,{dirty:x.dirty,saving:s,justSaved:x.status==="saved",error:x.error,onDiscard:y,saveLabel:u("save"),discardLabel:u("discard"),unsavedLabel:u("unsavedChanges"),savedLabel:u("saved")})]})}),a.length>0&&e.jsx(is,{summary:u("groupCommands"),children:e.jsx("ul",{className:"flex list-none flex-col gap-3 p-0",children:a.map(v=>e.jsxs("li",{className:"flex flex-col gap-1",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("code",{dir:"ltr",className:"font-mono text-sm font-bold text-brand-cyan",children:[i,v.name]}),e.jsx(Ce,{children:p(v.permission)}),e.jsx(Ce,{tone:v.enabled?"ok":"neutral",children:v.enabled?u("statusEnabled"):u("statusDisabled")})]}),e.jsx("p",{dir:"auto",className:"text-xs text-muted",children:h(v)})]},v.key||v.name))})})]})}var ll;const Hi=typeof((ll=window.LevixHost)==null?void 0:ll.hostLog)=="function",yx=()=>{const{t,language:s}=me(),{toast:n}=qe(),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[d,c]=o.useState(!1),m=o.useRef(!1),u=o.useRef(0),[p,h]=o.useState([]),[g,x]=o.useState("all"),[f,k]=o.useState(!0),N=o.useRef(null),[w,S]=o.useState("bot"),[b,R]=o.useState([]),j=o.useCallback(async()=>{var F;if(m.current)return;const I=u.current;try{if(w==="bot"){const E=await Q.getLogs();if(I!==u.current)return;h(E.logs||[])}else{const E=((F=window.LevixHost)==null?void 0:F.hostLog(500))??"";if(I!==u.current)return;R(E.split(`
455
+ `).filter(Boolean))}a(!1)}catch{I===u.current&&a(!0)}},[w]);o.useEffect(()=>{u.current+=1;let I=!1,F;const E=async()=>{await j(),I||(F=setTimeout(E,3e3))};return E(),()=>{I=!0,clearTimeout(F),u.current+=1}},[j]);const y=async()=>{var I;if(!m.current){m.current=!0,c(!0),u.current+=1;try{if(w==="bot")await Q.clearLogs();else if(!JSON.parse(((I=window.LevixHost)==null?void 0:I.clearHostLogs())||"{}").ok)throw new Error("clear failed");l(!1),n(t("logsCleared"),"success")}catch{n(t("logsClearFailed"),"error")}finally{m.current=!1,c(!1),await j()}}};o.useEffect(()=>{f&&N.current&&N.current.scrollIntoView({behavior:"smooth"})},[p,b,f]);const _=p.filter(I=>g==="all"?!0:I.level===g),A=w==="bot"?_.length:b.length,D=I=>I==="error"?"danger":I==="warn"?"warn":"info";return e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsx(Kt,{icon:e.jsx(en,{size:20}),title:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t("liveServerLogs"),e.jsx(Ce,{tone:"neutral",className:"font-mono",children:A})]}),description:t("logsSubtitle"),actions:e.jsxs(It,{children:[Hi&&e.jsx(Rt,{"aria-label":t("logs"),value:w,onChange:I=>{m.current||S(I)},options:[{value:"bot",label:t("logSourceBot")},{value:"host",label:t("logSourceHost"),icon:e.jsx(hn,{size:14})}]}),w==="bot"&&e.jsx(zt,{label:t("filter"),resetLabel:t("reset"),activeCount:g==="all"?0:1,onReset:()=>x("all"),children:e.jsx(st,{name:"log-level",label:t("allLogs"),value:g,onChange:x,options:[{value:"all",label:t("allLogs")},{value:"info",label:"INFO"},{value:"warn",label:"WARN"},{value:"error",label:"ERROR"}]})}),w==="host"&&Hi&&e.jsx(xe,{label:t("shareLogs"),icon:e.jsx(rs,{size:18}),onClick:()=>{var I;try{(I=window.LevixHost)==null||I.shareHostLogs()}catch{}}}),e.jsx(xe,{label:t("autoScroll"),pressed:f,icon:e.jsx(Md,{size:18,className:f?"animate-bounce":""}),onClick:()=>k(I=>!I)}),e.jsx(xe,{label:t("clearLogs"),variant:"ghost",icon:e.jsx(lt,{size:18}),disabled:d,onClick:()=>l(!0)})]})}),e.jsxs(ut,{isOpen:i,onClose:()=>{d||l(!1)},onConfirm:y,title:t("clearLogsConfirm"),confirmLabel:t("clearLogs"),cancelLabel:t("cancel"),loading:d,children:[t("clearLogsBody")," · ",t(w==="host"?"logSourceHost":"logSourceBot")]}),r&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:t("logsLoadFailed")}),e.jsxs(he,{padded:!1,className:"h-[65vh] overflow-y-auto bg-bg p-4 font-mono text-xs leading-relaxed text-muted shadow-2xl md:p-5",dir:"ltr","data-tour":"logs-stream",children:[w==="bot"?_.length===0?e.jsx(Pe,{icon:e.jsx(en,{size:24}),text:t("noLogs")}):e.jsx("div",{className:"flex flex-col gap-1.5",children:_.map((I,F)=>e.jsxs("div",{className:"rounded px-1 py-0.5 hover:bg-panel-hover/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"shrink-0 select-none text-[11px] text-faint",children:I.time||new Date().toLocaleTimeString(At(s))}),e.jsx(Ce,{tone:D(I.level||"info"),className:"px-1.5 py-px font-mono text-[10px]",children:(I.level||"info").toUpperCase()})]}),e.jsx("span",{className:"whitespace-pre-wrap break-words font-mono text-text-main [overflow-wrap:anywhere]",children:I.msg})]},F))}):b.length===0?e.jsx(Pe,{icon:e.jsx(hn,{size:24}),text:t("noLogs")}):e.jsx("div",{className:"flex flex-col gap-1.5",children:b.map((I,F)=>e.jsx("div",{className:"rounded px-1 py-0.5 hover:bg-panel-hover/40",children:e.jsx("span",{className:"break-all font-mono text-text-main",children:I})},F))}),e.jsx("div",{ref:N})]})]})},vx=({status:t,onNavigate:s})=>{var w;const{t:n}=me(),{toast:r}=qe(),[a,i]=o.useState(null),[l,d]=o.useState(!0),[c,m]=o.useState(!1),u=!!(t&&["idle","disconnected","retry_exhausted","error"].includes(t.state)),p=!!((w=t==null?void 0:t.user)!=null&&w.id||t!=null&&t.linked),h=u&&p,g=async()=>{if(!(!h||c)){m(!0);try{await Q.startSession(),r(n("starting"),"info")}catch(S){r(je(n,S,"sessionStartError"),"error")}finally{m(!1)}}};o.useEffect(()=>{let S=!0;return Q.getStats().then(b=>{S&&(b!=null&&b.stats)&&i(b.stats)}).catch(b=>{r(je(n,b,"overviewLoadError"),"error")}).finally(()=>{S&&d(!1)}),()=>{S=!1}},[n,r]);const x=S=>{const b=Math.floor(S/86400),R=Math.floor(S%86400/3600),j=Math.floor(S%3600/60);return b?`${b} ${n("uptimeDayUnit")} ${R} ${n("uptimeHourUnit")}`:R?`${R} ${n("uptimeHourUnit")} ${j} ${n("uptimeMinuteUnit")}`:`${j} ${n("uptimeMinuteUnit")}`},f=(t==null?void 0:t.state)==="connected",k=[{id:"connection",title:n("connection"),desc:n(f?"connected":"accountCardNotConnected"),icon:Cr,color:"border-brand-cyan/20 bg-brand-cyan/10 text-brand-cyan"},{id:"ai",title:n("ai"),desc:n("aiAssistantDesc")||"Autonomous tool-calling AI agent",icon:Cn,color:"border-brand-purple/20 bg-brand-purple/10 text-brand-purple"},{id:"commands",title:n("commands"),desc:n("quickCommandsDesc").replace("{n}",String((a==null?void 0:a.commandCount)??0)),icon:en,color:"border-brand-blue/20 bg-brand-blue/10 text-brand-blue"},{id:"settings",title:n("settings"),desc:n("settingsSub")||"Prefix, ports, delays, security & storage",icon:To,color:"border-ok/20 bg-ok/10 text-ok"}],N=[{label:n("totalGroups"),value:(a==null?void 0:a.totalGroups)??0,icon:En,tone:"border-brand-blue/20 bg-brand-blue/10 text-brand-blue"},{label:n("commandCount"),value:(a==null?void 0:a.commandCount)??0,icon:en,tone:"border-brand-cyan/20 bg-brand-cyan/10 text-brand-cyan"},{label:n("uptime"),value:x((a==null?void 0:a.uptime)||0),icon:Pl,tone:"border-ok/20 bg-ok/10 text-ok"},{label:n("activeSchedules"),value:(a==null?void 0:a.activeSchedules)??0,icon:Ss,tone:"border-brand-purple/20 bg-brand-purple/10 text-brand-purple"}];return e.jsxs("div",{className:"flex flex-col gap-5 sm:gap-6",children:[e.jsx(Rc,{status:t,variant:"compact",onManage:()=>s("connection"),onStart:h?g:void 0,starting:c}),e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:gap-5 lg:grid-cols-4","data-tour":"overview-stats",children:N.map(S=>{const b=S.icon;return e.jsxs(he,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"line-clamp-2 text-[11px] font-bold uppercase tracking-wider text-muted sm:text-xs",children:S.label}),e.jsx("div",{className:`flex size-10 shrink-0 items-center justify-center rounded-xl border ${S.tone}`,children:e.jsx(b,{size:18})})]}),e.jsx("div",{className:"mt-2 font-mono text-2xl font-extrabold tracking-tight text-text-main sm:text-3xl",children:l?"—":S.value})]},S.label)})}),e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4",children:k.map(S=>{const b=S.icon;return e.jsx(he,{padded:!1,className:"h-full transition-colors hover:border-brand-blue/30",children:e.jsxs(U,{variant:"ghost",onClick:()=>s(S.id),className:"h-full w-full flex-col items-stretch justify-between gap-3 rounded-2xl p-4 text-start sm:gap-4 sm:p-5",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("div",{className:`flex size-10 shrink-0 items-center justify-center rounded-xl border ${S.color}`,children:e.jsx(b,{size:18})}),e.jsx(Ps,{size:16,className:"shrink-0 text-faint rtl:-scale-x-100","aria-hidden":!0})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-bold text-text-main sm:text-sm",children:S.title}),e.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-relaxed text-muted sm:text-xs",children:S.desc})]})]})},S.id)})})]})},jx=new Intl.Segmenter("en",{granularity:"grapheme"}),wx=["🤦","🌐","🧠","👁️","💾","👍","❤️","✅"],Tc=["add","change","remove"],Xt=["text","voice","audio","image","video","document","sticker"],Pc=["any","owner","bot_admin","group_admin","member"],Or=100,kx=0,Nx=1e3,Fr=100,on={perReactor:3,perChat:10,perRule:5,windowMs:6e4,globalJobs:2,candidateLimit:100},Sx=new Set(["RULE_INVALID","NOT_CONNECTED","ACTION_DISABLED","STT_DISABLED","STT_KEY_MISSING","OWNER_NOT_LINKED","CANDIDATE_LIMIT"]),Cx=new Set(["AUTOMATION_OFF","RULE_OFF"]),Fa={status:"any",action:"any"};function fr(t){return typeof t=="string"&&t.length>0&&t.length<=32&&new RegExp("^(?:\\p{Extended_Pictographic}|\\p{Regional_Indicator}|\\p{Emoji_Modifier}|\\uFE0F|\\u200D|\\u20E3|[#*0-9])+$","u").test(t)&&new RegExp("\\p{Extended_Pictographic}|\\p{Regional_Indicator}|\\u20e3","u").test(t)&&[...jx.segment(t)].length===1}function Vi(){return{chatJid:"",chatName:"",emoji:"",transitions:["add"],originalTypes:[...Xt],role:"owner",senderIds:[],action:"",destination:"same_chat",priority:Fr}}function Zt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ba(t){return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}function Ex(t){const s=Zt(t.definition),n=Zt(s==null?void 0:s.senders),r=Zt(s==null?void 0:s.destination),a=Ba(s==null?void 0:s.transitions).filter(m=>Tc.includes(m)),i=Ba(s==null?void 0:s.originalTypes).filter(m=>Xt.includes(m)),l=n==null?void 0:n.role,d=s==null?void 0:s.action,c=r==null?void 0:r.mode;return{chatJid:typeof t.chatJid=="string"?t.chatJid:"",chatName:typeof t.chatName=="string"&&t.chatName!==t.chatJid?t.chatName:"",emoji:typeof(s==null?void 0:s.emoji)=="string"?s.emoji:"",transitions:a.length?a:["add"],originalTypes:i.length?i:d==="stt"?["voice"]:[...Xt],role:Pc.includes(l)?l:"owner",senderIds:Ba(n==null?void 0:n.ids).slice(0,Or),action:d==="ping"||d==="stt"?d:"",destination:c==="owner_private"||c==="same_chat"?c:"same_chat",priority:Number.isInteger(t.priority)?t.priority:Fr}}function Dc(t){const s=Zt(t.definition),n=Zt(s==null?void 0:s.senders),r=Zt(s==null?void 0:s.destination),a=s==null?void 0:s.emoji,i=s==null?void 0:s.action,l=r==null?void 0:r.mode,d=n==null?void 0:n.role;return{emoji:typeof a=="string"&&a?a:t.valid===!1?"?":"—",action:typeof i=="string"?i:"",destination:typeof l=="string"?l:"",role:typeof d=="string"?d:""}}function Ax(t){if(!t.action)throw new Error("REACTION_ACTION_REQUIRED");const s=t.action==="stt"?["voice"]:[...t.originalTypes],n={version:1,emoji:t.emoji,transitions:[...t.transitions],originalTypes:s,senders:{role:t.role,ids:[...t.senderIds]},action:t.action,destination:{mode:t.destination}};return{chatJid:t.chatJid,priority:t.priority,definition:n}}function qi(t){return Number.isFinite(t)?Math.min(Nx,Math.max(kx,Math.round(t))):Fr}function Ua(t,s){if(!t)return"";const n=s==null?void 0:s.get(t);if(n&&n!==t)return n;const r=/^(\d+)@s\.whatsapp\.net$/i.exec(t);return r?`+${r[1]}`:""}function Rx(t){const s=[];return t.chatJid||s.push({field:"chatJid",code:"required"}),fr(t.emoji)||s.push({field:"definition.emoji",code:t.emoji?"invalid":"required"}),t.action||s.push({field:"definition.action",code:"invalid"}),t.transitions.length||s.push({field:"definition.transitions",code:"invalid"}),t.action!=="stt"&&!t.originalTypes.length&&s.push({field:"definition.originalTypes",code:"invalid"}),t.senderIds.length>Or&&s.push({field:"definition.senders.ids",code:"too_many"}),s}function _x(t){return t==="READY"?"ok":t==="AUTOMATION_OFF"||t==="RULE_OFF"?"neutral":t==="RULE_INVALID"||t==="ACTION_DISABLED"||t==="STT_KEY_MISSING"||t==="OWNER_NOT_LINKED"?"danger":"warn"}function Lx(t,s){var r;if(s.action!=="any"&&((r=Zt(t.definition))==null?void 0:r.action)!==s.action)return!1;const n=Array.isArray(t.statuses)?t.statuses:[];return s.status==="ready"?n.includes("READY"):s.status==="off"?n.some(a=>Cx.has(a)):s.status==="attention"?n.some(a=>Sx.has(a)):!0}function Mx(t,s,n){const r=[...t],a=(i,l)=>i.id.localeCompare(l.id);if(s==="chat")r.sort((i,l)=>(i.chatName||i.chatJid).localeCompare(l.chatName||l.chatJid,n,{sensitivity:"base"})||i.priority-l.priority||a(i,l));else if(s==="recent"){const i=l=>{var d;return((d=l.runtime)==null?void 0:d.lastAt)??l.enabledAt??0};r.sort((l,d)=>i(d)-i(l)||a(d,l))}else r.sort((i,l)=>i.priority-l.priority||a(i,l));return r}function Tx(t){var n;if(!t||typeof t!="object"||!("automation"in t))return;const s=(n=t.automation)==null?void 0:n.enabled;return typeof s=="boolean"?s:void 0}function Px(t){var n;if(!t||typeof t!="object"||!("automation"in t))return;const s=(n=t.automation)==null?void 0:n.revision;return typeof s=="string"&&s?s:void 0}function Dx(t){let s=!1;return async(n,r)=>{var i,l,d,c,m;if(s)return!1;s=!0,t.written(),t.alive()&&t.busy(!0);let a=null;try{const u=await t.send(n,t.revision()),p=(i=u.automation)==null?void 0:i.revision;return typeof p=="string"&&p&&((l=t.remember)==null||l.call(t,p)),t.alive()&&t.show(!!((d=u.automation)!=null&&d.enabled)),!0}catch(u){return Sn(u)==="REACTION_AUTOMATION_CHANGED"?(a=u,!0):(t.alive()&&(t.show(r),t.failed(u)),!0)}finally{if(s=!1,t.written(),t.alive()){t.busy(!1);const u=await t.reconcile();if(a){const p=Tx(u);p!==void 0&&t.show(p);const h=Px(u);h&&((c=t.remember)==null||c.call(t,h)),(m=t.conflict)==null||m.call(t,a)}}}}}function Ix(t){return[t.status,t.action].filter(s=>s!=="any").length}function Ic(t){const s=String(t??"");return s.startsWith("definition.")?s.slice(11):s}function zx(t){const s=Ic(t).split(".")[0];return s==="chatJid"||s==="priority"||s==="emoji"||s==="transitions"||s==="originalTypes"||s==="senders"||s==="action"||s==="destination"?s:"form"}function Ox(t){const s=t&&typeof t=="object"?t:{},n=(i,l)=>{const d=Number(s[i]);return Number.isFinite(d)&&d>=0?d:l},r=n("windowMs",Number.NaN),a=n("windowSeconds",Number.NaN);return{perReactor:n("perReactor",on.perReactor),perChat:n("perChat",on.perChat),perRule:n("perRule",on.perRule),windowMs:Number.isFinite(r)?r:Number.isFinite(a)?a*1e3:on.windowMs,globalJobs:n("globalJobs",on.globalJobs),candidateLimit:n("candidateLimit",on.candidateLimit)}}function Sn(t){if(!t||typeof t!="object")return null;const s="data"in t?t.data:void 0;if(s&&typeof s.error=="string")return s.error;if("message"in t&&typeof t.message=="string"){const n=t.message;if(n==="INTERNAL"||n.startsWith("REACTION_")||n.startsWith("STT_")||n.startsWith("MEDIA_"))return n}return null}function Fx(t){var n;if(!t||typeof t!="object"||!("data"in t))return[];const s=(n=t.data)==null?void 0:n.issues;return Array.isArray(s)?s.filter(r=>!!r&&typeof r=="object"&&typeof r.field=="string"&&typeof r.code=="string"):[]}function Bx(t,s,n){const r=Sn(s);return r==="REACTION_RULE_INVALID"?t("reactionErrorRuleInvalid"):r==="REACTION_RULE_MISSING"?t("reactionErrorRuleMissing"):r==="REACTION_RULE_CHANGED"?t("reactionErrorRuleChanged"):r==="REACTION_SWITCH_INVALID"?t("reactionErrorSwitchInvalid"):r==="INTERNAL"?t("reactionErrorInternal"):je(t,s,n)}function Ux(t,s,n){const r=Ic(s).split(".")[0];return t(n==="owner_unlinked"?"reactionDestOwnerDisabled":r==="chatJid"&&n==="required"?"reactionChatRequired":r==="emoji"&&n==="required"?"reactionEmojiRequired":n==="voice_only"?"reactionIssueVoiceOnly":n==="too_many"?r==="senders"?"reactionIssueSendersTooMany":"reactionIssueTooMany":n==="duplicate"?r==="senders"?"reactionIssueSendersDuplicate":"reactionIssueDuplicate":n==="unknown_field"?"reactionIssueUnknownField":r==="chatJid"?"reactionIssueChatJidInvalid":r==="priority"?"reactionIssuePriorityInvalid":r==="emoji"?"reactionIssueEmojiInvalid":r==="transitions"?"reactionIssueTransitionsInvalid":r==="originalTypes"?"reactionIssueOriginalTypesInvalid":r==="senders"?"reactionIssueSendersInvalid":r==="action"?"reactionIssueActionInvalid":r==="destination"?"reactionIssueDestinationInvalid":r==="version"?"reactionIssueVersionInvalid":r==="body"?"reactionIssueBodyInvalid":"reactionIssueInvalid")}function zc(t,s){return t(s==="add"?"reactionTransitionAdd":s==="change"?"reactionTransitionChange":"reactionTransitionRemove")}function Oc(t,s){return t(s==="text"?"reactionTypeText":s==="voice"?"reactionTypeVoice":s==="audio"?"reactionTypeAudio":s==="image"?"reactionTypeImage":s==="video"?"reactionTypeVideo":s==="document"?"reactionTypeDocument":"reactionTypeSticker")}function Fc(t,s){return t(s==="any"?"reactionRoleAny":s==="owner"?"reactionRoleOwner":s==="bot_admin"?"reactionRoleBotAdmin":s==="group_admin"?"reactionRoleGroupAdmin":"reactionRoleMember")}function $x(t,s){return s==="chatJid"?t("reactionChat"):s==="emoji"?t("reactionEmoji"):s==="action"?t("reactionAction"):s==="originalTypes"?t("reactionTypes"):s==="senders"?t("reactionSendersRole"):s==="transitions"?t("reactionTransitions"):s==="destination"?t("reactionDestination"):`${t("reactionAdvanced")} (${t("reactionPriority")})`}function Kx(t,s){const n={role:Fc(t,s.role),emoji:s.emoji||t("reactionPreviewEmoji"),transitions:s.transitions.map(r=>zc(t,r)).join(t("reactionListJoin"))||t("reactionTransitions"),types:s.action!=="stt"&&Xt.every(r=>s.originalTypes.includes(r))?t("reactionPreviewAllTypes"):(s.action==="stt"?["voice"]:s.originalTypes).map(r=>Oc(t,r)).join(t("reactionListJoin"))||t("reactionTypes"),chat:s.chatName.trim()||t("reactionPreviewChat"),action:s.action==="stt"?t("reactionPreviewActionStt"):s.action==="ping"?t("reactionPreviewActionPing"):t("reactionPreviewActionUnset"),destination:s.destination==="owner_private"?t("reactionDestOwner"):t("reactionDestSame"),n:s.senderIds.length};return de(s.senderIds.length>0?t("reactionPreviewWithPeople"):t("reactionPreview"),n)}function Wi(t,s){return t.includes(s)?t.filter(n=>n!==s):[...t,s]}function qt(...t){const s=t.filter(n=>!!n);return s.length?s.join(" "):void 0}const Hx=({open:t,rule:s,names:n,ownerLinked:r,onClose:a,onSaved:i,onConflict:l})=>{const{t:d}=me(),c=d,m=(s==null?void 0:s.id)??null,u=o.useRef(t);u.current=t;const p=o.useRef(s);p.current=s;const h=o.useRef(null),g=o.useRef(0),x=o.useRef(!1),[f,k]=o.useState(Vi),[N,w]=o.useState(!1),[S,b]=o.useState(!1),[R,j]=o.useState(!1),[y,_]=o.useState(null),[A,D]=o.useState({});o.useEffect(()=>{if(!t){g.current+=1,h.current=null;return}g.current+=1;const C=p.current??null;return h.current=C,k(C?Ex(C):Vi()),w(!1),b(!1),j(x.current),_(null),D({}),()=>{g.current+=1}},[t,m]);const I=(C,O)=>{k(Y=>({...Y,[C]:typeof O=="function"?O(Y[C]):O})),_(null);const J=C==="chatJid"||C==="chatName"?"chatJid":C==="senderIds"||C==="role"?"senders":C==="originalTypes"?"originalTypes":String(C);D(Y=>{const L={...Y};return delete L[J],C==="action"&&delete L.originalTypes,L})},F=C=>{const O={},J=[];for(const Y of C){const L=Ux(c,Y.field,Y.code),v=zx(Y.field);v==="form"?J.push(L):O[v]=O[v]?`${O[v]} ${L}`:L}D(O),_(J.length?J.join(" "):null)},E=async C=>{var oe,ye,fe,we;if(C.preventDefault(),x.current)return;const O=Rx(f);if(f.destination==="owner_private"&&!r&&((fe=(ye=(oe=h.current)==null?void 0:oe.definition)==null?void 0:ye.destination)==null?void 0:fe.mode)!=="owner_private"&&O.push({field:"definition.destination",code:"owner_unlinked"}),F(O),O.length)return;const J=Ax({...f,priority:qi(f.priority)}),Y=++g.current,L=h.current,v=(L==null?void 0:L.id)??null,T=L==null?void 0:L.revision,te=()=>{var Le;return Y!==g.current||!u.current||(((Le=h.current)==null?void 0:Le.id)??null)!==v};x.current=!0,j(!0),_(null);try{const Le=await Q.checkReactionRule(J);if(te())return;if((we=Le.issues)!=null&&we.length){F(Le.issues);return}const ee=v?await Q.updateReactionRule(v,{...J,revision:T}):await Q.createReactionRule(J);if(te())return;if(!ee.rule){_(c("reactionSaveFailed"));return}i(ee.rule,!!v)}catch(Le){if(te())return;if(Sn(Le)==="REACTION_RULE_CHANGED"){_(c("reactionEditConflict")),l();return}const ee=Fx(Le);if(ee.length){F(ee);return}_(Bx(c,Le,"reactionSaveFailed"))}finally{x.current=!1,u.current&&j(!1)}},P=C=>{if(!f.senderIds.includes(C)){if(f.senderIds.length>=Or){D(O=>({...O,senders:c("reactionTooManySenders")}));return}I("senderIds",O=>O.includes(C)?O:[...O,C])}},M=f.emoji&&!fr(f.emoji)?c("reactionEmojiInvalid"):A.emoji,$={...A,...M?{emoji:M}:{}},G=Object.keys($).map(C=>$x(c,C)),ne=[y,G.length?de(c("reactionFixSections"),{sections:G.join(c("reactionListJoin"))}):null].filter(Boolean).join(" "),se=Xt.every(C=>f.originalTypes.includes(C)),V=Ua(f.chatJid,n)||f.chatName||c("reactionPreviewChat"),q=()=>{x.current||a()};return e.jsxs(e.Fragment,{children:[e.jsx(Ye,{isOpen:t,onClose:q,title:c(s?"reactionEditTitle":"reactionNewTitle"),variant:"mobileFullscreen",maxWidth:"40rem",footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:q,disabled:R,children:c("reactionCancel")}),e.jsx(U,{variant:"primary",type:"submit",form:"reaction-rule-form",loading:R,children:c("reactionSave")})]}),children:e.jsxs("form",{id:"reaction-rule-form",className:"flex flex-col gap-4","aria-busy":R,onSubmit:C=>void E(C),children:[ne&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:ne}),e.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"rx-chat-heading",children:[e.jsxs("h3",{id:"rx-chat-heading",className:"text-sm font-bold text-text-main",children:["1. ",c("reactionChat")]}),e.jsxs(re,{htmlFor:"rx-chat",error:A.chatJid,children:[f.chatJid&&e.jsx(ze,{className:"text-sm font-semibold",children:V}),e.jsx(U,{id:"rx-chat",type:"button",variant:"secondary","aria-invalid":A.chatJid?!0:void 0,"aria-describedby":qt(A.chatJid?"rx-chat-message":void 0),onClick:()=>w(!0),children:f.chatJid?c("reactionChangeChat"):c("reactionChooseChat")})]})]}),e.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"rx-emoji-heading",children:[e.jsxs("h3",{id:"rx-emoji-heading",className:"text-sm font-bold text-text-main",children:["2. ",c("reactionEmoji")]}),e.jsxs(re,{htmlFor:"rx-emoji",error:M,description:c("reactionEmojiHint"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[fr(f.emoji)&&e.jsx("span",{className:"text-4xl leading-none","aria-hidden":!0,children:e.jsx(ze,{children:f.emoji})}),e.jsx(be,{id:"rx-emoji",name:"emoji",dir:"auto",value:f.emoji,"aria-labelledby":"rx-emoji-heading","aria-invalid":M?!0:void 0,"aria-describedby":"rx-emoji-message",onChange:C=>I("emoji",C.target.value)})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:wx.map(C=>e.jsx(xe,{label:de(c("reactionPickEmoji"),{emoji:C}),pressed:f.emoji===C,icon:e.jsx("span",{className:"text-lg leading-none",children:C}),onClick:()=>I("emoji",C)},C))})]})]}),e.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"rx-action-heading",children:[e.jsxs("h3",{id:"rx-action-heading",className:"text-sm font-bold text-text-main",children:["3. ",c("reactionAction")]}),e.jsx(re,{htmlFor:"rx-action",error:A.action,children:e.jsx("fieldset",{id:"rx-action",className:"min-w-0","aria-labelledby":"rx-action-heading","aria-invalid":A.action?!0:void 0,"aria-describedby":qt(A.action?"rx-action-message":void 0),children:e.jsx(Rt,{"aria-label":c("reactionAction"),className:"flex w-full flex-wrap",value:f.action,onChange:C=>I("action",C),options:[{value:"stt",label:c("reactionActionStt")},{value:"ping",label:c("reactionActionPing")}]})})})]}),e.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"rx-types-heading",children:[e.jsxs("h3",{id:"rx-types-heading",className:"text-sm font-bold text-text-main",children:["4. ",c("reactionTypes")]}),e.jsx(re,{htmlFor:"rx-types",error:A.originalTypes,children:f.action==="stt"?e.jsx("p",{id:"rx-types",className:"text-sm text-muted",children:c("reactionSttVoiceOnly")}):e.jsxs("fieldset",{id:"rx-types",className:"grid min-w-0 grid-cols-2 gap-x-3","aria-labelledby":"rx-types-heading","aria-describedby":qt(A.originalTypes?"rx-types-message":void 0),children:[e.jsx("div",{className:"col-span-2",children:e.jsx(ht,{label:c("reactionAllTypes"),checked:se,ref:C=>{C&&(C.indeterminate=!se&&f.originalTypes.length>0)},"aria-invalid":A.originalTypes?!0:void 0,onChange:C=>I("originalTypes",C.target.checked?[...Xt]:[])})}),Xt.map(C=>e.jsx(ht,{label:Oc(c,C),checked:f.originalTypes.includes(C),"aria-invalid":A.originalTypes?!0:void 0,"aria-describedby":qt(A.originalTypes?"rx-types-message":void 0),onChange:()=>I("originalTypes",O=>Wi(O,C))},C))]})})]}),e.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"rx-senders-heading",children:[e.jsxs("h3",{id:"rx-senders-heading",className:"text-sm font-bold text-text-main",children:["5. ",c("reactionSendersRole")]}),e.jsx(re,{label:c("reactionRole"),htmlFor:"rx-role",children:e.jsx(Re,{id:"rx-role",value:f.role,"aria-invalid":A.senders?!0:void 0,"aria-describedby":qt(A.senders?"rx-senders-message":void 0),onChange:C=>I("role",C.target.value),children:Pc.map(C=>e.jsx("option",{value:C,children:Fc(c,C)},C))})}),e.jsxs(re,{label:c("reactionSendersIds"),htmlFor:"rx-senders",description:c("reactionSendersIdsHint"),error:A.senders,children:[f.senderIds.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:f.senderIds.map(C=>{const O=Ua(C,n)||c("reactionUnknownPerson");return e.jsx(Ks,{removeLabel:de(c("reactionRemoveSender"),{name:O}),onRemove:()=>I("senderIds",J=>J.filter(Y=>Y!==C)),children:e.jsx(ze,{children:O})},C)})}),e.jsx(U,{id:"rx-senders",type:"button",variant:"secondary","aria-invalid":A.senders?!0:void 0,"aria-describedby":"rx-senders-message",onClick:()=>b(!0),children:c("reactionChooseSenders")})]})]}),e.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"rx-transitions-heading",children:[e.jsxs("h3",{id:"rx-transitions-heading",className:"text-sm font-bold text-text-main",children:["6. ",c("reactionTransitions")]}),e.jsx(re,{htmlFor:"rx-transitions",error:A.transitions,children:e.jsx("fieldset",{id:"rx-transitions",className:"flex min-w-0 flex-col","aria-labelledby":"rx-transitions-heading","aria-describedby":qt(A.transitions?"rx-transitions-message":void 0),children:Tc.map(C=>e.jsx(ht,{label:zc(c,C),checked:f.transitions.includes(C),"aria-invalid":A.transitions?!0:void 0,onChange:()=>I("transitions",O=>Wi(O,C))},C))})})]}),e.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"rx-destination-heading",children:[e.jsxs("h3",{id:"rx-destination-heading",className:"text-sm font-bold text-text-main",children:["7. ",c("reactionDestination")]}),e.jsx(re,{htmlFor:"rx-destination",error:A.destination,children:e.jsx("fieldset",{id:"rx-destination",className:"min-w-0","aria-labelledby":"rx-destination-heading","aria-invalid":A.destination?!0:void 0,"aria-describedby":qt(A.destination?"rx-destination-message":void 0),children:e.jsx(st,{name:"rx-destination",value:f.destination,onChange:C=>{C==="owner_private"&&!r||I("destination",C)},options:[{value:"same_chat",label:c("reactionDestSame")},{value:"owner_private",label:c("reactionDestOwner"),description:r?void 0:c("reactionDestOwnerDisabled")}]})})})]}),e.jsx(is,{summary:e.jsxs("span",{className:"flex flex-col gap-1",children:[e.jsxs("span",{children:["8. ",c("reactionAdvanced")]}),A.priority&&e.jsx("span",{className:"text-xs text-danger",children:A.priority})]}),children:e.jsx(re,{label:c("reactionPriority"),htmlFor:"rx-priority",error:A.priority,description:c("reactionPriorityHint"),children:e.jsx(be,{id:"rx-priority",name:"priority",type:"number",min:0,max:1e3,step:1,technical:!0,value:Number.isFinite(f.priority)?f.priority:100,"aria-invalid":A.priority?!0:void 0,"aria-describedby":"rx-priority-message",onChange:C=>I("priority",qi(Number(C.target.value)))})})},`${t}-${m}`),e.jsx(ze,{as:"p",className:"text-sm text-muted",children:Kx(c,{...f,chatName:V})})]})}),e.jsx(es,{open:N,onClose:()=>w(!1),title:c("reactionChooseChat"),includeGroups:!0,selectedIds:f.chatJid?[f.chatJid]:[],emptyText:c("reactionNoChats"),onPick:C=>{k(O=>({...O,chatJid:C,chatName:Ua(C,n)})),D(O=>{if(!O.chatJid)return O;const J={...O};return delete J.chatJid,J}),w(!1),_(null)}}),e.jsx(es,{open:S,onClose:()=>b(!1),title:c("reactionChooseSenders"),includeGroups:!1,selectedIds:f.senderIds,emptyText:c("reactionNoContacts"),onPick:C=>P(C)})]})};function Fn(t,s,n){const r=Sn(s);return r==="REACTION_RULE_INVALID"?t("reactionErrorRuleInvalid"):r==="REACTION_RULE_MISSING"?t("reactionErrorRuleMissing"):r==="REACTION_RULE_CHANGED"?t("reactionErrorRuleChanged"):r==="REACTION_SWITCH_INVALID"?t("reactionErrorSwitchInvalid"):r==="INTERNAL"?t("reactionErrorInternal"):je(t,s,n)}function Vx(t,s){switch(s){case"READY":return{label:t("reactionStatusReady"),hint:t("reactionStatusReadyHint")};case"AUTOMATION_OFF":return{label:t("reactionStatusAutomationOff"),hint:t("reactionStatusAutomationOffHint")};case"RULE_OFF":return{label:t("reactionStatusRuleOff"),hint:t("reactionStatusRuleOffHint")};case"RULE_INVALID":return{label:t("reactionStatusRuleInvalid"),hint:t("reactionStatusRuleInvalidHint")};case"NOT_CONNECTED":return{label:t("reactionStatusNotConnected"),hint:t("reactionStatusNotConnectedHint")};case"ACTION_DISABLED":return{label:t("reactionStatusActionDisabled"),hint:t("reactionStatusActionDisabledHint")};case"STT_DISABLED":return{label:t("reactionStatusSttDisabled"),hint:t("reactionStatusSttDisabledHint")};case"STT_KEY_MISSING":return{label:t("reactionStatusSttKeyMissing"),hint:t("reactionStatusSttKeyMissingHint")};case"OWNER_NOT_LINKED":return{label:t("reactionStatusOwnerNotLinked"),hint:t("reactionStatusOwnerNotLinkedHint")};case"CANDIDATE_LIMIT":return{label:t("reactionStatusCandidateLimit"),hint:t("reactionStatusCandidateLimitHint")};default:return{label:t("reactionStatusUnknown"),hint:t("reactionStatusUnknown")}}}function qx(t,s){switch(s){case"DELIVERED":return t("reactionOutcomeDelivered");case"NO_MATCH":return t("reactionOutcomeNoMatch");case"BUSY":return t("reactionOutcomeBusy");case"ACTION_FAILED":return t("reactionOutcomeActionFailed");case"RATE_LIMIT":return t("reactionOutcomeRateLimit");case"CAPACITY":return t("reactionOutcomeCapacity");case"EVENT_MISSING":return t("reactionOutcomeEventMissing");case"DUPLICATE":return t("reactionOutcomeDuplicate");case"REACTION_CANCELLED":return t("reactionOutcomeReactionCancelled");case"REACTION_TIMEOUT":return t("reactionOutcomeReactionTimeout");case"REACTION_STALE":return t("reactionOutcomeReactionStale");case"REACTION_INACCESSIBLE":return t("reactionOutcomeReactionInaccessible");case"REACTION_FORBIDDEN":return t("reactionOutcomeReactionForbidden");case"REACTION_STT_DISABLED":return t("reactionOutcomeReactionSttDisabled");case"REACTION_DELIVERY_REFUSED":return t("reactionOutcomeReactionDeliveryRefused");case"REACTION_CAPACITY":return t("reactionOutcomeReactionCapacity");case"REACTION_IDENTITY_INVALID":return t("reactionOutcomeReactionIdentityInvalid");case"REACTION_VOICE_REQUIRED":return t("reactionOutcomeReactionVoiceRequired");case"STT_KEY_REQUIRED":return t("reactionOutcomeSttKeyRequired");case"STT_OUTPUT_INVALID":return t("reactionOutcomeSttOutputInvalid");case"MEDIA_AUDIO_INVALID":return t("reactionOutcomeMediaAudioInvalid");case"MEDIA_TOO_LARGE":return t("reactionOutcomeMediaTooLarge");case"MEDIA_NOT_AVAILABLE":return t("reactionOutcomeMediaNotAvailable");case"MEDIA_URL_INVALID":return t("reactionOutcomeMediaUrlInvalid");default:return t(s?"reactionStatusUnknown":"reactionNeverRan")}}function Wx(t,s){return s==="stt"?t("reactionActionStt"):s==="ping"?t("reactionActionPing"):"?"}function Gx(t,s){return s==="owner_private"?t("reactionDestOwner"):s==="same_chat"?t("reactionDestSame"):"?"}function Jx(t,s){return s==="any"?t("reactionRoleAny"):s==="owner"?t("reactionRoleOwner"):s==="bot_admin"?t("reactionRoleBotAdmin"):s==="group_admin"?t("reactionRoleGroupAdmin"):s==="member"?t("reactionRoleMember"):"?"}function Yx(t){return`${Dc(t).emoji} ${t.chatName||t.chatJid}`.trim()}const Qx=()=>{const{t,language:s}=me(),n=t,{toast:r}=qe(),[a,i]=o.useState([]),[l,d]=o.useState(!1),[c,m]=o.useState(!1),[u,p]=o.useState(!0),[h,g]=o.useState(!1),[x,f]=o.useState(""),[k,N]=o.useState(()=>new Map),[w,S]=o.useState(!0),[b,R]=o.useState(null),[j,y]=o.useState(0),[_,A]=o.useState("priority"),[D,I]=o.useState(Fa),[F,E]=o.useState(!1),[P,M]=o.useState(null),[$,G]=o.useState(null),[ne,se]=o.useState(!1),V=o.useRef(new Set),[q,C]=o.useState(()=>new Set),O=o.useRef(0),J=o.useRef(0),Y=o.useRef(!0),L=o.useRef(0),v=o.useRef("0"),T=o.useRef(async()=>"discarded"),te=o.useRef(n),oe=o.useRef(r);te.current=n,oe.current=r;const ye=o.useCallback(K=>{var $e,Be,z,B;const pe=($e=K.automation)==null?void 0:$e.revision;typeof pe=="string"&&pe&&(v.current=pe),d(!!((Be=K.automation)!=null&&Be.enabled)),p(!!((z=K.connection)!=null&&z.connected)),g(!!((B=K.owner)!=null&&B.linked));const Ae=Ox(K.limits);f(de(n("reactionLimits"),{perReactor:Ae.perReactor,perChat:Ae.perChat,perRule:Ae.perRule,windowSeconds:Math.max(1,Math.round(Ae.windowMs/1e3)),globalJobs:Ae.globalJobs,candidateLimit:Ae.candidateLimit}));const Fe=K.rules??[];i(Z=>Fe.map(ie=>{if(!V.current.has(ie.id))return ie;const Ne=Z.find(Qe=>Qe.id===ie.id);return Ne?{...ie,enabled:Ne.enabled}:ie})),J.current+=1},[n]);o.useEffect(()=>{const K=++O.current,pe=L.current;return S(!0),Q.getReactions().then(Ae=>{!Y.current||O.current!==K||(ye(Ae),R(null),L.current!==pe&&(S(!1),T.current()))}).catch(Ae=>{if(!Y.current||O.current!==K)return;const Fe=Fn(n,Ae,"reactionLoadFailed");R(Fe),r(Fe,"error")}).finally(()=>{Y.current&&O.current===K&&S(!1)}),()=>{O.current+=1}},[j,n,r,ye]),o.useEffect(()=>(Y.current=!0,()=>{Y.current=!1}),[]);const fe=o.useCallback(async()=>{const K=++O.current,pe=L.current;try{const Ae=await Q.getReactions();return!Y.current||O.current!==K||L.current!==pe?"discarded":(ye(Ae),R(null),Ae)}catch{return!Y.current||O.current!==K||L.current!==pe?"discarded":"failed"}},[ye]);T.current=fe;const we=o.useMemo(()=>Dx({send:(K,pe)=>Q.setReactionAutomation(K,pe),revision:()=>v.current,remember:K=>{v.current=K},reconcile:()=>T.current(),show:K=>d(K),busy:K=>m(K),failed:K=>{const pe=te.current;oe.current(Fn(pe,K,"reactionSwitchFailed"),"error")},conflict:()=>{oe.current(te.current("reactionAutomationChanged"),"warning")},alive:()=>Y.current,written:()=>{L.current+=1}}),[]);o.useEffect(()=>{if(w)return;const K=()=>{document.visibilityState!=="hidden"&&fe()};window.addEventListener("focus",K),document.addEventListener("visibilitychange",K);const pe=window.setInterval(K,3e4);return()=>{window.removeEventListener("focus",K),document.removeEventListener("visibilitychange",K),window.clearInterval(pe)}},[w,fe]),o.useEffect(()=>{let K=!1;return Q.getRecipients().then(pe=>{if(K)return;const Ae=new Map;for(const Fe of pe.recipients)Fe.name&&Ae.set(Fe.id,Fe.name);N(Ae)}).catch(pe=>{K||r(Fn(n,pe,"reactionRecipientsFailed"),"error")}),()=>{K=!0}},[n,r]);const Le=o.useMemo(()=>Mx(a.filter(K=>Lx(K,D)),_,s),[a,D,_,s]),ee=`${_}|${D.status}|${D.action}`,{page:le,pageCount:Se,pageItems:X,setPage:ve,total:ue}=An(Le,20,ee),ke=P?a.find(K=>K.id===P.id)??P:null,Me=async()=>{r(n("reactionErrorRuleChanged"),"warning"),G(null),await fe()},Te=async(K,pe)=>{if(V.current.has(K.id))return;L.current+=1;const Ae=L.current,Fe=J.current,$e=K.enabled;V.current.add(K.id),C(Be=>{const z=new Set(Be);return z.add(K.id),z}),i(Be=>Be.map(z=>z.id===K.id?{...z,enabled:pe}:z));try{const Be=await Q.setReactionRuleEnabled(K.id,{revision:K.revision,enabled:pe});i(z=>z.map(B=>B.id===K.id?Be.rule:B))}catch(Be){V.current.delete(K.id),await fe()==="failed"&&L.current===Ae&&J.current===Fe&&i(B=>B.map(Z=>Z.id===K.id?{...Z,enabled:$e}:Z)),Sn(Be)==="REACTION_RULE_CHANGED"?r(n("reactionErrorRuleChanged"),"warning"):r(Fn(n,Be,"reactionToggleFailed"),"error")}finally{L.current+=1,V.current.delete(K.id),C(Be=>{if(!Be.has(K.id))return Be;const z=new Set(Be);return z.delete(K.id),z})}},ae=async()=>{if($){L.current+=1,se(!0);try{await Q.deleteReactionRule($.id,$.revision),i(K=>K.filter(pe=>pe.id!==$.id)),r(n("reactionDeleted"),"success"),G(null)}catch(K){Sn(K)==="REACTION_RULE_CHANGED"?(r(n("reactionErrorRuleChanged"),"warning"),G(null),await fe()):r(Fn(n,K,"ruleDeleteError"),"error")}finally{L.current+=1,se(!1)}}};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Kt,{icon:e.jsx(ks,{size:24}),title:n("reaction"),description:n("reactionSubtitle"),actions:a.length>0?e.jsx(U,{variant:"primary",icon:e.jsx(_t,{size:16}),onClick:()=>{M(null),E(!0)},children:n("reactionNew")}):void 0}),!w&&e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx(Je,{checked:l,"aria-busy":c,onChange:K=>void we(K,l),label:n("reactionAutomation"),description:n("reactionAutomationHint")}),x?e.jsx("p",{className:"text-xs text-muted",children:x}):null,!u&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ce,{tone:"warn",children:n("reactionStatusNotConnected")}),e.jsx(rr,{label:n("reactionStatusNotConnected"),content:n("reactionStatusNotConnectedHint"),children:e.jsx(nr,{size:16})})]})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&!b&&a.length>0&&e.jsxs(It,{children:[e.jsx(Rn,{label:n("reactionSort"),value:_,onChange:A,options:[{value:"priority",label:n("reactionSortPriority")},{value:"chat",label:n("reactionSortChat")},{value:"recent",label:n("reactionSortRecent")}]}),e.jsxs(zt,{label:n("reactionFilter"),resetLabel:n("reactionReset"),activeCount:Ix(D),onReset:()=>I(Fa),children:[e.jsx(st,{label:n("reactionFilterStatus"),name:"rx-status",value:D.status,onChange:K=>I(pe=>({...pe,status:K})),options:[{value:"any",label:n("reactionStatusAny")},{value:"ready",label:n("reactionFilterReady")},{value:"off",label:n("reactionFilterOff")},{value:"attention",label:n("reactionFilterAttention")}]}),e.jsx(st,{label:n("reactionFilterAction"),name:"rx-action",value:D.action,onChange:K=>I(pe=>({...pe,action:K})),options:[{value:"any",label:n("reactionStatusAny")},{value:"stt",label:n("reactionActionStt")},{value:"ping",label:n("reactionActionPing")}]})]})]}),w&&e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2","aria-busy":"true",children:["s1","s2","s3","s4"].map(K=>e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx(Ve,{className:"h-5 w-40"}),e.jsx(Ve,{className:"h-6 w-full"}),e.jsx(Ve,{className:"h-8 w-24"})]},K))}),!w&&b&&a.length===0&&e.jsx(Pe,{kind:"error",icon:e.jsx(ks,{size:28}),description:b,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>y(K=>K+1),children:n("reactionRetry")})}),!w&&!b&&a.length===0&&e.jsx(Pe,{kind:"empty",icon:e.jsx(ks,{size:28}),title:n("reactionEmptyTitle"),description:n("reactionEmptyBody"),action:e.jsx(U,{variant:"primary",icon:e.jsx(_t,{size:16}),onClick:()=>{M(null),E(!0)},children:n("reactionNew")})}),!w&&!b&&a.length>0&&Le.length===0&&e.jsx(Pe,{kind:"no-results",title:n("reactionNoResults"),action:e.jsx(U,{variant:"secondary",onClick:()=>I(Fa),children:n("reactionClearFilters")})}),!w&&!b&&Le.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:X.map(K=>{var z,B;const pe=Array.isArray(K.statuses)?K.statuses:[],Ae=((z=K.runtime)==null?void 0:z.lastCode)??null,Fe=((B=K.runtime)==null?void 0:B.lastAt)??null,$e=Dc(K),Be=Array.isArray(K.overlaps)?K.overlaps:[];return e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-2xl leading-none","aria-hidden":!0,children:$e.emoji}),e.jsx(ze,{as:"strong",className:"min-w-0 flex-1 text-sm font-bold",children:K.chatName||K.chatJid}),e.jsx(Je,{checked:K.enabled,disabled:q.has(K.id),"aria-label":n("reactionEnabled"),onChange:Z=>void Te(K,Z)}),e.jsxs(mt,{label:n("reactionMore"),children:[e.jsx(_e,{icon:e.jsx(as,{size:16}),onSelect:()=>{M(K),E(!0)},children:n("reactionEdit")}),e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>G(K),children:n("reactionDelete")})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(Ce,{children:Wx(n,$e.action)}),e.jsx(Ce,{children:Gx(n,$e.destination)}),e.jsx(Ce,{children:Jx(n,$e.role)}),e.jsx(Ce,{children:de(n("reactionPriorityBadge"),{n:K.priority})})]}),pe.length>0&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:pe.map(Z=>{const ie=Vx(n,Z);return e.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[e.jsx(xn,{tone:_x(Z),children:ie.label}),e.jsx(rr,{label:ie.label,content:ie.hint,children:e.jsx(nr,{size:16})})]},Z)})}),Be.length>0&&e.jsx("p",{className:"text-xs text-muted",children:de(n("reactionOverlaps"),{n:Be.length})}),e.jsx("p",{className:"text-xs text-muted",children:Ae?e.jsxs(e.Fragment,{children:[n("reactionLastOutcome")," ",qx(n,Ae),Fe?e.jsxs(e.Fragment,{children:[" ",e.jsx(jn,{value:Fe,className:"text-xs text-muted"})]}):null]}):n("reactionNeverRan")})]},K.id)})}),e.jsx(Ht,{page:le,pageCount:Se,total:ue,onPageChange:ve})]})]}),e.jsx(Hx,{open:F,rule:ke,names:k,ownerLinked:h,onClose:()=>E(!1),onConflict:()=>void Me(),onSaved:(K,pe)=>{L.current+=1,i(Ae=>{const Fe=Ae.findIndex(Be=>Be.id===K.id);if(Fe===-1)return[K,...Ae];const $e=Ae.slice();return $e[Fe]=K,$e}),r(n(pe?"reactionEditedOff":"reactionCreated"),"success"),E(!1)}}),e.jsx(ut,{isOpen:$!==null,onClose:()=>G(null),onConfirm:()=>void ae(),title:n("reactionDeleteTitle"),description:e.jsx("span",{dir:"auto",children:de(n("reactionDeleteBody"),{name:$?Yx($):""})}),confirmLabel:n("reactionDelete"),cancelLabel:n("reactionCancel"),loading:ne})]})},Xx=["weekdaySun","weekdayMon","weekdayTue","weekdayWed","weekdayThu","weekdayFri","weekdaySat"],Zx=["schedulesWeekdaySunday","schedulesWeekdayMonday","schedulesWeekdayTuesday","schedulesWeekdayWednesday","schedulesWeekdayThursday","schedulesWeekdayFriday","schedulesWeekdaySaturday"],Bc=[1,2,3,4,6,8,12];function ep(){const t=window.LevixHost;return!!(t&&typeof t.pickContact=="function")}function tp(t){let s=String(t||"").replace(/\D/g,"");return s.startsWith("00")&&(s=s.slice(2)),s.length<8||s.length>15?null:`${s}@s.whatsapp.net`}function Bn(t){const s=String(t||"").trim();return!s||s.includes("@")||/^\d{8,}$/.test(s)?null:s}function mn(t){return String(t).padStart(2,"0")}function np(t,s){const n=t.map(a=>s(Zx[a]));if(n.length<=1)return n[0]||"";const r=s("schedulesWeekdayAnd");return n.length===2?`${n[0]}${r}${n[1]}`:`${n.slice(0,-1).join(s("schedulesWeekdaySep"))}${r}${n[n.length-1]}`}function $a(t,s){return t.whenByLocale?bn(t.whenByLocale,s):bn({en:t.when||void 0,ar:t.whenAr||void 0},s)}function Gi(t,s){return s==="image"?t("mediaKindImage"):s==="video"?t("mediaKindVideo"):s==="audio"?t("mediaKindAudio"):s==="document"?t("mediaKindDocument"):s}const Lt=({label:t,children:s})=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-3",children:[e.jsx("span",{className:"sm:w-32 shrink-0 font-bold text-muted",children:t}),e.jsx("span",{className:"min-w-0",children:s})]});function sp(t,s,n,r,a,i,l,d){const c=/^\d{1,2}:\d{2}$/.test(s),m=l||"UTC";if(t==="hourly")return!Number.isInteger(a)||!Bc.includes(a)||!Number.isInteger(i)||i<0||i>59?null:a===1?de(d("schedulesHourlyOne"),{minute:i,zone:m}):a===2?de(d("schedulesHourlyTwo"),{minute:i,zone:m}):a<=10?de(d("schedulesHourlyFew"),{hours:a,minute:i,zone:m}):de(d("schedulesHourlyMany"),{hours:a,minute:i,zone:m});if(!c)return null;const[u,p]=s.split(":").map(Number);if(u>23||p>59)return null;const h=`${mn(u)}:${mn(p)}`;if(t==="daily")return de(d("schedulesDaily"),{time:h,zone:m});if(t==="weekly"){const g=[...new Set(n.filter(x=>x>=0&&x<=6))].sort((x,f)=>x-f);return g.length?de(d("schedulesWeekly"),{days:np(g,d),time:h,zone:m}):null}return t==="monthly"?!Number.isInteger(r)||r<1||r>31?null:de(d("schedulesMonthly"),{day:r,time:h,zone:m}):null}const Ka={type:"any",delivery:"any",media:"any"};function gr(t){return{id:t.targetJid,name:t.targetLabel,type:t.targetKind==="group"?"group":"contact",phone:t.phone||t.targetPhone,savedName:t.savedName,pushName:t.pushName,nameSource:t.targetNameSource,targetJid:t.targetJid,targetLabel:t.targetLabel,targetKind:t.targetKind,targetPhone:t.targetPhone,targetNameSource:t.targetNameSource}}function ap(t,s,n){const r=s.trim().toLowerCase();if(r){const a=Mr(gr(t),s),i=[t.message,t.when,t.whenAr,...t.whenByLocale?Object.values(t.whenByLocale):[]].filter(Boolean).join(" ").toLowerCase();if(!a&&!i.includes(r))return!1}return!(n.type!=="any"&&t.type!==n.type||n.delivery==="failed"&&t.lastDeliveryStatus!=="failed"||n.delivery==="active"&&t.lastDeliveryStatus==="failed"||n.media==="with"&&!t.media||n.media==="without"&&t.media)}function rp(t,s,n){const r=[...t],a=(i,l)=>i.parts.title.localeCompare(l.parts.title,n,{sensitivity:"base"})||i.parts.subtitle.localeCompare(l.parts.subtitle,n,{sensitivity:"base"});if(s==="oldest")r.sort((i,l)=>(i.schedule.createdAt??0)-(l.schedule.createdAt??0)||a(i,l));else if(s==="target")r.sort(a);else if(s==="status"){const i=l=>l.schedule.lastDeliveryStatus==="failed"?0:1;r.sort((l,d)=>i(l)-i(d)||(d.schedule.createdAt??0)-(l.schedule.createdAt??0)||a(l,d))}else r.sort((i,l)=>(l.schedule.createdAt??0)-(i.schedule.createdAt??0)||a(i,l));return r}function Un({parts:t,kindLabel:s,showIcon:n=!0,showKind:r=!1,titleClass:a="text-sm font-semibold"}){const i=t.kind==="group"?En:Lr,l=t.kind==="group"?"bg-brand-blue/10 text-brand-cyan":"bg-ok/10 text-ok",d=t.title.startsWith("+");return e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[n?e.jsx("span",{className:`flex size-9 shrink-0 items-center justify-center rounded-xl ${l}`,children:e.jsx(i,{size:16,"aria-hidden":!0})}):null,e.jsxs("span",{className:"min-w-0",children:[e.jsx(ze,{lines:1,dir:d?"ltr":"auto",className:`block text-text-main ${a}`,children:t.title}),t.subtitle?e.jsx(Dr,{text:t.subtitle,className:"block truncate text-[11px] text-muted"}):null,r&&s?e.jsx("span",{className:"block text-[11px] font-medium text-muted",children:s}):null]})]})}const ip=({isConnected:t=!1,onNavigate:s})=>{var Br;const{t:n,language:r}=me(),{toast:a}=qe(),[i,l]=o.useState([]),[d,c]=o.useState("UTC"),[m,u]=o.useState(!0),[p,h]=o.useState(null),[g,x]=o.useState(0),[f,k]=o.useState(""),[N,w]=o.useState("newest"),[S,b]=o.useState(Ka),[R,j]=o.useState([]),[y,_]=o.useState(!1),[A,D]=o.useState(null),[I,F]=o.useState(""),[E,P]=o.useState(!1),[M,$]=o.useState(""),[G,ne]=o.useState("recurring"),[se,V]=o.useState("daily"),[q,C]=o.useState("09:00"),[O,J]=o.useState([1]),[Y,L]=o.useState(1),[v,T]=o.useState(1),[te,oe]=o.useState(0),[ye,fe]=o.useState(""),[we,Le]=o.useState(!1),[ee,le]=o.useState(null),[Se,X]=o.useState(null),ve=o.useRef(null),[ue,ke]=o.useState(null),Me=3,Te=20*1024*1024,ae=20,K=i.length>=Me,pe=rm(d||"UTC",At(r)),Ae=o.useMemo(()=>sp(se,q,O,Y,v,te,pe,n),[se,q,O,Y,v,te,pe,n]),Fe=o.useMemo(()=>{if(!ye)return null;const W=new Date(ye).getTime();return Number.isFinite(W)?im(W,d||"UTC",At(r)):null},[ye,d,r]),$e=async()=>{u(!0);try{const W=await Q.getSchedules();W!=null&&W.schedules&&(l(W.schedules),W.timezone&&c(W.timezone)),h(null)}catch(W){const Ee=je(n,W,"schedulesLoadError");h(Ee),a(Ee,"error")}finally{u(!1)}},Be=async()=>{_(!0);try{const W=await Q.getRecipients();W!=null&&W.recipients&&j(W.recipients)}catch{}finally{_(!1)}};o.useEffect(()=>{$e(),t&&Be()},[t,g]);const z=o.useMemo(()=>{const W=i.filter(rt=>ap(rt,f,S)),Ee=pr(W.map(gr),rt=>n(rt),r),De=W.map((rt,Ft)=>({schedule:rt,parts:Ee[Ft]}));return rp(De,N,r)},[i,f,S,N,r,n]),B=`${f}|${N}|${S.type}|${S.delivery}|${S.media}`,{page:Z,pageCount:ie,pageItems:Ne,setPage:Qe,total:at}=An(z,20,B),Vt=(S.type!=="any"?1:0)+(S.delivery!=="any"?1:0)+(S.media!=="any"?1:0),jt=()=>{k(""),b(Ka)},Ln=async W=>{try{await Q.deleteSchedule(W),a(n("savedSuccessfully"),"success"),l(Ee=>Ee.filter(De=>De.id!==W))}catch(Ee){a(je(n,Ee,"scheduleDeleteError"),"error")}},Mn=async W=>{if(!t){a(n("schedulesRetryDisconnected"),"warning");return}try{await Q.retrySchedule(W),a(n("schedulesRetryTriggered"),"info"),$e()}catch(Ee){a(je(n,Ee,"scheduleRetryError"),"error")}},kt=async()=>{const W=window.LevixHost;if(!(W!=null&&W.pickContact)){a(n("schedulesPhoneBookAndroid"),"info");return}const Ee=await new Promise(Qs=>{var Ur;const Xs=ad=>{window.removeEventListener("levix-contact",Xs);const Dn=ad.detail;if(!(Dn!=null&&Dn.phone)){Qs(null);return}Qs({name:String(Dn.name||""),phone:String(Dn.phone)})};window.addEventListener("levix-contact",Xs);try{(Ur=W.pickContact)==null||Ur.call(W)}catch{window.removeEventListener("levix-contact",Xs),Qs(null)}});if(!Ee)return;const De=tp(Ee.phone);if(!De){a(n("schedulesInvalidNumber"),"error");return}const rt=`+${De.split("@")[0]}`,Ft=Bn(Ee.name);D({id:De,name:Ft||rt,savedName:Ft,pushName:null,phone:rt,type:"contact",nameSource:Ft?"saved":"phone"})},cs=()=>{D(null),F(""),$(""),ne("recurring"),V("daily"),C("09:00"),J([1]),L(1),T(1),oe(0),fe(""),le(null),X(null)},ds=()=>{le(null),X(null)},us=async()=>{try{const W=await xl();if(!W)return;if(W.size>Te){a(n("feedbackFileTooLarge").replace("{max}",String(ae)),"error");return}X(W)}catch(W){a(je(n,W,"attachmentError"),"error")}},Tn=()=>{if(!t){a(n("schedulesNeedConnection"),"warning");return}if(K){a(n("maxSchedulesReached"),"warning");return}cs(),P(!0),R.length||Be()},ms=W=>{J(Ee=>Ee.includes(W)?Ee.filter(De=>De!==W):[...Ee,W].sort((De,rt)=>De-rt))},Pn=()=>{const W=[];if(A||W.push(n("schedulesMissingRecipient")),!M.trim()&&!ee&&!Se&&W.push(n("schedulesMissingMessage")),G==="once"){const Ee=ye?new Date(ye).getTime():0;(!Ee||Ee<=Date.now())&&W.push(n("schedulesMissingWhen"))}else Ae||W.push(n("schedulesMissingRecurrence"));return W},xs=async()=>{const W=Pn();if(W.length){a(de(n("schedulesMissingHint"),{items:W.join(n("schedulesMissingSep"))}),"warning");return}if(!A)return;Le(!0);const Ee={targetJid:A.id,message:M.trim(),type:G};if(A.type==="contact"){const De=A.nameSource,rt=Bn(A.savedName)||(De==="push"?Bn(A.pushName)||Bn(A.name):null)||(De==="saved"?Bn(A.name):null);rt&&!rt.startsWith("+")&&(Ee.targetName=rt)}if(G==="recurring"){const De={kind:se};se==="hourly"?(De.everyHours=v,De.time=`00:${mn(te)}`):(De.time=q,se==="weekly"&&(De.weekdays=O),se==="monthly"&&(De.dayOfMonth=Y)),Ee.recurrence=De}else Ee.scheduledTime=new Date(ye).getTime();try{const De={};for(const[rt,Ft]of Object.entries(Ee))De[rt]=rt==="recurrence"?JSON.stringify(Ft):String(Ft);Se?await pl("/dashboard/api/schedules",De,Se.token,Te+1024*1024):ee?await Q.postMultipart("/schedules",De,ee):await Q.createSchedule(Ee),a(n("savedSuccessfully"),"success"),P(!1),cs(),$e()}catch(De){a(je(n,De,"scheduleCreateError"),"error")}finally{Le(!1)}},Ot=o.useMemo(()=>R.filter(W=>Mr(W,I)),[R,I]),H=o.useMemo(()=>pr(Ot,W=>n(W),r),[Ot,r,n]),ge=A?xr(A,W=>n(W),r):null,Ie=Pn(),Ze=G==="recurring"?Ae:Fe,Nt=(()=>{if(G==="once")return Fe;if(se==="hourly")return!Number.isInteger(te)||te<0||te>59?null:de(n("schedulesLocalTime"),{time:`00:${mn(te)}`,zone:pe});if(!/^\d{1,2}:\d{2}$/.test(q))return null;const[W,Ee]=q.split(":").map(Number);return W>23||Ee>59?null:de(n("schedulesLocalTime"),{time:`${mn(W)}:${mn(Ee)}`,zone:pe})})(),Ke=ue?((Br=z.find(W=>W.schedule.id===ue.id))==null?void 0:Br.parts)??xr(gr(ue),W=>n(W),r):null,an=W=>n(W==="group"?"recipientGroup":"recipientContact");return e.jsxs("div",{className:"flex flex-col gap-5 sm:gap-6",children:[!t&&e.jsxs("div",{className:"rounded-2xl border border-warn/30 bg-warn/10 p-4 sm:p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3.5",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-warn/20 text-warn flex items-center justify-center shrink-0",children:e.jsx(Wt,{size:22})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm sm:text-base font-bold text-warn",children:n("schedulesDisconnectedTitle")}),e.jsx("p",{className:"text-xs sm:text-sm text-text-main/80 mt-0.5",children:n("schedulesDisconnectedBody")})]})]}),e.jsx(U,{variant:"primary",className:"shrink-0",onClick:()=>s==null?void 0:s("connection"),children:n("schedulesGoToConnection")})]}),e.jsx(Kt,{icon:e.jsx(tr,{size:24}),title:e.jsxs("span",{className:"inline-flex flex-wrap items-center gap-2",children:[n("schedules"),e.jsxs(Ce,{tone:K?"warn":"info",children:[i.length," / ",Me," ",n("scheduledCount")]})]}),description:e.jsxs(e.Fragment,{children:[n("timezoneLabel"),":"," ",e.jsx("code",{className:"rounded border border-line bg-bg-soft px-1.5 py-0.5 font-mono font-semibold text-brand-cyan",children:d})," ","· ",n("headerSubtitle")]}),actions:i.length>0?e.jsx(U,{variant:"primary",size:"lg",className:"w-full sm:w-auto",icon:e.jsx(_t,{size:18}),onClick:Tn,disabled:K||!t,children:n(t?K?"limitReached":"scheduleNewMsg":"schedulesConnectionRequired")}):void 0}),!m&&!p&&i.length>0&&e.jsxs(It,{"data-tour":"schedules-list",children:[e.jsx(be,{type:"search",name:"schedule-search",autoComplete:"off",value:f,onChange:W=>k(W.target.value),placeholder:n("searchSchedules"),"aria-label":n("searchSchedules"),className:"min-w-48 flex-1"}),e.jsx(Rn,{label:n("sort"),value:N,onChange:w,options:[{value:"newest",label:n("sortNewest")},{value:"oldest",label:n("sortOldest")},{value:"target",label:n("thTarget")},{value:"status",label:n("thDelivery")}]}),e.jsxs(zt,{label:n("filter"),resetLabel:n("reset"),activeCount:Vt,onReset:()=>b(Ka),children:[e.jsx(st,{label:n("thType"),name:"schedule-type-filter",value:S.type,onChange:W=>b(Ee=>({...Ee,type:W})),options:[{value:"any",label:n("statusAny")},{value:"recurring",label:n("typeRecurring")},{value:"once",label:n("typeOnce")}]}),e.jsx(st,{label:n("thDelivery"),name:"schedule-delivery-filter",value:S.delivery,onChange:W=>b(Ee=>({...Ee,delivery:W})),options:[{value:"any",label:n("statusAny")},{value:"active",label:n("deliveryActive")},{value:"failed",label:n("deliveryFailed")}]}),e.jsx(st,{label:n("thMedia"),name:"schedule-media-filter",value:S.media,onChange:W=>b(Ee=>({...Ee,media:W})),options:[{value:"any",label:n("statusAny")},{value:"with",label:n("mediaWith")},{value:"without",label:n("mediaWithout")}]})]})]}),m&&e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2","aria-busy":"true",children:["s1","s2","s3","s4"].map(W=>e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ve,{className:"size-10 rounded-xl"}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[e.jsx(Ve,{className:"h-4 w-32"}),e.jsx(Ve,{className:"h-3 w-24"})]})]}),e.jsx(Ve,{className:"h-4 w-full"}),e.jsx(Ve,{className:"h-6 w-28"})]},W))}),!m&&p&&e.jsx(Pe,{kind:"error",icon:e.jsx(Wt,{size:28}),description:p,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>x(W=>W+1),children:n("retryLoad")})}),!m&&!p&&i.length===0&&e.jsx(Pe,{kind:"empty",icon:e.jsx(tr,{size:28}),text:n("noSchedules"),action:e.jsx(U,{variant:"primary",icon:e.jsx(_t,{size:16}),onClick:Tn,disabled:!t||K,children:n("scheduleNewMsg")})}),!m&&!p&&i.length>0&&z.length===0&&e.jsx(Pe,{kind:"no-results",action:e.jsx(U,{variant:"secondary",onClick:jt,children:n("clearFilters")})}),!m&&!p&&z.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 gap-3 md:hidden",children:Ne.map(({schedule:W,parts:Ee})=>e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("div",{className:`flex size-10 shrink-0 items-center justify-center rounded-xl ${Ee.kind==="group"?"bg-brand-blue/10 text-brand-cyan":"bg-ok/10 text-ok"}`,children:Ee.kind==="group"?e.jsx(En,{size:18}):e.jsx(Lr,{size:18})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(Un,{parts:Ee,showIcon:!1,titleClass:"text-sm font-bold"}),e.jsx("p",{className:"mt-0.5 truncate text-xs text-muted",dir:"auto",children:$a(W,r)||n("schedulesCustomWhen")})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[W.lastDeliveryStatus==="failed"&&e.jsx(xe,{label:n("retryDelivery"),icon:e.jsx(it,{size:16}),onClick:()=>{Mn(W.id)}}),e.jsx(xe,{label:n("scheduleDetails"),variant:"ghost",icon:e.jsx(ts,{size:16}),onClick:()=>ke(W)}),e.jsx(mt,{label:n("moreActions"),children:e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>{Ln(W.id)},children:n("delete")})})]})]}),e.jsx(ze,{lines:2,className:"text-sm text-text-main",children:W.media?`${W.media.fileName||""} ${W.message}`.trim():W.message||"—"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[W.media&&e.jsxs(Ce,{tone:"info",children:[e.jsx(Hn,{size:12}),Gi(n,W.media.kind)]}),e.jsx(Ce,{tone:W.type==="recurring"?"info":"neutral",children:W.type==="recurring"?n("typeRecurring"):n("typeOnce")}),e.jsxs(xn,{tone:W.lastDeliveryStatus==="failed"?"danger":W.status==="active"?"ok":"neutral",children:[W.lastDeliveryStatus==="failed"?e.jsx(Wt,{size:13}):e.jsx(Qt,{size:13}),e.jsx("span",{children:W.lastDeliveryStatus==="failed"?n("deliveryFailed"):W.status==="active"?n("deliveryActive"):W.status})]})]})]},W.id))}),e.jsx(he,{padded:!1,className:"hidden overflow-hidden md:block",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed border-collapse text-start text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-panel-raised border-b border-line text-xs font-bold text-muted uppercase tracking-wider",children:[e.jsx("th",{className:"w-[22%] px-4 py-4 text-start",children:n("thTarget")}),e.jsx("th",{className:"w-[30%] px-4 py-4 text-start",children:n("thMessage")}),e.jsx("th",{className:"w-[16%] px-4 py-4 text-start",children:n("thSchedule")}),e.jsx("th",{className:"w-[9%] px-4 py-4 text-start",children:n("thType")}),e.jsx("th",{className:"w-[13%] px-4 py-4 text-start",children:n("thDelivery")}),e.jsx("th",{className:"w-[10%] px-4 py-4 text-center",children:n("thActions")})]})}),e.jsx("tbody",{className:"divide-y divide-line/40",children:Ne.map(({schedule:W,parts:Ee})=>e.jsxs("tr",{onClick:()=>ke(W),className:"cursor-pointer transition-colors hover:bg-panel-hover/50",children:[e.jsx("td",{className:"px-4 py-4 text-xs text-text-main",children:e.jsx(Un,{parts:Ee,titleClass:"text-xs font-semibold sm:text-sm"})}),e.jsx("td",{className:"px-4 py-4 text-xs text-text-main sm:text-sm",children:e.jsx(ze,{lines:2,children:W.media?`${W.media.fileName||""} ${W.message}`.trim():W.message||"—"})}),e.jsx("td",{className:"px-4 py-4 text-xs text-muted",children:e.jsx("span",{dir:"auto",children:$a(W,r)||n("schedulesCustomWhen")})}),e.jsx("td",{className:"px-4 py-4",children:e.jsx(Ce,{tone:W.type==="recurring"?"info":"neutral",children:W.type==="recurring"?n("typeRecurring"):n("typeOnce")})}),e.jsx("td",{className:"px-4 py-4",children:e.jsxs(xn,{tone:W.lastDeliveryStatus==="failed"?"danger":W.status==="active"?"ok":"neutral",children:[W.lastDeliveryStatus==="failed"?e.jsx(Wt,{size:13}):e.jsx(Qt,{size:13}),e.jsx("span",{children:W.lastDeliveryStatus==="failed"?n("deliveryFailed"):W.status==="active"?n("deliveryActive"):W.status})]})}),e.jsx("td",{className:"px-4 py-4 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",onClick:De=>De.stopPropagation(),children:[W.lastDeliveryStatus==="failed"&&e.jsx(xe,{label:n("retryDelivery"),icon:e.jsx(it,{size:16}),onClick:()=>{Mn(W.id)}}),e.jsx(mt,{label:n("moreActions"),children:e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>{Ln(W.id)},children:n("delete")})})]})})]},W.id))})]})})}),e.jsx(Ht,{page:Z,pageCount:ie,total:at,onPageChange:Qe})]}),e.jsx(Ye,{isOpen:E,onClose:()=>P(!1),title:n("scheduleNewMsg"),maxWidth:"560px",footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:()=>P(!1),children:n("cancel")}),e.jsx(U,{variant:"primary",loading:we,onClick:xs,disabled:we||Ie.length>0,"aria-describedby":Ie.length?"schedule-missing":void 0,children:n(we?"saving":"scheduleAction")})]}),children:e.jsxs("div",{className:"flex flex-col gap-4 py-1",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"block text-xs font-bold text-text-main",children:[n("selectRecipient")," ",e.jsx("span",{className:"text-danger",children:"*"})]}),ge?e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-brand-blue/40 bg-brand-blue/10 p-3",children:[e.jsx(Un,{parts:ge,showKind:!0,kindLabel:an(ge.kind),titleClass:"text-sm font-bold"}),e.jsx(xe,{label:n("changeChat"),variant:"ghost",icon:e.jsx(yt,{size:16}),onClick:()=>D(null)})]}):e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(Er,{size:16,className:"pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-muted"}),e.jsx(be,{type:"search",value:I,onChange:W=>F(W.target.value),placeholder:n("searchRecipients"),"aria-label":n("searchRecipients"),className:"ps-9"})]}),ep()&&e.jsx(U,{variant:"secondary",size:"sm",className:"shrink-0",icon:e.jsx(Dd,{size:15}),onClick:kt,title:n("pickPhoneContactHint"),children:e.jsx("span",{className:"hidden sm:inline",children:n("pickPhoneContact")})})]}),!y&&e.jsx("p",{className:"text-xs text-muted","aria-live":"polite",children:de(n("recipientResultCount"),{count:Ot.length})}),e.jsx("div",{className:"max-h-72 overflow-y-auto rounded-xl border border-line bg-panel-raised",children:y?e.jsx("div",{className:"flex justify-center p-4",children:e.jsx(nt,{label:n("loading")})}):Ot.length===0?e.jsx(Pe,{className:"px-4 py-4",text:n("noRecipientsFound")}):Ot.map((W,Ee)=>{const De=H[Ee];return e.jsx(U,{variant:"ghost","aria-pressed":!1,onClick:()=>D(W),className:"h-auto min-h-14 w-full justify-start gap-2 rounded-none px-2.5 py-1.5 text-start",children:e.jsx(Un,{parts:De,titleClass:"text-sm font-semibold"})},W.id)})})]})]}),e.jsx(re,{label:n("scheduleType"),htmlFor:"schedule-type",children:e.jsxs(Re,{id:"schedule-type",value:G,onChange:W=>ne(W.target.value),children:[e.jsx("option",{value:"recurring",children:n("scheduleRecurring")}),e.jsx("option",{value:"once",children:n("scheduleOnce")})]})}),G==="recurring"?e.jsxs("div",{className:"space-y-3 rounded-xl border border-line bg-panel-raised/40 p-3.5",children:[e.jsx(re,{label:n("repeat"),htmlFor:"repeat-kind",children:e.jsxs(Re,{id:"repeat-kind",value:se,onChange:W=>V(W.target.value),children:[e.jsx("option",{value:"daily",children:n("repeatDaily")}),e.jsx("option",{value:"weekly",children:n("repeatWeekly")}),e.jsx("option",{value:"monthly",children:n("repeatMonthly")}),e.jsx("option",{value:"hourly",children:n("repeatHourly")})]})}),se==="weekly"&&e.jsxs("fieldset",{className:"space-y-1.5",children:[e.jsx("legend",{className:"block text-xs font-bold text-text-main",children:n("weekdays")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Xx.map((W,Ee)=>{const De=O.includes(Ee);return e.jsx(U,{size:"sm",variant:De?"primary":"secondary","aria-pressed":De,onClick:()=>ms(Ee),children:n(W)},W)})})]}),se==="monthly"&&e.jsx(re,{label:n("dayOfMonth"),htmlFor:"day-of-month",description:n("monthDayHint"),children:e.jsx(be,{id:"day-of-month",type:"number",min:1,max:31,inputMode:"numeric",value:Y,onChange:W=>L(Number(W.target.value))})}),se==="hourly"?e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(re,{label:n("everyHours"),htmlFor:"every-hours",children:e.jsx(Re,{id:"every-hours",value:v,onChange:W=>T(Number(W.target.value)),children:Bc.map(W=>e.jsx("option",{value:W,children:W},W))})}),e.jsx(re,{label:n("atMinute"),htmlFor:"hourly-minute",children:e.jsx(be,{id:"hourly-minute",type:"number",min:0,max:59,inputMode:"numeric",value:te,onChange:W=>oe(Number(W.target.value)),dir:"ltr"})})]}):e.jsx(re,{label:e.jsxs(e.Fragment,{children:[n("sendTime"),e.jsxs("span",{className:"ms-1.5 font-semibold text-muted",children:["(",d,")"]})]}),htmlFor:"send-time",children:e.jsx(be,{id:"send-time",type:"time",value:q,onChange:W=>C(W.target.value),dir:"ltr"})}),Nt&&G==="recurring"?e.jsx("p",{className:"text-xs text-muted",dir:"auto",children:Nt}):null,e.jsxs("p",{className:"rounded-lg border border-line bg-bg-soft px-3 py-2 text-xs text-text-main/90",children:[e.jsxs("span",{className:"font-bold text-muted",children:[n("recurrencePreview"),": "]}),e.jsx("span",{dir:"auto",children:Ae||"—"})]})]}):e.jsxs(re,{label:n("deliveryDateTime"),htmlFor:"one-off-time",children:[e.jsx(be,{id:"one-off-time",type:"datetime-local",value:ye,onChange:W=>fe(W.target.value),dir:"ltr"}),Nt?e.jsx("p",{className:"mt-1.5 text-xs text-muted",dir:"auto",children:Nt}):null]}),ge&&Ze?e.jsxs("p",{className:"rounded-lg border border-line bg-bg-soft px-3 py-2 text-xs text-text-main",dir:"auto",children:[e.jsx("span",{children:n("schedulesSummaryTo")})," ",e.jsx(ze,{dir:ge.title.startsWith("+")?"ltr":"auto",className:"font-semibold",children:ge.title}),ge.subtitle?e.jsxs(e.Fragment,{children:[" ",e.jsx(Dr,{text:`(${ge.subtitle})`})]}):null,e.jsx("span",{children:n("schedulesSummarySep")}),e.jsx("span",{dir:"auto",children:Ze})]}):null,Ie.length>0&&e.jsx("p",{id:"schedule-missing",className:"text-xs text-muted",role:"status",children:de(n("schedulesMissingHint"),{items:Ie.join(n("schedulesMissingSep"))})}),e.jsx(re,{label:e.jsxs(e.Fragment,{children:[n("messageText")," ",!ee&&!Se&&e.jsx("span",{className:"text-danger",children:"*"})]}),htmlFor:"schedule-message",children:e.jsx(wt,{id:"schedule-message",rows:3,placeholder:n("messagePlaceholder"),value:M,onChange:W=>$(W.target.value)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs font-bold text-text-main",children:n("scheduleAttachMedia")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Se||ee?e.jsxs("span",{className:"inline-flex max-w-full items-center gap-2 rounded-xl border border-brand-blue/40 bg-brand-blue/10 ps-3 pe-1 text-xs text-text-main sm:text-sm",children:[e.jsx(Hn,{size:14,className:"shrink-0 text-brand-cyan"}),e.jsx("span",{className:"max-w-[220px] truncate",children:(Se==null?void 0:Se.name)??(ee==null?void 0:ee.name)}),e.jsx(xe,{label:n("scheduleRemoveMedia"),variant:"ghost",icon:e.jsx(yt,{size:14}),onClick:ds})]}):e.jsx(U,{variant:"secondary",size:"sm",icon:e.jsx(Hn,{size:14,className:"text-brand-cyan"}),onClick:()=>{var W;return Ts()?void us():(W=ve.current)==null?void 0:W.click()},children:n("scheduleAttachMedia")}),e.jsx("span",{className:"text-[11px] text-muted",children:n("scheduleMediaHint").replace("{max}",String(ae))})]}),!Ts()&&e.jsx("input",{ref:ve,type:"file",className:"sr-only",onChange:W=>{var De;const Ee=((De=W.target.files)==null?void 0:De[0])??null;if(W.target.value="",!!Ee){if(Ee.size>Te){a(n("feedbackFileTooLarge").replace("{max}",String(ae)),"error");return}le(Ee)}}})]})]})}),e.jsx(Ye,{isOpen:!!ue,onClose:()=>ke(null),title:n("scheduleDetails"),maxWidth:"560px",footer:e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[(ue==null?void 0:ue.lastDeliveryStatus)==="failed"?e.jsx(xe,{label:n("retryDelivery"),icon:e.jsx(it,{size:16}),onClick:()=>{const W=ue.id;ke(null),Mn(W)}}):e.jsx("span",{}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{variant:"secondary",onClick:()=>ke(null),children:n("close")}),e.jsx(mt,{label:n("moreActions"),children:e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>{const W=ue==null?void 0:ue.id;ke(null),W&&Ln(W)},children:n("delete")})})]})]}),children:ue&&e.jsxs("div",{className:"flex flex-col gap-3.5 py-1 text-xs sm:text-sm",children:[e.jsx(Lt,{label:n("thTarget"),children:Ke?e.jsx(Un,{parts:Ke,showIcon:!1,showKind:!0,kindLabel:an(Ke.kind),titleClass:"font-semibold"}):null}),e.jsx(Lt,{label:n("thMessage"),children:ue.message?e.jsx("span",{className:"whitespace-pre-wrap break-words",children:ue.message}):e.jsx("span",{className:"text-muted",children:"—"})}),ue.media&&e.jsx(Lt,{label:n("detailMedia"),children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 min-w-0",children:[e.jsx(Hn,{size:13,className:"text-brand-cyan shrink-0"}),e.jsxs("span",{className:"truncate",children:[Gi(n,ue.media.kind),ue.media.fileName?` · ${ue.media.fileName}`:""]})]})}),e.jsx(Lt,{label:n("thSchedule"),children:e.jsx("span",{dir:"auto",children:$a(ue,r)||n("schedulesCustomWhen")})}),e.jsx(Lt,{label:n("thType"),children:ue.type==="recurring"?n("typeRecurring"):n("typeOnce")}),e.jsx(Lt,{label:n("thDelivery"),children:e.jsxs(xn,{tone:ue.lastDeliveryStatus==="failed"?"danger":ue.status==="active"?"ok":"neutral",children:[ue.lastDeliveryStatus==="failed"?e.jsx(Wt,{size:13}):e.jsx(Qt,{size:13}),e.jsx("span",{children:ue.lastDeliveryStatus==="failed"?n("deliveryFailed"):ue.status==="active"?n("deliveryActive"):ue.status})]})}),ue.lastRunAt&&e.jsx(Lt,{label:n("detailLastRun"),children:new Date(ue.lastRunAt).toLocaleString(At(r,{ar:"ar-EG",en:"en-GB"}))}),ue.lastError&&e.jsx(Lt,{label:n("detailError"),children:e.jsx("span",{className:"text-danger break-words",dir:"auto",children:je(n,ue.lastError,"scheduleDeliveryError")})}),ue.createdAt&&e.jsx(Lt,{label:n("detailCreated"),children:new Date(ue.createdAt).toLocaleString(At(r,{ar:"ar-EG",en:"en-GB"}))})]})})]})};function Uc(t,s){const n=Number.isFinite(t)&&t>0?t:0;return n>=1024*1024?s("fileSizeMb").replace("{size}",(n/(1024*1024)).toFixed(1)):s("fileSizeKb").replace("{size}",String(Math.max(1,Math.round(n/1024))))}const $c=({debugLog:t})=>{const{t:s}=me();if(!t)return null;const n=new TextEncoder().encode(t).length;return e.jsx("div",{className:"w-full min-w-0",children:e.jsxs(is,{summary:e.jsxs("span",{className:"flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-0.5",children:[e.jsx("span",{className:"min-w-0 break-words text-sm font-semibold text-text-main",children:s("debugLogSectionLabel")}),e.jsx("span",{className:"text-xs text-muted tabular-nums",children:Uc(n,s)})]}),children:[e.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted",children:s("debugLogHint")}),e.jsx("pre",{dir:"ltr",className:"max-h-64 overflow-y-auto whitespace-pre-wrap break-words rounded-lg border border-line bg-panel-raised p-2.5 font-mono text-[11px] leading-relaxed text-text-main select-text",children:t})]})})},Ha={messageMin:10,messageMax:2e3,attachmentMax:20*1024*1024},Va={bug:{icon:Id,labelKey:"feedbackTopicBug"},idea:{icon:Wd,labelKey:"feedbackTopicIdea"},question:{icon:Vs,labelKey:"feedbackTopicQuestion"},praise:{icon:Kd,labelKey:"feedbackTopicPraise"},other:{icon:vn,labelKey:"feedbackTopicOther"}},lp=["bug","idea","question","praise","other"],op=()=>{var Le;const{t,language:s,theme:n}=me(),{toast:r}=qe(),[a,i]=o.useState(null),[l,d]=o.useState("bug"),[c,m]=o.useState(""),[u,p]=o.useState(0),[h,g]=o.useState(""),[x,f]=o.useState(null),[k,N]=o.useState(null),[w,S]=o.useState(!1),[b,R]=o.useState(null),[j,y]=o.useState(""),[_,A]=o.useState(""),[D,I]=o.useState(!1),[F,E]=o.useState(!1),[P,M]=o.useState(null),[$,G]=o.useState(!1),[ne,se]=o.useState(!1),V=o.useRef(null);o.useEffect(()=>{Q.getFeedbackMeta().then(i).catch(()=>{})},[]),o.useEffect(()=>{if(!w){R(null),y(""),A("");return}const ee=lr(s,n);I(!0),Q.getFeedbackDiagnosticsPreview(ee).then(le=>{le!=null&&le.diagnostics?(R(le.diagnostics),y(le.debugLog||""),A(typeof le.debugLogId=="string"?le.debugLogId:"")):(R(ee),y(""),A(""))}).catch(()=>{R(ee),y(""),A("")}).finally(()=>{I(!1)})},[w,s,n]);const q=(a==null?void 0:a.messageMin)??Ha.messageMin,C=(a==null?void 0:a.messageMax)??Ha.messageMax,O=(a==null?void 0:a.attachmentMax)??Ha.attachmentMax,J=Math.round(O/(1024*1024)),Y=c.trim(),L=Math.max(0,q-Y.length),v=ee=>Uc(ee,t),T=((Le=a==null?void 0:a.topics)!=null&&Le.length?a.topics:lp).filter(ee=>ee in Va),te=()=>r(t("feedbackFileTooLarge").replace("{max}",String(J)),"error"),oe=async()=>{try{const ee=await xl();if(!ee)return;if(ee.size>O){te();return}N(ee)}catch(ee){r(je(t,ee,"attachmentError"),"error")}},ye=async ee=>{if(ee.preventDefault(),L>0||$)return;G(!0),M(k?0:null);const le=w?lr(s,n):void 0,Se={message:Y,topic:l,rating:u||null,contact:h.trim()||null,...le?{diagnostics:le}:{},...le&&_?{debugLogId:_}:{}};try{k?await pl("/dashboard/api/feedback",{message:Se.message,topic:Se.topic,...Se.rating?{rating:String(Se.rating)}:{},...Se.contact?{contact:Se.contact}:{},...le?{diagnostics:JSON.stringify(le)}:{},...le&&_?{debugLogId:_}:{}},k.token,O+1024*1024):x?await Q.sendFeedbackMultipart(Se,x,X=>M(X)):await Q.sendFeedback(Se),se(!0),r(t("feedbackSent"),"success")}catch(X){r(je(t,X,"feedbackSendError"),"error")}finally{G(!1),M(null)}},fe=()=>{m(""),g(""),p(0),d("bug"),f(null),N(null),S(!1),R(null),E(!1),se(!1)},we=()=>{f(null),N(null)};return ne?e.jsxs(he,{className:"border-ok/30 text-center",children:[e.jsx("div",{className:"mx-auto flex size-12 items-center justify-center rounded-full bg-ok/10 text-ok",children:e.jsx(Qt,{size:26})}),e.jsx("h3",{className:"mt-4 text-lg font-bold text-text-main",children:t("feedbackSent")}),e.jsx("p",{className:"mx-auto mt-2 max-w-md text-xs leading-relaxed text-muted sm:text-sm",children:t("feedbackSentDesc")}),e.jsx(U,{className:"mt-6",onClick:fe,children:t("feedbackSendAnother")})]}):e.jsx("div",{className:"flex flex-col gap-5",children:e.jsx(he,{children:e.jsxs("form",{onSubmit:ye,className:"flex flex-col gap-5",children:[e.jsxs("div",{className:"flex items-center gap-3 pb-4 border-b border-line",children:[e.jsx("div",{className:"w-10 h-10 sm:w-11 sm:h-11 rounded-xl bg-brand-cyan/10 text-brand-cyan flex items-center justify-center shrink-0",children:e.jsx(vn,{size:20})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base sm:text-lg font-bold text-text-main",children:t("feedbackTitle")}),e.jsx("p",{className:"text-xs sm:text-sm text-muted mt-0.5",children:t("feedbackDesc")})]})]}),e.jsx(re,{label:t("feedbackTopicLabel"),children:e.jsx(ls,{"aria-label":t("feedbackTopicLabel"),value:l,onChange:d,className:"flex-wrap gap-1.5 sm:gap-2",options:T.map(ee=>{const le=Va[ee].icon;return{value:ee,label:t(Va[ee].labelKey),icon:e.jsx(le,{size:16})}})})}),e.jsxs(re,{label:t("feedbackMessageLabel"),htmlFor:"feedback-message",children:[e.jsx(wt,{id:"feedback-message",rows:6,required:!0,maxLength:C,value:c,onChange:ee=>m(ee.target.value),placeholder:t("feedbackMessagePlaceholder")}),e.jsx("span",{className:"self-end text-[11px] tabular-nums text-muted",children:L>0?`${L} ${t("feedbackCharsNeeded")}`:`${c.length} / ${C}`})]}),e.jsxs(re,{label:t("feedbackAttach"),description:t("feedbackAttachmentHint").replace("{max}",String(J)),children:[k||x?e.jsx("span",{className:"flex",children:e.jsx(Ks,{onRemove:we,removeLabel:t("feedbackRemoveAttachment"),className:"max-w-full",children:`${(k==null?void 0:k.name)??(x==null?void 0:x.name)} · ${v((k==null?void 0:k.size)??(x==null?void 0:x.size)??0)}`})}):e.jsx(U,{type:"button",variant:"secondary",icon:e.jsx(Hn,{size:16,className:"text-brand-cyan"}),className:"w-full justify-center border-dashed",onClick:()=>{var ee;return Ts()?void oe():(ee=V.current)==null?void 0:ee.click()},children:t("feedbackAttach")}),!Ts()&&e.jsx("input",{ref:V,type:"file",className:"sr-only",onChange:ee=>{var Se;const le=((Se=ee.target.files)==null?void 0:Se[0])??null;if(ee.target.value="",!!le){if(le.size>O){te();return}f(le)}}})]}),e.jsxs("fieldset",{className:"flex flex-col gap-2",children:[e.jsx("legend",{className:"text-xs sm:text-sm font-bold text-text-main mb-1",children:t("feedbackRatingLabel")}),e.jsx("div",{className:"flex items-center justify-center gap-1",children:[1,2,3,4,5].map(ee=>e.jsx(xe,{label:`${ee} / 5`,variant:"ghost","aria-pressed":u===ee,onClick:()=>p(u===ee?0:ee),icon:e.jsx(qs,{size:22,className:ee<=u?"fill-brand-cyan text-brand-cyan":"text-muted"})},ee))})]}),e.jsx(re,{label:t("feedbackContactLabel"),htmlFor:"feedback-contact",children:e.jsx(be,{id:"feedback-contact",type:"text",maxLength:200,value:h,onChange:ee=>g(ee.target.value),placeholder:t("feedbackContactPlaceholder")})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(ht,{id:"feedback-diagnostics-consent",checked:w,onChange:ee=>S(ee.target.checked),label:t("feedbackAttachDiagnostics")}),w&&e.jsxs("details",{open:F,onToggle:ee=>E(ee.currentTarget.open),className:"group rounded-xl border border-line bg-panel-raised",children:[e.jsxs("summary",{className:"flex min-h-10 cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-semibold text-muted select-none hover:text-text-main [&::-webkit-details-marker]:hidden",children:[e.jsx("span",{className:"flex-1",children:t("feedbackDiagnosticsPreview")}),D?e.jsx(nt,{className:"size-3.5 shrink-0 text-muted"}):e.jsx(Dt,{size:14,"aria-hidden":!0,className:"shrink-0 transition-transform group-open:rotate-180"})]}),e.jsx("div",{className:"border-t border-line px-3 py-2 text-xs",children:D&&!b?e.jsx("p",{className:"text-muted",children:t("feedbackDiagnosticsLoading")}):b?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("pre",{dir:"ltr",className:"overflow-x-auto rounded-lg bg-panel p-2 font-mono text-[11px] leading-relaxed text-text-main border border-line select-text",children:JSON.stringify(b,null,2)}),e.jsx($c,{debugLog:j})]}):e.jsx("p",{className:"text-muted",children:t("feedbackDiagnosticsEmpty")})})]})]}),$&&(k||x)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"h-2 rounded-full bg-line overflow-hidden",children:k?e.jsx("div",{className:"h-full w-1/3 rounded-full bg-brand-blue animate-pulse"}):e.jsx("div",{className:"h-full rounded-full bg-brand-blue transition-[width]",style:{width:`${Math.max(4,Math.round((P??0)*100))}%`}})}),e.jsxs("span",{className:"text-[11px] text-muted tabular-nums",children:[t("feedbackSending"),!k&&P!==null&&P>0?` ${Math.round(P*100)}%`:"…"]})]}),e.jsxs("div",{className:"flex flex-col gap-3 border-t border-line pt-4",children:[e.jsxs("div",{className:"flex flex-col gap-2.5 sm:flex-row sm:items-center sm:justify-between",children:[a!=null&&a.runtime?e.jsxs("span",{className:"text-[11px] text-muted",children:[t("feedbackRuntimeLabel"),": v",a.runtime.version," · ",a.runtime.platform]}):e.jsx("span",{}),e.jsx(U,{type:"submit",variant:"primary",disabled:L>0,loading:$,icon:e.jsx(vn,{size:16}),className:"w-full sm:w-auto",children:t($?"feedbackSending":"feedbackSendBtn")})]}),e.jsxs("details",{className:"group rounded-xl border border-line bg-panel-raised",children:[e.jsxs("summary",{className:"flex min-h-10 cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-semibold text-muted select-none hover:text-text-main [&::-webkit-details-marker]:hidden",children:[e.jsx(Ar,{size:14,className:"shrink-0 text-brand-cyan"}),e.jsx("span",{className:"flex-1",children:t("feedbackWhatIsSent")}),e.jsx(Dt,{size:14,"aria-hidden":!0,className:"shrink-0 transition-transform group-open:rotate-180"})]}),e.jsx("p",{className:"px-3 pb-3 text-xs leading-relaxed text-muted",children:t("feedbackWhatIsSentDesc")})]}),e.jsxs("p",{className:"text-xs leading-relaxed text-muted",children:[t("feedbackGithubHint")," ",e.jsxs("a",{href:"https://github.com/Abdodiab2005/levix/issues",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 font-semibold text-brand-cyan hover:underline",children:[t("feedbackOpenGithub"),e.jsx(Ds,{size:13,"aria-hidden":!0,className:"shrink-0"})]})]})]})]})})})};function Kc(t,s,n,r){var a,i;try{return((i=(a=new Intl.DateTimeFormat(n,{timeZone:t,hour:"2-digit",timeZoneName:r}).formatToParts(s).find(c=>c.type==="timeZoneName"))==null?void 0:a.value)==null?void 0:i.trim())||null}catch{return null}}function cp(t,s){const n=Kc(t,s,"en","longOffset");if(!n)return"";if(/^GMT$/i.test(n))return"UTC+00:00";const r=/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/i.exec(n);if(!r)return n.replace(/^GMT/i,"UTC");const a=r[2].padStart(2,"0"),i=(r[3]??"00").padStart(2,"0");return`UTC${r[1]}${a}:${i}`}function dp(t){return(t.split("/").pop()??"").replace(/_/g," ").trim()}function up(t,s,n=new Date){const r=t.trim();if(!r)return"";const a=Kc(r,n,s||"en","longGeneric"),i=cp(r,n),l=a||dp(r);return l&&i?`${l} (${i})`:l||i}const mp=["settings","apiKeys","schedules","groups","roles","conversations","memoryFiles","stickers","packs"],Ji={WRONG_PASSWORD:"backupErrWrongPassword",DAMAGED:"backupErrDamaged",NOT_A_BACKUP:"backupErrNotBackup",UNSUPPORTED_VERSION:"backupErrVersion",BAD_HEADER:"backupErrHeader",BAD_MANIFEST:"backupErrManifest",KDF_LIMIT:"backupErrKdf",SCHEMA_NEWER:"backupErrSchemaNewer",SCHEMA_MISMATCH:"backupErrSchemaMismatch",NO_SPACE:"backupErrSpace",BUSY:"backupErrBusy",LIMIT:"backupErrLimit",BAD_PASSWORD:"backupErrPassword",wrong_password:"backupErrPanelPassword",too_many_attempts:"backupErrAttempts",UNCLASSIFIED_TABLE:"backupErrTable",SECRET_FOUND:"backupErrSecret",RESTORE_INCOMPLETE:"backupErrIncomplete",CONFIRM_REQUIRED:"backupErrConfirmRequired",UNSUPPORTED_MEDIA_TYPE:"backupErrMedia",LENGTH_REQUIRED:"backupErrLength",BAD_LENGTH:"backupErrLength",NOT_FOUND:"backupErrNotFound",IO:"backupErrUnknown"},Yi={prefix:"prefix",command_permissions:"thRequiredRole",command_aliases:"thAliases",disabled_commands:"commands",ai_provider:"aiProvider",ai_enabled:"aiAgentEnabled",ai_vision_enabled:"aiVision",ai_stt_enabled:"aiSttEnabled",ai_stt_provider:"aiStt",bot_language:"botLanguage",ai_reply_language:"aiReplyLanguage",bot_timezone:"botTimezone",bot_min_delay_ms:"botMinDelay",bot_max_delay_ms:"botMaxDelay",gemini_model:"modelName",openai_model:"modelName",anthropic_model:"modelName",gemini_api_key:"providerGemini",openai_api_key:"providerOpenAI",anthropic_api_key:"providerAnthropic",google_translate_api_key:"googleTranslateApiKey",openweathermap_api_key:"weatherApiKey",translate_engine:"translateEngine",forward_score_ttl_days:"forwardTtl",max_fetch_bytes:"maxFetchBytes",sticker_library_limit:"stickerLibraryLimit",auto_delete_keep_days:"autoDeleteKeepDays",reply_route:"replyRoute",reply_route_chat:"replyRouteChat",reply_route_overrides:"replyRouteOverrides",command_parser:"commandParser",connection_log_level:"connectionLogLevel",ai_global_memory_read:"aiGlobalMemoryRead",ai_global_memory_write:"aiGlobalMemoryWrite",ai_global_memory_where:"aiGlobalMemoryWhere","cfg:presets":"plusTabPresets","cfg:visibility":"plusTabVisibility","cfg:auto-reply":"plusTabAutoReply"};function Mt(t,s){return typeof t=="string"&&Object.hasOwn(dl.en,t)?t:s}const qa=16*1024**3,xp=t=>`${(t/1024**2).toFixed(1)} MiB`,$n=(t,s)=>new Date(t).toLocaleString(s);function pp(){var z;const{t,language:s}=me(),n=At(s),[r,a]=o.useState(null),[i,l]=o.useState(null),[d,c]=o.useState(""),[m,u]=o.useState(!1),[p,h]=o.useState(null),[g,x]=o.useState(null),[f,k]=o.useState(""),[N,w]=o.useState(""),[S,b]=o.useState(null),[R,j]=o.useState(null),[y,_]=o.useState(null),[A,D]=o.useState(!1),[I,F]=o.useState(!1),E=o.useRef(null),P=o.useRef(null),M=o.useRef(null),$=o.useRef(null),G=o.useRef(null),ne=o.useRef(null),se=o.useRef(null),V=o.useRef(null),q=o.useRef(null),C=o.useRef(0),O=o.useRef(!1),J=o.useRef(!0),Y=o.useRef(null),L=B=>{var Z;return((Z=B.current)==null?void 0:Z.value)??""},v=(...B)=>B.forEach(Z=>{Z.current&&(Z.current.value="")}),T=B=>{const Z=B instanceof et?B.data:null,ie=(B instanceof et?B.code:void 0)||(Z==null?void 0:Z.code);if(ie==="throttled")return de(t("backupErrThrottled"),{n:Number(Z==null?void 0:Z.retryAfter)||60});const Ne=typeof ie=="string"&&Object.hasOwn(Ji,ie)?Ji[ie]:void 0;return Ne?t(Ne):je(t,B,"backupErrUnknown")},te=async()=>{try{const[B,Z]=await Promise.all([Q.get("/backup/contents"),Q.get("/backup/pending")]);J.current&&(a(B),l(Z))}catch(B){J.current&&c(T(B))}},oe=o.useRef(te);oe.current=te,o.useEffect(()=>(J.current=!0,oe.current(),()=>{var B,Z;J.current=!1,Y.current&&clearTimeout(Y.current),(B=V.current)==null||B.abort(),(Z=q.current)==null||Z.abort()}),[]);const ye=async(B,Z,ie)=>{try{const Ne=await Q.get(`/backup/jobs/${B}`);if(!J.current||ie!==void 0&&ie!==C.current)return;if(h(Ne),!Ne.done){Y.current=setTimeout(()=>void ye(B,Z,ie),1e3);return}if(u(!1),Ne.error){const Qe=Ne.error.code==="CONFIRM_REQUIRED"?Ne.error.plan:void 0;Qe&&(D(!1),j(at=>at&&{...at,plan:Qe})),c(T(new et(0,Ne.error.code,Ne.error)));return}Z==="backup"?x(Ne.result):(_(Ne.result),oe.current())}catch(Ne){J.current&&(ie===void 0||ie===C.current)&&(u(!1),c(T(Ne)))}},fe=async B=>{B.preventDefault(),c("");const Z=L(E);if(Array.from(Z.normalize("NFC")).length<12){c(t("backupErrPassword")),v(E,P,M);return}if(Z!==L(P)){c(t("backupErrConfirm")),v(E,P,M);return}u(!0),x(null),h(null);try{const ie=await Q.post("/backup/exports",{password:Z,confirm:L(P),current:L(M)});ye(ie.jobId,"backup")}catch(ie){u(!1),c(T(ie))}finally{v(E,P,M)}},we=()=>{var B;return(B=se.current)==null?void 0:B.click()},Le=()=>{var Z,ie;const B=++C.current;return(Z=V.current)==null||Z.abort(),(ie=q.current)==null||ie.abort(),c(""),j(null),D(!1),_(null),k(""),w(""),b(null),B},ee=B=>{if(O.current)return;const Z=Le();if(B.size>qa||B.size<1){c(t("backupErrLimit"));return}w(B.name),b(0);const ie=new XMLHttpRequest;V.current=ie,ie.open("POST","/dashboard/api/backup/restore/uploads"),ie.setRequestHeader("Content-Type","application/octet-stream"),ie.responseType="json",ie.upload.onprogress=Ne=>{J.current&&Z===C.current&&Ne.lengthComputable&&b(Math.round(Ne.loaded/Ne.total*100))},ie.onload=()=>{if(!J.current||Z!==C.current)return;if(V.current=null,b(null),ie.status===401){window.location.href="/login";return}const Ne=ie.response;ie.status>=200&&ie.status<300&&(Ne!=null&&Ne.uploadId)?k(Ne.uploadId):c(T(new et(ie.status,"",Ne)))},ie.onerror=()=>{!J.current||Z!==C.current||(V.current=null,b(null),c(t("backupErrNetwork")))},ie.onabort=()=>{!J.current||Z!==C.current||(V.current=null,b(null))},ie.send(B)},le=async()=>{if(m||O.current)return;if(!hd()){Wr()?c(t("backupHostUpdate")):we();return}const B=Le();try{const Z=await fd();if(!J.current||B!==C.current||!Z)return;if(Z.size>qa){c(t("backupErrLimit"));return}w(Z.name),b(0);const ie=new AbortController;q.current=ie;const Ne=await gd(Z.token,qa,ie.signal,(Qe,at)=>{J.current&&B===C.current&&at>0&&b(Math.round(Qe/at*100))});if(!J.current||B!==C.current)return;Ne==="UNAVAILABLE"?c(t("backupHostUpdate")):Ne!=="CANCELLED"&&k(Ne.uploadId)}catch(Z){if(!J.current||B!==C.current)return;Z instanceof et&&Z.code==="STORAGE_UNAVAILABLE"?c(t("backupHostUpdate")):c(T(Z))}finally{J.current&&B===C.current&&(q.current=null,b(null))}},Se=()=>{var B,Z;(B=V.current)==null||B.abort(),(Z=q.current)==null||Z.abort()},X=async B=>{if(B.preventDefault(),O.current)return;O.current=!0;const Z=C.current,ie=f,Ne=$.current;u(!0),c("");try{const Qe=await Q.post(`/backup/restore/uploads/${ie}/preview`,{password:(Ne==null?void 0:Ne.value)??""});J.current&&Z===C.current&&(D(!1),j(Qe))}catch(Qe){J.current&&Z===C.current&&c(T(Qe))}finally{Ne&&(Ne.value=""),O.current=!1,J.current&&Z===C.current&&u(!1)}},ve=async B=>{if(B.preventDefault(),O.current)return;O.current=!0;const Z=C.current,ie=f,Ne=$.current,Qe=G.current;u(!0),c(""),h(null);try{const at=await Q.post(`/backup/restore/uploads/${ie}/restore`,{password:(Ne==null?void 0:Ne.value)??"",current:(Qe==null?void 0:Qe.value)??"",confirmDestructive:A});J.current&&Z===C.current&&ye(at.jobId,"restore",Z)}catch(at){J.current&&Z===C.current&&(u(!1),c(T(at)))}finally{Ne&&(Ne.value=""),Qe&&(Qe.value=""),O.current=!1}},ue=async()=>{if(g)try{if(Wr()&&!Gr()){c(t("backupHostUpdate"));return}if(Gr()){await pd(g.token,g.fileName)==="UNAVAILABLE"&&c(t("backupHostUpdate"));return}const B=document.createElement("a");B.href=`/dashboard/api/backup/exports/${g.token}`,B.download=g.fileName,B.click()}catch(B){B instanceof et&&B.code==="STORAGE_UNAVAILABLE"?c(t("backupHostUpdate")):c(T(B))}},ke=async()=>{if(g)try{await Q.delete(`/backup/exports/${g.token}`),x(null)}catch(B){c(T(B))}},Me=async()=>{u(!0),c("");try{await Q.deleteWithBody("/backup/pending",{current:L(ne)}),F(!1),await te()}catch(B){c(T(B))}finally{v(ne),u(!1)}},Te=B=>e.jsx("dl",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3",children:mp.map(Z=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm text-muted",children:t(`backupCount${Z[0].toUpperCase()}${Z.slice(1)}`)}),e.jsx("dd",{className:"font-semibold tabular-nums",children:B[Z]??0})]},Z))}),ae=(B,Z="backupErrorOtherSetting")=>{const ie=B.startsWith("setting:")?B.slice(8):B,Ne=Object.hasOwn(Yi,ie)?Yi[ie]:void 0;return t(Ne?Mt(Ne,Z):Z)},K=B=>e.jsxs("p",{className:"text-sm text-muted",children:[t("backupKeyNames"),":"," ",B.length?B.map((Z,ie)=>e.jsxs("span",{children:[ie?", ":"",e.jsx("span",{children:ae(Z,"backupErrorOtherItem")})]},Z)):t("backupNone")]}),pe=B=>B.map((Z,ie)=>e.jsxs("span",{children:[ie?", ":"",e.jsx("span",{children:ae(Z)})]},Z)),Ae=(B,Z)=>Z.length>0&&e.jsxs("p",{className:"text-sm",children:[e.jsxs("span",{className:"font-semibold",children:[t(B),":"]})," ",pe(Z)]}),Fe=(B,Z)=>e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h4",{className:"text-sm font-semibold",children:t(B)}),Ae("backupPlanAdded",Z.added),Ae("backupPlanReplaced",Z.replaced),Ae("backupPlanRemoved",Z.removed),Z.unchanged>0&&e.jsx("p",{className:"text-sm text-muted",children:de(t("backupPlanUnchanged"),{n:Z.unchanged})}),Z.kept.length>0&&e.jsx(is,{summary:de(t("backupPlanKept"),{n:Z.kept.length}),children:e.jsx("p",{className:"text-sm text-muted",children:pe(Z.kept)})})]}),$e=B=>!B||!(B.messages.total>0||B.presets!=="none"||B.visibility!=="none"||B.autoReply!=="none")?null:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h4",{className:"text-sm font-semibold",children:t("backupPlanPlusTitle")}),B.messages.total>0&&e.jsx("p",{className:"text-sm",children:de(t("backupPlanPlusMessages"),{total:B.messages.total,added:B.messages.added,replaced:B.messages.replaced,unchanged:B.messages.unchanged})}),B.presets!=="none"&&e.jsx("p",{className:"text-sm",children:t(Mt(`backupPlanPlusPresets${B.presets}`,"backupErrorOtherItem"))}),B.visibility!=="none"&&e.jsx("p",{className:"text-sm",children:t(Mt(`backupPlanPlusVisibility${B.visibility}`,"backupErrorOtherItem"))}),B.autoReply!=="none"&&e.jsx("p",{className:"text-sm",children:t(Mt(`backupPlanPlusAutoReply${B.autoReply}`,"backupErrorOtherItem"))}),B.autoReplyWaits&&e.jsx("p",{className:"text-sm text-muted",children:t("backupPlanPlusAutoReplyWaits")})]}),Be=B=>{var Z,ie;return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("h3",{className:"font-semibold",children:t("backupPlanTitle")}),!B.exact&&e.jsx("p",{className:"text-sm text-warn",children:t("backupPlanUnknown")}),Fe("backupPlanSettings",B.settings),Fe("backupPlanApiKeys",B.apiKeys),e.jsx("p",{className:"text-sm",children:t(Mt(`backupPersona${B.persona}`,"backupErrorOtherItem"))}),$e(B.plus),((Z=B.accountData)==null?void 0:Z.replacesCurrent)&&e.jsx("p",{className:"text-sm text-warn",children:t("backupPlanReplacesCurrent")}),((ie=B.accountData)==null?void 0:ie.replacesWaiting)&&e.jsx("p",{className:"text-sm text-warn",children:de(t("backupPlanReplacesWaiting"),{account:B.accountData.replacesWaiting})})]})};return e.jsxs("div",{className:"flex flex-col gap-5",children:[d&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:d}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{icon:e.jsx(Ns,{size:22}),title:t("backupContents"),description:t("backupEncryptionNotice"),actions:e.jsx(xe,{label:t("refresh"),icon:e.jsx(it,{size:18}),onClick:()=>void te()})}),r?e.jsxs(e.Fragment,{children:[Te(r.counts),K(r.apiKeys),e.jsx("p",{className:"text-sm",children:r.paired?de(t("backupPaired"),{account:r.maskedAccount||""}):t("backupUnpaired")}),e.jsxs("p",{className:"text-sm text-muted",children:[t("backupIncludes"),": ",t("backupIncludedPlus")]}),e.jsxs("p",{className:"text-sm text-muted",children:[t("backupNeverIncludes"),": ",t("backupExclusions"),", ",t("backupPlusExclusions")]})]}):e.jsx(nt,{label:t("loading")})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{title:t("backupCreateTitle"),description:t("backupPasswordRule")}),e.jsxs("form",{onSubmit:fe,className:"flex flex-col gap-3",children:[e.jsx(re,{label:t("backupPassword"),htmlFor:"backup-export-password",children:e.jsx(dt,{id:"backup-export-password",ref:E,required:!0,autoComplete:"new-password"})}),e.jsx(re,{label:t("backupConfirmPassword"),htmlFor:"backup-export-confirm",children:e.jsx(dt,{id:"backup-export-confirm",ref:P,required:!0,autoComplete:"new-password"})}),e.jsx(re,{label:t("backupPanelPassword"),htmlFor:"backup-export-current",children:e.jsx(dt,{id:"backup-export-current",ref:M,required:!0,autoComplete:"current-password"})}),e.jsx(U,{type:"submit",variant:"primary",disabled:m,children:t("backupCreate")})]}),p&&p.kind==="backup"&&e.jsx("p",{role:"status",className:"text-sm",children:de(t("backupJobProgress"),{phase:t(Mt(`backupPhase${p.phase}`,"backupPhaseWorking")),percent:p.totalBytes?Math.round(p.bytes/p.totalBytes*100):0})}),g&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"min-w-0 flex-1 text-sm",children:[e.jsx(ze,{as:"span",children:g.fileName})," · ",xp(g.size)," ·"," ",de(t("backupExpires"),{date:$n(g.expiresAt,n)})]}),e.jsx(xe,{label:t("backupDownload"),icon:e.jsx(ns,{size:18}),onClick:()=>void ue()}),e.jsx(xe,{label:t("backupDeleteNow"),icon:e.jsx(lt,{size:18}),onClick:()=>void ke()})]})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{icon:e.jsx(_r,{size:22}),title:t("backupRestoreTitle"),description:t("backupRestoreIntro")}),e.jsx("input",{ref:se,type:"file",accept:".levixbak",className:"sr-only","aria-label":t("backupChooseFile"),onChange:B=>{var ie;const Z=(ie=B.target.files)==null?void 0:ie[0];Z&&ee(Z),B.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{type:"button",variant:"secondary",disabled:m,onClick:()=>void le(),children:t("backupChooseFile")}),N&&e.jsx(ze,{as:"span",className:"min-w-0 text-sm",children:N})]}),S!==null&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{role:"status",className:"flex-1 text-sm",children:de(t("backupUploadProgress"),{percent:S})}),e.jsx(xe,{label:t("cancel"),icon:e.jsx(yt,{size:18}),onClick:Se})]}),f&&!R&&e.jsxs("form",{onSubmit:X,className:"flex flex-col gap-3",children:[e.jsx(re,{label:t("backupPassword"),htmlFor:"backup-preview-password",children:e.jsx(dt,{id:"backup-preview-password",ref:$,required:!0})}),e.jsx(U,{type:"submit",variant:"primary",disabled:m,children:t("backupPreview")})]}),R&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("h3",{className:"font-semibold",children:t("backupPreviewTitle")}),e.jsx("p",{className:"text-sm",children:de(t("backupPreviewMeta"),{date:$n(R.created,n),version:R.app,platform:R.platform})}),Te(R.counts),K(R.apiKeys),e.jsxs("p",{className:"text-sm",children:[t(Mt({match:"backupAccountmatch",different:"backupAccountdifferent","target-unpaired":"backupAccounttargetunpaired",none:"backupAccountnone"}[R.account.status],"backupErrorOtherItem"))," ",R.account.masked&&e.jsx(ze,{as:"span",children:R.account.masked})]}),Be(R.plan),e.jsx("p",{className:"text-sm text-muted",children:t("backupRestoreEffects")}),e.jsxs("form",{onSubmit:ve,className:"flex flex-col gap-3",children:[R.plan.destructive&&e.jsx(ht,{checked:A,onChange:B=>D(B.target.checked),label:t("backupConfirmDestructive")}),e.jsx(re,{label:t("backupPassword"),htmlFor:"backup-restore-password",children:e.jsx(dt,{id:"backup-restore-password",ref:$,required:!0})}),e.jsx(re,{label:t("backupPanelPassword"),htmlFor:"backup-restore-current",children:e.jsx(dt,{id:"backup-restore-current",ref:G,required:!0})}),e.jsx(U,{type:"submit",variant:"danger",disabled:m||R.plan.destructive&&!A,children:t("backupConfirmRestore")})]})]}),p&&p.kind==="restore"&&e.jsx("p",{role:"status",className:"text-sm",children:de(t("backupJobProgress"),{phase:t(Mt(`backupPhase${p.phase}`,"backupPhaseWorking")),percent:p.totalBytes?Math.round(p.bytes/p.totalBytes*100):0})}),y&&e.jsxs("div",{className:"flex flex-col gap-2 text-sm",children:[e.jsx("h3",{className:"font-semibold",children:t("backupRestoreDone")}),e.jsx("p",{children:de(t("backupApplied"),{n:y.applied.length})}),e.jsxs("p",{children:[t("backupAccountData"),":"," ",t(y.accountData==="waits"?"backupAccountWaits":"backupNone")]}),y.skipped.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:t("backupSkipped")}),y.skipped.map(B=>e.jsxs("p",{children:[ae(B.key),": ",t("backupErrorSkipped")]},B.key))]}),y.restartNeeded.length>0&&e.jsxs("p",{children:[t("backupRestartNeeded"),": ",pe(y.restartNeeded)]})]})]}),(i==null?void 0:i.waiting)&&e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsx(He,{title:t("backupPendingTitle"),description:de(t("backupPendingDescription"),{account:i.account||"",date:$n(i.backupCreated||"",n)}),actions:e.jsx(xe,{label:t("backupDiscard"),icon:e.jsx(lt,{size:18}),onClick:()=>F(!0)})}),i.counts&&Te(i.counts),i.lastActivation&&e.jsxs("p",{className:"text-sm",children:[t("backupActivation"),":"," ",t(Mt(`backupActivation${i.lastActivation.status}`,"backupErrorOtherItem"))," ","· ",$n(i.lastActivation.at,n)]})]}),((z=i==null?void 0:i.lastOutcome)==null?void 0:z.outcome)&&i.lastOutcome.outcome!=="restored"&&e.jsx("p",{role:"status",className:"text-sm text-warn",children:de(t("backupLastOutcome"),{outcome:t(i.lastOutcome.outcome==="completed-after-restart"?"backupOutcomeCompleted":"backupOutcomeUnchanged"),date:$n(i.lastOutcome.at,n)})}),e.jsxs(ut,{isOpen:I,onClose:()=>{v(ne),F(!1)},onConfirm:()=>void Me(),title:t("backupDiscardTitle"),confirmLabel:t("backupDiscard"),cancelLabel:t("cancel"),loading:m,children:[e.jsx(re,{label:t("backupPanelPassword"),htmlFor:"backup-discard-current",children:e.jsx(dt,{id:"backup-discard-current",ref:ne,required:!0})}),d&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:d})]})]})}const hp=()=>{const{t}=me(),{toast:s}=qe(),[n,r]=o.useState([]),[a,i]=o.useState([]),[l,d]=o.useState(!0),[c,m]=o.useState(null),[u,p]=o.useState(null),[h,g]=o.useState(null),[x,f]=o.useState(!1),k=o.useCallback(async()=>{m(null);try{const b=await Q.getCrashReports();b&&(r(b.reports||[]),i(b.sent||[]))}catch(b){m(je(t,b,"reportsLoadError"))}finally{d(!1)}},[t]);o.useEffect(()=>{k()},[k]);const N=async(b,R)=>{p(b);try{await Q.sendCrashReport(b,R),s(t("reportSentSuccess"),"success"),await k()}catch(j){s(je(t,j,"reportSendError"),"error"),await k()}finally{p(null)}},w=async b=>{try{await Q.deleteCrashReport(b),s(t("reportDeleteSuccess"),"success"),await k()}catch(R){s(je(t,R,"reportDeleteError"),"error")}finally{g(null)}},S=async()=>{try{await Q.deleteAllCrashReports(),s(t("allReportsDeleted"),"success"),await k()}catch(b){s(je(t,b,"reportsDeleteError"),"error")}finally{f(!1)}};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsxs(he,{className:"flex flex-col gap-5",children:[e.jsx(He,{icon:e.jsx(ss,{size:22}),title:t("diagnosticsTitle"),description:t("diagnosticsDesc"),actions:n.length>0?e.jsx(mt,{label:t("more"),children:e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>f(!0),children:t("deleteAllReports")})}):void 0}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("h3",{className:"text-sm font-bold text-text-main flex items-center gap-2",children:[e.jsx("span",{children:t("pendingReports")}),n.length>0&&e.jsx(Ce,{tone:"info",className:"tabular-nums",children:n.length})]}),l?e.jsx(vt,{text:t("loading")}):c?e.jsx(Pe,{kind:"error",title:c,action:e.jsx(U,{variant:"secondary",onClick:k,children:t("retry")})}):n.length===0?e.jsx(Pe,{kind:"empty",icon:e.jsx(Qt,{size:32,className:"text-ok"}),title:t("noPendingReports")}):e.jsx("div",{className:"flex flex-col gap-3",children:n.map(b=>{const{status:R,lastError:j,debugLog:y,debugLogId:_,...A}=b;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-line bg-panel-raised p-4 transition-colors",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-line pb-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[e.jsx(Ce,{tone:"neutral",children:b.category}),e.jsx("span",{className:"font-mono text-xs sm:text-sm font-bold text-text-main truncate",children:t("errorBoundaryTitle")}),e.jsx(jn,{value:b.createdAt,className:"text-xs text-muted"})]}),e.jsxs("div",{className:"flex items-center gap-2 self-end sm:self-auto shrink-0",children:[e.jsx(U,{variant:"primary",size:"sm",loading:u===b.id,disabled:u!==null,onClick:()=>N(b.id,_),icon:e.jsx(vn,{size:14}),children:u===b.id?t("sendingReport"):t("sendReport")}),e.jsx(xe,{label:t("deleteReport"),icon:e.jsx(lt,{size:16}),variant:"ghost",onClick:()=>g(b.id)})]})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted select-text",children:t("diagnosticsDesc")}),b.lastError&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-danger/30 bg-danger/10 p-2.5 text-xs text-danger",children:[e.jsx(tn,{size:15,className:"shrink-0 mt-0.5"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"font-semibold",children:[t("reportLastError"),": "]}),e.jsx("span",{children:je(t,b.lastError,"reportSendError")})]})]}),e.jsxs("details",{className:"group rounded-xl border border-line bg-panel mt-1",children:[e.jsxs("summary",{className:"flex min-h-10 cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-semibold text-muted select-none hover:text-text-main [&::-webkit-details-marker]:hidden",children:[e.jsx("span",{className:"flex-1",children:t("crashReportPreview")}),e.jsx(Dt,{size:14,"aria-hidden":!0,className:"shrink-0 transition-transform group-open:rotate-180"})]}),e.jsxs("div",{className:"border-t border-line p-3",children:[e.jsx("pre",{dir:"ltr",className:"overflow-x-auto rounded-lg bg-panel-raised p-2.5 font-mono text-[11px] leading-relaxed text-text-main border border-line select-text",children:JSON.stringify(A,null,2)}),e.jsx("div",{className:"mt-2",children:e.jsx($c,{debugLog:y})})]})]})]},b.id)})})]}),e.jsxs("div",{className:"flex flex-col gap-3 border-t border-line pt-4",children:[e.jsxs("h3",{className:"text-sm font-bold text-text-main flex items-center gap-2",children:[e.jsx("span",{children:t("sentReports")}),a.length>0&&e.jsx(Ce,{tone:"neutral",className:"tabular-nums",children:a.length})]}),a.length===0?e.jsx("p",{className:"text-xs text-muted py-2",children:t("noSentReports")}):e.jsx("div",{className:"flex flex-col gap-2",children:a.map(b=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-2 rounded-xl border border-line bg-panel-raised p-3 text-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[e.jsx(Ce,{tone:"neutral",className:"shrink-0",children:b.category}),e.jsx("span",{className:"font-mono font-semibold text-text-main select-all",children:b.id}),e.jsx("span",{className:"text-muted truncate",children:b.type})]}),e.jsx(jn,{value:b.sentAt,className:"text-muted shrink-0"})]},b.id))})]})]}),e.jsx(ut,{isOpen:h!==null,onClose:()=>g(null),onConfirm:()=>h&&w(h),title:t("confirmDeleteReport"),description:t("confirmDeleteReportDesc"),confirmLabel:t("deleteReport"),cancelLabel:t("cancel"),variant:"danger"}),e.jsx(ut,{isOpen:x,onClose:()=>f(!1),onConfirm:S,title:t("confirmDeleteAllReports"),description:t("confirmDeleteAllDesc"),confirmLabel:t("deleteAllReports"),cancelLabel:t("cancel"),variant:"danger"})]})},fp=["about","general","integrations","proxy","security","storage","backup","feedback","diagnostics"];function Qi(){const t=window.location.hash.replace(/^#\/?/,"").split("/");if(t[0]==="settings"&&t[1]){if(t[1]==="plus")return"general";if(fp.includes(t[1]))return t[1]}return"general"}const gp=["!","/",".","#","$","?"],bp="levix-settings";function yp(t){const s=new TextEncoder().encode(t);let n="";for(const r of s)n+=String.fromCharCode(r);return btoa(n)}function Wa(t,s){const n=s instanceof et?s.data:null,r=typeof(n==null?void 0:n.error)=="string"?n.error:"",a=r==="expired"||r==="no_pending"||r==="too_many_attempts";switch(r){case"invalid_email":return{text:t("recoveryErrInvalidEmail"),backToEmail:a};case"wrong_password":return{text:t("recoveryErrWrongPassword"),backToEmail:a};case"throttled":return{text:de(t("recoveryErrThrottled"),{n:Number(n==null?void 0:n.retryAfter)||60}),backToEmail:a};case"rate_limited":return{text:n!=null&&n.retryAfter?de(t("recoveryErrThrottled"),{n:n.retryAfter}):t("recoveryErrRateLimited"),backToEmail:a};case"":case"unavailable":return{text:t("recoveryErrUnavailable"),backToEmail:a};case"invalid":return{text:t("recoveryErrInvalid"),backToEmail:a};case"wrong_code":{const i=(n==null?void 0:n.attemptsLeft)==null?"":` ${de(t("recoveryErrAttemptsLeft"),{n:n.attemptsLeft})}`;return{text:`${t("recoveryErrWrongCode")}${i}`,backToEmail:a}}case"expired":case"no_pending":case"too_many_attempts":return{text:t("recoveryErrExpired"),backToEmail:a};default:return{text:je(t,s,"recoveryErrFailed"),backToEmail:!1}}}function vp(){const{t,language:s}=me(),{toast:n}=qe(),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[d,c]=o.useState(!1),[m,u]=o.useState(!1),[p,h]=o.useState(null),[g,x]=o.useState(!1),[f,k]=o.useState("email"),[N,w]=o.useState(""),[S,b]=o.useState(""),[R,j]=o.useState(""),[y,_]=o.useState(!1),[A,D]=o.useState(null),[I,F]=o.useState(null),[E,P]=o.useState(!1),[M,$]=o.useState(!1);o.useEffect(()=>{let O=!1;return Q.getRecoveryEmail().then(J=>{O||(c(!!J.verified),u(!!J.needsVerification),h(typeof J.masked=="string"?J.masked:null),a(!0))}).catch(()=>{O||(l(!0),a(!0))}),()=>{O=!0}},[]);function G(){k("email"),w(""),b(""),j(""),D(null),F(null)}function ne(){x(!0),G()}function se(){x(!1),G()}async function V(O){if(O.preventDefault(),!y){if(_(!0),f==="email"){D(null);try{await Q.startRecoveryEmail(N.trim(),S,s),k("code"),b(""),j(""),F(null)}catch(J){D(Wa(t,J).text)}finally{_(!1)}return}F(null);try{const J=await Q.verifyRecoveryEmail(R.trim());c(!0),u(!1),h(J.masked),x(!1),G(),n(t("recoveryEmailVerified"),"success")}catch(J){const Y=Wa(t,J);Y.backToEmail?(k("email"),j(""),F(null),D(Y.text)):F(Y.text)}finally{_(!1)}}}async function q(){$(!0);try{await Q.deleteRecoveryEmail(),c(!1),u(!1),h(null),x(!1),G(),P(!1),n(t("recoveryEmailRemoved"),"success")}catch(O){n(Wa(t,O).text,"error")}finally{$(!1)}}const C=!i&&r&&(!d||g||f==="code");return e.jsxs(he,{className:"flex max-w-xl flex-col gap-4",children:[e.jsx(He,{icon:e.jsx(Jd,{size:20}),title:t("recoveryEmailTitle"),description:t("recoveryEmailDesc")}),e.jsx("p",{className:"text-xs text-muted",children:t("recoveryEmailTokenPolicy")}),m&&e.jsx("p",{role:"status",className:"text-sm text-warn",children:t("recoveryEmailReverify")}),i?e.jsx("p",{className:"text-sm text-danger",children:t("recoveryErrFailed")}):r?p&&!g&&f==="email"?e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-bold text-text-main",children:t("recoveryEmailCurrent")}),e.jsx(ze,{dir:"ltr",className:"font-mono text-sm text-text-main",children:p})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx(U,{variant:"secondary",onClick:ne,children:t("recoveryEmailChange")}),e.jsx(xe,{label:t("recoveryEmailRemove"),variant:"danger",icon:e.jsx(lt,{size:16}),onClick:()=>P(!0)})]})]}):null:e.jsx(nt,{className:"size-5",label:t("loading")}),C&&e.jsxs("form",{onSubmit:V,className:"flex flex-col gap-3.5",children:[d&&p&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("p",{className:"text-xs text-muted",children:t("recoveryEmailStays")}),e.jsx(ze,{dir:"ltr",className:"font-mono text-sm text-text-main",children:p})]}),f==="email"?e.jsxs(e.Fragment,{children:[e.jsx(re,{label:t("recoveryEmailLabel"),htmlFor:"recovery-email",error:A,children:e.jsx(be,{id:"recovery-email",type:"text",inputMode:"email",autoComplete:"email",technical:!0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",required:!0,value:N,onChange:O=>w(O.target.value)})}),e.jsx(re,{label:t("currentPassword"),description:t("recoveryEmailPasswordHint"),htmlFor:"recovery-current-password",children:e.jsx(dt,{id:"recovery-current-password",autoComplete:"current-password",required:!0,value:S,onChange:O=>b(O.target.value)})})]}):e.jsx(re,{label:t("recoveryEmailCode"),description:t("recoveryEmailCodeSent"),htmlFor:"recovery-code",error:I,children:e.jsx(be,{id:"recovery-code",type:"text",inputMode:"numeric",autoComplete:"one-time-code",technical:!0,className:"font-mono",maxLength:6,required:!0,value:R,onChange:O=>j(O.target.value)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(U,{type:"submit",variant:"primary",loading:y,children:t(f==="email"?"recoveryEmailSendCode":"recoveryEmailVerify")}),f==="code"?e.jsx(U,{variant:"ghost",onClick:()=>{k("email"),j(""),F(null)},disabled:y,children:t("cancel")}):g&&e.jsx(U,{variant:"ghost",onClick:se,disabled:y,children:t("cancel")})]})]}),e.jsx(ut,{isOpen:E,onClose:()=>{M||P(!1)},onConfirm:q,title:t("recoveryEmailRemoveTitle"),description:t("recoveryEmailRemoveDesc"),confirmLabel:t("delete"),cancelLabel:t("cancel"),variant:"danger",loading:M})]})}const jp=()=>{var Ae,Fe,$e,Be;const{t,language:s,setLanguage:n}=me(),{toast:r}=qe(),a=xc(),[i,l]=o.useState(()=>Qi());o.useEffect(()=>{const z=()=>{const B=Qi();l(Z=>Z!==B?B:Z)};return window.addEventListener("hashchange",z),()=>window.removeEventListener("hashchange",z)},[]);const d=z=>{l(z),window.location.hash=`settings/${z}`},[c,m]=o.useState({}),[u,p]=o.useState({}),[h,g]=o.useState(!0),[x,f]=o.useState("!"),[k,N]=o.useState("!"),[w,S]=o.useState(!1),b=k||x,[R,j]=o.useState(""),[y,_]=o.useState(""),[A,D]=o.useState(""),[I,F]=o.useState(!1),[E,P]=o.useState(!1),[M,$]=o.useState(!1),[G,ne]=o.useState(null),se=o.useRef(null),V=async(z,B)=>{await Q.updateSetting(z,B),z.endsWith("_api_key")||z==="whatsapp_proxy_password"?(m(ie=>({...ie,[z]:""})),p(ie=>({...ie,[z]:!!String(B||"").trim()}))):m(ie=>({...ie,[z]:B}))},q=async(z,B)=>{m(Z=>({...Z,[z]:B}));try{await Q.updateSetting(z,B),r(t("savedSuccessfully"),"success")}catch(Z){r(je(t,Z,"saveFailed"),"error"),await Me()}},C=We(s),O=We(String(c.bot_language||"auto")),J=We(String(c.ai_reply_language||"follow_bot")),Y=We(String(c.bot_timezone||"Africa/Cairo")),L=up(Y.value,s),v=We(String(c.reply_route||"same_chat")),T=We(String(c.reply_route_chat||"")),te=We(String(c.reply_route_overrides||"")),oe=We(String(c.command_parser||"v2")),ye=We(String(c.connection_log_level||"info")),fe=We(String(c.openweathermap_api_key||"")),we=We(Number(c.forward_score_ttl_days||30)),Le=We(Number(c.max_fetch_bytes||524288)),ee=We(Number(c.sticker_library_limit||1e3)),le=We(Number(c.auto_delete_keep_days||30)),Se=wn({min:Number(c.bot_min_delay_ms??400),max:Number(c.bot_max_delay_ms??900)}),X=wn({protocol:String(c.whatsapp_proxy_protocol||"http"),host:String(c.whatsapp_proxy_host||""),port:Number(c.whatsapp_proxy_port||0),username:String(c.whatsapp_proxy_username||""),password:String(c.whatsapp_proxy_password||"")}),ve=async()=>{var z;P(!0);try{const B=await Q.exportSettings(),Z=JSON.stringify(B,null,2),ie=`levix-settings-${((z=B.exportedAt)==null?void 0:z.slice(0,10))||"export"}.json`,Ne=window.LevixHost;if(Ne&&typeof Ne.saveExportFile=="function"){const jt=JSON.parse(Ne.saveExportFile(ie,yp(Z)));if(!(jt!=null&&jt.ok))throw new Error((jt==null?void 0:jt.error)||t("exportSettingsError"));r(`${t("exportSettingsSuccess")} — ${t("exportSavedTo")} ${jt.dir}`,"success");return}const Qe=new Blob([Z],{type:"application/json"}),at=URL.createObjectURL(Qe),Vt=document.createElement("a");Vt.href=at,Vt.download=ie,Vt.click(),URL.revokeObjectURL(at),r(t("exportSettingsSuccess"),"success")}catch(B){r(je(t,B,"exportSettingsError"),"error")}finally{P(!1)}},ue=async z=>{var ie;const B=(ie=z.target.files)==null?void 0:ie[0];if(z.target.value="",!B)return;let Z;try{Z=JSON.parse(await B.text())}catch{r(t("importSettingsError"),"error");return}if((Z==null?void 0:Z.format)!==bp){r(t("importSettingsError"),"error");return}ne(Z)},ke=async()=>{var z,B,Z;if(G){$(!0);try{const ie=await Q.importSettings(G),Ne=[`${((z=ie.applied)==null?void 0:z.length)||0} ${t("importSettingsCount")}`];(B=ie.skipped)!=null&&B.length&&Ne.push(`${t("importSkipped")}: ${ie.skipped.length}`),(Z=ie.restartNeeded)!=null&&Z.length&&Ne.push(`${t("importRestartNeeded")}: ${ie.restartNeeded.length}`),r(`${t("importSuccess")} — ${Ne.join(" · ")}`,"success"),ne(null),await Me()}catch(ie){r(je(t,ie,"importSettingsApplyError"),"error")}finally{$(!1)}}},Me=async()=>{try{const z=await Q.getSettings();if(z!=null&&z.settings){const B={},Z={};z.settings.forEach(ie=>{ie.type==="secret"?(Z[ie.key]=!!ie.configured,B[ie.key]=""):B[ie.key]=ie.value}),m(B),p(Z)}z!=null&&z.prefix&&(f(z.prefix),N(z.prefix))}catch(z){r(je(t,z,"settingsLoadError"),"error")}finally{g(!1)}};o.useEffect(()=>{Me()},[]);const Te=async z=>{const B=(z!==void 0?z:k).trim();if(!B||B.length>3){r(t("prefixValidation"),"error");return}S(!0);try{await Q.updatePrefix(B),f(B),N(B),r(`${t("prefixUpdated")} (${B})`,"success")}catch(Z){r(je(t,Z,"prefixSaveError"),"error")}finally{S(!1)}},ae=async z=>{if(z.preventDefault(),y!==A){r(t("passwordMatchError"),"error");return}if(y.length<8){r(t("passwordMinLength"),"error");return}F(!0);try{await Q.changePassword(R,y),r(t("passwordChangedSuccess"),"success"),j(""),_(""),D("")}catch(B){r(je(t,B,"passwordChangeError"),"error")}finally{F(!1)}},K={saveLabel:t("save"),savedLabel:t("saved")},pe={saveLabel:t("save"),discardLabel:t("discard"),unsavedLabel:t("unsavedChanges"),savedLabel:t("saved")};return h?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(nt,{className:"size-6",label:t("loading")})}):e.jsxs("div",{className:"flex flex-col gap-5 sm:gap-6",children:[e.jsx(ls,{value:i,onChange:z=>d(z),"aria-label":t("settings"),className:"overflow-x-auto no-scrollbar",options:[{value:"about",label:t("aboutLevix"),icon:e.jsx(Yr,{size:17})},{value:"general",label:t("tabGeneral"),icon:e.jsx(To,{size:17})},{value:"integrations",label:t("tabIntegrations"),icon:e.jsx(sr,{size:17})},{value:"proxy",label:t("tabProxy"),icon:e.jsx(Is,{size:17})},{value:"security",label:t("tabSecurity"),icon:e.jsx(Ar,{size:17})},{value:"storage",label:t("tabStorage"),icon:e.jsx(Ns,{size:17})},{value:"backup",label:t("tabBackup"),icon:e.jsx(Ns,{size:17})},{value:"feedback",label:t("tabFeedback"),icon:e.jsx(zs,{size:17})},{value:"diagnostics",label:t("tabDiagnostics"),icon:e.jsx(ss,{size:17})}]}),i==="about"&&e.jsx(hc,{}),i==="general"&&e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsxs(he,{className:"flex flex-col gap-4 sm:gap-5","data-tour":"settings-general",children:[e.jsx(He,{icon:e.jsx(en,{size:22}),title:t("prefixTitle"),description:t("prefixDesc"),actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs font-semibold text-muted",children:[t("activePrefix"),":"]}),e.jsx(Ce,{tone:"info",children:e.jsx(ot,{children:x})})]})}),e.jsxs("div",{className:"flex flex-col items-stretch gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5 sm:max-w-72",children:[e.jsx("span",{className:"text-xs font-semibold text-muted",children:t("prefixPresets")}),e.jsx("div",{className:"flex max-w-full flex-wrap items-center gap-2",children:gp.map(z=>{const B=x===z;return e.jsx(xe,{label:z,size:"md",variant:B?"primary":"secondary",className:"shrink-0",onClick:()=>{N(z),Te(z)},children:e.jsx(ot,{children:z})},z)})})]}),e.jsx(re,{label:t("changePrefix"),className:"min-w-[200px] flex-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"text",className:"h-11 w-20 text-center font-mono sm:w-24",maxLength:3,placeholder:t("prefixPlaceholder"),value:k,onChange:z=>N(z.target.value),onKeyDown:z=>{z.key==="Enter"&&Te()}}),e.jsx(U,{variant:"primary",icon:e.jsx(yn,{size:16}),onClick:()=>Te(),disabled:w||k.trim()===x,loading:w,children:t(w?"saving":"prefixSaveBtn")})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold text-muted sm:text-sm",children:t("prefixPreview")}),e.jsx(Ce,{tone:"info",children:e.jsx(ot,{children:`${b}help`})}),e.jsx(Ce,{tone:"info",children:e.jsx(ot,{children:`${b}lang ar`})}),e.jsx(Ce,{tone:"info",children:e.jsx(ot,{children:`${b}sticker`})})]})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{title:t("settingsBehaviorTitle")}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsx(Ge,{label:t("interfaceLanguage"),description:t("interfaceLanguageDesc"),htmlFor:"panel-language",dirty:C.dirty,saving:C.status==="saving",justSaved:C.status==="saved",error:C.error,onSave:()=>C.save(async z=>n(z)),onRevert:C.revert,...K,children:e.jsx(Re,{id:"panel-language",value:C.value,onChange:z=>{const B=z.target.value,Z=Za.find(ie=>ie.code===B);Z&&C.setValue(Z.code)},children:Za.map(z=>e.jsx("option",{value:z.code,children:`${z.name} (${t(z.dir==="rtl"?"settingsDirRtl":"settingsDirLtr")})`},z.code))})}),e.jsx(Ge,{label:t("botLanguage"),description:t("botLanguageDesc"),htmlFor:"bot-language",dirty:O.dirty,saving:O.status==="saving",justSaved:O.status==="saved",error:O.error,onSave:()=>O.save(z=>V("bot_language",z)),onRevert:O.revert,...K,children:e.jsxs(Re,{id:"bot-language",value:O.value,onChange:z=>O.setValue(z.target.value),children:[e.jsx("option",{value:"auto",children:t("langAuto")}),e.jsx("option",{value:"ar",children:t("langAr")}),e.jsx("option",{value:"en",children:t("langEn")}),e.jsx("option",{value:"pt-BR",children:t("langPtBr")}),e.jsx("option",{value:"es-419",children:t("langEs419")})]})}),e.jsx(Ge,{label:t("aiReplyLanguage"),description:t("aiReplyLanguageDesc"),htmlFor:"ai-reply-language",dirty:J.dirty,saving:J.status==="saving",justSaved:J.status==="saved",error:J.error,onSave:()=>J.save(z=>V("ai_reply_language",z)),onRevert:J.revert,...K,children:e.jsxs(Re,{id:"ai-reply-language",value:J.value,onChange:z=>J.setValue(z.target.value),children:[e.jsx("option",{value:"follow_bot",children:t("aiLangFollowBot")}),e.jsx("option",{value:"auto",children:t("langAuto")}),e.jsx("option",{value:"ar",children:t("langAr")}),e.jsx("option",{value:"en",children:t("langEn")}),e.jsx("option",{value:"pt-BR",children:t("langPtBr")}),e.jsx("option",{value:"es-419",children:t("langEs419")})]})}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[e.jsx(Ge,{label:t("botTimezone"),description:t("botTimezoneDesc"),htmlFor:"bot-timezone",dirty:Y.dirty,saving:Y.status==="saving",justSaved:Y.status==="saved",error:Y.error,onSave:()=>Y.save(z=>V("bot_timezone",z)),onRevert:Y.revert,...K,children:e.jsx(be,{id:"bot-timezone",type:"text",technical:!0,className:"font-mono",placeholder:"Africa/Cairo",value:Y.value,onChange:z=>Y.setValue(z.target.value)})}),L&&e.jsx("p",{className:"text-sm text-text-main",children:L}),Y.value.trim()&&e.jsx(ot,{className:"text-xs text-muted",children:Y.value.trim()})]})]}),e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:z=>{z.preventDefault(),Se.save(async B=>{if(B.min>B.max)throw new et(400,"DELAY_RANGE_INVALID",{code:"DELAY_RANGE_INVALID"});await V("bot_min_delay_ms",B.min),await V("bot_max_delay_ms",B.max)})},onKeyDown:z=>{z.key==="Escape"&&Se.revert()},children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(re,{label:t("botMinDelay"),description:t("delaysDesc"),htmlFor:"bot-min-delay",children:e.jsx(be,{id:"bot-min-delay",type:"number",value:Se.draft.min,onChange:z=>Se.setField("min",Number(z.target.value))})}),e.jsx(re,{label:t("botMaxDelay"),htmlFor:"bot-max-delay",children:e.jsx(be,{id:"bot-max-delay",type:"number",value:Se.draft.max,onChange:z=>Se.setField("max",Number(z.target.value))})})]}),e.jsx(kn,{dirty:Se.dirty,saving:Se.status==="saving",justSaved:Se.status==="saved",error:Se.error,onDiscard:Se.revert,...pe})]})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{icon:e.jsx(zs,{size:20}),title:t("replyRoute"),description:t("replyRouteDesc")}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(Ge,{label:t("replyRoute"),htmlFor:"reply-route",dirty:v.dirty,saving:v.status==="saving",justSaved:v.status==="saved",error:v.error,onSave:()=>v.save(z=>V("reply_route",z)),onRevert:v.revert,...K,children:e.jsxs(Re,{id:"reply-route",value:v.value,onChange:z=>v.setValue(z.target.value),children:[e.jsx("option",{value:"same_chat",children:t("replyRouteSame")}),e.jsx("option",{value:"owner_private",children:t("replyRouteOwner")}),e.jsx("option",{value:"authorized_chat",children:t("replyRouteAuthorized")})]})}),e.jsx(Ge,{label:t("replyRouteChat"),description:t("replyRouteChatDesc"),htmlFor:"reply-route-chat",dirty:T.dirty,saving:T.status==="saving",justSaved:T.status==="saved",error:T.error,onSave:()=>T.save(z=>V("reply_route_chat",z.trim())),onRevert:T.revert,...K,children:e.jsx(be,{id:"reply-route-chat",type:"text",technical:!0,dir:"auto",className:"font-mono",value:T.value,onChange:z=>T.setValue(z.target.value)})}),e.jsx(Ge,{label:t("commandParser"),description:t("commandParserDesc"),htmlFor:"command-parser",dirty:oe.dirty,saving:oe.status==="saving",justSaved:oe.status==="saved",error:oe.error,onSave:()=>oe.save(z=>V("command_parser",z)),onRevert:oe.revert,...K,children:e.jsxs(Re,{id:"command-parser",value:oe.value,onChange:z=>oe.setValue(z.target.value),children:[e.jsx("option",{value:"v2",children:t("commandParserV2")}),e.jsx("option",{value:"v1",children:t("commandParserV1")})]})})]}),e.jsx(Ge,{label:t("replyRouteOverrides"),description:t("replyRouteOverridesDesc"),htmlFor:"reply-route-overrides",dirty:te.dirty,saving:te.status==="saving",justSaved:te.status==="saved",error:te.error,onSave:()=>te.save(z=>V("reply_route_overrides",z.trim())),onRevert:te.revert,...K,children:e.jsx(wt,{id:"reply-route-overrides",dir:"auto",rows:3,className:"font-mono",value:te.value,onChange:z=>te.setValue(z.target.value)})}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(He,{className:"min-w-0 flex-1",title:t("replyHideProgress"),description:t("replyHideProgressDesc")}),e.jsx(Je,{className:"shrink-0",checked:!!c.reply_hide_progress,onChange:z=>q("reply_hide_progress",z)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(He,{className:"min-w-0 flex-1",title:t("messageWatermark"),description:t("messageWatermarkDesc")}),e.jsx(Je,{className:"shrink-0",checked:!!c.message_watermark,onChange:z=>q("message_watermark",z)})]})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{icon:e.jsx(rs,{size:20}),title:t("shareSettingsTitle"),description:t("shareSettingsDesc")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(U,{variant:"secondary",icon:e.jsx(_r,{size:16}),onClick:ve,loading:E,children:t("exportAction")}),e.jsx(U,{variant:"secondary",icon:e.jsx(ns,{size:16}),onClick:()=>{var z;return(z=se.current)==null?void 0:z.click()},children:t("importSettings")})]}),e.jsx("input",{ref:se,type:"file",accept:"application/json,.json",className:"hidden",onChange:ue})]}),e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{icon:e.jsx(Bd,{size:20}),title:t("tourReplayTitle"),description:t("tourReplayDesc")}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(U,{variant:"secondary",icon:e.jsx(Yr,{size:16}),onClick:()=>a==null?void 0:a.startMainTour(),children:t("tourReplayAction")})})]})]}),i==="integrations"&&e.jsxs(he,{className:"flex flex-col gap-5",children:[e.jsx(He,{icon:e.jsx(sr,{size:22}),title:t("tabIntegrations"),description:t("integrationsDesc")}),e.jsx("div",{className:"grid grid-cols-1 gap-5 md:grid-cols-2",children:e.jsx(Ge,{label:t("weatherApiKey"),description:t("settingsWeatherDesc"),htmlFor:"weather-api-key",dirty:fe.dirty,saving:fe.status==="saving",justSaved:fe.status==="saved",error:fe.error,onSave:()=>fe.save(async z=>{await V("openweathermap_api_key",z),fe.setValue("")}),onRevert:fe.revert,...K,children:e.jsx(dt,{id:"weather-api-key",className:"font-mono",placeholder:u.openweathermap_api_key?"••••••••••••":"OpenWeatherMap API Key",value:fe.value,onChange:z=>fe.setValue(z.target.value)})})})]}),i==="proxy"&&e.jsxs(he,{className:"flex flex-col gap-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(He,{className:"min-w-0 flex-1",icon:e.jsx(Is,{size:22}),title:t("proxyTitle"),description:t("proxyDesc")}),e.jsx(Je,{className:"shrink-0",checked:!!c.whatsapp_proxy_enabled,onChange:z=>q("whatsapp_proxy_enabled",z)})]}),e.jsxs("form",{className:"flex flex-col gap-4",onSubmit:z=>{z.preventDefault(),X.save(async B=>{await V("whatsapp_proxy_protocol",B.protocol),await V("whatsapp_proxy_host",B.host),await V("whatsapp_proxy_port",B.port),await V("whatsapp_proxy_username",B.username),B.password.trim()&&await V("whatsapp_proxy_password",B.password),X.setDraft({...B,password:""})})},onKeyDown:z=>{z.key==="Escape"&&X.revert()},children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsx(re,{label:t("proxyProtocol"),htmlFor:"proxy-protocol",children:e.jsxs(Re,{id:"proxy-protocol",value:X.draft.protocol,onChange:z=>X.setField("protocol",z.target.value),children:[e.jsx("option",{value:"http",children:"HTTP"}),e.jsx("option",{value:"https",children:"HTTPS"}),e.jsx("option",{value:"socks5",children:"SOCKS5"})]})}),e.jsx(re,{label:t("proxyHost"),htmlFor:"proxy-host",children:e.jsx(be,{id:"proxy-host",type:"text",technical:!0,className:"font-mono",placeholder:"proxy.example.com",value:X.draft.host,onChange:z=>X.setField("host",z.target.value)})}),e.jsx(re,{label:t("proxyPort"),htmlFor:"proxy-port",children:e.jsx(be,{id:"proxy-port",type:"number",placeholder:"1080",value:X.draft.port,onChange:z=>X.setField("port",Number(z.target.value))})}),e.jsx(re,{label:t("proxyUsername"),htmlFor:"proxy-username",children:e.jsx(be,{id:"proxy-username",type:"text",technical:!0,className:"font-mono",value:X.draft.username,onChange:z=>X.setField("username",z.target.value)})}),e.jsx(re,{label:t("proxyPassword"),htmlFor:"proxy-password",children:e.jsx(dt,{id:"proxy-password",placeholder:u.whatsapp_proxy_password?"••••••••••••":void 0,value:X.draft.password,onChange:z=>X.setField("password",z.target.value)})})]}),e.jsx(kn,{dirty:X.dirty,saving:X.status==="saving",justSaved:X.status==="saved",error:X.error,onDiscard:X.revert,...pe})]})]}),i==="security"&&e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsxs(he,{className:"flex max-w-xl flex-col gap-4","data-tour":"settings-password",children:[e.jsx(He,{icon:e.jsx(Sr,{size:20}),title:t("changePassword")}),e.jsxs("form",{onSubmit:ae,className:"flex flex-col gap-3.5",children:[e.jsx(re,{label:t("currentPassword"),htmlFor:"current-password",children:e.jsx(dt,{id:"current-password",required:!0,value:R,onChange:z=>j(z.target.value)})}),e.jsx(re,{label:t("newPassword"),description:t("passwordMinLength"),htmlFor:"new-password",children:e.jsx(dt,{id:"new-password",required:!0,minLength:8,value:y,onChange:z=>_(z.target.value)})}),e.jsx(re,{label:t("confirmPassword"),htmlFor:"confirm-password",children:e.jsx(dt,{id:"confirm-password",required:!0,minLength:8,value:A,onChange:z=>D(z.target.value)})}),e.jsx(U,{type:"submit",variant:"primary",className:"mt-2 w-full self-start sm:w-auto",icon:e.jsx(yn,{size:16}),disabled:I,loading:I,children:t(I?"saving":"save")})]})]}),e.jsx(vp,{})]}),i==="storage"&&e.jsxs(he,{className:"flex flex-col gap-5",children:[e.jsx(He,{icon:e.jsx(Ns,{size:22}),title:t("storageTitle"),description:t("storageDesc")}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(Ge,{label:t("forwardTtl"),description:t("forwardTtlDesc"),htmlFor:"forward-ttl",dirty:we.dirty,saving:we.status==="saving",justSaved:we.status==="saved",error:we.error,onSave:()=>we.save(z=>V("forward_score_ttl_days",z)),onRevert:we.revert,...K,children:e.jsx(be,{id:"forward-ttl",type:"number",value:we.value,onChange:z=>we.setValue(Number(z.target.value))})}),e.jsx(Ge,{label:t("maxFetchBytes"),description:t("maxFetchBytesDesc"),htmlFor:"max-fetch-bytes",dirty:Le.dirty,saving:Le.status==="saving",justSaved:Le.status==="saved",error:Le.error,onSave:()=>Le.save(z=>V("max_fetch_bytes",z)),onRevert:Le.revert,...K,children:e.jsx(be,{id:"max-fetch-bytes",type:"number",value:Le.value,onChange:z=>Le.setValue(Number(z.target.value))})}),e.jsx(Ge,{label:t("stickerLibraryLimit"),htmlFor:"sticker-library-limit",description:t("stickerLibraryLimitDesc"),dirty:ee.dirty,saving:ee.status==="saving",justSaved:ee.status==="saved",error:ee.error,onSave:()=>ee.save(z=>V("sticker_library_limit",z)),onRevert:ee.revert,...K,children:e.jsx(be,{id:"sticker-library-limit",type:"number",min:1,max:1e5,value:ee.value,onChange:z=>ee.setValue(Number(z.target.value))})}),e.jsx(Ge,{label:t("autoDeleteKeepDays"),htmlFor:"auto-delete-keep-days",description:t("autoDeleteKeepDaysDesc"),dirty:le.dirty,saving:le.status==="saving",justSaved:le.status==="saved",error:le.error,onSave:()=>le.save(z=>V("auto_delete_keep_days",z)),onRevert:le.revert,...K,children:e.jsx(be,{id:"auto-delete-keep-days",type:"number",min:1,max:365,value:le.value,onChange:z=>le.setValue(Number(z.target.value))})})]})]}),i==="feedback"&&e.jsx("div",{"data-tour":"settings-feedback",children:e.jsx(op,{})}),i==="backup"&&e.jsx(pp,{}),i==="diagnostics"&&e.jsxs("div",{"data-tour":"settings-diagnostics",className:"flex flex-col gap-5",children:[e.jsx(he,{children:e.jsx(Ge,{label:t("connectionLogLevel"),description:t("connectionLogLevelDesc"),htmlFor:"connection-log-level",dirty:ye.dirty,saving:ye.status==="saving",justSaved:ye.status==="saved",error:ye.error,onSave:()=>ye.save(z=>V("connection_log_level",z)),onRevert:ye.revert,...K,children:e.jsxs(Re,{id:"connection-log-level",value:ye.value,onChange:z=>ye.setValue(z.target.value),children:[e.jsx("option",{value:"silent",children:t("connectionLogOff")}),e.jsx("option",{value:"error",children:t("connectionLogError")}),e.jsx("option",{value:"warn",children:t("connectionLogWarn")}),e.jsx("option",{value:"info",children:t("connectionLogInfo")}),e.jsx("option",{value:"debug",children:t("connectionLogDebug")}),e.jsx("option",{value:"trace",children:t("connectionLogTrace")})]})})}),e.jsx(hp,{})]}),e.jsx(Ye,{isOpen:!!G,onClose:()=>ne(null),title:t("importTitle"),footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:()=>ne(null),children:t("cancel")}),e.jsx(U,{variant:"primary",onClick:ke,disabled:M,loading:M,children:t("importApply")})]}),children:G&&e.jsxs("div",{className:"flex flex-col gap-3 text-xs text-text-main sm:text-sm",children:[e.jsx("p",{className:"text-muted",children:t("importSummary")}),e.jsxs("ul",{className:"flex flex-col gap-1.5 rounded-xl border border-line bg-panel-raised p-4",children:[e.jsxs("li",{children:[t("importPrefix"),":"," ",e.jsx("span",{className:"font-mono font-bold",children:(Ae=G.commands)==null?void 0:Ae.prefix})]}),e.jsxs("li",{children:[Object.keys(G.settings||{}).length," ",t("importSettingsCount")]}),e.jsxs("li",{children:[Object.keys(((Fe=G.commands)==null?void 0:Fe.permissions)||{}).length," ",t("importPermissionsCount")]}),e.jsxs("li",{children:[Object.keys((($e=G.commands)==null?void 0:$e.aliases)||{}).length," ",t("importAliasesCount")]}),e.jsxs("li",{children:[(((Be=G.commands)==null?void 0:Be.disabled)||[]).length," ",t("importDisabledCount")]})]})]})})]})};function $s(t,s){return`${[...(t||"sticker").replace(/[\\/:*?"<>|]+/g," ").trim()||"sticker"].slice(0,80).join("")}.${s}`}function Hc(t,s){const n=URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=s,r.rel="noopener",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1500)}async function Vc(t,s){return Hc(t,s),{ok:!0,via:"browser"}}async function qc(t,s,n){const r=new File([t],s,{type:n});if(typeof navigator.share=="function"&&typeof navigator.canShare=="function"&&navigator.canShare({files:[r]}))try{return await navigator.share({files:[r]}),{ok:!0,via:"share"}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return{ok:!1,cancelled:!0}}return Hc(t,s),{ok:!0,via:"browser"}}async function Ws(t,s,n,r,a,i){const l=await bd(t,s,n,r,a,i);return t==="share"?{ok:!0,via:"share"}:{ok:!0,via:"host",name:l.name||a,dir:l.dir||"Downloads/Levix"}}const $t={webp:"image/webp",png:"image/png",gif:"image/gif",zip:"application/zip"};function Gs(t,s,n,r){return{name:t||s,mime:n.type||r,blob:n}}async function Jn(t,s){if(Hs())return Ws("save",`/dashboard/api/stickers/${encodeURIComponent(t.id)}/export?format=${s}`,"GET","",$s(t.name,s),$t[s]);const n=await Q.exportSticker(t.id,s),r=Gs(n.fileName,$s(t.name,s),n.blob,$t[s]);return Vc(r.blob,r.name)}async function Wc(t,s){if(Hs())return Ws("share",`/dashboard/api/stickers/${encodeURIComponent(t.id)}/export?format=${s}`,"GET","",$s(t.name,s),$t[s]);const n=await Q.exportSticker(t.id,s),r=Gs(n.fileName,$s(t.name,s),n.blob,$t[s]);return qc(r.blob,r.name,r.mime)}async function wp(t,s){if(Hs())return Ws("save","/dashboard/api/stickers/export","POST",JSON.stringify({ids:t,format:s}),`stickers-${s}.zip`,$t.zip);const n=await Q.exportStickers(t,s),r=Gs(n.fileName,`stickers-${s}.zip`,n.blob,$t.zip);return Vc(r.blob,r.name)}async function kp(t,s){if(Hs())return Ws("share","/dashboard/api/stickers/export","POST",JSON.stringify({ids:t,format:s}),`stickers-${s}.zip`,$t.zip);const n=await Q.exportStickers(t,s),r=Gs(n.fileName,`stickers-${s}.zip`,n.blob,$t.zip);return qc(r.blob,r.name,r.mime)}async function br(t){if(t.length)try{await Q.bulkStickers({action:"touch",ids:t})}catch{}}function Xe(t,s,n="stickerActionError"){var i;const r=s instanceof et?s.code??((i=s.data)==null?void 0:i.error):void 0,a=typeof r=="string"?Tr(r):null;return typeof a=="string"?t(a):je(t,s,n)}const Np=16*1024*1024,Xi=200,Sp=10,Gc=40,Js=60,Cp=[['"','"'],["'","'"],["“","”"],["«","»"],["„","‟"],["‹","›"]],Zi=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter("en",{granularity:"grapheme"}):null;function Ep(t){const s=t.trim();if(s.length<2)return s;for(const[n,r]of Cp)if(s.startsWith(n)&&s.endsWith(r)&&s.length>n.length+r.length-1)return s.slice(n.length,s.length-r.length).trim();return s}function Ap(t){if(!Zi)return[...t].length;let s=0;for(const n of Zi.segment(t))s+=1;return s}function Yn(t){const s=Ep(t).normalize("NFC").replace(/\s+/g," ").trim(),n=Ap(s);return n<1?"empty":n>Gc?"long":null}function Rp(t){return t.type.startsWith("video/")||/\.(mp4|webm|mov|mkv)$/i.test(t.name)}function _p(t){return new Promise(s=>{const n=URL.createObjectURL(t),r=new Image;r.onload=()=>{URL.revokeObjectURL(n),s({width:r.naturalWidth,height:r.naturalHeight})},r.onerror=()=>{URL.revokeObjectURL(n),s(null)},r.src=n})}function Lp(t){return new Promise(s=>{const n=URL.createObjectURL(t),r=document.createElement("video");r.preload="metadata",r.onloadedmetadata=()=>{const a={width:r.videoWidth,height:r.videoHeight,duration:r.duration};URL.revokeObjectURL(n),r.src="",s(a)},r.onerror=()=>{URL.revokeObjectURL(n),s(null)},r.src=n})}async function Mp(t,s){if(t.size<=0)return"stickerErr_NO_MEDIA";if(t.size>s.uploadBytes)return"stickerErr_TOO_LARGE";if(Rp(t)){const r=await Lp(t);return r?r.width>s.maxSide||r.height>s.maxSide?"stickerErr_DIMENSIONS_TOO_LARGE":Number.isFinite(r.duration)&&r.duration>s.videoSeconds+.05?"stickerErr_VIDEO_TOO_LONG":null:null}const n=await _p(t);return n&&(n.width>s.maxSide||n.height>s.maxSide)?"stickerErr_DIMENSIONS_TOO_LARGE":null}function Tp(t){return!t||t==="transparent"?"transparent":t==="#ffffff"?"white":t==="#000000"?"black":"custom"}const Pp=({options:t,onChange:s,canRemoveBackground:n,name:r,onName:a,packId:i,onPack:l,packs:d})=>{var h,g,x;const{t:c}=me(),m=Tp(t.background),u=((h=t.removeBackground)==null?void 0:h.tolerance)??.15,p=t.rotate??0;return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{children:[e.jsx(Yt,{htmlFor:"sticker-fit",children:c("fit")}),e.jsxs(Re,{id:"sticker-fit",value:t.fit||"contain",onChange:f=>s({fit:f.target.value==="cover"?"cover":"contain"}),children:[e.jsx("option",{value:"contain",children:c("contain")}),e.jsx("option",{value:"cover",children:c("cover")})]})]}),e.jsxs("label",{className:"text-xs font-bold",htmlFor:"sticker-zoom",children:[c("zoom")," (",(t.zoom??1).toFixed(2),")"]}),e.jsx("input",{id:"sticker-zoom",type:"range",min:1,max:4,step:.01,value:t.zoom??1,onChange:f=>s({zoom:Number(f.target.value)}),className:"w-full accent-brand-blue"}),e.jsxs("label",{className:"text-xs font-bold",htmlFor:"sticker-pan-x",children:[c("panX")," (",(t.panX??0).toFixed(2),")"]}),e.jsx("input",{id:"sticker-pan-x",type:"range",min:-1,max:1,step:.01,value:t.panX??0,onChange:f=>s({panX:Number(f.target.value)}),className:"w-full accent-brand-blue"}),e.jsxs("label",{className:"text-xs font-bold",htmlFor:"sticker-pan-y",children:[c("panY")," (",(t.panY??0).toFixed(2),")"]}),e.jsx("input",{id:"sticker-pan-y",type:"range",min:-1,max:1,step:.01,value:t.panY??0,onChange:f=>s({panY:Number(f.target.value)}),className:"w-full accent-brand-blue"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{onClick:()=>s({panX:0,panY:0,zoom:1}),children:c("resetPan")}),e.jsxs(U,{onClick:()=>{const f=(p+90)%360;s({rotate:f})},children:[c("rotateQuarter")," (",p,"°)"]})]}),e.jsx(Rt,{"aria-label":c("background"),className:"max-w-full flex-wrap",value:m,onChange:f=>{s(f==="transparent"?{background:"transparent"}:f==="white"?{background:"#ffffff"}:f==="black"?{background:"#000000"}:{background:"#3366ff"})},options:[{value:"transparent",label:c("transparent")},{value:"white",label:c("white")},{value:"black",label:c("black")},{value:"custom",label:c("customColor")}]}),m==="custom"&&e.jsx("input",{type:"color","aria-label":c("customColor"),value:/^#[0-9a-f]{6}$/i.test(t.background||"")?t.background:"#3366ff",onChange:f=>s({background:f.target.value.toLowerCase()}),className:"h-10 w-full rounded-xl border border-line bg-panel-raised"}),n&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(ht,{checked:((g=t.removeBackground)==null?void 0:g.mode)==="plain",onChange:f=>s({removeBackground:f.target.checked?{mode:"plain",tolerance:.15}:null}),label:c("removePlainBackground"),description:c("stickerRemoveHint")}),((x=t.removeBackground)==null?void 0:x.mode)==="plain"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"text-xs font-bold",htmlFor:"sticker-tolerance",children:[c("tolerance")," (",u.toFixed(2),")"]}),e.jsx("input",{id:"sticker-tolerance",type:"range",min:.02,max:.6,step:.01,value:u,onChange:f=>s({removeBackground:{mode:"plain",tolerance:Number(f.target.value)}}),className:"w-full accent-brand-blue"})]})]}),e.jsxs("div",{children:[e.jsx(Yt,{htmlFor:"sticker-name",children:c("stickerName")}),e.jsx(be,{id:"sticker-name",value:r,maxLength:Js,dir:"auto",onChange:f=>a(f.target.value),placeholder:c("stickerNamePlaceholder")})]}),e.jsxs("div",{children:[e.jsx(Yt,{htmlFor:"sticker-pack",children:c("targetPack")}),e.jsxs(Re,{id:"sticker-pack",value:i,onChange:f=>l(f.target.value),children:[e.jsx("option",{value:"",children:c("noPack")}),d.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})]})]})},Dp=({options:t,onChange:s,kind:n,durationMs:r,limits:a,animatedOk:i})=>{const{t:l}=me();if(!(n==="video"||n==="gif"))return null;const c=r>0?r/1e3:a.videoSeconds,m=Math.min(a.videoSeconds,Math.max(0,c)),u=(p,h)=>{const g=Math.min(m,Math.max(0,p)),x=Math.min(a.stickerSeconds,Math.max(.5,h));s({trim:{start:g,duration:x}})};return e.jsxs(he,{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx(ht,{checked:!!t.trim,onChange:p=>{p.target.checked?u(0,Math.min(a.stickerSeconds,Math.max(.5,c))):s({trim:null})},label:e.jsx("span",{className:"font-bold",children:l("trim")})}),t.trim&&e.jsxs("span",{className:"font-mono text-xs text-muted",dir:"ltr",children:[t.trim.start.toFixed(1),"s →"," ",(t.trim.start+t.trim.duration).toFixed(1),"s"]})]}),!i&&e.jsx("p",{className:"text-xs text-warn",children:l("animatedUnavailable")}),e.jsx("p",{className:"text-xs text-muted",children:l(n==="gif"?"gifTrimNote":"trimApplied")}),t.trim&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"text-xs font-bold",htmlFor:"trim-start",children:[l("trimStart")," (",t.trim.start.toFixed(1)," ",l("trimSeconds"),")"]}),e.jsx("input",{id:"trim-start",type:"range",min:0,max:m,step:.1,value:t.trim.start,onChange:p=>{var h;return u(Number(p.target.value),((h=t.trim)==null?void 0:h.duration)??.5)},className:"w-full accent-brand-blue"}),e.jsxs("label",{className:"text-xs font-bold",htmlFor:"trim-duration",children:[l("trimDuration")," (",t.trim.duration.toFixed(1)," ",l("trimSeconds"),")"]}),e.jsx("input",{id:"trim-duration",type:"range",min:.5,max:a.stickerSeconds,step:.1,value:t.trim.duration,onChange:p=>{var h;return u(((h=t.trim)==null?void 0:h.start)??0,Number(p.target.value))},className:"w-full accent-brand-blue"})]})]})},tt=512;function Ip(t,s,n){const r=n.fit||"contain",a=n.zoom??1,i=n.panX??0,l=n.panY??0,d=n.rotate??0,c=d===90||d===270,m=c?s:t,u=c?t:s,h=(r==="cover"?tt/Math.min(m,u):tt/Math.max(m,u))*a,g=Math.max(1,Math.round(m*h)),x=Math.max(1,Math.round(u*h)),f=Math.round((tt-g)/2+i*Math.abs(tt-g)/2),k=Math.round((tt-x)/2+l*Math.abs(tt-x)/2);return{width:g,height:x,x:f,y:k}}const zp='"Segoe UI", Tahoma, "Noto Naskh Arabic", "Noto Sans Arabic", "Geeza Pro", Arial, sans-serif';function Op(t){return/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/.test(t)}function Fp(t){const s=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!s)return"#000000";const n=Number.parseInt(s[1],16),r=n>>16&255,a=n>>8&255,i=n&255;return(.2126*r+.7152*a+.0722*i)/255>.6?"#000000":"#ffffff"}function Bp(t,s,n,r,a,i){const l=Math.max(0,Math.min(i,r/2,a/2));t.beginPath(),t.moveTo(s+l,n),t.arcTo(s+r,n,s+r,n+a,l),t.arcTo(s+r,n+a,s,n+a,l),t.arcTo(s,n+a,s,n,l),t.arcTo(s,n,s+r,n,l),t.closePath(),t.fill()}function Up(t,s,n,r){const a=t==="center"?"center":t==="start"?s==="rtl"?"right":"left":s==="rtl"?"left":"right";return a==="center"?-n/2-r:a==="right"?-n-r:-r}function Jc(t,s,n){const r=[];for(const a of s){if(!a.text)continue;const i=Op(a.text)?"rtl":"ltr";t.save(),t.translate(a.x,a.y),t.rotate(a.rotate*Math.PI/180),t.direction=i,t.font=`${a.fontSize}px ${zp}`,t.textAlign=a.align,t.textBaseline="middle";const l=t.measureText(a.text).width,d=a.background?a.fontSize*.4:8,c=a.background?a.fontSize*.22:6,m=l+d*2,u=a.fontSize*1.25+c*2,p=Up(a.align,i,l,d),h=-u/2;a.background&&(t.fillStyle="rgba(0, 0, 0, 0.55)",Bp(t,p,h,m,u,u/2)),n===a.id&&(t.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--color-brand-cyan").trim(),t.lineWidth=2,t.strokeRect(p-3,h-3,m+6,u+6)),a.outline&&(t.lineJoin="round",t.miterLimit=2,t.lineWidth=Math.max(2,a.fontSize/10),t.strokeStyle=Fp(a.color),t.strokeText(a.text,0,0)),t.fillStyle=a.color,t.fillText(a.text,0,0),t.restore(),r.push({id:a.id,cx:a.x,cy:a.y,rotate:a.rotate,left:p,top:h,right:p+m,bottom:h+u})}return r}function $p(t,s,n){for(let r=t.length-1;r>=0;r--){const a=t[r],i=s-a.cx,l=n-a.cy,d=-a.rotate*Math.PI/180,c=i*Math.cos(d)-l*Math.sin(d),m=i*Math.sin(d)+l*Math.cos(d);if(c>=a.left&&c<=a.right&&m>=a.top&&m<=a.bottom)return a.id}return null}function Kp(t){const s=t.filter(a=>a.text.trim().length>0);if(!s.length)return;const n=document.createElement("canvas");n.width=512,n.height=512;const r=n.getContext("2d");if(r)return Jc(r,s,null),n.toDataURL("image/png")}const Hp=["😀","😂","❤️","🔥","👍","🎉","✨","💯","🙏","😎","🥳","💀","👀","💪","🌹","⭐","✅","😢","🤔","👋"];function ys(t,s,n){return Math.min(n,Math.max(s,t))}const Vp=({mediaUrl:t,kind:s,width:n,height:r,options:a,layers:i,selectedId:l,onPan:d,onSelect:c,onMoveLayer:m,label:u})=>{const p=o.useRef(null),h=o.useRef(null),g=o.useRef([]),x=o.useRef(null),f=o.useRef(null),k=o.useRef(1),N=a.rotate??0,w=n>0&&r>0?Ip(n,r,{fit:a.fit,zoom:a.zoom,panX:a.panX,panY:a.panY,rotate:N}):null,S=N===90||N===270,b=w?S?w.height:w.width:0,R=w?S?w.width:w.height:0,j=w?w.x+(w.width-b)/2:0,y=w?w.y+(w.height-R)/2:0,_=a.background&&a.background!=="transparent"?a.background:null;o.useEffect(()=>{const P=p.current;if(!P)return;const M=()=>{const G=Math.min(P.clientWidth,512);k.current=G>0?G/tt:1,P.style.setProperty("--stage-scale",String(k.current))};M();const $=new ResizeObserver(M);return $.observe(P),()=>$.disconnect()},[]),o.useEffect(()=>{const P=h.current;if(!P)return;const M=window.devicePixelRatio||1;P.width=tt*M,P.height=tt*M;const $=P.getContext("2d");$&&($.setTransform(M,0,0,M,0,0),$.clearRect(0,0,tt,tt),g.current=Jc($,i,l))},[i,l]),o.useEffect(()=>{const P=f.current,M=a.trim;if(!P||!M||s!=="video"||!t)return;const $=M.start,G=M.start+M.duration,ne=()=>{(P.currentTime<$-.05||P.currentTime>=G-.02)&&(P.currentTime=$)};return P.addEventListener("timeupdate",ne),P.addEventListener("ended",ne),P.currentTime=$,()=>{P.removeEventListener("timeupdate",ne),P.removeEventListener("ended",ne)}},[a.trim,s,t]);const A=P=>{const M=P.currentTarget.getBoundingClientRect();return{x:(P.clientX-M.left)/M.width*tt,y:(P.clientY-M.top)/M.height*tt}},D=P=>{if(P.button!==0)return;P.currentTarget.setPointerCapture(P.pointerId);const M=A(P),$=$p(g.current,M.x,M.y);if($){const G=i.find(ne=>ne.id===$);if(!G)return;c($),x.current={kind:"layer",id:$,x:M.x,y:M.y,originX:G.x,originY:G.y};return}c(null),w&&(x.current={kind:"pan",x:M.x,y:M.y,panX:a.panX??0,panY:a.panY??0,placeW:w.width,placeH:w.height})},I=P=>{const M=x.current;if(!M)return;const $=A(P);if(M.kind==="layer"){m(M.id,ys(M.originX+($.x-M.x),0,tt),ys(M.originY+($.y-M.y),0,tt));return}const G=Math.abs(tt-M.placeW),ne=Math.abs(tt-M.placeH),se=G<1?M.panX:ys(M.panX+($.x-M.x)*2/G,-1,1),V=ne<1?M.panY:ys(M.panY+($.y-M.y)*2/ne,-1,1);d(se,V)},F=()=>{x.current=null},E={position:"absolute",left:j,top:y,width:b,height:R,transform:`rotate(${N}deg)`,transformOrigin:"center center",maxWidth:"none",pointerEvents:"none"};return e.jsx("div",{ref:p,className:"w-full",children:e.jsx("div",{className:"relative mx-auto overflow-hidden rounded-2xl border border-line",style:{width:"calc(512px * var(--stage-scale, 1))",height:"calc(512px * var(--stage-scale, 1))"},children:e.jsxs("div",{role:"img","aria-label":u,className:"absolute top-0 start-0 origin-top-left bg-[repeating-conic-gradient(var(--panel-raised)_0%_25%,var(--bg)_0%_50%)] bg-[length:32px_32px]",style:{width:tt,height:tt,transform:"scale(var(--stage-scale, 1))"},children:[_&&e.jsx("div",{className:"absolute inset-0",style:{background:_}}),w&&s==="video"?e.jsx("video",{ref:f,src:t,muted:!0,autoPlay:!0,playsInline:!0,loop:!a.trim,style:E}):w&&e.jsx("img",{src:t,alt:"",draggable:!1,style:E}),e.jsx("canvas",{ref:h,className:"absolute inset-0 w-full h-full touch-none",onPointerDown:D,onPointerMove:I,onPointerUp:F,onPointerCancel:F})]})})})},qp=({layers:t,selectedId:s,onSelect:n,onChange:r,onDelete:a,onAddText:i,onAddEmoji:l})=>{const{t:d}=me(),c=t.find(m=>m.id===s)||null;return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{onClick:i,children:d("addText")}),e.jsx(U,{onClick:()=>l("😀"),children:d("addEmoji")})]}),e.jsxs("div",{children:[e.jsx(Yt,{children:d("emojiPaletteLabel")}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Hp.map(m=>e.jsx(xe,{label:m,variant:"secondary",onClick:()=>l(m),children:e.jsx("span",{className:"text-lg leading-none",children:m})},m))}),e.jsx(Yt,{htmlFor:"emoji-free",children:d("customEmoji")}),e.jsx(be,{id:"emoji-free",className:"mt-1",placeholder:d("emojiInputLabel"),onKeyDown:m=>{if(m.key==="Enter"){const u=m.currentTarget.value.trim();u&&(l(u),m.currentTarget.value="")}}})]}),t.length===0&&e.jsx("p",{className:"text-xs text-muted",children:d("noLayers")}),t.length>0&&e.jsx("div",{className:"flex flex-col gap-1",children:t.map(m=>{const u=m.id===s;return e.jsx(U,{variant:u?"secondary":"ghost","aria-pressed":u,onClick:()=>n(m.id),className:Ue("h-auto w-full justify-start",u&&"border-brand-blue bg-brand-blue/10"),children:e.jsx("span",{className:"truncate",children:m.text||d("textPlaceholder")})},m.id)})}),c&&e.jsxs("div",{className:"flex flex-col gap-2 rounded-xl border border-line p-3",children:[e.jsx("p",{className:"text-xs font-bold",children:d("layerSelected")}),e.jsx(Yt,{htmlFor:"layer-text",children:d("textContent")}),e.jsx(be,{id:"layer-text",value:c.text,onChange:m=>r(c.id,{text:m.target.value})}),e.jsx("label",{className:"text-xs font-bold",htmlFor:"layer-size",children:d("textSize")}),e.jsx("input",{id:"layer-size",type:"range",min:16,max:200,value:c.fontSize,onChange:m=>r(c.id,{fontSize:Number(m.target.value)}),className:"w-full accent-brand-blue"}),e.jsx("label",{className:"text-xs font-bold",htmlFor:"layer-color",children:d("textColor")}),e.jsx("input",{id:"layer-color",type:"color",value:/^#[0-9a-f]{6}$/i.test(c.color)?c.color:"#ffffff",onChange:m=>r(c.id,{color:m.target.value}),className:"h-10 w-full rounded-xl border border-line bg-panel-raised"}),e.jsx(Rt,{"aria-label":d("textAlignment"),value:c.align,onChange:m=>r(c.id,{align:m}),options:[{value:"start",label:d("stickerAlignmentStart")},{value:"center",label:d("stickerAlignmentCenter")},{value:"end",label:d("stickerAlignmentEnd")}]}),e.jsx("label",{className:"text-xs font-bold",htmlFor:"layer-rotate",children:d("layerRotation")}),e.jsx("input",{id:"layer-rotate",type:"range",min:-180,max:180,value:c.rotate,onChange:m=>r(c.id,{rotate:Number(m.target.value)}),className:"w-full accent-brand-blue"}),e.jsx(ht,{checked:c.outline,onChange:m=>r(c.id,{outline:m.target.checked}),label:d("textOutline")}),e.jsx(ht,{checked:c.background,onChange:m=>r(c.id,{background:m.target.checked}),label:d("textBackground")}),e.jsx(U,{variant:"danger",onClick:()=>a(c.id),icon:e.jsx(lt,{size:16}),children:d("deleteLayer")})]})]})},Yc=({open:t,title:s,packs:n,onClose:r,onPick:a,onCreated:i})=>{const{t:l}=me(),{toast:d}=qe(),[c,m]=o.useState(""),[u,p]=o.useState(null),[h,g]=o.useState(!1);o.useEffect(()=>{t||(m(""),p(null))},[t]);const x=async()=>{if(Yn(c)){p(l("packNameLength"));return}g(!0),p(null);try{const k=await Q.createPack(c.trim());m(""),i(k),a(k.id),d(l("packCreated"),"success")}catch(k){d(Xe(l,k,"failedToCreatePack"),"error")}finally{g(!1)}};return e.jsx(Ye,{isOpen:t,onClose:r,title:s,footer:e.jsx(U,{onClick:r,children:l("close")}),children:e.jsxs("div",{className:"flex flex-col gap-3",children:[n.length===0?e.jsx("p",{className:"text-sm text-muted",children:l("noPacks")}):e.jsx("div",{className:"flex max-h-64 flex-col gap-1.5 overflow-y-auto",children:n.map(f=>e.jsxs(U,{variant:"ghost",onClick:()=>a(f.id),className:"h-auto w-full min-w-0 justify-start px-3 py-2.5",children:[e.jsx(ze,{className:"flex-1 text-start",children:f.name}),e.jsx("span",{className:"ms-2 shrink-0 font-medium text-muted",children:f.count})]},f.id))}),e.jsxs("div",{className:"flex flex-col gap-1.5 border-t border-line pt-3",children:[e.jsx(Yt,{htmlFor:"new-pack-name",children:l("newPack")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{id:"new-pack-name",value:c,onChange:f=>{const k=f.target.value;m(k),u&&p(Yn(k)?l("packNameLength"):null)},placeholder:l("newPackPlaceholder"),maxLength:80,dir:"auto"}),e.jsx(U,{variant:"primary",onClick:x,disabled:h,children:l("createPack")})]}),u&&e.jsx("p",{className:"text-xs text-danger",children:u})]})]})})},Wp=600;function Gp(){const[t,s]=o.useState(null),[n,r]=o.useState(!1),[a,i]=o.useState(null),l=o.useRef(0);return o.useEffect(()=>()=>{l.current+=1},[]),{job:t,running:n,submitError:a,start:async m=>{const u=++l.current;i(null),s(null),r(!0);try{const{jobId:p}=await Q.createStickerJob(m);for(;l.current===u;){const h=await Q.getStickerJob(p);if(l.current!==u)return;if(s(h),h.state==="done"||h.state==="failed")break;await new Promise(g=>setTimeout(g,Wp))}}catch(p){l.current===u&&i(p)}finally{l.current===u&&r(!1)}},reset:()=>{l.current+=1,s(null),i(null),r(!1)}}}const Ga={fit:"contain",zoom:1,panX:0,panY:0,rotate:0,background:"transparent",removeBackground:null,trim:null};function Jp(t,s){return t(s==="gif"?"stickerKindGif":s==="video"?"stickerKindVideo":s==="webp"?"stickerKindWebp":"stickerKindImage")}const Yp=({capabilities:t,capsError:s,onRetryCaps:n,incoming:r,onConsumedIncoming:a,isConnected:i,onGoLibrary:l,onCreated:d})=>{var fe,we,Le,ee,le,Se,X,ve,ue,ke,Me,Te;const{t:c}=me(),{toast:m}=qe(),u=Gp(),[p,h]=o.useState(null),[g,x]=o.useState(null),[f,k]=o.useState("PANEL_UPLOAD"),[N,w]=o.useState(!1),[S,b]=o.useState(!1),[R,j]=o.useState(Ga),[y,_]=o.useState([]),[A,D]=o.useState(null),[I,F]=o.useState(""),[E,P]=o.useState(""),[M,$]=o.useState([]),[G,ne]=o.useState(!1),[se,V]=o.useState(!1),q=o.useRef(null),C=o.useRef(null),O=o.useRef(async()=>{});o.useEffect(()=>(Q.getPacks().then(ae=>$(ae.packs)).catch(()=>{}),()=>{q.current&&URL.revokeObjectURL(q.current)}),[]);const J=ae=>{q.current&&URL.revokeObjectURL(q.current);const K=URL.createObjectURL(ae);q.current=K,x(K)},Y=async(ae,K,pe,Ae,Fe)=>{if(!(t!=null&&t.webp))return;const $e=ae instanceof File?ae:new File([ae],K,{type:ae.type}),Be=await Mp($e,t.limits);if(Be){m(c(Be),"error");return}w(!0),k(pe);try{const z=Ae?await hl(Ae,K,t.limits.uploadBytes):Fe?await Q.uploadExistingStickerSource(Fe):await Q.uploadStickerSource($e,K);J($e),h(z),j(Ga),m(c("uploadReady"),"success")}catch(z){m(Xe(c,z),"error")}finally{w(!1)}};O.current=Y,o.useEffect(()=>{!r||!t||r===C.current||(C.current=r,a(),Promise.resolve(r.blob).then(ae=>O.current(ae,r.name,r.source,r.token,r.existingId)).catch(ae=>m(Xe(c,ae),"error")))},[r,t,a]);const L=()=>{u.reset(),h(null),F(""),P(""),_([]),D(null),j(Ga),k("PANEL_UPLOAD"),q.current&&URL.revokeObjectURL(q.current),q.current=null,x(null),C.current=null},v=()=>{if(!p)return null;const ae=I.trim();if([...ae].length>Js)return m(c("stickerNameTooLong"),"warning"),null;const K=Kp(y);return{uploadId:p.uploadId,options:R,...K?{overlay:K}:{},...ae?{name:ae}:{},...E?{packId:E}:{},source:f}},T=()=>{const ae=v();ae&&u.start(ae)},te=async(ae,K)=>{ae.ok&&(ae.via==="host"?m(de(c("stickerShareSaved"),{dir:ae.dir}),"success"):ae.via==="share"?m(c("shareDone"),"success"):m(c("downloaded"),"success"),await br([K.id]),d())};if(s)return e.jsxs("div",{className:"flex flex-col items-center gap-3 py-16",children:[e.jsx("p",{className:"text-sm text-danger",children:s}),e.jsx(U,{onClick:n,children:c("retryLoad")})]});if(!t)return e.jsx(vt,{text:c("loading")});if(!t.webp)return e.jsx("p",{className:"p-6 text-sm text-warn text-center",children:c("stickerErr_ENCODER_MISSING")});const oe=((fe=u.job)==null?void 0:fe.state)==="done"?u.job.sticker:null;if(oe)return e.jsxs("div",{className:"flex flex-col gap-4 max-w-md mx-auto",children:[e.jsx("div",{className:"aspect-square overflow-hidden rounded-2xl border border-line bg-[repeating-conic-gradient(var(--panel-raised)_0%_25%,var(--bg)_0%_50%)] bg-[length:20px_20px]",children:e.jsx("img",{src:oe.url,alt:oe.name||c("stickerPreview"),className:"w-full h-full object-contain"})}),((we=u.job)==null?void 0:we.created)===!1&&e.jsx("p",{className:"text-sm text-ok",children:c("alreadyInLibrary")}),((Le=u.job)==null?void 0:Le.qualityReduced)&&e.jsx("p",{className:"text-sm text-warn",children:c("qualityReduced")}),((ee=u.job)==null?void 0:ee.created)!==!1&&e.jsx("p",{className:"text-sm text-ok",children:c("stickerCreated")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(xe,{label:c("downloadWebp"),icon:e.jsx(ns,{size:18}),onClick:()=>{Jn(oe,"webp").then(ae=>te(ae,oe)).catch(ae=>m(Xe(c,ae),"error"))}}),e.jsx(xe,{label:c("shareSticker"),icon:e.jsx(rs,{size:18}),onClick:()=>{Wc(oe,"webp").then(ae=>te(ae,oe)).catch(ae=>m(Xe(c,ae),"error"))}}),e.jsx(U,{disabled:!i,title:i?void 0:c("notConnectedHint"),onClick:()=>ne(!0),children:c("sendViaWhatsapp")}),e.jsx(U,{onClick:()=>V(!0),children:c("addToPack")}),e.jsx(U,{variant:"primary",onClick:L,children:c("createAnother")}),e.jsx(U,{onClick:l,children:c("goToLibrary")}),e.jsxs(mt,{label:c("moreActions"),children:[e.jsx(_e,{onSelect:()=>{oe.animated&&m(c("firstFrameHint"),"info"),Jn(oe,"png").then(ae=>te(ae,oe)).catch(ae=>m(Xe(c,ae),"error"))},children:c("downloadPng")}),oe.animated&&e.jsx(_e,{disabled:!t.gif,title:c("gifOnlyAnimated"),onSelect:()=>{Jn(oe,"gif").then(ae=>te(ae,oe)).catch(ae=>m(Xe(c,ae),"error"))},children:c("downloadGif")})]})]}),!i&&e.jsx("p",{className:"text-xs text-muted",children:c("notConnectedHint")}),e.jsx(es,{open:G,busy:!1,onClose:()=>ne(!1),onPick:ae=>{Q.sendStickers({ids:[oe.id],jid:ae}).then(K=>{K.sent>0?(m(c("stickerSent"),"success"),ne(!1),d()):m(c("stickerErr_NOT_CONNECTED"),"error")}).catch(K=>m(Xe(c,K),"error"))}}),e.jsx(Yc,{open:se,title:c("addToPack"),packs:M,onClose:()=>V(!1),onCreated:ae=>$(K=>[...K,ae]),onPick:ae=>{Q.bulkStickers({action:"addToPack",ids:[oe.id],packId:ae}).then(()=>{m(c("addedToPack"),"success"),V(!1),d()}).catch(K=>m(Xe(c,K),"error"))}})]});const ye=u.submitError||((le=u.job)==null?void 0:le.state)==="failed";return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_320px] gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3",children:[!p&&e.jsxs("label",{className:`flex flex-col items-center justify-center gap-2 min-h-64 rounded-2xl border border-dashed ${S?"border-brand-blue bg-brand-blue/10":"border-line bg-panel"} p-6 cursor-pointer`,onClick:ae=>{ws()&&(ae.preventDefault(),yd().then(async K=>{if(!K)return;const pe=await fetch(K.url);if(!pe.ok)throw new Error("source unavailable");await Y(await pe.blob(),K.name,"PANEL_UPLOAD",K.token)}).catch(K=>m(Xe(c,K),"error")))},onDragOver:ae=>{ae.preventDefault(),b(!0)},onDragLeave:()=>b(!1),onDrop:ae=>{if(ae.preventDefault(),b(!1),ws())return;const K=ae.dataTransfer.files[0];K&&Y(K,K.name,"PANEL_UPLOAD")},children:[e.jsx(_r,{size:28,className:"text-muted"}),e.jsx("span",{className:"text-sm font-bold text-text-main",children:c("stickerDrag")}),e.jsx("span",{className:"text-xs text-muted",children:c("uploadHint")}),e.jsx("input",{type:"file",accept:"image/*,video/*,.webp,.gif",className:"sr-only",disabled:ws(),onChange:ae=>{var pe;const K=(pe=ae.target.files)==null?void 0:pe[0];ae.target.value="",K&&Y(K,K.name,"PANEL_UPLOAD")}})]}),N&&e.jsx(vt,{text:c("loading")}),p&&g&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted",children:de(c("stickerUploadInfo"),{kind:Jp(c,p.kind),size:Math.max(1,Math.round(p.size/1024))})}),e.jsx(Vp,{mediaUrl:g,kind:p.kind,width:p.width,height:p.height,options:R,layers:y,selectedId:A,label:c("previewStage"),onPan:(ae,K)=>j(pe=>({...pe,panX:ae,panY:K})),onSelect:D,onMoveLayer:(ae,K,pe)=>_(Ae=>Ae.map(Fe=>Fe.id===ae?{...Fe,x:K,y:pe}:Fe))}),e.jsx(Dp,{options:R,onChange:ae=>j(K=>({...K,...ae})),kind:p.kind,durationMs:p.durationMs,limits:t.limits,animatedOk:t.animated})]}),(u.running||((Se=u.job)==null?void 0:Se.state)==="queued"||((X=u.job)==null?void 0:X.state)==="running")&&e.jsxs("div",{children:[e.jsx("div",{className:"h-2 rounded-full bg-line overflow-hidden",children:e.jsx("div",{className:"h-full bg-brand-blue",style:{width:`${Math.round((((ve=u.job)==null?void 0:ve.progress)||0)*100)}%`}})}),e.jsx("p",{className:"text-xs text-muted mt-1",children:om(c,((ue=u.job)==null?void 0:ue.state)==="queued"?"queued":(ke=u.job)==null?void 0:ke.stage)})]}),ye&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:"text-sm text-danger",children:u.submitError?Xe(c,u.submitError):Pr(c,(Te=(Me=u.job)==null?void 0:Me.error)==null?void 0:Te.code)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"primary",onClick:T,children:c("tryAgain")}),e.jsx(U,{onClick:L,children:c("clearLbl")})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[p&&e.jsx(Pp,{options:R,onChange:ae=>j(K=>({...K,...ae})),canRemoveBackground:t.backgroundRemoval.includes("plain"),name:I,onName:F,packId:E,onPack:P,packs:M}),p&&e.jsx(qp,{layers:y,selectedId:A,onSelect:D,onChange:(ae,K)=>_(pe=>pe.map(Ae=>Ae.id===ae?{...Ae,...K}:Ae)),onDelete:ae=>{_(K=>K.filter(pe=>pe.id!==ae)),D(K=>K===ae?null:K)},onAddText:()=>{const ae=crypto.randomUUID();_(K=>[...K,{id:ae,text:c("textPlaceholder"),x:256,y:256,fontSize:64,color:"#ffffff",align:"center",rotate:0,outline:!0,background:!1}]),D(ae)},onAddEmoji:ae=>{const K=crypto.randomUUID();_(pe=>[...pe,{id:K,text:ae,x:256,y:240,fontSize:96,color:"#ffffff",align:"center",rotate:0,outline:!1,background:!1}]),D(K)}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{variant:"primary",disabled:!p||u.running||N,onClick:T,icon:e.jsx(_t,{size:16}),children:c("createBtn")}),p&&e.jsx(U,{onClick:L,disabled:u.running,children:c("clearLbl")})]})]})]})};let Rs=null,_s=!1,Et=null;function el(t){Et=t}async function Qp(t,s){var n;try{const r=await hl(t,s,Np),{jobId:a}=await Q.createStickerJob({uploadId:r.uploadId,source:"MEDIA_HUB"});for(;;){const i=await Q.getStickerJob(a);if(i.state==="done"){Et==null||Et({type:"saved",created:i.created!==!1,qualityReduced:i.qualityReduced===!0});return}if(i.state==="failed"){Et==null||Et({type:"error",code:(n=i.error)==null?void 0:n.code});return}await new Promise(l=>setTimeout(l,600))}}catch(r){Et==null||Et({type:"error",code:r instanceof et?r.code:void 0})}finally{_s=!1}}function Xp(){if(_s)return Rs;const t=vd();return(t==null?void 0:t.intent)==="create"?Rs={blob:fetch(t.url).then(s=>{if(!s.ok)throw new Error("source unavailable");return s.blob()}),name:t.name||"sticker",source:"MEDIA_HUB",token:t.token}:(t==null?void 0:t.intent)==="save"&&!_s&&(_s=!0,Qp(t.token,t.name||"sticker")),Rs}function Zp(){Rs=null}const Qc=({count:t,animatedSelected:s,canRemove:n,sendReason:r,exportReason:a,onSelectAll:i,selectAllLabel:l,onClear:d,onFavorite:c,onUnfavorite:m,onAdd:u,onMove:p,onRemove:h,onDownload:g,onConvert:x,onShare:f,onSend:k,onDelete:N})=>{const{t:w}=me();return t===0?null:e.jsx("div",{className:"sticky bottom-2 z-20 pb-[max(0.25rem,env(safe-area-inset-bottom))] sm:static sm:pb-0",children:e.jsxs(he,{className:"border-brand-blue/40 bg-panel/95 backdrop-blur-md shadow-lg shadow-black/15 p-2 sm:p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[e.jsx("span",{className:"me-auto min-w-0 truncate text-xs sm:text-sm font-bold text-text-main",children:de(w("nSelected"),{n:t})}),e.jsx(xe,{label:t>1?w("downloadZip"):w("download"),icon:e.jsx(ns,{size:16}),onClick:g,disabled:!!a}),e.jsx(xe,{label:w("sendViaWhatsapp"),icon:e.jsx(vn,{size:16,className:"rtl:-scale-x-100"}),onClick:k,disabled:!!r}),e.jsx(xe,{label:w("shareSticker"),icon:e.jsx(rs,{size:16}),onClick:f}),e.jsxs(mt,{label:w("moreActions"),children:[e.jsx(_e,{onSelect:i,children:l}),e.jsx(_e,{onSelect:d,children:w("clearSelection")}),e.jsx(pn,{}),e.jsx(_e,{onSelect:c,children:w("favorite")}),e.jsx(_e,{onSelect:m,children:w("unfavorite")}),e.jsx(pn,{}),e.jsx(_e,{onSelect:u,children:w("addToPack")}),e.jsx(_e,{onSelect:p,children:w("moveToPack")}),n&&e.jsx(_e,{onSelect:h,children:w("removeFromPack")}),e.jsx(_e,{onSelect:x,disabled:!!a,children:w("convertToImage")}),e.jsx(pn,{}),e.jsx(_e,{danger:!0,onSelect:N,children:w("delete")})]}),e.jsx(xe,{variant:"ghost",label:w("clearSelection"),icon:e.jsx(yt,{size:16}),onClick:d})]}),(r||a||s)&&e.jsxs("div",{className:"mt-1.5 space-y-0.5 border-t border-line/50 pt-1 text-xs text-muted",children:[r&&e.jsx("p",{children:r}),a&&e.jsx("p",{children:a}),s&&e.jsx("p",{children:w("firstFrameHint")})]})]})})},eh=({open:t,busy:s,count:n,inUse:r,packs:a,onClose:i,onConfirm:l,onConfirmEverywhere:d})=>{const{t:c}=me();return e.jsx(Ye,{isOpen:t,onClose:i,title:c("deleteStickersTitle"),footer:e.jsxs("div",{className:"flex w-full flex-wrap justify-end gap-2",children:[e.jsx(U,{onClick:i,disabled:s,children:c("cancel")}),r?e.jsx(U,{variant:"danger",onClick:d,disabled:s,children:c("deleteEverywhere")}):e.jsx(U,{variant:"danger",onClick:l,disabled:s,children:c("delete")})]}),children:e.jsxs("div",{className:"flex flex-col gap-2 text-sm text-text-main",children:[e.jsx("p",{children:de(c("nSelected"),{n})}),r?e.jsxs(e.Fragment,{children:[e.jsx("p",{children:c(n===1?"inUseBody":"inUseBulkBody")}),a.length>0&&e.jsxs("p",{children:[c("inUsePacksLabel"),":"," ",a.map((m,u)=>e.jsxs(o.Fragment,{children:[u>0&&", ",e.jsx(ze,{as:"bdi",children:m.name})]},m.id))]}),e.jsx("p",{className:"text-xs text-muted",children:c("deleteEverywhereHint")})]}):e.jsx("p",{children:c("deleteConfirm")})]})})},th="bg-[repeating-conic-gradient(var(--panel-raised)_0%_25%,var(--bg)_0%_50%)] bg-[length:20px_20px]",nh=({sticker:t,packs:s,isConnected:n,gifEnabled:r,onClose:a,onRename:i,onFavorite:l,onAddToPack:d,onRemoveFromPack:c,onDownload:m,onShare:u,onSend:p,onDelete:h,onOpenInCreate:g})=>{const{t:x}=me(),[f,k]=o.useState(""),[N,w]=o.useState("");if(o.useEffect(()=>{k((t==null?void 0:t.name)||""),w("")},[t]),!t)return null;const S=s.filter(j=>t.packIds.includes(j.id)),b=s.filter(j=>!t.packIds.includes(j.id)),R=t.animated&&r?"gif":"webp";return e.jsx(Ye,{isOpen:!!t,onClose:a,title:e.jsx(ze,{children:t.name||x("stickerPreview")}),maxWidth:"38rem",footer:e.jsx("div",{className:"flex w-full justify-end gap-2",children:e.jsx(U,{onClick:a,children:x("close")})}),children:e.jsxs("div",{className:"flex flex-col gap-4 min-w-0",children:[e.jsxs("div",{className:`relative mx-auto aspect-square w-full max-w-[240px] sm:max-w-[280px] max-h-[min(40vh,280px)] overflow-hidden rounded-2xl border border-line ${th}`,children:[e.jsx("img",{src:t.url,alt:t.name||x("stickerPreview"),className:"h-full w-full object-contain"}),e.jsxs("div",{className:"absolute end-2 top-2 flex gap-1",children:[e.jsx(xe,{label:x(R==="gif"?"downloadGif":"downloadWebp"),icon:e.jsx(ns,{size:16}),onClick:()=>m(R)}),e.jsx(xe,{label:x("shareSticker"),icon:e.jsx(rs,{size:16}),onClick:u})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(U,{variant:"primary",size:"sm",className:"h-auto min-w-0 flex-1 py-2",onClick:p,disabled:!n,title:n?void 0:x("notConnectedHint"),icon:e.jsx(vn,{size:16,className:"rtl:-scale-x-100"}),children:e.jsx("span",{className:"min-w-0 break-words",children:x("sendViaWhatsapp")})}),e.jsx(xe,{label:t.favorite?x("unfavorite"):x("favorite"),"aria-pressed":t.favorite,onClick:()=>l(!t.favorite),icon:e.jsx(qs,{size:16,className:t.favorite?"fill-warn text-warn":void 0})}),e.jsx("span",{className:"shrink-0",children:e.jsxs(mt,{label:x("moreActions"),align:"end",children:[e.jsx(_e,{onSelect:()=>m("webp"),children:x("downloadWebp")}),e.jsx(_e,{title:t.animated?x("firstFrameHint"):void 0,onSelect:()=>m("png"),children:x("downloadPng")}),t.animated&&e.jsx(_e,{disabled:!r,title:x("gifOnlyAnimated"),onSelect:()=>m("gif"),children:x("downloadGif")}),e.jsx(_e,{onSelect:g,children:x("openInCreate")}),e.jsx(pn,{}),e.jsx(_e,{danger:!0,onSelect:h,children:x("delete")})]})})]}),t.animated&&e.jsx("p",{className:"text-xs text-muted",children:x("firstFrameHint")}),!n&&e.jsx("p",{className:"text-xs text-muted",children:x("notConnectedHint")}),e.jsxs("div",{className:"flex gap-2 min-w-0",children:[e.jsx(be,{value:f,onChange:j=>k(j.target.value),maxLength:Js,dir:"auto","aria-label":x("stickerName"),placeholder:x("stickerNamePlaceholder"),className:"min-w-0 flex-1"}),e.jsx(U,{variant:"secondary",onClick:()=>i(f.trim()),children:x("rename")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-xs font-bold text-text-main",children:x("inUsePacksLabel")}),S.length===0?e.jsx("p",{className:"text-xs text-muted",children:x("notInPack")}):e.jsx("ul",{className:"flex flex-col gap-1.5",children:S.map(j=>e.jsxs("li",{className:"flex items-center justify-between gap-2",children:[e.jsx(ze,{className:"flex-1 text-sm",children:j.name}),e.jsx(xe,{label:x("removeFromPack"),variant:"ghost",icon:e.jsx(yt,{size:16}),onClick:()=>c(j.id)})]},j.id))}),b.length>0&&e.jsxs("div",{className:"mt-2 flex gap-2",children:[e.jsxs(Re,{value:N,onChange:j=>w(j.target.value),"aria-label":x("addToPack"),children:[e.jsx("option",{value:"",children:x("selectPack")}),b.map(j=>e.jsx("option",{value:j.id,children:j.name},j.id))]}),e.jsx(U,{variant:"primary",disabled:!N,onClick:()=>N&&d(N),children:x("addToPack")})]})]})]})})};function sh(t){const{t:s}=me(),{toast:n}=qe(),[r,a]=o.useState(null),[i,l]=o.useState(!1);return{phase:r,busy:i,requestDelete:u=>{u.length&&a({kind:"ask",ids:u})},run:async(u,p)=>{var h;l(!0);try{if(u.length===1&&!p){try{await Q.deleteSticker(u[0],!1),n(s("deleted"),"success"),a(null),t()}catch(k){if(k instanceof et&&k.code==="IN_USE"){const N=Array.isArray((h=k.data)==null?void 0:h.packs)?k.data.packs:[];a({kind:"inUse",ids:u,packs:N,otherSkipped:0})}else n(Xe(s,k),"error")}return}const g=await Q.bulkStickers({action:"delete",ids:u,confirm:p}),x=g.skipped.filter(k=>k.code==="IN_USE").map(k=>k.id),f=g.skipped.length-x.length;if(!p&&x.length>0){a({kind:"inUse",ids:x,packs:[],otherSkipped:f});return}f>0?n(s("skippedOther"),"warning"):n(s("deleted"),"success"),a(null),t()}catch(g){n(Xe(s,g),"error")}finally{l(!1)}},close:()=>{i||a(null)}}}function ah(t,s,n){const r=new Map(n.map(i=>[i.id,i.name])),a=new Map;for(const i of t){const l=s.find(d=>d.id===i);for(const d of(l==null?void 0:l.packIds)??[])a.set(d,r.get(d)||d)}return[...a].map(([i,l])=>({id:i,name:l}))}function Xc({items:t,packs:s,selectedIds:n,clearSelection:r,reload:a,fromPackId:i,isConnected:l,gifEnabled:d,onOpenInCreate:c,onPackCreated:m}){var ne,se,V;const{t:u}=me(),{toast:p}=qe(),h=o.useRef(!1),[g,x]=o.useState(null),[f,k]=o.useState(null),[N,w]=o.useState([]),[S,b]=o.useState([]),[R,j]=o.useState(!1),y=sh(()=>{x(null),r(),a()}),_=t.find(q=>q.id===g)||null,A=n.length>Xi?u("stickerExportLimit"):null,D=l?n.length>Sp?u("stickerSendLimit"):null:u("notConnectedHint"),I=((ne=y.phase)==null?void 0:ne.kind)==="inUse"?y.phase.packs.length?y.phase.packs:ah(y.phase.ids,t,s):[],F=q=>{q.ok&&(q.via==="host"?p(de(u("stickerShareSaved"),{dir:q.dir}),"success"):q.via==="share"?p(u("shareDone"),"success"):p(u("downloaded"),"success"))},E=async q=>{if(!h.current){h.current=!0;try{await q()}catch(C){p(Xe(u,C),"error")}finally{h.current=!1}}},P=q=>t.find(C=>C.id===q),M=(q,C,O)=>E(async()=>{if(!q.length||q.length>Xi)return;const J=q.length===1?P(q[0]):null,Y=q.some(v=>{var T;return(T=P(v))==null?void 0:T.animated});C==="png"&&Y&&p(u("firstFrameHint"),"info");const L=q.length===1&&J?await(O?Wc(J,C):Jn(J,C)):await(O?kp(q,C):wp(q,C));F(L),L.ok&&(await br(q),a())}),$=(q,C)=>E(async()=>{if(!q.length)return;const O=await Q.bulkStickers({action:C?"favorite":"unfavorite",ids:q});p(O.skipped.length?u("skippedOther"):u("saved"),O.skipped.length?"warning":"success"),a()}),G=(q,C,O)=>E(async()=>{if(!O.length)return;const J=await Q.bulkStickers({action:q,ids:O,packId:C,...q==="moveToPack"&&i?{fromPackId:i}:{}}),Y=u(q==="addToPack"?"addedToPack":"movedToPack");p(J.skipped.length?u("skippedOther"):Y,J.skipped.length?"warning":"success"),k(null),a()});return{exportReason:A,sendReason:D,openDetail:q=>x(q.id),toggleFavorite:q=>void $([q.id],!q.favorite),favorite:()=>void $(n,!0),unfavorite:()=>void $(n,!1),askAdd:()=>{w(n),k("add")},askMove:()=>{w(n),k("move")},remove:()=>{!i||!n.length||E(async()=>{const q=await Q.bulkStickers({action:"removeFromPack",ids:n,packId:i});p(q.skipped.length?u("skippedOther"):u("removedFromPack"),q.skipped.length?"warning":"success"),r(),a()})},download:()=>void M(n,"webp",!1),convert:()=>void M(n,"png",!1),share:()=>void M(n,"webp",!0),askSend:()=>{D||!n.length||b(n)},askDelete:()=>y.requestDelete(n),dialogs:e.jsxs(e.Fragment,{children:[e.jsx(Yc,{open:f!==null,title:u(f==="move"?"moveToPack":"addToPack"),packs:s,onClose:()=>k(null),onCreated:m,onPick:q=>void G(f==="move"?"moveToPack":"addToPack",q,N)}),e.jsx(es,{open:S.length>0,busy:R,onClose:()=>b([]),onPick:q=>{E(async()=>{j(!0);try{(await Q.sendStickers({ids:S,jid:q})).sent>0?(p(S.length>1?u("stickersSent"):u("stickerSent"),"success"),b([]),a()):p(u("stickerErr_NOT_CONNECTED"),"error")}finally{j(!1)}})}}),e.jsx(eh,{open:y.phase!==null,busy:y.busy,count:((se=y.phase)==null?void 0:se.ids.length)??0,inUse:((V=y.phase)==null?void 0:V.kind)==="inUse",packs:I,onClose:y.close,onConfirm:()=>{y.phase&&y.run(y.phase.ids,!1)},onConfirmEverywhere:()=>{y.phase&&y.run(y.phase.ids,!0)}}),e.jsx(nh,{sticker:_,packs:s,isConnected:l,gifEnabled:d,onClose:()=>x(null),onRename:q=>{if(_){if([...q.trim()].length>Js){p(u("stickerNameTooLong"),"warning");return}E(async()=>{await Q.updateSticker(_.id,{name:q.trim()}),p(u("renamed"),"success"),a()})}},onFavorite:q=>{_&&E(async()=>{await Q.updateSticker(_.id,{favorite:q}),p(u("saved"),"success"),a()})},onAddToPack:q=>{_&&G("addToPack",q,[_.id])},onRemoveFromPack:q=>{_&&E(async()=>{await Q.bulkStickers({action:"removeFromPack",ids:[_.id],packId:q}),p(u("removedFromPack"),"success"),a()})},onDownload:q=>{if(_){if(q==="gif"){E(async()=>{const C=await Jn(_,"gif");F(C),C.ok&&(await br([_.id]),a())});return}M([_.id],q,!1)}},onShare:()=>{_&&M([_.id],"webp",!0)},onSend:()=>{_&&l&&b([_.id])},onDelete:()=>{_&&y.requestDelete([_.id])},onOpenInCreate:()=>{_&&(x(null),c(_))}})]})}}const rh="bg-[repeating-conic-gradient(var(--panel-raised)_0%_25%,var(--bg)_0%_50%)] bg-[length:16px_16px]",Zc=({sticker:t,selected:s,onToggle:n,onOpen:r,onFavorite:a})=>{const{t:i}=me(),l=t.name||i("stickerPreview");return e.jsxs("div",{className:Ue("relative aspect-square overflow-hidden rounded-xl border bg-panel transition-shadow",s?"border-brand-blue ring-2 ring-brand-blue/50":"border-line"),children:[e.jsx(U,{variant:"ghost",onClick:()=>r(),"aria-label":i("stickerOpen"),className:"absolute inset-0 h-auto min-h-0 w-full rounded-none p-0 hover:bg-transparent focus-visible:ring-inset",children:e.jsx("img",{src:t.thumbUrl,alt:"",loading:"lazy",draggable:!1,className:Ue("h-full w-full object-contain",rh)})}),e.jsx(xe,{label:i(s?"deselectSticker":"stickerSelect"),role:"checkbox","aria-checked":s,"aria-pressed":s,variant:"ghost",className:"absolute top-0.5 start-0.5 z-10 size-10 min-h-10 min-w-10 p-0 hover:bg-transparent focus-visible:ring-offset-0",onClick:d=>n(d.shiftKey),icon:e.jsx("span",{className:Ue("flex size-7 items-center justify-center rounded-lg border transition-all shadow-xs",s?"border-brand-blue bg-brand-blue text-white":"border-line/70 bg-panel/85 text-muted backdrop-blur-xs hover:border-line hover:text-text-main"),children:e.jsx(gn,{size:14,strokeWidth:s?3:2.5,className:s?void 0:"opacity-40"})})}),t.animated&&e.jsx(Ce,{tone:"neutral",className:"pointer-events-none absolute bottom-1 start-1 z-10 px-1.5 py-0.5 text-[10px] font-bold",children:i("gifBadge")}),e.jsx(xe,{label:t.favorite?i("unfavorite"):i("favorite"),"aria-pressed":t.favorite,variant:"ghost",className:"absolute top-0.5 end-0.5 z-10 size-10 min-h-10 min-w-10 p-0 hover:bg-transparent focus-visible:ring-offset-0",onClick:a,icon:e.jsx("span",{className:Ue("flex size-7 items-center justify-center rounded-lg border transition-all shadow-xs",t.favorite?"border-warn/50 bg-panel/90 text-warn backdrop-blur-xs":"border-line/70 bg-panel/85 text-muted backdrop-blur-xs hover:border-line hover:text-text-main"),children:e.jsx(qs,{size:14,className:t.favorite?"fill-warn text-warn":void 0})})}),e.jsx("span",{className:"sr-only",children:l})]})},ih=({items:t,total:s,page:n,pageCount:r,loading:a,error:i,emptyText:l,isFiltered:d,selected:c,onToggle:m,onOpen:u,onFavorite:p,onPageChange:h,onRetry:g,onClearFilters:x,onGoCreate:f})=>{const{t:k}=me();return e.jsxs("div",{className:"flex min-w-0 flex-col gap-4",children:[a&&t.length===0?e.jsx(vt,{text:k("loading")}):i?e.jsx(Pe,{kind:"error",description:i,action:e.jsx(U,{onClick:g,children:k("retryLoad")})}):t.length===0?d?e.jsx(Pe,{kind:"no-results",description:l,action:x?e.jsx(U,{variant:"secondary",onClick:x,children:k("reset")}):void 0}):e.jsx(Pe,{kind:"empty",icon:e.jsx(Rr,{size:28,className:"text-muted"}),description:l,action:f?e.jsx(U,{variant:"primary",onClick:f,children:k("createBtn")}):void 0}):e.jsx("div",{className:Ue("grid grid-cols-3 min-[390px]:grid-cols-4 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8 xl:grid-cols-10 gap-2 sm:gap-3 transition-opacity",a&&"opacity-60 pointer-events-none"),children:t.map((N,w)=>e.jsx(Zc,{sticker:N,selected:c.has(N.id),onToggle:S=>m(w,S),onOpen:()=>u(N),onFavorite:()=>p(N)},N.id))}),s>0&&e.jsx(Ht,{page:n,pageCount:r,total:s,onPageChange:h,className:"pt-1"})]})};function ed(t,s){const[n,r]=o.useState(new Set),a=o.useRef(null),i=o.useRef(s);return o.useEffect(()=>{i.current!==s&&(i.current=s,r(new Set),a.current=null)},[s]),{selected:n,toggle:(m,u)=>{const p=t[m];p&&r(h=>{const g=new Set(h);if(u&&a.current!=null){const x=Math.min(a.current,m),f=Math.max(a.current,m);for(let k=x;k<=f;k++){const N=t[k];N&&g.add(N)}return g}return g.has(p)?g.delete(p):g.add(p),a.current=m,g})},selectAll:()=>{r(m=>{const u=new Set(m);for(const p of t)p&&u.add(p);return u})},clear:()=>{a.current=null,r(new Set)}}}const Kn=24;function lh(t){const{t:s}=me(),{toast:n}=qe(),[r,a]=o.useState(""),[i,l]=o.useState(""),[d,c]=o.useState(t==="recent"?"recent":"newest"),[m,u]=o.useState(t),[p,h]=o.useState(""),[g,x]=o.useState(1),[f,k]=o.useState(null),[N,w]=o.useState(0),[S,b]=o.useState([]),[R,j]=o.useState(!0),[y,_]=o.useState(null),A=o.useRef(0),D=`${i}|${m}|${d}|${p}`;o.useEffect(()=>{u(t)},[t]),o.useEffect(()=>{const ne=setTimeout(()=>l(r),300);return()=>clearTimeout(ne)},[r]);const I=o.useCallback(()=>{Q.getPacks().then(ne=>b(ne.packs)).catch(()=>{})},[]);o.useEffect(()=>{I()},[I]);const F=o.useCallback(async ne=>{const se=++A.current;j(!0),_(null);const V=Math.max(0,(ne-1)*Kn);try{const q=await Q.getStickers({q:i||void 0,sort:d,filter:m,pack:p||void 0,offset:V,limit:Kn});if(se!==A.current)return;const C=q.total,O=Math.max(1,Math.ceil(C/Kn));if(ne>O){x(O);return}k({page:ne,filterKey:D,items:q.items}),w(C)}catch(q){if(se!==A.current)return;const C=Xe(s,q);_({page:ne,filterKey:D,message:C}),n(C,"error")}finally{se===A.current&&j(!1)}},[i,d,m,p,D,s,n]),E=o.useRef(D);o.useEffect(()=>{if(E.current!==D&&(E.current=D,g!==1)){x(1);return}F(g)},[D,g,F]);const P=o.useCallback(()=>{I(),F(g)},[F,I,g]),M=o.useCallback(ne=>{x(Math.max(1,Math.floor(ne)||1))},[]),$=(f==null?void 0:f.page)===g&&f.filterKey===D,G=(y==null?void 0:y.page)===g&&y.filterKey===D?y.message:null;return{q:r,setQ:a,sort:d,setSort:c,filter:m,setFilter:u,pack:p,setPack:h,page:g,setPage:M,pageCount:Math.max(1,Math.ceil(N/Kn)),pageSize:Kn,items:$?f.items:[],loadedItems:(f==null?void 0:f.items)??null,total:N,packs:S,loading:R||!$&&!G,error:G,reload:P,loadPacks:I,lockedFilter:t!=="all"}}const Ja=({preset:t,isConnected:s,gifEnabled:n,refreshKey:r,onOpenInCreate:a,onGoCreate:i})=>{const{t:l}=me(),d=lh(t),c=d.items.map(j=>j.id),m=`${d.q}|${d.filter}|${d.sort}|${d.pack}`,u=ed(c,m),p=[...u.selected],h=o.useRef({key:m,loadedItems:null,stickers:new Map});if(h.current.key!==m&&(h.current={key:m,loadedItems:d.loadedItems,stickers:new Map}),d.loadedItems&&h.current.loadedItems!==d.loadedItems){for(const j of d.loadedItems)h.current.stickers.set(j.id,j);h.current.loadedItems=d.loadedItems}const g=new Map(d.items.map(j=>[j.id,j]));for(const j of p){const y=h.current.stickers.get(j);y&&!g.has(j)&&g.set(j,y)}const x=d.pack&&d.pack!=="none"?d.pack:void 0,f=o.useRef(d.reload);f.current=d.reload,o.useEffect(()=>{r!==0&&f.current()},[r]);const k=Xc({items:[...g.values()],packs:d.packs,selectedIds:p,clearSelection:u.clear,reload:d.reload,fromPackId:x,isConnected:s,gifEnabled:n,onOpenInCreate:a,onPackCreated:d.loadPacks}),N=!!(d.q||d.pack||!d.lockedFilter&&d.filter!=="all"),w=l(N?"noResults":t==="favorites"?"favoritesEmpty":t==="recent"?"recentEmpty":"emptyLibrary"),S=[...g.values()].some(j=>u.selected.has(j.id)&&j.animated),b=(d.lockedFilter||d.filter==="all"?0:1)+(d.pack?1:0),R=()=>{d.setQ(""),d.lockedFilter||d.setFilter("all"),d.setPack("")};return e.jsxs("div",{className:Ue("flex flex-col gap-3 min-w-0",p.length>0&&"pb-16 sm:pb-0"),children:[e.jsxs(It,{children:[e.jsx(be,{type:"search",value:d.q,onChange:j=>d.setQ(j.target.value),placeholder:l("searchStickers"),"aria-label":l("searchStickers"),className:"min-w-48 flex-1"}),e.jsxs(zt,{label:l("filter"),resetLabel:l("reset"),activeCount:b,onReset:()=>{d.lockedFilter||d.setFilter("all"),d.setPack("")},children:[!d.lockedFilter&&e.jsxs(Re,{"aria-label":l("filterBy"),value:d.filter,onChange:j=>d.setFilter(j.target.value),children:[e.jsx("option",{value:"all",children:l("allStickers")}),e.jsx("option",{value:"favorites",children:l("favorites")}),e.jsx("option",{value:"recent",children:l("recent")}),e.jsx("option",{value:"animated",children:l("animated")}),e.jsx("option",{value:"static",children:l("static")})]}),e.jsxs(Re,{"aria-label":l("packFilter"),value:d.pack,onChange:j=>d.setPack(j.target.value),children:[e.jsx("option",{value:"",children:l("anyPack")}),e.jsx("option",{value:"none",children:l("noPack")}),d.packs.map(j=>e.jsx("option",{value:j.id,children:j.name},j.id))]})]}),e.jsx(Rn,{label:l("sort"),value:d.sort,onChange:j=>d.setSort(j),options:[{value:"newest",label:l("sortNewest")},{value:"oldest",label:l("sortOldest")},{value:"name",label:l("sortName")},{value:"recent",label:l("sortRecent")}]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-muted",children:[e.jsx("span",{children:l("resultCount").replace("{n}",String(d.total))}),d.items.length>0&&e.jsx(U,{variant:"ghost",size:"sm",onClick:u.selectAll,children:l(d.pageCount>1?"selectCurrentPage":"selectAll")})]}),e.jsx(Qc,{count:p.length,animatedSelected:S,canRemove:!!x,sendReason:p.length?k.sendReason:null,exportReason:p.length?k.exportReason:null,onSelectAll:u.selectAll,selectAllLabel:l(d.pageCount>1?"selectCurrentPage":"selectAll"),onClear:u.clear,onFavorite:k.favorite,onUnfavorite:k.unfavorite,onAdd:k.askAdd,onMove:k.askMove,onRemove:k.remove,onDownload:k.download,onConvert:k.convert,onShare:k.share,onSend:k.askSend,onDelete:k.askDelete}),e.jsx(ih,{items:d.items,total:d.total,page:d.page,pageCount:d.pageCount,loading:d.loading,error:d.error,emptyText:w,isFiltered:N,selected:u.selected,onToggle:u.toggle,onOpen:k.openDetail,onFavorite:k.toggleFavorite,onPageChange:d.setPage,onRetry:d.reload,onClearFilters:N?R:void 0,onGoCreate:t==="all"&&!N?i:void 0}),k.dialogs]})},oh=({packId:t,isConnected:s,gifEnabled:n,onBack:r,onOpenInCreate:a})=>{const{t:i}=me(),{toast:l}=qe(),[d,c]=o.useState(null),[m,u]=o.useState([]),[p,h]=o.useState([]),[g,x]=o.useState(!0),[f,k]=o.useState(null),[N,w]=o.useState(0),[S,b]=o.useState(!1),R=o.useRef(""),{page:j,pageCount:y,pageItems:_,setPage:A,total:D}=An(m,48,t),I=_.map(V=>V.id),F=ed(I,t),E=[...F.selected];o.useEffect(()=>{if(N<0)return;let V=!0;return k(null),Promise.all([Q.getPack(t),Q.getPacks()]).then(([q,C])=>{V&&(c(q.pack),u(q.items),h(C.packs))}).catch(q=>{V&&k(Xe(i,q))}).finally(()=>{V&&x(!1)}),()=>{V=!1}},[t,N,i]);const P=()=>{x(m.length===0),w(V=>V+1)},M=Xc({items:m,packs:p,selectedIds:E,clearSelection:F.clear,reload:P,fromPackId:t,isConnected:s,gifEnabled:n,onOpenInCreate:a,onPackCreated:P}),$=async V=>{const q=m;u(V),b(!0);try{await Q.reorderPack(t,V.map(C=>C.id))}catch(C){u(q),l(Xe(i,C),"error")}finally{b(!1)}},G=(V,q)=>{const C=V+q;if(S||C<0||C>=m.length)return;const O=m.slice(),[J]=O.splice(V,1);J&&(O.splice(C,0,J),$(O))},ne=V=>{const q=m.findIndex(Y=>Y.id===R.current),C=m.findIndex(Y=>Y.id===V);if(R.current="",S||q<0||C<0||q===C)return;const O=m.slice(),[J]=O.splice(q,1);J&&(O.splice(C,0,J),$(O))},se=m.some(V=>F.selected.has(V.id)&&V.animated);return e.jsxs("div",{className:Ue("flex flex-col gap-3 min-w-0",E.length>0&&"pb-16 sm:pb-0"),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(U,{onClick:r,children:[e.jsx(Xn,{size:16,className:"rtl:-scale-x-100"}),i("backToPacks")]}),d&&e.jsxs("div",{className:"min-w-0 max-w-full",children:[e.jsx("h3",{className:"text-base font-bold text-text-main",children:e.jsx(ze,{children:d.name})}),e.jsx("p",{className:"text-xs text-muted",children:de(i("stickerCount"),{n:d.count})})]})]}),g&&m.length===0&&e.jsx(vt,{text:i("loading")}),f&&m.length===0&&e.jsx(Pe,{kind:"error",description:f,action:e.jsx(U,{onClick:P,children:i("retryLoad")})}),!g&&!f&&m.length===0&&e.jsx(Pe,{kind:"empty",icon:e.jsx(Xr,{size:28,className:"text-muted"}),description:i("packEmpty")}),m.length>0&&e.jsxs(e.Fragment,{children:[E.length===0&&e.jsx("div",{children:e.jsx(U,{variant:"ghost",size:"sm",onClick:F.selectAll,children:i(y>1?"selectCurrentPage":"selectAll")})}),e.jsx(Qc,{count:E.length,animatedSelected:se,canRemove:!0,sendReason:E.length?M.sendReason:null,exportReason:E.length?M.exportReason:null,onSelectAll:F.selectAll,selectAllLabel:i(y>1?"selectCurrentPage":"selectAll"),onClear:F.clear,onFavorite:M.favorite,onUnfavorite:M.unfavorite,onAdd:M.askAdd,onMove:M.askMove,onRemove:M.remove,onDownload:M.download,onConvert:M.convert,onShare:M.share,onSend:M.askSend,onDelete:M.askDelete}),e.jsx("ul",{className:"flex flex-col gap-2",children:_.map((V,q)=>{const C=(j-1)*48+q;return e.jsxs("li",{className:"flex items-center gap-2 rounded-xl border border-line bg-panel p-2",onDragOver:O=>O.preventDefault(),onDrop:O=>{O.preventDefault(),ne(V.id)},children:[e.jsx("div",{className:"w-16 shrink-0",children:e.jsx(Zc,{sticker:V,selected:F.selected.has(V.id),onToggle:O=>F.toggle(q,O),onOpen:()=>M.openDetail(V),onFavorite:()=>M.toggleFavorite(V)})}),e.jsx("p",{className:"flex-1 min-w-0 text-sm font-semibold",children:e.jsx(ze,{children:V.name||i("stickerPreview")})}),e.jsx(xe,{label:i("reorderUp"),disabled:S||C===0,onClick:()=>G(C,-1),children:e.jsx(zd,{size:14})}),e.jsx(xe,{label:i("reorderDown"),disabled:S||C===m.length-1,onClick:()=>G(C,1),children:e.jsx(Dt,{size:14})}),e.jsx(xe,{label:i("reorderDragHint"),variant:"ghost",className:"cursor-grab",draggable:!S,onDragStart:O=>{R.current=V.id,O.dataTransfer.effectAllowed="move",O.dataTransfer.setData("text/plain",V.id)},icon:e.jsx(Xr,{size:16})})]},V.id)})}),e.jsx(Ht,{page:j,pageCount:y,total:D,onPageChange:A})]}),M.dialogs]})},ch=({isConnected:t,gifEnabled:s,onOpenInCreate:n})=>{const{t:r}=me(),{toast:a}=qe(),[i,l]=o.useState([]),[d,c]=o.useState(!0),[m,u]=o.useState(null),[p,h]=o.useState(""),[g,x]=o.useState(null),[f,k]=o.useState(!1),[N,w]=o.useState(null),[S,b]=o.useState(null),[R,j]=o.useState(""),[y,_]=o.useState(null),[A,D]=o.useState(!1),[I,F]=o.useState(null),[E,P]=o.useState(""),M=o.useCallback(()=>{u(null),Q.getPacks().then(V=>l(V.packs)).catch(V=>u(Xe(r,V,"loadError"))).finally(()=>c(!1))},[r]);o.useEffect(()=>{M()},[M]);const $=async()=>{if(Yn(p)){x(r("packNameLength"));return}k(!0),x(null);try{await Q.createPack(p.trim()),h(""),a(r("packCreated"),"success"),M()}catch(V){a(Xe(r,V,"failedToCreatePack"),"error")}finally{k(!1)}},G=async()=>{if(S){if(Yn(R)){a(r("packNameLength"),"warning");return}k(!0);try{await Q.updatePack(S.id,R.trim()),a(r("packRenamed"),"success"),b(null),M()}catch(V){a(Xe(r,V,"failedToRenamePack"),"error")}finally{k(!1)}}},ne=async()=>{if(y){k(!0);try{await Q.deletePack(y.id,A),a(r("packDeleted"),"success"),_(null),D(!1),M()}catch(V){a(Xe(r,V,"failedToDeletePack"),"error")}finally{k(!1)}}},se=async()=>{if(I){if(!E){a(r("noDestinationPack"),"warning");return}k(!0);try{await Q.mergePack(I.id,E),a(r("packsMerged"),"success"),F(null),P(""),M()}catch(V){a(Xe(r,V,"failedToMerge"),"error")}finally{k(!1)}}};return N?e.jsx(oh,{packId:N,isConnected:t,gifEnabled:s,onOpenInCreate:n,onBack:()=>{w(null),M()}}):e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:p,onChange:V=>{const q=V.target.value;h(q),g&&x(Yn(q)?r("packNameLength"):null)},onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),$())},placeholder:r("newPackPlaceholder"),"aria-label":r("packName"),dir:"auto",maxLength:Gc+20,className:"min-w-0 flex-1"}),e.jsxs(U,{variant:"primary",onClick:()=>void $(),disabled:f,icon:e.jsx(_t,{size:16}),className:"shrink-0 whitespace-nowrap",children:[e.jsx("span",{className:"sm:hidden",children:r("create")}),e.jsx("span",{className:"hidden sm:inline",children:r("createPack")})]})]}),g&&e.jsx("p",{className:"text-xs text-danger",children:g}),d&&e.jsx(vt,{text:r("loading")}),m&&!d&&e.jsx(Pe,{kind:"error",description:m,action:e.jsx(U,{onClick:M,children:r("retryLoad")})}),!d&&!m&&i.length===0&&e.jsx(Pe,{kind:"empty",icon:e.jsx(ar,{size:28,className:"text-muted"}),description:r("noPacks")}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:i.map(V=>e.jsxs(he,{className:"flex items-center gap-3",children:[e.jsxs(U,{variant:"ghost",onClick:()=>w(V.id),className:"h-auto min-h-11 min-w-0 flex-1 justify-start gap-3 px-1","aria-label":r("openPack"),children:[V.coverUrl?e.jsx("img",{src:V.coverUrl,alt:"",loading:"lazy",className:"w-14 h-14 rounded-xl object-cover bg-panel-hover shrink-0"}):e.jsx("span",{className:"w-14 h-14 rounded-xl bg-panel-hover text-muted flex items-center justify-center shrink-0",children:e.jsx(ar,{size:20})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx(ze,{lines:2,className:"font-bold text-text-main text-start",children:V.name}),e.jsx("span",{className:"block text-xs text-muted",children:de(r("stickerCount"),{n:V.count})})]})]}),e.jsxs(mt,{label:r("moreActions"),children:[e.jsx(_e,{icon:e.jsx(as,{size:16}),onSelect:()=>{b(V),j(V.name)},children:r("renamePack")}),e.jsx(_e,{icon:e.jsx(Qd,{size:16}),onSelect:()=>{F(V),P("")},children:r("merge")}),e.jsx(pn,{}),e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>{_(V),D(!1)},children:r("deletePack")})]})]},V.id))}),e.jsx(Ye,{isOpen:S!==null,onClose:()=>b(null),title:r("renamePack"),footer:e.jsxs("div",{className:"flex w-full justify-end gap-2",children:[e.jsx(U,{onClick:()=>b(null),children:r("cancel")}),e.jsx(U,{variant:"primary",onClick:()=>void G(),disabled:f,children:r("save")})]}),children:e.jsx(be,{value:R,onChange:V=>j(V.target.value),"aria-label":r("packName"),dir:"auto"})}),e.jsx(Ye,{isOpen:y!==null,onClose:()=>_(null),title:r("deletePackTitle"),footer:e.jsxs("div",{className:"flex w-full justify-end gap-2",children:[e.jsx(U,{onClick:()=>_(null),children:r("cancel")}),e.jsx(U,{variant:"danger",onClick:()=>void ne(),disabled:f,children:r("delete")})]}),children:e.jsx(st,{name:"delete-pack-mode",value:A?"stickers":"keep",onChange:V=>D(V==="stickers"),options:[{value:"keep",label:r("deleteKeepStickers")},{value:"stickers",label:r("deletePackAndStickers")}]})}),e.jsx(Ye,{isOpen:I!==null,onClose:()=>F(null),title:r("mergeTitle"),footer:e.jsxs("div",{className:"flex w-full justify-end gap-2",children:[e.jsx(U,{onClick:()=>F(null),children:r("cancel")}),e.jsx(U,{variant:"primary",onClick:()=>void se(),disabled:f||!E,children:r("confirmMerge")})]}),children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-sm text-text-main",children:r("mergeConfirmBody")}),e.jsx("label",{className:"text-xs font-bold",htmlFor:"merge-into",children:r("mergeInto")}),e.jsxs(Re,{id:"merge-into",value:E,onChange:V=>P(V.target.value),children:[e.jsx("option",{value:"",children:r("selectPack")}),i.filter(V=>V.id!==(I==null?void 0:I.id)).map(V=>e.jsx("option",{value:V.id,children:V.name},V.id))]})]})})]})},dh=["library","packs","favorites","create","recent"];function tl(){const t=window.location.hash.replace(/^#/,"");if(t.startsWith("stickers/")){const s=t.slice(9);if(dh.includes(s))return s}return"library"}const uh=({isConnected:t})=>{const{t:s}=me(),{toast:n}=qe(),[r,a]=o.useState(tl),[i,l]=o.useState(r==="create"),[d,c]=o.useState(null),[m,u]=o.useState(null),[p,h]=o.useState(0),[g,x]=o.useState(null),[f,k]=o.useState(0),N=o.useCallback(()=>{let y=!0;return u(null),Q.getStickerCapabilities().then(_=>{y&&c(_)}).catch(_=>{y&&u(hr(s,_))}),()=>{y=!1}},[s]);o.useEffect(()=>{if(!(p<0))return N()},[N,p]);const w=o.useCallback(y=>{a(y),y==="create"&&l(!0);const _=`stickers/${y}`;window.location.hash.replace(/^#/,"")!==_&&(window.location.hash=_)},[]);o.useEffect(()=>{const y=()=>a(tl());return window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[]),o.useEffect(()=>{r==="create"&&l(!0)},[r]),o.useEffect(()=>(el(y=>{if(y.type==="saved"){n(y.created?s("stickerCreated"):s("alreadyInLibrary"),y.created?"success":"info"),y.qualityReduced&&n(s("qualityReduced"),"info"),k(_=>_+1);return}n(Pr(s,y.code),"error")}),()=>el(null)),[s,n]),o.useEffect(()=>{const y=()=>{const A=Xp();A&&(x(A),l(!0),a("create"),window.location.hash.startsWith("#stickers/create")||(window.location.hash="stickers/create"))};y();const _=()=>{document.visibilityState==="visible"&&y()};return document.addEventListener("visibilitychange",_),()=>document.removeEventListener("visibilitychange",_)},[]);const S=o.useCallback(()=>{Zp(),x(null)},[]),b=o.useCallback(async y=>{try{const _=await fetch(y.url,{credentials:"same-origin"});if(!_.ok)throw new Error(String(_.status));const A=await _.blob(),D=y.name.trim(),I=D?D.toLowerCase().endsWith(".webp")?D:`${D}.webp`:"sticker.webp";x({blob:A,name:I,source:"PANEL_UPLOAD",...ws()?{existingId:y.id}:{}}),w("create")}catch(_){n(hr(s,_),"error")}},[w,s,n]),R=d!==null&&!d.webp,j=[{id:"library",label:s("library"),icon:e.jsx(Hd,{size:16})},{id:"packs",label:s("packs"),icon:e.jsx(ar,{size:16})},{id:"favorites",label:s("favorites"),icon:e.jsx(qs,{size:16})},{id:"create",label:s("create"),icon:e.jsx(Od,{size:16})},{id:"recent",label:s("recent"),icon:e.jsx(Pl,{size:16})}];return e.jsxs("div",{className:"flex flex-col gap-5 sm:gap-6 min-w-0",children:[e.jsx(Kt,{icon:e.jsx(Rr,{size:24}),title:s("stickers"),description:s("stickersDesc")}),R&&e.jsxs("div",{className:"rounded-2xl border border-warn/30 bg-warn/10 p-4 flex items-center gap-3",children:[e.jsx(tn,{size:20,className:"text-warn shrink-0"}),e.jsx("span",{className:"text-sm text-warn font-medium",children:s("stickerErr_ENCODER_MISSING")})]}),e.jsx("div",{className:"-mx-4 overflow-x-auto no-scrollbar px-4 sm:mx-0 sm:px-0","data-tour":"stickers-tabs",children:e.jsx(ls,{"aria-label":s("stickers"),className:"min-w-max",value:r,onChange:w,options:j.map(y=>({value:y.id,label:y.label,icon:y.icon}))})}),r==="library"&&e.jsx(Ja,{preset:"all",isConnected:t,gifEnabled:(d==null?void 0:d.gif)===!0,refreshKey:f,onOpenInCreate:y=>void b(y),onGoCreate:()=>w("create")}),r==="favorites"&&e.jsx(Ja,{preset:"favorites",isConnected:t,gifEnabled:(d==null?void 0:d.gif)===!0,refreshKey:f,onOpenInCreate:y=>void b(y),onGoCreate:()=>w("create")}),r==="recent"&&e.jsx(Ja,{preset:"recent",isConnected:t,gifEnabled:(d==null?void 0:d.gif)===!0,refreshKey:f,onOpenInCreate:y=>void b(y),onGoCreate:()=>w("create")}),r==="packs"&&e.jsx(ch,{isConnected:t,gifEnabled:(d==null?void 0:d.gif)===!0,onOpenInCreate:y=>void b(y)}),i&&e.jsx("div",{className:r==="create"?"":"hidden",children:e.jsx(Yp,{capabilities:d,capsError:m,onRetryCaps:()=>h(y=>y+1),incoming:g,onConsumedIncoming:S,isConnected:t,onGoLibrary:()=>w("library"),onCreated:()=>k(y=>y+1)})})]})};function mh(t){return t==="active"||t==="grace"||t==="canceled"}const xh=new Set(["none","expired","unverified","inactive"]),ph=5*6e4;function hh(t=ph,s=Date.now){const n=new Map;return{take(r){const a=[...r].sort().join(`
456
+ `),i=s(),l=n.get(a);return l!==void 0&&i-l<t?!1:(n.set(a,i),!0)}}}async function fh({purchases:t,state:s,claim:n,readState:r,refresh:a,gate:i}){const l=t.filter(u=>u.status==="purchased"),d=l.filter(u=>!u.acknowledged),c=l.filter(u=>u.acknowledged);if(d.length>0&&await n(d),c.length===0)return d.length>0?"claimed":"none";const m=d.length>0?await r():s;return!m||!xh.has(m)?d.length>0?"claimed":"none":i.take(c.map(u=>u.purchaseToken))?(await a(),"refreshed"):"skipped"}function td(){let t=Promise.resolve();return{enqueue(s){return new Promise((n,r)=>{t=t.catch(()=>{}).then(async()=>{try{const a=await s();n(a)}catch(a){r(a)}})})}}}function gh(t){return t==="name"?"Levix":t==="count"?"3":`<${t}>`}function bh(t){return t.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(s,n)=>gh(n))}function yh(t,s,n,r,a){var i;return s==="original"||t===n?r:((i=a[t])==null?void 0:i.trim())||""}function nl(t,s){var r,a;if(!(t!=null&&t.ok)||t.basePlanId!=="monthly"||t.billingPeriod!=="P1M"||!t.offerToken||!((r=t.formattedPrice)!=null&&r.trim()))return null;const n=t.introduction;return t.offerId!==null&&(t.offerId!=="intro-3months"||!n||n.billingPeriod!=="P1M"||n.billingCycleCount!==3||!((a=n.formattedPrice)!=null&&a.trim()))||t.offerId===null&&n!=null?null:{product:t,price:de(s("plusPrice"),{price:(n==null?void 0:n.formattedPrice)??t.formattedPrice,period:s("plusMonthly")}),disclosure:n?de(s("plusIntroDisclosure"),{introPrice:n.formattedPrice,months:n.billingCycleCount,price:t.formattedPrice,renewalMonth:n.billingCycleCount+1}):de(s("plusDisclosure"),{price:t.formattedPrice})}}const qn=["ar","en","pt-BR","es-419"],Ya={ar:"العربية",en:"English","pt-BR":"Português (Brasil)","es-419":"Español (Latinoamérica)"};function Wn(t){return qn.includes(t)}const Oe={templateText:1e3,autoReplyChats:100,keywords:20,keywordChars:40,instructions:1e3,globalPerHour:{min:1,max:200},cooldownSeconds:{min:0,max:3600},perSenderPerHour:{min:1,max:60},perChatPerHour:{min:1,max:200}},vh=/^(?:\d+@s\.whatsapp\.net|\d+@lid|\d+@g\.us)$/;function jh(t){return t.endsWith("@g.us")}const wh=["all","mention","keywords"];function Qa(t){return Number.parseInt(t,10)}function kh({onClose:t,onSaved:s,chat:n,existingJids:r}){var J;const{t:a}=me(),[i,l]=o.useState((n==null?void 0:n.jid)??""),[d,c]=o.useState((n==null?void 0:n.enabled)??!0),[m,u]=o.useState((n==null?void 0:n.trigger)??(n&&jh(n.jid)?"mention":"all")),[p,h]=o.useState((n==null?void 0:n.keywords)??[]),[g,x]=o.useState((n==null?void 0:n.instructions)??""),[f,k]=o.useState(String((n==null?void 0:n.cooldownSeconds)??20)),[N,w]=o.useState(String((n==null?void 0:n.perSenderPerHour)??10)),[S,b]=o.useState(String((n==null?void 0:n.perChatPerHour)??30)),[R,j]=o.useState(((J=n==null?void 0:n.globalMemory)==null?void 0:J.read)??!1),[y,_]=o.useState(!1),[A,D]=o.useState(null),[I,F]=o.useState(null),[E,P]=o.useState(null),[M,$]=o.useState(null),[G,ne]=o.useState(null),se=o.useRef(n!==null),V=(Y,L)=>de(a("plusAutoReplyRange"),{min:Y,max:L}),q=Y=>a(Y==="mention"?"plusTriggerMention":Y==="keywords"?"plusTriggerKeywords":"plusTriggerAll");function C(Y){F(Y==="long"?a("plusAutoReplyKeywordTooLong"):Y==="max"?a("plusAutoReplyKeywordMax"):Y==="duplicate"?a("plusAutoReplyKeywordDuplicate"):null)}function O(Y){Y.preventDefault();const L=i.trim(),v=vh.test(L)?r.includes(L)?a("plusAutoReplyDuplicateJid"):null:a("plusAutoReplyInvalidJid"),T=Qa(f),te=Number.isInteger(T)&&T>=Oe.cooldownSeconds.min&&T<=Oe.cooldownSeconds.max?null:V(Oe.cooldownSeconds.min,Oe.cooldownSeconds.max),oe=Qa(N),ye=Number.isInteger(oe)&&oe>=Oe.perSenderPerHour.min&&oe<=Oe.perSenderPerHour.max?null:V(Oe.perSenderPerHour.min,Oe.perSenderPerHour.max),fe=Qa(S),we=Number.isInteger(fe)&&fe>=Oe.perChatPerHour.min&&fe<=Oe.perChatPerHour.max?null:V(Oe.perChatPerHour.min,Oe.perChatPerHour.max);D(v),P(te),$(ye),ne(we),!(v||te||ye||we)&&s({jid:L,enabled:d,trigger:m,keywords:p,instructions:g.trim(),cooldownSeconds:T,perSenderPerHour:oe,perChatPerHour:fe,globalMemory:{read:R}})}return e.jsxs(e.Fragment,{children:[e.jsx(Ye,{isOpen:!0,onClose:t,title:a(n?"plusAutoReplyEditChat":"plusAutoReplyAddChat"),maxWidth:"40rem",footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"secondary",onClick:t,children:a("cancel")}),e.jsx(U,{variant:"primary",type:"submit",form:"plus-auto-reply-chat",children:a("save")})]}),children:e.jsxs("form",{id:"plus-auto-reply-chat",className:"flex flex-col gap-4",onSubmit:Y=>O(Y),children:[e.jsx(Je,{checked:d,label:a("plusAutoReplyChatOn"),onChange:Y=>c(Y)}),e.jsx(re,{label:a("plusAutoReplyJid"),htmlFor:"plus-chat-jid",error:A,children:e.jsx(be,{id:"plus-chat-jid",technical:!0,value:i,placeholder:"201234567890@s.whatsapp.net","aria-invalid":A?!0:void 0,onChange:Y=>{const L=Y.target.value;l(L),D(null),se.current||u(L.trim().endsWith("@g.us")?"mention":"all")}})}),e.jsx("p",{className:"text-xs text-muted",children:a("plusAutoReplyJidHint")}),e.jsx(re,{label:a("plusAutoReplyTrigger"),htmlFor:"plus-chat-trigger",children:e.jsx(Re,{id:"plus-chat-trigger",value:m,onChange:Y=>{se.current=!0,u(Y.target.value)},children:wh.map(Y=>e.jsx("option",{value:Y,children:q(Y)},Y))})}),m==="keywords"&&e.jsxs(re,{label:a("plusAutoReplyKeywords"),error:I,children:[e.jsx(ul,{value:p,onChange:h,max:Oe.keywords,maxLength:Oe.keywordChars,onReject:C,removeLabel:Y=>de(a("removeKeyword"),{word:Y}),countLabel:de(a("plusAutoReplyKeywordCount"),{n:p.length,max:Oe.keywords}),placeholder:a("keywordsPlaceholder"),"aria-label":a("plusAutoReplyKeywords"),"aria-invalid":I?!0:void 0}),e.jsx("p",{className:"text-xs text-muted",children:a("plusAutoReplyKeywordsHint")})]}),e.jsx(re,{label:a("plusAutoReplyInstructions"),htmlFor:"plus-chat-instructions",description:de(a("plusTextCount"),{n:g.length,max:Oe.instructions}),children:e.jsx(wt,{id:"plus-chat-instructions",dir:"auto",rows:4,maxLength:Oe.instructions,value:g,onChange:Y=>x(Y.target.value)})}),e.jsx("p",{className:"text-xs text-muted",children:a("plusAutoReplyInstructionsHint")}),e.jsx(cn,{title:a("plusAutoReplyGlobalMemoryTitle"),children:e.jsx(Je,{checked:R,label:a("plusAutoReplyGlobalMemoryRead"),onChange:Y=>{Y?_(!0):j(!1)}})}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(re,{label:a("plusAutoReplyCooldown"),htmlFor:"plus-chat-cooldown",error:E,children:e.jsx(be,{id:"plus-chat-cooldown",type:"number",inputMode:"numeric",min:Oe.cooldownSeconds.min,max:Oe.cooldownSeconds.max,value:f,"aria-invalid":E?!0:void 0,onChange:Y=>{k(Y.target.value),P(null)}})}),e.jsx(re,{label:a("plusAutoReplyPerSender"),htmlFor:"plus-chat-sender",error:M,children:e.jsx(be,{id:"plus-chat-sender",type:"number",inputMode:"numeric",min:Oe.perSenderPerHour.min,max:Oe.perSenderPerHour.max,value:N,"aria-invalid":M?!0:void 0,onChange:Y=>{w(Y.target.value),$(null)}})}),e.jsx(re,{label:a("plusAutoReplyPerChat"),htmlFor:"plus-chat-per-chat",error:G,children:e.jsx(be,{id:"plus-chat-per-chat",type:"number",inputMode:"numeric",min:Oe.perChatPerHour.min,max:Oe.perChatPerHour.max,value:S,"aria-invalid":G?!0:void 0,onChange:Y=>{b(Y.target.value),ne(null)}})})]})]})}),e.jsx(ut,{isOpen:y,onClose:()=>_(!1),onConfirm:()=>{j(!0),_(!1)},title:a("plusAutoReplyGlobalMemoryConfirmTitle"),description:a("plusAutoReplyGlobalMemoryReadWarning"),confirmLabel:a("turnOn"),cancelLabel:a("cancel"),variant:"primary"})]})}const Ys="/plus/ext",os=t=>Q.get(`${Ys}${t}`),fn=(t,s)=>Q.put(`${Ys}${t}`,s),Nh=(t,s)=>Q.post(`${Ys}${t}`,s??{}),Sh=t=>Q.delete(`${Ys}${t}`),sl={inactive:"plusExtErrorInactive",BAD_REQUEST:"plusExtErrorBadRequest",INVALID_TEMPLATE:"plusExtErrorInvalidTemplate",UNKNOWN_PLACEHOLDER:"plusExtErrorUnknownPlaceholder",NOT_CUSTOMIZABLE:"plusExtErrorNotCustomizable",TOO_LONG:"plusExtErrorTooLong",INVALID_CHAT:"plusExtErrorInvalidChat",LIMIT:"plusExtErrorLimit",NOT_FOUND:"plusExtErrorNotFound",TRANSLATE_FAILED:"plusExtErrorTranslateFailed",network:"plusErrorNetwork"};function xt(t){var n;if(!(t instanceof et))return"network";if(t.status===409)return"inactive";if(t.status===0)return"network";if(t.code)return t.code;const s=(n=t.data)==null?void 0:n.error;return typeof s=="string"&&s?s:"FAILED"}function bt(t,s,n="plusExtErrorFailed"){const r=xt(s),a=Object.hasOwn(sl,r)?sl[r]:void 0;return a?t(a):je(t,s,n)}function Ch(){return Q.get("/plus/status")}async function al(t,s){try{return await t()}catch(n){throw xt(n)==="inactive"&&s(),n}}function Eh({onInactive:t}){const{t:s}=me(),[n,r]=o.useState(null),[a,i]=o.useState(!0),[l,d]=o.useState(null),[c,m]=o.useState(0);return o.useEffect(()=>{let u=!0;return i(!0),os("/auto-reply").then(p=>{u&&(r(p),d(null))}).catch(p=>{if(!u)return;xt(p)==="inactive"&&t(),d(bt(s,p))}).finally(()=>{u&&i(!1)}),()=>{u=!1}},[c,t,s]),a&&!n?e.jsx(vt,{text:s("loading")}):l&&!n?e.jsx(Pe,{kind:"error",icon:e.jsx(Cn,{size:28}),description:l,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>m(u=>u+1),children:s("retry")})}):n?e.jsx(Ah,{config:n,onSaved:r,onInactive:t}):null}function Ah({config:t,onSaved:s,onInactive:n}){const{t:r}=me(),a=o.useMemo(()=>JSON.stringify(t.chats),[t.chats]),i=o.useMemo(()=>({globalPerHour:t.globalPerHour,chats:t.chats}),[t.globalPerHour,a]),l=wn(i,"plusExtErrorFailed",bt),d=o.useRef(i);o.useEffect(()=>{if(d.current!==i){const E=d.current;d.current=i;const P=l.draft.globalPerHour!==E.globalPerHour,M=JSON.stringify(l.draft.chats)!==JSON.stringify(E.chats);(P||M)&&l.setDraft({globalPerHour:P?l.draft.globalPerHour:i.globalPerHour,chats:M?l.draft.chats:i.chats})}},[i,l.draft.globalPerHour,l.draft.chats,l.setDraft]);const[c,m]=o.useState(!1),[u,p]=o.useState(!1),[h,g]=o.useState(null),x=o.useRef(td()),f=o.useRef(t);f.current=t;const[k,N]=o.useState(null),[w,S]=o.useState(null),[b,R]=o.useState(null),j=l.draft.chats,y=j.length>=Oe.autoReplyChats,_=E=>r(E==="mention"?"plusTriggerMention":E==="keywords"?"plusTriggerKeywords":"plusTriggerAll");async function A(E){m(!0),g(null);try{const P=await x.current.enqueue(async()=>{const M=f.current;return fn("/auto-reply",{...M,enabled:E})});f.current=P,s(P)}catch(P){xt(P)==="inactive"&&n(),g(bt(r,P))}finally{m(!1)}}async function D(E){p(!0),g(null);try{const P=await x.current.enqueue(async()=>{const M=f.current;return fn("/auto-reply",{...M,killSwitch:E})});f.current=P,s(P)}catch(P){xt(P)==="inactive"&&n(),g(bt(r,P))}finally{p(!1)}}function I(E){E.preventDefault();const P=l.draft.globalPerHour,M=Number.isInteger(P)&&P>=Oe.globalPerHour.min&&P<=Oe.globalPerHour.max;R(M?null:de(r("plusAutoReplyRange"),{min:Oe.globalPerHour.min,max:Oe.globalPerHour.max})),M&&l.save(async $=>{try{const G=await x.current.enqueue(async()=>{const ne=f.current;return fn("/auto-reply",{...ne,globalPerHour:$.globalPerHour,chats:$.chats})});f.current=G,s(G)}catch(G){throw xt(G)==="inactive"&&n(),G}})}function F(E){l.setField("chats",j.map(P=>P.jid===E.jid?{...P,enabled:!P.enabled}:P))}return e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-muted",children:r("plusAutoReplyIntro")}),e.jsxs("form",{className:"flex flex-col gap-4",onSubmit:I,children:[e.jsx(Je,{checked:t.enabled,disabled:c,label:r("plusAutoReplyEnabled"),onChange:E=>void A(E)}),e.jsx(Je,{checked:t.killSwitch,disabled:u,label:r("plusAutoReplyKill"),description:r("plusAutoReplyKillHint"),onChange:E=>void D(E)}),h&&e.jsx("p",{role:"alert",className:"text-xs text-danger",children:h}),e.jsx(re,{label:r("plusAutoReplyGlobalLimit"),htmlFor:"plus-auto-reply-global",error:b,children:e.jsx(be,{id:"plus-auto-reply-global",type:"number",inputMode:"numeric",min:Oe.globalPerHour.min,max:Oe.globalPerHour.max,value:String(l.draft.globalPerHour),"aria-invalid":b?!0:void 0,onChange:E=>{l.setField("globalPerHour",Number(E.target.value)),R(null)}})}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"text-sm font-bold text-text-main",children:r("plusAutoReplyChats")}),e.jsx("span",{className:"text-xs text-muted tabular-nums",children:de(r("plusAutoReplyChatsCount"),{n:j.length,max:Oe.autoReplyChats})})]}),e.jsx(U,{variant:"secondary",icon:e.jsx(_t,{size:16}),disabled:y,onClick:()=>N({chat:null}),children:r("plusAutoReplyAddChat")})]}),j.length===0?e.jsx(Pe,{kind:"empty",icon:e.jsx(Cn,{size:26}),description:r("plusAutoReplyEmpty")}):e.jsx("ul",{className:"flex flex-col gap-2",children:j.map(E=>e.jsxs("li",{className:"flex flex-col gap-2 rounded-xl border border-line bg-panel-raised/40 p-3 sm:flex-row sm:items-start",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("span",{dir:"ltr",className:"block break-all font-mono text-sm text-text-main",children:E.jid}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:de(r("plusAutoReplyRowHint"),{cooldown:E.cooldownSeconds,sender:E.perSenderPerHour,chat:E.perChatPerHour})}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[e.jsx(Ce,{children:_(E.trigger)}),e.jsx(Ce,{tone:E.enabled?"ok":"neutral",children:E.enabled?r("plusAutoReplyOn"):r("plusAutoReplyOff")}),E.keywords.length>0&&e.jsx(Ce,{children:de(r("plusAutoReplyKeywordCount"),{n:E.keywords.length,max:Oe.keywords})})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1 self-end sm:self-start",children:[e.jsx(xe,{label:r("plusAutoReplyEditChat"),icon:e.jsx(as,{size:16}),onClick:()=>N({chat:E})}),e.jsxs(mt,{label:r("more"),children:[e.jsx(_e,{onSelect:()=>F(E),children:E.enabled?r("plusAutoReplyDisable"):r("plusAutoReplyEnable")}),e.jsx(_e,{danger:!0,icon:e.jsx(lt,{size:16}),onSelect:()=>S(E.jid),children:r("plusAutoReplyRemove")})]})]})]},E.jid))})]}),e.jsx(kn,{dirty:l.dirty,saving:l.status==="saving",justSaved:l.status==="saved",error:l.error,onDiscard:l.revert,saveLabel:r("save"),discardLabel:r("discard"),unsavedLabel:r("unsavedChanges"),savedLabel:r("saved")})]}),k&&e.jsx(kh,{chat:k.chat,existingJids:j.filter(E=>{var P;return E.jid!==((P=k.chat)==null?void 0:P.jid)}).map(E=>E.jid),onClose:()=>N(null),onSaved:E=>{const P=k.chat;l.setField("chats",P?j.map(M=>M.jid===P.jid?E:M):[...j,E]),N(null)}}),e.jsx(ut,{isOpen:w!==null,onClose:()=>S(null),onConfirm:()=>{w&&l.setField("chats",j.filter(E=>E.jid!==w)),S(null)},title:r("plusAutoReplyRemoveTitle"),description:r("plusAutoReplyRemoveBody"),confirmLabel:r("plusAutoReplyRemove"),cancelLabel:r("cancel")})]})}const Rh={ai:"plusAreaAi",core:"plusAreaCore",group:"plusAreaGroup",help:"plusAreaHelp",lang:"plusAreaLang",moderation:"plusAreaModeration",schedules:"plusAreaSchedules",stickers:"plusAreaStickers",tools:"plusAreaTools"},_h="plusAreaOther",Lh={count:"plusPlaceholderCount",name:"plusPlaceholderName",user:"plusPlaceholderUser",group:"plusPlaceholderGroup",n:"plusPlaceholderN",emoji:"plusPlaceholderEmoji",prefix:"plusPlaceholderPrefix",command:"plusPlaceholderCommand"},Mh="plusPlaceholderValue",Th=new Set(["add","all","antilink","antispam","approveall","autodelete","autoschedule","blacklist","block","calc","clearwarns","debt","deletenote","deleteschedule","demote","digit","flagged","gemini","group","help","kick","lang","listschedules","loop","md","media","members","memory","mod","note","notes","pack","packs","perm","ping","policy","poll","prayer","promote","qr","rand","removeall","restart","rules","save","schedule","score","send","setname","setpp","setprefix","setrules","setwarn","shortlink","status","sticker","stickers","stopbot","stt","tagadmins","todo","toimage","translate","tts","unblock","update","warn","warns","weather","welcome"]),Ph=/\{([A-Za-z_][A-Za-z0-9_]*)\}/g;function yr(t){const s=t.split(".").filter(Boolean);return s[0]==="bot"&&s.length>=2?s[1]??"":s[0]??""}function Qn(t){return Rh[yr(t)]??_h}function vr(t){const s=t.split(".").filter(Boolean);if(s[0]!=="bot"||s.length<3)return null;const n=s[2]??"";return Th.has(n)?n:null}function Dh(t){return Lh[t]??Mh}function Ih(t){const s=[];let n=0;for(const r of t.matchAll(Ph)){const a=r.index??0;a>n&&s.push({kind:"text",text:t.slice(n,a)}),s.push({kind:"token",text:r[0]}),n=a+r[0].length}return n<t.length&&s.push({kind:"text",text:t.slice(n)}),s.length===0&&s.push({kind:"text",text:t}),s}function zh(t){return t.split(`
457
+ `).length>2?!0:t.length>96}const Oh=["auto","original"];function Ls({text:t}){return Ih(t).map((n,r)=>n.kind==="token"?e.jsx(ot,{className:"text-xs",children:n.text},`${n.text}-${r}`):e.jsx("span",{children:n.text},`text-${r}`))}function Fh(t){const s=new Set;for(const n of t.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g))n[1]&&s.add(n[1]);return[...s]}function Bh({open:t,item:s,onClose:n,onSaved:r,onRefresh:a,onInactive:i}){const{t:l,language:d}=me(),c=o.useRef(s);c.current=s;const[m,u]=o.useState("auto"),[p,h]=o.useState(Wn(d)?d:"en"),[g,x]=o.useState(""),[f,k]=o.useState({}),[N,w]=o.useState([]),[S,b]=o.useState(null),[R,j]=o.useState(null),[y,_]=o.useState(!1),[A,D]=o.useState(!1),[I,F]=o.useState(!1),[E,P]=o.useState(null),[M,$]=o.useState(!1),[G,ne]=o.useState(0),se=o.useRef(null);o.useEffect(()=>{if(!t)return;const ee=c.current;if(!ee)return;const le=ee.override,Se=Wn(d)?d:"en",X=(le==null?void 0:le.mode)??"auto",ve=(le==null?void 0:le.source.locale)??Se,ue=(le==null?void 0:le.source.text)??ee.catalog[Se]??ee.catalog.en??"";u(X),h(ve),x(ue);const ke={};for(const Me of(le==null?void 0:le.manual)??[]){const Te=le==null?void 0:le.values[Me];typeof Te=="string"&&(ke[Me]=Te)}k(ke),se.current={mode:X,sourceLocale:ve,text:ue,manual:ke},w((le==null?void 0:le.failed)??[]),b(null),j(null),_(!1),D(!1),F(!1),ne(Me=>Me+1)},[t,s==null?void 0:s.key,d]);const q=!!(se.current&&(m!==se.current.mode||p!==se.current.sourceLocale||g!==se.current.text||qn.some(ee=>{var le;return(f[ee]??"").trim()!==(((le=se.current)==null?void 0:le.manual[ee])??"").trim()})))&&g.trim().length>0,C=yh(p,m,p,g,f),O=bh(C);o.useEffect(()=>{var X;if(!t)return;const ee=(X=c.current)==null?void 0:X.key;if(!ee||q)return;let le=!0;const Se=window.setTimeout(()=>{$(!1),os(`/preview?key=${encodeURIComponent(ee)}&locale=${encodeURIComponent(p)}`).then(ve=>{le&&P(ve.text)}).catch(ve=>{le&&(xt(ve)==="inactive"&&i(),P(null),$(!0))})},250);return()=>{le=!1,window.clearTimeout(Se)}},[t,s==null?void 0:s.key,p,G,i,q]);const J=(s==null?void 0:s.catalog)??{},Y=(s==null?void 0:s.placeholders)??[],L=Wn(d)?d:"en",v=s?s.catalog[L]??s.catalog.en??"":"",T=s?vr(s.key):null,te=de(l("plusCharactersUsed"),{n:g.length,max:Oe.templateText});async function oe(ee){var ue;if(ee.preventDefault(),!s)return;const le=g.trim();if(!le){b(l("plusTextRequired"));return}if(le.length>Oe.templateText){b(l("plusTextTooLong"));return}const Se=Fh(le).filter(ke=>!Y.includes(ke));if(Se.length>0){b(de(l("plusPlaceholderUnknown"),{names:Se.join(", ")}));return}const X={};for(const ke of qn){if(ke===p)continue;const Me=(ue=f[ke])==null?void 0:ue.trim();if(Me){if(Me.length>Oe.templateText){b(l("plusTextTooLong"));return}X[ke]=Me}}const ve={mode:m,locale:p,text:le};Object.keys(X).length>0&&(ve.manual=X),_(!0),b(null),j(null);try{const ke=await fn(`/templates/${encodeURIComponent(s.key)}`,ve);w(ke.override.failed??[]),(ke.override.failed??[]).length>0&&j(l("plusExtErrorTranslateFailed")),se.current={mode:m,sourceLocale:p,text:le,manual:X},r(ke.override),ne(Me=>Me+1)}catch(ke){const Me=xt(ke);if(Me==="inactive"&&i(),Me==="TRANSLATE_FAILED"){j(l("plusExtErrorTranslateFailed"));const Te=ke instanceof et?ke.data??{}:{};Te.override&&(w(Te.override.failed??[]),r(Te.override)),a()}else b(bt(l,ke))}finally{_(!1)}}async function ye(){if(s){D(!0),b(null);try{await Sh(`/templates/${encodeURIComponent(s.key)}`),r(null),n()}catch(ee){xt(ee)==="inactive"&&i(),b(bt(l,ee))}finally{D(!1),F(!1)}}}const fe=N.map(ee=>Ya[ee]??ee).join(", "),we=qn.filter(ee=>ee!==p),Le=we.filter(ee=>(f[ee]??"").trim().length>0).length;return e.jsxs(e.Fragment,{children:[e.jsx(Ye,{isOpen:t,onClose:n,title:l("plusMessagesEdit"),description:s?e.jsxs("span",{className:"inline-flex max-w-full flex-wrap items-center gap-2",children:[e.jsx("span",{children:l(Qn(s.key))}),T&&e.jsx(ot,{className:"text-xs",children:`!${T}`}),s.override&&e.jsx(Ce,{tone:"info",children:l("plusMessagesCustomized")})]}):void 0,maxWidth:"44rem",footer:e.jsxs(e.Fragment,{children:[e.jsxs(mt,{label:l("more"),align:"start",children:[e.jsx(_e,{icon:e.jsx(qo,{size:16}),disabled:Le===0,onSelect:()=>k({}),children:l("plusClearManual")}),e.jsx(pn,{}),e.jsx(_e,{danger:!0,icon:e.jsx(ft,{size:16}),onSelect:()=>F(!0),children:l("plusResetDefault")})]}),e.jsx(U,{variant:"secondary",onClick:n,disabled:y,children:l("cancel")}),e.jsx(U,{variant:"primary",type:"submit",form:"plus-template-form",loading:y,children:l("save")})]}),children:e.jsxs("form",{id:"plus-template-form",className:"flex flex-col gap-4",onSubmit:ee=>void oe(ee),children:[S&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:S}),R&&e.jsx("p",{role:"status",className:"text-sm text-warn",children:R}),e.jsx(re,{label:l("plusMessagesMode"),description:l(m==="auto"?"plusModeAutoHint":"plusModeOriginalHint"),children:e.jsx(Rt,{"aria-label":l("plusMessagesMode"),className:"flex w-full flex-wrap",value:m,onChange:u,options:Oh.map(ee=>({value:ee,label:l(ee==="auto"?"plusModeAuto":"plusModeOriginal")}))})}),e.jsx(re,{label:l("plusSourceLanguage"),htmlFor:"plus-template-locale",children:e.jsx(Re,{id:"plus-template-locale",value:p,onChange:ee=>{const le=ee.target.value;Wn(le)&&h(le)},children:qn.map(ee=>e.jsx("option",{value:ee,dir:"auto",children:Ya[ee]},ee))})}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("p",{className:"text-xs font-bold text-text-main",children:l("plusMessagesDefault")}),e.jsx("div",{dir:"auto",className:"whitespace-pre-wrap break-words text-sm text-text-main",children:v?e.jsx(Ls,{text:v}):e.jsx("span",{className:"text-muted",children:l("plusMessagesNoPreview")})})]}),e.jsxs(re,{label:l("plusSourceText"),htmlFor:"plus-template-text",children:[e.jsx(wt,{id:"plus-template-text",value:g,dir:"auto",rows:4,"aria-describedby":"plus-template-count",onChange:ee=>{x(ee.target.value),b(null)}}),e.jsx("p",{id:"plus-template-count","aria-live":"polite",className:"text-xs text-muted",children:te})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("p",{className:"text-xs font-bold text-text-main",children:l("plusMessagesPlaceholders")}),Y.length===0?e.jsx("p",{className:"text-xs text-muted",children:l("plusMessagesNoPlaceholders")}):e.jsx("ul",{className:"m-0 flex list-none flex-col gap-2 p-0",children:Y.map(ee=>e.jsxs("li",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsx(ot,{className:"text-xs",children:`{${ee}}`}),e.jsx("span",{className:"text-xs text-muted",children:l(Dh(ee))})]},ee))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("p",{className:"text-xs font-bold text-text-main",children:l("plusMessagesPreview")}),e.jsx("div",{dir:"auto",className:"whitespace-pre-wrap break-words rounded-xl border border-line bg-panel-raised/50 p-3 text-sm text-text-main",children:q?e.jsx(Ls,{text:O}):M?e.jsx("span",{className:"text-muted",children:l("plusMessagesPreviewFailed")}):e.jsx(Ls,{text:E??O})})]}),N.length>0&&e.jsxs("p",{className:"text-sm text-warn",children:[l("plusFailedTitle")," ",e.jsx("span",{dir:"auto",children:fe})]}),e.jsx(is,{summary:e.jsx("span",{className:"text-sm font-semibold",children:l("plusManualTitle")}),children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-xs text-muted",children:l("plusManualHint")}),we.map(ee=>e.jsx(re,{label:Ya[ee],htmlFor:`plus-manual-${ee}`,children:e.jsx(wt,{id:`plus-manual-${ee}`,dir:"auto",rows:3,value:f[ee]??"",placeholder:J[ee]??J.en??"",onChange:le=>{const Se=le.target.value;k(X=>({...X,[ee]:Se})),b(null)}})},ee))]})})]})}),e.jsx(ut,{isOpen:I,onClose:()=>F(!1),onConfirm:()=>void ye(),title:l("plusRestoreDefaultTitle"),description:l("plusRestoreDefaultBody"),confirmLabel:l("plusResetDefault"),cancelLabel:l("cancel"),loading:A})]})}function vs(t){const s=t??"";return s.trim()?s:""}function Uh(t,s){var i,l;const n=(i=t.override)==null?void 0:i.values,r=(l=t.override)==null?void 0:l.source,a=d=>vs(n==null?void 0:n[d])||((r==null?void 0:r.locale)===d?vs(r.text):"");return a(s)||vs(t.catalog[s])||(s==="en"?"":a("en"))||vs(t.catalog.en)}function $h({onInactive:t}){const{t:s,language:n}=me(),r=Wn(n)?n:"en",[a,i]=o.useState(null),[l,d]=o.useState(!0),[c,m]=o.useState(null),[u,p]=o.useState(""),[h,g]=o.useState("all"),[x,f]=o.useState(null),[k,N]=o.useState(0),[w,S]=o.useState(new Set);o.useEffect(()=>{let $=!0;return d(!0),os("/templates").then(G=>{$&&(i(G),m(null))}).catch(G=>{if(!$)return;xt(G)==="inactive"&&t(),m(bt(s,G))}).finally(()=>{$&&d(!1)}),()=>{$=!1}},[k,t,s]);const b=(a==null?void 0:a.keys)??[],R=o.useMemo(()=>{const $=new Set;for(const G of b){const ne=yr(G.key);ne&&$.add(ne)}return[...$]},[b]),j=o.useMemo(()=>R.map($=>({id:$,label:s(Qn($))})).sort(($,G)=>$.label.localeCompare(G.label,n)),[R,n,s]),y=o.useMemo(()=>{const $=u.trim().toLowerCase();return b.filter(G=>{var q,C,O;if(h!=="all"&&yr(G.key)!==h)return!1;if(!$)return!0;const ne=[...Object.values(G.catalog),...Object.values(((q=G.override)==null?void 0:q.values)??{}),(O=(C=G.override)==null?void 0:C.source)==null?void 0:O.text].filter(J=>typeof J=="string").join(`
458
+ `).toLowerCase(),se=vr(G.key)??"",V=s(Qn(G.key)).toLowerCase();return ne.includes($)||se.includes($)||V.includes($)})},[b,h,u,s]),{page:_,pageCount:A,pageItems:D,setPage:I,total:F}=An(y,20,`${u}|${h}`),E=x?b.find($=>$.key===x)??null:null,P=()=>N($=>$+1),M=()=>P();return l&&!a?e.jsx(vt,{text:s("loading")}):c&&!a?e.jsx(Pe,{kind:"error",icon:e.jsx(zs,{size:28}),description:c,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:P,children:s("retry")})}):e.jsxs(he,{padded:!1,className:"flex flex-col",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-line p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("p",{className:"text-sm font-bold text-text-main",children:s("plusTabMessages")}),a&&e.jsx("p",{className:"text-xs text-muted tabular-nums",children:de(s("plusMessagesUsed"),{used:a.used,limit:a.limit})})]}),e.jsxs(It,{children:[e.jsx(be,{type:"search",value:u,placeholder:s("plusMessagesSearch"),"aria-label":s("plusMessagesSearch"),className:"min-w-48 flex-1",onChange:$=>p($.target.value)}),e.jsx(zt,{label:s("filter"),resetLabel:s("reset"),activeCount:h==="all"?0:1,onReset:()=>g("all"),children:e.jsxs(Re,{"aria-label":s("plusMessagesArea"),value:h,onChange:$=>g($.target.value),children:[e.jsx("option",{value:"all",children:s("plusMessagesAreaAll")}),j.map($=>e.jsx("option",{value:$.id,dir:"auto",children:$.label},$.id))]})})]})]}),c&&e.jsx("p",{role:"alert",className:"border-b border-line p-4 text-sm text-danger",children:c}),F===0?e.jsx(Pe,{kind:"no-results",title:s("plusMessagesNoResults")}):e.jsx("ul",{className:"divide-y divide-line",children:D.map($=>{const G=Uh($,r),ne=vr($.key),se=w.has($.key),V=zh(G);return e.jsxs("li",{className:"flex items-start gap-2 p-3 sm:gap-3 sm:p-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"mb-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted",children:[e.jsx("span",{children:s(Qn($.key))}),ne&&e.jsx(ot,{className:"text-xs",children:`!${ne}`}),$.override&&e.jsx(Ce,{tone:"info",children:s("plusMessagesCustomized")})]}),e.jsx(ze,{as:"p",lines:se?void 0:2,title:se?void 0:G||s("plusMessagesNoPreview"),className:"text-sm text-text-main",children:G?e.jsx(Ls,{text:G}):s("plusMessagesNoPreview")})]}),V&&e.jsx(xe,{label:s(se?"plusMessagesShowLess":"plusMessagesShowFull"),"aria-expanded":se,icon:e.jsx(Dt,{size:16,className:se?"rotate-180 transition-transform":"transition-transform"}),onClick:()=>S(q=>{const C=new Set(q);return C.has($.key)?C.delete($.key):C.add($.key),C})}),e.jsx(xe,{label:s("plusMessagesEdit"),icon:e.jsx(as,{size:16}),onClick:()=>f($.key)})]},$.key)})}),A>1&&e.jsx("div",{className:"border-t border-line p-3",children:e.jsx(Ht,{page:_,pageCount:A,total:F,onPageChange:I,label:s("plusTabMessages")})}),e.jsx(Bh,{open:x!==null,item:E,onClose:()=>f(null),onSaved:M,onRefresh:P,onInactive:t})]})}function Kh({onInactive:t}){const{t:s}=me(),[n,r]=o.useState(null),[a,i]=o.useState(!0),[l,d]=o.useState(null),[c,m]=o.useState(null),[u,p]=o.useState(!1),[h,g]=o.useState(!1),[x,f]=o.useState(null),[k,N]=o.useState(0);o.useEffect(()=>{let S=!0;return i(!0),os("/presets").then(b=>{S&&(r(b),d(null))}).catch(b=>{if(!S)return;xt(b)==="inactive"&&t(),d(bt(s,b))}).finally(()=>{S&&i(!1)}),()=>{S=!1}},[k,t,s]);async function w(){if(c){g(!0),d(null),f(null);try{const S=await Nh(`/presets/${encodeURIComponent(c.id)}/apply`,{overwriteManual:u});f(S.applied),m(null),p(!1),N(b=>b+1)}catch(S){xt(S)==="inactive"&&t(),d(bt(s,S))}finally{g(!1)}}}return a&&!n?e.jsx(vt,{text:s("loading")}):l&&!n?e.jsx(Pe,{kind:"error",icon:e.jsx(Vs,{size:28}),description:l,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>N(S=>S+1),children:s("retry")})}):e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-muted",children:s("plusPresetsIntro")}),l&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:l}),x!==null&&e.jsx("p",{role:"status",className:"text-sm text-ok",children:de(s("plusPresetApplied"),{n:x})}),e.jsx("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-3",children:((n==null?void 0:n.presets)??[]).map(S=>e.jsxs(he,{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ze,{as:"strong",className:"min-w-0 flex-1 text-sm font-bold text-text-main",children:S.name}),(n==null?void 0:n.active)===S.id&&e.jsx(Ce,{tone:"ok",children:s("plusPresetActive")})]}),e.jsx(ze,{as:"p",className:"text-sm text-muted",children:S.description}),e.jsx("ul",{className:"flex flex-col gap-2",children:S.preview.slice(0,3).map(b=>e.jsxs("li",{children:[e.jsx(ze,{as:"p",lines:2,className:"text-sm text-text-main",children:b.text}),e.jsx("p",{className:"mt-0.5 text-[11px] text-faint",children:s(Qn(b.key))})]},b.key))}),e.jsx(U,{variant:"secondary",className:"mt-auto self-start",onClick:()=>{m(S),p(!1)},children:s("plusPresetApply")})]},S.id))}),e.jsx(ut,{isOpen:c!==null,onClose:()=>m(null),onConfirm:()=>void w(),title:de(s("plusPresetConfirmTitle"),{name:(c==null?void 0:c.name)??""}),description:s("plusPresetConfirmBody"),confirmLabel:s("plusPresetApply"),cancelLabel:s("cancel"),variant:"primary",loading:h,children:e.jsx(ht,{label:s("plusPresetOverwriteManual"),checked:u,onChange:S=>p(S.target.checked)})})]})}function Hh({onInactive:t}){const{t:s}=me(),[n,r]=o.useState(null),[a,i]=o.useState([]),[l,d]=o.useState(!0),[c,m]=o.useState(null),[u,p]=o.useState(0);return o.useEffect(()=>{let h=!0;return d(!0),Promise.all([os("/visibility"),Q.get("/commands")]).then(([g,x])=>{h&&(r(g),i(x.commands.map(f=>f.name)),m(null))}).catch(g=>{if(!h)return;xt(g)==="inactive"&&t(),m(bt(s,g))}).finally(()=>{h&&d(!1)}),()=>{h=!1}},[u,t,s]),l&&!n?e.jsx(vt,{text:s("loading")}):c&&!n?e.jsx(Pe,{kind:"error",icon:e.jsx(kr,{size:28}),description:c,action:e.jsx(U,{variant:"secondary",icon:e.jsx(ft,{size:16}),onClick:()=>p(h=>h+1),children:s("retry")})}):n?e.jsx(Vh,{visibility:n,commands:a,onSaved:r,onInactive:t}):null}function Vh({visibility:t,commands:s,onSaved:n,onInactive:r}){const{t:a}=me(),i=o.useMemo(()=>t.commands.join(","),[t.commands]),l=o.useMemo(()=>({hideProgress:t.hideProgress,commands:t.commands}),[t.hideProgress,i]),d=wn(l,"plusExtErrorFailed",bt),c=o.useRef(l);o.useEffect(()=>{if(c.current!==l){const b=c.current;c.current=l;const R=d.draft.hideProgress!==b.hideProgress,j=d.draft.commands.join(",")!==b.commands.join(",");(R||j)&&d.setDraft({hideProgress:R?d.draft.hideProgress:l.hideProgress,commands:j?d.draft.commands:l.commands})}},[l,d.draft.hideProgress,d.draft.commands,d.setDraft]);const m=o.useRef(td()),u=o.useRef(t);u.current=t;const[p,h]=o.useState(!1),[g,x]=o.useState(null),[f,k]=o.useState(""),N=o.useMemo(()=>{const b=f.trim().toLowerCase();return b?s.filter(R=>R.toLowerCase().includes(b)):s},[s,f]);async function w(b){h(!0),x(null);try{const R=await m.current.enqueue(async()=>{const j=u.current;return al(()=>fn("/visibility",{hideWatermark:b,hideProgress:j.hideProgress,commands:j.commands}),r)});u.current=R,n(R)}catch(R){xt(R)!=="inactive"&&x(bt(a,R))}finally{h(!1)}}function S(b,R){d.setField("commands",R?[...d.draft.commands,b]:d.draft.commands.filter(j=>j!==b))}return e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(Je,{checked:t.hideWatermark,disabled:p,label:a("plusVisibilityWatermark"),description:a("plusVisibilityWatermarkHint"),onChange:b=>void w(b)}),g&&e.jsx("p",{role:"alert",className:"text-xs text-danger",children:g})]}),e.jsxs("form",{className:"flex flex-col gap-4",onSubmit:b=>{b.preventDefault(),d.save(async R=>{const j=await m.current.enqueue(async()=>{const y=u.current;return al(()=>fn("/visibility",{hideWatermark:y.hideWatermark,hideProgress:R.hideProgress,commands:R.commands}),r)});u.current=j,n(j)})},children:[e.jsx(re,{label:a("plusVisibilityProgress"),htmlFor:"plus-hide-progress",children:e.jsxs(Re,{id:"plus-hide-progress",value:d.draft.hideProgress,onChange:b=>d.setField("hideProgress",b.target.value),children:[e.jsx("option",{value:"none",children:a("plusProgressNone")}),e.jsx("option",{value:"all",children:a("plusProgressAll")}),e.jsx("option",{value:"selected",children:a("plusProgressSelected")})]})}),d.draft.hideProgress==="selected"&&e.jsxs(re,{label:a("plusVisibilityCommands"),description:de(a("plusVisibilitySelectedCount"),{n:d.draft.commands.length,max:s.length}),children:[e.jsx("p",{className:"text-xs text-muted",children:a("plusVisibilityCommandsHint")}),e.jsx(be,{type:"search",value:f,placeholder:a("plusMessagesSearch"),"aria-label":a("plusVisibilityCommands"),onChange:b=>k(b.target.value)}),e.jsx("div",{className:"flex max-h-72 flex-col gap-1 overflow-y-auto rounded-xl border border-line bg-panel-raised/40 p-3",children:N.map(b=>e.jsx(ht,{checked:d.draft.commands.includes(b),onChange:R=>S(b,R.target.checked),label:e.jsx("span",{dir:"ltr",className:"font-mono text-sm",children:b})},b))})]}),e.jsx(kn,{dirty:d.dirty,saving:d.status==="saving",justSaved:d.status==="saved",error:d.error,onDiscard:d.revert,saveLabel:a("save"),discardLabel:a("discard"),unsavedLabel:a("unsavedChanges"),savedLabel:a("saved")})]})]})}function qh(){const{t}=me(),[s,n]=o.useState(()=>Jr(window.location.hash)??"messages");o.useEffect(()=>{const l=()=>{const d=Jr(window.location.hash);d&&n(d)};return window.addEventListener("hashchange",l),()=>window.removeEventListener("hashchange",l)},[]);const[r,a]=o.useState(!1),i=o.useCallback(()=>{(async()=>{try{(await Ch()).extension.state!=="active"&&a(!0)}catch{a(!0)}})()},[]);return r?e.jsx("p",{className:"text-sm text-muted",children:t("plusExtErrorInactive")}):e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(ls,{value:s,onChange:l=>{n(l),window.location.hash!==Ms(l)&&window.history.replaceState(null,"",Ms(l))},"aria-label":t("plusTitle"),className:"overflow-x-auto no-scrollbar",options:[{value:"messages",label:t("plusTabMessages"),icon:e.jsx(zs,{size:17})},{value:"presets",label:t("plusTabPresets"),icon:e.jsx(Vs,{size:17})},{value:"visibility",label:t("plusTabVisibility"),icon:e.jsx(kr,{size:17})},{value:"autoReply",label:t("plusTabAutoReply"),icon:e.jsx(Cn,{size:17})}]}),s==="messages"&&e.jsx($h,{onInactive:i}),s==="presets"&&e.jsx(Kh,{onInactive:i}),s==="visibility"&&e.jsx(Hh,{onInactive:i}),s==="autoReply"&&e.jsx(Eh,{onInactive:i})]})}const Wh={none:"plusStateNone",active:"plusStateActive",grace:"plusStateGrace",canceled:"plusStateCanceled",inactive:"plusStateInactive",expired:"plusStateExpired",clock:"plusStateClock",unverified:"plusStateUnverified"},Gh={absent:"plusExtensionAbsent",inactive:"plusExtensionInactive",active:"plusExtensionActive",incompatible:"plusExtensionIncompatible",disabled:"plusExtensionDisabled",failed:"plusExtensionFailed"},rl={UNCONFIGURED:"plusNotAvailable",UNAVAILABLE:"plusErrorUnavailable",PURCHASE_INVALID:"plusErrorPurchaseInvalid",ACCOUNT_MISMATCH:"plusErrorAccountMismatch",REBIND_LIMIT:"plusErrorRebindLimit",RATE_LIMITED:"plusErrorRateLimited",UNAVAILABLE_IN_BUILD:"plusNotIncluded",NETWORK_ERROR:"plusErrorNetwork",SERVICE_TIMEOUT:"plusErrorNetwork",SERVICE_DISCONNECTED:"plusErrorUnavailable",SERVICE_UNAVAILABLE:"plusErrorUnavailable",BILLING_UNAVAILABLE:"plusErrorUnavailable",FEATURE_NOT_SUPPORTED:"plusErrorUnavailable",ITEM_UNAVAILABLE:"plusErrorUnavailable",OFFER_CHANGED:"plusOfferChanged",ITEM_ALREADY_OWNED:"plusErrorAlreadyOwned",BUSY:"plusErrorBusy",network:"plusErrorNetwork"},Jh=hh();function Ct(t="FAILED"){throw new et(0,t,{code:t})}function js(t){var s;return t instanceof et?t.status===429?"RATE_LIMITED":t.code||(typeof((s=t.data)==null?void 0:s.error)=="string"?t.data.error:"FAILED"):"network"}function Yh({enabled:t,onEnabledChange:s}){const{t:n,language:r}=me(),a=Nd(),{status:i,refresh:l,error:d}=wr(),[c,m]=o.useState(null),[u,p]=o.useState(!0),[h,g]=o.useState(!1),[x,f]=o.useState(null),k=o.useRef(!1),[N,w]=o.useState(0),S=o.useRef(-1),[b,R]=o.useState(null),[j,y]=o.useState(null),[_,A]=o.useState(!1),[D,I]=o.useState(!1),F=o.useRef(d);o.useEffect(()=>{if(!d){F.current=null;return}d!==F.current&&R(d)},[d]),o.useEffect(()=>{let L=!0;async function v(){try{const T=await kd();if(!L)return;if(p(!1),a&&T.configured&&T.extension.state!=="absent"){g(!0);const te=await ps();if(!L)return;m(te),te.ok||R(te.code||"UNAVAILABLE")}}catch(T){L&&R(js(T))}finally{L&&(p(!1),g(!1))}}return v(),()=>{L=!1}},[a]);const E=o.useCallback(async(L,v)=>{if(!(k.current||h)){k.current=!0,f(L),L!=="recover"&&(R(null),y(null));try{await v()}catch(T){R(js(T))}finally{try{await l()}catch(T){R(js(T))}k.current=!1,f(null)}}},[h,l]),P=o.useCallback(async L=>{if(!L.ok)L.status==="cancelled"?y("plusPurchaseCancelled"):Ct(L.code);else if(L.status==="pending")y("plusPaymentPending");else{const v=await Q.post("/plus/claim",{purchaseToken:L.purchaseToken,productId:L.productId,packageName:L.packageName});v.ok||Ct(v.code)}},[]),M=o.useCallback(async L=>{let v;for(const T of L)try{await P(T)}catch(te){v??(v=te)}if(v)throw v},[P]);o.useEffect(()=>{if(!a)return;const L=()=>w(T=>T+1),v=()=>{document.visibilityState==="visible"&&L()};return document.addEventListener("visibilitychange",v),window.addEventListener("levix-plus-purchase",L),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("levix-plus-purchase",L)}},[a]);const $=a&&(i==null?void 0:i.configured)&&i.extension.state!=="absent";o.useEffect(()=>{!$||u||h||x||S.current===N||(S.current=N,E("recover",async()=>{const L=await jd();L.ok||Ct(L.code),await fh({purchases:L.purchases,state:i==null?void 0:i.entitlement.state,gate:Jh,claim:async v=>{R(null),y(null),await M(v.map(T=>({ok:!0,...T})))},readState:async()=>(await l()).entitlement.state,refresh:async()=>{try{const v=await Q.post("/plus/refresh");v.ok||Ct(v.code),await l()}catch(v){if(v instanceof et&&v.status===429||js(v)==="RATE_LIMITED")return;throw v}}})}))},[$,u,h,x,N,E,M,i,l]);function G(){E("subscribe",async()=>{const L=nl(c,n);L||Ct("UNAVAILABLE");const v=await Q.post("/plus/prepare"),T=await Sd(L.product.offerToken,v.installationId);!T.ok&&T.code==="OFFER_CHANGED"&&m(await ps()),await P(T)})}function ne(){E("restore",async()=>{const L=await Cd();L.ok||Ct(L.code),L.purchases.length===0&&y("plusNoPurchases"),await M(L.purchases)})}function se(){E("refresh",async()=>{const L=await Q.post("/plus/refresh");L.ok||Ct(L.code),await l(),y("plusRefreshDone");const v=await ps();m(v),v.ok||Ct(v.code)})}const V=b?Object.hasOwn(rl,b)?n(rl[b]):je(n,{data:{error:b}},"plusErrorFailed"):null;if(u)return e.jsx(nt,{label:n("loading")});if((i==null?void 0:i.extension.state)==="absent")return e.jsx("p",{className:"text-sm text-muted",children:n("plusNotIncluded")});if(i&&!i.configured)return e.jsx("p",{className:"text-sm text-muted",children:n("plusNotAvailable")});if(!i)return e.jsxs(he,{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-danger",children:V||n("plusErrorFailed")}),e.jsx(xe,{label:n("refresh"),icon:e.jsx(it,{size:18}),disabled:!!x,onClick:()=>void E("reload",async()=>{const L=await l();if(a&&L.configured&&L.extension.state!=="absent"){const v=await ps();m(v),v.ok||Ct(v.code)}})})]});const q=i.entitlement.until?new Date(i.entitlement.until):null,C=q&&Number.isFinite(q.getTime()),O=["active","grace","canceled"].includes(i.entitlement.state),J=nl(c,n),Y=!!x||h;return e.jsxs(he,{className:"flex flex-col gap-4",children:[e.jsx(He,{title:n("plusTitle"),actions:a?e.jsxs(e.Fragment,{children:[e.jsx(xe,{label:n("plusManage"),icon:e.jsx(Ds,{size:18}),disabled:Y,onClick:()=>void E("manage",async()=>{const L=wd();L.ok||Ct(L.code)})}),e.jsx(xe,{label:n("refresh"),icon:e.jsx(it,{size:18}),disabled:Y,loading:x==="refresh",onClick:se})]}):void 0}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2","aria-live":"polite",children:[e.jsx("span",{className:"text-sm text-muted",children:n("plusStatus")}),e.jsx(xn,{tone:O?"ok":"neutral",children:n(Wh[i.entitlement.state])}),mh(i.entitlement.state)&&C&&e.jsx("time",{dateTime:i.entitlement.until||void 0,className:"text-sm text-muted",children:de(n("plusUntil"),{date:q.toLocaleString(r)})})]}),e.jsx("p",{className:"text-sm text-muted",children:n(Gh[i.extension.state])}),a?e.jsxs(e.Fragment,{children:[e.jsx(Je,{label:n("plusEnabled"),description:n("plusEnabledDescription"),checked:t,disabled:Y,onChange:L=>void E("toggle",()=>s(L))}),h&&e.jsx(nt,{label:n("loading")}),J&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-sm text-text-main",children:J.price}),!O&&e.jsxs(e.Fragment,{children:[e.jsx("p",{id:"plus-disclosure",className:"text-sm text-muted",children:J.disclosure}),e.jsx(U,{variant:"primary",className:"self-start","aria-describedby":"plus-disclosure",disabled:Y,loading:x==="subscribe",onClick:G,children:n("plusSubscribe")})]})]}),e.jsx(U,{variant:"secondary",className:"self-start",disabled:Y,loading:x==="restore",onClick:()=>A(!0),children:n("plusRestore")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"text-sm text-muted",children:n("plusActiveInstallationLimit")}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>I(!0),children:n("plusViewTerms")})]})]}):e.jsx("p",{className:"text-sm text-muted",children:n("plusAndroidOnly")}),j&&e.jsx("p",{role:"status",className:"text-sm text-info",children:n(j)}),V&&e.jsx("p",{role:"alert",className:"text-sm text-danger",children:V}),e.jsx(ut,{isOpen:_,onClose:()=>{x||A(!1)},onConfirm:()=>{A(!1),ne()},title:n("plusRestoreConfirmTitle"),description:n("plusRestoreConfirm"),confirmLabel:n("plusRestore"),cancelLabel:n("cancel"),variant:"primary",loading:x==="restore"}),e.jsx(sx,{isOpen:D,onClose:()=>I(!1)}),i.extension.state==="active"&&e.jsx(qh,{})]})}const nd=["overview","connection","commands","ai","groups","autodelete","reactions","schedules","plus","settings","logs","stickers"];function sd(){const t=Rd(window.location.hash);t&&window.history.replaceState(null,"",t)}function Qh(){sd();const t=window.location.hash.replace(/^#/,"").split("/")[0];return nd.includes(t)?t:"overview"}const Xh=()=>{const{t}=me(),[s,n]=o.useState(null);return o.useEffect(()=>{let r=!0;return Q.getSettings().then(a=>{var l;if(!r)return;const i=(l=a==null?void 0:a.settings)==null?void 0:l.find(d=>d.key==="plus_enabled");n(i?i.value!==!1:!0)}).catch(()=>{r&&n(!0)}),()=>{r=!1}},[]),s===null?e.jsx(nt,{label:t("loading")}):e.jsx(Yh,{enabled:s,onEnabledChange:async r=>{await Q.updateSetting("plus_enabled",r),n(r)}})},Zh=()=>{const{t}=me(),{toast:s}=qe(),[n,r]=o.useState(Qh),[a,i]=o.useState(!1),{sessionStatus:l}=Ad((R,j)=>{if(R==="status"){const y=j==null?void 0:j.state;s(t(fc({state:y}).labelKey),"info")}}),[d,c]=o.useState(null),[m,u]=o.useState(null),p=o.useRef(null),h=o.useRef(0),g=o.useRef(!1),[x,f]=o.useState(!1),k=o.useCallback(async()=>{const R=++h.current;try{const j=await Q.getSession();if(R!==h.current)return null;if(j!=null&&j.session)return c({...j.session,qr:j.qr??null,pairingCode:j.pairingCode??null}),j.session;if(j!=null&&j.status)return c(j.status),j.status}catch{}return null},[]);o.useEffect(()=>{k()},[k]);const N=d||l||m?{state:(l==null?void 0:l.state)||(d==null?void 0:d.state)||"idle",...d||{},...l||{},...m&&(!l||l.state==="consent_required")?m:{}}:null;o.useEffect(()=>{m&&l&&l!==p.current&&l.state!=="consent_required"&&u(null)},[m,l]),o.useEffect(()=>{const R=(N==null?void 0:N.state)==="consent_required";R&&!g.current&&f(!0),g.current=R},[N==null?void 0:N.state]);const w=(N==null?void 0:N.connected)===!0||(N==null?void 0:N.state)==="connected";o.useEffect(()=>{const R=N==null?void 0:N.state,y=R==="starting"||R==="linking"||R==="reconnecting"||R==="waiting_for_qr"&&!(N!=null&&N.qr)&&!(N!=null&&N.pairingCode)?2e3:15e3,_=setInterval(()=>{k()},y);return()=>clearInterval(_)},[N==null?void 0:N.state,N==null?void 0:N.qr,N==null?void 0:N.pairingCode,k]);const S=R=>{r(R),window.location.hash=R};o.useEffect(()=>{const R=()=>{sd();const j=window.location.hash.replace(/^#/,"").split("/")[0];nd.includes(j)&&r(j)};return window.addEventListener("hashchange",R),()=>window.removeEventListener("hashchange",R)},[]);const b={overview:t("overview"),connection:t("connection"),commands:t("commands"),ai:t("ai"),groups:t("groups"),autodelete:t("autoDelete"),reactions:t("reaction"),schedules:t("schedules"),plus:t("plusTitle"),settings:t("settings"),logs:t("logs"),stickers:t("stickers")};return o.useEffect(()=>Eu(),[]),e.jsxs("div",{className:"min-h-screen min-h-[100dvh] flex bg-bg text-text-main bg-ambient-glow overflow-x-clip relative",children:[e.jsx(Tu,{currentView:n,onSelectView:S,isOpenMobile:a,onCloseMobile:()=>i(!1)}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(Mu,{onToggleMobileMenu:()=>i(R=>!R),title:b[n]||"Dashboard",view:n,status:N}),e.jsxs("main",{className:"flex-1 max-w-7xl w-full mx-auto p-4 sm:p-6 lg:p-8",children:[e.jsx(Nu,{}),e.jsxs(dc,{children:[n==="overview"&&e.jsx(vx,{status:N,onNavigate:S}),n==="connection"&&e.jsx(rx,{status:N,onRefresh:k,onStatusUpdate:R=>c(j=>({...j||{},...R})),onReviewTerms:()=>f(!0)}),n==="ai"&&e.jsx(Fu,{}),n==="commands"&&e.jsx(Em,{}),n==="schedules"&&e.jsx(ip,{isConnected:w,onNavigate:S}),n==="groups"&&e.jsx(fx,{}),n==="autodelete"&&e.jsx(pm,{}),n==="reactions"&&e.jsx(Qx,{}),n==="plus"&&e.jsx(Xh,{}),n==="settings"&&e.jsx(jp,{}),n==="stickers"&&e.jsx(uh,{isConnected:w}),n==="logs"&&e.jsx(yx,{})]})]})]}),e.jsx(nx,{isOpen:x,onClose:()=>f(!1),onAccepted:R=>{p.current=l,h.current++,u(R),c(j=>({...j||{},...R})),k().then(j=>{j&&u(j.state==="consent_required"?null:j)})}})]})},ef=()=>e.jsx(Ed,{children:e.jsx(ku,{children:e.jsx(Lu,{children:e.jsx(Zh,{})})})}),il=document.getElementById("root");il&&_d.createRoot(il).render(e.jsx(Ld.StrictMode,{children:e.jsx(ef,{})}));