fi-glass 1.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,4316 @@
1
+ 'use client';
2
+
3
+ // src/theme/glass-theme.ts
4
+ var glassTheme = {
5
+ blur: "12px",
6
+ blurCompact: "8px",
7
+ opacity: 0.8,
8
+ saturation: "180%",
9
+ surfaceLight: "255, 255, 255",
10
+ borderLight: "rgba(255, 255, 255, 0.18)",
11
+ surfaceDark: "rgba(15, 23, 42, 0.7)",
12
+ borderDark: "rgba(148, 163, 184, 0.2)"
13
+ };
14
+
15
+ // src/messages/styles.ts
16
+ var messageStyles = {
17
+ // Container
18
+ container: {
19
+ base: "space-y-0.5",
20
+ padding: "px-4"
21
+ },
22
+ // Message row
23
+ message: {
24
+ base: "group relative py-3 px-4 -mx-4 transition-colors duration-150",
25
+ user: "bg-transparent hover:bg-white/[0.02]",
26
+ assistant: "bg-white/[0.02] hover:bg-white/[0.04]",
27
+ borderRadius: "rounded-lg"
28
+ },
29
+ // Avatar
30
+ avatar: {
31
+ size: "w-6 h-6",
32
+ base: "rounded-md flex items-center justify-center text-[10px] font-semibold flex-shrink-0",
33
+ user: "bg-violet-600/80 text-white",
34
+ assistant: "bg-amber-500/80 text-slate-900"
35
+ },
36
+ // Meta (name + time)
37
+ meta: {
38
+ container: "flex items-baseline gap-2",
39
+ name: "text-[13px] font-medium text-slate-300",
40
+ time: "text-[11px] text-slate-500 tabular-nums"
41
+ },
42
+ // Content
43
+ content: {
44
+ base: "text-[14px] leading-relaxed",
45
+ user: "text-slate-200",
46
+ assistant: "text-slate-100",
47
+ indent: "pl-8"
48
+ // Align with avatar
49
+ },
50
+ // Actions toolbar
51
+ actions: {
52
+ container: `
53
+ absolute top-2 right-2
54
+ flex items-center gap-0.5
55
+ opacity-0 group-hover:opacity-100
56
+ transition-opacity duration-150
57
+ bg-slate-800/95 backdrop-blur-sm rounded-md p-0.5
58
+ border border-slate-700/50 shadow-lg
59
+ `,
60
+ button: {
61
+ base: "p-1 rounded transition-colors duration-150",
62
+ idle: "hover:bg-slate-700 text-slate-400 hover:text-slate-200",
63
+ active: "bg-emerald-500/20 text-emerald-400",
64
+ speaking: "bg-amber-500/20 text-amber-400"
65
+ },
66
+ icon: "w-3 h-3"
67
+ },
68
+ // Date divider
69
+ dateDivider: {
70
+ container: "my-4 flex items-center gap-3",
71
+ line: "flex-1 h-px bg-gradient-to-r from-transparent via-slate-700/30 to-transparent",
72
+ label: "px-3 py-1 text-[10px] text-slate-500 font-medium bg-slate-900/50 rounded-full"
73
+ },
74
+ // Typing indicator
75
+ typing: {
76
+ container: "flex items-center gap-2 px-4 py-2",
77
+ dot: "w-1.5 h-1.5 bg-amber-400/80 rounded-full",
78
+ animation: "animate-bounce"
79
+ }
80
+ };
81
+ var markdownStyles = {
82
+ p: "mb-3 last:mb-0",
83
+ strong: "font-semibold text-white",
84
+ em: "italic text-slate-300",
85
+ code: "px-1 py-0.5 bg-slate-800/80 rounded text-amber-300/90 font-mono text-[13px]",
86
+ pre: "my-3 p-3 bg-slate-900/80 rounded-lg border border-slate-700/30 overflow-x-auto text-[13px]",
87
+ ul: "my-2 ml-0.5 space-y-1.5",
88
+ ol: "my-2 ml-0.5 space-y-1.5 list-decimal list-inside",
89
+ li: "flex gap-1.5 text-slate-200",
90
+ bullet: "text-slate-500 select-none text-[10px] mt-1",
91
+ h1: "text-lg font-semibold text-white mt-4 mb-2",
92
+ h2: "text-base font-semibold text-white mt-3 mb-1.5",
93
+ h3: "text-sm font-semibold text-slate-100 mt-2 mb-1",
94
+ blockquote: "my-3 pl-3 border-l-2 border-slate-600/50 text-slate-400 italic text-[13px]",
95
+ link: "text-amber-400/90 hover:text-amber-300 underline underline-offset-2 transition-colors"
96
+ };
97
+
98
+ // src/messages/MessageContent.tsx
99
+ import { memo } from "react";
100
+ import ReactMarkdown from "react-markdown";
101
+ import remarkGfm from "remark-gfm";
102
+
103
+ // src/messages/normalizeStreamedMarkdown.ts
104
+ var FENCE_SPLIT = /(```[\s\S]*?(?:```|$))/;
105
+ var GLUED_HEADING = /([.!?:;,)\]"'»…])(#{1,6} )/g;
106
+ function normalizeStreamedMarkdown(content) {
107
+ if (!content.includes("#")) return content;
108
+ return content.split(FENCE_SPLIT).map(
109
+ (segment, i) => i % 2 === 1 ? segment : segment.replace(GLUED_HEADING, "$1\n\n$2")
110
+ ).join("");
111
+ }
112
+
113
+ // src/messages/CollapsibleText.tsx
114
+ import { useEffect, useId, useRef, useState } from "react";
115
+ import { jsx, jsxs } from "react/jsx-runtime";
116
+ var OVERFLOW_TOLERANCE_PX = 16;
117
+ function CollapsibleText({
118
+ children,
119
+ maxHeight = 264,
120
+ fadeHeight = 48,
121
+ showMoreLabel = "Mostrar m\xE1s",
122
+ showLessLabel = "Mostrar menos",
123
+ className,
124
+ toggleClassName
125
+ }) {
126
+ const contentId = useId();
127
+ const contentRef = useRef(null);
128
+ const [expanded, setExpanded] = useState(false);
129
+ const [overflowing, setOverflowing] = useState(false);
130
+ useEffect(() => {
131
+ const el = contentRef.current;
132
+ if (!el) return;
133
+ const measure = () => setOverflowing(el.scrollHeight > maxHeight + OVERFLOW_TOLERANCE_PX);
134
+ measure();
135
+ if (typeof ResizeObserver === "undefined") return;
136
+ const ro = new ResizeObserver(measure);
137
+ ro.observe(el);
138
+ return () => ro.disconnect();
139
+ }, [maxHeight]);
140
+ const clamped = overflowing && !expanded;
141
+ const mask = `linear-gradient(rgb(0,0,0) calc(100% - ${fadeHeight}px), transparent)`;
142
+ return /* @__PURE__ */ jsxs("div", { className, children: [
143
+ /* @__PURE__ */ jsx(
144
+ "div",
145
+ {
146
+ id: contentId,
147
+ ref: contentRef,
148
+ style: clamped ? {
149
+ maxHeight,
150
+ overflow: "hidden",
151
+ maskImage: mask,
152
+ WebkitMaskImage: mask
153
+ } : void 0,
154
+ children
155
+ }
156
+ ),
157
+ overflowing && /* @__PURE__ */ jsx(
158
+ "button",
159
+ {
160
+ type: "button",
161
+ "aria-expanded": expanded,
162
+ "aria-controls": contentId,
163
+ onClick: () => setExpanded((e) => !e),
164
+ className: toggleClassName,
165
+ style: toggleClassName ? void 0 : {
166
+ marginTop: "0.25rem",
167
+ padding: 0,
168
+ border: "none",
169
+ background: "transparent",
170
+ color: "#94a3b8",
171
+ fontSize: "0.8rem",
172
+ cursor: "pointer",
173
+ textDecoration: "underline",
174
+ textUnderlineOffset: 2
175
+ },
176
+ children: expanded ? showLessLabel : showMoreLabel
177
+ }
178
+ )
179
+ ] });
180
+ }
181
+
182
+ // src/messages/MessageContent.tsx
183
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
184
+ var mdComponents = {
185
+ p: ({ children }) => /* @__PURE__ */ jsx2("p", { className: markdownStyles.p, children }),
186
+ strong: ({ children }) => /* @__PURE__ */ jsx2("strong", { className: markdownStyles.strong, children }),
187
+ em: ({ children }) => /* @__PURE__ */ jsx2("em", { className: markdownStyles.em, children }),
188
+ code: ({ children }) => /* @__PURE__ */ jsx2("code", { className: markdownStyles.code, children }),
189
+ pre: ({ children }) => /* @__PURE__ */ jsx2("pre", { className: markdownStyles.pre, children }),
190
+ ul: ({ children }) => /* @__PURE__ */ jsx2("ul", { className: markdownStyles.ul, children }),
191
+ ol: ({ children }) => /* @__PURE__ */ jsx2("ol", { className: markdownStyles.ol, children }),
192
+ li: ({ children }) => /* @__PURE__ */ jsxs2("li", { className: markdownStyles.li, children: [
193
+ /* @__PURE__ */ jsx2("span", { className: markdownStyles.bullet, children: "\u2022" }),
194
+ /* @__PURE__ */ jsx2("span", { className: "flex-1", children })
195
+ ] }),
196
+ h1: ({ children }) => /* @__PURE__ */ jsx2("h1", { className: markdownStyles.h1, children }),
197
+ h2: ({ children }) => /* @__PURE__ */ jsx2("h2", { className: markdownStyles.h2, children }),
198
+ h3: ({ children }) => /* @__PURE__ */ jsx2("h3", { className: markdownStyles.h3, children }),
199
+ blockquote: ({ children }) => /* @__PURE__ */ jsx2("blockquote", { className: markdownStyles.blockquote, children }),
200
+ a: ({ href, children }) => /* @__PURE__ */ jsx2("a", { href, className: markdownStyles.link, target: "_blank", rel: "noopener noreferrer", children })
201
+ };
202
+ function defaultRenderMarkdown(content) {
203
+ return /* @__PURE__ */ jsx2(ReactMarkdown, { remarkPlugins: [remarkGfm], components: mdComponents, children: normalizeStreamedMarkdown(content) });
204
+ }
205
+ var MessageContent = memo(function MessageContent2({
206
+ isUser,
207
+ content,
208
+ isStreaming = false,
209
+ renderMarkdown = defaultRenderMarkdown,
210
+ collapsible = false,
211
+ collapsedMaxHeight,
212
+ showMoreLabel,
213
+ showLessLabel,
214
+ collapseToggleClassName
215
+ }) {
216
+ const { content: styles } = messageStyles;
217
+ const body = isUser ? (
218
+ // User: plain text, preserve whitespace
219
+ /* @__PURE__ */ jsx2("p", { className: "whitespace-pre-wrap", children: content })
220
+ ) : (
221
+ // Assistant: markdown (overridable)
222
+ renderMarkdown(content)
223
+ );
224
+ return /* @__PURE__ */ jsxs2(
225
+ "div",
226
+ {
227
+ className: `${styles.base} ${isUser ? styles.user : styles.assistant} ${styles.indent}`,
228
+ children: [
229
+ collapsible && !isStreaming ? /* @__PURE__ */ jsx2(
230
+ CollapsibleText,
231
+ {
232
+ maxHeight: collapsedMaxHeight,
233
+ showMoreLabel,
234
+ showLessLabel,
235
+ toggleClassName: collapseToggleClassName,
236
+ children: body
237
+ }
238
+ ) : body,
239
+ isStreaming && /* @__PURE__ */ jsx2("span", { className: "inline-block w-1.5 h-4 bg-amber-400/80 ml-0.5 animate-pulse rounded-sm" })
240
+ ]
241
+ }
242
+ );
243
+ });
244
+
245
+ // src/messages/CopyButton.tsx
246
+ import { memo as memo2, useCallback, useState as useState2 } from "react";
247
+ import { Copy, Check } from "lucide-react";
248
+ import { jsx as jsx3 } from "react/jsx-runtime";
249
+ var CopyButton = memo2(function CopyButton2({
250
+ content,
251
+ onError,
252
+ className,
253
+ idleClassName,
254
+ activeClassName,
255
+ iconClassName,
256
+ copyLabel = "Copiar",
257
+ copiedLabel = "Copiado",
258
+ resetMs = 2e3
259
+ }) {
260
+ const [copied, setCopied] = useState2(false);
261
+ const { actions } = messageStyles;
262
+ const base = className ?? actions.button.base;
263
+ const idle = idleClassName ?? actions.button.idle;
264
+ const active = activeClassName ?? actions.button.active;
265
+ const icon = iconClassName ?? actions.icon;
266
+ const handleCopy = useCallback(async () => {
267
+ try {
268
+ await navigator.clipboard.writeText(content);
269
+ setCopied(true);
270
+ setTimeout(() => setCopied(false), resetMs);
271
+ } catch (err) {
272
+ onError?.(err);
273
+ }
274
+ }, [content, onError, resetMs]);
275
+ return /* @__PURE__ */ jsx3(
276
+ "button",
277
+ {
278
+ onClick: handleCopy,
279
+ className: `${base} ${copied ? active : idle}`,
280
+ title: copied ? copiedLabel : copyLabel,
281
+ "aria-label": copied ? copiedLabel : `${copyLabel} mensaje`,
282
+ children: copied ? /* @__PURE__ */ jsx3(Check, { className: icon }) : /* @__PURE__ */ jsx3(Copy, { className: icon })
283
+ }
284
+ );
285
+ });
286
+
287
+ // src/messages/MessageBubble.tsx
288
+ import { memo as memo3 } from "react";
289
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
290
+ var MessageBubble = memo3(function MessageBubble2({
291
+ role,
292
+ children,
293
+ header,
294
+ reasoning,
295
+ badge,
296
+ actions,
297
+ className,
298
+ ariaLabel
299
+ }) {
300
+ const { message: styles } = messageStyles;
301
+ const isUser = role === "user";
302
+ return /* @__PURE__ */ jsxs3(
303
+ "article",
304
+ {
305
+ className: `fi-msg-appear ${styles.base} ${styles.borderRadius} ${isUser ? styles.user : styles.assistant} ${className || ""}`,
306
+ role: "article",
307
+ "aria-label": ariaLabel,
308
+ children: [
309
+ header && /* @__PURE__ */ jsx4("div", { className: "flex items-center gap-2 mb-1", children: header }),
310
+ reasoning && /* @__PURE__ */ jsx4("div", { className: "mt-3 mb-3", children: reasoning }),
311
+ children,
312
+ badge && /* @__PURE__ */ jsx4("div", { className: "mt-2", children: badge }),
313
+ actions
314
+ ]
315
+ }
316
+ );
317
+ });
318
+
319
+ // src/messages/MessageList.tsx
320
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
321
+ function MessageList({
322
+ groups,
323
+ renderItem,
324
+ renderDivider,
325
+ containerClassName,
326
+ groupClassName,
327
+ header,
328
+ footer
329
+ }) {
330
+ return /* @__PURE__ */ jsxs4("div", { className: containerClassName, children: [
331
+ header,
332
+ groups.map((group) => /* @__PURE__ */ jsxs4("div", { children: [
333
+ renderDivider?.(group.key),
334
+ /* @__PURE__ */ jsx5("div", { className: groupClassName, children: group.items.map((item, idx) => renderItem(item, idx)) })
335
+ ] }, group.key)),
336
+ footer
337
+ ] });
338
+ }
339
+
340
+ // src/composer/AutoResizeTextarea.tsx
341
+ import {
342
+ forwardRef,
343
+ useEffect as useEffect2,
344
+ useImperativeHandle,
345
+ useRef as useRef2,
346
+ useState as useState3
347
+ } from "react";
348
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
349
+ var AutoResizeTextarea = forwardRef(function AutoResizeTextarea2({
350
+ value,
351
+ onChange,
352
+ maxRows = 5,
353
+ showCounter = false,
354
+ maxLength,
355
+ wrapperClassName = "",
356
+ wrapperStyle,
357
+ className = "",
358
+ ...props
359
+ }, ref) {
360
+ const textareaRef = useRef2(null);
361
+ useImperativeHandle(ref, () => textareaRef.current);
362
+ const [rows, setRows] = useState3(1);
363
+ useEffect2(() => {
364
+ if (!textareaRef.current) return;
365
+ const textarea = textareaRef.current;
366
+ textarea.rows = 1;
367
+ textarea.style.height = "auto";
368
+ const computed = window.getComputedStyle(textarea);
369
+ const parsed = parseFloat(computed.lineHeight);
370
+ const lineHeight = Number.isFinite(parsed) && parsed > 0 ? parsed : 20;
371
+ const newRows = Math.max(
372
+ 1,
373
+ Math.min(Math.ceil(textarea.scrollHeight / lineHeight), maxRows)
374
+ );
375
+ setRows(newRows);
376
+ textarea.rows = newRows;
377
+ textarea.style.height = `${newRows * lineHeight}px`;
378
+ textarea.style.width = "100%";
379
+ }, [value, maxRows]);
380
+ const charCount = typeof value === "string" ? value.length : 0;
381
+ const isNearLimit = maxLength && charCount > maxLength * 0.9;
382
+ const isOverLimit = maxLength && charCount > maxLength;
383
+ return /* @__PURE__ */ jsxs5("div", { className: `relative ${wrapperClassName}`, style: wrapperStyle, children: [
384
+ /* @__PURE__ */ jsx6(
385
+ "textarea",
386
+ {
387
+ ref: textareaRef,
388
+ value,
389
+ onChange,
390
+ maxLength,
391
+ className: `
392
+ resize-none
393
+ ${className}
394
+ `,
395
+ rows,
396
+ ...props
397
+ }
398
+ ),
399
+ showCounter && maxLength && /* @__PURE__ */ jsxs5("div", { className: isOverLimit ? "chat-char-counter-error" : isNearLimit ? "chat-char-counter-warning" : "chat-char-counter-ok", children: [
400
+ charCount,
401
+ "/",
402
+ maxLength
403
+ ] })
404
+ ] });
405
+ });
406
+
407
+ // src/composer/Composer.tsx
408
+ import { jsx as jsx7 } from "react/jsx-runtime";
409
+ function Composer({
410
+ message,
411
+ loading = false,
412
+ placeholder = "Escribe tu mensaje...",
413
+ onMessageChange,
414
+ onSend,
415
+ maxRows = 5,
416
+ areaClassName,
417
+ wrapperClassName,
418
+ wrapperStyle,
419
+ textareaClassName,
420
+ textareaRef
421
+ }) {
422
+ const handleKeyDown = (e) => {
423
+ if (e.key === "Enter" && !e.shiftKey) {
424
+ e.preventDefault();
425
+ onSend();
426
+ }
427
+ };
428
+ return /* @__PURE__ */ jsx7("div", { className: areaClassName, children: /* @__PURE__ */ jsx7(
429
+ AutoResizeTextarea,
430
+ {
431
+ ref: textareaRef,
432
+ value: message,
433
+ onChange: (e) => onMessageChange(e.target.value),
434
+ onKeyDown: handleKeyDown,
435
+ placeholder,
436
+ disabled: loading,
437
+ maxRows,
438
+ showCounter: false,
439
+ wrapperClassName,
440
+ wrapperStyle,
441
+ className: textareaClassName
442
+ }
443
+ ) });
444
+ }
445
+
446
+ // src/voice/recording/RecordingButton.tsx
447
+ import { forwardRef as forwardRef2 } from "react";
448
+ import { Loader2 } from "lucide-react";
449
+
450
+ // src/voice/recording/types.ts
451
+ var BUTTON_SIZES = {
452
+ sm: {
453
+ button: "rec-btn-sm",
454
+ icon: "rec-icon-sm",
455
+ ring: "rec-ring-sm"
456
+ },
457
+ md: {
458
+ button: "rec-btn-md",
459
+ icon: "rec-icon-md",
460
+ ring: "rec-ring-md"
461
+ },
462
+ lg: {
463
+ button: "rec-btn-lg",
464
+ icon: "rec-icon-lg",
465
+ ring: "rec-ring-lg"
466
+ },
467
+ xl: {
468
+ button: "rec-btn-xl",
469
+ icon: "rec-icon-xl",
470
+ ring: "rec-ring-xl"
471
+ }
472
+ };
473
+ var COLOR_THEMES = {
474
+ medical: {
475
+ idle: "rec-theme-medical-idle",
476
+ starting: "rec-theme-medical-starting",
477
+ recording: "rec-theme-medical-recording",
478
+ pausing: "rec-theme-medical-pausing",
479
+ paused: "rec-theme-medical-paused",
480
+ resuming: "rec-theme-medical-resuming",
481
+ processing: "rec-theme-medical-processing",
482
+ stopping: "rec-theme-medical-stopping",
483
+ finalized: "rec-theme-medical-finalized"
484
+ },
485
+ chat: {
486
+ idle: "rec-theme-chat-idle",
487
+ starting: "rec-theme-chat-starting",
488
+ recording: "rec-theme-chat-recording",
489
+ pausing: "rec-theme-chat-pausing",
490
+ paused: "rec-theme-chat-paused",
491
+ resuming: "rec-theme-chat-resuming",
492
+ processing: "rec-theme-chat-processing",
493
+ stopping: "rec-theme-chat-stopping",
494
+ finalized: "rec-theme-chat-finalized"
495
+ },
496
+ minimal: {
497
+ idle: "rec-theme-minimal-idle",
498
+ starting: "rec-theme-minimal-starting",
499
+ recording: "rec-theme-minimal-recording",
500
+ pausing: "rec-theme-minimal-pausing",
501
+ paused: "rec-theme-minimal-paused",
502
+ resuming: "rec-theme-minimal-resuming",
503
+ processing: "rec-theme-minimal-processing",
504
+ stopping: "rec-theme-minimal-stopping",
505
+ finalized: "rec-theme-minimal-finalized"
506
+ }
507
+ };
508
+ var STATUS_TEXT_ES = {
509
+ idle: "Presiona para comenzar",
510
+ starting: "Iniciando...",
511
+ recording: "Grabando...",
512
+ pausing: "Pausando...",
513
+ paused: "Pausado",
514
+ resuming: "Reanudando...",
515
+ processing: "Procesando...",
516
+ stopping: "Finalizando...",
517
+ finalized: "Completado"
518
+ };
519
+ var STATUS_TEXT_EN = {
520
+ idle: "Press to start",
521
+ starting: "Starting...",
522
+ recording: "Recording...",
523
+ pausing: "Pausing...",
524
+ paused: "Paused",
525
+ resuming: "Resuming...",
526
+ processing: "Processing...",
527
+ stopping: "Stopping...",
528
+ finalized: "Complete"
529
+ };
530
+
531
+ // src/voice/recording/RecordingButton.tsx
532
+ import { jsx as jsx8 } from "react/jsx-runtime";
533
+ var RecordingButton = forwardRef2(
534
+ function RecordingButton2({
535
+ size = "md",
536
+ bgColor,
537
+ icon: Icon,
538
+ iconSpin = false,
539
+ iconColor = "rec-icon-white",
540
+ disabled = false,
541
+ onClick,
542
+ ariaLabel,
543
+ className = "",
544
+ borderStyle = "",
545
+ animate = ""
546
+ }, ref) {
547
+ const sizeConfig = BUTTON_SIZES[size];
548
+ const DisplayIcon = iconSpin ? Loader2 : Icon;
549
+ return /* @__PURE__ */ jsx8(
550
+ "button",
551
+ {
552
+ ref,
553
+ onClick,
554
+ disabled,
555
+ "aria-label": ariaLabel,
556
+ className: `fi-recording-btn-base ${sizeConfig.button} ${bgColor} ${borderStyle} ${animate} ${disabled ? "rec-btn-disabled" : "rec-btn-enabled"} ${className}`,
557
+ children: /* @__PURE__ */ jsx8(
558
+ DisplayIcon,
559
+ {
560
+ className: `${sizeConfig.icon} ${iconColor} ${iconSpin ? "rec-icon-spin" : ""}`
561
+ }
562
+ )
563
+ }
564
+ );
565
+ }
566
+ );
567
+
568
+ // src/voice/recording/PulseRings.tsx
569
+ import { motion } from "framer-motion";
570
+ import { Fragment, jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
571
+ function PingRings({ color = "yellow-500" }) {
572
+ const bgClass = `rec-pulse-bg-${color}`;
573
+ return /* @__PURE__ */ jsxs6(Fragment, { children: [
574
+ /* @__PURE__ */ jsx9(
575
+ "div",
576
+ {
577
+ className: `rec-pulse-ping-primary ${bgClass}`
578
+ }
579
+ ),
580
+ /* @__PURE__ */ jsx9(
581
+ "div",
582
+ {
583
+ className: `rec-pulse-ping-secondary ${bgClass}`,
584
+ style: { animation: "pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite" }
585
+ }
586
+ )
587
+ ] });
588
+ }
589
+ function ConcentricRings({ color = "yellow-500" }) {
590
+ const borderClass = `rec-pulse-border-${color}`;
591
+ const rings = [
592
+ { scale: 1.3, opacity: 0.4, delay: 0 },
593
+ { scale: 1.5, opacity: 0.3, delay: 0.2 },
594
+ { scale: 1.7, opacity: 0.2, delay: 0.4 }
595
+ ];
596
+ return /* @__PURE__ */ jsx9(Fragment, { children: rings.map((ring, i) => /* @__PURE__ */ jsx9(
597
+ motion.div,
598
+ {
599
+ className: `rec-pulse-concentric ${borderClass}`,
600
+ initial: { scale: 1, opacity: ring.opacity },
601
+ animate: {
602
+ scale: [1, ring.scale, 1],
603
+ opacity: [ring.opacity, ring.opacity * 0.5, ring.opacity]
604
+ },
605
+ transition: {
606
+ duration: 1.5,
607
+ repeat: Infinity,
608
+ ease: "easeInOut",
609
+ delay: ring.delay
610
+ }
611
+ },
612
+ i
613
+ )) });
614
+ }
615
+ function VADRings({
616
+ audioLevel = 0,
617
+ isSilent = true
618
+ }) {
619
+ const audioScale = !isSilent ? Math.max(1, 1 + audioLevel / 255 * 1) : 1;
620
+ const ringColor = isSilent ? "rgb(239, 68, 68)" : "rgb(34, 197, 94)";
621
+ const rings = [
622
+ { baseScale: 1.2, opacityBase: 0.6 },
623
+ { baseScale: 1.4, opacityBase: 0.4 },
624
+ { baseScale: 1.6, opacityBase: 0.2 }
625
+ ];
626
+ return /* @__PURE__ */ jsx9(Fragment, { children: rings.map((ring, i) => /* @__PURE__ */ jsx9(
627
+ motion.div,
628
+ {
629
+ className: "rec-pulse-vad",
630
+ style: { borderColor: ringColor },
631
+ animate: {
632
+ scale: audioScale * ring.baseScale,
633
+ opacity: ring.opacityBase
634
+ },
635
+ transition: {
636
+ duration: 0.2,
637
+ // Transición suave pero rápida para seguir el ritmo
638
+ ease: "easeOut"
639
+ }
640
+ },
641
+ i
642
+ )) });
643
+ }
644
+ function PulseRings({
645
+ style,
646
+ color = "yellow-500",
647
+ audioLevel = 0,
648
+ isSilent = true,
649
+ className = ""
650
+ }) {
651
+ if (style === "none") return null;
652
+ return /* @__PURE__ */ jsxs6("div", { className: `rec-pulse-container ${className}`, children: [
653
+ style === "ping" && /* @__PURE__ */ jsx9(PingRings, { color }),
654
+ style === "rings" && /* @__PURE__ */ jsx9(ConcentricRings, { color }),
655
+ style === "vad" && /* @__PURE__ */ jsx9(VADRings, { audioLevel, isSilent })
656
+ ] });
657
+ }
658
+
659
+ // src/voice/recording/RecordingTimer.tsx
660
+ import { motion as motion2 } from "framer-motion";
661
+ import { jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
662
+ function formatRecordingTime(seconds) {
663
+ const mins = Math.floor(seconds / 60);
664
+ const secs = seconds % 60;
665
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
666
+ }
667
+ var SIZE_CLASSES = {
668
+ sm: "rec-timer-sm",
669
+ md: "rec-timer-md",
670
+ lg: "rec-timer-lg"
671
+ };
672
+ function RecordingTimer({
673
+ time,
674
+ visible = true,
675
+ size = "md",
676
+ showDot = false,
677
+ textColor = "rec-timer-text-white",
678
+ dotColor = "rec-timer-dot-red",
679
+ className = ""
680
+ }) {
681
+ if (!visible || time <= 0) return null;
682
+ return /* @__PURE__ */ jsxs7("div", { className: `rec-timer-wrap ${SIZE_CLASSES[size]} ${className}`, children: [
683
+ showDot && /* @__PURE__ */ jsx10(
684
+ motion2.div,
685
+ {
686
+ className: `rec-timer-dot ${dotColor}`,
687
+ animate: { opacity: [1, 0.3, 1] },
688
+ transition: {
689
+ duration: 1.5,
690
+ repeat: Infinity,
691
+ ease: "easeInOut"
692
+ }
693
+ }
694
+ ),
695
+ /* @__PURE__ */ jsx10("span", { className: `${textColor} rec-timer-value`, children: formatRecordingTime(time) })
696
+ ] });
697
+ }
698
+
699
+ // src/voice/recording/StatusText.tsx
700
+ import { Loader2 as Loader22 } from "lucide-react";
701
+ import { motion as motion3 } from "framer-motion";
702
+ import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
703
+ function StatusText({
704
+ text,
705
+ color = "rec-status-color-default",
706
+ showLoader = false,
707
+ animate = false,
708
+ className = ""
709
+ }) {
710
+ const content = /* @__PURE__ */ jsxs8("div", { className: `rec-status-wrap ${color} ${className}`, children: [
711
+ showLoader && /* @__PURE__ */ jsx11(Loader22, { className: "rec-status-loader" }),
712
+ /* @__PURE__ */ jsx11("p", { className: "rec-status-text", children: text })
713
+ ] });
714
+ if (animate) {
715
+ return /* @__PURE__ */ jsx11(
716
+ motion3.div,
717
+ {
718
+ initial: { opacity: 0.7 },
719
+ animate: { opacity: [0.7, 1, 0.7] },
720
+ transition: { duration: 1.5, repeat: Infinity, ease: "easeInOut" },
721
+ children: content
722
+ }
723
+ );
724
+ }
725
+ return content;
726
+ }
727
+
728
+ // src/voice/VoiceMicButton.tsx
729
+ import { Mic, Square, Loader2 as Loader23 } from "lucide-react";
730
+ import { motion as motion4 } from "framer-motion";
731
+ import { jsx as jsx12, jsxs as jsxs9 } from "react/jsx-runtime";
732
+ function deriveState(isRecording, isTranscribing) {
733
+ if (isTranscribing && !isRecording) return "processing";
734
+ if (isRecording) return "recording";
735
+ return "idle";
736
+ }
737
+ function getButtonColor(state, isSilent) {
738
+ if (state === "recording") {
739
+ return isSilent ? "bg-red-500 hover:bg-red-600 text-white" : "bg-green-500 hover:bg-green-600 text-white";
740
+ }
741
+ if (state === "processing") {
742
+ return "bg-blue-500 text-white";
743
+ }
744
+ return "bg-gray-200 hover:bg-gray-300 text-gray-700 dark:bg-gray-700 dark:hover:bg-gray-600 dark:text-gray-200";
745
+ }
746
+ function VoiceMicButton({
747
+ isRecording,
748
+ isTranscribing,
749
+ audioLevel,
750
+ isSilent,
751
+ recordingTime,
752
+ onStart,
753
+ onStop,
754
+ className = ""
755
+ }) {
756
+ const state = deriveState(isRecording, isTranscribing);
757
+ const isDisabled = isTranscribing && !isRecording;
758
+ const handleClick = () => {
759
+ if (isRecording) {
760
+ onStop();
761
+ } else if (!isTranscribing) {
762
+ onStart();
763
+ }
764
+ };
765
+ const icon = isTranscribing ? Loader23 : isRecording ? Square : Mic;
766
+ const iconColor = state === "idle" ? "text-gray-700 dark:text-gray-200" : "text-white";
767
+ return /* @__PURE__ */ jsxs9("div", { className: `relative inline-flex items-center gap-3 ${className}`, children: [
768
+ /* @__PURE__ */ jsxs9("div", { className: "relative", children: [
769
+ isRecording && /* @__PURE__ */ jsx12(
770
+ PulseRings,
771
+ {
772
+ style: "vad",
773
+ audioLevel,
774
+ isSilent
775
+ }
776
+ ),
777
+ /* @__PURE__ */ jsx12(
778
+ motion4.div,
779
+ {
780
+ animate: {
781
+ scale: isRecording && !isSilent ? [1, 1.05, 1] : 1
782
+ },
783
+ transition: {
784
+ duration: 0.6,
785
+ repeat: isRecording && !isSilent ? Infinity : 0,
786
+ ease: "easeInOut"
787
+ },
788
+ children: /* @__PURE__ */ jsx12(
789
+ RecordingButton,
790
+ {
791
+ size: "md",
792
+ bgColor: getButtonColor(state, isSilent),
793
+ icon,
794
+ iconSpin: isTranscribing && !isRecording,
795
+ iconColor,
796
+ disabled: isDisabled,
797
+ onClick: handleClick,
798
+ ariaLabel: isRecording ? "Detener grabaci\xF3n" : "Iniciar grabaci\xF3n de voz",
799
+ className: "relative z-10"
800
+ }
801
+ )
802
+ }
803
+ )
804
+ ] }),
805
+ isRecording && /* @__PURE__ */ jsx12(
806
+ motion4.div,
807
+ {
808
+ initial: { opacity: 0, x: -10 },
809
+ animate: { opacity: 1, x: 0 },
810
+ exit: { opacity: 0, x: -10 },
811
+ children: /* @__PURE__ */ jsx12(
812
+ RecordingTimer,
813
+ {
814
+ time: recordingTime,
815
+ size: "sm",
816
+ showDot: true,
817
+ textColor: "text-gray-700 dark:text-gray-300"
818
+ }
819
+ )
820
+ }
821
+ ),
822
+ isTranscribing && !isRecording && /* @__PURE__ */ jsx12(
823
+ motion4.div,
824
+ {
825
+ initial: { opacity: 0 },
826
+ animate: { opacity: 1 },
827
+ className: "text-sm text-blue-600 dark:fi-text-primary font-medium",
828
+ children: "Transcribiendo..."
829
+ }
830
+ )
831
+ ] });
832
+ }
833
+
834
+ // src/voice/SpeakButton.tsx
835
+ import { Volume2, Loader2 as Loader24, Play } from "lucide-react";
836
+ import { jsx as jsx13 } from "react/jsx-runtime";
837
+ var ICON_SIZE = { xs: "w-3 h-3", sm: "w-3.5 h-3.5", md: "w-4 h-4" };
838
+ var PAD_SIZE = { xs: "p-1", sm: "p-1.5", md: "p-2" };
839
+ function formatVoiceName(voiceId) {
840
+ const match = voiceId.match(/([A-Z][a-z]+)Neural$/);
841
+ if (match) return match[1];
842
+ return voiceId.charAt(0).toUpperCase() + voiceId.slice(1);
843
+ }
844
+ function SpeakButton({
845
+ content,
846
+ voice = "nova",
847
+ isUserMessage = false,
848
+ onOpenPlayer,
849
+ busy = false,
850
+ cached = false,
851
+ size = "sm",
852
+ className,
853
+ iconClassName,
854
+ title,
855
+ busyTitle = "Generando audio\u2026",
856
+ cachedTitle = "Reproducir (ya generado)"
857
+ }) {
858
+ const voiceDisplay = formatVoiceName(voice);
859
+ const icon = iconClassName ?? ICON_SIZE[size];
860
+ const label = busy ? busyTitle : cached ? cachedTitle : title ?? `Escuchar (${voiceDisplay})`;
861
+ return /* @__PURE__ */ jsx13(
862
+ "button",
863
+ {
864
+ type: "button",
865
+ onClick: () => {
866
+ if (!busy) onOpenPlayer(content, voice, isUserMessage);
867
+ },
868
+ disabled: busy,
869
+ "aria-busy": busy,
870
+ className: className ?? PAD_SIZE[size],
871
+ title: label,
872
+ "aria-label": busy ? busyTitle : cached ? cachedTitle : `Escuchar mensaje con voz ${voiceDisplay}`,
873
+ children: busy ? /* @__PURE__ */ jsx13(Loader24, { className: `${icon} animate-spin` }) : cached ? /* @__PURE__ */ jsx13(Play, { className: icon }) : /* @__PURE__ */ jsx13(Volume2, { className: icon })
874
+ }
875
+ );
876
+ }
877
+
878
+ // src/voice/createAudioPlayer.ts
879
+ function clampSeekTarget(seconds, duration) {
880
+ if (!Number.isFinite(seconds)) return 0;
881
+ const lowerBounded = Math.max(0, seconds);
882
+ if (Number.isFinite(duration) && duration > 0) {
883
+ return Math.min(lowerBounded, duration);
884
+ }
885
+ return lowerBounded;
886
+ }
887
+ var INITIAL = {
888
+ status: "idle",
889
+ isPlaying: false,
890
+ isLoading: false,
891
+ error: null,
892
+ currentSrc: null,
893
+ duration: 0,
894
+ currentTime: 0
895
+ };
896
+ function defaultCreateElement() {
897
+ if (typeof Audio === "undefined") {
898
+ throw new Error(
899
+ "createAudioPlayer: no Audio constructor available. Run in a browser, or inject `createElement` for non-DOM environments/tests."
900
+ );
901
+ }
902
+ return new Audio();
903
+ }
904
+ function isBlob(source) {
905
+ return typeof Blob !== "undefined" && source instanceof Blob;
906
+ }
907
+ function createAudioPlayer(options = {}) {
908
+ const {
909
+ createElement = defaultCreateElement,
910
+ createObjectURL = (blob) => URL.createObjectURL(blob),
911
+ revokeObjectURL = (url) => URL.revokeObjectURL(url),
912
+ onError,
913
+ onEnded
914
+ } = options;
915
+ let state = { ...INITIAL };
916
+ let el = null;
917
+ let ownedUrl = null;
918
+ let disposed = false;
919
+ const listeners = /* @__PURE__ */ new Set();
920
+ function emit() {
921
+ for (const l of listeners) l();
922
+ }
923
+ function setState(patch) {
924
+ state = { ...state, ...patch };
925
+ emit();
926
+ }
927
+ const onLoadedMetadata = () => {
928
+ setState({
929
+ isLoading: false,
930
+ duration: Number.isFinite(el?.duration) ? el.duration : 0
931
+ });
932
+ };
933
+ const onTimeUpdate = () => {
934
+ if (el) setState({ currentTime: el.currentTime });
935
+ };
936
+ const onPlaying = () => {
937
+ setState({ status: "playing", isPlaying: true, isLoading: false, error: null });
938
+ };
939
+ const onPause = () => {
940
+ if (state.status !== "idle" && state.status !== "error") {
941
+ setState({ status: "paused", isPlaying: false });
942
+ }
943
+ };
944
+ const onEndedEvt = () => {
945
+ setState({ status: "idle", isPlaying: false, currentTime: 0 });
946
+ onEnded?.();
947
+ };
948
+ const onErrorEvt = () => {
949
+ const err = new Error("audio element error");
950
+ setState({ status: "error", isPlaying: false, isLoading: false, error: err });
951
+ onError?.(err, "audioPlayer:element");
952
+ };
953
+ function ensureElement() {
954
+ if (el) return el;
955
+ el = createElement();
956
+ el.addEventListener("loadedmetadata", onLoadedMetadata);
957
+ el.addEventListener("timeupdate", onTimeUpdate);
958
+ el.addEventListener("playing", onPlaying);
959
+ el.addEventListener("play", onPlaying);
960
+ el.addEventListener("pause", onPause);
961
+ el.addEventListener("ended", onEndedEvt);
962
+ el.addEventListener("error", onErrorEvt);
963
+ return el;
964
+ }
965
+ function releaseOwnedUrl() {
966
+ if (ownedUrl) {
967
+ revokeObjectURL(ownedUrl);
968
+ ownedUrl = null;
969
+ }
970
+ }
971
+ function load(source) {
972
+ if (disposed) return;
973
+ const element = ensureElement();
974
+ releaseOwnedUrl();
975
+ let url;
976
+ if (isBlob(source)) {
977
+ url = createObjectURL(source);
978
+ ownedUrl = url;
979
+ } else {
980
+ url = source.url;
981
+ }
982
+ element.src = url;
983
+ element.load();
984
+ setState({
985
+ status: "loading",
986
+ isLoading: true,
987
+ isPlaying: false,
988
+ error: null,
989
+ currentSrc: url,
990
+ currentTime: 0,
991
+ duration: 0
992
+ });
993
+ }
994
+ async function play() {
995
+ if (disposed || !el) return;
996
+ try {
997
+ await el.play();
998
+ setState({ status: "playing", isPlaying: true, error: null });
999
+ } catch (error) {
1000
+ setState({
1001
+ status: "error",
1002
+ isPlaying: false,
1003
+ error: error instanceof Error ? error : new Error(String(error))
1004
+ });
1005
+ onError?.(error, "audioPlayer:play");
1006
+ }
1007
+ }
1008
+ function pause() {
1009
+ if (disposed || !el) return;
1010
+ el.pause();
1011
+ setState({ status: "paused", isPlaying: false });
1012
+ }
1013
+ function stop() {
1014
+ if (disposed || !el) return;
1015
+ el.pause();
1016
+ el.currentTime = 0;
1017
+ el.src = "";
1018
+ releaseOwnedUrl();
1019
+ setState({
1020
+ status: "idle",
1021
+ isPlaying: false,
1022
+ isLoading: false,
1023
+ currentSrc: null,
1024
+ currentTime: 0
1025
+ });
1026
+ }
1027
+ async function toggle() {
1028
+ if (state.isPlaying) {
1029
+ pause();
1030
+ return;
1031
+ }
1032
+ await play();
1033
+ }
1034
+ function seek(seconds) {
1035
+ if (disposed || !el) return;
1036
+ const target = clampSeekTarget(seconds, state.duration);
1037
+ el.currentTime = target;
1038
+ setState({ currentTime: target });
1039
+ }
1040
+ function seekBy(deltaSeconds) {
1041
+ if (disposed || !el) return;
1042
+ const base = Number.isFinite(el.currentTime) ? el.currentTime : state.currentTime;
1043
+ seek(base + deltaSeconds);
1044
+ }
1045
+ function dispose() {
1046
+ if (disposed) return;
1047
+ disposed = true;
1048
+ if (el) {
1049
+ el.pause();
1050
+ el.removeEventListener("loadedmetadata", onLoadedMetadata);
1051
+ el.removeEventListener("timeupdate", onTimeUpdate);
1052
+ el.removeEventListener("playing", onPlaying);
1053
+ el.removeEventListener("play", onPlaying);
1054
+ el.removeEventListener("pause", onPause);
1055
+ el.removeEventListener("ended", onEndedEvt);
1056
+ el.removeEventListener("error", onErrorEvt);
1057
+ }
1058
+ releaseOwnedUrl();
1059
+ listeners.clear();
1060
+ }
1061
+ return {
1062
+ getState: () => state,
1063
+ subscribe(listener) {
1064
+ listeners.add(listener);
1065
+ return () => listeners.delete(listener);
1066
+ },
1067
+ load,
1068
+ play,
1069
+ pause,
1070
+ stop,
1071
+ toggle,
1072
+ seek,
1073
+ seekBy,
1074
+ dispose
1075
+ };
1076
+ }
1077
+
1078
+ // src/voice/useAudioPlayer.ts
1079
+ import { useEffect as useEffect3, useMemo, useRef as useRef3, useSyncExternalStore } from "react";
1080
+ function useAudioPlayer(opts = {}) {
1081
+ const cbRef = useRef3(opts);
1082
+ cbRef.current = opts;
1083
+ const controller = useMemo(
1084
+ () => createAudioPlayer({
1085
+ onError: (e, ctx) => cbRef.current.onError?.(e, ctx),
1086
+ onEnded: () => cbRef.current.onEnded?.(),
1087
+ ...opts.deps
1088
+ }),
1089
+ // One controller for the component's lifetime; deps are read once by design.
1090
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1091
+ []
1092
+ );
1093
+ useEffect3(() => () => controller.dispose(), [controller]);
1094
+ const state = useSyncExternalStore(
1095
+ controller.subscribe,
1096
+ controller.getState,
1097
+ controller.getState
1098
+ );
1099
+ return {
1100
+ ...state,
1101
+ load: controller.load,
1102
+ play: controller.play,
1103
+ pause: controller.pause,
1104
+ stop: controller.stop,
1105
+ toggle: controller.toggle,
1106
+ seek: controller.seek,
1107
+ seekBy: controller.seekBy,
1108
+ playSource: async (source) => {
1109
+ controller.load(source);
1110
+ await controller.play();
1111
+ }
1112
+ };
1113
+ }
1114
+
1115
+ // src/voice/AudioPlayer.tsx
1116
+ import { Play as Play2, Pause, Square as Square2, Loader2 as Loader25, AlertCircle } from "lucide-react";
1117
+ import { useEffect as useEffect4 } from "react";
1118
+ import { jsx as jsx14, jsxs as jsxs10 } from "react/jsx-runtime";
1119
+ var ICON = "w-4 h-4";
1120
+ var BTN = "p-2 disabled:opacity-40";
1121
+ function AudioPlayer({
1122
+ source,
1123
+ autoPlay = false,
1124
+ onError,
1125
+ onEnded,
1126
+ className,
1127
+ buttonClassName,
1128
+ iconClassName
1129
+ }) {
1130
+ const player = useAudioPlayer({ onError, onEnded });
1131
+ const { load, play, toggle, stop, isPlaying, isLoading, error, currentSrc } = player;
1132
+ useEffect4(() => {
1133
+ if (!source) return;
1134
+ load(source);
1135
+ if (autoPlay) void play();
1136
+ }, [source, autoPlay]);
1137
+ const hasSource = currentSrc !== null;
1138
+ const btnClass = buttonClassName ?? BTN;
1139
+ const iconClass = iconClassName ?? ICON;
1140
+ return /* @__PURE__ */ jsxs10("div", { className, "data-fi-audio-player": "", children: [
1141
+ /* @__PURE__ */ jsx14(
1142
+ "button",
1143
+ {
1144
+ type: "button",
1145
+ onClick: () => void toggle(),
1146
+ disabled: !hasSource || isLoading,
1147
+ "aria-pressed": isPlaying,
1148
+ "aria-label": isPlaying ? "Pausar audio" : "Reproducir audio",
1149
+ className: btnClass,
1150
+ children: isLoading ? /* @__PURE__ */ jsx14(Loader25, { className: `${iconClass} animate-spin`, "aria-hidden": true }) : isPlaying ? /* @__PURE__ */ jsx14(Pause, { className: iconClass, "aria-hidden": true }) : /* @__PURE__ */ jsx14(Play2, { className: iconClass, "aria-hidden": true })
1151
+ }
1152
+ ),
1153
+ /* @__PURE__ */ jsx14(
1154
+ "button",
1155
+ {
1156
+ type: "button",
1157
+ onClick: stop,
1158
+ disabled: !hasSource,
1159
+ "aria-label": "Detener audio",
1160
+ className: btnClass,
1161
+ children: /* @__PURE__ */ jsx14(Square2, { className: iconClass, "aria-hidden": true })
1162
+ }
1163
+ ),
1164
+ error ? /* @__PURE__ */ jsxs10("span", { role: "alert", className: "inline-flex items-center gap-1 text-xs", children: [
1165
+ /* @__PURE__ */ jsx14(AlertCircle, { className: iconClass, "aria-hidden": true }),
1166
+ "Error de audio"
1167
+ ] }) : null
1168
+ ] });
1169
+ }
1170
+
1171
+ // src/voice/RichAudioPlayer.tsx
1172
+ import {
1173
+ Play as Play3,
1174
+ Pause as Pause2,
1175
+ Square as Square3,
1176
+ Loader2 as Loader26,
1177
+ AlertCircle as AlertCircle2,
1178
+ RotateCcw,
1179
+ RotateCw
1180
+ } from "lucide-react";
1181
+ import { useEffect as useEffect5 } from "react";
1182
+ import { jsx as jsx15, jsxs as jsxs11 } from "react/jsx-runtime";
1183
+ var ICON2 = "w-4 h-4";
1184
+ var BTN2 = "p-2 disabled:opacity-40";
1185
+ function formatPlaybackTime(seconds) {
1186
+ if (!Number.isFinite(seconds) || seconds < 0) seconds = 0;
1187
+ const total = Math.floor(seconds);
1188
+ const h = Math.floor(total / 3600);
1189
+ const m = Math.floor(total % 3600 / 60);
1190
+ const s = total % 60;
1191
+ const ss = String(s).padStart(2, "0");
1192
+ if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${ss}`;
1193
+ return `${m}:${ss}`;
1194
+ }
1195
+ function RichAudioPlayer({
1196
+ source,
1197
+ autoPlay = false,
1198
+ skipSeconds = 10,
1199
+ showTime = true,
1200
+ onError,
1201
+ onEnded,
1202
+ className,
1203
+ buttonClassName,
1204
+ iconClassName,
1205
+ progressClassName
1206
+ }) {
1207
+ const player = useAudioPlayer({ onError, onEnded });
1208
+ const {
1209
+ load,
1210
+ play,
1211
+ toggle,
1212
+ stop,
1213
+ seek,
1214
+ seekBy,
1215
+ isPlaying,
1216
+ isLoading,
1217
+ error,
1218
+ currentSrc,
1219
+ duration,
1220
+ currentTime
1221
+ } = player;
1222
+ useEffect5(() => {
1223
+ if (!source) return;
1224
+ load(source);
1225
+ if (autoPlay) void play();
1226
+ }, [source, autoPlay]);
1227
+ const hasSource = currentSrc !== null;
1228
+ const canSeek = hasSource && duration > 0;
1229
+ const btnClass = buttonClassName ?? BTN2;
1230
+ const iconClass = iconClassName ?? ICON2;
1231
+ const positionLabel = `${formatPlaybackTime(currentTime)} / ${formatPlaybackTime(
1232
+ duration
1233
+ )}`;
1234
+ return /* @__PURE__ */ jsxs11(
1235
+ "div",
1236
+ {
1237
+ className,
1238
+ "data-fi-audio-player": "rich",
1239
+ role: "group",
1240
+ "aria-label": "Controles de reproducci\xF3n de audio",
1241
+ children: [
1242
+ /* @__PURE__ */ jsx15(
1243
+ "button",
1244
+ {
1245
+ type: "button",
1246
+ onClick: () => seekBy(-skipSeconds),
1247
+ disabled: !canSeek,
1248
+ "aria-label": `Retroceder ${skipSeconds} segundos`,
1249
+ className: btnClass,
1250
+ children: /* @__PURE__ */ jsx15(RotateCcw, { className: iconClass, "aria-hidden": true })
1251
+ }
1252
+ ),
1253
+ /* @__PURE__ */ jsx15(
1254
+ "button",
1255
+ {
1256
+ type: "button",
1257
+ onClick: () => void toggle(),
1258
+ disabled: !hasSource || isLoading,
1259
+ "aria-pressed": isPlaying,
1260
+ "aria-label": isPlaying ? "Pausar audio" : "Reproducir audio",
1261
+ className: btnClass,
1262
+ children: isLoading ? /* @__PURE__ */ jsx15(Loader26, { className: `${iconClass} animate-spin`, "aria-hidden": true }) : isPlaying ? /* @__PURE__ */ jsx15(Pause2, { className: iconClass, "aria-hidden": true }) : /* @__PURE__ */ jsx15(Play3, { className: iconClass, "aria-hidden": true })
1263
+ }
1264
+ ),
1265
+ /* @__PURE__ */ jsx15(
1266
+ "button",
1267
+ {
1268
+ type: "button",
1269
+ onClick: stop,
1270
+ disabled: !hasSource,
1271
+ "aria-label": "Detener audio",
1272
+ className: btnClass,
1273
+ children: /* @__PURE__ */ jsx15(Square3, { className: iconClass, "aria-hidden": true })
1274
+ }
1275
+ ),
1276
+ /* @__PURE__ */ jsx15(
1277
+ "button",
1278
+ {
1279
+ type: "button",
1280
+ onClick: () => seekBy(skipSeconds),
1281
+ disabled: !canSeek,
1282
+ "aria-label": `Avanzar ${skipSeconds} segundos`,
1283
+ className: btnClass,
1284
+ children: /* @__PURE__ */ jsx15(RotateCw, { className: iconClass, "aria-hidden": true })
1285
+ }
1286
+ ),
1287
+ /* @__PURE__ */ jsx15(
1288
+ "input",
1289
+ {
1290
+ type: "range",
1291
+ min: 0,
1292
+ max: duration > 0 ? duration : 0,
1293
+ step: 0.1,
1294
+ value: Math.min(currentTime, duration > 0 ? duration : currentTime),
1295
+ onChange: (e) => seek(Number(e.target.value)),
1296
+ disabled: !canSeek,
1297
+ "aria-label": "Progreso de reproducci\xF3n",
1298
+ "aria-valuetext": positionLabel,
1299
+ className: progressClassName,
1300
+ "data-fi-audio-progress": ""
1301
+ }
1302
+ ),
1303
+ showTime ? /* @__PURE__ */ jsx15("span", { "data-fi-audio-time": "", "aria-hidden": true, className: "text-xs tabular-nums", children: positionLabel }) : null,
1304
+ error ? /* @__PURE__ */ jsxs11("span", { role: "alert", className: "inline-flex items-center gap-1 text-xs", children: [
1305
+ /* @__PURE__ */ jsx15(AlertCircle2, { className: iconClass, "aria-hidden": true }),
1306
+ "Error de audio"
1307
+ ] }) : null
1308
+ ]
1309
+ }
1310
+ );
1311
+ }
1312
+
1313
+ // src/voice/AudioVisualizer.tsx
1314
+ import { jsx as jsx16 } from "react/jsx-runtime";
1315
+ var MIN_BAR_PCT = 4;
1316
+ function normalizeLevels(levels) {
1317
+ return levels.map(
1318
+ (v) => !Number.isFinite(v) ? 0 : v < 0 ? 0 : v > 1 ? 1 : v
1319
+ );
1320
+ }
1321
+ function resampleLevels(levels, count) {
1322
+ if (count <= 0) return [];
1323
+ if (levels.length === 0) return new Array(count).fill(0);
1324
+ if (levels.length === count) return levels.slice();
1325
+ const out = [];
1326
+ for (let i = 0; i < count; i++) {
1327
+ const idx = Math.min(
1328
+ levels.length - 1,
1329
+ Math.floor(i / count * levels.length)
1330
+ );
1331
+ out.push(levels[idx]);
1332
+ }
1333
+ return out;
1334
+ }
1335
+ function AudioVisualizer({
1336
+ levels,
1337
+ variant = "bars",
1338
+ active = true,
1339
+ barCount,
1340
+ label = "Visualizador de nivel de audio",
1341
+ className,
1342
+ barClassName,
1343
+ color
1344
+ }) {
1345
+ const normalized = normalizeLevels(levels);
1346
+ if (variant === "pulse") {
1347
+ const peak = active && normalized.length ? Math.max(...normalized) : 0;
1348
+ const scale = 1 + peak;
1349
+ return /* @__PURE__ */ jsx16(
1350
+ "div",
1351
+ {
1352
+ role: "img",
1353
+ "aria-label": label,
1354
+ className,
1355
+ "data-fi-audio-visualizer": "pulse",
1356
+ "data-active": active ? "" : void 0,
1357
+ children: /* @__PURE__ */ jsx16(
1358
+ "span",
1359
+ {
1360
+ "data-fi-pulse-core": "",
1361
+ style: {
1362
+ display: "inline-block",
1363
+ transform: `scale(${scale})`,
1364
+ borderColor: color
1365
+ }
1366
+ }
1367
+ )
1368
+ }
1369
+ );
1370
+ }
1371
+ const count = barCount && barCount > 0 ? barCount : normalized.length;
1372
+ const bars = resampleLevels(normalized, count);
1373
+ return /* @__PURE__ */ jsx16(
1374
+ "div",
1375
+ {
1376
+ role: "img",
1377
+ "aria-label": label,
1378
+ className,
1379
+ "data-fi-audio-visualizer": "bars",
1380
+ "data-active": active ? "" : void 0,
1381
+ style: { display: "inline-flex", alignItems: "flex-end" },
1382
+ children: bars.map((level, i) => {
1383
+ const pct = active ? Math.max(MIN_BAR_PCT, level * 100) : MIN_BAR_PCT;
1384
+ return /* @__PURE__ */ jsx16(
1385
+ "span",
1386
+ {
1387
+ "data-fi-audio-bar": "",
1388
+ className: barClassName,
1389
+ style: { height: `${pct}%`, backgroundColor: color }
1390
+ },
1391
+ i
1392
+ );
1393
+ })
1394
+ }
1395
+ );
1396
+ }
1397
+
1398
+ // src/voice/ComposerMicSlot.tsx
1399
+ import { Mic as Mic2, MicOff, Square as Square4, Loader2 as Loader27 } from "lucide-react";
1400
+ import { jsx as jsx17 } from "react/jsx-runtime";
1401
+ var ICON3 = "w-4 h-4";
1402
+ var BTN3 = "p-2 disabled:opacity-40";
1403
+ function ComposerMicSlot({
1404
+ available = false,
1405
+ recording = false,
1406
+ busy = false,
1407
+ onStart,
1408
+ onStop,
1409
+ unavailableLabel = "Dictado por voz no disponible todav\xEDa",
1410
+ startLabel = "Iniciar dictado por voz",
1411
+ stopLabel = "Detener dictado por voz",
1412
+ busyLabel = "Transcribiendo\u2026",
1413
+ className,
1414
+ buttonClassName,
1415
+ iconClassName
1416
+ }) {
1417
+ const btnClass = buttonClassName ?? BTN3;
1418
+ const iconClass = iconClassName ?? ICON3;
1419
+ const disabled = !available || busy;
1420
+ const label = !available ? unavailableLabel : busy ? busyLabel : recording ? stopLabel : startLabel;
1421
+ const handleClick = () => {
1422
+ if (disabled) return;
1423
+ if (recording) onStop?.();
1424
+ else onStart?.();
1425
+ };
1426
+ const Icon = !available ? MicOff : busy ? Loader27 : recording ? Square4 : Mic2;
1427
+ return /* @__PURE__ */ jsx17("div", { className, "data-fi-mic-slot": "", "data-available": available ? "" : void 0, children: /* @__PURE__ */ jsx17(
1428
+ "button",
1429
+ {
1430
+ type: "button",
1431
+ onClick: handleClick,
1432
+ disabled,
1433
+ "aria-disabled": disabled,
1434
+ "aria-pressed": available ? recording : void 0,
1435
+ "aria-label": label,
1436
+ title: !available ? unavailableLabel : void 0,
1437
+ className: btnClass,
1438
+ children: /* @__PURE__ */ jsx17(
1439
+ Icon,
1440
+ {
1441
+ className: busy ? `${iconClass} animate-spin` : iconClass,
1442
+ "aria-hidden": true
1443
+ }
1444
+ )
1445
+ }
1446
+ ) });
1447
+ }
1448
+
1449
+ // src/voice/useVoice.ts
1450
+ import { useCallback as useCallback2, useRef as useRef4, useState as useState4 } from "react";
1451
+ function toUrl(src) {
1452
+ return src instanceof Blob ? URL.createObjectURL(src) : src.url;
1453
+ }
1454
+ var TTS_CACHE_MAX_CLIPS = 8;
1455
+ var clipKey = (text, voice) => `${voice}\0${text}`;
1456
+ function useVoice(adapter, opts = {}) {
1457
+ const { onError } = opts;
1458
+ const [isOpen, setIsOpen] = useState4(false);
1459
+ const [isLoading, setIsLoading] = useState4(false);
1460
+ const [audioUrl, setAudioUrl] = useState4(null);
1461
+ const [voiceName, setVoiceName] = useState4("nova");
1462
+ const [isUserMessage, setIsUserMessage] = useState4(false);
1463
+ const [currentVoice, setCurrentVoice] = useState4("nova");
1464
+ const [currentText, setCurrentText] = useState4("");
1465
+ const inFlight = useRef4(false);
1466
+ const clipCache = useRef4(/* @__PURE__ */ new Map());
1467
+ const synthesizeCached = useCallback2(
1468
+ async (text, voice) => {
1469
+ const cache = clipCache.current;
1470
+ const key = clipKey(text, voice);
1471
+ const hit = cache.get(key);
1472
+ if (hit) {
1473
+ cache.delete(key);
1474
+ cache.set(key, hit);
1475
+ return hit;
1476
+ }
1477
+ const src = await adapter.synthesize(text, voice);
1478
+ if (src instanceof Blob && src.size > 0) {
1479
+ cache.set(key, src);
1480
+ while (cache.size > TTS_CACHE_MAX_CLIPS) {
1481
+ const oldest = cache.keys().next().value;
1482
+ if (oldest === void 0) break;
1483
+ cache.delete(oldest);
1484
+ }
1485
+ }
1486
+ return src;
1487
+ },
1488
+ [adapter]
1489
+ );
1490
+ const getVoiceDisplayName = useCallback2(
1491
+ (voiceId) => {
1492
+ const found = adapter?.availableVoices?.find((v) => v.id === voiceId);
1493
+ if (found) return found.label.split(" ")[0];
1494
+ const match = voiceId.match(/([A-Z][a-z]+)Neural$/);
1495
+ return match ? match[1] : voiceId;
1496
+ },
1497
+ [adapter]
1498
+ );
1499
+ const generateAudio = useCallback2(
1500
+ async (text, voice = "nova", isUser = false) => {
1501
+ if (!adapter?.synthesize) return;
1502
+ if (inFlight.current) return;
1503
+ inFlight.current = true;
1504
+ setCurrentText(text);
1505
+ setCurrentVoice(voice);
1506
+ setIsUserMessage(isUser);
1507
+ setVoiceName(getVoiceDisplayName(voice));
1508
+ setIsOpen(true);
1509
+ setAudioUrl((prev) => {
1510
+ if (prev?.startsWith("blob:")) URL.revokeObjectURL(prev);
1511
+ return null;
1512
+ });
1513
+ const isHit = clipCache.current.has(clipKey(text, voice));
1514
+ if (!isHit) setIsLoading(true);
1515
+ try {
1516
+ const src = await synthesizeCached(text, voice);
1517
+ setAudioUrl(toUrl(src));
1518
+ } catch (error) {
1519
+ onError?.(error, "useVoice:TTS");
1520
+ setIsOpen(false);
1521
+ } finally {
1522
+ inFlight.current = false;
1523
+ setIsLoading(false);
1524
+ }
1525
+ },
1526
+ [adapter, getVoiceDisplayName, onError, synthesizeCached]
1527
+ );
1528
+ const changeVoice = useCallback2(
1529
+ async (newVoice) => {
1530
+ if (!currentText || !adapter?.synthesize) return;
1531
+ if (inFlight.current) return;
1532
+ inFlight.current = true;
1533
+ setCurrentVoice(newVoice);
1534
+ setVoiceName(getVoiceDisplayName(newVoice));
1535
+ setIsLoading(true);
1536
+ if (audioUrl) URL.revokeObjectURL(audioUrl);
1537
+ setAudioUrl(null);
1538
+ try {
1539
+ const src = await synthesizeCached(currentText, newVoice);
1540
+ setAudioUrl(toUrl(src));
1541
+ } catch (error) {
1542
+ onError?.(error, "useVoice:VoiceChange");
1543
+ } finally {
1544
+ inFlight.current = false;
1545
+ setIsLoading(false);
1546
+ }
1547
+ },
1548
+ [adapter, audioUrl, currentText, getVoiceDisplayName, onError, synthesizeCached]
1549
+ );
1550
+ const close = useCallback2(() => {
1551
+ setIsOpen(false);
1552
+ setAudioUrl(null);
1553
+ setIsLoading(false);
1554
+ setCurrentText("");
1555
+ setIsUserMessage(false);
1556
+ }, []);
1557
+ const hasCachedAudio = useCallback2(
1558
+ (text, voice = "nova") => clipCache.current.has(clipKey(text, voice)),
1559
+ []
1560
+ );
1561
+ return {
1562
+ isOpen,
1563
+ isLoading,
1564
+ audioUrl,
1565
+ voiceName,
1566
+ isUserMessage,
1567
+ currentVoice,
1568
+ currentText,
1569
+ generateAudio,
1570
+ changeVoice,
1571
+ close,
1572
+ hasCachedAudio
1573
+ };
1574
+ }
1575
+
1576
+ // src/voice/useDictation.ts
1577
+ import { useCallback as useCallback4, useState as useState7 } from "react";
1578
+
1579
+ // src/voice/useRecorder.ts
1580
+ import { useState as useState5, useRef as useRef5, useCallback as useCallback3 } from "react";
1581
+
1582
+ // src/voice/makeRecorder.ts
1583
+ async function makeRecorder(stream, onChunk, opts) {
1584
+ const timeSlice = opts?.timeSlice;
1585
+ const channels = opts?.channels ?? 1;
1586
+ const mod = await import("recordrtc");
1587
+ const RecordRTC = mod.default ?? mod;
1588
+ if (!RecordRTC) {
1589
+ throw new Error("[makeRecorder] RecordRTC library not available");
1590
+ }
1591
+ const mimeType = "audio/wav";
1592
+ let currentRecorder = null;
1593
+ let loopTimer = null;
1594
+ let isActive = false;
1595
+ const createRecorder = () => {
1596
+ return new RecordRTC(stream, {
1597
+ type: "audio",
1598
+ recorderType: RecordRTC.StereoAudioRecorder,
1599
+ mimeType,
1600
+ numberOfAudioChannels: channels,
1601
+ desiredSampRate: opts?.sampleRate ?? 16e3,
1602
+ disableLogs: true
1603
+ });
1604
+ };
1605
+ const startLoop = async () => {
1606
+ if (!isActive) return;
1607
+ currentRecorder = createRecorder();
1608
+ currentRecorder.startRecording();
1609
+ if (timeSlice && timeSlice > 0) {
1610
+ loopTimer = setTimeout(async () => {
1611
+ if (!currentRecorder || !isActive) return;
1612
+ currentRecorder.stopRecording(() => {
1613
+ if (!isActive) return;
1614
+ const blob = currentRecorder.getBlob();
1615
+ if (blob && blob.size > 0) {
1616
+ onChunk(blob);
1617
+ }
1618
+ if (isActive) {
1619
+ startLoop();
1620
+ }
1621
+ });
1622
+ }, timeSlice);
1623
+ }
1624
+ };
1625
+ return {
1626
+ start: () => {
1627
+ isActive = true;
1628
+ startLoop();
1629
+ },
1630
+ stop: () => new Promise((resolve) => {
1631
+ isActive = false;
1632
+ if (loopTimer) {
1633
+ clearTimeout(loopTimer);
1634
+ loopTimer = null;
1635
+ }
1636
+ if (currentRecorder) {
1637
+ currentRecorder.stopRecording(() => {
1638
+ const finalBlob = currentRecorder.getBlob();
1639
+ resolve(finalBlob);
1640
+ });
1641
+ } else {
1642
+ resolve(new Blob([], { type: mimeType }));
1643
+ }
1644
+ }),
1645
+ kind: "recordrtc"
1646
+ };
1647
+ }
1648
+
1649
+ // src/voice/useRecorder.ts
1650
+ var log = {
1651
+ error: (_m, _meta) => {
1652
+ void _m;
1653
+ void _meta;
1654
+ },
1655
+ warn: (_m, _meta) => {
1656
+ void _m;
1657
+ void _meta;
1658
+ }
1659
+ };
1660
+ function useRecorder(config) {
1661
+ const {
1662
+ onChunk,
1663
+ onError,
1664
+ timeSlice = 3e3,
1665
+ sampleRate = 16e3,
1666
+ channels = 1,
1667
+ externalStream = null,
1668
+ deviceId = null
1669
+ } = config;
1670
+ const [isRecording, setIsRecording] = useState5(false);
1671
+ const [recordingTime, setRecordingTime] = useState5(0);
1672
+ const [fullAudioBlob, setFullAudioBlob] = useState5(null);
1673
+ const [fullAudioUrl, setFullAudioUrl] = useState5(null);
1674
+ const [currentStream, setCurrentStream] = useState5(null);
1675
+ const recorderRef = useRef5(null);
1676
+ const continuousRecorderRef = useRef5(null);
1677
+ const currentStreamRef = useRef5(null);
1678
+ const recordingTimerRef = useRef5(null);
1679
+ const fullAudioUrlRef = useRef5(null);
1680
+ const chunkNumberRef = useRef5(0);
1681
+ const startRecording = useCallback3(async () => {
1682
+ try {
1683
+ chunkNumberRef.current = 0;
1684
+ setRecordingTime(0);
1685
+ setFullAudioBlob(null);
1686
+ if (fullAudioUrlRef.current) {
1687
+ URL.revokeObjectURL(fullAudioUrlRef.current);
1688
+ fullAudioUrlRef.current = null;
1689
+ setFullAudioUrl(null);
1690
+ }
1691
+ let stream;
1692
+ if (externalStream) {
1693
+ stream = externalStream;
1694
+ } else {
1695
+ try {
1696
+ const timeoutMs = 15e3;
1697
+ const timeoutPromise = new Promise((_, reject) => {
1698
+ setTimeout(() => {
1699
+ reject(new Error(
1700
+ "Microphone permission timeout (15s). Check: 1) macOS System Preferences \u2192 Privacy \u2192 Microphone has your browser enabled, 2) Restart browser after granting permission"
1701
+ ));
1702
+ }, timeoutMs);
1703
+ });
1704
+ const audioConstraints = deviceId ? { deviceId: { exact: deviceId } } : true;
1705
+ stream = await Promise.race([
1706
+ navigator.mediaDevices.getUserMedia({ audio: audioConstraints }),
1707
+ timeoutPromise
1708
+ ]);
1709
+ } catch (micError) {
1710
+ log.error("Microphone access failed", { error: String(micError) });
1711
+ throw micError;
1712
+ }
1713
+ }
1714
+ currentStreamRef.current = stream;
1715
+ setCurrentStream(stream);
1716
+ const chunkedRecorder = await makeRecorder(
1717
+ stream,
1718
+ async (blob) => {
1719
+ const chunkNumber = chunkNumberRef.current++;
1720
+ await onChunk(blob, chunkNumber);
1721
+ },
1722
+ {
1723
+ timeSlice,
1724
+ sampleRate,
1725
+ channels
1726
+ }
1727
+ );
1728
+ recorderRef.current = chunkedRecorder;
1729
+ chunkedRecorder.start();
1730
+ const continuousRecorder = await makeRecorder(
1731
+ stream,
1732
+ () => {
1733
+ },
1734
+ // Empty callback - blob comes from .stop() return value
1735
+ {
1736
+ // NO timeSlice = records continuously until stop()
1737
+ sampleRate,
1738
+ channels
1739
+ }
1740
+ );
1741
+ continuousRecorderRef.current = continuousRecorder;
1742
+ continuousRecorder.start();
1743
+ setIsRecording(true);
1744
+ recordingTimerRef.current = setInterval(() => {
1745
+ setRecordingTime((prev) => prev + 1);
1746
+ }, 1e3);
1747
+ } catch (err) {
1748
+ const errorMessage = err instanceof Error ? err.message : "No se pudo acceder al micr\xF3fono. Por favor, verifica los permisos.";
1749
+ log.error("Start failed", { error: String(err) });
1750
+ if (onError) {
1751
+ onError(errorMessage);
1752
+ }
1753
+ }
1754
+ }, [onChunk, onError, timeSlice, sampleRate, channels, externalStream, deviceId]);
1755
+ const stopRecording = useCallback3(async () => {
1756
+ try {
1757
+ if (recordingTimerRef.current) {
1758
+ clearInterval(recordingTimerRef.current);
1759
+ recordingTimerRef.current = null;
1760
+ }
1761
+ setIsRecording(false);
1762
+ if (currentStreamRef.current) {
1763
+ currentStreamRef.current.getTracks().forEach((track) => {
1764
+ track.stop();
1765
+ });
1766
+ currentStreamRef.current = null;
1767
+ setCurrentStream(null);
1768
+ }
1769
+ let fullBlob = null;
1770
+ if (continuousRecorderRef.current) {
1771
+ try {
1772
+ fullBlob = await continuousRecorderRef.current.stop();
1773
+ if (fullBlob && fullBlob.size > 0) {
1774
+ if (fullAudioUrlRef.current) {
1775
+ URL.revokeObjectURL(fullAudioUrlRef.current);
1776
+ }
1777
+ const audioUrl = URL.createObjectURL(fullBlob);
1778
+ fullAudioUrlRef.current = audioUrl;
1779
+ setFullAudioUrl(audioUrl);
1780
+ setFullAudioBlob(fullBlob);
1781
+ }
1782
+ } catch (err) {
1783
+ log.warn("Continuous recorder stop error (non-critical)", { error: String(err) });
1784
+ }
1785
+ continuousRecorderRef.current = null;
1786
+ }
1787
+ if (recorderRef.current) {
1788
+ try {
1789
+ const lastChunk = await recorderRef.current.stop();
1790
+ if (lastChunk && lastChunk.size > 0) {
1791
+ const finalChunkNumber = chunkNumberRef.current++;
1792
+ try {
1793
+ const result = onChunk(lastChunk, finalChunkNumber);
1794
+ if (result instanceof Promise) {
1795
+ result.catch((err) => {
1796
+ log.error("Final chunk processing failed", { error: String(err) });
1797
+ });
1798
+ }
1799
+ } catch (err) {
1800
+ log.error("Final chunk processing failed", { error: String(err) });
1801
+ }
1802
+ }
1803
+ } catch (err) {
1804
+ log.warn("Chunked recorder stop error (non-critical)", { error: String(err) });
1805
+ }
1806
+ recorderRef.current = null;
1807
+ }
1808
+ return fullBlob;
1809
+ } catch (err) {
1810
+ log.error("Stop failed", { error: String(err) });
1811
+ if (currentStreamRef.current) {
1812
+ currentStreamRef.current.getTracks().forEach((track) => track.stop());
1813
+ currentStreamRef.current = null;
1814
+ setCurrentStream(null);
1815
+ }
1816
+ setIsRecording(false);
1817
+ if (onError) {
1818
+ onError(err instanceof Error ? err.message : "Error al detener grabaci\xF3n");
1819
+ }
1820
+ return null;
1821
+ }
1822
+ }, [onChunk, onError]);
1823
+ return {
1824
+ isRecording,
1825
+ recordingTime,
1826
+ currentStream,
1827
+ fullAudioBlob,
1828
+ fullAudioUrl,
1829
+ startRecording,
1830
+ stopRecording
1831
+ };
1832
+ }
1833
+
1834
+ // src/voice/useAudioAnalysis.ts
1835
+ import { useState as useState6, useRef as useRef6, useEffect as useEffect6 } from "react";
1836
+ var AUDIO_CONFIG = { SILENCE_THRESHOLD: 2, AUDIO_GAIN: 2.5 };
1837
+ function frequencyDataToBands(data, bandCount, gain) {
1838
+ if (bandCount <= 0 || data.length === 0) return new Array(Math.max(0, bandCount)).fill(0);
1839
+ const usable = Math.floor(data.length * 0.75) || data.length;
1840
+ const sliceSize = Math.max(1, Math.floor(usable / bandCount));
1841
+ const bands = new Array(bandCount);
1842
+ for (let b = 0; b < bandCount; b++) {
1843
+ const start = b * sliceSize;
1844
+ let sum = 0;
1845
+ let n = 0;
1846
+ for (let i = start; i < start + sliceSize && i < usable; i++) {
1847
+ sum += data[i];
1848
+ n++;
1849
+ }
1850
+ const avg = n ? sum / n : 0;
1851
+ const scaled = avg / 255 * gain;
1852
+ bands[b] = scaled > 1 ? 1 : scaled < 0 ? 0 : scaled;
1853
+ }
1854
+ return bands;
1855
+ }
1856
+ function useAudioAnalysis(stream, config) {
1857
+ const {
1858
+ silenceThreshold = AUDIO_CONFIG.SILENCE_THRESHOLD,
1859
+ gain = AUDIO_CONFIG.AUDIO_GAIN,
1860
+ isActive,
1861
+ bandCount = 24
1862
+ } = config;
1863
+ const [audioLevel, setAudioLevel] = useState6(0);
1864
+ const [bands, setBands] = useState6([]);
1865
+ const analyserRef = useRef6(null);
1866
+ const audioContextRef = useRef6(null);
1867
+ const animationFrameRef = useRef6(null);
1868
+ const isSilent = audioLevel < silenceThreshold;
1869
+ useEffect6(() => {
1870
+ if (!stream || !isActive) {
1871
+ setAudioLevel(0);
1872
+ setBands([]);
1873
+ return;
1874
+ }
1875
+ const audioContext = new AudioContext();
1876
+ const analyser = audioContext.createAnalyser();
1877
+ const gainNode = audioContext.createGain();
1878
+ const source = audioContext.createMediaStreamSource(stream);
1879
+ gainNode.gain.value = gain;
1880
+ analyser.fftSize = 256;
1881
+ analyser.smoothingTimeConstant = 0.8;
1882
+ source.connect(gainNode);
1883
+ gainNode.connect(analyser);
1884
+ audioContextRef.current = audioContext;
1885
+ analyserRef.current = analyser;
1886
+ const dataArray = new Uint8Array(analyser.frequencyBinCount);
1887
+ const updateLevel = () => {
1888
+ if (!analyserRef.current) return;
1889
+ analyserRef.current.getByteFrequencyData(dataArray);
1890
+ const average = dataArray.reduce((a, b) => a + b, 0) / dataArray.length;
1891
+ setAudioLevel(average);
1892
+ setBands(frequencyDataToBands(dataArray, bandCount, gain));
1893
+ animationFrameRef.current = requestAnimationFrame(updateLevel);
1894
+ };
1895
+ updateLevel();
1896
+ return () => {
1897
+ if (animationFrameRef.current) {
1898
+ cancelAnimationFrame(animationFrameRef.current);
1899
+ }
1900
+ if (audioContextRef.current) {
1901
+ audioContextRef.current.close();
1902
+ }
1903
+ };
1904
+ }, [stream, isActive, gain, silenceThreshold, bandCount]);
1905
+ return { audioLevel, isSilent, bands };
1906
+ }
1907
+
1908
+ // src/voice/useDictation.ts
1909
+ function useDictation(adapter, opts = {}) {
1910
+ const { timeSliceMs = 3e4, deviceId = null, onTranscriptUpdate, onError } = opts;
1911
+ const [liveTranscript, setLiveTranscript] = useState7("");
1912
+ const [isTranscribing, setIsTranscribing] = useState7(false);
1913
+ const handleChunk = useCallback4(
1914
+ async (blob, chunkNumber) => {
1915
+ if (!adapter?.transcribe) return;
1916
+ setIsTranscribing(true);
1917
+ try {
1918
+ const { text } = await adapter.transcribe(blob, { index: chunkNumber });
1919
+ if (text) {
1920
+ setLiveTranscript((prev) => {
1921
+ const updated = prev ? `${prev} ${text}` : text;
1922
+ onTranscriptUpdate?.(updated);
1923
+ return updated;
1924
+ });
1925
+ }
1926
+ } catch (err) {
1927
+ onError?.(err instanceof Error ? err.message : "transcription failed");
1928
+ } finally {
1929
+ setIsTranscribing(false);
1930
+ }
1931
+ },
1932
+ [adapter, onTranscriptUpdate, onError]
1933
+ );
1934
+ const { isRecording, recordingTime, currentStream, startRecording, stopRecording } = useRecorder({
1935
+ onChunk: handleChunk,
1936
+ onError,
1937
+ timeSlice: timeSliceMs,
1938
+ deviceId
1939
+ });
1940
+ const { audioLevel, isSilent, bands } = useAudioAnalysis(currentStream, {
1941
+ isActive: isRecording
1942
+ });
1943
+ const start = useCallback4(async () => {
1944
+ setLiveTranscript("");
1945
+ await startRecording();
1946
+ }, [startRecording]);
1947
+ const stop = useCallback4(async () => {
1948
+ await stopRecording();
1949
+ }, [stopRecording]);
1950
+ return {
1951
+ isRecording,
1952
+ recordingTime,
1953
+ audioLevel,
1954
+ isSilent,
1955
+ bands,
1956
+ liveTranscript,
1957
+ isTranscribing,
1958
+ startRecording: start,
1959
+ stopRecording: stop
1960
+ };
1961
+ }
1962
+
1963
+ // src/voice/audioArtifact.ts
1964
+ var AUDIO_QUEUE_DEFAULTS = {
1965
+ maxItems: 10,
1966
+ maxBytes: 50 * 1024 * 1024,
1967
+ // 50 MB total queue
1968
+ maxBytesPerItem: 10 * 1024 * 1024
1969
+ // 10 MB per artifact
1970
+ };
1971
+ function makeArtifactId() {
1972
+ return `audio-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
1973
+ }
1974
+ function isPending(a) {
1975
+ return a.state !== "transcribed" && a.state !== "archived" && a.state !== "deleted";
1976
+ }
1977
+ function isTerminal(a) {
1978
+ return a.state === "transcribed" || a.state === "archived" || a.state === "deleted";
1979
+ }
1980
+ function artifactLabel(state) {
1981
+ const map = {
1982
+ recording: "Grabando",
1983
+ paused: "En pausa",
1984
+ stopping: "Guardando...",
1985
+ saved: "Guardado",
1986
+ queued: "En cola",
1987
+ uploading: "Subiendo",
1988
+ transcribing: "Transcribiendo",
1989
+ transcribed: "Transcrito",
1990
+ archived: "Enviado",
1991
+ failed: "Fall\xF3",
1992
+ deleted: "Eliminado"
1993
+ };
1994
+ return map[state];
1995
+ }
1996
+ function formatArtifactSize(bytes) {
1997
+ if (bytes < 1024) return `${bytes} B`;
1998
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
1999
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2000
+ }
2001
+ function formatArtifactDuration(ms) {
2002
+ if (!ms) return "--:--";
2003
+ const s = Math.floor(ms / 1e3);
2004
+ const m = Math.floor(s / 60);
2005
+ return `${String(m).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
2006
+ }
2007
+
2008
+ // src/voice/AudioQueueStore.ts
2009
+ var DEFAULT_DB_NAME = "free-intelligence-audio-queue";
2010
+ var DEFAULT_STORE_NAME = "audio-artifacts";
2011
+ var DB_VERSION = 1;
2012
+ var CREATED_AT_INDEX = "by_createdAt";
2013
+ function unavailable() {
2014
+ return typeof indexedDB === "undefined";
2015
+ }
2016
+ function unavailableError() {
2017
+ return new Error(
2018
+ "AudioQueueStore: IndexedDB is not available (SSR or storage disabled)."
2019
+ );
2020
+ }
2021
+ var AudioQueueStore = class {
2022
+ constructor(opts = {}) {
2023
+ this.dbPromise = null;
2024
+ this.dbName = opts.dbName ?? DEFAULT_DB_NAME;
2025
+ this.storeName = opts.storeName ?? DEFAULT_STORE_NAME;
2026
+ }
2027
+ open() {
2028
+ if (unavailable()) return Promise.reject(unavailableError());
2029
+ if (!this.dbPromise) {
2030
+ this.dbPromise = new Promise((resolve, reject) => {
2031
+ const req = indexedDB.open(this.dbName, DB_VERSION);
2032
+ req.onupgradeneeded = () => {
2033
+ const db = req.result;
2034
+ if (!db.objectStoreNames.contains(this.storeName)) {
2035
+ const store = db.createObjectStore(this.storeName, { keyPath: "id" });
2036
+ store.createIndex(CREATED_AT_INDEX, "createdAt", { unique: false });
2037
+ }
2038
+ };
2039
+ req.onsuccess = () => resolve(req.result);
2040
+ req.onerror = () => reject(req.error ?? new Error("AudioQueueStore: open failed"));
2041
+ });
2042
+ }
2043
+ return this.dbPromise;
2044
+ }
2045
+ async run(mode, makeRequest) {
2046
+ const db = await this.open();
2047
+ return new Promise((resolve, reject) => {
2048
+ const tx = db.transaction(this.storeName, mode);
2049
+ const req = makeRequest(tx.objectStore(this.storeName));
2050
+ req.onsuccess = () => resolve(req.result);
2051
+ req.onerror = () => reject(req.error ?? new Error("AudioQueueStore: request failed"));
2052
+ });
2053
+ }
2054
+ async list() {
2055
+ return this.run("readonly", (s) => s.getAll());
2056
+ }
2057
+ async get(id) {
2058
+ const r = await this.run(
2059
+ "readonly",
2060
+ (s) => s.get(id)
2061
+ );
2062
+ return r ?? null;
2063
+ }
2064
+ async put(artifact) {
2065
+ await this.run("readwrite", (s) => s.put(artifact));
2066
+ }
2067
+ async updateMeta(id, patch) {
2068
+ const existing = await this.get(id);
2069
+ if (!existing) return;
2070
+ await this.put({
2071
+ ...existing,
2072
+ ...patch,
2073
+ id,
2074
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2075
+ });
2076
+ }
2077
+ async delete(id) {
2078
+ await this.run("readwrite", (s) => s.delete(id));
2079
+ }
2080
+ async clear() {
2081
+ await this.run("readwrite", (s) => s.clear());
2082
+ }
2083
+ };
2084
+
2085
+ // src/voice/useDurableRecording.ts
2086
+ import { useState as useState8, useRef as useRef7, useCallback as useCallback5, useEffect as useEffect7 } from "react";
2087
+
2088
+ // src/voice/wav.ts
2089
+ function blobToArrayBuffer(blob) {
2090
+ if (typeof blob.arrayBuffer === "function") return blob.arrayBuffer();
2091
+ return new Promise((resolve, reject) => {
2092
+ const reader = new FileReader();
2093
+ reader.onload = () => resolve(reader.result);
2094
+ reader.onerror = () => reject(reader.error ?? new Error("FileReader failed"));
2095
+ reader.readAsArrayBuffer(blob);
2096
+ });
2097
+ }
2098
+ function readFourCC(view, offset) {
2099
+ return String.fromCharCode(
2100
+ view.getUint8(offset),
2101
+ view.getUint8(offset + 1),
2102
+ view.getUint8(offset + 2),
2103
+ view.getUint8(offset + 3)
2104
+ );
2105
+ }
2106
+ function parseWav(buffer) {
2107
+ const view = new DataView(buffer);
2108
+ if (buffer.byteLength < 44 || readFourCC(view, 0) !== "RIFF" || readFourCC(view, 8) !== "WAVE") {
2109
+ throw new Error("Not a RIFF/WAVE file");
2110
+ }
2111
+ let fmt = null;
2112
+ let data = null;
2113
+ let offset = 12;
2114
+ while (offset + 8 <= buffer.byteLength) {
2115
+ const id = readFourCC(view, offset);
2116
+ const size = view.getUint32(offset + 4, true);
2117
+ const body = offset + 8;
2118
+ if (id === "fmt ") {
2119
+ fmt = {
2120
+ audioFormat: view.getUint16(body, true),
2121
+ numChannels: view.getUint16(body + 2, true),
2122
+ sampleRate: view.getUint32(body + 4, true),
2123
+ bitsPerSample: view.getUint16(body + 14, true)
2124
+ };
2125
+ } else if (id === "data") {
2126
+ const end = Math.min(body + size, buffer.byteLength);
2127
+ data = new Uint8Array(buffer.slice(body, end));
2128
+ }
2129
+ offset = body + size + size % 2;
2130
+ }
2131
+ if (!fmt || !data) throw new Error("WAV missing fmt or data chunk");
2132
+ return { ...fmt, data };
2133
+ }
2134
+ function buildWav(fmt, pcm) {
2135
+ const header = new ArrayBuffer(44);
2136
+ const view = new DataView(header);
2137
+ const byteRate = fmt.sampleRate * fmt.numChannels * fmt.bitsPerSample / 8;
2138
+ const blockAlign = fmt.numChannels * fmt.bitsPerSample / 8;
2139
+ const writeFourCC = (offset, s) => {
2140
+ for (let i = 0; i < 4; i++) view.setUint8(offset + i, s.charCodeAt(i));
2141
+ };
2142
+ writeFourCC(0, "RIFF");
2143
+ view.setUint32(4, 36 + pcm.byteLength, true);
2144
+ writeFourCC(8, "WAVE");
2145
+ writeFourCC(12, "fmt ");
2146
+ view.setUint32(16, 16, true);
2147
+ view.setUint16(20, fmt.audioFormat, true);
2148
+ view.setUint16(22, fmt.numChannels, true);
2149
+ view.setUint32(24, fmt.sampleRate, true);
2150
+ view.setUint32(28, byteRate, true);
2151
+ view.setUint16(32, blockAlign, true);
2152
+ view.setUint16(34, fmt.bitsPerSample, true);
2153
+ writeFourCC(36, "data");
2154
+ view.setUint32(40, pcm.byteLength, true);
2155
+ return new Blob([header, pcm.buffer], { type: "audio/wav" });
2156
+ }
2157
+ async function mergeWavBlobs(blobs) {
2158
+ if (blobs.length === 0) throw new Error("No WAV segments to merge");
2159
+ if (blobs.length === 1) return blobs[0];
2160
+ const parsed = await Promise.all(
2161
+ blobs.map(async (b) => parseWav(await blobToArrayBuffer(b)))
2162
+ );
2163
+ const first = parsed[0];
2164
+ for (const p of parsed.slice(1)) {
2165
+ if (p.audioFormat !== first.audioFormat || p.numChannels !== first.numChannels || p.sampleRate !== first.sampleRate || p.bitsPerSample !== first.bitsPerSample) {
2166
+ throw new Error("WAV segments have mismatched formats");
2167
+ }
2168
+ }
2169
+ const total = parsed.reduce((s, p) => s + p.data.byteLength, 0);
2170
+ const pcm = new Uint8Array(total);
2171
+ let cursor = 0;
2172
+ for (const p of parsed) {
2173
+ pcm.set(p.data, cursor);
2174
+ cursor += p.data.byteLength;
2175
+ }
2176
+ return buildWav(first, pcm);
2177
+ }
2178
+
2179
+ // src/voice/useDurableRecording.ts
2180
+ var MIC_TIMEOUT_MS = 15e3;
2181
+ async function loadRecordRTC() {
2182
+ const mod = await import("recordrtc");
2183
+ const RTC = mod.default ?? mod.RecordRTC ?? mod;
2184
+ if (!RTC || typeof RTC !== "function") {
2185
+ throw new Error("[useDurableRecording] RecordRTC not available");
2186
+ }
2187
+ return RTC;
2188
+ }
2189
+ function useDurableRecording(opts) {
2190
+ const {
2191
+ store,
2192
+ policy = AUDIO_QUEUE_DEFAULTS,
2193
+ deviceId = null,
2194
+ onSaved,
2195
+ onError
2196
+ } = opts;
2197
+ const [artifact, setArtifact] = useState8(null);
2198
+ const [recordingTime, setRecordingTime] = useState8(0);
2199
+ const [currentStream, setCurrentStream] = useState8(null);
2200
+ const [isAtCapacity, setIsAtCapacity] = useState8(false);
2201
+ const [isStarting, setIsStarting] = useState8(false);
2202
+ const [pausedPreviewBlob, setPausedPreviewBlob] = useState8(null);
2203
+ const recorderRef = useRef7(null);
2204
+ const streamRef = useRef7(null);
2205
+ const timerRef = useRef7(null);
2206
+ const startTimeRef = useRef7(0);
2207
+ const pausedElapsedRef = useRef7(0);
2208
+ const artifactRef = useRef7(null);
2209
+ const segmentsRef = useRef7([]);
2210
+ const rtcCtorRef = useRef7(null);
2211
+ const pauseOpRef = useRef7(Promise.resolve());
2212
+ useEffect7(() => {
2213
+ artifactRef.current = artifact;
2214
+ }, [artifact]);
2215
+ useEffect7(() => {
2216
+ store.list().then((stored) => {
2217
+ const pending = stored.filter(isPending);
2218
+ const totalBytes = pending.reduce((s, a) => s + a.size, 0);
2219
+ setIsAtCapacity(
2220
+ pending.length >= policy.maxItems || totalBytes >= policy.maxBytes
2221
+ );
2222
+ }).catch(() => {
2223
+ });
2224
+ }, [store, policy]);
2225
+ const { audioLevel, isSilent, bands } = useAudioAnalysis(currentStream, {
2226
+ isActive: artifact?.state === "recording"
2227
+ });
2228
+ const stopTimer = useCallback5(() => {
2229
+ if (timerRef.current) {
2230
+ clearInterval(timerRef.current);
2231
+ timerRef.current = null;
2232
+ }
2233
+ }, []);
2234
+ const releaseStream = useCallback5(() => {
2235
+ if (streamRef.current) {
2236
+ streamRef.current.getTracks().forEach((t) => t.stop());
2237
+ streamRef.current = null;
2238
+ setCurrentStream(null);
2239
+ }
2240
+ }, []);
2241
+ const updateArtifact = useCallback5(
2242
+ (patch) => {
2243
+ const prev = artifactRef.current;
2244
+ if (!prev) return;
2245
+ const updated = { ...prev, ...patch, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
2246
+ artifactRef.current = updated;
2247
+ setArtifact(updated);
2248
+ },
2249
+ []
2250
+ );
2251
+ const startNewRecorderSegment = useCallback5((stream) => {
2252
+ const RecordRTC = rtcCtorRef.current;
2253
+ if (!RecordRTC) throw new Error("[useDurableRecording] RecordRTC not loaded");
2254
+ const recorder = new RecordRTC(stream, {
2255
+ type: "audio",
2256
+ recorderType: RecordRTC.StereoAudioRecorder,
2257
+ mimeType: "audio/wav",
2258
+ numberOfAudioChannels: 1,
2259
+ desiredSampRate: 16e3,
2260
+ disableLogs: true
2261
+ });
2262
+ recorder.startRecording();
2263
+ return recorder;
2264
+ }, []);
2265
+ const startRecording = useCallback5(async () => {
2266
+ if (artifact?.state === "recording" || artifact?.state === "paused") return;
2267
+ setIsStarting(true);
2268
+ try {
2269
+ const stored = await store.list();
2270
+ const pending = stored.filter(isPending);
2271
+ const totalBytes = pending.reduce((s, a) => s + a.size, 0);
2272
+ if (pending.length >= policy.maxItems || totalBytes >= policy.maxBytes) {
2273
+ setIsAtCapacity(true);
2274
+ onError?.(
2275
+ `Cola llena (m\xE1ximo ${policy.maxItems} audios o ${Math.round(policy.maxBytes / 1024 / 1024)} MB). Transcribe o elimina audios antes de grabar.`
2276
+ );
2277
+ return;
2278
+ }
2279
+ const timeoutPromise = new Promise(
2280
+ (_, reject) => setTimeout(
2281
+ () => reject(new Error("Permiso de micr\xF3fono expirado (15s).")),
2282
+ MIC_TIMEOUT_MS
2283
+ )
2284
+ );
2285
+ const audioConstraints = deviceId ? { deviceId: { exact: deviceId } } : true;
2286
+ const stream = await Promise.race([
2287
+ navigator.mediaDevices.getUserMedia({ audio: audioConstraints }),
2288
+ timeoutPromise
2289
+ ]);
2290
+ streamRef.current = stream;
2291
+ setCurrentStream(stream);
2292
+ rtcCtorRef.current = await loadRecordRTC();
2293
+ segmentsRef.current = [];
2294
+ pauseOpRef.current = Promise.resolve();
2295
+ setPausedPreviewBlob(null);
2296
+ recorderRef.current = startNewRecorderSegment(stream);
2297
+ const now = Date.now();
2298
+ startTimeRef.current = now;
2299
+ pausedElapsedRef.current = 0;
2300
+ setRecordingTime(0);
2301
+ timerRef.current = setInterval(() => {
2302
+ setRecordingTime(
2303
+ Math.floor((Date.now() - startTimeRef.current) / 1e3)
2304
+ );
2305
+ }, 1e3);
2306
+ const newArtifact = {
2307
+ id: makeArtifactId(),
2308
+ mime: "audio/wav",
2309
+ size: 0,
2310
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2311
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2312
+ state: "recording"
2313
+ };
2314
+ setArtifact(newArtifact);
2315
+ artifactRef.current = newArtifact;
2316
+ } catch (err) {
2317
+ releaseStream();
2318
+ onError?.(err instanceof Error ? err.message : "No se pudo iniciar la grabaci\xF3n.");
2319
+ } finally {
2320
+ setIsStarting(false);
2321
+ }
2322
+ }, [artifact, store, policy, deviceId, onError, releaseStream, startNewRecorderSegment]);
2323
+ const pauseRecording = useCallback5(() => {
2324
+ if (artifactRef.current?.state !== "recording") return;
2325
+ stopTimer();
2326
+ pausedElapsedRef.current = Date.now() - startTimeRef.current;
2327
+ updateArtifact({ state: "paused", durationMs: pausedElapsedRef.current });
2328
+ const recorder = recorderRef.current;
2329
+ recorderRef.current = null;
2330
+ pauseOpRef.current = new Promise((resolve) => {
2331
+ if (!recorder) {
2332
+ resolve();
2333
+ return;
2334
+ }
2335
+ recorder.stopRecording(() => {
2336
+ const segment = recorder.getBlob();
2337
+ if (segment && segment.size > 0) segmentsRef.current.push(segment);
2338
+ const totalBytes = segmentsRef.current.reduce((s, b) => s + b.size, 0);
2339
+ if (totalBytes > policy.maxBytesPerItem) {
2340
+ resolve();
2341
+ return;
2342
+ }
2343
+ void mergeWavBlobs(segmentsRef.current).then((preview) => {
2344
+ if (artifactRef.current?.state === "paused") {
2345
+ setPausedPreviewBlob(preview);
2346
+ }
2347
+ }).catch(() => {
2348
+ }).finally(resolve);
2349
+ });
2350
+ });
2351
+ }, [stopTimer, updateArtifact, policy]);
2352
+ const resumeRecording = useCallback5(() => {
2353
+ if (artifactRef.current?.state !== "paused") return;
2354
+ setPausedPreviewBlob(null);
2355
+ startTimeRef.current = Date.now() - pausedElapsedRef.current;
2356
+ timerRef.current = setInterval(() => {
2357
+ setRecordingTime(
2358
+ Math.floor((Date.now() - startTimeRef.current) / 1e3)
2359
+ );
2360
+ }, 1e3);
2361
+ updateArtifact({ state: "recording" });
2362
+ void pauseOpRef.current.then(() => {
2363
+ if (artifactRef.current?.state !== "recording") return;
2364
+ const stream = streamRef.current;
2365
+ if (!stream) return;
2366
+ try {
2367
+ recorderRef.current = startNewRecorderSegment(stream);
2368
+ } catch (err) {
2369
+ updateArtifact({
2370
+ state: "failed",
2371
+ errorMessage: err instanceof Error ? err.message : "No se pudo reanudar la grabaci\xF3n."
2372
+ });
2373
+ }
2374
+ });
2375
+ }, [updateArtifact, startNewRecorderSegment]);
2376
+ const stopRecording = useCallback5(async () => {
2377
+ const current = artifactRef.current;
2378
+ if (current?.state !== "recording" && current?.state !== "paused") {
2379
+ return null;
2380
+ }
2381
+ stopTimer();
2382
+ const durationMs = current.state === "paused" ? pausedElapsedRef.current : Date.now() - startTimeRef.current;
2383
+ updateArtifact({ state: "stopping" });
2384
+ setPausedPreviewBlob(null);
2385
+ await pauseOpRef.current;
2386
+ const recorder = recorderRef.current;
2387
+ recorderRef.current = null;
2388
+ if (recorder) {
2389
+ await new Promise((resolve) => recorder.stopRecording(resolve));
2390
+ const segment = recorder.getBlob();
2391
+ if (segment && segment.size > 0) segmentsRef.current.push(segment);
2392
+ }
2393
+ releaseStream();
2394
+ const segments = segmentsRef.current;
2395
+ segmentsRef.current = [];
2396
+ let blob = null;
2397
+ if (segments.length > 0) {
2398
+ try {
2399
+ blob = await mergeWavBlobs(segments);
2400
+ } catch {
2401
+ blob = null;
2402
+ }
2403
+ }
2404
+ if (!blob || blob.size === 0) {
2405
+ updateArtifact({ state: "failed", errorMessage: "Grabaci\xF3n vac\xEDa." });
2406
+ return null;
2407
+ }
2408
+ if (blob.size > policy.maxBytesPerItem) {
2409
+ updateArtifact({
2410
+ state: "failed",
2411
+ errorMessage: `Audio demasiado grande (${Math.round(blob.size / 1024 / 1024)} MB, m\xE1ximo ${Math.round(policy.maxBytesPerItem / 1024 / 1024)} MB).`
2412
+ });
2413
+ return null;
2414
+ }
2415
+ const finalArtifact = {
2416
+ ...current,
2417
+ size: blob.size,
2418
+ durationMs,
2419
+ state: "queued",
2420
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2421
+ };
2422
+ updateArtifact({
2423
+ size: blob.size,
2424
+ durationMs,
2425
+ state: "queued"
2426
+ });
2427
+ try {
2428
+ await store.put({ ...finalArtifact, blob });
2429
+ onSaved?.(finalArtifact);
2430
+ setIsAtCapacity(false);
2431
+ return finalArtifact;
2432
+ } catch (err) {
2433
+ const msg = err instanceof Error ? err.message : "Error al guardar audio.";
2434
+ updateArtifact({ state: "failed", errorMessage: msg });
2435
+ onError?.(msg);
2436
+ return null;
2437
+ }
2438
+ }, [store, policy, releaseStream, stopTimer, updateArtifact, onSaved, onError]);
2439
+ const cancelRecording = useCallback5(() => {
2440
+ stopTimer();
2441
+ releaseStream();
2442
+ if (recorderRef.current) {
2443
+ try {
2444
+ recorderRef.current.stopRecording(() => {
2445
+ });
2446
+ } catch {
2447
+ }
2448
+ recorderRef.current = null;
2449
+ }
2450
+ segmentsRef.current = [];
2451
+ setPausedPreviewBlob(null);
2452
+ setArtifact(null);
2453
+ artifactRef.current = null;
2454
+ setRecordingTime(0);
2455
+ }, [stopTimer, releaseStream]);
2456
+ return {
2457
+ artifact,
2458
+ recordingTime,
2459
+ pausedPreviewBlob,
2460
+ bands,
2461
+ audioLevel,
2462
+ isSilent,
2463
+ isStarting,
2464
+ startRecording,
2465
+ pauseRecording,
2466
+ resumeRecording,
2467
+ stopRecording,
2468
+ cancelRecording,
2469
+ isAtCapacity
2470
+ };
2471
+ }
2472
+
2473
+ // src/voice/useAudioQueue.ts
2474
+ import { useState as useState9, useEffect as useEffect8, useCallback as useCallback6 } from "react";
2475
+ function useAudioQueue(opts) {
2476
+ const { store, adapter, onTranscribed, onError } = opts;
2477
+ const [artifacts, setArtifacts] = useState9([]);
2478
+ const [isLoading, setIsLoading] = useState9(true);
2479
+ const loadFromStore = useCallback6(async () => {
2480
+ try {
2481
+ const stored = await store.list();
2482
+ const metas = stored.filter((a) => a.state !== "deleted").map(({ blob: _blob, ...meta }) => meta).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
2483
+ setArtifacts(metas);
2484
+ } catch {
2485
+ }
2486
+ setIsLoading(false);
2487
+ }, [store]);
2488
+ useEffect8(() => {
2489
+ loadFromStore();
2490
+ }, [loadFromStore]);
2491
+ const patchLocal = useCallback6(
2492
+ (id, patch) => {
2493
+ setArtifacts(
2494
+ (prev) => prev.map(
2495
+ (a) => a.id === id ? { ...a, ...patch, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } : a
2496
+ )
2497
+ );
2498
+ },
2499
+ []
2500
+ );
2501
+ const doTranscribe = useCallback6(
2502
+ async (id) => {
2503
+ if (!adapter?.transcribe) {
2504
+ onError?.(id, "Adaptador de voz sin capacidad de transcripci\xF3n.");
2505
+ return;
2506
+ }
2507
+ patchLocal(id, { state: "transcribing", errorMessage: void 0 });
2508
+ await store.updateMeta(id, { state: "transcribing", errorMessage: void 0 });
2509
+ const stored = await store.get(id);
2510
+ if (!stored) {
2511
+ patchLocal(id, { state: "failed", errorMessage: "Artefacto no encontrado." });
2512
+ onError?.(id, "Artefacto no encontrado.");
2513
+ return;
2514
+ }
2515
+ patchLocal(id, { state: "uploading" });
2516
+ await store.updateMeta(id, { state: "uploading" });
2517
+ try {
2518
+ const { text } = await adapter.transcribe(stored.blob);
2519
+ patchLocal(id, { state: "transcribed", transcript: text });
2520
+ await store.updateMeta(id, { state: "transcribed", transcript: text });
2521
+ onTranscribed?.(id, text);
2522
+ } catch (err) {
2523
+ const msg = err instanceof Error ? err.message : "Transcripci\xF3n fallida.";
2524
+ patchLocal(id, { state: "failed", errorMessage: msg });
2525
+ await store.updateMeta(id, { state: "failed", errorMessage: msg });
2526
+ onError?.(id, msg);
2527
+ }
2528
+ },
2529
+ [adapter, store, patchLocal, onTranscribed, onError]
2530
+ );
2531
+ const transcribeArtifact = useCallback6(
2532
+ async (id) => {
2533
+ const a = artifacts.find((x) => x.id === id);
2534
+ if (!a || a.state !== "queued" && a.state !== "saved") return;
2535
+ await doTranscribe(id);
2536
+ },
2537
+ [artifacts, doTranscribe]
2538
+ );
2539
+ const retryTranscription = useCallback6(
2540
+ async (id) => {
2541
+ const a = artifacts.find((x) => x.id === id);
2542
+ if (!a || a.state !== "failed") return;
2543
+ await doTranscribe(id);
2544
+ },
2545
+ [artifacts, doTranscribe]
2546
+ );
2547
+ const getPlaybackUrl = useCallback6(
2548
+ async (id) => {
2549
+ const stored = await store.get(id);
2550
+ if (!stored?.blob || stored.blob.size === 0) return null;
2551
+ return URL.createObjectURL(stored.blob);
2552
+ },
2553
+ [store]
2554
+ );
2555
+ const deleteArtifact = useCallback6(
2556
+ async (id) => {
2557
+ await store.delete(id);
2558
+ setArtifacts((prev) => prev.filter((a) => a.id !== id));
2559
+ },
2560
+ [store]
2561
+ );
2562
+ const archiveArtifact = useCallback6(
2563
+ async (id) => {
2564
+ const a = artifacts.find((x) => x.id === id);
2565
+ if (!a || a.state !== "transcribed") return;
2566
+ patchLocal(id, { state: "archived" });
2567
+ await store.updateMeta(id, { state: "archived" });
2568
+ },
2569
+ [artifacts, store, patchLocal]
2570
+ );
2571
+ const clearTranscribed = useCallback6(async () => {
2572
+ const used = (a) => a.state === "transcribed" || a.state === "archived";
2573
+ const toDelete = artifacts.filter(used);
2574
+ await Promise.all(toDelete.map((a) => store.delete(a.id)));
2575
+ setArtifacts((prev) => prev.filter((a) => !used(a)));
2576
+ }, [artifacts, store]);
2577
+ const reload = useCallback6(async () => {
2578
+ setIsLoading(true);
2579
+ await loadFromStore();
2580
+ }, [loadFromStore]);
2581
+ const totalBytes = artifacts.filter(isPending).reduce((s, a) => s + a.size, 0);
2582
+ return {
2583
+ artifacts,
2584
+ totalBytes,
2585
+ isLoading,
2586
+ transcribeArtifact,
2587
+ retryTranscription,
2588
+ getPlaybackUrl,
2589
+ deleteArtifact,
2590
+ archiveArtifact,
2591
+ clearTranscribed,
2592
+ reload
2593
+ };
2594
+ }
2595
+
2596
+ // src/voice/AudioQueuePanel.tsx
2597
+ import { useEffect as useEffect9, useState as useState11 } from "react";
2598
+ import { Loader2 as Loader29, Trash2 as Trash22, Info } from "lucide-react";
2599
+
2600
+ // src/voice/AudioQueueItem.tsx
2601
+ import { useState as useState10, useCallback as useCallback7 } from "react";
2602
+ import {
2603
+ Mic as Mic3,
2604
+ PauseCircle,
2605
+ CheckCircle2,
2606
+ CheckCheck,
2607
+ AlertCircle as AlertCircle3,
2608
+ Loader2 as Loader28,
2609
+ Play as Play4,
2610
+ RotateCcw as RotateCcw2,
2611
+ Trash2,
2612
+ FileAudio
2613
+ } from "lucide-react";
2614
+ import { jsx as jsx18, jsxs as jsxs12 } from "react/jsx-runtime";
2615
+ function StateIcon({ state }) {
2616
+ const base = "w-4 h-4 shrink-0";
2617
+ switch (state) {
2618
+ case "recording":
2619
+ return /* @__PURE__ */ jsx18(Mic3, { className: `${base} text-red-400 animate-pulse` });
2620
+ case "paused":
2621
+ return /* @__PURE__ */ jsx18(PauseCircle, { className: `${base} text-yellow-400` });
2622
+ case "stopping":
2623
+ return /* @__PURE__ */ jsx18(Loader28, { className: `${base} text-amber-400 animate-spin` });
2624
+ case "transcribed":
2625
+ return /* @__PURE__ */ jsx18(CheckCircle2, { className: `${base} text-green-400` });
2626
+ case "failed":
2627
+ return /* @__PURE__ */ jsx18(AlertCircle3, { className: `${base} text-red-400` });
2628
+ case "transcribing":
2629
+ case "uploading":
2630
+ return /* @__PURE__ */ jsx18(Loader28, { className: `${base} text-blue-400 animate-spin` });
2631
+ default:
2632
+ return /* @__PURE__ */ jsx18(FileAudio, { className: `${base} text-gray-400` });
2633
+ }
2634
+ }
2635
+ function AudioQueueItem({
2636
+ artifact,
2637
+ onTranscribe,
2638
+ onRetry,
2639
+ onDelete,
2640
+ onArchive,
2641
+ onGetPlaybackUrl,
2642
+ className = ""
2643
+ }) {
2644
+ const [playing, setPlaying] = useState10(false);
2645
+ const [audioEl, setAudioEl] = useState10(null);
2646
+ const handlePlay = useCallback7(async () => {
2647
+ if (!onGetPlaybackUrl) return;
2648
+ if (playing && audioEl) {
2649
+ audioEl.pause();
2650
+ setPlaying(false);
2651
+ return;
2652
+ }
2653
+ const url = await onGetPlaybackUrl(artifact.id);
2654
+ if (!url) return;
2655
+ const el = new Audio(url);
2656
+ setAudioEl(el);
2657
+ setPlaying(true);
2658
+ el.play().catch(() => setPlaying(false));
2659
+ el.addEventListener("ended", () => {
2660
+ setPlaying(false);
2661
+ URL.revokeObjectURL(url);
2662
+ });
2663
+ el.addEventListener("error", () => {
2664
+ setPlaying(false);
2665
+ URL.revokeObjectURL(url);
2666
+ });
2667
+ }, [artifact.id, onGetPlaybackUrl, playing, audioEl]);
2668
+ const canTranscribe = artifact.state === "queued" || artifact.state === "saved";
2669
+ const canRetry = artifact.state === "failed";
2670
+ const canPlay = !!onGetPlaybackUrl && artifact.size > 0 && artifact.state !== "recording" && artifact.state !== "paused";
2671
+ const isBusy = artifact.state === "transcribing" || artifact.state === "uploading";
2672
+ return /* @__PURE__ */ jsxs12(
2673
+ "div",
2674
+ {
2675
+ className: `flex items-start gap-3 p-3 rounded-lg bg-white/5 border border-white/10 ${className}`,
2676
+ children: [
2677
+ /* @__PURE__ */ jsx18(StateIcon, { state: artifact.state }),
2678
+ /* @__PURE__ */ jsxs12("div", { className: "flex-1 min-w-0 space-y-0.5", children: [
2679
+ /* @__PURE__ */ jsxs12("div", { className: "flex items-center gap-2 text-xs", children: [
2680
+ /* @__PURE__ */ jsx18("span", { className: "font-medium text-white/80", children: artifactLabel(artifact.state) }),
2681
+ /* @__PURE__ */ jsx18("span", { className: "text-white/40", children: "\xB7" }),
2682
+ /* @__PURE__ */ jsx18("span", { className: "text-white/50", children: formatArtifactDuration(artifact.durationMs) }),
2683
+ /* @__PURE__ */ jsx18("span", { className: "text-white/40", children: "\xB7" }),
2684
+ /* @__PURE__ */ jsx18("span", { className: "text-white/50", children: formatArtifactSize(artifact.size) })
2685
+ ] }),
2686
+ artifact.state === "transcribed" && artifact.transcript && /* @__PURE__ */ jsx18("p", { className: "text-xs text-white/60 truncate", children: artifact.transcript }),
2687
+ artifact.state === "failed" && artifact.errorMessage && /* @__PURE__ */ jsx18("p", { className: "text-xs text-red-400/80 truncate", children: artifact.errorMessage }),
2688
+ /* @__PURE__ */ jsx18("p", { className: "text-[10px] text-white/30", children: new Date(artifact.createdAt).toLocaleString("es-MX", {
2689
+ hour: "2-digit",
2690
+ minute: "2-digit",
2691
+ day: "numeric",
2692
+ month: "short"
2693
+ }) })
2694
+ ] }),
2695
+ /* @__PURE__ */ jsxs12("div", { className: "flex items-center gap-1 shrink-0", children: [
2696
+ canPlay && /* @__PURE__ */ jsx18(
2697
+ "button",
2698
+ {
2699
+ onClick: handlePlay,
2700
+ disabled: isBusy,
2701
+ className: "p-1.5 rounded-md hover:bg-white/10 text-white/50 hover:text-white/80 transition-colors",
2702
+ "aria-label": playing ? "Pausar" : "Reproducir",
2703
+ children: /* @__PURE__ */ jsx18(Play4, { className: "w-3.5 h-3.5" })
2704
+ }
2705
+ ),
2706
+ canTranscribe && onTranscribe && /* @__PURE__ */ jsx18(
2707
+ "button",
2708
+ {
2709
+ onClick: () => onTranscribe(artifact.id),
2710
+ disabled: isBusy,
2711
+ className: "px-2 py-1 rounded-md text-xs bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 transition-colors",
2712
+ children: "Transcribir"
2713
+ }
2714
+ ),
2715
+ canRetry && onRetry && /* @__PURE__ */ jsx18(
2716
+ "button",
2717
+ {
2718
+ onClick: () => onRetry(artifact.id),
2719
+ className: "p-1.5 rounded-md hover:bg-white/10 text-yellow-400/70 hover:text-yellow-400 transition-colors",
2720
+ "aria-label": "Reintentar transcripci\xF3n",
2721
+ children: /* @__PURE__ */ jsx18(RotateCcw2, { className: "w-3.5 h-3.5" })
2722
+ }
2723
+ ),
2724
+ artifact.state === "transcribed" && onArchive && /* @__PURE__ */ jsx18(
2725
+ "button",
2726
+ {
2727
+ onClick: () => onArchive(artifact.id),
2728
+ className: "fi-audio-item-archive p-1.5 rounded-md hover:bg-white/10 text-emerald-400/60 hover:text-emerald-400 transition-colors",
2729
+ "aria-label": "Marcar como enviado al chat",
2730
+ title: "Marcar como enviado al chat",
2731
+ children: /* @__PURE__ */ jsx18(CheckCheck, { className: "w-3.5 h-3.5" })
2732
+ }
2733
+ ),
2734
+ onDelete && artifact.state !== "recording" && artifact.state !== "paused" && /* @__PURE__ */ jsx18(
2735
+ "button",
2736
+ {
2737
+ onClick: () => onDelete(artifact.id),
2738
+ disabled: isBusy,
2739
+ className: "p-1.5 rounded-md hover:bg-white/10 text-white/30 hover:text-red-400 transition-colors",
2740
+ "aria-label": "Eliminar audio",
2741
+ children: /* @__PURE__ */ jsx18(Trash2, { className: "w-3.5 h-3.5" })
2742
+ }
2743
+ )
2744
+ ] })
2745
+ ]
2746
+ }
2747
+ );
2748
+ }
2749
+
2750
+ // src/voice/AudioQueuePanel.tsx
2751
+ import { jsx as jsx19, jsxs as jsxs13 } from "react/jsx-runtime";
2752
+ var DEFAULT_PRIVACY_NOTICE = "Tu audio se guarda localmente hasta que lo transcribas o elimines. No se env\xEDa al servidor hasta que lo solicites.";
2753
+ var DEFAULT_PRIVACY_NOTICE_MS = 35e3;
2754
+ function AudioQueuePanel({
2755
+ queue,
2756
+ className = "",
2757
+ privacyNotice = DEFAULT_PRIVACY_NOTICE,
2758
+ privacyNoticeMs = DEFAULT_PRIVACY_NOTICE_MS,
2759
+ maxVisible = 6,
2760
+ excludeIds = []
2761
+ }) {
2762
+ const {
2763
+ artifacts,
2764
+ isLoading,
2765
+ transcribeArtifact,
2766
+ retryTranscription,
2767
+ deleteArtifact,
2768
+ archiveArtifact,
2769
+ clearTranscribed,
2770
+ getPlaybackUrl
2771
+ } = queue;
2772
+ const [showNotice, setShowNotice] = useState11(true);
2773
+ useEffect9(() => {
2774
+ if (!privacyNoticeMs) return;
2775
+ const t = setTimeout(() => setShowNotice(false), privacyNoticeMs);
2776
+ return () => clearTimeout(t);
2777
+ }, [privacyNoticeMs]);
2778
+ const visible = artifacts.filter(
2779
+ (a) => a.state !== "deleted" && a.state !== "archived" && // used/sent — hidden, kept until cleared
2780
+ !excludeIds.includes(a.id)
2781
+ );
2782
+ const hasTranscribed = visible.some((a) => a.state === "transcribed");
2783
+ const visibleBytes = visible.reduce((s, a) => s + a.size, 0);
2784
+ if (isLoading) {
2785
+ return /* @__PURE__ */ jsx19("div", { className: `flex items-center justify-center p-4 ${className}`, children: /* @__PURE__ */ jsx19(Loader29, { className: "w-4 h-4 text-white/40 animate-spin" }) });
2786
+ }
2787
+ if (visible.length === 0) return null;
2788
+ return /* @__PURE__ */ jsxs13("div", { className: `space-y-2 ${className}`, children: [
2789
+ showNotice && /* @__PURE__ */ jsxs13("div", { className: "fi-audio-queue-notice flex items-start gap-2 px-3 py-2 rounded-lg bg-blue-500/10 border border-blue-500/20", children: [
2790
+ /* @__PURE__ */ jsx19(Info, { className: "w-3.5 h-3.5 text-blue-400 shrink-0 mt-0.5" }),
2791
+ /* @__PURE__ */ jsx19("p", { className: "text-[11px] text-blue-200/70 leading-relaxed", children: privacyNotice })
2792
+ ] }),
2793
+ /* @__PURE__ */ jsxs13("div", { className: "flex items-center justify-between px-1", children: [
2794
+ /* @__PURE__ */ jsxs13("span", { className: "text-xs text-white/50", children: [
2795
+ visible.length,
2796
+ " audio",
2797
+ visible.length !== 1 ? "s" : "",
2798
+ " \xB7 ",
2799
+ formatArtifactSize(visibleBytes)
2800
+ ] }),
2801
+ hasTranscribed && /* @__PURE__ */ jsxs13(
2802
+ "button",
2803
+ {
2804
+ onClick: clearTranscribed,
2805
+ className: "flex items-center gap-1 text-xs text-white/40 hover:text-white/70 transition-colors",
2806
+ children: [
2807
+ /* @__PURE__ */ jsx19(Trash22, { className: "w-3 h-3" }),
2808
+ "Limpiar transcritos"
2809
+ ]
2810
+ }
2811
+ )
2812
+ ] }),
2813
+ /* @__PURE__ */ jsx19(
2814
+ "div",
2815
+ {
2816
+ className: "space-y-1.5 overflow-y-auto",
2817
+ style: { maxHeight: `${maxVisible * 68}px` },
2818
+ children: visible.map((artifact) => /* @__PURE__ */ jsx19(
2819
+ AudioQueueItem,
2820
+ {
2821
+ artifact,
2822
+ onTranscribe: transcribeArtifact,
2823
+ onRetry: retryTranscription,
2824
+ onDelete: deleteArtifact,
2825
+ onArchive: archiveArtifact,
2826
+ onGetPlaybackUrl: getPlaybackUrl
2827
+ },
2828
+ artifact.id
2829
+ ))
2830
+ }
2831
+ )
2832
+ ] });
2833
+ }
2834
+
2835
+ // src/voice/AudioDraftPlayer.tsx
2836
+ import { useState as useState12, useEffect as useEffect10 } from "react";
2837
+ import { Play as Play5, Trash2 as Trash23, Loader2 as Loader210, RotateCcw as RotateCcw3, ArrowUp } from "lucide-react";
2838
+ import { jsx as jsx20, jsxs as jsxs14 } from "react/jsx-runtime";
2839
+ function AudioDraftPlayer({
2840
+ artifact,
2841
+ onGetPlaybackUrl,
2842
+ onPrimary,
2843
+ onDiscard,
2844
+ onRetry,
2845
+ onResume,
2846
+ pausedPreview = null,
2847
+ primaryActionLabel = "Transcribir",
2848
+ className = ""
2849
+ }) {
2850
+ const isPaused = artifact.state === "paused";
2851
+ const isSaving = artifact.state === "stopping";
2852
+ const isBusy = artifact.state === "transcribing" || artifact.state === "uploading";
2853
+ const isFailed = artifact.state === "failed";
2854
+ const hasBlob = artifact.size > 0 && !isSaving && !isPaused;
2855
+ const [playbackUrl, setPlaybackUrl] = useState12(null);
2856
+ useEffect10(() => {
2857
+ if (!onGetPlaybackUrl || !hasBlob) {
2858
+ setPlaybackUrl(null);
2859
+ return;
2860
+ }
2861
+ let cancelled = false;
2862
+ let url = null;
2863
+ void onGetPlaybackUrl(artifact.id).then((resolved) => {
2864
+ if (cancelled) {
2865
+ if (resolved) URL.revokeObjectURL(resolved);
2866
+ return;
2867
+ }
2868
+ url = resolved;
2869
+ setPlaybackUrl(resolved);
2870
+ });
2871
+ return () => {
2872
+ cancelled = true;
2873
+ if (url) URL.revokeObjectURL(url);
2874
+ setPlaybackUrl(null);
2875
+ };
2876
+ }, [artifact.id, hasBlob, onGetPlaybackUrl]);
2877
+ return /* @__PURE__ */ jsxs14(
2878
+ "div",
2879
+ {
2880
+ className: `fi-audio-draft flex items-center gap-3 px-4 py-3 rounded-2xl bg-white/[0.07] border border-white/[0.14] backdrop-blur-xl shadow-lg shadow-black/30 ${className}`,
2881
+ role: "group",
2882
+ "aria-label": "Audio grabado",
2883
+ children: [
2884
+ isPaused && pausedPreview ? (
2885
+ // Paused with the recorded-so-far WAV in hand: play it back through
2886
+ // the SAME primitive the TTS player uses. The pulsing dot keeps
2887
+ // signalling that the recording session is still open.
2888
+ /* @__PURE__ */ jsxs14("div", { className: "flex items-center gap-2 flex-1 min-w-0", children: [
2889
+ /* @__PURE__ */ jsx20(
2890
+ "span",
2891
+ {
2892
+ className: "fi-audio-draft-pauseddot shrink-0 w-2.5 h-2.5 rounded-full bg-amber-400 animate-pulse",
2893
+ "aria-hidden": "true"
2894
+ }
2895
+ ),
2896
+ /* @__PURE__ */ jsx20(
2897
+ RichAudioPlayer,
2898
+ {
2899
+ source: pausedPreview,
2900
+ className: "fi-audio-draft-player flex items-center gap-1 flex-1 min-w-0",
2901
+ buttonClassName: "p-2 rounded-xl text-white/80 hover:text-white hover:bg-white/10 disabled:opacity-35 disabled:cursor-not-allowed transition-colors",
2902
+ iconClassName: "w-4 h-4",
2903
+ progressClassName: "flex-1 min-w-0 h-1 accent-amber-400 cursor-pointer disabled:cursor-not-allowed"
2904
+ }
2905
+ ),
2906
+ /* @__PURE__ */ jsx20("span", { className: "hidden sm:inline text-xs font-medium text-amber-300/80 shrink-0", children: "En pausa" })
2907
+ ] })
2908
+ ) : isPaused ? (
2909
+ // Paused but the preview WAV is still being spliced (or the consumer
2910
+ // didn't wire one): honest status, never a dead play control.
2911
+ /* @__PURE__ */ jsxs14("div", { className: "flex items-center gap-2.5 flex-1 min-w-0", children: [
2912
+ /* @__PURE__ */ jsx20(
2913
+ "span",
2914
+ {
2915
+ className: "fi-audio-draft-pauseddot shrink-0 w-2.5 h-2.5 rounded-full bg-amber-400 animate-pulse",
2916
+ "aria-hidden": "true"
2917
+ }
2918
+ ),
2919
+ /* @__PURE__ */ jsx20("span", { className: "text-sm tabular-nums text-white/80", children: formatArtifactDuration(artifact.durationMs) }),
2920
+ /* @__PURE__ */ jsx20("span", { className: "text-xs font-medium text-amber-300/80", children: "Grabaci\xF3n en pausa" })
2921
+ ] })
2922
+ ) : /* @__PURE__ */ jsxs14("div", { className: "flex items-center gap-2 flex-1 min-w-0", children: [
2923
+ /* @__PURE__ */ jsx20(
2924
+ RichAudioPlayer,
2925
+ {
2926
+ source: playbackUrl ? { url: playbackUrl } : null,
2927
+ className: "fi-audio-draft-player flex items-center gap-1 flex-1 min-w-0",
2928
+ buttonClassName: "p-2 rounded-xl text-white/80 hover:text-white hover:bg-white/10 disabled:opacity-35 disabled:cursor-not-allowed transition-colors",
2929
+ iconClassName: "w-4 h-4",
2930
+ progressClassName: "flex-1 min-w-0 h-1 accent-emerald-400 cursor-pointer disabled:cursor-not-allowed"
2931
+ }
2932
+ ),
2933
+ /* @__PURE__ */ jsxs14("div", { className: "hidden sm:flex items-center gap-1.5 shrink-0 text-xs text-white/45", children: [
2934
+ artifact.size > 0 && /* @__PURE__ */ jsx20("span", { children: formatArtifactSize(artifact.size) }),
2935
+ isSaving && /* @__PURE__ */ jsxs14("span", { className: "inline-flex items-center gap-1 text-amber-400/70", children: [
2936
+ /* @__PURE__ */ jsx20(Loader210, { className: "w-3.5 h-3.5 animate-spin", "aria-hidden": true }),
2937
+ "Guardando\u2026"
2938
+ ] }),
2939
+ isBusy && /* @__PURE__ */ jsx20("span", { className: "text-blue-400/70", children: "Transcribiendo\u2026" })
2940
+ ] }),
2941
+ isFailed && artifact.errorMessage && /* @__PURE__ */ jsx20("span", { role: "alert", className: "text-xs text-red-400/80 truncate shrink min-w-0", children: artifact.errorMessage })
2942
+ ] }),
2943
+ /* @__PURE__ */ jsxs14("div", { className: "flex items-center gap-1 shrink-0", children: [
2944
+ onDiscard && !isBusy && /* @__PURE__ */ jsx20(
2945
+ "button",
2946
+ {
2947
+ type: "button",
2948
+ onClick: () => onDiscard(artifact.id),
2949
+ "aria-label": "Descartar grabaci\xF3n",
2950
+ className: "fi-audio-draft-discard p-2 rounded-xl text-white/35 hover:text-red-400 hover:bg-white/10 transition-colors",
2951
+ children: /* @__PURE__ */ jsx20(Trash23, { className: "w-4 h-4" })
2952
+ }
2953
+ ),
2954
+ onResume ? /* @__PURE__ */ jsxs14(
2955
+ "button",
2956
+ {
2957
+ type: "button",
2958
+ onClick: onResume,
2959
+ "aria-label": "Reanudar grabaci\xF3n",
2960
+ className: "fi-audio-draft-resume flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 transition-all active:scale-95",
2961
+ children: [
2962
+ /* @__PURE__ */ jsx20(Play5, { className: "w-3.5 h-3.5 ml-0.5" }),
2963
+ "Reanudar"
2964
+ ]
2965
+ }
2966
+ ) : isFailed && onRetry ? /* @__PURE__ */ jsx20(
2967
+ "button",
2968
+ {
2969
+ type: "button",
2970
+ onClick: () => onRetry(artifact.id),
2971
+ "aria-label": "Reintentar",
2972
+ className: "fi-audio-draft-retry p-2 rounded-xl text-amber-400/80 hover:text-amber-400 hover:bg-white/10 transition-colors",
2973
+ children: /* @__PURE__ */ jsx20(RotateCcw3, { className: "w-4 h-4" })
2974
+ }
2975
+ ) : onPrimary && /* @__PURE__ */ jsxs14(
2976
+ "button",
2977
+ {
2978
+ type: "button",
2979
+ onClick: () => onPrimary(artifact.id),
2980
+ disabled: isSaving || isBusy,
2981
+ className: "fi-audio-draft-primary flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-300 disabled:opacity-40 disabled:cursor-not-allowed transition-all active:scale-95",
2982
+ children: [
2983
+ /* @__PURE__ */ jsx20(ArrowUp, { className: "w-3.5 h-3.5" }),
2984
+ primaryActionLabel
2985
+ ]
2986
+ }
2987
+ )
2988
+ ] })
2989
+ ]
2990
+ }
2991
+ );
2992
+ }
2993
+
2994
+ // src/shell/ChatWidget.tsx
2995
+ import { useCallback as useCallback9 } from "react";
2996
+
2997
+ // src/shell/useChatWidgetState.ts
2998
+ import { useState as useState13, useCallback as useCallback8 } from "react";
2999
+ function useChatWidgetState({
3000
+ initialOpen,
3001
+ initialMode
3002
+ }) {
3003
+ const [isOpen, setIsOpen] = useState13(initialOpen);
3004
+ const [viewMode, setViewMode] = useState13(initialMode);
3005
+ const [isHistoryOpen, setIsHistoryOpen] = useState13(false);
3006
+ const [conversationStarted, setConversationStarted] = useState13(false);
3007
+ const [isStartingConversation, _setIsStartingConversation] = useState13(false);
3008
+ const open = useCallback8(() => {
3009
+ setIsOpen(true);
3010
+ }, []);
3011
+ const close = useCallback8(() => {
3012
+ setIsOpen(false);
3013
+ setViewMode("normal");
3014
+ }, []);
3015
+ const minimize = useCallback8(() => {
3016
+ if (viewMode === "expanded") {
3017
+ setViewMode("normal");
3018
+ }
3019
+ }, [viewMode]);
3020
+ const maximize = useCallback8(() => {
3021
+ setViewMode(viewMode === "expanded" ? "normal" : "expanded");
3022
+ }, [viewMode]);
3023
+ const toggleDenseMode = useCallback8(() => {
3024
+ setViewMode(viewMode === "dense" ? "fullscreen" : "dense");
3025
+ }, [viewMode]);
3026
+ const openHistory = useCallback8(() => {
3027
+ setIsHistoryOpen(true);
3028
+ }, []);
3029
+ const closeHistory = useCallback8(() => {
3030
+ setIsHistoryOpen(false);
3031
+ }, []);
3032
+ const startConversation = useCallback8(() => {
3033
+ setConversationStarted(true);
3034
+ }, []);
3035
+ const onMessagesLoaded = useCallback8((hasMessages) => {
3036
+ if (hasMessages) {
3037
+ setConversationStarted(true);
3038
+ }
3039
+ }, []);
3040
+ return {
3041
+ isOpen,
3042
+ viewMode,
3043
+ isHistoryOpen,
3044
+ conversationStarted,
3045
+ isStartingConversation,
3046
+ open,
3047
+ close,
3048
+ setViewMode,
3049
+ minimize,
3050
+ maximize,
3051
+ toggleDenseMode,
3052
+ openHistory,
3053
+ closeHistory,
3054
+ startConversation,
3055
+ onMessagesLoaded
3056
+ };
3057
+ }
3058
+
3059
+ // src/shell/useMediaQuery.ts
3060
+ import { useSyncExternalStore as useSyncExternalStore2 } from "react";
3061
+ var mqlCache = /* @__PURE__ */ new Map();
3062
+ function getMql(query, useCache = true) {
3063
+ if (typeof window === "undefined" || !("matchMedia" in window)) {
3064
+ return null;
3065
+ }
3066
+ if (useCache) {
3067
+ const cached = mqlCache.get(query);
3068
+ if (cached) return cached;
3069
+ }
3070
+ const mql = window.matchMedia(query);
3071
+ if (useCache) {
3072
+ mqlCache.set(query, mql);
3073
+ }
3074
+ return mql;
3075
+ }
3076
+ function useMediaQuery(query, options) {
3077
+ const ssrMatch = options?.ssrMatch ?? false;
3078
+ const useRaf = options?.useRaf ?? true;
3079
+ const cache = options?.cache ?? true;
3080
+ const mql = getMql(query, cache);
3081
+ const getSnapshot = () => mql ? mql.matches : ssrMatch;
3082
+ const getServerSnapshot = () => ssrMatch;
3083
+ const subscribe = (onStoreChange) => {
3084
+ if (!mql) return () => {
3085
+ };
3086
+ let rafId = 0;
3087
+ const handler = () => {
3088
+ if (!useRaf) {
3089
+ onStoreChange();
3090
+ return;
3091
+ }
3092
+ if (rafId) cancelAnimationFrame(rafId);
3093
+ rafId = requestAnimationFrame(() => onStoreChange());
3094
+ };
3095
+ const mqlAny = mql;
3096
+ if (typeof mqlAny.addEventListener === "function") {
3097
+ mqlAny.addEventListener("change", handler);
3098
+ } else if (typeof mqlAny.addListener === "function") {
3099
+ mqlAny.addListener(handler);
3100
+ }
3101
+ return () => {
3102
+ if (rafId) cancelAnimationFrame(rafId);
3103
+ if (typeof mqlAny.removeEventListener === "function") {
3104
+ mqlAny.removeEventListener("change", handler);
3105
+ } else if (typeof mqlAny.removeListener === "function") {
3106
+ mqlAny.removeListener(handler);
3107
+ }
3108
+ };
3109
+ };
3110
+ return useSyncExternalStore2(subscribe, getSnapshot, getServerSnapshot);
3111
+ }
3112
+ function useBreakpoints(breakpoints, options) {
3113
+ const isMobile = useMediaQuery(breakpoints.mobile, { ssrMatch: options?.ssrMatch });
3114
+ const isTablet = useMediaQuery(breakpoints.tablet, { ssrMatch: options?.ssrMatch });
3115
+ const isDesktop = useMediaQuery(breakpoints.desktop, { ssrMatch: options?.ssrMatch });
3116
+ return { isMobile, isTablet, isDesktop };
3117
+ }
3118
+ function clearMediaQueryCache() {
3119
+ mqlCache.clear();
3120
+ }
3121
+
3122
+ // src/shell/config.ts
3123
+ var defaultTheme = {
3124
+ background: {
3125
+ header: "bg-gradient-to-r from-emerald-600 to-cyan-600",
3126
+ body: "bg-slate-950",
3127
+ input: "bg-slate-800"
3128
+ },
3129
+ border: {
3130
+ main: "border-slate-700",
3131
+ input: "border-slate-700",
3132
+ bubble: "border-slate-600/60"
3133
+ },
3134
+ text: {
3135
+ primary: "text-white",
3136
+ secondary: "text-slate-200",
3137
+ muted: "text-slate-400",
3138
+ accent: "text-emerald-300"
3139
+ },
3140
+ accent: { from: "from-emerald-600", to: "to-cyan-600" },
3141
+ shadow: "shadow-2xl",
3142
+ timestamp: {
3143
+ text: "text-slate-400/70",
3144
+ tooltip: "bg-slate-800/95 text-slate-200"
3145
+ }
3146
+ };
3147
+ var defaultBehavior = {
3148
+ autoScroll: true,
3149
+ showTyping: true,
3150
+ groupMessages: true,
3151
+ groupThresholdMinutes: 2,
3152
+ showDayDividers: true,
3153
+ animateEntrance: true,
3154
+ maxMessages: 100,
3155
+ inputPlaceholder: "Escribe tu mensaje...",
3156
+ enableReactions: false,
3157
+ enableReadReceipts: false,
3158
+ enableThinking: true,
3159
+ showThinking: true
3160
+ };
3161
+ var defaultTimestampConfig = {
3162
+ show: true,
3163
+ format: "smart",
3164
+ showTooltip: true,
3165
+ relativeThreshold: 60,
3166
+ showSeconds: false,
3167
+ position: "inline",
3168
+ updateInterval: 6e4
3169
+ };
3170
+ var defaultAnimationConfig = {
3171
+ entrance: { enabled: true, duration: "0.4s", easing: "ease-out" },
3172
+ typing: { dotDuration: "1.4s", dotDelay: "0.2s" },
3173
+ scroll: { behavior: "smooth", duration: 300 }
3174
+ };
3175
+ var defaultChatConfig = {
3176
+ title: "Free Intelligence",
3177
+ subtitle: void 0,
3178
+ theme: defaultTheme,
3179
+ behavior: defaultBehavior,
3180
+ timestamp: defaultTimestampConfig,
3181
+ animation: defaultAnimationConfig,
3182
+ footer: void 0,
3183
+ dimensions: { width: "24rem", height: "600px", minHeight: "400px", maxHeight: "80vh" }
3184
+ };
3185
+ function mergeChatConfig(custom) {
3186
+ if (!custom) return defaultChatConfig;
3187
+ return {
3188
+ ...defaultChatConfig,
3189
+ ...custom,
3190
+ theme: { ...defaultChatConfig.theme, ...custom.theme },
3191
+ behavior: { ...defaultChatConfig.behavior, ...custom.behavior },
3192
+ timestamp: { ...defaultChatConfig.timestamp, ...custom.timestamp },
3193
+ animation: { ...defaultChatConfig.animation, ...custom.animation }
3194
+ };
3195
+ }
3196
+ var CHAT_BREAKPOINTS = {
3197
+ mobile: "(max-width: 639.98px)",
3198
+ tablet: "(min-width: 640px) and (max-width: 1023.98px)",
3199
+ desktop: "(min-width: 1024px)"
3200
+ };
3201
+
3202
+ // src/shell/FloatingButton.tsx
3203
+ import { MessageCircle } from "lucide-react";
3204
+ import { jsx as jsx21, jsxs as jsxs15 } from "react/jsx-runtime";
3205
+ function FloatingButton({ onClick, isMobile }) {
3206
+ const buttonSize = isMobile ? "w-16 h-16" : "w-14 h-14";
3207
+ const iconSize = isMobile ? "h-7 w-7" : "h-6 w-6";
3208
+ const buttonPosition = isMobile ? "bottom-4 right-4" : "bottom-6 right-6";
3209
+ return /* @__PURE__ */ jsxs15(
3210
+ "button",
3211
+ {
3212
+ onClick,
3213
+ className: `
3214
+ fixed ${buttonPosition} ${buttonSize}
3215
+ fi-fab-emerald z-50 group
3216
+ `,
3217
+ "aria-label": "Chat with Free Intelligence",
3218
+ children: [
3219
+ /* @__PURE__ */ jsx21(MessageCircle, { className: `${iconSize} text-white` }),
3220
+ /* @__PURE__ */ jsx21("span", { className: "fi-dot-pulse-red" }),
3221
+ !isMobile && /* @__PURE__ */ jsx21("div", { className: "fi-tooltip-right", children: "Habla con Free Intelligence" })
3222
+ ]
3223
+ }
3224
+ );
3225
+ }
3226
+
3227
+ // src/shell/ChatContent.tsx
3228
+ import { Loader2 as Loader213 } from "lucide-react";
3229
+
3230
+ // src/shell/ChatWidgetContainer.tsx
3231
+ import { MessageCircle as MessageCircle2 } from "lucide-react";
3232
+ import { Fragment as Fragment2, jsx as jsx22, jsxs as jsxs16 } from "react/jsx-runtime";
3233
+ function ChatWidgetContainer(props) {
3234
+ const { mode, title, children, embedded = false, onModeChange } = props;
3235
+ const { isMobile, isTablet } = useBreakpoints(CHAT_BREAKPOINTS, {
3236
+ ssrMatch: false
3237
+ });
3238
+ const effectiveMode = mode === "minimized" ? "minimized" : isMobile ? mode === "dense" ? "dense" : "fullscreen" : isTablet && (mode === "normal" || mode === "expanded") ? "expanded" : mode;
3239
+ if (effectiveMode === "minimized") {
3240
+ return /* @__PURE__ */ jsxs16("div", { className: "chat-container-minimized", onClick: () => onModeChange("normal"), children: [
3241
+ /* @__PURE__ */ jsx22(MessageCircle2, { className: "chat-container-minimized-icon" }),
3242
+ /* @__PURE__ */ jsx22("span", { className: "chat-container-minimized-title", children: title }),
3243
+ /* @__PURE__ */ jsx22(
3244
+ "button",
3245
+ {
3246
+ onClick: (e) => {
3247
+ e.stopPropagation();
3248
+ onModeChange("normal");
3249
+ },
3250
+ className: "ml-2 fi-hover-ghost",
3251
+ "aria-label": "Expand chat",
3252
+ children: /* @__PURE__ */ jsx22("div", { className: "chat-container-minimized-pulse" })
3253
+ }
3254
+ )
3255
+ ] });
3256
+ }
3257
+ if (effectiveMode === "expanded" && isTablet) {
3258
+ return /* @__PURE__ */ jsxs16(Fragment2, { children: [
3259
+ /* @__PURE__ */ jsx22("div", { className: "chat-backdrop", onClick: () => onModeChange("normal") }),
3260
+ /* @__PURE__ */ jsx22(
3261
+ "div",
3262
+ {
3263
+ className: "chat-container-expanded-tablet",
3264
+ style: { width: "min(90vw, 900px)", height: "min(90vh, 800px)" },
3265
+ children
3266
+ }
3267
+ )
3268
+ ] });
3269
+ }
3270
+ if (effectiveMode === "expanded") {
3271
+ return /* @__PURE__ */ jsx22(
3272
+ "div",
3273
+ {
3274
+ className: "chat-container-expanded",
3275
+ style: {
3276
+ width: "min(80vw, 1200px)",
3277
+ height: "700px",
3278
+ maxWidth: "calc(100vw - 3rem)",
3279
+ maxHeight: "calc(100vh - 3rem)"
3280
+ },
3281
+ children
3282
+ }
3283
+ );
3284
+ }
3285
+ if (embedded && (effectiveMode === "fullscreen" || effectiveMode === "dense")) {
3286
+ return /* @__PURE__ */ jsx22("div", { className: "chat-container-embedded", children });
3287
+ }
3288
+ if (effectiveMode === "dense") {
3289
+ return /* @__PURE__ */ jsx22("div", { className: "chat-container-dense", children });
3290
+ }
3291
+ if (effectiveMode === "fullscreen") {
3292
+ return /* @__PURE__ */ jsx22("div", { className: "chat-container-fullscreen", children });
3293
+ }
3294
+ return /* @__PURE__ */ jsx22("div", { className: "chat-container-normal", children });
3295
+ }
3296
+
3297
+ // src/shell/ChatWidgetHeader.tsx
3298
+ import { X, Minimize2, Maximize2, MessageCircle as MessageCircle3, Search } from "lucide-react";
3299
+ import { Fragment as Fragment3, jsx as jsx23, jsxs as jsxs17 } from "react/jsx-runtime";
3300
+ var HEADER_BTN_CLASS = "fi-btn-ghost fi-btn-sm chat-header-btn";
3301
+ var DEFAULT_HEADER_GRADIENT = "bg-gradient-to-r from-emerald-600 to-cyan-600";
3302
+ function ChatWidgetHeader({
3303
+ title,
3304
+ subtitle,
3305
+ backgroundClass = DEFAULT_HEADER_GRADIENT,
3306
+ mode,
3307
+ showControls = true,
3308
+ showHistorySearch = true,
3309
+ onNavigate,
3310
+ onMinimize,
3311
+ onMaximize,
3312
+ onToggleDenseMode,
3313
+ onClose,
3314
+ onHistorySearch
3315
+ }) {
3316
+ return /* @__PURE__ */ jsxs17("div", { className: `${backgroundClass} chat-header`, children: [
3317
+ /* @__PURE__ */ jsxs17("div", { className: "flex items-center gap-3 min-w-0", children: [
3318
+ /* @__PURE__ */ jsx23(
3319
+ "button",
3320
+ {
3321
+ type: "button",
3322
+ onClick: () => onNavigate?.("chat"),
3323
+ className: "chat-header-icon",
3324
+ title: "Abrir chat completo",
3325
+ "aria-label": "Abrir chat completo",
3326
+ children: /* @__PURE__ */ jsx23(MessageCircle3, { className: "h-5 w-5 text-white" })
3327
+ }
3328
+ ),
3329
+ /* @__PURE__ */ jsxs17("div", { className: "min-w-0", children: [
3330
+ /* @__PURE__ */ jsx23("h3", { className: "chat-header-title", children: title }),
3331
+ subtitle && /* @__PURE__ */ jsx23("p", { className: "chat-header-subtitle", children: subtitle })
3332
+ ] })
3333
+ ] }),
3334
+ /* @__PURE__ */ jsx23("div", { className: "chat-header-controls", children: showControls && /* @__PURE__ */ jsxs17(Fragment3, { children: [
3335
+ showHistorySearch && onHistorySearch && mode !== "minimized" && /* @__PURE__ */ jsx23("button", { onClick: onHistorySearch, className: HEADER_BTN_CLASS, "aria-label": "Search history", title: "Buscar en historial", type: "button", children: /* @__PURE__ */ jsx23(Search, { className: "h-4 w-4" }) }),
3336
+ mode === "fullscreen" && onToggleDenseMode && /* @__PURE__ */ jsx23("button", { onClick: onToggleDenseMode, className: HEADER_BTN_CLASS, "aria-label": "Cambiar a modo denso", title: "Modo denso (sin controles)", type: "button", children: /* @__PURE__ */ jsxs17("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", fill: "currentColor", viewBox: "0 0 16 16", children: [
3337
+ /* @__PURE__ */ jsx23("path", { d: "M0 3.5A1.5 1.5 0 0 1 1.5 2h13A1.5 1.5 0 0 1 16 3.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 0 12.5v-9zM1.5 3a.5.5 0 0 0-.5.5v9a.5.5 0 0 0 .5.5h13a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5h-13z" }),
3338
+ /* @__PURE__ */ jsx23("path", { d: "M3 4.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0 2a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0 2a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5z" })
3339
+ ] }) }),
3340
+ mode === "dense" && onToggleDenseMode && /* @__PURE__ */ jsx23("button", { onClick: onToggleDenseMode, className: HEADER_BTN_CLASS, "aria-label": "Cambiar a modo expandido", title: "Modo expandido (con controles)", type: "button", children: /* @__PURE__ */ jsxs17("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", fill: "currentColor", viewBox: "0 0 16 16", children: [
3341
+ /* @__PURE__ */ jsx23("path", { d: "M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z" }),
3342
+ /* @__PURE__ */ jsx23("path", { d: "M6.5 4.5a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1 0-1h2V5a.5.5 0 0 1 .5-.5zM8 8.5a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1 0-1h2v-2a.5.5 0 0 1 .5-.5zm3-4a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1 0-1h2V5a.5.5 0 0 1 .5-.5zm0 6a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1 0-1h2v-2a.5.5 0 0 1 .5-.5z" })
3343
+ ] }) }),
3344
+ mode === "expanded" && /* @__PURE__ */ jsx23("button", { onClick: onMinimize, className: HEADER_BTN_CLASS, "aria-label": "Restaurar tama\xF1o", title: "Restaurar a tama\xF1o normal", type: "button", children: /* @__PURE__ */ jsx23(Minimize2, { className: "h-4 w-4" }) }),
3345
+ mode === "normal" && /* @__PURE__ */ jsx23("button", { onClick: onMaximize, className: HEADER_BTN_CLASS, "aria-label": "Expandir", title: "Expandir (60% m\xE1s grande)", type: "button", children: /* @__PURE__ */ jsx23(Maximize2, { className: "h-4 w-4" }) }),
3346
+ /* @__PURE__ */ jsx23("button", { onClick: onClose, className: HEADER_BTN_CLASS, "aria-label": "Close", title: "Cerrar", type: "button", children: /* @__PURE__ */ jsx23(X, { className: "h-5 w-5" }) })
3347
+ ] }) })
3348
+ ] });
3349
+ }
3350
+
3351
+ // src/shell/ChatToolbar.tsx
3352
+ import { useState as useState14, useRef as useRef8, useEffect as useEffect11 } from "react";
3353
+ import { createPortal } from "react-dom";
3354
+ import { Paperclip, Globe, Type, Zap, Trash, Sparkles, BookOpen, Terminal, MoreVertical, Send, Loader2 as Loader211 } from "lucide-react";
3355
+ import { Fragment as Fragment4, jsx as jsx24, jsxs as jsxs18 } from "react/jsx-runtime";
3356
+ function ChatToolbar({
3357
+ showAttach = true,
3358
+ showLanguage = true,
3359
+ showFormatting = true,
3360
+ showResponseMode = true,
3361
+ showVoice = true,
3362
+ showPersonaSelector = true,
3363
+ showThinkingToggle = true,
3364
+ responseMode = "explanatory",
3365
+ selectedPersona: _selectedPersona = "general_assistant",
3366
+ showThinking = true,
3367
+ voiceRecording,
3368
+ personaSelector,
3369
+ onAttach,
3370
+ onLanguage,
3371
+ onFormatting,
3372
+ onResponseModeToggle,
3373
+ onVoiceStart,
3374
+ onVoiceStop,
3375
+ onShowThinkingToggle,
3376
+ showClear = true,
3377
+ onClearConversation,
3378
+ showCopyCurl = true,
3379
+ onCopyCurl,
3380
+ onSend,
3381
+ canSend = false,
3382
+ sendLoading = false
3383
+ }) {
3384
+ const [overflowOpen, setOverflowOpen] = useState14(false);
3385
+ const overflowButtonRef = useRef8(null);
3386
+ const [dropdownPosition, setDropdownPosition] = useState14({ top: 0, left: 0 });
3387
+ useEffect11(() => {
3388
+ if (overflowOpen && overflowButtonRef.current) {
3389
+ const rect = overflowButtonRef.current.getBoundingClientRect();
3390
+ setDropdownPosition({
3391
+ top: rect.top - 8,
3392
+ // 8px margin above button
3393
+ left: rect.left
3394
+ });
3395
+ }
3396
+ }, [overflowOpen]);
3397
+ const buttonBaseClass = "chat-toolbar-btn";
3398
+ const iconClass = "chat-toolbar-icon";
3399
+ return /* @__PURE__ */ jsxs18("div", { className: "chat-toolbar", children: [
3400
+ /* @__PURE__ */ jsxs18("div", { className: "fi-flex-gap-sm", children: [
3401
+ showPersonaSelector && personaSelector,
3402
+ (showAttach || showLanguage || showFormatting) && /* @__PURE__ */ jsxs18("div", { className: "relative", children: [
3403
+ /* @__PURE__ */ jsx24(
3404
+ "button",
3405
+ {
3406
+ ref: overflowButtonRef,
3407
+ onClick: () => setOverflowOpen(!overflowOpen),
3408
+ className: buttonBaseClass,
3409
+ title: "M\xE1s opciones",
3410
+ "aria-label": "M\xE1s opciones",
3411
+ children: /* @__PURE__ */ jsx24(MoreVertical, { className: iconClass })
3412
+ }
3413
+ ),
3414
+ overflowOpen && createPortal(
3415
+ /* @__PURE__ */ jsxs18(Fragment4, { children: [
3416
+ /* @__PURE__ */ jsx24(
3417
+ "div",
3418
+ {
3419
+ className: "fixed inset-0 z-[9998]",
3420
+ onClick: () => setOverflowOpen(false),
3421
+ "aria-hidden": "true"
3422
+ }
3423
+ ),
3424
+ /* @__PURE__ */ jsxs18(
3425
+ "div",
3426
+ {
3427
+ className: "chat-dropdown",
3428
+ style: {
3429
+ top: dropdownPosition.top,
3430
+ left: dropdownPosition.left,
3431
+ transform: "translateY(-100%)"
3432
+ },
3433
+ children: [
3434
+ showAttach && /* @__PURE__ */ jsxs18(
3435
+ "button",
3436
+ {
3437
+ onClick: () => {
3438
+ onAttach?.();
3439
+ setOverflowOpen(false);
3440
+ },
3441
+ className: "chat-dropdown-item",
3442
+ children: [
3443
+ /* @__PURE__ */ jsx24(Paperclip, { className: "fi-icon-sm" }),
3444
+ /* @__PURE__ */ jsx24("span", { children: "Adjuntar archivo" })
3445
+ ]
3446
+ }
3447
+ ),
3448
+ showLanguage && /* @__PURE__ */ jsxs18(
3449
+ "button",
3450
+ {
3451
+ onClick: () => {
3452
+ onLanguage?.();
3453
+ setOverflowOpen(false);
3454
+ },
3455
+ className: "chat-dropdown-item",
3456
+ children: [
3457
+ /* @__PURE__ */ jsx24(Globe, { className: "fi-icon-sm" }),
3458
+ /* @__PURE__ */ jsx24("span", { children: "Cambiar idioma" })
3459
+ ]
3460
+ }
3461
+ ),
3462
+ showFormatting && /* @__PURE__ */ jsxs18(
3463
+ "button",
3464
+ {
3465
+ onClick: () => {
3466
+ onFormatting?.();
3467
+ setOverflowOpen(false);
3468
+ },
3469
+ className: "chat-dropdown-item",
3470
+ children: [
3471
+ /* @__PURE__ */ jsx24(Type, { className: "fi-icon-sm" }),
3472
+ /* @__PURE__ */ jsx24("span", { children: "Formato de texto" })
3473
+ ]
3474
+ }
3475
+ ),
3476
+ showCopyCurl && /* @__PURE__ */ jsxs18(Fragment4, { children: [
3477
+ /* @__PURE__ */ jsx24("div", { className: "chat-dropdown-divider" }),
3478
+ /* @__PURE__ */ jsxs18(
3479
+ "button",
3480
+ {
3481
+ onClick: () => {
3482
+ onCopyCurl?.();
3483
+ setOverflowOpen(false);
3484
+ },
3485
+ className: "chat-dropdown-item fi-text-warning hover:bg-amber-900/20 hover:text-amber-300",
3486
+ children: [
3487
+ /* @__PURE__ */ jsx24(Terminal, { className: "fi-icon-sm" }),
3488
+ /* @__PURE__ */ jsx24("span", { children: "Copiar plantilla curl" })
3489
+ ]
3490
+ }
3491
+ )
3492
+ ] }),
3493
+ showThinkingToggle && /* @__PURE__ */ jsxs18("div", { className: "@md:hidden", children: [
3494
+ /* @__PURE__ */ jsx24("div", { className: "chat-dropdown-divider" }),
3495
+ /* @__PURE__ */ jsxs18(
3496
+ "button",
3497
+ {
3498
+ onClick: () => {
3499
+ onShowThinkingToggle?.();
3500
+ setOverflowOpen(false);
3501
+ },
3502
+ className: `chat-dropdown-item ${showThinking ? "fi-text-purple hover:bg-purple-900/20" : ""}`,
3503
+ children: [
3504
+ /* @__PURE__ */ jsx24(Sparkles, { className: "fi-icon-sm" }),
3505
+ /* @__PURE__ */ jsx24("span", { children: showThinking ? "Ocultar razonamiento" : "Mostrar razonamiento" })
3506
+ ]
3507
+ }
3508
+ )
3509
+ ] }),
3510
+ showClear && /* @__PURE__ */ jsxs18("div", { className: "@md:hidden", children: [
3511
+ /* @__PURE__ */ jsx24("div", { className: "chat-dropdown-divider" }),
3512
+ /* @__PURE__ */ jsxs18(
3513
+ "button",
3514
+ {
3515
+ onClick: () => {
3516
+ onClearConversation?.();
3517
+ setOverflowOpen(false);
3518
+ },
3519
+ className: "chat-dropdown-item-danger",
3520
+ children: [
3521
+ /* @__PURE__ */ jsx24(Trash, { className: "fi-icon-sm" }),
3522
+ /* @__PURE__ */ jsx24("span", { children: "Limpiar conversaci\xF3n" })
3523
+ ]
3524
+ }
3525
+ )
3526
+ ] })
3527
+ ]
3528
+ }
3529
+ )
3530
+ ] }),
3531
+ document.body
3532
+ )
3533
+ ] })
3534
+ ] }),
3535
+ /* @__PURE__ */ jsxs18("div", { className: "fi-flex-gap-sm", children: [
3536
+ showClear && /* @__PURE__ */ jsx24(
3537
+ "button",
3538
+ {
3539
+ onClick: () => onClearConversation?.(),
3540
+ className: `${buttonBaseClass} chat-toolbar-btn-danger hidden @md:flex`,
3541
+ title: "Limpiar conversaci\xF3n",
3542
+ "aria-label": "Limpiar conversaci\xF3n",
3543
+ children: /* @__PURE__ */ jsx24(Trash, { className: iconClass })
3544
+ }
3545
+ ),
3546
+ showThinkingToggle && /* @__PURE__ */ jsx24(
3547
+ "button",
3548
+ {
3549
+ onClick: onShowThinkingToggle,
3550
+ className: `${buttonBaseClass} hidden @md:flex ${showThinking ? "chat-toolbar-btn-active" : ""}`,
3551
+ title: showThinking ? "Razonamiento visible (click para ocultar)" : "Razonamiento oculto (click para mostrar)",
3552
+ "aria-label": showThinking ? "Ocultar razonamiento del modelo" : "Mostrar razonamiento del modelo",
3553
+ children: /* @__PURE__ */ jsx24(Sparkles, { className: iconClass })
3554
+ }
3555
+ ),
3556
+ showResponseMode && /* @__PURE__ */ jsx24(
3557
+ "button",
3558
+ {
3559
+ onClick: onResponseModeToggle,
3560
+ className: `${buttonBaseClass} ${responseMode === "concise" ? "fi-text-info hover:text-cyan-300" : "chat-toolbar-btn-success"}`,
3561
+ title: responseMode === "explanatory" ? "Modo: Explicativo (detallado)" : "Modo: Conciso (breve)",
3562
+ "aria-label": responseMode === "explanatory" ? "Cambiar a modo conciso" : "Cambiar a modo explicativo",
3563
+ children: responseMode === "explanatory" ? /* @__PURE__ */ jsx24(BookOpen, { className: iconClass }) : /* @__PURE__ */ jsx24(Zap, { className: iconClass })
3564
+ }
3565
+ ),
3566
+ showVoice && /* @__PURE__ */ jsx24(
3567
+ VoiceMicButton,
3568
+ {
3569
+ isRecording: voiceRecording?.isRecording || false,
3570
+ isTranscribing: voiceRecording?.isTranscribing || false,
3571
+ audioLevel: voiceRecording?.audioLevel || 0,
3572
+ isSilent: voiceRecording?.isSilent ?? true,
3573
+ recordingTime: voiceRecording?.recordingTime || 0,
3574
+ onStart: onVoiceStart || (() => {
3575
+ }),
3576
+ onStop: onVoiceStop || (() => {
3577
+ })
3578
+ }
3579
+ ),
3580
+ /* @__PURE__ */ jsx24(
3581
+ "button",
3582
+ {
3583
+ onClick: onSend,
3584
+ disabled: !canSend,
3585
+ className: `p-2.5 rounded-xl flex items-center justify-center flex-shrink-0 transition-all duration-200 ${canSend ? "bg-gradient-to-r from-amber-500 to-orange-500 text-slate-900 shadow-lg shadow-amber-500/25 hover:shadow-amber-500/40" : "bg-slate-800 text-slate-500 cursor-not-allowed"}`,
3586
+ "aria-label": "Enviar mensaje",
3587
+ children: sendLoading ? /* @__PURE__ */ jsx24(Loader211, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx24(Send, { className: "h-4 w-4" })
3588
+ }
3589
+ )
3590
+ ] })
3591
+ ] });
3592
+ }
3593
+
3594
+ // src/shell/ChatFilePreview.tsx
3595
+ import {
3596
+ FileText,
3597
+ FileCode,
3598
+ Image as ImageIcon,
3599
+ File,
3600
+ X as X2,
3601
+ Loader2 as Loader212,
3602
+ CheckCircle,
3603
+ AlertCircle as AlertCircle4
3604
+ } from "lucide-react";
3605
+ import { Fragment as Fragment5, jsx as jsx25, jsxs as jsxs19 } from "react/jsx-runtime";
3606
+ var FILE_ICONS = {
3607
+ "application/pdf": FileText,
3608
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": FileText,
3609
+ "application/msword": FileText,
3610
+ "text/plain": File,
3611
+ "text/markdown": FileCode,
3612
+ "image/png": ImageIcon,
3613
+ "image/jpeg": ImageIcon,
3614
+ "image/jpg": ImageIcon
3615
+ };
3616
+ function formatFileSize(bytes) {
3617
+ if (bytes === 0) return "0 B";
3618
+ const k = 1024;
3619
+ const sizes = ["B", "KB", "MB", "GB"];
3620
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
3621
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
3622
+ }
3623
+ function getFileIcon(file) {
3624
+ return FILE_ICONS[file.type] || File;
3625
+ }
3626
+ function ChatFilePreview({
3627
+ file,
3628
+ status,
3629
+ progress = 0,
3630
+ error,
3631
+ onCancel
3632
+ }) {
3633
+ const FileIcon = getFileIcon(file);
3634
+ const isCompleted = status === "indexed";
3635
+ const isError = status === "error";
3636
+ const isUploading = status === "uploading";
3637
+ const isProcessing = status === "processing" || status === "pending_instructions";
3638
+ return /* @__PURE__ */ jsxs19("div", { className: `
3639
+ flex items-center gap-3 p-3 rounded-xl border
3640
+ ${isError ? "bg-red-900/20 border-red-700/50" : isCompleted ? "bg-emerald-900/20 border-emerald-700/50" : "bg-slate-800/80 border-slate-700/50"}
3641
+ transition-colors duration-200
3642
+ `, children: [
3643
+ /* @__PURE__ */ jsx25("div", { className: `
3644
+ p-2 rounded-lg
3645
+ ${isError ? "bg-red-900/50" : isCompleted ? "bg-emerald-900/50" : "bg-slate-700"}
3646
+ `, children: isProcessing ? /* @__PURE__ */ jsx25(Loader212, { className: "w-5 h-5 fi-text-primary animate-spin" }) : isCompleted ? /* @__PURE__ */ jsx25(CheckCircle, { className: "w-5 h-5 fi-text-success" }) : isError ? /* @__PURE__ */ jsx25(AlertCircle4, { className: "w-5 h-5 fi-text-error" }) : /* @__PURE__ */ jsx25(FileIcon, { className: "w-5 h-5 fi-text" }) }),
3647
+ /* @__PURE__ */ jsxs19("div", { className: "flex-1 min-w-0", children: [
3648
+ /* @__PURE__ */ jsx25("p", { className: "fi-title-sm-medium truncate", title: file.name, children: file.name }),
3649
+ /* @__PURE__ */ jsxs19("div", { className: "flex items-center gap-2 fi-text-xs", children: [
3650
+ /* @__PURE__ */ jsx25("span", { children: formatFileSize(file.size) }),
3651
+ isUploading && /* @__PURE__ */ jsxs19(Fragment5, { children: [
3652
+ /* @__PURE__ */ jsx25("span", { children: "-" }),
3653
+ /* @__PURE__ */ jsx25("span", { className: "fi-text-primary", children: progress < 100 ? `Subiendo... ${progress}%` : "Completado" })
3654
+ ] }),
3655
+ isProcessing && /* @__PURE__ */ jsxs19(Fragment5, { children: [
3656
+ /* @__PURE__ */ jsx25("span", { children: "-" }),
3657
+ /* @__PURE__ */ jsx25("span", { className: "fi-text-primary", children: "Procesando..." })
3658
+ ] }),
3659
+ isCompleted && /* @__PURE__ */ jsxs19(Fragment5, { children: [
3660
+ /* @__PURE__ */ jsx25("span", { children: "-" }),
3661
+ /* @__PURE__ */ jsx25("span", { className: "chat-file-status-indexed", children: "Indexado" })
3662
+ ] }),
3663
+ isError && error && /* @__PURE__ */ jsxs19(Fragment5, { children: [
3664
+ /* @__PURE__ */ jsx25("span", { children: "-" }),
3665
+ /* @__PURE__ */ jsx25("span", { className: "fi-text-error truncate", title: error, children: error })
3666
+ ] })
3667
+ ] }),
3668
+ isUploading && /* @__PURE__ */ jsx25("div", { className: "mt-2 h-1.5 bg-slate-700 rounded-full overflow-hidden", children: /* @__PURE__ */ jsx25(
3669
+ "div",
3670
+ {
3671
+ className: "fi-progress-bar duration-300",
3672
+ style: { width: `${progress}%` }
3673
+ }
3674
+ ) })
3675
+ ] }),
3676
+ !isCompleted && !isProcessing && /* @__PURE__ */ jsx25(
3677
+ "button",
3678
+ {
3679
+ type: "button",
3680
+ onClick: onCancel,
3681
+ className: "fi-btn-ghost fi-btn-sm fi-hover-bg",
3682
+ "aria-label": "Cancelar",
3683
+ title: "Cancelar",
3684
+ children: /* @__PURE__ */ jsx25(X2, { className: "h-4 w-4" })
3685
+ }
3686
+ )
3687
+ ] });
3688
+ }
3689
+
3690
+ // src/shell/ChatStartScreen.tsx
3691
+ import { Download, MessageSquareText, Monitor, Shield, Sparkles as Sparkles2 } from "lucide-react";
3692
+ import { Fragment as Fragment6, jsx as jsx26, jsxs as jsxs20 } from "react/jsx-runtime";
3693
+ function ChatStartScreen({
3694
+ isAuthenticated,
3695
+ userName,
3696
+ onStart,
3697
+ onLogin: _onLogin,
3698
+ onNavigate,
3699
+ isLoading = false
3700
+ }) {
3701
+ if (!isAuthenticated) {
3702
+ return /* @__PURE__ */ jsx26("div", { className: "chat-start-screen", children: /* @__PURE__ */ jsxs20("div", { className: "chat-start-container", children: [
3703
+ /* @__PURE__ */ jsx26("div", { className: "flex justify-center", children: /* @__PURE__ */ jsx26("div", { className: "chat-start-icon", children: /* @__PURE__ */ jsx26(Monitor, { className: "fi-icon-xl text-purple-400" }) }) }),
3704
+ /* @__PURE__ */ jsxs20("div", { className: "fi-stack-sm", children: [
3705
+ /* @__PURE__ */ jsx26("h3", { className: "chat-start-title", children: "\xA1Pru\xE9balo en tu escritorio!" }),
3706
+ /* @__PURE__ */ jsx26("p", { className: "chat-start-subtitle", children: "IA offline para tu desarrollo profesional. Licencias piloto gratuitas disponibles. \xA1Descarga la tuya!" })
3707
+ ] }),
3708
+ /* @__PURE__ */ jsxs20(
3709
+ "button",
3710
+ {
3711
+ type: "button",
3712
+ onClick: () => onNavigate?.("downloads"),
3713
+ className: "chat-start-btn-login",
3714
+ children: [
3715
+ /* @__PURE__ */ jsx26(Download, { className: "fi-icon-md" }),
3716
+ "Ir a Descargas"
3717
+ ]
3718
+ }
3719
+ ),
3720
+ /* @__PURE__ */ jsx26("p", { className: "chat-start-hint", children: "100% privado, funciona sin internet" })
3721
+ ] }) });
3722
+ }
3723
+ return /* @__PURE__ */ jsx26("div", { className: "chat-start-screen", children: /* @__PURE__ */ jsxs20("div", { className: "chat-start-container", children: [
3724
+ /* @__PURE__ */ jsx26("div", { className: "pt-4 flex justify-center", children: /* @__PURE__ */ jsx26("div", { className: "chat-start-icon-large", children: /* @__PURE__ */ jsx26(Sparkles2, { className: "w-10 h-10 fi-text-purple" }) }) }),
3725
+ /* @__PURE__ */ jsxs20("div", { className: "fi-stack-sm", children: [
3726
+ /* @__PURE__ */ jsxs20("h3", { className: "chat-start-title-large", children: [
3727
+ "Hola, ",
3728
+ userName?.split(" ")[0] || "Doctor"
3729
+ ] }),
3730
+ /* @__PURE__ */ jsx26("p", { className: "chat-start-subtitle", children: "Soy tu asistente de Free Intelligence. Estoy listo para ayudarte con consultas m\xE9dicas, notas SOAP y an\xE1lisis cl\xEDnicos." })
3731
+ ] }),
3732
+ /* @__PURE__ */ jsxs20("div", { className: "chat-start-features", children: [
3733
+ /* @__PURE__ */ jsxs20("div", { className: "chat-start-feature", children: [
3734
+ /* @__PURE__ */ jsx26(MessageSquareText, { className: "w-4 h-4 fi-text-purple flex-shrink-0" }),
3735
+ /* @__PURE__ */ jsx26("span", { children: "Conversaci\xF3n privada y segura" })
3736
+ ] }),
3737
+ /* @__PURE__ */ jsxs20("div", { className: "chat-start-feature", children: [
3738
+ /* @__PURE__ */ jsx26(Shield, { className: "w-4 h-4 fi-text-green flex-shrink-0" }),
3739
+ /* @__PURE__ */ jsx26("span", { children: "Datos encriptados localmente" })
3740
+ ] })
3741
+ ] }),
3742
+ /* @__PURE__ */ jsx26("button", { onClick: onStart, disabled: isLoading, className: "chat-start-btn-begin", children: isLoading ? /* @__PURE__ */ jsxs20(Fragment6, { children: [
3743
+ /* @__PURE__ */ jsx26("div", { className: "chat-start-spinner" }),
3744
+ "Iniciando..."
3745
+ ] }) : /* @__PURE__ */ jsxs20(Fragment6, { children: [
3746
+ /* @__PURE__ */ jsx26(MessageSquareText, { className: "w-5 h-5" }),
3747
+ "Comenzar conversaci\xF3n"
3748
+ ] }) }),
3749
+ /* @__PURE__ */ jsx26("p", { className: "chat-start-hint", children: "Presiona para iniciar una nueva conversaci\xF3n" })
3750
+ ] }) });
3751
+ }
3752
+
3753
+ // src/shell/ChatContent.tsx
3754
+ import { jsx as jsx27, jsxs as jsxs21 } from "react/jsx-runtime";
3755
+ function ChatContent({
3756
+ config,
3757
+ embedded,
3758
+ isAuthenticated,
3759
+ userName,
3760
+ viewMode,
3761
+ isHistoryOpen,
3762
+ isStartingConversation,
3763
+ messageCount,
3764
+ loading,
3765
+ isTyping,
3766
+ loadingInitial,
3767
+ customEmptyState,
3768
+ customQuickReplies,
3769
+ message,
3770
+ responseMode,
3771
+ selectedPersona,
3772
+ personaName,
3773
+ showThinking = true,
3774
+ voiceState,
3775
+ uploadFile,
3776
+ uploadStatus,
3777
+ isUploadActive,
3778
+ onNavigate,
3779
+ onModeChange,
3780
+ onMinimize,
3781
+ onMaximize,
3782
+ onToggleDenseMode,
3783
+ onClose,
3784
+ onHistoryOpen,
3785
+ onHistoryClose,
3786
+ onStartConversation,
3787
+ onLogin,
3788
+ onMessageChange,
3789
+ onSend,
3790
+ onResponseModeToggle,
3791
+ onShowThinkingToggle,
3792
+ onPersonaChange: _onPersonaChange,
3793
+ onClearConversation,
3794
+ onVoiceStart,
3795
+ onVoiceStop,
3796
+ onAttach,
3797
+ onCancelUpload,
3798
+ onCopyCurl,
3799
+ personaSelector,
3800
+ renderHistory,
3801
+ renderMessages
3802
+ }) {
3803
+ const dynamicPlaceholder = personaName ? `Escribe a ${personaName}...` : "Escribe tu mensaje...";
3804
+ const showVoice = typeof onVoiceStart === "function";
3805
+ const showAttach = typeof onAttach === "function";
3806
+ const showResponseMode = typeof onResponseModeToggle === "function";
3807
+ const showThinkingToggle = typeof onShowThinkingToggle === "function";
3808
+ const showClear = typeof onClearConversation === "function";
3809
+ const showPersonaSelector = personaSelector != null;
3810
+ return /* @__PURE__ */ jsxs21("div", { className: "relative flex h-full flex-1 flex-col overflow-hidden", children: [
3811
+ !isHistoryOpen && /* @__PURE__ */ jsxs21(
3812
+ ChatWidgetContainer,
3813
+ {
3814
+ mode: viewMode,
3815
+ title: config.title,
3816
+ embedded,
3817
+ onModeChange,
3818
+ children: [
3819
+ viewMode !== "dense" && !embedded && /* @__PURE__ */ jsx27(
3820
+ ChatWidgetHeader,
3821
+ {
3822
+ title: config.title,
3823
+ subtitle: config.subtitle,
3824
+ backgroundClass: config.theme.background.header,
3825
+ mode: viewMode,
3826
+ showControls: !embedded,
3827
+ onNavigate,
3828
+ onMinimize,
3829
+ onMaximize,
3830
+ onToggleDenseMode,
3831
+ onClose,
3832
+ onHistorySearch: onHistoryOpen
3833
+ }
3834
+ ),
3835
+ messageCount === 0 && loadingInitial ? /* @__PURE__ */ jsx27("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx27(Loader213, { className: "h-8 w-8 animate-spin text-slate-400" }) }) : messageCount === 0 && !isTyping && customEmptyState ? customEmptyState : messageCount === 0 && !isTyping ? /* @__PURE__ */ jsx27(
3836
+ ChatStartScreen,
3837
+ {
3838
+ isAuthenticated,
3839
+ userName,
3840
+ onStart: onStartConversation,
3841
+ onLogin,
3842
+ onNavigate,
3843
+ isLoading: isStartingConversation
3844
+ }
3845
+ ) : renderMessages?.({ viewMode }),
3846
+ customQuickReplies,
3847
+ viewMode !== "dense" && /* @__PURE__ */ jsx27("div", { className: "chat-input-wrapper", children: /* @__PURE__ */ jsxs21("div", { className: "chat-input-floating-box", children: [
3848
+ isUploadActive && uploadFile && /* @__PURE__ */ jsx27(
3849
+ ChatFilePreview,
3850
+ {
3851
+ file: uploadFile,
3852
+ status: uploadStatus ?? "selecting",
3853
+ onCancel: onCancelUpload ?? (() => {
3854
+ })
3855
+ }
3856
+ ),
3857
+ /* @__PURE__ */ jsx27(
3858
+ Composer,
3859
+ {
3860
+ message,
3861
+ loading,
3862
+ placeholder: dynamicPlaceholder,
3863
+ onMessageChange,
3864
+ onSend,
3865
+ maxRows: 5,
3866
+ areaClassName: "chat-input-area-top",
3867
+ wrapperClassName: "flex-1",
3868
+ textareaClassName: "chat-textarea"
3869
+ }
3870
+ ),
3871
+ /* @__PURE__ */ jsx27(
3872
+ ChatToolbar,
3873
+ {
3874
+ responseMode,
3875
+ selectedPersona,
3876
+ showThinking,
3877
+ voiceRecording: voiceState,
3878
+ personaSelector,
3879
+ showAttach,
3880
+ showLanguage: false,
3881
+ showFormatting: false,
3882
+ showResponseMode,
3883
+ showVoice,
3884
+ showPersonaSelector,
3885
+ showThinkingToggle,
3886
+ showClear,
3887
+ showCopyCurl: typeof onCopyCurl === "function",
3888
+ onResponseModeToggle,
3889
+ onShowThinkingToggle,
3890
+ onClearConversation,
3891
+ onCopyCurl,
3892
+ onAttach,
3893
+ onVoiceStart,
3894
+ onVoiceStop,
3895
+ onSend,
3896
+ canSend: message.trim().length > 0 && !loading,
3897
+ sendLoading: loading
3898
+ }
3899
+ )
3900
+ ] }) })
3901
+ ]
3902
+ }
3903
+ ),
3904
+ isHistoryOpen && renderHistory?.({ onClose: onHistoryClose })
3905
+ ] });
3906
+ }
3907
+
3908
+ // src/shell/ChatWidget.tsx
3909
+ import { jsx as jsx28 } from "react/jsx-runtime";
3910
+ function ChatWidget({
3911
+ chatHook,
3912
+ config: customConfig,
3913
+ user,
3914
+ isAuthenticated = false,
3915
+ onLogin,
3916
+ onNavigate,
3917
+ isMobile: isMobileProp,
3918
+ initialOpen = false,
3919
+ initialMode = "normal",
3920
+ embedded = false,
3921
+ message,
3922
+ onMessageChange,
3923
+ onSend,
3924
+ responseMode,
3925
+ selectedPersona,
3926
+ personaName,
3927
+ showThinking,
3928
+ onResponseModeToggle,
3929
+ onShowThinkingToggle,
3930
+ onPersonaChange,
3931
+ onClearConversation,
3932
+ voiceState,
3933
+ onVoiceStart,
3934
+ onVoiceStop,
3935
+ uploadFile,
3936
+ uploadStatus,
3937
+ isUploadActive,
3938
+ onAttach,
3939
+ onCancelUpload,
3940
+ isStartingConversation = false,
3941
+ onStartConversation,
3942
+ personaSelector,
3943
+ renderHistory,
3944
+ renderMessages,
3945
+ onCopyCurl
3946
+ }) {
3947
+ const internalIsMobile = useMediaQuery(CHAT_BREAKPOINTS.mobile, { ssrMatch: false });
3948
+ const isMobile = isMobileProp ?? internalIsMobile;
3949
+ const config = mergeChatConfig(customConfig);
3950
+ const widgetState = useChatWidgetState({ initialOpen, initialMode });
3951
+ const messages = chatHook.messages;
3952
+ const messageCount = messages.length;
3953
+ const loading = chatHook.loading;
3954
+ const isTyping = chatHook.isTyping;
3955
+ const loadingInitial = chatHook.loadingInitial ?? false;
3956
+ const customEmptyState = chatHook.customEmptyState;
3957
+ const customQuickReplies = chatHook.customQuickReplies;
3958
+ const handleOpen = useCallback9(() => {
3959
+ widgetState.open();
3960
+ widgetState.onMessagesLoaded(messageCount > 0);
3961
+ }, [widgetState, messageCount]);
3962
+ if (!widgetState.isOpen) {
3963
+ if (embedded) return null;
3964
+ return /* @__PURE__ */ jsx28(FloatingButton, { onClick: handleOpen, isMobile });
3965
+ }
3966
+ return /* @__PURE__ */ jsx28(
3967
+ ChatContent,
3968
+ {
3969
+ config,
3970
+ embedded,
3971
+ isAuthenticated,
3972
+ userName: user?.name || void 0,
3973
+ viewMode: widgetState.viewMode,
3974
+ isHistoryOpen: widgetState.isHistoryOpen,
3975
+ isStartingConversation,
3976
+ messageCount,
3977
+ loading,
3978
+ isTyping,
3979
+ loadingInitial,
3980
+ customEmptyState,
3981
+ customQuickReplies,
3982
+ message,
3983
+ responseMode,
3984
+ selectedPersona,
3985
+ personaName,
3986
+ showThinking,
3987
+ voiceState,
3988
+ uploadFile,
3989
+ uploadStatus,
3990
+ isUploadActive,
3991
+ onNavigate,
3992
+ onModeChange: widgetState.setViewMode,
3993
+ onMinimize: widgetState.minimize,
3994
+ onMaximize: widgetState.maximize,
3995
+ onToggleDenseMode: widgetState.toggleDenseMode,
3996
+ onClose: widgetState.close,
3997
+ onHistoryOpen: widgetState.openHistory,
3998
+ onHistoryClose: widgetState.closeHistory,
3999
+ onStartConversation: onStartConversation ?? widgetState.startConversation,
4000
+ onLogin: onLogin ?? (() => {
4001
+ }),
4002
+ onMessageChange,
4003
+ onSend,
4004
+ onResponseModeToggle,
4005
+ onShowThinkingToggle,
4006
+ onPersonaChange,
4007
+ onClearConversation,
4008
+ onVoiceStart,
4009
+ onVoiceStop,
4010
+ onAttach,
4011
+ onCancelUpload,
4012
+ onCopyCurl,
4013
+ personaSelector,
4014
+ renderHistory,
4015
+ renderMessages
4016
+ }
4017
+ );
4018
+ }
4019
+
4020
+ // src/shell/ChatSurface.tsx
4021
+ import { jsx as jsx29 } from "react/jsx-runtime";
4022
+ function ChatSurface(props) {
4023
+ return /* @__PURE__ */ jsx29(
4024
+ ChatWidget,
4025
+ {
4026
+ ...props,
4027
+ embedded: true,
4028
+ initialOpen: true,
4029
+ initialMode: "fullscreen"
4030
+ }
4031
+ );
4032
+ }
4033
+
4034
+ // src/persona-selector/PersonaSelector.tsx
4035
+ import {
4036
+ useCallback as useCallback10,
4037
+ useEffect as useEffect12,
4038
+ useId as useId2,
4039
+ useRef as useRef9,
4040
+ useState as useState15
4041
+ } from "react";
4042
+ import { createPortal as createPortal2 } from "react-dom";
4043
+ import { ChevronDown, Check as Check2 } from "lucide-react";
4044
+ import { Fragment as Fragment7, jsx as jsx30, jsxs as jsxs22 } from "react/jsx-runtime";
4045
+ var TRIGGER_DEFAULT = "flex w-full items-center justify-between rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-sm transition-colors";
4046
+ var CONTENT_BASE = "rounded-md border border-slate-700 bg-slate-800 p-1 shadow-lg";
4047
+ var ITEM_BASE = "cursor-pointer rounded-lg px-3 py-2 text-left transition-all";
4048
+ function PersonaSelector({
4049
+ personas,
4050
+ selected,
4051
+ onSelect,
4052
+ getPersonaId,
4053
+ loading = false,
4054
+ getPersonaLabel,
4055
+ getPersonaDescription,
4056
+ renderPersonaIcon,
4057
+ renderPersonaBadge,
4058
+ renderPersonaMeta,
4059
+ renderTriggerValue,
4060
+ renderHeader,
4061
+ renderFooter,
4062
+ renderLoading,
4063
+ placeholder = "Seleccionar...",
4064
+ className = "relative",
4065
+ triggerClassName,
4066
+ contentClassName = "",
4067
+ ariaLabel
4068
+ }) {
4069
+ const [isOpen, setIsOpen] = useState15(false);
4070
+ const [position, setPosition] = useState15({ top: 0, left: 0, width: 0 });
4071
+ const triggerRef = useRef9(null);
4072
+ const contentRef = useRef9(null);
4073
+ const reactId = useId2();
4074
+ const triggerId = `persona-trigger-${reactId}`;
4075
+ const contentId = `persona-content-${reactId}`;
4076
+ const close = useCallback10(() => setIsOpen(false), []);
4077
+ useEffect12(() => {
4078
+ if (!isOpen) return;
4079
+ const handle = (event) => {
4080
+ const target = event.target;
4081
+ if (triggerRef.current?.contains(target) || contentRef.current?.contains(target)) {
4082
+ return;
4083
+ }
4084
+ setIsOpen(false);
4085
+ };
4086
+ document.addEventListener("mousedown", handle);
4087
+ return () => document.removeEventListener("mousedown", handle);
4088
+ }, [isOpen]);
4089
+ useEffect12(() => {
4090
+ if (!isOpen) return;
4091
+ const trigger = triggerRef.current;
4092
+ if (!trigger) return;
4093
+ const rect = trigger.getBoundingClientRect();
4094
+ const baseTop = rect.bottom + window.scrollY + 4;
4095
+ const left = rect.left + window.scrollX;
4096
+ const width = rect.width;
4097
+ setPosition({ top: baseTop, left, width });
4098
+ const raf = requestAnimationFrame(() => {
4099
+ const el = contentRef.current;
4100
+ if (!el) return;
4101
+ const height = el.offsetHeight;
4102
+ const spaceBelow = window.innerHeight - rect.bottom;
4103
+ if (spaceBelow < height && rect.top > height) {
4104
+ setPosition({ top: rect.top + window.scrollY - height - 4, left, width });
4105
+ }
4106
+ });
4107
+ return () => cancelAnimationFrame(raf);
4108
+ }, [isOpen]);
4109
+ useEffect12(() => {
4110
+ if (!isOpen) return;
4111
+ const raf = requestAnimationFrame(() => {
4112
+ const content2 = contentRef.current;
4113
+ if (!content2) return;
4114
+ const sel = content2.querySelector(
4115
+ '[role="option"][aria-selected="true"]'
4116
+ );
4117
+ const first = content2.querySelector('[role="option"]');
4118
+ (sel || first)?.focus();
4119
+ });
4120
+ return () => cancelAnimationFrame(raf);
4121
+ }, [isOpen]);
4122
+ const handleOptionKeyDown = (event) => {
4123
+ const key = event.key;
4124
+ if (key === "Enter" || key === " ") {
4125
+ event.preventDefault();
4126
+ event.currentTarget.click();
4127
+ return;
4128
+ }
4129
+ if (key === "Escape") {
4130
+ event.preventDefault();
4131
+ setIsOpen(false);
4132
+ triggerRef.current?.focus();
4133
+ return;
4134
+ }
4135
+ if (key === "ArrowDown" || key === "ArrowUp") {
4136
+ event.preventDefault();
4137
+ const root = event.currentTarget.closest(
4138
+ "[data-persona-content]"
4139
+ );
4140
+ const options = root ? Array.from(root.querySelectorAll('[role="option"]')) : [];
4141
+ if (!options.length) return;
4142
+ const idx = options.indexOf(event.currentTarget);
4143
+ const nextIdx = key === "ArrowDown" ? (idx + 1) % options.length : (idx - 1 + options.length) % options.length;
4144
+ options[nextIdx]?.focus();
4145
+ }
4146
+ };
4147
+ if (loading) {
4148
+ return renderLoading ? /* @__PURE__ */ jsx30(Fragment7, { children: renderLoading() }) : /* @__PURE__ */ jsx30("div", { role: "status", "aria-live": "polite", children: "Cargando..." });
4149
+ }
4150
+ const selectedPersona = personas.find((p) => getPersonaId(p) === selected);
4151
+ const triggerInner = renderTriggerValue ? renderTriggerValue(selectedPersona, isOpen) : selectedPersona && getPersonaLabel ? getPersonaLabel(selectedPersona) : placeholder;
4152
+ const content = isOpen ? /* @__PURE__ */ jsxs22(
4153
+ "div",
4154
+ {
4155
+ ref: contentRef,
4156
+ id: contentId,
4157
+ role: "listbox",
4158
+ "aria-labelledby": triggerId,
4159
+ tabIndex: -1,
4160
+ "data-persona-content": true,
4161
+ style: {
4162
+ position: "fixed",
4163
+ top: `${position.top}px`,
4164
+ left: `${position.left}px`,
4165
+ minWidth: `${position.width}px`,
4166
+ zIndex: 9999
4167
+ },
4168
+ className: `${CONTENT_BASE} ${contentClassName}`.trim(),
4169
+ children: [
4170
+ renderHeader?.({ count: personas.length }),
4171
+ personas.map((persona) => {
4172
+ const id = getPersonaId(persona);
4173
+ const isSelected = id === selected;
4174
+ const ctx = { selected: isSelected };
4175
+ const badge = renderPersonaBadge?.(persona, ctx);
4176
+ const meta = renderPersonaMeta?.(persona);
4177
+ const description = getPersonaDescription?.(persona);
4178
+ return /* @__PURE__ */ jsxs22(
4179
+ "div",
4180
+ {
4181
+ role: "option",
4182
+ "aria-selected": isSelected,
4183
+ tabIndex: 0,
4184
+ onClick: () => {
4185
+ onSelect(id);
4186
+ setIsOpen(false);
4187
+ },
4188
+ onKeyDown: handleOptionKeyDown,
4189
+ className: `${ITEM_BASE} hover:bg-slate-700/60 ${isSelected ? "bg-purple-500/20 border-purple-500/50 border" : "bg-slate-700/30 border border-transparent"}`,
4190
+ children: [
4191
+ /* @__PURE__ */ jsxs22("div", { className: "flex items-center gap-2 mb-1", children: [
4192
+ renderPersonaIcon?.(persona, ctx),
4193
+ /* @__PURE__ */ jsx30(
4194
+ "span",
4195
+ {
4196
+ className: `font-medium text-sm ${isSelected ? "text-purple-200" : "text-slate-200"}`,
4197
+ children: getPersonaLabel?.(persona) ?? id
4198
+ }
4199
+ ),
4200
+ isSelected && /* @__PURE__ */ jsx30(Check2, { className: "w-4 h-4 fi-text-purple ml-auto" })
4201
+ ] }),
4202
+ description && /* @__PURE__ */ jsx30("p", { className: "fi-text-xs mb-2 line-clamp-2", children: description }),
4203
+ (badge || meta) && /* @__PURE__ */ jsxs22("div", { className: "flex items-center gap-2 flex-wrap", children: [
4204
+ badge,
4205
+ meta
4206
+ ] })
4207
+ ]
4208
+ },
4209
+ id
4210
+ );
4211
+ }),
4212
+ renderFooter?.({ close })
4213
+ ]
4214
+ }
4215
+ ) : null;
4216
+ return /* @__PURE__ */ jsxs22("div", { className, "data-persona-root": true, children: [
4217
+ /* @__PURE__ */ jsxs22(
4218
+ "button",
4219
+ {
4220
+ ref: triggerRef,
4221
+ id: triggerId,
4222
+ type: "button",
4223
+ onClick: () => setIsOpen((v) => !v),
4224
+ "aria-haspopup": "listbox",
4225
+ "aria-expanded": isOpen,
4226
+ "aria-controls": isOpen ? contentId : void 0,
4227
+ "aria-label": ariaLabel,
4228
+ className: triggerClassName ?? TRIGGER_DEFAULT,
4229
+ children: [
4230
+ triggerInner,
4231
+ /* @__PURE__ */ jsx30(
4232
+ ChevronDown,
4233
+ {
4234
+ className: `h-4 w-4 transition-transform ${isOpen ? "rotate-180" : ""}`
4235
+ }
4236
+ )
4237
+ ]
4238
+ }
4239
+ ),
4240
+ content && createPortal2(content, document.body)
4241
+ ] });
4242
+ }
4243
+ export {
4244
+ AUDIO_QUEUE_DEFAULTS,
4245
+ AudioDraftPlayer,
4246
+ AudioPlayer,
4247
+ AudioQueueItem,
4248
+ AudioQueuePanel,
4249
+ AudioQueueStore,
4250
+ AudioVisualizer,
4251
+ AutoResizeTextarea,
4252
+ BUTTON_SIZES,
4253
+ CHAT_BREAKPOINTS,
4254
+ COLOR_THEMES,
4255
+ ChatContent,
4256
+ ChatFilePreview,
4257
+ ChatStartScreen,
4258
+ ChatSurface,
4259
+ ChatToolbar,
4260
+ ChatWidget,
4261
+ ChatWidgetContainer,
4262
+ ChatWidgetHeader,
4263
+ CollapsibleText,
4264
+ Composer,
4265
+ ComposerMicSlot,
4266
+ CopyButton,
4267
+ FloatingButton,
4268
+ MessageBubble,
4269
+ MessageContent,
4270
+ MessageList,
4271
+ PersonaSelector,
4272
+ PulseRings,
4273
+ RecordingButton,
4274
+ RecordingTimer,
4275
+ RichAudioPlayer,
4276
+ STATUS_TEXT_EN,
4277
+ STATUS_TEXT_ES,
4278
+ SpeakButton,
4279
+ StatusText,
4280
+ VoiceMicButton,
4281
+ artifactLabel,
4282
+ clearMediaQueryCache,
4283
+ createAudioPlayer,
4284
+ defaultAnimationConfig,
4285
+ defaultBehavior,
4286
+ defaultChatConfig,
4287
+ defaultTheme,
4288
+ defaultTimestampConfig,
4289
+ formatArtifactDuration,
4290
+ formatArtifactSize,
4291
+ formatPlaybackTime,
4292
+ formatRecordingTime,
4293
+ glassTheme,
4294
+ isPending,
4295
+ isTerminal,
4296
+ makeArtifactId,
4297
+ makeRecorder,
4298
+ markdownStyles,
4299
+ mergeChatConfig,
4300
+ mergeWavBlobs,
4301
+ messageStyles,
4302
+ normalizeLevels,
4303
+ normalizeStreamedMarkdown,
4304
+ resampleLevels,
4305
+ useAudioAnalysis,
4306
+ useAudioPlayer,
4307
+ useAudioQueue,
4308
+ useBreakpoints,
4309
+ useChatWidgetState,
4310
+ useDictation,
4311
+ useDurableRecording,
4312
+ useMediaQuery,
4313
+ useRecorder,
4314
+ useVoice
4315
+ };
4316
+ //# sourceMappingURL=index.js.map