@fayz-ai/plugin-conversations 0.42.1 → 0.43.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 (75) hide show
  1. package/dist/{CampaignsSurface-X2LPJEKF.js → CampaignsSurface-QZ4BVND2.js} +3 -3
  2. package/dist/{CampaignsSurface-X2LPJEKF.js.map → CampaignsSurface-QZ4BVND2.js.map} +1 -1
  3. package/dist/ConversationThreadSurface-O6MQVLOO.js +111 -0
  4. package/dist/ConversationThreadSurface-O6MQVLOO.js.map +1 -0
  5. package/dist/ConversationsPage-ZYMNPRSI.js +621 -0
  6. package/dist/ConversationsPage-ZYMNPRSI.js.map +1 -0
  7. package/dist/{ConversationsSettings-GORCWUHD.js → ConversationsSettings-4UUJD6IC.js} +6 -5
  8. package/dist/ConversationsSettings-4UUJD6IC.js.map +1 -0
  9. package/dist/chunk-27Z3U4CN.js +290 -0
  10. package/dist/chunk-27Z3U4CN.js.map +1 -0
  11. package/dist/{chunk-GYEAIN3O.js → chunk-B6ACT265.js} +49 -36
  12. package/dist/chunk-B6ACT265.js.map +1 -0
  13. package/dist/chunk-IH7XSR4A.js +13 -0
  14. package/dist/chunk-IH7XSR4A.js.map +1 -0
  15. package/dist/{ConversationsPage-Z3YKLAOJ.js → chunk-KTYFNZ2V.js} +289 -701
  16. package/dist/chunk-KTYFNZ2V.js.map +1 -0
  17. package/dist/{chunk-W5VV6G35.js → chunk-R65GJLBC.js} +4 -16
  18. package/dist/chunk-R65GJLBC.js.map +1 -0
  19. package/dist/components/Composer.d.ts +3 -1
  20. package/dist/components/Composer.d.ts.map +1 -1
  21. package/dist/context.d.ts +3 -0
  22. package/dist/context.d.ts.map +1 -1
  23. package/dist/data/accents.d.ts.map +1 -1
  24. package/dist/data/mock.d.ts.map +1 -1
  25. package/dist/data/supabase.d.ts.map +1 -1
  26. package/dist/data/types.d.ts +6 -0
  27. package/dist/data/types.d.ts.map +1 -1
  28. package/dist/index.d.ts +11 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +40 -285
  31. package/dist/index.js.map +1 -1
  32. package/dist/lib/ao-vivo.d.ts +32 -0
  33. package/dist/lib/ao-vivo.d.ts.map +1 -0
  34. package/dist/lib/onboarding.d.ts +3 -4
  35. package/dist/lib/onboarding.d.ts.map +1 -1
  36. package/dist/lib/runtime.d.ts +10 -0
  37. package/dist/lib/runtime.d.ts.map +1 -0
  38. package/dist/locales/en.d.ts.map +1 -1
  39. package/dist/locales/pt-BR.d.ts.map +1 -1
  40. package/dist/migrations/index.d.ts +2 -0
  41. package/dist/migrations/index.d.ts.map +1 -1
  42. package/dist/migrations/main.browser.js +3 -1
  43. package/dist/migrations/main.browser.js.map +1 -1
  44. package/dist/migrations/main.js +191 -2
  45. package/dist/migrations/main.js.map +1 -1
  46. package/dist/settings/ConversationsSettings.d.ts.map +1 -1
  47. package/dist/settings/WhatsAppProviders.d.ts.map +1 -1
  48. package/dist/store.d.ts +6 -0
  49. package/dist/store.d.ts.map +1 -1
  50. package/dist/types.d.ts +6 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/views/CampaignsView.d.ts.map +1 -1
  53. package/dist/views/ContactPanel.d.ts +3 -1
  54. package/dist/views/ContactPanel.d.ts.map +1 -1
  55. package/dist/views/ConversationList.d.ts.map +1 -1
  56. package/dist/views/ConversationThreadSurface.d.ts +12 -0
  57. package/dist/views/ConversationThreadSurface.d.ts.map +1 -0
  58. package/dist/views/ConversationsPage.d.ts +6 -1
  59. package/dist/views/ConversationsPage.d.ts.map +1 -1
  60. package/dist/views/MessageInspector.d.ts.map +1 -1
  61. package/dist/views/MessageThread.d.ts +7 -1
  62. package/dist/views/MessageThread.d.ts.map +1 -1
  63. package/dist/views/NewConversationPanel.d.ts.map +1 -1
  64. package/dist/views/RecordLinks.d.ts +53 -0
  65. package/dist/views/RecordLinks.d.ts.map +1 -0
  66. package/dist/views/SendWindow.d.ts +2 -1
  67. package/dist/views/SendWindow.d.ts.map +1 -1
  68. package/dist/views/TemplatesView.d.ts.map +1 -1
  69. package/dist/views/useConversaAoVivo.d.ts +17 -0
  70. package/dist/views/useConversaAoVivo.d.ts.map +1 -0
  71. package/package.json +4 -4
  72. package/dist/ConversationsPage-Z3YKLAOJ.js.map +0 -1
  73. package/dist/ConversationsSettings-GORCWUHD.js.map +0 -1
  74. package/dist/chunk-GYEAIN3O.js.map +0 -1
  75. package/dist/chunk-W5VV6G35.js.map +0 -1
@@ -0,0 +1,621 @@
1
+ import { useMediaQuery, MessageThread, ContactPanel, CHANNEL_ICON, CHANNEL_ACCENT, Avatar, relativeTime, ChannelBadge } from './chunk-KTYFNZ2V.js';
2
+ import { ConversationsContextProvider, useConversationsStore, assinarChegada, useConversationsConfig, CHANNEL_LABELS, currentUserId, isWaitingOnUs, MessagePreview } from './chunk-B6ACT265.js';
3
+ import { providersApi } from './chunk-HMWUU5O7.js';
4
+ import * as React2 from 'react';
5
+ import React2__default from 'react';
6
+ import { SquarePen, MessageSquare, Search, User, Archive, Inbox, CheckCheck } from 'lucide-react';
7
+ import { PageHeaderActions, cn, Button, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Textarea, ModalFooter, Input, FilterChip, Skeleton, toast } from '@fayz-ai/ui';
8
+ import { useRightRailStore, PageActions, useLimitGuard, ContactPicker, invalidateLimit, useConnectors } from '@fayz-ai/admin';
9
+ import { currentAppPath, replaceApp, appHref, onAppPathChange, useTranslation, useActiveTenantId, errorMessage } from '@fayz-ai/core';
10
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
11
+
12
+ var whatsappCache = null;
13
+ var whatsappConnected = () => {
14
+ whatsappCache ?? (whatsappCache = providersApi.list().then((rows) => rows.some((r) => r.isActive || r.hasCredential)).catch(() => {
15
+ whatsappCache = null;
16
+ return false;
17
+ }));
18
+ return whatsappCache;
19
+ };
20
+ function useChannelConnections() {
21
+ const [whatsapp, setWhatsapp] = React2.useState(void 0);
22
+ const { connectors } = useConnectors({ hostPluginId: "conversations", includeGrants: false });
23
+ React2.useEffect(() => {
24
+ let cancelled = false;
25
+ void whatsappConnected().then((v) => {
26
+ if (!cancelled) setWhatsapp(v);
27
+ });
28
+ return () => {
29
+ cancelled = true;
30
+ };
31
+ }, []);
32
+ return React2.useMemo(() => {
33
+ if (whatsapp === void 0) return void 0;
34
+ const live = (needle) => (connectors ?? []).some((c) => c.state === "connected" && c.slug.toLowerCase().includes(needle));
35
+ return { whatsapp: whatsapp || live("whatsapp"), email: live("mail"), instagram: live("instagram") };
36
+ }, [whatsapp, connectors]);
37
+ }
38
+ var FILTERS = ["all", "whatsapp", "instagram", "email"];
39
+ function ConversationList({ className }) {
40
+ const t = useTranslation();
41
+ const connected = useChannelConnections();
42
+ const {
43
+ conversations,
44
+ selectedId,
45
+ channelFilter,
46
+ leadOwnerFilter,
47
+ search,
48
+ loading,
49
+ select,
50
+ markRead,
51
+ setChannelFilter,
52
+ setLeadOwnerFilter,
53
+ setSearch
54
+ } = useConversationsStore((s) => s);
55
+ const [archived, setArchived] = React2__default.useState(false);
56
+ const [me, setMe] = React2__default.useState(null);
57
+ React2__default.useEffect(() => {
58
+ void currentUserId().then(setMe);
59
+ }, []);
60
+ const mine = Boolean(me) && leadOwnerFilter === me;
61
+ const decided = React2__default.useRef(false);
62
+ React2__default.useEffect(() => {
63
+ if (decided.current || !me || loading || conversations.length === 0) return;
64
+ decided.current = true;
65
+ let pref = null;
66
+ try {
67
+ pref = localStorage.getItem("conversas.owner");
68
+ } catch {
69
+ }
70
+ const ownsAny = conversations.some((c) => c.leadOwnerId === me);
71
+ if (leadOwnerFilter === void 0 && (pref === "me" || pref === null && ownsAny)) void setLeadOwnerFilter(me);
72
+ }, [me, loading, conversations, leadOwnerFilter, setLeadOwnerFilter]);
73
+ const pickOwner = (v) => {
74
+ try {
75
+ localStorage.setItem("conversas.owner", v && v === me ? "me" : "any");
76
+ } catch {
77
+ }
78
+ void setLeadOwnerFilter(v);
79
+ };
80
+ const mineCount = React2__default.useMemo(
81
+ () => mine ? conversations.filter((c) => c.status !== "closed" && isWaitingOnUs(c)).length : 0,
82
+ [conversations, mine]
83
+ );
84
+ const [inbox, setInbox] = React2__default.useState("commercial");
85
+ const inboxes = React2__default.useMemo(() => new Set(conversations.map((c) => c.inbox ?? "commercial")), [conversations]);
86
+ const bothInboxes = inboxes.size > 1;
87
+ const waitingIn = (which) => conversations.filter((c) => (c.inbox ?? "commercial") === which && c.status !== "closed" && isWaitingOnUs(c)).length;
88
+ const shown = React2__default.useMemo(
89
+ // Waiting on us stays pinned on top (newest first among them): a red thread
90
+ // is a contact to make, and it must not sink under newer chatter.
91
+ () => conversations.filter((c) => !bothInboxes || (c.inbox ?? "commercial") === inbox).filter((c) => archived ? c.status === "closed" : c.status !== "closed").map((c, i) => ({ c, i, waiting: isWaitingOnUs(c) })).sort((a, b) => a.waiting === b.waiting ? a.i - b.i : a.waiting ? -1 : 1).map(({ c }) => c),
92
+ [conversations, archived, bothInboxes, inbox]
93
+ );
94
+ const donos = React2__default.useMemo(() => {
95
+ const vistos = /* @__PURE__ */ new Map();
96
+ for (const c of conversations) {
97
+ if (c.leadOwnerId) vistos.set(c.leadOwnerId, c.leadOwnerName ?? c.leadOwnerId);
98
+ }
99
+ return [...vistos].map(([value, label]) => ({ value, label }));
100
+ }, [conversations]);
101
+ const filters = React2__default.useMemo(
102
+ () => channelFilter === "support" || conversations.some((c) => c.channel === "support") ? [...FILTERS, "support"] : FILTERS,
103
+ [conversations, channelFilter]
104
+ );
105
+ return /* @__PURE__ */ jsxs("aside", { className: cn("w-full shrink-0 flex-col border-r border-border bg-card lg:w-[320px]", className), children: [
106
+ bothInboxes && /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 border-b border-border text-sm", children: ["commercial", "support"].map((which) => {
107
+ const n = waitingIn(which);
108
+ return /* @__PURE__ */ jsxs(
109
+ "button",
110
+ {
111
+ type: "button",
112
+ onClick: () => setInbox(which),
113
+ className: cn(
114
+ "flex items-center justify-center gap-1.5 py-2.5 font-medium transition-colors",
115
+ inbox === which ? "border-b-2 border-primary text-foreground" : "text-muted-foreground hover:text-foreground"
116
+ ),
117
+ children: [
118
+ which === "commercial" ? "Comercial" : "Suporte",
119
+ n > 0 && /* @__PURE__ */ jsx("span", { className: "rounded-full bg-destructive px-1.5 text-[10px] font-semibold text-destructive-foreground", children: n })
120
+ ]
121
+ },
122
+ which
123
+ );
124
+ }) }),
125
+ /* @__PURE__ */ jsxs("div", { className: "border-b border-border px-3 py-3", children: [
126
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
127
+ /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }),
128
+ /* @__PURE__ */ jsx(
129
+ Input,
130
+ {
131
+ value: search,
132
+ onChange: (e) => setSearch(e.target.value),
133
+ placeholder: t("conversations.list.search"),
134
+ className: "pl-8"
135
+ }
136
+ )
137
+ ] }),
138
+ /* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-wrap gap-1", children: filters.map((id) => {
139
+ const off = id !== "all" && id !== "support" && connected !== void 0 && !connected[id];
140
+ return /* @__PURE__ */ jsx(
141
+ Button,
142
+ {
143
+ variant: "bare",
144
+ size: "bare",
145
+ onClick: () => setChannelFilter(id),
146
+ title: off ? t("conversations.filter.notConnected") : void 0,
147
+ className: cn(
148
+ "rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",
149
+ channelFilter === id ? "border-transparent bg-primary text-primary-foreground" : off ? "border-dashed border-muted-foreground/40 bg-transparent text-muted-foreground hover:bg-muted/50" : "border-transparent bg-muted text-muted-foreground hover:bg-muted/70"
150
+ ),
151
+ children: t(`conversations.filter.${id}`)
152
+ },
153
+ id
154
+ );
155
+ }) }),
156
+ /* @__PURE__ */ jsxs("div", { className: "mt-2 flex flex-wrap items-center gap-1", children: [
157
+ (donos.length > 0 || mine) && /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
158
+ FilterChip,
159
+ {
160
+ label: t("conversations.contact.leadOwner"),
161
+ icon: User,
162
+ allLabel: t("conversations.filter.anyOwner"),
163
+ options: [
164
+ ...me ? [{ value: me, label: mine && mineCount > 0 ? `Meus leads \xB7 ${mineCount} esperando` : "Meus leads" }] : [],
165
+ { value: "none", label: t("conversations.filter.noOwner") },
166
+ ...donos.filter((d) => d.value !== me)
167
+ ],
168
+ value: leadOwnerFilter,
169
+ onChange: (v) => pickOwner(v)
170
+ }
171
+ ) }),
172
+ /* @__PURE__ */ jsxs(
173
+ Button,
174
+ {
175
+ variant: "bare",
176
+ size: "bare",
177
+ type: "button",
178
+ "aria-pressed": archived,
179
+ onClick: () => setArchived((v) => !v),
180
+ className: cn(
181
+ "inline-flex items-center gap-1 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",
182
+ archived ? "border-transparent bg-primary text-primary-foreground" : "border-transparent bg-muted text-muted-foreground hover:bg-muted/70"
183
+ ),
184
+ children: [
185
+ /* @__PURE__ */ jsx(Archive, { className: "h-3 w-3" }),
186
+ " ",
187
+ t("conversations.filter.archived")
188
+ ]
189
+ }
190
+ )
191
+ ] })
192
+ ] }),
193
+ /* @__PURE__ */ jsxs("div", { className: "min-h-0 flex-1 overflow-y-auto", children: [
194
+ loading && conversations.length === 0 && Array.from({ length: 6 }, (_, i) => /* @__PURE__ */ jsxs("div", { className: "flex w-full items-start gap-3 border-b border-border/50 px-3 py-3", children: [
195
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-10 shrink-0 rounded-full" }),
196
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
197
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
198
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-28" }),
199
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-3 w-8" })
200
+ ] }),
201
+ /* @__PURE__ */ jsx(Skeleton, { className: "mt-1.5 h-4 w-16 rounded-full" }),
202
+ /* @__PURE__ */ jsx(Skeleton, { className: "mt-1.5 h-3 w-3/4" })
203
+ ] })
204
+ ] }, i)),
205
+ !loading && mine && !archived && shown.length === 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2 p-8 text-center text-muted-foreground", children: [
206
+ /* @__PURE__ */ jsx(Inbox, { className: "h-6 w-6" }),
207
+ /* @__PURE__ */ jsx("p", { className: "text-sm", children: "Voc\xEA ainda n\xE3o tem leads nas conversas." }),
208
+ /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", onClick: () => pickOwner(void 0), children: "Ver todas as conversas" })
209
+ ] }),
210
+ !loading && !(mine && !archived) && shown.length === 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2 p-8 text-center text-muted-foreground", children: [
211
+ /* @__PURE__ */ jsx(Inbox, { className: "h-6 w-6" }),
212
+ /* @__PURE__ */ jsx("p", { className: "text-sm", children: archived ? t("conversations.list.emptyArchived") : t("conversations.list.empty") })
213
+ ] }),
214
+ !loading && mine && !archived && shown.length > 0 && !isWaitingOnUs(shown[0]) && /* @__PURE__ */ jsxs("div", { className: "m-3 flex items-center gap-2 rounded-lg border border-success/30 bg-success-soft px-3 py-2.5 text-sm text-success-soft-foreground", children: [
215
+ /* @__PURE__ */ jsx(CheckCheck, { className: "h-4 w-4 shrink-0" }),
216
+ " Nenhum lead esperando sua resposta."
217
+ ] }),
218
+ shown.map((c, idx) => {
219
+ const sectionHeader = mine && !archived ? idx === 0 && isWaitingOnUs(c) ? /* @__PURE__ */ jsxs("p", { className: "sticky top-0 z-[1] bg-destructive-soft px-3 py-1.5 text-xs font-semibold text-destructive-soft-foreground", children: [
220
+ "Esperando sua resposta \xB7 ",
221
+ shown.filter(isWaitingOnUs).length
222
+ ] }, `h-wait`) : idx > 0 && isWaitingOnUs(shown[idx - 1]) && !isWaitingOnUs(c) ? /* @__PURE__ */ jsx("p", { className: "bg-muted/60 px-3 py-1.5 text-xs font-medium text-muted-foreground", children: "Em dia" }, `h-ok`) : null : null;
223
+ const active = c.id === selectedId;
224
+ const unread = isWaitingOnUs(c);
225
+ return (
226
+ // `div` em volta e não um botão dentro de outro: HTML não permite
227
+ // aninhar, e o navegador resolve isso silenciosamente movendo o
228
+ // interno para fora — a linha inteira deixa de ser clicável e
229
+ // ninguém entende por quê.
230
+ /* @__PURE__ */ jsxs(React2__default.Fragment, { children: [
231
+ sectionHeader,
232
+ /* @__PURE__ */ jsxs("div", { className: "group relative", children: [
233
+ /* @__PURE__ */ jsxs(
234
+ Button,
235
+ {
236
+ variant: "bare",
237
+ size: "bare",
238
+ onClick: () => select(c.id),
239
+ className: cn(
240
+ "flex w-full items-start justify-start gap-3 rounded-none border-b border-border/50 px-3 py-3 text-left font-normal transition-colors",
241
+ // Um TOM da cor de marca, e não `bg-accent`.
242
+ //
243
+ // `bg-accent` resolve para quase preto neste tema, e a linha da
244
+ // conversa aberta ficava escura sobre escura. Trocar junto o
245
+ // `text-accent-foreground` deixava legível, mas pintava de
246
+ // preto a única linha que se está a ler — chamava mais atenção
247
+ // que a conversa.
248
+ //
249
+ // `bg-primary/10` é um véu: o texto continua com as cores dele,
250
+ // a seleção se lê como seleção e não como bloco, e funciona nos
251
+ // dois temas porque não presume nada sobre o fundo.
252
+ active ? "bg-primary/10" : "hover:bg-muted/50"
253
+ ),
254
+ children: [
255
+ /* @__PURE__ */ jsx(Avatar, { name: c.contactName, accent: c.accent, channel: c.channel }),
256
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
257
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
258
+ /* @__PURE__ */ jsx("span", { className: cn("truncate text-sm text-foreground", unread ? "font-semibold" : "font-medium"), children: c.contactName }),
259
+ /* @__PURE__ */ jsx("span", { className: cn("shrink-0 text-[11px]", unread ? "font-semibold text-primary" : "text-muted-foreground"), children: relativeTime(c.lastMessageAt) })
260
+ ] }),
261
+ /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
262
+ /* @__PURE__ */ jsx(ChannelBadge, { channel: c.channel }),
263
+ c.status !== "open" && /* @__PURE__ */ jsx("span", { className: "text-[10px] uppercase tracking-wide text-muted-foreground/70", children: t(`conversations.status.${c.status}`) }),
264
+ c.leadOwnerName && /* @__PURE__ */ jsxs("span", { className: "inline-flex shrink-0 items-center gap-0.5 rounded-full bg-muted px-1.5 text-[10px] text-muted-foreground", children: [
265
+ /* @__PURE__ */ jsx(User, { className: "h-2.5 w-2.5" }),
266
+ c.leadOwnerName.split(" ")[0]
267
+ ] })
268
+ ] }),
269
+ /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center justify-between gap-2", children: [
270
+ /* @__PURE__ */ jsx("span", { className: cn("truncate text-xs", unread ? "text-foreground" : "text-muted-foreground"), children: /* @__PURE__ */ jsx(MessagePreview, { text: c.lastMessagePreview }) }),
271
+ unread && /* @__PURE__ */ jsx("span", { className: "flex h-[18px] min-w-[18px] shrink-0 items-center justify-center rounded-full bg-destructive px-1.5 text-[10px] font-semibold text-destructive-foreground group-hover:invisible", children: c.unreadCount > 0 ? c.unreadCount : "\xB7" })
272
+ ] })
273
+ ] })
274
+ ]
275
+ }
276
+ ),
277
+ unread && /* @__PURE__ */ jsx(
278
+ Button,
279
+ {
280
+ variant: "bare",
281
+ size: "bare",
282
+ type: "button",
283
+ title: t("conversations.markRead"),
284
+ "aria-label": t("conversations.markRead"),
285
+ onClick: (e) => {
286
+ e.stopPropagation();
287
+ void markRead(c.id);
288
+ },
289
+ className: "absolute bottom-2.5 right-2.5 hidden rounded-full p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground group-hover:block",
290
+ children: /* @__PURE__ */ jsx(CheckCheck, { className: "h-3.5 w-3.5" })
291
+ }
292
+ )
293
+ ] })
294
+ ] }, c.id)
295
+ );
296
+ })
297
+ ] })
298
+ ] });
299
+ }
300
+ var CHANNELS = ["whatsapp", "sms", "instagram", "email", "webchat"];
301
+ function personHandleFor(channel, contact) {
302
+ if (!contact) return "";
303
+ if (channel === "email") return contact.email ?? "";
304
+ if (channel === "sms" || channel === "whatsapp") return contact.phone ?? "";
305
+ return "";
306
+ }
307
+ var HANDLE_LABEL_KEY = {
308
+ whatsapp: "conversations.new.handleLabel.phone",
309
+ sms: "conversations.new.handleLabel.phone",
310
+ email: "conversations.new.handleLabel.email",
311
+ instagram: "conversations.new.handleLabel.instagram",
312
+ webchat: "conversations.new.handleLabel.webchat",
313
+ // Never offered here (a ticket opens its own thread); the key keeps the map total.
314
+ support: "conversations.new.handleLabel.email"
315
+ };
316
+ function NewConversationPanel({
317
+ open,
318
+ onOpenChange
319
+ }) {
320
+ const t = useTranslation();
321
+ const create = useConversationsStore((s) => s.create);
322
+ const config = useConversationsConfig();
323
+ const guardConversations = useLimitGuard("conversations_month");
324
+ const [channel, setChannel] = React2__default.useState("whatsapp");
325
+ const [contact, setContact] = React2__default.useState(null);
326
+ const [typedHandle, setTypedHandle] = React2__default.useState("");
327
+ const [creatingContact, setCreatingContact] = React2__default.useState(false);
328
+ const [firstMessage, setFirstMessage] = React2__default.useState("");
329
+ const [submitting, setSubmitting] = React2__default.useState(false);
330
+ const [pickerKey, setPickerKey] = React2__default.useState(0);
331
+ React2__default.useEffect(() => {
332
+ if (open) {
333
+ setChannel("whatsapp");
334
+ setContact(null);
335
+ setTypedHandle("");
336
+ setCreatingContact(false);
337
+ setFirstMessage("");
338
+ setSubmitting(false);
339
+ setPickerKey((k) => k + 1);
340
+ }
341
+ }, [open]);
342
+ const derivedHandle = personHandleFor(channel, contact);
343
+ const effectiveHandle = derivedHandle || typedHandle;
344
+ const handleLabel = t(HANDLE_LABEL_KEY[channel]);
345
+ const canSubmit = (contact?.name.trim().length ?? 0) > 0 && !submitting;
346
+ async function handleSubmit(e) {
347
+ e.preventDefault();
348
+ if (!canSubmit) return;
349
+ setSubmitting(true);
350
+ try {
351
+ if (await guardConversations() === "blocked") return;
352
+ await create({
353
+ channel,
354
+ contactName: contact.name.trim(),
355
+ contactPersonId: contact?.id,
356
+ contactHandle: effectiveHandle.trim() || void 0,
357
+ firstMessage: firstMessage.trim() || void 0
358
+ });
359
+ invalidateLimit("conversations_month");
360
+ onOpenChange(false);
361
+ } catch (err) {
362
+ const message = errorMessage(err);
363
+ toast.error(t("conversations.new.createFailed"), { description: message });
364
+ } finally {
365
+ setSubmitting(false);
366
+ }
367
+ }
368
+ return /* @__PURE__ */ jsx(Modal, { open, onOpenChange, children: /* @__PURE__ */ jsxs(ModalContent, { className: "max-w-md", children: [
369
+ /* @__PURE__ */ jsx(ModalHeader, { children: /* @__PURE__ */ jsx(ModalTitle, { children: t("conversations.new.title") }) }),
370
+ /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [
371
+ /* @__PURE__ */ jsxs(ModalBody, { className: "space-y-4", children: [
372
+ /* @__PURE__ */ jsxs("div", { children: [
373
+ /* @__PURE__ */ jsx("label", { className: "mb-1.5 block text-xs font-medium text-muted-foreground", children: t("conversations.new.channel") }),
374
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: CHANNELS.map((ch) => {
375
+ const Icon = CHANNEL_ICON[ch];
376
+ const active = channel === ch;
377
+ return /* @__PURE__ */ jsxs(
378
+ Button,
379
+ {
380
+ variant: "bare",
381
+ size: "bare",
382
+ type: "button",
383
+ onClick: () => setChannel(ch),
384
+ "aria-pressed": active,
385
+ className: cn(
386
+ "inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",
387
+ active ? "text-white" : "bg-muted text-muted-foreground hover:bg-muted/70"
388
+ ),
389
+ style: active ? { backgroundColor: CHANNEL_ACCENT[ch].color } : void 0,
390
+ children: [
391
+ /* @__PURE__ */ jsx(Icon, { className: "h-3 w-3" }),
392
+ CHANNEL_LABELS[ch]
393
+ ]
394
+ },
395
+ ch
396
+ );
397
+ }) })
398
+ ] }),
399
+ /* @__PURE__ */ jsx(
400
+ ContactPicker,
401
+ {
402
+ value: contact,
403
+ onChange: setContact,
404
+ kind: config.contactKind,
405
+ lookup: config.contactLookup,
406
+ createEntityDef: config.contactEntityDef,
407
+ allowFreeText: true,
408
+ onCreatingChange: setCreatingContact,
409
+ autoFocus: true,
410
+ label: t("conversations.new.contactName"),
411
+ placeholder: t("conversations.new.contactNamePlaceholder"),
412
+ secondaryText: derivedHandle || void 0,
413
+ handleField: {
414
+ label: handleLabel,
415
+ derived: derivedHandle || void 0,
416
+ value: typedHandle,
417
+ onChange: setTypedHandle,
418
+ fieldLabel: t("conversations.new.handle"),
419
+ placeholder: t("conversations.new.handlePlaceholder")
420
+ }
421
+ },
422
+ pickerKey
423
+ ),
424
+ /* @__PURE__ */ jsxs("div", { children: [
425
+ /* @__PURE__ */ jsx("label", { htmlFor: "conv-first-message", className: "mb-1.5 block text-xs font-medium text-muted-foreground", children: t("conversations.new.firstMessage") }),
426
+ /* @__PURE__ */ jsx(
427
+ Textarea,
428
+ {
429
+ id: "conv-first-message",
430
+ value: firstMessage,
431
+ onChange: (e) => setFirstMessage(e.target.value),
432
+ rows: 3,
433
+ placeholder: t("conversations.new.firstMessagePlaceholder"),
434
+ className: "max-h-40 min-h-[64px] resize-none rounded-md border-border bg-background shadow-none focus:border-primary focus-visible:ring-0 focus-visible:ring-offset-0"
435
+ }
436
+ )
437
+ ] })
438
+ ] }),
439
+ /* @__PURE__ */ jsx(ModalFooter, { children: /* @__PURE__ */ jsx(Button, { type: "submit", disabled: !canSubmit, className: "w-full", children: submitting ? t("conversations.new.creating") : t("conversations.new.create") }) })
440
+ ] })
441
+ ] }) });
442
+ }
443
+ function useCaixaAoVivo() {
444
+ const tenantId = useActiveTenantId();
445
+ const load = useConversationsStore((s) => s.load);
446
+ const refreshMessages = useConversationsStore((s) => s.refreshMessages);
447
+ const selectedId = useConversationsStore((s) => s.selectedId);
448
+ const abertoRef = React2.useRef(selectedId);
449
+ abertoRef.current = selectedId;
450
+ React2.useEffect(() => {
451
+ if (!tenantId) return;
452
+ return assinarChegada(tenantId, ({ conversationId }) => {
453
+ void load({ autoSelect: false });
454
+ if (conversationId && conversationId === abertoRef.current) {
455
+ void refreshMessages();
456
+ }
457
+ });
458
+ }, [tenantId, load, refreshMessages]);
459
+ }
460
+ function InboxView({ layout = "page", newSignal = 0 } = {}) {
461
+ const t = useTranslation();
462
+ const dock = layout !== "page";
463
+ const { conversations, selectedId, deselect } = useConversationsStore((s) => s);
464
+ useCaixaAoVivo();
465
+ const isWideViewport = useMediaQuery("(min-width: 1280px)");
466
+ const isWidePanel = isWideViewport && !dock;
467
+ const railOpen = useRightRailStore((s) => s.open);
468
+ const [panelOpen, setPanelOpen] = React2__default.useState(false);
469
+ const [newOpen, setNewOpen] = React2__default.useState(false);
470
+ const selected = conversations.find((c) => c.id === selectedId) ?? null;
471
+ React2__default.useEffect(() => {
472
+ if (newSignal > 0) setNewOpen(true);
473
+ }, [newSignal]);
474
+ React2__default.useEffect(() => {
475
+ setPanelOpen(isWidePanel && !railOpen);
476
+ }, [isWidePanel, railOpen]);
477
+ const newActions = React2__default.useMemo(() => [{
478
+ id: "new-conversation",
479
+ label: t("conversations.list.new"),
480
+ icon: SquarePen,
481
+ intent: "primary",
482
+ // Starting a conversation creates a thread — the FAB is a "+".
483
+ creates: true,
484
+ testId: "conversations-new",
485
+ permission: { feature: "conversations", action: "create" },
486
+ onSelect: () => setNewOpen(true)
487
+ }], [t]);
488
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
489
+ !dock && /* @__PURE__ */ jsx(PageHeaderActions, { children: /* @__PURE__ */ jsx(PageActions, { actions: newActions }) }),
490
+ /* @__PURE__ */ jsx(NewConversationPanel, { open: newOpen, onOpenChange: setNewOpen }),
491
+ /* @__PURE__ */ jsxs("div", { className: "relative flex h-full min-h-0 overflow-hidden bg-background", children: [
492
+ /* @__PURE__ */ jsx(ConversationList, { className: cn(
493
+ layout === "page" && (selected ? "hidden lg:flex" : "flex"),
494
+ layout === "dock" && (selected ? "hidden" : "flex lg:w-full border-r-0"),
495
+ layout === "dock-wide" && "flex lg:w-[300px]"
496
+ ) }),
497
+ selected ? /* @__PURE__ */ jsx(
498
+ MessageThread,
499
+ {
500
+ selected,
501
+ panelOpen,
502
+ onTogglePanel: () => setPanelOpen((v) => !v),
503
+ onBack: deselect,
504
+ backAlways: layout === "dock",
505
+ className: "flex"
506
+ }
507
+ ) : layout === "dock" ? null : /* @__PURE__ */ jsxs("section", { className: cn("min-w-0 flex-1 flex-col items-center justify-center bg-muted/20 text-muted-foreground", dock ? "flex" : "hidden lg:flex"), children: [
508
+ /* @__PURE__ */ jsx(MessageSquare, { className: "h-9 w-9" }),
509
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm", children: t("conversations.empty.select") })
510
+ ] }),
511
+ selected && panelOpen && /* @__PURE__ */ jsxs(Fragment, { children: [
512
+ /* @__PURE__ */ jsx(
513
+ Button,
514
+ {
515
+ variant: "bare",
516
+ size: "bare",
517
+ className: cn("absolute inset-0 z-10 rounded-none bg-black/40", !dock && "xl:hidden"),
518
+ "aria-label": "Close details",
519
+ onClick: () => setPanelOpen(false)
520
+ }
521
+ ),
522
+ /* @__PURE__ */ jsx(
523
+ ContactPanel,
524
+ {
525
+ contact: selected,
526
+ onClose: () => setPanelOpen(false),
527
+ className: cn("absolute inset-y-0 right-0 z-20 w-[340px] max-w-[88%] shadow-2xl", !dock && "xl:static xl:z-auto xl:w-[300px] xl:max-w-none xl:bg-muted/20 xl:shadow-none")
528
+ }
529
+ )
530
+ ] })
531
+ ] })
532
+ ] });
533
+ }
534
+ var CHANNELS2 = ["sms", "whatsapp", "instagram", "email", "webchat"];
535
+ function requestedContact() {
536
+ try {
537
+ const hash = currentAppPath();
538
+ const qs = hash.includes("?") ? hash.slice(hash.indexOf("?") + 1) : "";
539
+ if (!qs) return null;
540
+ const p = new URLSearchParams(qs);
541
+ const handle = (p.get("handle") ?? "").trim();
542
+ const name = (p.get("name") ?? "").trim();
543
+ const personId = (p.get("personId") ?? "").trim() || void 0;
544
+ if (!handle) return null;
545
+ const raw = (p.get("channel") ?? "whatsapp").toLowerCase();
546
+ const channel = CHANNELS2.includes(raw) ? raw : "whatsapp";
547
+ return { personId, name: name || handle, handle, channel };
548
+ } catch {
549
+ return null;
550
+ }
551
+ }
552
+ function conversationIdFromPath(path) {
553
+ const m = /^\/conversations\/([^/?#]+)/.exec(path);
554
+ return m ? decodeURIComponent(m[1]) : null;
555
+ }
556
+ function legacyConversationId(path) {
557
+ try {
558
+ const qs = path.includes("?") ? path.slice(path.indexOf("?") + 1) : "";
559
+ return qs ? (new URLSearchParams(qs).get("conversation") ?? "").trim() || null : null;
560
+ } catch {
561
+ return null;
562
+ }
563
+ }
564
+ function ConversationsPage({ store, config }) {
565
+ React2__default.useEffect(() => {
566
+ const wanted = requestedContact();
567
+ if (!wanted) {
568
+ const path = currentAppPath();
569
+ const legacy = legacyConversationId(path);
570
+ const threadId = conversationIdFromPath(path) ?? legacy;
571
+ if (legacy) {
572
+ try {
573
+ replaceApp(`/conversations/${encodeURIComponent(legacy)}`);
574
+ } catch {
575
+ }
576
+ }
577
+ if (threadId) {
578
+ store.setState({ selectedId: threadId, channelFilter: "all", search: "" });
579
+ void store.getState().load().then(() => store.getState().focus(threadId));
580
+ } else {
581
+ void store.getState().load();
582
+ }
583
+ return;
584
+ }
585
+ void store.getState().openForPerson(wanted).catch(() => {
586
+ void store.getState().load();
587
+ });
588
+ try {
589
+ const hash = currentAppPath();
590
+ const clean = hash.includes("?") ? hash.slice(0, hash.indexOf("?")) : hash;
591
+ window.history.replaceState(null, "", appHref(clean || "/conversations"));
592
+ } catch {
593
+ }
594
+ }, []);
595
+ React2__default.useEffect(() => {
596
+ const write = (id) => {
597
+ const path = currentAppPath();
598
+ if (!path.startsWith("/conversations")) return;
599
+ if (path.includes("?")) return;
600
+ if (conversationIdFromPath(path) === id) return;
601
+ replaceApp(id ? `/conversations/${encodeURIComponent(id)}` : "/conversations");
602
+ };
603
+ write(store.getState().selectedId);
604
+ const unsubscribe = store.subscribe((state, previous) => {
605
+ if (state.selectedId !== previous.selectedId) write(state.selectedId);
606
+ });
607
+ const off = onAppPathChange((path) => {
608
+ const id = conversationIdFromPath(path || "/");
609
+ if (id && id !== store.getState().selectedId) void store.getState().select(id);
610
+ });
611
+ return () => {
612
+ unsubscribe();
613
+ off();
614
+ };
615
+ }, [store]);
616
+ return /* @__PURE__ */ jsx(ConversationsContextProvider, { store, config, children: /* @__PURE__ */ jsx(InboxView, {}) });
617
+ }
618
+
619
+ export { ConversationsPage, conversationIdFromPath, legacyConversationId };
620
+ //# sourceMappingURL=ConversationsPage-ZYMNPRSI.js.map
621
+ //# sourceMappingURL=ConversationsPage-ZYMNPRSI.js.map