@sesionario/blocks 1.5.0 → 1.7.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.cjs CHANGED
@@ -9,6 +9,7 @@ var classVarianceAuthority = require('class-variance-authority');
9
9
  var jsxRuntime = require('react/jsx-runtime');
10
10
  var AlertDialogPrimitive = require('@radix-ui/react-alert-dialog');
11
11
  var reactSlot = require('@radix-ui/react-slot');
12
+ var reactDom = require('react-dom');
12
13
  var nextThemes = require('next-themes');
13
14
  var framerMotion = require('framer-motion');
14
15
  var DropdownMenuPrimitive = require('@radix-ui/react-dropdown-menu');
@@ -455,6 +456,301 @@ function ConfirmDestructiveDialog({
455
456
  ] })
456
457
  ] }) });
457
458
  }
459
+ var MIN_SCALE = 1;
460
+ var MAX_SCALE = 4;
461
+ var DOUBLE_TAP_MS = 300;
462
+ var IDENTITY = { scale: 1, tx: 0, ty: 0 };
463
+ function clamp(value, min, max) {
464
+ return Math.min(max, Math.max(min, value));
465
+ }
466
+ function zoomToward(prev, nextScale, originX, originY) {
467
+ const scale = clamp(nextScale, MIN_SCALE, MAX_SCALE);
468
+ if (scale === MIN_SCALE) return IDENTITY;
469
+ const ratio = scale / prev.scale;
470
+ return {
471
+ scale,
472
+ tx: originX - (originX - prev.tx) * ratio,
473
+ ty: originY - (originY - prev.ty) * ratio
474
+ };
475
+ }
476
+ function pointerDistance(a, b) {
477
+ return Math.hypot(b.x - a.x, b.y - a.y);
478
+ }
479
+ function ImageLightbox({
480
+ images,
481
+ index,
482
+ onIndexChange,
483
+ onClose,
484
+ labels
485
+ }) {
486
+ const ariaLabel = labels?.ariaLabel ?? "Visor de im\xE1genes";
487
+ const closeLabel = labels?.close ?? "Cerrar";
488
+ const previousLabel = labels?.previous ?? "Anterior";
489
+ const nextLabel = labels?.next ?? "Siguiente";
490
+ const hasMultiple = images.length > 1;
491
+ const [transform, setTransform] = React6.useState(IDENTITY);
492
+ const transformRef = React6.useRef(transform);
493
+ transformRef.current = transform;
494
+ const stageRef = React6.useRef(null);
495
+ const pointersRef = React6.useRef(/* @__PURE__ */ new Map());
496
+ const pinchStartRef = React6.useRef(null);
497
+ const panRef = React6.useRef(null);
498
+ const lastTapRef = React6.useRef(
499
+ null
500
+ );
501
+ const resetZoom = React6.useCallback(() => {
502
+ setTransform(IDENTITY);
503
+ }, []);
504
+ React6.useEffect(() => {
505
+ resetZoom();
506
+ }, [index, images[index], resetZoom]);
507
+ function goPrev() {
508
+ onIndexChange((index - 1 + images.length) % images.length);
509
+ }
510
+ function goNext() {
511
+ onIndexChange((index + 1) % images.length);
512
+ }
513
+ React6.useEffect(() => {
514
+ function handleKeyDown(e) {
515
+ if (e.key === "Escape") {
516
+ onClose();
517
+ return;
518
+ }
519
+ if (!hasMultiple) return;
520
+ if (e.key === "ArrowLeft") {
521
+ onIndexChange((index - 1 + images.length) % images.length);
522
+ } else if (e.key === "ArrowRight") {
523
+ onIndexChange((index + 1) % images.length);
524
+ }
525
+ }
526
+ window.addEventListener("keydown", handleKeyDown);
527
+ return () => window.removeEventListener("keydown", handleKeyDown);
528
+ }, [index, images.length, hasMultiple, onClose, onIndexChange]);
529
+ React6.useEffect(() => {
530
+ const previousOverflow = document.body.style.overflow;
531
+ document.body.style.overflow = "hidden";
532
+ return () => {
533
+ document.body.style.overflow = previousOverflow;
534
+ };
535
+ }, []);
536
+ const stageOrigin = React6.useCallback((clientX, clientY) => {
537
+ const stage = stageRef.current;
538
+ if (!stage) return { x: 0, y: 0 };
539
+ const rect = stage.getBoundingClientRect();
540
+ return {
541
+ x: clientX - rect.left - rect.width / 2,
542
+ y: clientY - rect.top - rect.height / 2
543
+ };
544
+ }, []);
545
+ React6.useEffect(() => {
546
+ const stage = stageRef.current;
547
+ if (!stage) return;
548
+ const handleWheel = (e) => {
549
+ e.preventDefault();
550
+ e.stopPropagation();
551
+ const prev = transformRef.current;
552
+ const factor = e.deltaY > 0 ? 0.9 : 1.1;
553
+ const { x, y } = stageOrigin(e.clientX, e.clientY);
554
+ setTransform(zoomToward(prev, prev.scale * factor, x, y));
555
+ };
556
+ stage.addEventListener("wheel", handleWheel, { passive: false });
557
+ return () => stage.removeEventListener("wheel", handleWheel);
558
+ }, [stageOrigin]);
559
+ function beginPinch() {
560
+ const pts = [...pointersRef.current.values()];
561
+ const [a, b] = pts;
562
+ if (!a || !b) return;
563
+ const midX = (a.x + b.x) / 2;
564
+ const midY = (a.y + b.y) / 2;
565
+ const { x, y } = stageOrigin(midX, midY);
566
+ pinchStartRef.current = {
567
+ distance: Math.max(pointerDistance(a, b), 1),
568
+ originX: x,
569
+ originY: y,
570
+ transform: { ...transformRef.current }
571
+ };
572
+ panRef.current = null;
573
+ }
574
+ function onPointerDown(e) {
575
+ e.stopPropagation();
576
+ const stage = stageRef.current;
577
+ if (!stage) return;
578
+ stage.setPointerCapture(e.pointerId);
579
+ pointersRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
580
+ if (pointersRef.current.size === 2) {
581
+ beginPinch();
582
+ return;
583
+ }
584
+ if (transformRef.current.scale > MIN_SCALE) {
585
+ panRef.current = {
586
+ pointerId: e.pointerId,
587
+ startX: e.clientX,
588
+ startY: e.clientY,
589
+ originTx: transformRef.current.tx,
590
+ originTy: transformRef.current.ty,
591
+ moved: false
592
+ };
593
+ }
594
+ }
595
+ function onPointerMove(e) {
596
+ if (!pointersRef.current.has(e.pointerId)) return;
597
+ pointersRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
598
+ const pinchStart = pinchStartRef.current;
599
+ if (pointersRef.current.size >= 2 && pinchStart) {
600
+ const pts = [...pointersRef.current.values()];
601
+ const [a, b] = pts;
602
+ if (!a || !b) return;
603
+ const distance = Math.max(pointerDistance(a, b), 1);
604
+ const nextScale = pinchStart.transform.scale * (distance / pinchStart.distance);
605
+ setTransform(
606
+ zoomToward(
607
+ pinchStart.transform,
608
+ nextScale,
609
+ pinchStart.originX,
610
+ pinchStart.originY
611
+ )
612
+ );
613
+ return;
614
+ }
615
+ const pan = panRef.current;
616
+ if (pan && pan.pointerId === e.pointerId) {
617
+ const dx = e.clientX - pan.startX;
618
+ const dy = e.clientY - pan.startY;
619
+ if (Math.abs(dx) > 2 || Math.abs(dy) > 2) pan.moved = true;
620
+ setTransform((prev) => ({
621
+ ...prev,
622
+ tx: pan.originTx + dx,
623
+ ty: pan.originTy + dy
624
+ }));
625
+ }
626
+ }
627
+ function onPointerUp(e) {
628
+ const stage = stageRef.current;
629
+ if (stage?.hasPointerCapture(e.pointerId)) {
630
+ stage.releasePointerCapture(e.pointerId);
631
+ }
632
+ pointersRef.current.delete(e.pointerId);
633
+ if (pointersRef.current.size < 2) {
634
+ pinchStartRef.current = null;
635
+ }
636
+ if (pointersRef.current.size === 1) {
637
+ const remaining = [...pointersRef.current.entries()][0];
638
+ if (remaining && transformRef.current.scale > MIN_SCALE) {
639
+ const [pointerId, point] = remaining;
640
+ panRef.current = {
641
+ pointerId,
642
+ startX: point.x,
643
+ startY: point.y,
644
+ originTx: transformRef.current.tx,
645
+ originTy: transformRef.current.ty,
646
+ moved: true
647
+ };
648
+ }
649
+ }
650
+ const pan = panRef.current;
651
+ if (pan && pan.pointerId === e.pointerId) {
652
+ const wasMoved = pan.moved;
653
+ panRef.current = null;
654
+ if (wasMoved) return;
655
+ }
656
+ if (pointersRef.current.size === 0 && e.button === 0) {
657
+ const now = Date.now();
658
+ const last = lastTapRef.current;
659
+ if (last && now - last.time < DOUBLE_TAP_MS && Math.hypot(e.clientX - last.x, e.clientY - last.y) < 24) {
660
+ lastTapRef.current = null;
661
+ resetZoom();
662
+ return;
663
+ }
664
+ lastTapRef.current = { time: now, x: e.clientX, y: e.clientY };
665
+ }
666
+ }
667
+ function stopDialogClose(e) {
668
+ e.stopPropagation();
669
+ }
670
+ const { scale, tx, ty } = transform;
671
+ return reactDom.createPortal(
672
+ /* @__PURE__ */ jsxRuntime.jsxs(
673
+ "div",
674
+ {
675
+ className: "fixed inset-x-0 top-0 z-50 flex h-dvh items-center justify-center bg-black/90 p-4",
676
+ onClick: onClose,
677
+ role: "dialog",
678
+ "aria-modal": "true",
679
+ "aria-label": ariaLabel,
680
+ children: [
681
+ /* @__PURE__ */ jsxRuntime.jsx(
682
+ "button",
683
+ {
684
+ type: "button",
685
+ onClick: onClose,
686
+ "aria-label": closeLabel,
687
+ className: "absolute right-4 top-4 z-10 rounded-full bg-black/50 p-2 text-white transition-colors hover:bg-black/70",
688
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "h-5 w-5" })
689
+ }
690
+ ),
691
+ hasMultiple && /* @__PURE__ */ jsxRuntime.jsx(
692
+ "button",
693
+ {
694
+ type: "button",
695
+ onClick: (e) => {
696
+ e.stopPropagation();
697
+ goPrev();
698
+ },
699
+ "aria-label": previousLabel,
700
+ className: "absolute left-4 top-1/2 z-10 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white transition-colors hover:bg-black/70",
701
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronLeft, { className: "h-6 w-6" })
702
+ }
703
+ ),
704
+ /* @__PURE__ */ jsxRuntime.jsx(
705
+ "div",
706
+ {
707
+ ref: stageRef,
708
+ className: "relative flex max-h-full max-w-full touch-none items-center justify-center",
709
+ "data-scale": scale,
710
+ onClick: stopDialogClose,
711
+ onPointerDown,
712
+ onPointerMove,
713
+ onPointerUp,
714
+ onPointerCancel: onPointerUp,
715
+ children: /* @__PURE__ */ jsxRuntime.jsx(
716
+ "img",
717
+ {
718
+ src: images[index],
719
+ alt: "",
720
+ draggable: false,
721
+ className: "max-h-[calc(100dvh-2rem)] max-w-full select-none rounded-lg object-contain",
722
+ style: {
723
+ transform: `translate(${tx}px, ${ty}px) scale(${scale})`,
724
+ cursor: scale > MIN_SCALE ? "grab" : "default"
725
+ }
726
+ }
727
+ )
728
+ }
729
+ ),
730
+ hasMultiple && /* @__PURE__ */ jsxRuntime.jsx(
731
+ "button",
732
+ {
733
+ type: "button",
734
+ onClick: (e) => {
735
+ e.stopPropagation();
736
+ goNext();
737
+ },
738
+ "aria-label": nextLabel,
739
+ className: "absolute right-4 top-1/2 z-10 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white transition-colors hover:bg-black/70",
740
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronRight, { className: "h-6 w-6" })
741
+ }
742
+ ),
743
+ hasMultiple && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute bottom-4 left-1/2 z-10 -translate-x-1/2 rounded-full bg-black/50 px-3 py-1 text-xs text-white", children: [
744
+ index + 1,
745
+ " / ",
746
+ images.length
747
+ ] })
748
+ ]
749
+ }
750
+ ),
751
+ document.body
752
+ );
753
+ }
458
754
  var miniMenuContentClassName = "max-h-none overflow-x-visible overflow-y-visible";
459
755
  var miniMenuContentDefaults = {
460
756
  sideOffset: 8,
@@ -5071,6 +5367,635 @@ function ChatMessageList({
5071
5367
  /* @__PURE__ */ jsxRuntime.jsx(MessageScrollerButton, {})
5072
5368
  ] }) });
5073
5369
  }
5370
+ function useMediaQuery2(query) {
5371
+ const [matches, setMatches] = React6.useState(false);
5372
+ React6.useEffect(() => {
5373
+ if (typeof window === "undefined" || !window.matchMedia) return;
5374
+ const mql = window.matchMedia(query);
5375
+ const onChange = () => setMatches(mql.matches);
5376
+ onChange();
5377
+ mql.addEventListener("change", onChange);
5378
+ return () => mql.removeEventListener("change", onChange);
5379
+ }, [query]);
5380
+ return matches;
5381
+ }
5382
+ var RECONNECT_DELAY_MS = 2e3;
5383
+ function useSupportConversation({
5384
+ client,
5385
+ getWsUrl,
5386
+ conversationId: conversationIdProp,
5387
+ open = null,
5388
+ enabled = true,
5389
+ onConversationReady,
5390
+ onIncomingMessage
5391
+ }) {
5392
+ const [conversationId, setConversationId] = React6.useState(
5393
+ conversationIdProp
5394
+ );
5395
+ const [messages, setMessages] = React6.useState([]);
5396
+ const [loading, setLoading] = React6.useState(false);
5397
+ const [sending, setSending] = React6.useState(false);
5398
+ const [error, setError] = React6.useState(null);
5399
+ const socketRef = React6.useRef(null);
5400
+ const reconnectRef = React6.useRef(null);
5401
+ const closedByUser = React6.useRef(false);
5402
+ const onReadyRef = React6.useRef(onConversationReady);
5403
+ const onIncomingRef = React6.useRef(onIncomingMessage);
5404
+ onReadyRef.current = onConversationReady;
5405
+ onIncomingRef.current = onIncomingMessage;
5406
+ const load = React6.useCallback(async () => {
5407
+ if (!enabled) return;
5408
+ setLoading(true);
5409
+ setError(null);
5410
+ try {
5411
+ let id = conversationIdProp;
5412
+ if (!id && open) {
5413
+ const conv = await client.findOrCreateConversation(open);
5414
+ id = conv.id;
5415
+ }
5416
+ if (!id) {
5417
+ setConversationId(null);
5418
+ setMessages([]);
5419
+ return;
5420
+ }
5421
+ setConversationId(id);
5422
+ onReadyRef.current?.(id);
5423
+ const msgs = await client.listMessages(id);
5424
+ setMessages(msgs);
5425
+ await client.markRead(id);
5426
+ } catch (err) {
5427
+ setError(err instanceof Error ? err.message : "Chat load failed");
5428
+ } finally {
5429
+ setLoading(false);
5430
+ }
5431
+ }, [client, conversationIdProp, enabled, open]);
5432
+ React6.useEffect(() => {
5433
+ void load();
5434
+ }, [load]);
5435
+ React6.useEffect(() => {
5436
+ closedByUser.current = false;
5437
+ if (!enabled || !conversationId) return;
5438
+ let cancelled = false;
5439
+ const connect = async () => {
5440
+ const url = await getWsUrl(conversationId);
5441
+ if (!url || cancelled || closedByUser.current) return;
5442
+ const socket = new WebSocket(url);
5443
+ socketRef.current = socket;
5444
+ socket.onmessage = (event) => {
5445
+ let data;
5446
+ try {
5447
+ data = JSON.parse(String(event.data));
5448
+ } catch {
5449
+ return;
5450
+ }
5451
+ if (data.type === "message") {
5452
+ setMessages((prev) => {
5453
+ if (prev.some((m) => m.id === data.id)) return prev;
5454
+ return [...prev, data];
5455
+ });
5456
+ onIncomingRef.current?.(data);
5457
+ } else if (data.type === "deleted") {
5458
+ setMessages(
5459
+ (prev) => prev.map(
5460
+ (m) => m.id === data.id ? { ...m, deleted: true, body: "" } : m
5461
+ )
5462
+ );
5463
+ }
5464
+ };
5465
+ socket.onclose = () => {
5466
+ if (cancelled || closedByUser.current) return;
5467
+ reconnectRef.current = setTimeout(() => {
5468
+ void connect();
5469
+ }, RECONNECT_DELAY_MS);
5470
+ };
5471
+ };
5472
+ void connect();
5473
+ return () => {
5474
+ cancelled = true;
5475
+ closedByUser.current = true;
5476
+ if (reconnectRef.current) clearTimeout(reconnectRef.current);
5477
+ socketRef.current?.close();
5478
+ socketRef.current = null;
5479
+ };
5480
+ }, [conversationId, enabled, getWsUrl]);
5481
+ const send = React6.useCallback(
5482
+ async (text) => {
5483
+ const trimmed = text.trim();
5484
+ if (!conversationId || !trimmed || sending) return;
5485
+ setSending(true);
5486
+ setError(null);
5487
+ try {
5488
+ const msg = await client.sendMessage(conversationId, trimmed);
5489
+ setMessages((prev) => {
5490
+ if (prev.some((m) => m.id === msg.id)) return prev;
5491
+ return [...prev, msg];
5492
+ });
5493
+ await client.markRead(conversationId);
5494
+ } catch (err) {
5495
+ setError(err instanceof Error ? err.message : "Send failed");
5496
+ throw err;
5497
+ } finally {
5498
+ setSending(false);
5499
+ }
5500
+ },
5501
+ [client, conversationId, sending]
5502
+ );
5503
+ return {
5504
+ conversationId,
5505
+ messages,
5506
+ loading,
5507
+ sending,
5508
+ error,
5509
+ send,
5510
+ reload: load
5511
+ };
5512
+ }
5513
+ var SupportMessengerContext = React6.createContext(null);
5514
+ function useSupportMessenger() {
5515
+ const ctx = React6.useContext(SupportMessengerContext);
5516
+ if (!ctx) {
5517
+ throw new Error(
5518
+ "useSupportMessenger must be used within SupportMessengerProvider"
5519
+ );
5520
+ }
5521
+ return ctx;
5522
+ }
5523
+ function useSupportMessengerOptional() {
5524
+ return React6.useContext(SupportMessengerContext);
5525
+ }
5526
+ function ThreadPanel({
5527
+ thread,
5528
+ client,
5529
+ getWsUrl,
5530
+ currentUserId,
5531
+ labels,
5532
+ emojiLocale,
5533
+ onClose,
5534
+ onBack,
5535
+ showBack,
5536
+ onConversationReady,
5537
+ className
5538
+ }) {
5539
+ const [draft, setDraft] = React6.useState("");
5540
+ const { messages, loading, sending, error, send } = useSupportConversation({
5541
+ client,
5542
+ getWsUrl,
5543
+ conversationId: thread.conversationId ?? null,
5544
+ open: thread.open ?? null,
5545
+ onConversationReady
5546
+ });
5547
+ async function onSubmit(e) {
5548
+ e.preventDefault();
5549
+ const text = draft.trim();
5550
+ if (!text) return;
5551
+ setDraft("");
5552
+ try {
5553
+ await send(text);
5554
+ } catch {
5555
+ setDraft(text);
5556
+ }
5557
+ }
5558
+ return /* @__PURE__ */ jsxRuntime.jsxs(
5559
+ "div",
5560
+ {
5561
+ className: cn(
5562
+ "flex h-full min-h-0 flex-col overflow-hidden rounded-xl border bg-card shadow-lg",
5563
+ className
5564
+ ),
5565
+ children: [
5566
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1 border-b px-2 py-2", children: [
5567
+ showBack && onBack ? /* @__PURE__ */ jsxRuntime.jsx(
5568
+ Button,
5569
+ {
5570
+ type: "button",
5571
+ variant: "ghost",
5572
+ size: "icon-sm",
5573
+ onClick: onBack,
5574
+ "aria-label": labels.back,
5575
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronLeft, { className: "size-4" })
5576
+ }
5577
+ ) : null,
5578
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "min-w-0 flex-1 px-1", children: [
5579
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "truncate text-sm font-semibold", children: thread.title }),
5580
+ thread.subtitle ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "truncate text-xs text-muted-foreground", children: thread.subtitle }) : null
5581
+ ] }),
5582
+ /* @__PURE__ */ jsxRuntime.jsx(
5583
+ Button,
5584
+ {
5585
+ type: "button",
5586
+ variant: "ghost",
5587
+ size: "icon-sm",
5588
+ onClick: onClose,
5589
+ "aria-label": labels.close,
5590
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "size-4" })
5591
+ }
5592
+ )
5593
+ ] }),
5594
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "min-h-0 flex-1", children: loading ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-full items-center justify-center p-6", children: /* @__PURE__ */ jsxRuntime.jsx(LoadingState, { label: labels.loading, className: "py-0" }) }) : error ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "p-4 text-sm text-destructive", role: "alert", children: error }) : /* @__PURE__ */ jsxRuntime.jsx(
5595
+ ChatMessageList,
5596
+ {
5597
+ messages,
5598
+ currentUserId,
5599
+ emptyDescription: labels.emptyThread
5600
+ }
5601
+ ) }),
5602
+ /* @__PURE__ */ jsxRuntime.jsxs("form", { className: "flex gap-2 border-t p-3", onSubmit, children: [
5603
+ /* @__PURE__ */ jsxRuntime.jsx(
5604
+ EmojiTextarea,
5605
+ {
5606
+ locale: emojiLocale,
5607
+ value: draft,
5608
+ onChange: (e) => setDraft(e.target.value.slice(0, 2e3)),
5609
+ placeholder: labels.placeholder,
5610
+ "aria-label": labels.placeholder,
5611
+ disabled: loading || sending,
5612
+ maxLength: 2e3,
5613
+ rows: 2,
5614
+ className: "min-h-10 flex-1"
5615
+ }
5616
+ ),
5617
+ /* @__PURE__ */ jsxRuntime.jsx(Button, { type: "submit", disabled: !draft.trim() || sending || loading, children: labels.send })
5618
+ ] })
5619
+ ]
5620
+ }
5621
+ );
5622
+ }
5623
+ function ListPanel({
5624
+ items,
5625
+ labels,
5626
+ tabs,
5627
+ activeTab,
5628
+ onTabChange,
5629
+ onSelect,
5630
+ onClose,
5631
+ searchThreshold,
5632
+ className
5633
+ }) {
5634
+ const [query, setQuery] = React6.useState("");
5635
+ const showSearch = items.length >= searchThreshold;
5636
+ const filtered = React6.useMemo(() => {
5637
+ const q = query.trim().toLowerCase();
5638
+ if (!q) return items;
5639
+ return items.filter(
5640
+ (item) => item.title.toLowerCase().includes(q) || (item.subtitle?.toLowerCase().includes(q) ?? false)
5641
+ );
5642
+ }, [items, query]);
5643
+ return /* @__PURE__ */ jsxRuntime.jsxs(
5644
+ "div",
5645
+ {
5646
+ className: cn(
5647
+ "flex h-full min-h-0 flex-col overflow-hidden rounded-xl border bg-card shadow-lg",
5648
+ className
5649
+ ),
5650
+ children: [
5651
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between border-b px-3 py-2", children: [
5652
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-semibold", children: labels.listTitle }),
5653
+ /* @__PURE__ */ jsxRuntime.jsx(
5654
+ Button,
5655
+ {
5656
+ type: "button",
5657
+ variant: "ghost",
5658
+ size: "icon-sm",
5659
+ onClick: onClose,
5660
+ "aria-label": labels.close,
5661
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "size-4" })
5662
+ }
5663
+ )
5664
+ ] }),
5665
+ tabs && tabs.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex gap-1 border-b p-2", children: tabs.map((tab) => /* @__PURE__ */ jsxRuntime.jsx(
5666
+ Button,
5667
+ {
5668
+ type: "button",
5669
+ size: "sm",
5670
+ variant: activeTab === tab.id ? "default" : "outline",
5671
+ onClick: () => onTabChange?.(tab.id),
5672
+ children: tab.label
5673
+ },
5674
+ tab.id
5675
+ )) }) : null,
5676
+ showSearch ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-b p-2", children: /* @__PURE__ */ jsxRuntime.jsxs("label", { className: "relative block", children: [
5677
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Search, { className: "pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" }),
5678
+ /* @__PURE__ */ jsxRuntime.jsx(
5679
+ "input",
5680
+ {
5681
+ value: query,
5682
+ onChange: (e) => setQuery(e.target.value),
5683
+ placeholder: labels.searchPlaceholder ?? "Buscar\u2026",
5684
+ className: "h-8 w-full rounded-md border bg-transparent pr-2 pl-8 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
5685
+ }
5686
+ )
5687
+ ] }) }) : null,
5688
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "min-h-0 flex-1 overflow-y-auto p-1", children: filtered.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("li", { className: "px-3 py-8 text-center text-sm text-muted-foreground", children: labels.emptyList }) : filtered.map((item) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: /* @__PURE__ */ jsxRuntime.jsxs(
5689
+ "button",
5690
+ {
5691
+ type: "button",
5692
+ className: "flex w-full items-center gap-3 rounded-lg px-2 py-2.5 text-left transition-colors hover:bg-muted/80",
5693
+ onClick: () => onSelect(item),
5694
+ children: [
5695
+ /* @__PURE__ */ jsxRuntime.jsx(
5696
+ "span",
5697
+ {
5698
+ className: "flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-full text-xs font-semibold text-white",
5699
+ style: item.avatarUrl ? void 0 : avatarFallbackStyle(item.title),
5700
+ children: item.avatarUrl ? /* @__PURE__ */ jsxRuntime.jsx(
5701
+ "img",
5702
+ {
5703
+ src: item.avatarUrl,
5704
+ alt: "",
5705
+ className: "size-full object-cover"
5706
+ }
5707
+ ) : getInitials(item.title)
5708
+ }
5709
+ ),
5710
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "min-w-0 flex-1", children: [
5711
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block truncate text-sm font-medium", children: item.title }),
5712
+ item.subtitle ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block truncate text-xs text-muted-foreground", children: item.subtitle }) : null
5713
+ ] }),
5714
+ (item.unreadCount ?? 0) > 0 ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "rounded-full bg-primary px-2 py-0.5 text-[10px] font-semibold text-primary-foreground", children: (item.unreadCount ?? 0) > 99 ? "99+" : item.unreadCount }) : null
5715
+ ]
5716
+ }
5717
+ ) }, item.key)) })
5718
+ ]
5719
+ }
5720
+ );
5721
+ }
5722
+ function SupportMessengerProvider({
5723
+ children,
5724
+ client,
5725
+ getWsUrl,
5726
+ currentUserId,
5727
+ items,
5728
+ labels,
5729
+ enabled = true,
5730
+ forceMinimized = false,
5731
+ emojiLocale = "es",
5732
+ tabs,
5733
+ activeTab,
5734
+ onTabChange,
5735
+ onRefreshItems,
5736
+ searchThreshold = 8,
5737
+ className
5738
+ }) {
5739
+ const isMobile = useMediaQuery2("(max-width: 767px)");
5740
+ const [listOpen, setListOpen] = React6.useState(false);
5741
+ const [threads, setThreads] = React6.useState([]);
5742
+ const [mobileThreadKey, setMobileThreadKey] = React6.useState(null);
5743
+ const totalUnread = React6.useMemo(
5744
+ () => items.reduce((sum, item) => sum + (item.unreadCount ?? 0), 0),
5745
+ [items]
5746
+ );
5747
+ React6.useEffect(() => {
5748
+ if (!forceMinimized) return;
5749
+ setListOpen(false);
5750
+ setThreads([]);
5751
+ setMobileThreadKey(null);
5752
+ }, [forceMinimized]);
5753
+ const openList = React6.useCallback(() => {
5754
+ setListOpen(true);
5755
+ void onRefreshItems?.();
5756
+ }, [onRefreshItems]);
5757
+ const closeList = React6.useCallback(() => setListOpen(false), []);
5758
+ const toggleList = React6.useCallback(() => {
5759
+ setListOpen((prev) => {
5760
+ const next = !prev;
5761
+ if (next) void onRefreshItems?.();
5762
+ return next;
5763
+ });
5764
+ }, [onRefreshItems]);
5765
+ const openThread = React6.useCallback((req) => {
5766
+ setListOpen(false);
5767
+ setThreads((prev) => {
5768
+ const existing = prev.find((t) => t.key === req.key);
5769
+ if (existing) {
5770
+ return [
5771
+ ...prev.filter((t) => t.key !== req.key),
5772
+ { ...existing, ...req }
5773
+ ];
5774
+ }
5775
+ const next = [...prev, req];
5776
+ return next.slice(-2);
5777
+ });
5778
+ setMobileThreadKey(req.key);
5779
+ }, []);
5780
+ const closeThread = React6.useCallback((key) => {
5781
+ setThreads((prev) => prev.filter((t) => t.key !== key));
5782
+ setMobileThreadKey((prev) => prev === key ? null : prev);
5783
+ }, []);
5784
+ const closeAll = React6.useCallback(() => {
5785
+ setListOpen(false);
5786
+ setThreads([]);
5787
+ setMobileThreadKey(null);
5788
+ }, []);
5789
+ const ctx = React6.useMemo(
5790
+ () => ({
5791
+ listOpen,
5792
+ openList,
5793
+ closeList,
5794
+ toggleList,
5795
+ openThread,
5796
+ closeThread,
5797
+ closeAll,
5798
+ activeThreadKey: mobileThreadKey ?? threads[threads.length - 1]?.key ?? null,
5799
+ totalUnread
5800
+ }),
5801
+ [
5802
+ listOpen,
5803
+ openList,
5804
+ closeList,
5805
+ toggleList,
5806
+ openThread,
5807
+ closeThread,
5808
+ closeAll,
5809
+ mobileThreadKey,
5810
+ threads,
5811
+ totalUnread
5812
+ ]
5813
+ );
5814
+ const handleSelectItem = React6.useCallback(
5815
+ (item) => {
5816
+ openThread({
5817
+ key: item.key,
5818
+ title: item.title,
5819
+ subtitle: item.subtitle,
5820
+ conversationId: item.conversationId,
5821
+ open: item.open
5822
+ });
5823
+ },
5824
+ [openThread]
5825
+ );
5826
+ const activeMobileThread = threads.find((t) => t.key === mobileThreadKey);
5827
+ return /* @__PURE__ */ jsxRuntime.jsxs(SupportMessengerContext.Provider, { value: ctx, children: [
5828
+ children,
5829
+ enabled ? /* @__PURE__ */ jsxRuntime.jsxs(
5830
+ "div",
5831
+ {
5832
+ className: cn(
5833
+ "pointer-events-none fixed right-4 bottom-4 z-50 flex flex-col items-end gap-3",
5834
+ className
5835
+ ),
5836
+ children: [
5837
+ !isMobile ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pointer-events-auto flex items-end gap-3", children: [
5838
+ threads.map((thread) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-[28rem] w-[22rem]", children: /* @__PURE__ */ jsxRuntime.jsx(
5839
+ ThreadPanel,
5840
+ {
5841
+ thread,
5842
+ client,
5843
+ getWsUrl,
5844
+ currentUserId,
5845
+ labels,
5846
+ emojiLocale,
5847
+ onClose: () => closeThread(thread.key),
5848
+ onConversationReady: () => void onRefreshItems?.()
5849
+ }
5850
+ ) }, thread.key)),
5851
+ listOpen ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-[28rem] w-[20rem]", children: /* @__PURE__ */ jsxRuntime.jsx(
5852
+ ListPanel,
5853
+ {
5854
+ items,
5855
+ labels,
5856
+ tabs,
5857
+ activeTab,
5858
+ onTabChange,
5859
+ onSelect: handleSelectItem,
5860
+ onClose: closeList,
5861
+ searchThreshold
5862
+ }
5863
+ ) }) : null
5864
+ ] }) : null,
5865
+ isMobile ? /* @__PURE__ */ jsxRuntime.jsx(
5866
+ Drawer,
5867
+ {
5868
+ open: listOpen || Boolean(activeMobileThread),
5869
+ onOpenChange: (open) => {
5870
+ if (!open) closeAll();
5871
+ },
5872
+ children: /* @__PURE__ */ jsxRuntime.jsx(DrawerContent, { className: "pointer-events-auto mx-auto flex h-[85vh] max-w-lg flex-col", children: activeMobileThread ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
5873
+ /* @__PURE__ */ jsxRuntime.jsx(DrawerHeader, { className: "sr-only", children: /* @__PURE__ */ jsxRuntime.jsx(DrawerTitle, { children: activeMobileThread.title }) }),
5874
+ /* @__PURE__ */ jsxRuntime.jsx(
5875
+ ThreadPanel,
5876
+ {
5877
+ thread: activeMobileThread,
5878
+ client,
5879
+ getWsUrl,
5880
+ currentUserId,
5881
+ labels,
5882
+ emojiLocale,
5883
+ showBack: true,
5884
+ onBack: () => {
5885
+ closeThread(activeMobileThread.key);
5886
+ setListOpen(true);
5887
+ },
5888
+ onClose: closeAll,
5889
+ onConversationReady: () => void onRefreshItems?.(),
5890
+ className: "h-full rounded-none border-0 shadow-none"
5891
+ }
5892
+ )
5893
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
5894
+ /* @__PURE__ */ jsxRuntime.jsx(DrawerHeader, { className: "sr-only", children: /* @__PURE__ */ jsxRuntime.jsx(DrawerTitle, { children: labels.listTitle }) }),
5895
+ /* @__PURE__ */ jsxRuntime.jsx(
5896
+ ListPanel,
5897
+ {
5898
+ items,
5899
+ labels,
5900
+ tabs,
5901
+ activeTab,
5902
+ onTabChange,
5903
+ onSelect: handleSelectItem,
5904
+ onClose: closeAll,
5905
+ searchThreshold,
5906
+ className: "h-full rounded-none border-0 shadow-none"
5907
+ }
5908
+ )
5909
+ ] }) })
5910
+ }
5911
+ ) : null,
5912
+ /* @__PURE__ */ jsxRuntime.jsxs(
5913
+ "button",
5914
+ {
5915
+ type: "button",
5916
+ className: cn(
5917
+ "pointer-events-auto relative flex size-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-[transform,opacity] motion-safe:hover:scale-105 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
5918
+ listOpen && !forceMinimized && "ring-2 ring-ring ring-offset-2"
5919
+ ),
5920
+ "aria-label": totalUnread > 0 && labels.unreadBadgeAria ? `${labels.launcherAria}. ${labels.unreadBadgeAria.replace("{count}", String(totalUnread))}` : labels.launcherAria,
5921
+ onClick: () => {
5922
+ if (isMobile) {
5923
+ if (activeMobileThread) {
5924
+ closeAll();
5925
+ } else {
5926
+ toggleList();
5927
+ }
5928
+ return;
5929
+ }
5930
+ toggleList();
5931
+ },
5932
+ children: [
5933
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.MessageCircle, { className: "size-6" }),
5934
+ totalUnread > 0 ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "absolute -top-0.5 -right-0.5 flex size-5 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-white", children: totalUnread > 99 ? "99+" : totalUnread }) : null
5935
+ ]
5936
+ }
5937
+ )
5938
+ ]
5939
+ }
5940
+ ) : null
5941
+ ] });
5942
+ }
5943
+
5944
+ // src/lib/support-chat.ts
5945
+ async function parseJson(res) {
5946
+ const body = await res.json();
5947
+ if (!res.ok) {
5948
+ throw new Error(
5949
+ typeof body === "object" && body && "error" in body && body.error ? String(body.error) : `Chat request failed (${res.status})`
5950
+ );
5951
+ }
5952
+ return body;
5953
+ }
5954
+ function createSupportChatClient(basePath = "/api/chat-svc") {
5955
+ const root = basePath.replace(/\/$/, "");
5956
+ return {
5957
+ basePath: root,
5958
+ async listConversations() {
5959
+ const res = await fetch(`${root}/me/conversations`);
5960
+ const body = await parseJson(res);
5961
+ return body.result ?? [];
5962
+ },
5963
+ async findOrCreateConversation(input) {
5964
+ const res = await fetch(`${root}/conversations`, {
5965
+ method: "POST",
5966
+ headers: { "content-type": "application/json" },
5967
+ body: JSON.stringify(input)
5968
+ });
5969
+ const body = await parseJson(res);
5970
+ return body.result;
5971
+ },
5972
+ async listMessages(conversationId) {
5973
+ const res = await fetch(
5974
+ `${root}/conversations/${encodeURIComponent(conversationId)}/messages`
5975
+ );
5976
+ const body = await parseJson(res);
5977
+ return body.result ?? [];
5978
+ },
5979
+ async sendMessage(conversationId, text) {
5980
+ const res = await fetch(
5981
+ `${root}/conversations/${encodeURIComponent(conversationId)}/messages`,
5982
+ {
5983
+ method: "POST",
5984
+ headers: { "content-type": "application/json" },
5985
+ body: JSON.stringify({ body: text })
5986
+ }
5987
+ );
5988
+ const body = await parseJson(res);
5989
+ return body.result;
5990
+ },
5991
+ async markRead(conversationId) {
5992
+ await fetch(
5993
+ `${root}/conversations/${encodeURIComponent(conversationId)}/read`,
5994
+ { method: "POST" }
5995
+ );
5996
+ }
5997
+ };
5998
+ }
5074
5999
 
5075
6000
  Object.defineProperty(exports, "useMessageScroller", {
5076
6001
  enumerable: true,
@@ -5104,6 +6029,7 @@ exports.EmptyMedia = EmptyMedia;
5104
6029
  exports.EmptyState = EmptyState;
5105
6030
  exports.EmptyTitle = EmptyTitle;
5106
6031
  exports.ErrorState = ErrorState;
6032
+ exports.ImageLightbox = ImageLightbox;
5107
6033
  exports.LanguageContext = LanguageContext;
5108
6034
  exports.LanguageSwitcher = LanguageSwitcher;
5109
6035
  exports.LoadingState = LoadingState;
@@ -5128,6 +6054,7 @@ exports.MexicoMap = MexicoMap;
5128
6054
  exports.OrgSwitcher = OrgSwitcher;
5129
6055
  exports.PhoneInput = PhoneInput;
5130
6056
  exports.SearchCommand = SearchCommand;
6057
+ exports.SupportMessengerProvider = SupportMessengerProvider;
5131
6058
  exports.ThemeSwitcher = ThemeSwitcher;
5132
6059
  exports.VerifiedProfessionalBadge = VerifiedProfessionalBadge;
5133
6060
  exports.VideoPlayer = VideoPlayer;
@@ -5135,6 +6062,7 @@ exports.avatarFallbackStyle = avatarFallbackStyle;
5135
6062
  exports.bubbleVariants = bubbleVariants;
5136
6063
  exports.cn = cn;
5137
6064
  exports.createLiveHlsConfig = createLiveHlsConfig;
6065
+ exports.createSupportChatClient = createSupportChatClient;
5138
6066
  exports.createVodHlsConfig = createVodHlsConfig;
5139
6067
  exports.defaultLanguages = defaultLanguages;
5140
6068
  exports.describePlaybackError = describePlaybackError;
@@ -5151,5 +6079,8 @@ exports.useHlsPlayback = useHlsPlayback;
5151
6079
  exports.useLanguageContext = useLanguageContext;
5152
6080
  exports.usePlaybackStats = usePlaybackStats;
5153
6081
  exports.useSearchHotkey = useSearchHotkey;
6082
+ exports.useSupportConversation = useSupportConversation;
6083
+ exports.useSupportMessenger = useSupportMessenger;
6084
+ exports.useSupportMessengerOptional = useSupportMessengerOptional;
5154
6085
  //# sourceMappingURL=index.cjs.map
5155
6086
  //# sourceMappingURL=index.cjs.map