admesh-ui-sdk 1.0.45 โ 1.0.46
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/README.md +5 -0
- package/dist/components/AdMeshIntentAssistant.d.ts +3 -0
- package/dist/components/AdMeshIntentAssistant.d.ts.map +1 -1
- package/dist/index.js +39 -39
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1993 -2010
- package/dist/index.mjs.map +1 -1
- package/dist/publisher-assistant.js +56 -56
- package/dist/publisher-assistant.js.map +1 -1
- package/dist/publisherAssistantEmbed.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,99 +1,99 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var xo=Object.defineProperty;var bo=(t,e,o)=>e in t?xo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var Ye=(t,e,o)=>bo(t,typeof e!="symbol"?e+"":e,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),yo=require("react-dom/client"),a=require("react"),Hn=require("react-dom");let Qt=!1;var Dr;try{typeof globalThis.importMeta<"u"&&((Dr=globalThis.importMeta.env)!=null&&Dr.PROD)&&(Qt=!0)}catch{}Qt||(Qt=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const l={log:(...t)=>{Qt||console.log(...t)},warn:(...t)=>{Qt||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{Qt||console.info(...t)},debug:(...t)=>{Qt||console.debug(...t)}};/**
|
|
2
2
|
* @license lucide-react v0.563.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const Pr=(...t)=>t.filter((e,o,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===o).join(" ").trim();/**
|
|
7
7
|
* @license lucide-react v0.563.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const
|
|
11
|
+
*/const wo=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
|
|
12
12
|
* @license lucide-react v0.563.0 - ISC
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const
|
|
16
|
+
*/const _o=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,o,s)=>s?s.toUpperCase():o.toLowerCase());/**
|
|
17
17
|
* @license lucide-react v0.563.0 - ISC
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
21
|
+
*/const hr=t=>{const e=_o(t);return e.charAt(0).toUpperCase()+e.slice(1)};/**
|
|
22
22
|
* @license lucide-react v0.563.0 - ISC
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/var
|
|
26
|
+
*/var vo={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
|
27
27
|
* @license lucide-react v0.563.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
30
30
|
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const
|
|
31
|
+
*/const ko=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
|
|
32
32
|
* @license lucide-react v0.563.0 - ISC
|
|
33
33
|
*
|
|
34
34
|
* This source code is licensed under the ISC license.
|
|
35
35
|
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const
|
|
36
|
+
*/const So=a.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:o=2,absoluteStrokeWidth:s,className:i="",children:d,iconNode:u,...w},g)=>a.createElement("svg",{ref:g,...vo,width:e,height:e,stroke:t,strokeWidth:s?Number(o)*24/Number(e):o,className:Pr("lucide",i),...!d&&!ko(w)&&{"aria-hidden":"true"},...w},[...u.map(([_,c])=>a.createElement(_,c)),...Array.isArray(d)?d:[d]]));/**
|
|
37
37
|
* @license lucide-react v0.563.0 - ISC
|
|
38
38
|
*
|
|
39
39
|
* This source code is licensed under the ISC license.
|
|
40
40
|
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const
|
|
41
|
+
*/const gt=(t,e)=>{const o=a.forwardRef(({className:s,...i},d)=>a.createElement(So,{ref:d,iconNode:e,className:Pr(`lucide-${wo(hr(t))}`,`lucide-${t}`,s),...i}));return o.displayName=hr(t),o};/**
|
|
42
42
|
* @license lucide-react v0.563.0 - ISC
|
|
43
43
|
*
|
|
44
44
|
* This source code is licensed under the ISC license.
|
|
45
45
|
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const
|
|
46
|
+
*/const Ao=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],Co=gt("arrow-up-right",Ao);/**
|
|
47
47
|
* @license lucide-react v0.563.0 - ISC
|
|
48
48
|
*
|
|
49
49
|
* This source code is licensed under the ISC license.
|
|
50
50
|
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
-
*/const
|
|
51
|
+
*/const Mo=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],jo=gt("arrow-up",Mo);/**
|
|
52
52
|
* @license lucide-react v0.563.0 - ISC
|
|
53
53
|
*
|
|
54
54
|
* This source code is licensed under the ISC license.
|
|
55
55
|
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const
|
|
56
|
+
*/const Eo=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],Ro=gt("flag",Eo);/**
|
|
57
57
|
* @license lucide-react v0.563.0 - ISC
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const Io=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],To=gt("maximize-2",Io);/**
|
|
62
62
|
* @license lucide-react v0.563.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
65
65
|
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const
|
|
66
|
+
*/const Do=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Un=gt("message-square",Do);/**
|
|
67
67
|
* @license lucide-react v0.563.0 - ISC
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
70
70
|
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const
|
|
71
|
+
*/const Po=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],fr=gt("minimize-2",Po);/**
|
|
72
72
|
* @license lucide-react v0.563.0 - ISC
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const zo=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],gr=gt("send",zo);/**
|
|
77
77
|
* @license lucide-react v0.563.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
80
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const
|
|
81
|
+
*/const No=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],$o=gt("square",No);/**
|
|
82
82
|
* @license lucide-react v0.563.0 - ISC
|
|
83
83
|
*
|
|
84
84
|
* This source code is licensed under the ISC license.
|
|
85
85
|
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const
|
|
86
|
+
*/const Lo=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}],["path",{d:"M17 14V2",key:"8ymqnk"}]],xr=gt("thumbs-down",Lo);/**
|
|
87
87
|
* @license lucide-react v0.563.0 - ISC
|
|
88
88
|
*
|
|
89
89
|
* This source code is licensed under the ISC license.
|
|
90
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const
|
|
91
|
+
*/const Fo=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}],["path",{d:"M7 10v12",key:"1qc93n"}]],br=gt("thumbs-up",Fo);/**
|
|
92
92
|
* @license lucide-react v0.563.0 - ISC
|
|
93
93
|
*
|
|
94
94
|
* This source code is licensed under the ISC license.
|
|
95
95
|
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const $o=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Pn=yt("x",$o);function Lo(t,e,o){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...o}}function Fo(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function Wo(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,i=e.height,d=e.width;if(i===0||d===0)return 0;const u=Math.max(0,e.top),w=Math.min(o,e.bottom),g=Math.max(0,e.left),v=Math.min(s,e.right),c=Math.max(0,w-u),m=Math.max(0,v-g),k=c*m,j=i*d;return j>0?k/j:0}function br(){const t=window.innerHeight,e=document.documentElement.scrollHeight,o=window.pageYOffset||document.documentElement.scrollTop,s=e-t;return s<=0?100:Math.min(100,o/s*100)}function Bo(t){const e=t.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+o,left:e.left+s}}function Uo(t){const e=t.getBoundingClientRect(),o=Bo(t),s=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,d=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Fo(s),viewportWidth:s,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:d,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function Ho(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function qo(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function yr(t=new Date){return t.toISOString()}function Oo(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function wr(t,e){let o;return function(...i){o||(t(...i),o=!0,setTimeout(()=>o=!1,e))}}const Vo={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let Ko=Vo,Go=!1;function Pr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:i,config:d}){const u={...Ko,...d},w=a.useRef(Ho()),[g,v]=a.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:yr(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:u.enabled}),c=a.useRef(null),m=a.useRef(null),k=a.useRef(null),j=a.useRef(null),p=a.useRef(null),x=a.useRef([]),f=a.useRef([]),h=a.useRef(null),S=a.useCallback(C=>{u.debug&&l.log(`[AdMesh Viewability] ${C}`)},[u.debug]),I=a.useCallback(async(C,L)=>{if(!(!u.enabled||Go||!i.current||!c.current)&&(S(`Analytics disabled - skipping event: ${C}`),u.onEvent)){const N=Uo(i.current),F={eventType:C,timestamp:yr(),sessionId:w.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:g.timeMetrics,engagementMetrics:g.engagementMetrics,contextMetrics:N,mrcStandards:c.current,isViewable:g.isViewable,metadata:L};u.onEvent(F)}},[u,t,e,o,s,i,g,S]),G=a.useCallback(async()=>{f.current.length!==0&&(S("Analytics disabled - clearing batch without sending"),f.current=[],h.current&&(clearTimeout(h.current),h.current=null))},[S]),A=a.useCallback(wr(()=>{if(!i.current)return;const C=Wo(i.current),L=Date.now(),N=new Date(g.timeMetrics.loadedAt).getTime();v(F=>{const P={...F};C>0&&x.current.push(C);const z=F.isVisible,M=C>0;if(M&&!z)m.current=L,P.engagementMetrics.viewportEnterCount++,P.timeMetrics.timeToFirstVisible||(P.timeMetrics.timeToFirstVisible=L-N,P.engagementMetrics.scrollDepthAtFirstVisible=br(),I("ad_visible"));else if(!M&&z){if(m.current){const B=L-m.current;P.timeMetrics.totalVisibleDuration+=B,m.current=null}P.engagementMetrics.viewportExitCount++,I("ad_hidden")}else if(M&&z&&m.current){const B=L-m.current;P.timeMetrics.totalVisibleDuration+=B,m.current=L}if(P.isVisible=M,P.visibilityPercentage=C,C>P.engagementMetrics.maxVisibilityPercentage&&(P.engagementMetrics.maxVisibilityPercentage=C),x.current.length>0&&(P.engagementMetrics.averageVisibilityPercentage=Oo(x.current)),c.current){const B=F.isViewable,K=qo(C,P.timeMetrics.totalVisibleDuration,c.current);if(K&&!B)P.isViewable=!0,P.timeMetrics.timeToViewable=L-N,k.current=L,I("ad_viewable");else if(K&&B&&k.current){const X=L-k.current;P.timeMetrics.totalViewableDuration+=X,k.current=L}}return P.engagementMetrics.currentScrollDepth=br(),P})},100),[i,g.timeMetrics.loadedAt,I]);return a.useEffect(()=>{if(!i.current)return;const C=i.current.getBoundingClientRect();c.current=Lo(C.width,C.height,u.mrcStandards),S("Initialized MRC standards"),I("ad_loaded")},[i,u.mrcStandards,S,I]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=new IntersectionObserver(L=>{L.forEach(()=>{A()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return C.observe(i.current),()=>{C.disconnect()}},[u.enabled,i,A]),a.useEffect(()=>{if(!u.enabled)return;const C=wr(()=>{A()},100);return window.addEventListener("scroll",C,{passive:!0}),()=>window.removeEventListener("scroll",C)},[u.enabled,A]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,L=()=>{j.current=Date.now(),v(F=>({...F,engagementMetrics:{...F.engagementMetrics,hoverCount:F.engagementMetrics.hoverCount+1}})),I("ad_hover_start")},N=()=>{if(j.current){const F=Date.now()-j.current;v(P=>({...P,timeMetrics:{...P.timeMetrics,totalHoverDuration:P.timeMetrics.totalHoverDuration+F}})),j.current=null,I("ad_hover_end",{hoverDuration:F})}};return C.addEventListener("mouseenter",L),C.addEventListener("mouseleave",N),()=>{C.removeEventListener("mouseenter",L),C.removeEventListener("mouseleave",N)}},[u.enabled,i,I]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,L=()=>{p.current=Date.now(),I("ad_focus")},N=()=>{if(p.current){const F=Date.now()-p.current;v(P=>({...P,timeMetrics:{...P.timeMetrics,totalFocusDuration:P.timeMetrics.totalFocusDuration+F}})),p.current=null,I("ad_blur",{focusDuration:F})}};return C.addEventListener("focus",L),C.addEventListener("blur",N),()=>{C.removeEventListener("focus",L),C.removeEventListener("blur",N)}},[u.enabled,i,I]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,L=()=>{v(N=>({...N,engagementMetrics:{...N.engagementMetrics,wasClicked:!0}})),I("ad_click")};return C.addEventListener("click",L),()=>{C.removeEventListener("click",L)}},[u.enabled,i,I]),a.useEffect(()=>()=>{const C=Date.now(),L=new Date(g.timeMetrics.loadedAt).getTime(),N=C-L;v(F=>({...F,timeMetrics:{...F.timeMetrics,sessionDuration:N}})),I("ad_unloaded",{sessionDuration:N}),G()},[]),g}const un=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:i,sessionId:d,triggerExposureUrl:u=!0,children:w,config:g,className:v,style:c,onViewabilityChange:m,onVisible:k,onViewable:j,onClick:p})=>{const x=a.useRef(null),f=a.useRef(!1),h=Pr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:x,config:g}),S=a.useRef(h.isViewable);a.useEffect(()=>{f.current=!1,S.current=!1},[i,s,d]),a.useEffect(()=>{h.isViewable!==S.current&&(S.current=h.isViewable,m&&m(h.isViewable),h.isViewable&&j&&j(),h.isViewable&&!f.current&&u&&(l.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:i?"present":"MISSING",sessionId:d?"present":"MISSING",recommendationId:s}),i&&d?(f.current=!0,l.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",i),fetch(i,{method:"GET",keepalive:!0}).then(()=>{l.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(A=>{l.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",A),f.current=!1})):l.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!i,hasSessionId:!!d})))},[h.isViewable,m,j,i,d,s,u]);const I=a.useRef(h.isVisible);a.useEffect(()=>{h.isVisible!==I.current&&(I.current=h.isVisible,h.isVisible&&k&&k())},[h.isVisible,k]);const G=()=>{p&&p()};return n.jsx("div",{ref:x,className:v,style:c,onClick:G,"data-admesh-viewability-tracker":!0,"data-recommendation-id":s,"data-is-viewable":h.isViewable,"data-is-visible":h.isVisible,"data-visibility-percentage":h.visibilityPercentage.toFixed(2),children:w})};un.displayName="AdMeshViewabilityTracker";const _r=t=>{try{return new URL(t),!0}catch{return!1}},en=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",xt=t=>en(t)||void 0,Yo=t=>t&&t.trim()?t.trim():"",Qo=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return en(t)},Hn=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:g,onRecommendationReport:v})=>{var ot,Mt,jt,O,st,wt,Ft,qt,it;if(!t||t.length===0)return l.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],m=c==null?void 0:c.recommendation,k=m==null?void 0:m.creative,j=c==null?void 0:c.tracking,p=c==null?void 0:c.delegation,x=(c==null?void 0:c.recommendation_id)||"",f=(m==null?void 0:m.offerId)||"",h=(k==null?void 0:k.brand_name)||"",S=(k==null?void 0:k.headline)||"",I=(k==null?void 0:k.description)||"",G=(k==null?void 0:k.logo_url)||"",A=(j==null?void 0:j.click_url)||(k==null?void 0:k.landing_page_url)||"",C=(j==null?void 0:j.exposure_url)||"",L=(m==null?void 0:m.disclosure)||"Sponsored",N=(k==null?void 0:k.products)||[],F=N.slice(0,4),P=N.length>1,M=((m==null?void 0:m.format)||"tail")==="bridge",B=(p==null?void 0:p.available)===!0,K=M&&B,X=(p==null?void 0:p.brand_name)||h,U="Talk to Agent",H=Yo(k==null?void 0:k.cta_text),ne=!P&&!!H&&!!A;if(!h&&!S&&!I)return l.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:x}),null;const ce=S&&S!==h?S:h,q=I,Ce=h.trim().toLowerCase(),ke=ce.trim().toLowerCase(),tt=!!h&&Ce!==ke,[Ee,be]=a.useState(!1),[se,ue]=a.useState(!1),[le,me]=a.useState(!1),[Re,nt]=a.useState(null),$=a.useRef(null);a.useEffect(()=>()=>{$.current&&($.current(!1),$.current=null)},[]);const Q=Y=>{var we;Y&&ue(!0),(we=$.current)==null||we.call($,Y),$.current=null,Y||(ue(!1),be(!1))},J=async()=>u?await u(c):await new Promise(Y=>{$.current=Y,be(!0)}),ee=(Y,we)=>{we&&we.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:x,productId:f,clickUrl:A,source:Y}).catch(()=>{l.error(`[AdMesh] Failed to track ${Y} click`)})},oe=[{value:"irrelevant",label:"Not relevant"},{value:"misleading",label:"Misleading"},{value:"inappropriate",label:"Inappropriate"},{value:"broken_link",label:"Broken link"},{value:"other",label:"Other"}],Se=Y=>{Y.preventDefault(),Y.stopPropagation(),!Re&&me(we=>!we)},D=async(Y,we)=>{if(Y.preventDefault(),Y.stopPropagation(),me(!1),nt(we),!!v)try{await v({recommendation:c,recommendation_id:x,reason:we,session_id:i})}catch(at){l.warn("[AdMesh Compact Tail Ad] Failed to submit recommendation report:",at)}},ie=()=>{P||!A||(ee("compact_tail_ad_card"),typeof window<"u"&&window.open(A,"_blank","noopener,noreferrer"))},T=Y=>{P||!A||(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),ie())},E=async()=>{if(x&&i)try{const Y=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",we=await fetch(`${Y}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:x,session_id:i,is_test:!1})});we.ok||l.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",we.statusText)}catch(Y){l.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",Y)}},fe=async Y=>{if(Y.preventDefault(),Y.stopPropagation(),!c||!K||(ee("compact_tail_ad_delegation_cta"),!await J()))return;E();const at=p!=null&&p.available?{recommendation_id:c.recommendation_id,brand_id:xt(p.brand_id),brand_name:xt(p.brand_name||(k==null?void 0:k.brand_name)),mcp_endpoint:xt(p.mcp_endpoint),eligibility_reason:xt(p.eligibility_reason),delegate_reason:xt(p.delegate_reason),session_goal:xt(p.session_goal),desired_outcome_type:p.desired_outcome_type,required_user_inputs:Array.isArray(p.required_user_inputs)?p.required_user_inputs.filter(lt=>typeof lt=="string"):[],required_consent_types:Array.isArray(p.required_consent_types)?p.required_consent_types.filter(lt=>typeof lt=="string"):[],success_outcome:xt(p.success_outcome),fallback_message:xt(p.fallback_message),session_mode:xt(p.session_mode),status:xt(p.status),capabilities:p.capabilities||[],allowed_data_types:p.allowed_data_types||[],consent_requirements:p.consent_requirements||[],auth_model:xt(p.auth_model),handoff_protocol:p.handoff_protocol&&typeof p.handoff_protocol=="object"?p.handoff_protocol:void 0,supported_actions:p.supported_actions||[],metadata:p.metadata&&typeof p.metadata=="object"?p.metadata:void 0,platform_response:c}:null;if(w&&at){try{await w(at)}finally{ue(!1),be(!1)}return}if(g){try{await g(c)}finally{ue(!1),be(!1)}return}ue(!1),be(!1)},[te,Ge]=a.useState(!1),pe=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,Be=(e==null?void 0:e.surfaceColor)||((Mt=(ot=e==null?void 0:e.components)==null?void 0:ot.card)==null?void 0:Mt.backgroundColor)||(pe?"#111827":"#ffffff"),Ie=(e==null?void 0:e.borderColor)||((O=(jt=e==null?void 0:e.components)==null?void 0:jt.card)==null?void 0:O.borderColor)||(pe?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),Ae=((st=e==null?void 0:e.shadows)==null?void 0:st.medium)||((Ft=(wt=e==null?void 0:e.components)==null?void 0:wt.card)==null?void 0:Ft.boxShadow)||(pe?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),ye="#2563eb",Pe=pe?"#9ca3af":"#6b7280",Lt=pe?"#e5e7eb":"#374151",ht=pe?"#f9fafb":"#0f172a",Te=pe?"rgba(255, 255, 255, 0.04)":"#f8fafc",We="50px",ge=K||ne?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[K?n.jsx("button",{type:"button",onClick:fe,style:{background:"none",border:"none",padding:0,color:ye,fontSize:"12px",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:U}):null,ne?n.jsx("a",{href:A,target:"_blank",rel:"noopener noreferrer",onClick:Y=>ee("compact_tail_ad_cta",Y),style:{color:ye,fontSize:"12px",fontWeight:600,textDecoration:"none"},children:H}):null]}):null;return n.jsxs(un,{productId:f,recommendationId:x,exposureUrl:C,sessionId:i,triggerExposureUrl:d,className:`admesh-compact-tail-ad ${o}`,style:{all:"initial",boxSizing:"border-box",display:"block",fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[n.jsx("style",{children:`
|
|
96
|
+
*/const Wo=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],zn=gt("x",Wo);function Bo(t,e,o){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...o}}function Uo(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function Ho(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,i=e.height,d=e.width;if(i===0||d===0)return 0;const u=Math.max(0,e.top),w=Math.min(o,e.bottom),g=Math.max(0,e.left),_=Math.min(s,e.right),c=Math.max(0,w-u),m=Math.max(0,_-g),k=c*m,j=i*d;return j>0?k/j:0}function yr(){const t=window.innerHeight,e=document.documentElement.scrollHeight,o=window.pageYOffset||document.documentElement.scrollTop,s=e-t;return s<=0?100:Math.min(100,o/s*100)}function qo(t){const e=t.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+o,left:e.left+s}}function Oo(t){const e=t.getBoundingClientRect(),o=qo(t),s=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,d=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Uo(s),viewportWidth:s,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:d,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function Vo(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Ko(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function wr(t=new Date){return t.toISOString()}function Go(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function _r(t,e){let o;return function(...i){o||(t(...i),o=!0,setTimeout(()=>o=!1,e))}}const Yo={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let Qo=Yo,Xo=!1;function zr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:i,config:d}){const u={...Qo,...d},w=a.useRef(Vo()),[g,_]=a.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:wr(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:u.enabled}),c=a.useRef(null),m=a.useRef(null),k=a.useRef(null),j=a.useRef(null),p=a.useRef(null),x=a.useRef([]),f=a.useRef([]),h=a.useRef(null),S=a.useCallback(C=>{u.debug&&l.log(`[AdMesh Viewability] ${C}`)},[u.debug]),I=a.useCallback(async(C,L)=>{if(!(!u.enabled||Xo||!i.current||!c.current)&&(S(`Analytics disabled - skipping event: ${C}`),u.onEvent)){const $=Oo(i.current),F={eventType:C,timestamp:wr(),sessionId:w.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:g.timeMetrics,engagementMetrics:g.engagementMetrics,contextMetrics:$,mrcStandards:c.current,isViewable:g.isViewable,metadata:L};u.onEvent(F)}},[u,t,e,o,s,i,g,S]),G=a.useCallback(async()=>{f.current.length!==0&&(S("Analytics disabled - clearing batch without sending"),f.current=[],h.current&&(clearTimeout(h.current),h.current=null))},[S]),A=a.useCallback(_r(()=>{if(!i.current)return;const C=Ho(i.current),L=Date.now(),$=new Date(g.timeMetrics.loadedAt).getTime();_(F=>{const P={...F};C>0&&x.current.push(C);const z=F.isVisible,M=C>0;if(M&&!z)m.current=L,P.engagementMetrics.viewportEnterCount++,P.timeMetrics.timeToFirstVisible||(P.timeMetrics.timeToFirstVisible=L-$,P.engagementMetrics.scrollDepthAtFirstVisible=yr(),I("ad_visible"));else if(!M&&z){if(m.current){const W=L-m.current;P.timeMetrics.totalVisibleDuration+=W,m.current=null}P.engagementMetrics.viewportExitCount++,I("ad_hidden")}else if(M&&z&&m.current){const W=L-m.current;P.timeMetrics.totalVisibleDuration+=W,m.current=L}if(P.isVisible=M,P.visibilityPercentage=C,C>P.engagementMetrics.maxVisibilityPercentage&&(P.engagementMetrics.maxVisibilityPercentage=C),x.current.length>0&&(P.engagementMetrics.averageVisibilityPercentage=Go(x.current)),c.current){const W=F.isViewable,V=Ko(C,P.timeMetrics.totalVisibleDuration,c.current);if(V&&!W)P.isViewable=!0,P.timeMetrics.timeToViewable=L-$,k.current=L,I("ad_viewable");else if(V&&W&&k.current){const Y=L-k.current;P.timeMetrics.totalViewableDuration+=Y,k.current=L}}return P.engagementMetrics.currentScrollDepth=yr(),P})},100),[i,g.timeMetrics.loadedAt,I]);return a.useEffect(()=>{if(!i.current)return;const C=i.current.getBoundingClientRect();c.current=Bo(C.width,C.height,u.mrcStandards),S("Initialized MRC standards"),I("ad_loaded")},[i,u.mrcStandards,S,I]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=new IntersectionObserver(L=>{L.forEach(()=>{A()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return C.observe(i.current),()=>{C.disconnect()}},[u.enabled,i,A]),a.useEffect(()=>{if(!u.enabled)return;const C=_r(()=>{A()},100);return window.addEventListener("scroll",C,{passive:!0}),()=>window.removeEventListener("scroll",C)},[u.enabled,A]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,L=()=>{j.current=Date.now(),_(F=>({...F,engagementMetrics:{...F.engagementMetrics,hoverCount:F.engagementMetrics.hoverCount+1}})),I("ad_hover_start")},$=()=>{if(j.current){const F=Date.now()-j.current;_(P=>({...P,timeMetrics:{...P.timeMetrics,totalHoverDuration:P.timeMetrics.totalHoverDuration+F}})),j.current=null,I("ad_hover_end",{hoverDuration:F})}};return C.addEventListener("mouseenter",L),C.addEventListener("mouseleave",$),()=>{C.removeEventListener("mouseenter",L),C.removeEventListener("mouseleave",$)}},[u.enabled,i,I]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,L=()=>{p.current=Date.now(),I("ad_focus")},$=()=>{if(p.current){const F=Date.now()-p.current;_(P=>({...P,timeMetrics:{...P.timeMetrics,totalFocusDuration:P.timeMetrics.totalFocusDuration+F}})),p.current=null,I("ad_blur",{focusDuration:F})}};return C.addEventListener("focus",L),C.addEventListener("blur",$),()=>{C.removeEventListener("focus",L),C.removeEventListener("blur",$)}},[u.enabled,i,I]),a.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,L=()=>{_($=>({...$,engagementMetrics:{...$.engagementMetrics,wasClicked:!0}})),I("ad_click")};return C.addEventListener("click",L),()=>{C.removeEventListener("click",L)}},[u.enabled,i,I]),a.useEffect(()=>()=>{const C=Date.now(),L=new Date(g.timeMetrics.loadedAt).getTime(),$=C-L;_(F=>({...F,timeMetrics:{...F.timeMetrics,sessionDuration:$}})),I("ad_unloaded",{sessionDuration:$}),G()},[]),g}const hn=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:i,sessionId:d,triggerExposureUrl:u=!0,children:w,config:g,className:_,style:c,onViewabilityChange:m,onVisible:k,onViewable:j,onClick:p})=>{const x=a.useRef(null),f=a.useRef(!1),h=zr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:x,config:g}),S=a.useRef(h.isViewable);a.useEffect(()=>{f.current=!1,S.current=!1},[i,s,d]),a.useEffect(()=>{h.isViewable!==S.current&&(S.current=h.isViewable,m&&m(h.isViewable),h.isViewable&&j&&j(),h.isViewable&&!f.current&&u&&(l.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:i?"present":"MISSING",sessionId:d?"present":"MISSING",recommendationId:s}),i&&d?(f.current=!0,l.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",i),fetch(i,{method:"GET",keepalive:!0}).then(()=>{l.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(A=>{l.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",A),f.current=!1})):l.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!i,hasSessionId:!!d})))},[h.isViewable,m,j,i,d,s,u]);const I=a.useRef(h.isVisible);a.useEffect(()=>{h.isVisible!==I.current&&(I.current=h.isVisible,h.isVisible&&k&&k())},[h.isVisible,k]);const G=()=>{p&&p()};return n.jsx("div",{ref:x,className:_,style:c,onClick:G,"data-admesh-viewability-tracker":!0,"data-recommendation-id":s,"data-is-viewable":h.isViewable,"data-is-visible":h.isVisible,"data-visibility-percentage":h.visibilityPercentage.toFixed(2),children:w})};hn.displayName="AdMeshViewabilityTracker";const vr=t=>{try{return new URL(t),!0}catch{return!1}},rn=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",ht=t=>rn(t)||void 0,Jo=t=>t&&t.trim()?t.trim():"",Zo=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return rn(t)},qn=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:g,onRecommendationReport:_})=>{var pe,it,jt,Et,q,at,yt,Lt,Ut;if(!t||t.length===0)return l.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],m=c==null?void 0:c.recommendation,k=m==null?void 0:m.creative,j=c==null?void 0:c.tracking,p=c==null?void 0:c.delegation,x=(c==null?void 0:c.recommendation_id)||"",f=(m==null?void 0:m.offerId)||"",h=(k==null?void 0:k.brand_name)||"",S=(k==null?void 0:k.headline)||"",I=(k==null?void 0:k.description)||"",G=(k==null?void 0:k.logo_url)||"",A=(j==null?void 0:j.click_url)||(k==null?void 0:k.landing_page_url)||"",C=(j==null?void 0:j.exposure_url)||"",L=(m==null?void 0:m.disclosure)||"Sponsored",$=(k==null?void 0:k.products)||[],F=$.slice(0,4),P=$.length>1,M=((m==null?void 0:m.format)||"tail")==="bridge",W=(p==null?void 0:p.available)===!0,V=M&&W,Y=(p==null?void 0:p.brand_name)||h,U="Talk to Agent",H=Jo(k==null?void 0:k.cta_text),te=!P&&!!H&&!!A;if(!h&&!S&&!I)return l.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:x}),null;const ge=S&&S!==h?S:h,Z=I,ne=h.trim().toLowerCase(),_e=ge.trim().toLowerCase(),Ge=!!h&&ne!==_e,[Ee,ve]=a.useState(!1),[le,ue]=a.useState(!1),[Re,be]=a.useState(!1),[se,xt]=a.useState(null),N=a.useRef(null);a.useEffect(()=>()=>{N.current&&(N.current(!1),N.current=null)},[]);const Q=O=>{var Ce;O&&ue(!0),(Ce=N.current)==null||Ce.call(N,O),N.current=null,O||(ue(!1),ve(!1))},X=async()=>u?await u(c):await new Promise(O=>{N.current=O,ve(!0)}),ee=(O,Ce)=>{Ce&&Ce.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:x,productId:f,clickUrl:A,source:O}).catch(()=>{l.error(`[AdMesh] Failed to track ${O} click`)})},re=[{value:"irrelevant",label:"Not relevant"},{value:"misleading",label:"Misleading"},{value:"inappropriate",label:"Inappropriate"},{value:"broken_link",label:"Broken link"},{value:"other",label:"Other"}],Ie=O=>{O.preventDefault(),O.stopPropagation(),!se&&be(Ce=>!Ce)},T=async(O,Ce)=>{if(O.preventDefault(),O.stopPropagation(),be(!1),xt(Ce),!!_)try{await _({recommendation:c,recommendation_id:x,reason:Ce,session_id:i})}catch(Qe){l.warn("[AdMesh Compact Tail Ad] Failed to submit recommendation report:",Qe)}},ie=()=>{P||!A||(ee("compact_tail_ad_card"),typeof window<"u"&&window.open(A,"_blank","noopener,noreferrer"))},D=O=>{P||!A||(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),ie())},fe=async()=>{if(x&&i)try{const O=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",Ce=await fetch(`${O}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:x,session_id:i,is_test:!1})});Ce.ok||l.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",Ce.statusText)}catch(O){l.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",O)}},E=async O=>{if(O.preventDefault(),O.stopPropagation(),!c||!V||(ee("compact_tail_ad_delegation_cta"),!await X()))return;fe();const Qe=p!=null&&p.available?{recommendation_id:c.recommendation_id,brand_id:ht(p.brand_id),brand_name:ht(p.brand_name||(k==null?void 0:k.brand_name)),mcp_endpoint:ht(p.mcp_endpoint),eligibility_reason:ht(p.eligibility_reason),delegate_reason:ht(p.delegate_reason),session_goal:ht(p.session_goal),desired_outcome_type:p.desired_outcome_type,required_user_inputs:Array.isArray(p.required_user_inputs)?p.required_user_inputs.filter(ut=>typeof ut=="string"):[],required_consent_types:Array.isArray(p.required_consent_types)?p.required_consent_types.filter(ut=>typeof ut=="string"):[],success_outcome:ht(p.success_outcome),fallback_message:ht(p.fallback_message),session_mode:ht(p.session_mode),status:ht(p.status),capabilities:p.capabilities||[],allowed_data_types:p.allowed_data_types||[],consent_requirements:p.consent_requirements||[],auth_model:ht(p.auth_model),handoff_protocol:p.handoff_protocol&&typeof p.handoff_protocol=="object"?p.handoff_protocol:void 0,supported_actions:p.supported_actions||[],metadata:p.metadata&&typeof p.metadata=="object"?p.metadata:void 0,platform_response:c}:null;if(w&&Qe){try{await w(Qe)}finally{ue(!1),ve(!1)}return}if(g){try{await g(c)}finally{ue(!1),ve(!1)}return}ue(!1),ve(!1)},[de,ke]=a.useState(!1),me=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,Be=(e==null?void 0:e.surfaceColor)||((it=(pe=e==null?void 0:e.components)==null?void 0:pe.card)==null?void 0:it.backgroundColor)||(me?"#111827":"#ffffff"),Ne=(e==null?void 0:e.borderColor)||((Et=(jt=e==null?void 0:e.components)==null?void 0:jt.card)==null?void 0:Et.borderColor)||(me?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),Se=((q=e==null?void 0:e.shadows)==null?void 0:q.medium)||((yt=(at=e==null?void 0:e.components)==null?void 0:at.card)==null?void 0:yt.boxShadow)||(me?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),De="#2563eb",Ae=me?"#9ca3af":"#6b7280",bt=me?"#e5e7eb":"#374151",st=me?"#f9fafb":"#0f172a",Mt=me?"rgba(255, 255, 255, 0.04)":"#f8fafc",Pe="50px",Oe=V||te?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[V?n.jsx("button",{type:"button",onClick:E,style:{background:"none",border:"none",padding:0,color:De,fontSize:"12px",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:U}):null,te?n.jsx("a",{href:A,target:"_blank",rel:"noopener noreferrer",onClick:O=>ee("compact_tail_ad_cta",O),style:{color:De,fontSize:"12px",fontWeight:600,textDecoration:"none"},children:H}):null]}):null;return n.jsxs(hn,{productId:f,recommendationId:x,exposureUrl:C,sessionId:i,triggerExposureUrl:d,className:`admesh-compact-tail-ad ${o}`,style:{all:"initial",boxSizing:"border-box",display:"block",fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[n.jsx("style",{children:`
|
|
97
97
|
.admesh-compact-tail-ad,
|
|
98
98
|
.admesh-compact-tail-ad * {
|
|
99
99
|
box-sizing: border-box;
|
|
@@ -146,9 +146,9 @@
|
|
|
146
146
|
min-height: 34px;
|
|
147
147
|
}
|
|
148
148
|
}
|
|
149
|
-
`}),n.jsxs("div",{role:!P&&A?"link":void 0,tabIndex:!P&&A?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((it=(qt=e==null?void 0:e.components)==null?void 0:qt.card)==null?void 0:it.borderRadius)||"14px",border:`1px solid ${Ie}`,background:Be,boxShadow:Ae,minWidth:0,cursor:!P&&A?"pointer":void 0},onClick:ie,onKeyDown:T,children:[n.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[n.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:pe?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!te&&G&&_r(G)?n.jsx("img",{src:G,alt:`${h} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>Ge(!0)}):n.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:Pe},children:(h||"A").charAt(0).toUpperCase()})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{className:"admesh-compact-meta-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[n.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"11px",color:Pe},children:tt?h:""}),n.jsx("span",{style:{flexShrink:0,fontSize:"10px",color:Pe,textTransform:"uppercase",letterSpacing:"0.08em"},children:L})]}),!P&&n.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",lineHeight:1.3,fontWeight:700,color:ht,marginBottom:"4px"},title:ce,children:ce}),q&&n.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"12px",lineHeight:1.35,color:Lt},title:q,children:q})]})]}),P&&n.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:F.map(Y=>{const we=en(Y.product_name)||"Product",at=en(Y.product_link)||en(Y.product_url)||A||"#",lt=Qo(Y.product_price,Y.product_currency),_t=en(Y.product_image_url),Ot=_t&&_r(_t)?_t:"",vt=at!=="#";return n.jsx("a",{href:at,target:vt?"_blank":void 0,rel:vt?"noopener noreferrer":void 0,onClick:dt=>ee(`compact_tail_ad_product_${Y.product_id||"item"}`,dt),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${Ie}`,borderRadius:"12px",background:Te,padding:"8px",flexShrink:0},children:n.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[n.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:pe?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:Pe,fontSize:"12px",fontWeight:700},children:Ot?n.jsx("img",{src:Ot,alt:we,style:{width:"100%",height:"100%",objectFit:"cover"}}):we.charAt(0).toUpperCase()}),n.jsxs("div",{style:{minWidth:0,flex:1},children:[n.jsx("div",{style:{fontSize:"12px",lineHeight:1.25,fontWeight:600,color:ht,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:we,children:we}),n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:lt&&n.jsx("span",{style:{fontSize:"12px",fontWeight:700,color:ht},children:lt})})]})]})},Y.product_id||`${x}-${we}`)})}),n.jsxs("div",{className:"admesh-compact-footer-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:P?0:We},children:[n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:ge}),n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",marginLeft:"auto",flexShrink:0},children:[P&&N.length>F.length?n.jsxs("span",{style:{fontSize:"10px",color:Pe},children:["+",N.length-F.length," more"]}):null,n.jsx("button",{type:"button","aria-label":Re?"Recommendation reported":"Report recommendation",title:Re?"Reported":"Report recommendation",disabled:!!Re,onClick:Se,style:{width:"28px",height:"28px",borderRadius:"999px",border:`1px solid ${Ie}`,background:Re?Te:Be,color:Re?ye:Pe,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,cursor:Re?"default":"pointer",flexShrink:0},children:n.jsx(Mo,{size:13})})]})]}),le?n.jsx("div",{className:"admesh-compact-report-panel",onClick:Y=>Y.stopPropagation(),style:{marginLeft:P?0:We,border:`1px solid ${Ie}`,borderRadius:"12px",background:Te,padding:"8px",display:"flex",flexWrap:"wrap",gap:"6px"},children:oe.map(Y=>n.jsx("button",{className:"admesh-compact-report-option",type:"button",onClick:we=>D(we,Y.value),style:{borderRadius:"999px",border:`1px solid ${Ie}`,background:Be,color:ht,fontSize:"11px",fontWeight:600,padding:"6px 9px",cursor:"pointer"},children:Y.label},Y.value))}):null,Re?n.jsx("div",{className:"admesh-compact-report-status",style:{marginLeft:P?0:We,fontSize:"11px",color:Pe},children:"Thanks for reporting this recommendation."}):null,Ee?n.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${Ie}`,borderRadius:"12px",background:Te,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:ye},children:"Confirm Agent Access"}),n.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:ht,fontWeight:600},children:["Allow ",X||"this brand"," to start a delegated session?"]}),n.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:Lt},children:"The agent will only use the details you choose to share for this request."})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[n.jsx("button",{type:"button",disabled:se,onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),!se&&Q(!1)},style:{borderRadius:"10px",border:`1px solid ${Ie}`,background:Be,color:ht,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:se?"not-allowed":"pointer",opacity:se?.65:1},children:"Not now"}),n.jsx("button",{type:"button",disabled:se,onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),!se&&Q(!0)},style:{borderRadius:"10px",border:"none",background:ye,color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:se?"wait":"pointer",opacity:se?.86:1},children:se?"Connecting...":"Allow agent"})]})]}):null]})]})},zr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})=>{const g=t.filter(c=>c&&typeof c=="object"&&typeof c.recommendation_id=="string"&&c.recommendation_id.length>0);if(!g||g.length===0)return l.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;l.log(`[AdMeshLayout] Rendering with ${g.length} valid recommendations`);const v=()=>{var c;if(g.length>0){const m=g[0],k=(c=m.recommendation)==null?void 0:c.format;l.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:k,recommendationKeys:Object.keys(m||{})}),(k==="product_card"||k==="weave"||k==="bridge")&&l.warn(`[AdMeshLayout] ${k} format requested, falling back to tail for canonical render payload`)}return n.jsx(Hn,{recommendations:g,theme:e,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})};return n.jsx("div",{className:`admesh-layout ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:v()})};class Nr{constructor(e){Ke(this,"firedExposures",new Set);Ke(this,"debug",!1);Ke(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,o,s){const i=`${s}_${o}`;if(this.firedExposures.has(i)){this.debug&&l.log("[Tracker] Exposure already fired");return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&l.warn("[Tracker] Failed to fire exposure")}),this.debug&&l.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&l.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,i){const d=`${s}_${o}`;if(this.firedExposures.has(d)){this.debug&&l.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let w=null,g=null;const v=new IntersectionObserver(k=>{k.forEach(j=>{j.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?w===null&&(w=Date.now(),this.debug&&l.log("[Tracker] Ad reached MRC visibility threshold"),g=setTimeout(()=>{this.fireExposure(e,o,s),v.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):w!==null&&(g&&(clearTimeout(g),g=null),w=null,this.debug&&l.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});v.observe(i);const m=setTimeout(()=>{v.disconnect(),g&&clearTimeout(g),u()},3e4);i.__admeshTrackerCleanup=()=>{v.disconnect(),g&&clearTimeout(g),clearTimeout(m)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,o,s){this.fireExposure(e,o,s)}fireFollowupEngagement(e,o,s){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s})}).catch(i=>{this.debug&&l.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const qn=a.createContext(void 0);function On(){const t=a.useContext(qn);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function Xo(t){const e=t.split("/").filter(Boolean),i=(e[e.length-1]||e[e.length-2]||"").replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i?i.replace(/\b\w/g,d=>d.toUpperCase()):"This page"}function $r(){var t;try{console.log("[AdMesh] Starting direct headings extraction...");const e=v=>v.replace(/\s+/g," ").trim(),o=()=>{var f;const v=["article","main article","main",'[role="main"]',"[data-admesh-article]",".article-content",".post-content",".entry-content",".content"],c=["script","style","noscript","svg","canvas","iframe","nav","header","footer","aside",'[aria-hidden="true"]',"[data-admesh-ignore]",".admesh-publisher-assistant-root",".admesh-publisher-assistant-reactMount",".admesh-publisher-assistant-floating",".admesh-publisher-assistant-inline"].join(","),j=(((f=v.map(h=>document.querySelector(h)).filter(h=>!!h).map(h=>{const S=h.cloneNode(!0);S.querySelectorAll(c).forEach(G=>G.remove());const I=e(S.textContent||"");return{element:h,text:I}}).filter(h=>h.text.length>=200).sort((h,S)=>S.text.length-h.text.length)[0])==null?void 0:f.element)||document.body).cloneNode(!0);j.querySelectorAll(c).forEach(h=>h.remove());const p=Array.from(j.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(h=>e(h.textContent||"")).filter(h=>h.length>=24);return(p.length>0?p.join(`
|
|
150
|
-
`):e(j.textContent||"")).slice(0,6e3)},s=
|
|
151
|
-
Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const ss=6e4,Sr=3;function is(t){const e=rs();if(e)return e;const o=t==null?void 0:t.trim();return Fr(o)?o:null}const Wr=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:d,location:u,userId:w,model:g,messages:v,pageContext:c,articleUrl:m,contextMode:k="auto",agentDisplayId:j,children:p})=>{const[x,f]=a.useState(null),[h,S]=a.useState(new Set),[I,G]=a.useState(new Map),[A,C]=a.useState(null),[L,N]=a.useState([]),[F,P]=a.useState(!1),[z,M]=a.useState(null),[B,K]=a.useState(!1),X=a.useRef(!1),U=a.useRef(0),H=a.useRef(null),ne=a.useRef(null);ne.current=A;const ce=!!c||k==="ad-slot"||k==="auto"&&(!!(m!=null&&m.trim())||ns()),q=a.useCallback(async()=>{if(c)return c;if(!ce)return $r();const $=is(m);if(!$)return l.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),M("Article URL is required for ad-slot context"),null;if(!t||!i)return l.warn("[AdMeshProvider] Cannot fetch page context: missing API key or base URL"),kr($);try{K(!0);const Q=await ts($,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:j});return l.log("[AdMeshProvider] Page context resolved",{source:Q.source,cache_hit:Q.cache_hit,domain:Q.context.domain}),Q.context}catch(Q){return l.error("[AdMeshProvider] Failed to fetch page context:",Q),l.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),kr($)}finally{K(!1)}},[j,i,t,m,c,ce]),Ce=a.useCallback(($,Q)=>{const J=$.filter(ee=>!ee.is_sponsored).slice(0,3);return[Q,...J]},[]),ke=a.useCallback(($,Q)=>{const J=$.find(oe=>oe.is_sponsored),ee=Q.filter(oe=>!oe.is_sponsored).slice(0,3);return J?[J,...ee]:ee},[]);a.useEffect(()=>{if(!e||e.trim()===""){l.error("[AdMeshProvider] โ sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}l.log("[AdMeshProvider] โ
Session ID available:",e)},[e]),a.useEffect(()=>{if(!t){l.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){l.error("[AdMeshProvider] โ Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const $=new cn({apiKey:t,theme:s,apiBaseUrl:i,extension:o});f($),l.log("[AdMeshProvider] โ
AdMesh SDK initialized with session:",e),i&&l.log("[AdMeshProvider] ๐ Using custom API base URL")}catch($){l.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK:",$)}return()=>{l.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,s,i,e,o]);const tt=a.useCallback(async $=>{var Q;if(!t||!i){l.warn("[AdMeshProvider] โ ๏ธ Cannot perform intent analysis: missing API key or base URL");return}if(o)l.log("[AdMeshProvider] โน๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){l.log('[AdMeshProvider] โน๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{P(!0),M(null),l.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const J=$??await q();if(!J){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),M("Failed to extract page content");return}l.log("[AdMeshProvider] ๐ Extracted headings:",{title:J.title,headingsCount:J.headings.length,articleTextLength:((Q=J.article_text)==null?void 0:Q.length)||0,domain:J.domain});const oe=await Lr(J,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:w});oe?(l.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:oe.suggestions.length,suggestions:(oe.suggestions||[]).map(Se=>{var D;return{id:Se.id,text:Se.text,is_sponsored:Se.is_sponsored,recommendationId:((D=Se.recommendation)==null?void 0:D.recommendation_id)||null}})}),N(Se=>ke(Se,oe.suggestions||[]))):(l.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),M("Intent analysis failed"),N(Se=>Se.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),Se):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(J){l.error("[AdMeshProvider] โ Error in intent analysis:",J),M("Intent analysis error"),N(ee=>ee.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),ee):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{P(!1)}},[t,i,o,w,ke,q]),Ee=a.useCallback(async $=>{var ee,oe,Se,D,ie,T;if(!x||!t||!t.toLowerCase().startsWith("pub_"))return;const Q=$??await q();if(!Q){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const J=((oe=(ee=Q.headings)==null?void 0:ee[0])==null?void 0:oe.trim())||((Se=Q.title)==null?void 0:Se.trim());if(!J){l.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{l.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const E=await x.fetchPlatformResponse({query:J,sessionId:e,messageId:cn.createMessageId(e),platformSurface:"embedded_assistant",model:g,messages:[],language:d,location:u,userId:w}),fe=(T=(ie=(D=E.recommendation)==null?void 0:D.creative)==null?void 0:ie.follow_up_suggestion)==null?void 0:T.trim(),te=E.recommendation_id;if(!fe||!te){l.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const Ge={id:te,text:fe,type:"action",is_sponsored:!0,recommendation:E,metadata:{source:"aip_context_prefetch",recommendation_id:te}};N(pe=>Ce(pe,Ge)),l.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:te,suggestionText:fe})}catch(E){l.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",E)}},[t,d,u,g,x,e,w,Ce,q]),be=a.useCallback(async()=>{l.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await tt()},[tt]);a.useEffect(()=>{!x||X.current||(X.current=!0,(async()=>{const $=await q();await Promise.allSettled([Ee($),tt($)])})())},[x,tt,Ee,q]);const se=a.useCallback($=>{if(!$||$.status!=="active")return!1;const Q=Date.parse($.expires_at);return Number.isNaN(Q)?!1:Q>Date.now()},[]),ue=a.useCallback(async($,Q,J,ee)=>{const oe=ee??A;if(!oe||!x){l.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:$,eventType:Q,hasSession:!!oe,hasSdk:!!x});return}const Se=new Date().toISOString();l.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:$,eventType:Q,recommendationId:oe.recommendation_id,delegationSessionId:oe.delegation_session_id,sessionId:oe.session_id});const D=await fetch(`${x.getApiBaseUrl()}${$}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:oe.delegation_session_id,recommendation_id:oe.recommendation_id,session_id:oe.session_id,event_type:Q,timestamp:Se,metadata:J||{}})});if(!D.ok){const E=await D.text();throw l.error("[AdMeshProvider] โ Delegation event failed",{endpoint:$,eventType:Q,status:D.status,errorBody:E,recommendationId:oe.recommendation_id,delegationSessionId:oe.delegation_session_id}),new Error(`Delegation event failed (${D.status}): ${E}`)}const ie=await D.json(),T=ie==null?void 0:ie.session;l.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:$,eventType:Q,recommendationId:oe.recommendation_id,delegationSessionId:oe.delegation_session_id,returnedStatus:(T==null?void 0:T.status)||(ie==null?void 0:ie.status)}),T&&C(T)},[A,t,x]),le=a.useCallback(()=>{U.current=0},[]),me=a.useCallback(async($="user_stopped",Q)=>{const J=A;if(!J){l.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}l.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:$,recommendationId:J.recommendation_id,delegationSessionId:J.delegation_session_id}),await ue("/aip/delegation/stop","session_stopped",{reason:$,...Q||{}},J),await(x==null?void 0:x.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:J.session_id,recommendation_id:J.recommendation_id,delegation_session_id:J.delegation_session_id,brand_name:J.brand_name,status:"stopped",metadata:{reason:$,...Q||{}}}).catch(ee=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",ee)})),U.current=0,H.current=null,C(null),l.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},[A,ue,x]),Re=a.useCallback(async($="turn_completed",Q)=>{$==="turn_started"&&le(),await ue("/aip/delegation/activity",$,Q)},[ue,le]);a.useEffect(()=>{const $=(A==null?void 0:A.delegation_session_id)??null;$!==H.current&&(H.current=$,U.current=0)},[A==null?void 0:A.delegation_session_id]),a.useEffect(()=>{if(!((A==null?void 0:A.delegation_session_id)??null)||!x)return;const Q=ne.current;if(!Q||!se(Q)){C(ee=>ee?{...ee,status:"expired"}:null);return}const J=window.setInterval(()=>{const ee=ne.current;if(!(!ee||!se(ee))){if(U.current+=1,U.current>=Sr){l.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:ee.delegation_session_id,heartbeatsSinceLastUserTurn:U.current,idleHeartbeatLimit:Sr}),me("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:U.current}).catch(oe=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to stop idle delegation session:",oe)});return}ue("/aip/delegation/heartbeat","heartbeat").catch(oe=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",oe)})}},ss);return()=>{window.clearInterval(J)}},[A==null?void 0:A.delegation_session_id,se,ue,x,me]);const nt={sdk:x,apiKey:t,sessionId:e,theme:s,language:d,location:u,userId:w,model:g,messages:v,processedMessageIds:h,recommendationResults:I,activeDelegationSession:A,suggestions:L,isAnalyzingIntent:F||B,intentError:z,markMessageAsProcessed:$=>{S(Q=>{const J=new Set(Q);return J.add($),J})},isMessageProcessed:$=>h.has($),setRecommendationResult:($,Q)=>{G(J=>{const ee=new Map(J);return ee.set($,Q),ee}),S(J=>{const ee=new Set(J);return ee.add($),ee})},getRecommendationResult:$=>I.get($),hasRecommendationResult:$=>I.has($),setActiveDelegationSession:$=>{C($)},getActiveDelegationSession:()=>se(A)?A:null,hasActiveDelegationSession:()=>se(A),refreshDelegationActivity:Re,stopDelegationSession:me,retryIntentAnalysis:be};return n.jsx(qn.Provider,{value:nt,children:p})};class Br{constructor(){Ke(this,"roots",new Map)}async render(e){try{l.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){l.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw l.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);l.log("[AdMeshRenderer] โ
Container ready");const i=this.roots.get(e.containerId);i&&(l.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const d=go.createRoot(s);l.log("[AdMeshRenderer] ๐ Rendering recommendations"),d.render(n.jsx(Wr,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:n.jsx(zr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",l.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,d)}catch(o){throw l.error("[AdMeshRenderer] โ Error rendering recommendations"),o}}unmount(e){const o=this.roots.get(e);if(o){o.unmount(),this.roots.delete(e);const s=document.getElementById(e);s&&(s.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}const as=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},Ct=class Ct{constructor(e){Ke(this,"config");Ke(this,"apiBaseUrl");Ke(this,"renderer",null);Ke(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl,extension:e.extension,extensionSourceDomain:e.extensionSourceDomain,userId:e.userId},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static buildPlatformResponseCacheKey(e,o){return`${e}::${o}`}getExtensionSourceDomain(){var o,s;const e=(o=this.config.extensionSourceDomain)==null?void 0:o.trim();if(e)return e.toLowerCase();if(typeof window<"u"&&((s=window.location)!=null&&s.hostname))return window.location.hostname.trim().toLowerCase()||void 0}static createSession(){const e=Date.now(),o=Math.random().toString(36).substring(2,15);return`session_${e}_${o}`}static generateSessionIdFromUrl(e){const o=e||(typeof window<"u"?window.location.href:"");if(!o)return Ct.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),d=i[i.length-1];return d?`session_${Date.now()}_${d}`:Ct.createSession()}catch{return Ct.createSession()}}static createMessageId(e){const o=Date.now(),s=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${o}_${s}`:`msg_${o}_${s}`}getRenderer(){return this.renderer||(this.renderer=new Br),this.renderer}getTracker(){return this.tracker||(this.tracker=new Nr({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const d=await fetch(`${this.apiBaseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({delegation_session_id:o.delegation_session_id,recommendation_id:o.recommendation_id,session_id:o.session_id,event_type:s,timestamp:new Date().toISOString(),metadata:i||{}})});if(!d.ok){const w=await d.text();throw new Error(`Delegation event failed (${d.status}): ${w}`)}const u=await d.json();return(u==null?void 0:u.session)||null}async reportDelegationTurnStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_started",o)}async reportDelegationSessionStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"session_started",o)}async reportDelegationTurnCompleted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_completed",o)}async reportDelegationToolInvocation(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"tool_invoked",o)}async reportDelegationOutcome(e,o,s){return this.postDelegationEvent("/aip/delegation/complete",e,o,s)}async stopDelegationSession(e,o="user_stopped",s){return this.postDelegationEvent("/aip/delegation/stop",e,"session_stopped",{reason:o,...s||{}})}getActiveDelegationSession(e){if(!e||e.status!=="active")return null;const o=Date.parse(e.expires_at);return Number.isNaN(o)||o<=Date.now()?null:e}hasActiveDelegationSession(e){return!!this.getActiveDelegationSession(e)}async showRecommendations(e){try{if(!e.sessionId||e.sessionId.trim()==="")throw new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");if(!e.messageId||e.messageId.trim()==="")throw new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");const o=await this.fetchPlatformResponse({query:e.query,sessionId:e.sessionId,messageId:e.messageId,platformSurface:e.platformSurface,model:e.model,messages:e.messages,language:e.locale,location:e.location,userId:e.userId??this.config.userId}),s={sessionId:e.sessionId,messageId:e.messageId,recommendations:[o]},i=this.getRenderer(),d=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:d,sessionId:e.sessionId,apiKey:this.config.apiKey,apiBaseUrl:this.apiBaseUrl,language:e.locale,location:e.location,userId:e.userId,model:e.model,messages:e.messages,onPasteToInput:e.onPasteToInput,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation,onExecuteQuery:e.onExecuteQuery})}catch(o){throw l.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var f,h,S,I,G,A,C,L,N,F,P,z,M;const o=`${this.apiBaseUrl}/aip/context`;if(l.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const B=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw l.error("[AdMeshSDK] โ sessionId not provided by platform - cannot process request"),B}const s=e.messageId;if(!s||s.trim()===""){const B=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw l.error("[AdMeshSDK] โ messageId not provided by platform - cannot process request"),B}const i=Ct.buildPlatformResponseCacheKey(e.sessionId,s),d=Ct.inFlightPlatformResponses.get(i);if(d)return l.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),d;const u=e.messages?e.messages.length:0,w=(typeof window<"u"&&window.navigator,"web"),g=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",v=as((f=e.location)==null?void 0:f.countryCode)||"US",c=typeof window<"u"&&window.location?{url:window.location.href,origin:window.location.origin,referrer:document.referrer||void 0,host:window.location.hostname}:void 0,m=e.userId??this.config.userId,k={spec_version:"1.0",message_id:s,timestamp:new Date().toISOString(),platform:{platform_id:"placeholder",role:"platform",software:{name:"admesh_ui_sdk",version:e.model||"1.0.0"}},identity:{namespace:"platform_user",value_hash:m||"",confidence:m?1:0},consent:{status:"granted",source:"admesh_ui_sdk",scope:{intent_based_monetization:!0,agent_participation:!0,measurement:!0},constraints:{allow_identity_downstream:!1}},classification_input:{type:"interaction",interaction:{session:{id:e.sessionId,turn_index:u},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:w,form_factor:g,locale:e.language||"en-US",country:v,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((h=e.location)==null?void 0:h.city)||void 0,state:((S=e.location)==null?void 0:S.state)||void 0,state_code:((I=e.location)==null?void 0:I.stateCode)||void 0,country:((G=e.location)==null?void 0:G.country)||void 0,country_code:v,zipcode:((A=e.location)==null?void 0:A.zipcode)||void 0,latitude:(C=e.location)==null?void 0:C.latitude,longitude:(L=e.location)==null?void 0:L.longitude},page:c}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(F=(N=k.classification_input.interaction)==null?void 0:N.input.query_text)!=null&&F.trim()||l.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const j=JSON.stringify(k);l.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:k.message_id,specVersion:k.spec_version,classificationType:k.classification_input.type,platformId:k.platform.platform_id,surfaceChannel:(P=k.classification_input.interaction)==null?void 0:P.surface.channel,sessionId:(M=(z=k.classification_input.interaction)==null?void 0:z.session)==null?void 0:M.id});const p={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){p["X-AdMesh-Source"]="extension";const B=this.getExtensionSourceDomain();B&&(p["X-AdMesh-Source-Domain"]=B)}const x=(async()=>{const B=await fetch(o,{method:"POST",headers:p,body:j});if(!B.ok){const U=(await B.json().catch(()=>({}))).detail||`HTTP ${B.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${U}`)}const K=await B.json();return l.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{status:K.status,recommendationId:K.recommendation_id,hasRecommendation:!!K.recommendation,hasTracking:!!K.tracking,hasDelegation:!!K.delegation,topLevelKeys:Object.keys(K)}),l.log("[AdMeshSDK] ๐ฆ Full PlatformResponse received from /aip/context",K),K})();Ct.inFlightPlatformResponses.set(i,x);try{return await x}finally{Ct.inFlightPlatformResponses.delete(i)}}async trackPublisherAssistantEvent(e){const o=Array.isArray(e)?{events:e}:e,s=await fetch(`${this.apiBaseUrl}/analytics/publisher-assistant/events`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),keepalive:!0});if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Failed to track publisher assistant analytics (${s.status}): ${i}`)}}async reportSponsoredRecommendation(e){const o=await fetch(`${this.apiBaseUrl}/analytics/recommendation-reports`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(e),keepalive:!0});if(!o.ok){const s=await o.text().catch(()=>"");throw new Error(`Failed to report sponsored recommendation (${o.status}): ${s}`)}}fireFollowupExposure(e,o,s){this.getTracker().fireFollowupExposure(e,o,s)}async fireFollowupEngagement(e,o,s){return this.getTracker().fireFollowupEngagement(e,o,s)}};Ke(Ct,"inFlightPlatformResponses",new Map);let cn=Ct;class Vn{constructor(e={}){Ke(this,"autoAddLabels");Ke(this,"fireExposurePixels");Ke(this,"labelStyle");Ke(this,"processedLinks",new Set);Ke(this,"mutationObserver",null);var o,s,i,d;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((o=e.labelStyle)==null?void 0:o.fontSize)||"0.75em",fontWeight:((s=e.labelStyle)==null?void 0:s.fontWeight)||"bold",color:((i=e.labelStyle)==null?void 0:i.color)||"#666",marginLeft:((d=e.labelStyle)==null?void 0:d.marginLeft)||"2px"}}getLinksToProcess(e){const s=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return s.length>0?Array.from(s):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,o,s){if(!e)return[];const i=[];if(o.length>0){const d=this.getLinksToProcess(e),u=new Map(o.map(g=>{var v,c,m;return[((v=g==null?void 0:g.tracking)==null?void 0:v.click_url)||((m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url)||"",g]}).filter(([g])=>!!g)),w=new Map;o.forEach(g=>{var c,m;const v=(m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url;if(v&&typeof v=="string"){const k=v.trim().replace(/\/$/,"");w.set(k,g),w.set(`${k}/`,g)}}),d.forEach(g=>{var j,p,x,f,h,S,I,G;const v=g.getAttribute("href")||"",c=`${v}`;if(this.processedLinks.has(c))return;let m=u.get(v),k=v;if(!m){const A=v.trim().replace(/\/$/,"");m=w.get(A)||w.get(`${A}/`);const C=((j=m==null?void 0:m.tracking)==null?void 0:j.click_url)||((x=(p=m==null?void 0:m.recommendation)==null?void 0:p.creative)==null?void 0:x.landing_page_url);m&&C&&(l.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",v),g.setAttribute("href",C),k=C)}if(m){this.processedLinks.add(c),g.setAttribute("target","_blank"),g.setAttribute("rel","noopener noreferrer");const A={element:g,href:k,text:g.textContent||"",hasAdLabel:this.hasAdLabel(g),matchedRecommendation:{recommendation_id:(m==null?void 0:m.recommendation_id)||"",click_url:((f=m==null?void 0:m.tracking)==null?void 0:f.click_url)||((S=(h=m==null?void 0:m.recommendation)==null?void 0:h.creative)==null?void 0:S.landing_page_url)||"",exposure_url:(I=m==null?void 0:m.tracking)==null?void 0:I.exposure_url}};this.autoAddLabels&&!A.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",k),this.addAdLabel(g),A.hasAdLabel=!0):this.autoAddLabels?A.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const C=(G=m==null?void 0:m.tracking)==null?void 0:G.exposure_url;this.fireExposurePixels&&C&&s&&A.matchedRecommendation&&s({exposureUrl:C,recommendationId:A.matchedRecommendation.recommendation_id,linkElement:g}),i.push(A)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const w=u.getAttribute("href")||"",g=`${w}`;if(this.processedLinks.has(g))return;if(this.isAdMeshLink(w)){this.processedLinks.add(g);const c={element:u,href:w,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:void 0};if(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to pattern-matched AdMesh link:",w),this.addAdLabel(u),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const m=this.convertClickUrlToExposureUrl(w);s({exposureUrl:m,recommendationId:this.extractRecommendationIdFromUrl(w),linkElement:u})}i.push(c)}});return i}hasAdLabel(e){var u,w,g;if((e.textContent||"").includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Link text contains Ad label"),!0;const s=e.querySelectorAll("sub, span");for(const v of Array.from(s))if((u=v.textContent)!=null&&u.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Link has Ad label as child element"),!0;let i=e.previousSibling;for(;i&&i.nodeType===Node.TEXT_NODE;){const v=i.textContent||"";if(v.trim()===""){i=i.previousSibling;continue}if(v.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const v=i,c=v.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((w=v.textContent)!=null&&w.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",c),!0}let d=e.nextSibling;for(;d&&d.nodeType===Node.TEXT_NODE;){const v=d.textContent||"";if(v.trim()===""){d=d.nextSibling;continue}if(v.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(d&&d.nodeType===Node.ELEMENT_NODE){const v=d,c=v.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((g=v.textContent)!=null&&g.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next element sibling:",c),!0}return l.log("[WeaveResponseProcessor] โน๏ธ No existing Ad label found"),!1}addAdLabel(e){if(l.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){l.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){l.log("[WeaveResponseProcessor] โน๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){l.error("[WeaveResponseProcessor] โ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const s=document.createElement("sub");s.textContent="Ad",s.style.fontSize=this.labelStyle.fontSize,s.style.fontWeight=this.labelStyle.fontWeight,s.style.color=this.labelStyle.color,s.style.marginLeft=this.labelStyle.marginLeft,s.style.cursor="pointer",s.style.borderBottom=`1px dotted ${this.labelStyle.color}`,s.style.whiteSpace="nowrap",s.title="Why this ad? This is a sponsored recommendation based on your search query.";let i=!1;s.addEventListener("mouseenter",()=>{s.style.opacity="0.7"}),s.addEventListener("mouseleave",()=>{s.style.opacity="1",i&&(i=!1)}),s.addEventListener("click",u=>{u.stopPropagation(),i=!i,i?(s.style.textDecoration="underline",s.style.opacity="0.7"):(s.style.textDecoration="none",s.style.opacity="1")});const d=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",d);try{const u=e.nextSibling;u?(o.insertBefore(s,u),l.log("[WeaveResponseProcessor] โ
Ad label inserted before next sibling")):(o.appendChild(s),l.log("[WeaveResponseProcessor] โ
Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?l.log("[WeaveResponseProcessor] โ
Ad label successfully added to link:",e.href):l.error("[WeaveResponseProcessor] โ Ad label insertion failed - label not in DOM")}catch(u){l.error("[WeaveResponseProcessor] โ Error inserting Ad label:",u)}}removeLeftAdLabel(e){var s,i,d;let o=e.previousSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const u=o.textContent||"";if(u.trim()===""){o=o.previousSibling;continue}if(u.includes("Ad")){(s=o.parentNode)==null||s.removeChild(o);return}break}if(o&&o.nodeType===Node.ELEMENT_NODE){const u=o;(u.tagName==="SUB"||u.tagName==="SPAN")&&((i=u.textContent)!=null&&i.includes("Ad"))&&((d=u.parentNode)==null||d.removeChild(u))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(i=>e.includes(i)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractRecommendationIdFromUrl(e){try{const o=e.match(/\/click\/([^/?]+)/);return o&&o[1]?o[1]:""}catch{return e}}convertClickUrlToExposureUrl(e){try{const o=new URL(e),i=`${`${o.protocol}//${o.host}`}/exposure`,d=new URLSearchParams(o.search);return d.has("cpx")||d.set("cpx","0"),`${i}?${d.toString()}`}catch{return l.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,o,s){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,o,s)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}function tn(){const t=On();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,language:t.language,location:t.location,userId:t.userId,model:t.model,messages:t.messages,processedMessageIds:t.processedMessageIds,recommendationResults:t.recommendationResults,activeDelegationSession:t.activeDelegationSession,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed,setRecommendationResult:t.setRecommendationResult,getRecommendationResult:t.getRecommendationResult,hasRecommendationResult:t.hasRecommendationResult,setActiveDelegationSession:t.setActiveDelegationSession,getActiveDelegationSession:t.getActiveDelegationSession,hasActiveDelegationSession:t.hasActiveDelegationSession,refreshDelegationActivity:t.refreshDelegationActivity,stopDelegationSession:t.stopDelegationSession}}const ls=({className:t,size:e=20})=>n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M5 12h14"}),n.jsx("path",{d:"M12 5v14"})]}),Ur=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var k,j,p,x,f;const d=(j=(k=t.recommendation)==null?void 0:k.creative)!=null&&j.follow_up_suggestion&&((p=t.tracking)!=null&&p.followup_engagement_url)&&((x=t.tracking)!=null&&x.followup_exposure_url)?{query:t.recommendation.creative.follow_up_suggestion,engagement_url:t.tracking.followup_engagement_url,exposure_url:t.tracking.followup_exposure_url}:null,u=d==null?void 0:d.query,w=d==null?void 0:d.engagement_url,g=d==null?void 0:d.exposure_url,v=t.recommendation_id,c=((f=t.recommendation)==null?void 0:f.offerId)||v;if(!u||!w||!g)return l.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const m=async()=>{try{w&&v&&(l.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(w,v,s)),i&&u?(l.log(`[AdMeshFollowup] ๐ Executing query: ${u}`),await i(u)):l.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(h){l.error("[AdMeshFollowup] โ Error handling follow-up click:",h)}};return n.jsx(un,{productId:c,recommendationId:v||"",exposureUrl:g,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:n.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[n.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),n.jsxs("div",{onClick:m,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&m()},"aria-label":`Sponsored follow-up: ${u}`,children:[n.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),n.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),n.jsx(ls,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},dn=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:d,triggerExposureUrl:u=!0,followups_container_id:w,onPasteToInput:g,onDelegationConsent:v,onDelegationActivated:c,onStartDelegation:m,onRecommendationReport:k,onExecuteQuery:j,onFollowupDetected:p,isContainerReady:x})=>{var J,ee,oe,Se;const{sdk:f,sessionId:h,apiKey:S,language:I,location:G,userId:A,model:C,messages:L,theme:N,getRecommendationResult:F,hasRecommendationResult:P,setRecommendationResult:z,activeDelegationSession:M,setActiveDelegationSession:B,hasActiveDelegationSession:K}=tn(),X=D=>!!D&&D.status==="generated"&&!!D.recommendation,U=i||A,[H,ne]=a.useState(null),[ce,q]=a.useState(null),[Ce,ke]=a.useState(!0),[tt,Ee]=a.useState(null),be=a.useRef(null),se=a.useRef(!1),ue=a.useRef(!1),le=a.useRef(t),me=a.useRef(e);a.useEffect(()=>{le.current=t,me.current=e},[t,e]),a.useEffect(()=>{be.current!==o&&(be.current=null,ue.current=!1,ne(null),q(null))},[o]);const Re=K()&&(M==null?void 0:M.session_id)===h;a.useEffect(()=>{var T,E,fe;if(!o||!P(o)||Re)return;const D=F(o);if(!D){l.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),ne(null),q(null),Ee(null),ke(!1),be.current=o,se.current=!1,ue.current=!0;return}let ie=((T=D.recommendation)==null?void 0:T.format)||"tail";(ie==="weave"||ie==="product_card")&&(ie="tail"),l.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:D.recommendation_id,format:(E=D.recommendation)==null?void 0:E.format}),ne(D),q(ie),Ee(null),ke(!1),be.current=o,se.current=!1,ue.current=!0,(fe=le.current)==null||fe.call(le,o,D)},[F,P,Re,o]),a.useEffect(()=>{var D,ie,T,E,fe,te,Ge;if(!(!d||!o)&&!Re)try{const pe=d,Be=d.status||"unknown";if(!X(pe)){if(Be==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),ne(null),q(null),Ee(null),ke(!1),be.current=o,se.current=!1,ue.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${Be})`)}let Ie=((D=pe.recommendation)==null?void 0:D.format)||"tail";(Ie==="weave"||Ie==="product_card")&&(Ie="tail"),ne(pe),q(Ie),Ee(null),ke(!1),be.current=o,se.current=!1,ue.current=!0,z(o,pe),(ie=le.current)==null||ie.call(le,o,pe),l.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),l.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:pe.recommendation_id,format:(T=pe.recommendation)==null?void 0:T.format,brandName:(fe=(E=pe.recommendation)==null?void 0:E.creative)==null?void 0:fe.brand_name,headline:(Ge=(te=pe.recommendation)==null?void 0:te.creative)==null?void 0:Ge.headline,hasTracking:!!pe.tracking})}catch(pe){const Be=pe instanceof Error?pe:new Error(String(pe));ue.current=!1,l.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${Be.message}`)}},[Re,d,o,z]),a.useEffect(()=>{if(!o||!s||s.trim()===""){l.log("[AdMeshRecommendations] โ Validation failed - missing required parameters"),ke(!1);return}if(Re){l.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:h,delegationSessionId:M==null?void 0:M.delegation_session_id}),ne(null),q(null),Ee(null),ke(!1),se.current=!1;return}if(!(f!=null&&f.fetchPlatformResponse)){l.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),ke(!1);return}if(ue.current){l.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(be.current===o){l.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(se.current){l.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}l.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var ie,T,E,fe,te,Ge,pe,Be,Ie;try{se.current=!0,ke(!0),Ee(null);const Ae=await f.fetchPlatformResponse({query:s.trim(),sessionId:h,messageId:o,language:I,location:G,userId:U,model:C,...L&&L.length>0&&{messages:L}}),ye=(Ae==null?void 0:Ae.status)||"unknown";if(!X(Ae)){if(ye==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),ne(null),q(null),Ee(null),ke(!1),se.current=!1,be.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${ye})`)}ne(Ae),l.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:Ae.recommendation_id,format:(ie=Ae.recommendation)==null?void 0:ie.format,brandName:(E=(T=Ae.recommendation)==null?void 0:T.creative)==null?void 0:E.brand_name,headline:(te=(fe=Ae.recommendation)==null?void 0:fe.creative)==null?void 0:te.headline,hasTracking:!!Ae.tracking});let Pe=((Ge=Ae.recommendation)==null?void 0:Ge.format)||"tail";(Pe==="weave"||Pe==="product_card")&&(Pe="tail"),q(Pe),be.current=o,z(o,Ae),l.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(pe=Ae.recommendation)==null?void 0:pe.format,selected_format:Pe}),ke(!1),se.current=!1,(Be=le.current)==null||Be.call(le,o,Ae)}catch(Ae){const ye=Ae instanceof Error?Ae:new Error(String(Ae));ye.message.includes("Failed to fetch")||ye.message.includes("NetworkError")?l.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${ye.message} `):l.error(`[AdMeshRecommendations] โ Error fetching recommendations: ${ye.message} `),Ee(ye),ke(!1),se.current=!1,(Ie=me.current)==null||Ie.call(me,ye)}})()},[M==null?void 0:M.delegation_session_id,Re,f,h,o,s,I,G,U,C,d,z]),a.useEffect(()=>{var ie,T,E,fe;if(!H||!p)return;const D=(T=(ie=H.recommendation)==null?void 0:ie.creative)!=null&&T.follow_up_suggestion&&((E=H.tracking)!=null&&E.followup_engagement_url)&&((fe=H.tracking)!=null&&fe.followup_exposure_url)?{label:H.recommendation.creative.follow_up_suggestion,query:H.recommendation.creative.follow_up_suggestion,engagement_url:H.tracking.followup_engagement_url,exposure_url:H.tracking.followup_exposure_url}:null;D&&p(D,H.recommendation_id)},[H,p]);const nt=a.useCallback(async D=>{if(!f||!h)throw new Error("AdMesh SDK activation requires an initialized session");const ie=await fetch(`${f.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({session_id:h,recommendation_id:D.recommendation_id,metadata:D.metadata})});if(!ie.ok){const te=await ie.text();throw new Error(`Failed to activate delegation session: ${ie.status} ${te}`)}const T=await ie.json(),E={...D,delegation_session_id:T.delegation_session_id||D.delegation_session_id,session_id:T.session_id||h,brand_id:T.brand_id||D.brand_id,brand_name:T.brand_name||D.brand_name,mcp_endpoint:T.mcp_endpoint,eligibility_reason:T.eligibility_reason||D.eligibility_reason,delegate_reason:T.delegate_reason||D.delegate_reason,session_goal:T.session_goal||D.session_goal,desired_outcome_type:T.desired_outcome_type||D.desired_outcome_type,required_user_inputs:T.required_user_inputs||D.required_user_inputs||[],required_consent_types:T.required_consent_types||D.required_consent_types||[],success_outcome:T.success_outcome||D.success_outcome,fallback_message:T.fallback_message||D.fallback_message,session_mode:"inline",status:T.status||"active",capabilities:T.capabilities||D.capabilities||[],allowed_data_types:T.allowed_data_types||D.allowed_data_types||[],auth_model:T.auth_model||D.auth_model,handoff_protocol:T.handoff_protocol||D.handoff_protocol,supported_actions:T.supported_actions||D.supported_actions||[],metadata:T.metadata||D.metadata},fe={delegation_session_id:T.delegation_session_id,recommendation_id:D.recommendation_id,session_id:T.session_id||h,brand_agent_id:T.brand_agent_id,brand_id:T.brand_id||D.brand_id,brand_name:T.brand_name||D.brand_name||"Brand",mcp_endpoint:T.mcp_endpoint,status:T.status||"active",activated_at:T.created_at,last_activity_at:T.updated_at,expires_at:T.expires_at||T.updated_at,eligibility_reason:T.eligibility_reason||D.eligibility_reason,delegate_reason:T.delegate_reason||D.delegate_reason,session_goal:T.session_goal||D.session_goal,desired_outcome_type:T.desired_outcome_type||D.desired_outcome_type,required_user_inputs:T.required_user_inputs||D.required_user_inputs||[],required_consent_types:T.required_consent_types||D.required_consent_types||[],success_outcome:T.success_outcome||D.success_outcome,fallback_message:T.fallback_message||D.fallback_message,capabilities:T.capabilities||D.capabilities||[],allowed_data_types:T.allowed_data_types||D.allowed_data_types||[],consent_requirements:T.consent_requirements||D.consent_requirements||[],auth_model:T.auth_model||D.auth_model,handoff_protocol:T.handoff_protocol||D.handoff_protocol,supported_actions:T.supported_actions||D.supported_actions||[],metadata:T.metadata||D.metadata};if(B(fe),await f.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:h,recommendation_id:D.recommendation_id,delegation_session_id:T.delegation_session_id,brand_name:fe.brand_name,status:T.status||"active",metadata:{brand_agent_id:T.brand_agent_id,source:"recommendation_card"}}).catch(te=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",te)}),await f.reportDelegationSessionStarted(fe,{brand_agent_id:T.brand_agent_id,brand_name:fe.brand_name}).then(te=>{te&&B(te)}).catch(te=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",te)}),c){try{await c(E)}catch(te){l.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",te)}return}if(m)try{await m({...D.platform_response,delegation:{...D.platform_response.delegation,...E,delegation_session_id:T.delegation_session_id,available:!0,status:T.status||"active"}})}catch(te){l.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",te)}},[S,c,m,f,h,B]),$=a.useCallback(async D=>{var ie,T;if(k){await k(D);return}!f||!h||await f.reportSponsoredRecommendation({session_id:h,message_id:o,recommendation_id:D.recommendation_id,reason:D.reason,brand_name:(T=(ie=D.recommendation.recommendation)==null?void 0:ie.creative)==null?void 0:T.brand_name,metadata:{reason:D.reason,source:"recommendation_card"}}).catch(E=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report sponsored recommendation:",E)})},[o,k,f,h]);if(!o||!s||s.trim()===""||Ce||tt)return null;if(!H||!ce)return l.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!H,detectedFormat:ce,isLoading:Ce,hasError:!!tt}),null;l.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:H.recommendation_id,detectedFormat:ce,brandName:(ee=(J=H.recommendation)==null?void 0:J.creative)==null?void 0:ee.brand_name,headline:(Se=(oe=H.recommendation)==null?void 0:oe.creative)==null?void 0:Se.headline});const Q=typeof document<"u"&&w&&(x??!0)?document.getElementById(w):null;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:n.jsx(Hn,{recommendations:[H],theme:N,sessionId:h,triggerExposureUrl:u,onPasteToInput:g,onDelegationConsent:v,onDelegationActivated:nt,onStartDelegation:m,onRecommendationReport:$})}),Q&&f&&h?Un.createPortal(n.jsx(Ur,{recommendation:H,theme:N,sdk:f,sessionId:h,onExecuteQuery:j}),Q):null]})},Hr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:d})=>{const{sdk:u,sessionId:w,theme:g,apiKey:v,language:c,location:m,userId:k,model:j,messages:p}=tn(),x=a.useRef(null),[f,h]=a.useState("");return a.useEffect(()=>{o&&h(`admesh-weave-fallback-${o}`)},[o]),l.log("[WeaveFallbackRecommendations] ๐จ Component render"),a.useEffect(()=>{if(l.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:i,hasPreviousRecommendations:d&&d.length>0,previousRecommendationsCount:(d==null?void 0:d.length)||0}),!i){l.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(l.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){l.log("[WeaveFallbackRecommendations] โ Validation failed - returning early");return}if(l.log("[WeaveFallbackRecommendations] โ
Validation passed"),!u||!f){l.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const S=d&&d.length>0;l.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:S,count:(d==null?void 0:d.length)||0,fallback:i,messageId:o}),S?(l.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${d.length} previous recommendation(s), skipping API call`),(async()=>{var G,A,C,L,N,F,P;try{const z=d[0];if(l.log("[WeaveFallbackRecommendations] ๐ฆ Processing AIP response:",{hasAipResponse:!!z,recommendationId:(z==null?void 0:z.recommendation_id)||"",format:((G=z==null?void 0:z.recommendation)==null?void 0:G.format)||"unknown"}),z&&process.env.NODE_ENV==="development"&&l.log("[WeaveFallbackRecommendations] ๐ Recommendation received (DEV):",{recommendation_id:z==null?void 0:z.recommendation_id,click_url:((A=z==null?void 0:z.tracking)==null?void 0:A.click_url)||((L=(C=z==null?void 0:z.recommendation)==null?void 0:C.creative)==null?void 0:L.landing_page_url),format:(N=z==null?void 0:z.recommendation)==null?void 0:N.format,full_response:z}),!z){l.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o});return}const M=u,B=M.getRenderer,K=M.getTracker,X=(F=M.config)==null?void 0:F.theme;if(B&&K){const U={sessionId:w,messageId:o,recommendations:[z]},H=B.call(u),ne=K.call(u),ce=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await H.render({containerId:f,response:U,theme:g||X,tracker:ne,sessionId:w,apiKey:v||((P=u==null?void 0:u.config)==null?void 0:P.apiKey),apiBaseUrl:ce,language:c,location:m,userId:k,model:j,messages:p}),l.log("[WeaveFallbackRecommendations] โ
Recommendations rendered from previous response (no API call)")}else l.warn("[WeaveFallbackRecommendations] โ ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch(z){const M=z instanceof Error?z:new Error(String(z));l.error(`[WeaveFallbackRecommendations] โ Error rendering previous recommendations: ${M.message}`);try{await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch{e==null||e(M)}}})()):(l.log("[WeaveFallbackRecommendations] ๐ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){l.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o}),l.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(G){const A=G instanceof Error?G:new Error(String(G));l.log(`[WeaveFallbackRecommendations] โ Error: ${A.message}`),e==null||e(A)}})())},[u,w,f,t,o,s,i,e,d,g]),!i||!o||!s||s.trim()===""?null:n.jsx("div",{ref:x,id:f,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},qr=a.createContext(void 0),ds=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>n.jsx(qr.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),cs=()=>a.useContext(qr),zn=t=>{try{return new URL(t),!0}catch{return!1}},Ar=t=>t&&t.trim()?t.trim():"",Ht=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",bt=t=>Ht(t)||void 0,us=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},ms=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return Ht(t)},ps=(t,e,o)=>{if(t==null||t==="")return"";const s=(e||"percentage").trim().toLowerCase();if(typeof t=="number"){if(s==="amount"||s==="fixed"||s==="fixed_amount")try{return`${new Intl.NumberFormat("en-US",{style:"currency",currency:o||"USD",maximumFractionDigits:2}).format(t)} off`}catch{return`${t} off`}return`${t}% off`}const i=Ht(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},xe={surface:"#ffffff",surfaceMuted:"#f9fafb",surfaceSubtle:"#f8fafc",border:"rgba(17, 24, 39, 0.10)",text:"#111827",textSecondary:"#4b5563",textMuted:"#6b7280",link:"#2563eb",logoFallbackBg:"#f3f4f6",logoFallbackText:"#4b5563",productImageFallbackBg:"#e5e7eb",successText:"#065f46",successBg:"#d1fae5"},hs=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:g,onPasteToInput:v})=>{var fe,te,Ge,pe,Be,Ie,Ae,ye,Pe,Lt,ht,Te,We,ge,ot,Mt,jt,O,st,wt,Ft,qt,it,Y,we,at,lt,_t,Ot,vt,dt,Ye,Qt;if(!t||t.length===0)return l.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],m=((fe=c==null?void 0:c.recommendation)==null?void 0:fe.offerId)||"",k=((te=c==null?void 0:c.tracking)==null?void 0:te.exposure_url)||"",j=(c==null?void 0:c.recommendation_id)||"",p=((pe=(Ge=c==null?void 0:c.recommendation)==null?void 0:Ge.creative)==null?void 0:pe.description)||"",x=((Be=c==null?void 0:c.recommendation)==null?void 0:Be.disclosure)||"Sponsored",f=((Ae=(Ie=c==null?void 0:c.recommendation)==null?void 0:Ie.creative)==null?void 0:Ae.brand_name)||"",h=((Pe=(ye=c==null?void 0:c.recommendation)==null?void 0:ye.creative)==null?void 0:Pe.headline)||((ht=(Lt=c==null?void 0:c.recommendation)==null?void 0:Lt.creative)==null?void 0:ht.brand_name)||"",S=((We=(Te=c==null?void 0:c.recommendation)==null?void 0:Te.creative)==null?void 0:We.logo_url)||"",I=((ge=c==null?void 0:c.tracking)==null?void 0:ge.click_url)||((Mt=(ot=c==null?void 0:c.recommendation)==null?void 0:ot.creative)==null?void 0:Mt.landing_page_url)||"",G=Ar((O=(jt=c==null?void 0:c.recommendation)==null?void 0:jt.creative)==null?void 0:O.cta_text),A=((wt=(st=c==null?void 0:c.recommendation)==null?void 0:st.creative)==null?void 0:wt.products)||[],C=A.length>1,L=C?A.slice(0,4):[],N=((Ft=c==null?void 0:c.recommendation)==null?void 0:Ft.format)||"tail",F=N==="bridge",P=((qt=c==null?void 0:c.delegation)==null?void 0:qt.brand_name)||f,z=((it=c==null?void 0:c.delegation)==null?void 0:it.available)===!0,M=F&&z,B="Talk to Agent",K=!C&&!!G&&!!I;if(!f&&!h&&!p)return l.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:f,hasFirstRecommendation:!!c,recommendationId:j,recommendationKeys:c?Object.keys(c):[]}),null;let X=f,U="";h&&h!==f&&(U=h),U&&(X=`${f} โ ${U}`),l.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:j,productId:m,exposureUrl:k?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:I||"MISSING",clickUrlSource:(Y=c==null?void 0:c.tracking)!=null&&Y.click_url?"tracking.click_url":(at=(we=c==null?void 0:c.recommendation)==null?void 0:we.creative)!=null&&at.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:p?"present":"MISSING",brandName:f,productName:h,headlineText:X,triggerExposureUrl:d}),l.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:j,brandName:f,productName:h,hasDescription:!!p,hasClickUrl:!!I,hasLogoUrl:!!S,recommendationFormat:N});const H=(V,Fe)=>{Fe&&Fe.stopPropagation(),l.log(`AdMesh tail ad ${V} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:j,productId:m,clickUrl:I,source:V}).catch(()=>{l.error(`[AdMesh] Failed to track ${V} click`)})},ne=V=>{V.stopPropagation(),H("tail_ad_brand_name")},ce=V=>{V.stopPropagation(),H("tail_ad_cta")},q=V=>{V.stopPropagation(),H("tail_ad_logo")},Ce=()=>{C||!I||(H("tail_ad_card"),typeof window<"u"&&window.open(I,"_blank","noopener,noreferrer"))},ke=V=>{C||!I||(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),Ce())},[tt,Ee]=a.useState(!1),[be,se]=a.useState(!1),ue=a.useRef(null);a.useEffect(()=>()=>{ue.current&&(ue.current(!1),ue.current=null)},[]);const le=V=>{var Fe;V&&se(!0),(Fe=ue.current)==null||Fe.call(ue,V),ue.current=null,V||(se(!1),Ee(!1))},me=async()=>u?await u(c):await new Promise(V=>{ue.current=V,Ee(!0)}),Re=async()=>{if(j&&i)try{const V=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",Fe=await fetch(`${V}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:j,session_id:i,is_test:!1})});Fe.ok||l.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",Fe.statusText)}catch(V){l.error("[AdMesh Tail Ad] Error tracking delegation engagement:",V)}},nt=async V=>{var Et,Rt,It,Tt;if(V.preventDefault(),V.stopPropagation(),!c||!M)return;if(H("tail_ad_delegation_cta"),!await me()){l.log("[AdMesh Tail Ad] Delegation consent declined");return}Re();const ae=c.delegation,kt=ae!=null&&ae.available?{recommendation_id:c.recommendation_id,brand_id:bt(ae.brand_id),brand_name:bt(ae.brand_name||((Rt=(Et=c.recommendation)==null?void 0:Et.creative)==null?void 0:Rt.brand_name)),mcp_endpoint:bt(ae.mcp_endpoint),eligibility_reason:bt(ae.eligibility_reason),delegate_reason:bt(ae.delegate_reason),session_goal:bt(ae.session_goal),desired_outcome_type:ae.desired_outcome_type,required_user_inputs:Array.isArray(ae.required_user_inputs)?ae.required_user_inputs.filter(ft=>typeof ft=="string"):[],required_consent_types:Array.isArray(ae.required_consent_types)?ae.required_consent_types.filter(ft=>typeof ft=="string"):[],success_outcome:bt(ae.success_outcome),fallback_message:bt(ae.fallback_message),session_mode:bt(ae.session_mode),status:bt(ae.status),capabilities:ae.capabilities||[],allowed_data_types:ae.allowed_data_types||[],consent_requirements:ae.consent_requirements||[],auth_model:bt(ae.auth_model),handoff_protocol:ae.handoff_protocol&&typeof ae.handoff_protocol=="object"?ae.handoff_protocol:void 0,supported_actions:ae.supported_actions||[],metadata:ae.metadata&&typeof ae.metadata=="object"?ae.metadata:void 0,platform_response:c}:null;if(w&&kt){try{await w(kt)}finally{se(!1),Ee(!1)}return}if(g){try{await g(c)}finally{se(!1),Ee(!1)}return}const ct=((Tt=(It=c.recommendation)==null?void 0:It.creative)==null?void 0:Tt.follow_up_suggestion)||"";if(ct&&v){v(ct),se(!1),Ee(!1);return}if(ct&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(ct),se(!1),Ee(!1);return}se(!1),Ee(!1)},[$,Q]=a.useState(!1),J=f?f.charAt(0).toUpperCase():"B",ee=xe.surface,oe=xe.border,Se=(e==null?void 0:e.borderRadius)||((_t=(lt=e==null?void 0:e.components)==null?void 0:lt.card)==null?void 0:_t.borderRadius)||"8px",D="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",ie="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",T=((Ot=e==null?void 0:e.shadows)==null?void 0:Ot.medium)||((dt=(vt=e==null?void 0:e.components)==null?void 0:vt.card)==null?void 0:dt.boxShadow)||D,E=((Ye=e==null?void 0:e.shadows)==null?void 0:Ye.large)||ie;return n.jsxs(un,{productId:m,recommendationId:j,exposureUrl:k,sessionId:i,triggerExposureUrl:d,className:`admesh-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[n.jsx("style",{children:`
|
|
149
|
+
`}),n.jsxs("div",{role:!P&&A?"link":void 0,tabIndex:!P&&A?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((Ut=(Lt=e==null?void 0:e.components)==null?void 0:Lt.card)==null?void 0:Ut.borderRadius)||"14px",border:`1px solid ${Ne}`,background:Be,boxShadow:Se,minWidth:0,cursor:!P&&A?"pointer":void 0},onClick:ie,onKeyDown:D,children:[n.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[n.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:me?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!de&&G&&vr(G)?n.jsx("img",{src:G,alt:`${h} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>ke(!0)}):n.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:Ae},children:(h||"A").charAt(0).toUpperCase()})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{className:"admesh-compact-meta-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[n.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"11px",color:Ae},children:Ge?h:""}),n.jsx("span",{style:{flexShrink:0,fontSize:"10px",color:Ae,textTransform:"uppercase",letterSpacing:"0.08em"},children:L})]}),!P&&n.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",lineHeight:1.3,fontWeight:700,color:st,marginBottom:"4px"},title:ge,children:ge}),Z&&n.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"12px",lineHeight:1.35,color:bt},title:Z,children:Z})]})]}),P&&n.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:F.map(O=>{const Ce=rn(O.product_name)||"Product",Qe=rn(O.product_link)||rn(O.product_url)||A||"#",ut=Zo(O.product_price,O.product_currency),Rt=rn(O.product_image_url),It=Rt&&vr(Rt)?Rt:"",Ht=Qe!=="#";return n.jsx("a",{href:Qe,target:Ht?"_blank":void 0,rel:Ht?"noopener noreferrer":void 0,onClick:Tt=>ee(`compact_tail_ad_product_${O.product_id||"item"}`,Tt),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${Ne}`,borderRadius:"12px",background:Mt,padding:"8px",flexShrink:0},children:n.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[n.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:me?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:Ae,fontSize:"12px",fontWeight:700},children:It?n.jsx("img",{src:It,alt:Ce,style:{width:"100%",height:"100%",objectFit:"cover"}}):Ce.charAt(0).toUpperCase()}),n.jsxs("div",{style:{minWidth:0,flex:1},children:[n.jsx("div",{style:{fontSize:"12px",lineHeight:1.25,fontWeight:600,color:st,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:Ce,children:Ce}),n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:ut&&n.jsx("span",{style:{fontSize:"12px",fontWeight:700,color:st},children:ut})})]})]})},O.product_id||`${x}-${Ce}`)})}),n.jsxs("div",{className:"admesh-compact-footer-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:P?0:Pe},children:[n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:Oe}),n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",marginLeft:"auto",flexShrink:0},children:[P&&$.length>F.length?n.jsxs("span",{style:{fontSize:"10px",color:Ae},children:["+",$.length-F.length," more"]}):null,n.jsx("button",{type:"button","aria-label":se?"Recommendation reported":"Report recommendation",title:se?"Reported":"Report recommendation",disabled:!!se,onClick:Ie,style:{width:"28px",height:"28px",borderRadius:"999px",border:`1px solid ${Ne}`,background:se?Mt:Be,color:se?De:Ae,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,cursor:se?"default":"pointer",flexShrink:0},children:n.jsx(Ro,{size:13})})]})]}),Re?n.jsx("div",{className:"admesh-compact-report-panel",onClick:O=>O.stopPropagation(),style:{marginLeft:P?0:Pe,border:`1px solid ${Ne}`,borderRadius:"12px",background:Mt,padding:"8px",display:"flex",flexWrap:"wrap",gap:"6px"},children:re.map(O=>n.jsx("button",{className:"admesh-compact-report-option",type:"button",onClick:Ce=>T(Ce,O.value),style:{borderRadius:"999px",border:`1px solid ${Ne}`,background:Be,color:st,fontSize:"11px",fontWeight:600,padding:"6px 9px",cursor:"pointer"},children:O.label},O.value))}):null,se?n.jsx("div",{className:"admesh-compact-report-status",style:{marginLeft:P?0:Pe,fontSize:"11px",color:Ae},children:"Thanks for reporting this recommendation."}):null,Ee?n.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${Ne}`,borderRadius:"12px",background:Mt,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:De},children:"Confirm Agent Access"}),n.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:st,fontWeight:600},children:["Allow ",Y||"this brand"," to start a delegated session?"]}),n.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:bt},children:"The agent will only use the details you choose to share for this request."})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[n.jsx("button",{type:"button",disabled:le,onClick:O=>{O.preventDefault(),O.stopPropagation(),!le&&Q(!1)},style:{borderRadius:"10px",border:`1px solid ${Ne}`,background:Be,color:st,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:le?"not-allowed":"pointer",opacity:le?.65:1},children:"Not now"}),n.jsx("button",{type:"button",disabled:le,onClick:O=>{O.preventDefault(),O.stopPropagation(),!le&&Q(!0)},style:{borderRadius:"10px",border:"none",background:De,color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:le?"wait":"pointer",opacity:le?.86:1},children:le?"Connecting...":"Allow agent"})]})]}):null]})]})},Nr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})=>{const g=t.filter(c=>c&&typeof c=="object"&&typeof c.recommendation_id=="string"&&c.recommendation_id.length>0);if(!g||g.length===0)return l.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;l.log(`[AdMeshLayout] Rendering with ${g.length} valid recommendations`);const _=()=>{var c;if(g.length>0){const m=g[0],k=(c=m.recommendation)==null?void 0:c.format;l.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:k,recommendationKeys:Object.keys(m||{})}),(k==="product_card"||k==="weave"||k==="bridge")&&l.warn(`[AdMeshLayout] ${k} format requested, falling back to tail for canonical render payload`)}return n.jsx(qn,{recommendations:g,theme:e,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})};return n.jsx("div",{className:`admesh-layout ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:_()})};class $r{constructor(e){Ye(this,"firedExposures",new Set);Ye(this,"debug",!1);Ye(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,o,s){const i=`${s}_${o}`;if(this.firedExposures.has(i)){this.debug&&l.log("[Tracker] Exposure already fired");return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&l.warn("[Tracker] Failed to fire exposure")}),this.debug&&l.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&l.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,i){const d=`${s}_${o}`;if(this.firedExposures.has(d)){this.debug&&l.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let w=null,g=null;const _=new IntersectionObserver(k=>{k.forEach(j=>{j.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?w===null&&(w=Date.now(),this.debug&&l.log("[Tracker] Ad reached MRC visibility threshold"),g=setTimeout(()=>{this.fireExposure(e,o,s),_.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):w!==null&&(g&&(clearTimeout(g),g=null),w=null,this.debug&&l.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});_.observe(i);const m=setTimeout(()=>{_.disconnect(),g&&clearTimeout(g),u()},3e4);i.__admeshTrackerCleanup=()=>{_.disconnect(),g&&clearTimeout(g),clearTimeout(m)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,o,s){this.fireExposure(e,o,s)}fireFollowupEngagement(e,o,s){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s})}).catch(i=>{this.debug&&l.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const On=a.createContext(void 0);function Vn(){const t=a.useContext(On);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function es(t){const e=t.split("/").filter(Boolean),i=(e[e.length-1]||e[e.length-2]||"").replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i?i.replace(/\b\w/g,d=>d.toUpperCase()):"This page"}function Lr(){var t;try{console.log("[AdMesh] Starting direct headings extraction...");const e=_=>_.replace(/\s+/g," ").trim(),o=()=>{var f;const _=["article","main article","main",'[role="main"]',"[data-admesh-article]",".article-content",".post-content",".entry-content",".content"],c=["script","style","noscript","svg","canvas","iframe","nav","header","footer","aside",'[aria-hidden="true"]',"[data-admesh-ignore]",".admesh-publisher-assistant-root",".admesh-publisher-assistant-reactMount",".admesh-publisher-assistant-floating",".admesh-publisher-assistant-inline"].join(","),j=(((f=_.map(h=>document.querySelector(h)).filter(h=>!!h).map(h=>{const S=h.cloneNode(!0);S.querySelectorAll(c).forEach(G=>G.remove());const I=e(S.textContent||"");return{element:h,text:I}}).filter(h=>h.text.length>=200).sort((h,S)=>S.text.length-h.text.length)[0])==null?void 0:f.element)||document.body).cloneNode(!0);j.querySelectorAll(c).forEach(h=>h.remove());const p=Array.from(j.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(h=>e(h.textContent||"")).filter(h=>h.length>=24);return(p.length>0?p.join(`
|
|
150
|
+
`):e(j.textContent||"")).slice(0,6e3)},s=es(window.location.pathname||"/"),i=e(document.title||"")||s,u=(()=>{const _=[],c=document.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(c).forEach(m=>{const k=e(m.textContent||"");k.length>0&&_.push(k)}),_})(),w=u.length>0?u:[i||s],g={title:i,headings:w,article_text:o(),url:window.location.href,domain:window.location.hostname,extracted_at:new Date().toISOString()};return console.log("[AdMesh] Extracted headings:",{title:g.title,headingsCount:g.headings.length,articleTextLength:((t=g.article_text)==null?void 0:t.length)||0,domain:g.domain}),g}catch(e){return console.error("[AdMesh] Error in direct headings extraction:",e),null}}function ts(t){return!!(t&&typeof t=="object"&&"recommendation_id"in t&&"status"in t)}function ns(t){var s,i,d,u,w,g,_,c,m,k,j;if(!t||typeof t!="object")return;if(ts(t))return t;const e=t;if(!e.recommendation_id)return;const o=(e.products||[]).map(p=>{var x,f;return{product_id:p.product_id||"",product_link:p.product_link||p.product_click_url||e.click_url||e.url||"",product_name:p.product_name||e.title||((x=e.creative_input)==null?void 0:x.product_name)||"",product_description:p.product_description||"",product_price:p.product_price??void 0,product_discount:p.product_discount??void 0,product_currency:p.product_currency,product_discount_type:p.product_discount_type,product_cta_label:p.product_cta_label||((f=e.creative_input)==null?void 0:f.cta_label),product_image_url:p.product_image_url,product_features:p.product_features}});return{spec_version:"1.0",recommendation_id:e.recommendation_id,timestamp:new Date().toISOString(),status:"generated",ttl_ms:3e5,recommendation:{format:e.preferred_format||"tail",disclosure:"Sponsored",creative:{brand_name:((s=e.creative_input)==null?void 0:s.brand_name)||"",headline:e.title||((i=e.creative_input)==null?void 0:i.product_name)||"",description:((d=e.creative_input)==null?void 0:d.short_description)||((u=e.creative_input)==null?void 0:u.long_description)||"",cta_text:((w=e.creative_input)==null?void 0:w.cta_label)||((g=o[0])==null?void 0:g.product_cta_label)||"Learn more",follow_up_suggestion:e.follow_up_suggestion,logo_url:(c=(_=e.creative_input)==null?void 0:_.assets)==null?void 0:c.logo_url,image_urls:((k=(m=e.creative_input)==null?void 0:m.assets)==null?void 0:k.image_urls)||[],landing_page_url:e.url||e.click_url||((j=e.creative_input)==null?void 0:j.cta_url)||"",products:o}},tracking:{exposure_url:e.exposure_url,click_url:e.click_url,followup_exposure_url:e.followup_exposure_url,followup_engagement_url:e.followup_engagement_url}}}function rs(t){return{...t,suggestions:(t.suggestions||[]).map(e=>({...e,recommendation:ns(e.recommendation)}))}}function kr(t){try{const o=new URL(t).pathname.split("/").filter(i=>i.length>0);return o[o.length-1]||void 0}catch{return}}async function Fr(t,e){var o,s,i,d,u;try{console.log("[AdMesh SDK] Starting ACIE analyze-intent call...",{url:t.url});const w=Array.isArray(t.headings)?t.headings:[],g=(o=kr(t.url))==null?void 0:o.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),_=g?g.replace(/\b\w/g,S=>S.toUpperCase()):void 0,c=e.apiKey.toLowerCase().startsWith("pub_")?kr(t.url):void 0,m=e.extension?"extension":"admesh_ui_sdk",k=(t.domain||(typeof window<"u"?window.location.hostname:"")).trim().toLowerCase(),j={url:t.url,title:t.title||void 0,headings:w.length>0?w:_?[_]:void 0,article_text:((s=t.article_text)==null?void 0:s.trim())||void 0,domain:k,article_slug:c,agent_id:void 0,cpx_floor:void 0,source:m,api_key:e.apiKey,user_id:e.userId||void 0};console.log("[AdMesh SDK] Payload prepared:",{url:j.url,titleLength:((i=j.title)==null?void 0:i.length)||0,headingsCount:((d=j.headings)==null?void 0:d.length)||0,articleTextLength:((u=j.article_text)==null?void 0:u.length)||0,domain:j.domain,article_slug:j.article_slug,source:j.source,has_user_id:!!j.user_id});const p=`${e.apiBaseUrl}/acie/analyze-intent`;console.log("[AdMesh SDK] Calling ACIE API:",p);const x=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(j)});if(console.log("[AdMesh SDK] ACIE API response received:",{status:x.status,statusText:x.statusText,ok:x.ok}),!x.ok){const S=await x.text();throw console.error("[AdMesh SDK] ACIE API error:",{status:x.status,statusText:x.statusText,errorText:S}),new Error(`ACIE API error: ${x.status} - ${S}`)}const f=await x.json(),h=rs(f);return console.log("[AdMesh SDK] ACIE analysis completed:",{url:t.url,suggestionsCount:h.suggestions.length}),h}catch(w){return console.error("[AdMesh SDK] Error calling ACIE analyze-intent endpoint:",w),null}}async function os(t,e){var d,u;const o=(e.apiBaseUrl||"https://api.useadmesh.com").replace(/\/$/,""),s=new URLSearchParams({url:t.trim()});(d=e.agentDisplayId)!=null&&d.trim()&&s.set("agent_display_id",e.agentDisplayId.trim()),(u=e.publisherId)!=null&&u.trim()&&s.set("publisher_id",e.publisherId.trim());const i=await fetch(`${o}/publisher-assistant/page-context?${s.toString()}`,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e.apiKey}`}});if(!i.ok){const w=await i.text().catch(()=>"");throw new Error(`Page context request failed (${i.status}): ${w||i.statusText}`)}return await i.json()}function ss(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function is(){var t;if(typeof window>"u")return null;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Wr(e))return e}catch{return null}return null}function Wr(t){const e=t==null?void 0:t.trim();if(!e||/%%[^%]+%%/.test(e))return!1;try{const o=new URL(e);return o.protocol==="http:"||o.protocol==="https:"}catch{return!1}}function as(t){try{const e=new URL(t),o=e.pathname.split("/").filter(Boolean),i=(o[o.length-1]||o[o.length-2]||e.hostname).replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i?i.replace(/\b\w/g,d=>d.toUpperCase()):e.hostname}catch{return"This page"}}function Sr(t){const e=new URL(t),o=as(t);return{title:o,headings:[o],article_text:`Article URL: ${t}
|
|
151
|
+
Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const ls=6e4,Ar=3;function ds(t){const e=is();if(e)return e;const o=t==null?void 0:t.trim();return Wr(o)?o:null}const Br=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:d,location:u,userId:w,model:g,messages:_,pageContext:c,articleUrl:m,contextMode:k="auto",agentDisplayId:j,children:p})=>{const[x,f]=a.useState(null),[h,S]=a.useState(new Set),[I,G]=a.useState(new Map),[A,C]=a.useState(null),[L,$]=a.useState([]),[F,P]=a.useState(!1),[z,M]=a.useState(null),[W,V]=a.useState(!1),Y=a.useRef(!1),U=a.useRef(0),H=a.useRef(null),te=a.useRef(null);te.current=A;const ge=!!c||k==="ad-slot"||k==="auto"&&(!!(m!=null&&m.trim())||ss()),Z=a.useCallback(async()=>{if(c)return c;if(!ge)return Lr();const N=ds(m);if(!N)return l.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),M("Article URL is required for ad-slot context"),null;if(!t||!i)return l.warn("[AdMeshProvider] Cannot fetch page context: missing API key or base URL"),Sr(N);try{V(!0);const Q=await os(N,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:j});return l.log("[AdMeshProvider] Page context resolved",{source:Q.source,cache_hit:Q.cache_hit,domain:Q.context.domain}),Q.context}catch(Q){return l.error("[AdMeshProvider] Failed to fetch page context:",Q),l.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),Sr(N)}finally{V(!1)}},[j,i,t,m,c,ge]),ne=a.useCallback((N,Q)=>{const X=N.filter(ee=>!ee.is_sponsored).slice(0,3);return[Q,...X]},[]),_e=a.useCallback((N,Q)=>{const X=N.find(re=>re.is_sponsored),ee=Q.filter(re=>!re.is_sponsored).slice(0,3);return X?[X,...ee]:ee},[]);a.useEffect(()=>{if(!e||e.trim()===""){l.error("[AdMeshProvider] โ sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}l.log("[AdMeshProvider] โ
Session ID available:",e)},[e]),a.useEffect(()=>{if(!t){l.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){l.error("[AdMeshProvider] โ Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const N=new pn({apiKey:t,theme:s,apiBaseUrl:i,extension:o});f(N),l.log("[AdMeshProvider] โ
AdMesh SDK initialized with session:",e),i&&l.log("[AdMeshProvider] ๐ Using custom API base URL")}catch(N){l.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK:",N)}return()=>{l.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,s,i,e,o]);const Ge=a.useCallback(async N=>{var Q;if(!t||!i){l.warn("[AdMeshProvider] โ ๏ธ Cannot perform intent analysis: missing API key or base URL");return}if(o)l.log("[AdMeshProvider] โน๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){l.log('[AdMeshProvider] โน๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{P(!0),M(null),l.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const X=N??await Z();if(!X){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),M("Failed to extract page content");return}l.log("[AdMeshProvider] ๐ Extracted headings:",{title:X.title,headingsCount:X.headings.length,articleTextLength:((Q=X.article_text)==null?void 0:Q.length)||0,domain:X.domain});const re=await Fr(X,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:w});re?(l.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:re.suggestions.length,suggestions:(re.suggestions||[]).map(Ie=>{var T;return{id:Ie.id,text:Ie.text,is_sponsored:Ie.is_sponsored,recommendationId:((T=Ie.recommendation)==null?void 0:T.recommendation_id)||null}})}),$(Ie=>_e(Ie,re.suggestions||[]))):(l.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),M("Intent analysis failed"),$(Ie=>Ie.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),Ie):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(X){l.error("[AdMeshProvider] โ Error in intent analysis:",X),M("Intent analysis error"),$(ee=>ee.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),ee):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{P(!1)}},[t,i,o,w,_e,Z]),Ee=a.useCallback(async N=>{var ee,re,Ie,T,ie,D;if(!x||!t||!t.toLowerCase().startsWith("pub_"))return;const Q=N??await Z();if(!Q){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const X=((re=(ee=Q.headings)==null?void 0:ee[0])==null?void 0:re.trim())||((Ie=Q.title)==null?void 0:Ie.trim());if(!X){l.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{l.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const fe=await x.fetchPlatformResponse({query:X,sessionId:e,messageId:pn.createMessageId(e),platformSurface:"embedded_assistant",model:g,messages:[],language:d,location:u,userId:w}),E=(D=(ie=(T=fe.recommendation)==null?void 0:T.creative)==null?void 0:ie.follow_up_suggestion)==null?void 0:D.trim(),de=fe.recommendation_id;if(!E||!de){l.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const ke={id:de,text:E,type:"action",is_sponsored:!0,recommendation:fe,metadata:{source:"aip_context_prefetch",recommendation_id:de}};$(me=>ne(me,ke)),l.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:de,suggestionText:E})}catch(fe){l.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",fe)}},[t,d,u,g,x,e,w,ne,Z]),ve=a.useCallback(async()=>{l.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await Ge()},[Ge]);a.useEffect(()=>{!x||Y.current||(Y.current=!0,(async()=>{const N=await Z();await Promise.allSettled([Ee(N),Ge(N)])})())},[x,Ge,Ee,Z]);const le=a.useCallback(N=>{if(!N||N.status!=="active")return!1;const Q=Date.parse(N.expires_at);return Number.isNaN(Q)?!1:Q>Date.now()},[]),ue=a.useCallback(async(N,Q,X,ee)=>{const re=ee??A;if(!re||!x){l.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:N,eventType:Q,hasSession:!!re,hasSdk:!!x});return}const Ie=new Date().toISOString();l.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:N,eventType:Q,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id,sessionId:re.session_id});const T=await fetch(`${x.getApiBaseUrl()}${N}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:re.delegation_session_id,recommendation_id:re.recommendation_id,session_id:re.session_id,event_type:Q,timestamp:Ie,metadata:X||{}})});if(!T.ok){const fe=await T.text();throw l.error("[AdMeshProvider] โ Delegation event failed",{endpoint:N,eventType:Q,status:T.status,errorBody:fe,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id}),new Error(`Delegation event failed (${T.status}): ${fe}`)}const ie=await T.json(),D=ie==null?void 0:ie.session;l.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:N,eventType:Q,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id,returnedStatus:(D==null?void 0:D.status)||(ie==null?void 0:ie.status)}),D&&C(D)},[A,t,x]),Re=a.useCallback(()=>{U.current=0},[]),be=a.useCallback(async(N="user_stopped",Q)=>{const X=A;if(!X){l.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}l.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:N,recommendationId:X.recommendation_id,delegationSessionId:X.delegation_session_id}),await ue("/aip/delegation/stop","session_stopped",{reason:N,...Q||{}},X),await(x==null?void 0:x.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:X.session_id,recommendation_id:X.recommendation_id,delegation_session_id:X.delegation_session_id,brand_name:X.brand_name,status:"stopped",metadata:{reason:N,...Q||{}}}).catch(ee=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",ee)})),U.current=0,H.current=null,C(null),l.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},[A,ue,x]),se=a.useCallback(async(N="turn_completed",Q)=>{N==="turn_started"&&Re(),await ue("/aip/delegation/activity",N,Q)},[ue,Re]);a.useEffect(()=>{const N=(A==null?void 0:A.delegation_session_id)??null;N!==H.current&&(H.current=N,U.current=0)},[A==null?void 0:A.delegation_session_id]),a.useEffect(()=>{if(!((A==null?void 0:A.delegation_session_id)??null)||!x)return;const Q=te.current;if(!Q||!le(Q)){C(ee=>ee?{...ee,status:"expired"}:null);return}const X=window.setInterval(()=>{const ee=te.current;if(!(!ee||!le(ee))){if(U.current+=1,U.current>=Ar){l.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:ee.delegation_session_id,heartbeatsSinceLastUserTurn:U.current,idleHeartbeatLimit:Ar}),be("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:U.current}).catch(re=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to stop idle delegation session:",re)});return}ue("/aip/delegation/heartbeat","heartbeat").catch(re=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",re)})}},ls);return()=>{window.clearInterval(X)}},[A==null?void 0:A.delegation_session_id,le,ue,x,be]);const xt={sdk:x,apiKey:t,sessionId:e,theme:s,language:d,location:u,userId:w,model:g,messages:_,processedMessageIds:h,recommendationResults:I,activeDelegationSession:A,suggestions:L,isAnalyzingIntent:F||W,intentError:z,markMessageAsProcessed:N=>{S(Q=>{const X=new Set(Q);return X.add(N),X})},isMessageProcessed:N=>h.has(N),setRecommendationResult:(N,Q)=>{G(X=>{const ee=new Map(X);return ee.set(N,Q),ee}),S(X=>{const ee=new Set(X);return ee.add(N),ee})},getRecommendationResult:N=>I.get(N),hasRecommendationResult:N=>I.has(N),setActiveDelegationSession:N=>{C(N)},getActiveDelegationSession:()=>le(A)?A:null,hasActiveDelegationSession:()=>le(A),refreshDelegationActivity:se,stopDelegationSession:be,retryIntentAnalysis:ve};return n.jsx(On.Provider,{value:xt,children:p})};class Ur{constructor(){Ye(this,"roots",new Map)}async render(e){try{l.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){l.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw l.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);l.log("[AdMeshRenderer] โ
Container ready");const i=this.roots.get(e.containerId);i&&(l.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const d=yo.createRoot(s);l.log("[AdMeshRenderer] ๐ Rendering recommendations"),d.render(n.jsx(Br,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:n.jsx(Nr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",l.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,d)}catch(o){throw l.error("[AdMeshRenderer] โ Error rendering recommendations"),o}}unmount(e){const o=this.roots.get(e);if(o){o.unmount(),this.roots.delete(e);const s=document.getElementById(e);s&&(s.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}const cs=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},Ct=class Ct{constructor(e){Ye(this,"config");Ye(this,"apiBaseUrl");Ye(this,"renderer",null);Ye(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl,extension:e.extension,extensionSourceDomain:e.extensionSourceDomain,userId:e.userId},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static buildPlatformResponseCacheKey(e,o){return`${e}::${o}`}getExtensionSourceDomain(){var o,s;const e=(o=this.config.extensionSourceDomain)==null?void 0:o.trim();if(e)return e.toLowerCase();if(typeof window<"u"&&((s=window.location)!=null&&s.hostname))return window.location.hostname.trim().toLowerCase()||void 0}static createSession(){const e=Date.now(),o=Math.random().toString(36).substring(2,15);return`session_${e}_${o}`}static generateSessionIdFromUrl(e){const o=e||(typeof window<"u"?window.location.href:"");if(!o)return Ct.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),d=i[i.length-1];return d?`session_${Date.now()}_${d}`:Ct.createSession()}catch{return Ct.createSession()}}static createMessageId(e){const o=Date.now(),s=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${o}_${s}`:`msg_${o}_${s}`}getRenderer(){return this.renderer||(this.renderer=new Ur),this.renderer}getTracker(){return this.tracker||(this.tracker=new $r({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const d=await fetch(`${this.apiBaseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({delegation_session_id:o.delegation_session_id,recommendation_id:o.recommendation_id,session_id:o.session_id,event_type:s,timestamp:new Date().toISOString(),metadata:i||{}})});if(!d.ok){const w=await d.text();throw new Error(`Delegation event failed (${d.status}): ${w}`)}const u=await d.json();return(u==null?void 0:u.session)||null}async reportDelegationTurnStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_started",o)}async reportDelegationSessionStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"session_started",o)}async reportDelegationTurnCompleted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_completed",o)}async reportDelegationToolInvocation(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"tool_invoked",o)}async reportDelegationOutcome(e,o,s){return this.postDelegationEvent("/aip/delegation/complete",e,o,s)}async stopDelegationSession(e,o="user_stopped",s){return this.postDelegationEvent("/aip/delegation/stop",e,"session_stopped",{reason:o,...s||{}})}getActiveDelegationSession(e){if(!e||e.status!=="active")return null;const o=Date.parse(e.expires_at);return Number.isNaN(o)||o<=Date.now()?null:e}hasActiveDelegationSession(e){return!!this.getActiveDelegationSession(e)}async showRecommendations(e){try{if(!e.sessionId||e.sessionId.trim()==="")throw new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");if(!e.messageId||e.messageId.trim()==="")throw new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");const o=await this.fetchPlatformResponse({query:e.query,sessionId:e.sessionId,messageId:e.messageId,platformSurface:e.platformSurface,model:e.model,messages:e.messages,language:e.locale,location:e.location,userId:e.userId??this.config.userId}),s={sessionId:e.sessionId,messageId:e.messageId,recommendations:[o]},i=this.getRenderer(),d=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:d,sessionId:e.sessionId,apiKey:this.config.apiKey,apiBaseUrl:this.apiBaseUrl,language:e.locale,location:e.location,userId:e.userId,model:e.model,messages:e.messages,onPasteToInput:e.onPasteToInput,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation,onExecuteQuery:e.onExecuteQuery})}catch(o){throw l.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var f,h,S,I,G,A,C,L,$,F,P,z,M;const o=`${this.apiBaseUrl}/aip/context`;if(l.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const W=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw l.error("[AdMeshSDK] โ sessionId not provided by platform - cannot process request"),W}const s=e.messageId;if(!s||s.trim()===""){const W=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw l.error("[AdMeshSDK] โ messageId not provided by platform - cannot process request"),W}const i=Ct.buildPlatformResponseCacheKey(e.sessionId,s),d=Ct.inFlightPlatformResponses.get(i);if(d)return l.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),d;const u=e.messages?e.messages.length:0,w=(typeof window<"u"&&window.navigator,"web"),g=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",_=cs((f=e.location)==null?void 0:f.countryCode)||"US",c=typeof window<"u"&&window.location?{url:window.location.href,origin:window.location.origin,referrer:document.referrer||void 0,host:window.location.hostname}:void 0,m=e.userId??this.config.userId,k={spec_version:"1.0",message_id:s,timestamp:new Date().toISOString(),platform:{platform_id:"placeholder",role:"platform",software:{name:"admesh_ui_sdk",version:e.model||"1.0.0"}},identity:{namespace:"platform_user",value_hash:m||"",confidence:m?1:0},consent:{status:"granted",source:"admesh_ui_sdk",scope:{intent_based_monetization:!0,agent_participation:!0,measurement:!0},constraints:{allow_identity_downstream:!1}},classification_input:{type:"interaction",interaction:{session:{id:e.sessionId,turn_index:u},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:w,form_factor:g,locale:e.language||"en-US",country:_,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((h=e.location)==null?void 0:h.city)||void 0,state:((S=e.location)==null?void 0:S.state)||void 0,state_code:((I=e.location)==null?void 0:I.stateCode)||void 0,country:((G=e.location)==null?void 0:G.country)||void 0,country_code:_,zipcode:((A=e.location)==null?void 0:A.zipcode)||void 0,latitude:(C=e.location)==null?void 0:C.latitude,longitude:(L=e.location)==null?void 0:L.longitude},page:c}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(F=($=k.classification_input.interaction)==null?void 0:$.input.query_text)!=null&&F.trim()||l.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const j=JSON.stringify(k);l.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:k.message_id,specVersion:k.spec_version,classificationType:k.classification_input.type,platformId:k.platform.platform_id,surfaceChannel:(P=k.classification_input.interaction)==null?void 0:P.surface.channel,sessionId:(M=(z=k.classification_input.interaction)==null?void 0:z.session)==null?void 0:M.id});const p={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){p["X-AdMesh-Source"]="extension";const W=this.getExtensionSourceDomain();W&&(p["X-AdMesh-Source-Domain"]=W)}const x=(async()=>{const W=await fetch(o,{method:"POST",headers:p,body:j});if(!W.ok){const U=(await W.json().catch(()=>({}))).detail||`HTTP ${W.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${U}`)}const V=await W.json();return l.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{status:V.status,recommendationId:V.recommendation_id,hasRecommendation:!!V.recommendation,hasTracking:!!V.tracking,hasDelegation:!!V.delegation,topLevelKeys:Object.keys(V)}),l.log("[AdMeshSDK] ๐ฆ Full PlatformResponse received from /aip/context",V),V})();Ct.inFlightPlatformResponses.set(i,x);try{return await x}finally{Ct.inFlightPlatformResponses.delete(i)}}async trackPublisherAssistantEvent(e){const o=Array.isArray(e)?{events:e}:e,s=await fetch(`${this.apiBaseUrl}/analytics/publisher-assistant/events`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),keepalive:!0});if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Failed to track publisher assistant analytics (${s.status}): ${i}`)}}async reportSponsoredRecommendation(e){const o=await fetch(`${this.apiBaseUrl}/analytics/recommendation-reports`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(e),keepalive:!0});if(!o.ok){const s=await o.text().catch(()=>"");throw new Error(`Failed to report sponsored recommendation (${o.status}): ${s}`)}}fireFollowupExposure(e,o,s){this.getTracker().fireFollowupExposure(e,o,s)}async fireFollowupEngagement(e,o,s){return this.getTracker().fireFollowupEngagement(e,o,s)}};Ye(Ct,"inFlightPlatformResponses",new Map);let pn=Ct;class Kn{constructor(e={}){Ye(this,"autoAddLabels");Ye(this,"fireExposurePixels");Ye(this,"labelStyle");Ye(this,"processedLinks",new Set);Ye(this,"mutationObserver",null);var o,s,i,d;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((o=e.labelStyle)==null?void 0:o.fontSize)||"0.75em",fontWeight:((s=e.labelStyle)==null?void 0:s.fontWeight)||"bold",color:((i=e.labelStyle)==null?void 0:i.color)||"#666",marginLeft:((d=e.labelStyle)==null?void 0:d.marginLeft)||"2px"}}getLinksToProcess(e){const s=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return s.length>0?Array.from(s):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,o,s){if(!e)return[];const i=[];if(o.length>0){const d=this.getLinksToProcess(e),u=new Map(o.map(g=>{var _,c,m;return[((_=g==null?void 0:g.tracking)==null?void 0:_.click_url)||((m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url)||"",g]}).filter(([g])=>!!g)),w=new Map;o.forEach(g=>{var c,m;const _=(m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url;if(_&&typeof _=="string"){const k=_.trim().replace(/\/$/,"");w.set(k,g),w.set(`${k}/`,g)}}),d.forEach(g=>{var j,p,x,f,h,S,I,G;const _=g.getAttribute("href")||"",c=`${_}`;if(this.processedLinks.has(c))return;let m=u.get(_),k=_;if(!m){const A=_.trim().replace(/\/$/,"");m=w.get(A)||w.get(`${A}/`);const C=((j=m==null?void 0:m.tracking)==null?void 0:j.click_url)||((x=(p=m==null?void 0:m.recommendation)==null?void 0:p.creative)==null?void 0:x.landing_page_url);m&&C&&(l.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",_),g.setAttribute("href",C),k=C)}if(m){this.processedLinks.add(c),g.setAttribute("target","_blank"),g.setAttribute("rel","noopener noreferrer");const A={element:g,href:k,text:g.textContent||"",hasAdLabel:this.hasAdLabel(g),matchedRecommendation:{recommendation_id:(m==null?void 0:m.recommendation_id)||"",click_url:((f=m==null?void 0:m.tracking)==null?void 0:f.click_url)||((S=(h=m==null?void 0:m.recommendation)==null?void 0:h.creative)==null?void 0:S.landing_page_url)||"",exposure_url:(I=m==null?void 0:m.tracking)==null?void 0:I.exposure_url}};this.autoAddLabels&&!A.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",k),this.addAdLabel(g),A.hasAdLabel=!0):this.autoAddLabels?A.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const C=(G=m==null?void 0:m.tracking)==null?void 0:G.exposure_url;this.fireExposurePixels&&C&&s&&A.matchedRecommendation&&s({exposureUrl:C,recommendationId:A.matchedRecommendation.recommendation_id,linkElement:g}),i.push(A)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const w=u.getAttribute("href")||"",g=`${w}`;if(this.processedLinks.has(g))return;if(this.isAdMeshLink(w)){this.processedLinks.add(g);const c={element:u,href:w,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:void 0};if(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to pattern-matched AdMesh link:",w),this.addAdLabel(u),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const m=this.convertClickUrlToExposureUrl(w);s({exposureUrl:m,recommendationId:this.extractRecommendationIdFromUrl(w),linkElement:u})}i.push(c)}});return i}hasAdLabel(e){var u,w,g;if((e.textContent||"").includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Link text contains Ad label"),!0;const s=e.querySelectorAll("sub, span");for(const _ of Array.from(s))if((u=_.textContent)!=null&&u.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Link has Ad label as child element"),!0;let i=e.previousSibling;for(;i&&i.nodeType===Node.TEXT_NODE;){const _=i.textContent||"";if(_.trim()===""){i=i.previousSibling;continue}if(_.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const _=i,c=_.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((w=_.textContent)!=null&&w.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",c),!0}let d=e.nextSibling;for(;d&&d.nodeType===Node.TEXT_NODE;){const _=d.textContent||"";if(_.trim()===""){d=d.nextSibling;continue}if(_.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(d&&d.nodeType===Node.ELEMENT_NODE){const _=d,c=_.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((g=_.textContent)!=null&&g.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next element sibling:",c),!0}return l.log("[WeaveResponseProcessor] โน๏ธ No existing Ad label found"),!1}addAdLabel(e){if(l.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){l.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){l.log("[WeaveResponseProcessor] โน๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){l.error("[WeaveResponseProcessor] โ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const s=document.createElement("sub");s.textContent="Ad",s.style.fontSize=this.labelStyle.fontSize,s.style.fontWeight=this.labelStyle.fontWeight,s.style.color=this.labelStyle.color,s.style.marginLeft=this.labelStyle.marginLeft,s.style.cursor="pointer",s.style.borderBottom=`1px dotted ${this.labelStyle.color}`,s.style.whiteSpace="nowrap",s.title="Why this ad? This is a sponsored recommendation based on your search query.";let i=!1;s.addEventListener("mouseenter",()=>{s.style.opacity="0.7"}),s.addEventListener("mouseleave",()=>{s.style.opacity="1",i&&(i=!1)}),s.addEventListener("click",u=>{u.stopPropagation(),i=!i,i?(s.style.textDecoration="underline",s.style.opacity="0.7"):(s.style.textDecoration="none",s.style.opacity="1")});const d=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",d);try{const u=e.nextSibling;u?(o.insertBefore(s,u),l.log("[WeaveResponseProcessor] โ
Ad label inserted before next sibling")):(o.appendChild(s),l.log("[WeaveResponseProcessor] โ
Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?l.log("[WeaveResponseProcessor] โ
Ad label successfully added to link:",e.href):l.error("[WeaveResponseProcessor] โ Ad label insertion failed - label not in DOM")}catch(u){l.error("[WeaveResponseProcessor] โ Error inserting Ad label:",u)}}removeLeftAdLabel(e){var s,i,d;let o=e.previousSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const u=o.textContent||"";if(u.trim()===""){o=o.previousSibling;continue}if(u.includes("Ad")){(s=o.parentNode)==null||s.removeChild(o);return}break}if(o&&o.nodeType===Node.ELEMENT_NODE){const u=o;(u.tagName==="SUB"||u.tagName==="SPAN")&&((i=u.textContent)!=null&&i.includes("Ad"))&&((d=u.parentNode)==null||d.removeChild(u))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(i=>e.includes(i)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractRecommendationIdFromUrl(e){try{const o=e.match(/\/click\/([^/?]+)/);return o&&o[1]?o[1]:""}catch{return e}}convertClickUrlToExposureUrl(e){try{const o=new URL(e),i=`${`${o.protocol}//${o.host}`}/exposure`,d=new URLSearchParams(o.search);return d.has("cpx")||d.set("cpx","0"),`${i}?${d.toString()}`}catch{return l.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,o,s){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,o,s)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}function on(){const t=Vn();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,language:t.language,location:t.location,userId:t.userId,model:t.model,messages:t.messages,processedMessageIds:t.processedMessageIds,recommendationResults:t.recommendationResults,activeDelegationSession:t.activeDelegationSession,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed,setRecommendationResult:t.setRecommendationResult,getRecommendationResult:t.getRecommendationResult,hasRecommendationResult:t.hasRecommendationResult,setActiveDelegationSession:t.setActiveDelegationSession,getActiveDelegationSession:t.getActiveDelegationSession,hasActiveDelegationSession:t.hasActiveDelegationSession,refreshDelegationActivity:t.refreshDelegationActivity,stopDelegationSession:t.stopDelegationSession}}const us=({className:t,size:e=20})=>n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M5 12h14"}),n.jsx("path",{d:"M12 5v14"})]}),Hr=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var k,j,p,x,f;const d=(j=(k=t.recommendation)==null?void 0:k.creative)!=null&&j.follow_up_suggestion&&((p=t.tracking)!=null&&p.followup_engagement_url)&&((x=t.tracking)!=null&&x.followup_exposure_url)?{query:t.recommendation.creative.follow_up_suggestion,engagement_url:t.tracking.followup_engagement_url,exposure_url:t.tracking.followup_exposure_url}:null,u=d==null?void 0:d.query,w=d==null?void 0:d.engagement_url,g=d==null?void 0:d.exposure_url,_=t.recommendation_id,c=((f=t.recommendation)==null?void 0:f.offerId)||_;if(!u||!w||!g)return l.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const m=async()=>{try{w&&_&&(l.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(w,_,s)),i&&u?(l.log(`[AdMeshFollowup] ๐ Executing query: ${u}`),await i(u)):l.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(h){l.error("[AdMeshFollowup] โ Error handling follow-up click:",h)}};return n.jsx(hn,{productId:c,recommendationId:_||"",exposureUrl:g,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:n.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[n.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),n.jsxs("div",{onClick:m,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&m()},"aria-label":`Sponsored follow-up: ${u}`,children:[n.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),n.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),n.jsx(us,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},nn=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:d,triggerExposureUrl:u=!0,followups_container_id:w,onPasteToInput:g,onDelegationConsent:_,onDelegationActivated:c,onStartDelegation:m,onRecommendationReport:k,onExecuteQuery:j,onFollowupDetected:p,isContainerReady:x})=>{var X,ee,re,Ie;const{sdk:f,sessionId:h,apiKey:S,language:I,location:G,userId:A,model:C,messages:L,theme:$,getRecommendationResult:F,hasRecommendationResult:P,setRecommendationResult:z,activeDelegationSession:M,setActiveDelegationSession:W,hasActiveDelegationSession:V}=on(),Y=T=>!!T&&T.status==="generated"&&!!T.recommendation,U=i||A,[H,te]=a.useState(null),[ge,Z]=a.useState(null),[ne,_e]=a.useState(!0),[Ge,Ee]=a.useState(null),ve=a.useRef(null),le=a.useRef(!1),ue=a.useRef(!1),Re=a.useRef(t),be=a.useRef(e);a.useEffect(()=>{Re.current=t,be.current=e},[t,e]),a.useEffect(()=>{ve.current!==o&&(ve.current=null,ue.current=!1,te(null),Z(null))},[o]);const se=V()&&(M==null?void 0:M.session_id)===h;a.useEffect(()=>{var D,fe,E;if(!o||!P(o)||se)return;const T=F(o);if(!T){l.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),te(null),Z(null),Ee(null),_e(!1),ve.current=o,le.current=!1,ue.current=!0;return}let ie=((D=T.recommendation)==null?void 0:D.format)||"tail";(ie==="weave"||ie==="product_card")&&(ie="tail"),l.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:T.recommendation_id,format:(fe=T.recommendation)==null?void 0:fe.format}),te(T),Z(ie),Ee(null),_e(!1),ve.current=o,le.current=!1,ue.current=!0,(E=Re.current)==null||E.call(Re,o,T)},[F,P,se,o]),a.useEffect(()=>{var T,ie,D,fe,E,de,ke;if(!(!d||!o)&&!se)try{const me=d,Be=d.status||"unknown";if(!Y(me)){if(Be==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),te(null),Z(null),Ee(null),_e(!1),ve.current=o,le.current=!1,ue.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${Be})`)}let Ne=((T=me.recommendation)==null?void 0:T.format)||"tail";(Ne==="weave"||Ne==="product_card")&&(Ne="tail"),te(me),Z(Ne),Ee(null),_e(!1),ve.current=o,le.current=!1,ue.current=!0,z(o,me),(ie=Re.current)==null||ie.call(Re,o,me),l.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),l.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:me.recommendation_id,format:(D=me.recommendation)==null?void 0:D.format,brandName:(E=(fe=me.recommendation)==null?void 0:fe.creative)==null?void 0:E.brand_name,headline:(ke=(de=me.recommendation)==null?void 0:de.creative)==null?void 0:ke.headline,hasTracking:!!me.tracking})}catch(me){const Be=me instanceof Error?me:new Error(String(me));ue.current=!1,l.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${Be.message}`)}},[se,d,o,z]),a.useEffect(()=>{if(!o||!s||s.trim()===""){l.log("[AdMeshRecommendations] โ Validation failed - missing required parameters"),_e(!1);return}if(se){l.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:h,delegationSessionId:M==null?void 0:M.delegation_session_id}),te(null),Z(null),Ee(null),_e(!1),le.current=!1;return}if(!(f!=null&&f.fetchPlatformResponse)){l.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),_e(!1);return}if(ue.current){l.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(ve.current===o){l.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(le.current){l.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}l.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var ie,D,fe,E,de,ke,me,Be,Ne;try{le.current=!0,_e(!0),Ee(null);const Se=await f.fetchPlatformResponse({query:s.trim(),sessionId:h,messageId:o,language:I,location:G,userId:U,model:C,...L&&L.length>0&&{messages:L}}),De=(Se==null?void 0:Se.status)||"unknown";if(!Y(Se)){if(De==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),te(null),Z(null),Ee(null),_e(!1),le.current=!1,ve.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${De})`)}te(Se),l.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:Se.recommendation_id,format:(ie=Se.recommendation)==null?void 0:ie.format,brandName:(fe=(D=Se.recommendation)==null?void 0:D.creative)==null?void 0:fe.brand_name,headline:(de=(E=Se.recommendation)==null?void 0:E.creative)==null?void 0:de.headline,hasTracking:!!Se.tracking});let Ae=((ke=Se.recommendation)==null?void 0:ke.format)||"tail";(Ae==="weave"||Ae==="product_card")&&(Ae="tail"),Z(Ae),ve.current=o,z(o,Se),l.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(me=Se.recommendation)==null?void 0:me.format,selected_format:Ae}),_e(!1),le.current=!1,(Be=Re.current)==null||Be.call(Re,o,Se)}catch(Se){const De=Se instanceof Error?Se:new Error(String(Se));De.message.includes("Failed to fetch")||De.message.includes("NetworkError")?l.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${De.message} `):l.error(`[AdMeshRecommendations] โ Error fetching recommendations: ${De.message} `),Ee(De),_e(!1),le.current=!1,(Ne=be.current)==null||Ne.call(be,De)}})()},[M==null?void 0:M.delegation_session_id,se,f,h,o,s,I,G,U,C,d,z]),a.useEffect(()=>{var ie,D,fe,E;if(!H||!p)return;const T=(D=(ie=H.recommendation)==null?void 0:ie.creative)!=null&&D.follow_up_suggestion&&((fe=H.tracking)!=null&&fe.followup_engagement_url)&&((E=H.tracking)!=null&&E.followup_exposure_url)?{label:H.recommendation.creative.follow_up_suggestion,query:H.recommendation.creative.follow_up_suggestion,engagement_url:H.tracking.followup_engagement_url,exposure_url:H.tracking.followup_exposure_url}:null;T&&p(T,H.recommendation_id)},[H,p]);const xt=a.useCallback(async T=>{if(!f||!h)throw new Error("AdMesh SDK activation requires an initialized session");const ie=await fetch(`${f.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({session_id:h,recommendation_id:T.recommendation_id,metadata:T.metadata})});if(!ie.ok){const de=await ie.text();throw new Error(`Failed to activate delegation session: ${ie.status} ${de}`)}const D=await ie.json(),fe={...T,delegation_session_id:D.delegation_session_id||T.delegation_session_id,session_id:D.session_id||h,brand_id:D.brand_id||T.brand_id,brand_name:D.brand_name||T.brand_name,mcp_endpoint:D.mcp_endpoint,eligibility_reason:D.eligibility_reason||T.eligibility_reason,delegate_reason:D.delegate_reason||T.delegate_reason,session_goal:D.session_goal||T.session_goal,desired_outcome_type:D.desired_outcome_type||T.desired_outcome_type,required_user_inputs:D.required_user_inputs||T.required_user_inputs||[],required_consent_types:D.required_consent_types||T.required_consent_types||[],success_outcome:D.success_outcome||T.success_outcome,fallback_message:D.fallback_message||T.fallback_message,session_mode:"inline",status:D.status||"active",capabilities:D.capabilities||T.capabilities||[],allowed_data_types:D.allowed_data_types||T.allowed_data_types||[],auth_model:D.auth_model||T.auth_model,handoff_protocol:D.handoff_protocol||T.handoff_protocol,supported_actions:D.supported_actions||T.supported_actions||[],metadata:D.metadata||T.metadata},E={delegation_session_id:D.delegation_session_id,recommendation_id:T.recommendation_id,session_id:D.session_id||h,brand_agent_id:D.brand_agent_id,brand_id:D.brand_id||T.brand_id,brand_name:D.brand_name||T.brand_name||"Brand",mcp_endpoint:D.mcp_endpoint,status:D.status||"active",activated_at:D.created_at,last_activity_at:D.updated_at,expires_at:D.expires_at||D.updated_at,eligibility_reason:D.eligibility_reason||T.eligibility_reason,delegate_reason:D.delegate_reason||T.delegate_reason,session_goal:D.session_goal||T.session_goal,desired_outcome_type:D.desired_outcome_type||T.desired_outcome_type,required_user_inputs:D.required_user_inputs||T.required_user_inputs||[],required_consent_types:D.required_consent_types||T.required_consent_types||[],success_outcome:D.success_outcome||T.success_outcome,fallback_message:D.fallback_message||T.fallback_message,capabilities:D.capabilities||T.capabilities||[],allowed_data_types:D.allowed_data_types||T.allowed_data_types||[],consent_requirements:D.consent_requirements||T.consent_requirements||[],auth_model:D.auth_model||T.auth_model,handoff_protocol:D.handoff_protocol||T.handoff_protocol,supported_actions:D.supported_actions||T.supported_actions||[],metadata:D.metadata||T.metadata};if(W(E),await f.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:h,recommendation_id:T.recommendation_id,delegation_session_id:D.delegation_session_id,brand_name:E.brand_name,status:D.status||"active",metadata:{brand_agent_id:D.brand_agent_id,source:"recommendation_card"}}).catch(de=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",de)}),await f.reportDelegationSessionStarted(E,{brand_agent_id:D.brand_agent_id,brand_name:E.brand_name}).then(de=>{de&&W(de)}).catch(de=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",de)}),c){try{await c(fe)}catch(de){l.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",de)}return}if(m)try{await m({...T.platform_response,delegation:{...T.platform_response.delegation,...fe,delegation_session_id:D.delegation_session_id,available:!0,status:D.status||"active"}})}catch(de){l.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",de)}},[S,c,m,f,h,W]),N=a.useCallback(async T=>{var ie,D;if(k){await k(T);return}!f||!h||await f.reportSponsoredRecommendation({session_id:h,message_id:o,recommendation_id:T.recommendation_id,reason:T.reason,brand_name:(D=(ie=T.recommendation.recommendation)==null?void 0:ie.creative)==null?void 0:D.brand_name,metadata:{reason:T.reason,source:"recommendation_card"}}).catch(fe=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report sponsored recommendation:",fe)})},[o,k,f,h]);if(!o||!s||s.trim()===""||ne||Ge)return null;if(!H||!ge)return l.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!H,detectedFormat:ge,isLoading:ne,hasError:!!Ge}),null;l.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:H.recommendation_id,detectedFormat:ge,brandName:(ee=(X=H.recommendation)==null?void 0:X.creative)==null?void 0:ee.brand_name,headline:(Ie=(re=H.recommendation)==null?void 0:re.creative)==null?void 0:Ie.headline});const Q=typeof document<"u"&&w&&(x??!0)?document.getElementById(w):null;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:n.jsx(qn,{recommendations:[H],theme:$,sessionId:h,triggerExposureUrl:u,onPasteToInput:g,onDelegationConsent:_,onDelegationActivated:xt,onStartDelegation:m,onRecommendationReport:N})}),Q&&f&&h?Hn.createPortal(n.jsx(Hr,{recommendation:H,theme:$,sdk:f,sessionId:h,onExecuteQuery:j}),Q):null]})},qr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:d})=>{const{sdk:u,sessionId:w,theme:g,apiKey:_,language:c,location:m,userId:k,model:j,messages:p}=on(),x=a.useRef(null),[f,h]=a.useState("");return a.useEffect(()=>{o&&h(`admesh-weave-fallback-${o}`)},[o]),l.log("[WeaveFallbackRecommendations] ๐จ Component render"),a.useEffect(()=>{if(l.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:i,hasPreviousRecommendations:d&&d.length>0,previousRecommendationsCount:(d==null?void 0:d.length)||0}),!i){l.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(l.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){l.log("[WeaveFallbackRecommendations] โ Validation failed - returning early");return}if(l.log("[WeaveFallbackRecommendations] โ
Validation passed"),!u||!f){l.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const S=d&&d.length>0;l.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:S,count:(d==null?void 0:d.length)||0,fallback:i,messageId:o}),S?(l.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${d.length} previous recommendation(s), skipping API call`),(async()=>{var G,A,C,L,$,F,P;try{const z=d[0];if(l.log("[WeaveFallbackRecommendations] ๐ฆ Processing AIP response:",{hasAipResponse:!!z,recommendationId:(z==null?void 0:z.recommendation_id)||"",format:((G=z==null?void 0:z.recommendation)==null?void 0:G.format)||"unknown"}),z&&process.env.NODE_ENV==="development"&&l.log("[WeaveFallbackRecommendations] ๐ Recommendation received (DEV):",{recommendation_id:z==null?void 0:z.recommendation_id,click_url:((A=z==null?void 0:z.tracking)==null?void 0:A.click_url)||((L=(C=z==null?void 0:z.recommendation)==null?void 0:C.creative)==null?void 0:L.landing_page_url),format:($=z==null?void 0:z.recommendation)==null?void 0:$.format,full_response:z}),!z){l.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o});return}const M=u,W=M.getRenderer,V=M.getTracker,Y=(F=M.config)==null?void 0:F.theme;if(W&&V){const U={sessionId:w,messageId:o,recommendations:[z]},H=W.call(u),te=V.call(u),ge=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await H.render({containerId:f,response:U,theme:g||Y,tracker:te,sessionId:w,apiKey:_||((P=u==null?void 0:u.config)==null?void 0:P.apiKey),apiBaseUrl:ge,language:c,location:m,userId:k,model:j,messages:p}),l.log("[WeaveFallbackRecommendations] โ
Recommendations rendered from previous response (no API call)")}else l.warn("[WeaveFallbackRecommendations] โ ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch(z){const M=z instanceof Error?z:new Error(String(z));l.error(`[WeaveFallbackRecommendations] โ Error rendering previous recommendations: ${M.message}`);try{await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch{e==null||e(M)}}})()):(l.log("[WeaveFallbackRecommendations] ๐ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){l.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o}),l.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(G){const A=G instanceof Error?G:new Error(String(G));l.log(`[WeaveFallbackRecommendations] โ Error: ${A.message}`),e==null||e(A)}})())},[u,w,f,t,o,s,i,e,d,g]),!i||!o||!s||s.trim()===""?null:n.jsx("div",{ref:x,id:f,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Or=a.createContext(void 0),ms=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>n.jsx(Or.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),ps=()=>a.useContext(Or),Nn=t=>{try{return new URL(t),!0}catch{return!1}},Cr=t=>t&&t.trim()?t.trim():"",Bt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",ft=t=>Bt(t)||void 0,hs=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},fs=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return Bt(t)},gs=(t,e,o)=>{if(t==null||t==="")return"";const s=(e||"percentage").trim().toLowerCase();if(typeof t=="number"){if(s==="amount"||s==="fixed"||s==="fixed_amount")try{return`${new Intl.NumberFormat("en-US",{style:"currency",currency:o||"USD",maximumFractionDigits:2}).format(t)} off`}catch{return`${t} off`}return`${t}% off`}const i=Bt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},xe={surface:"#ffffff",surfaceMuted:"#f9fafb",surfaceSubtle:"#f8fafc",border:"rgba(17, 24, 39, 0.10)",text:"#111827",textSecondary:"#4b5563",textMuted:"#6b7280",link:"#2563eb",logoFallbackBg:"#f3f4f6",logoFallbackText:"#4b5563",productImageFallbackBg:"#e5e7eb",successText:"#065f46",successBg:"#d1fae5"},xs=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:g,onPasteToInput:_})=>{var E,de,ke,me,Be,Ne,Se,De,Ae,bt,st,Mt,Pe,Oe,pe,it,jt,Et,q,at,yt,Lt,Ut,O,Ce,Qe,ut,Rt,It,Ht,Tt,wt,Xe;if(!t||t.length===0)return l.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],m=((E=c==null?void 0:c.recommendation)==null?void 0:E.offerId)||"",k=((de=c==null?void 0:c.tracking)==null?void 0:de.exposure_url)||"",j=(c==null?void 0:c.recommendation_id)||"",p=((me=(ke=c==null?void 0:c.recommendation)==null?void 0:ke.creative)==null?void 0:me.description)||"",x=((Be=c==null?void 0:c.recommendation)==null?void 0:Be.disclosure)||"Sponsored",f=((Se=(Ne=c==null?void 0:c.recommendation)==null?void 0:Ne.creative)==null?void 0:Se.brand_name)||"",h=((Ae=(De=c==null?void 0:c.recommendation)==null?void 0:De.creative)==null?void 0:Ae.headline)||((st=(bt=c==null?void 0:c.recommendation)==null?void 0:bt.creative)==null?void 0:st.brand_name)||"",S=((Pe=(Mt=c==null?void 0:c.recommendation)==null?void 0:Mt.creative)==null?void 0:Pe.logo_url)||"",I=((Oe=c==null?void 0:c.tracking)==null?void 0:Oe.click_url)||((it=(pe=c==null?void 0:c.recommendation)==null?void 0:pe.creative)==null?void 0:it.landing_page_url)||"",G=Cr((Et=(jt=c==null?void 0:c.recommendation)==null?void 0:jt.creative)==null?void 0:Et.cta_text),A=((at=(q=c==null?void 0:c.recommendation)==null?void 0:q.creative)==null?void 0:at.products)||[],C=A.length>1,L=C?A.slice(0,4):[],$=((yt=c==null?void 0:c.recommendation)==null?void 0:yt.format)||"tail",F=$==="bridge",P=((Lt=c==null?void 0:c.delegation)==null?void 0:Lt.brand_name)||f,z=((Ut=c==null?void 0:c.delegation)==null?void 0:Ut.available)===!0,M=F&&z,W="Talk to Agent",V=!C&&!!G&&!!I;if(!f&&!h&&!p)return l.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:f,hasFirstRecommendation:!!c,recommendationId:j,recommendationKeys:c?Object.keys(c):[]}),null;let Y=f,U="";h&&h!==f&&(U=h),U&&(Y=`${f} โ ${U}`),l.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:j,productId:m,exposureUrl:k?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:I||"MISSING",clickUrlSource:(O=c==null?void 0:c.tracking)!=null&&O.click_url?"tracking.click_url":(Qe=(Ce=c==null?void 0:c.recommendation)==null?void 0:Ce.creative)!=null&&Qe.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:p?"present":"MISSING",brandName:f,productName:h,headlineText:Y,triggerExposureUrl:d}),l.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:j,brandName:f,productName:h,hasDescription:!!p,hasClickUrl:!!I,hasLogoUrl:!!S,recommendationFormat:$});const H=(K,$e)=>{$e&&$e.stopPropagation(),l.log(`AdMesh tail ad ${K} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:j,productId:m,clickUrl:I,source:K}).catch(()=>{l.error(`[AdMesh] Failed to track ${K} click`)})},te=K=>{K.stopPropagation(),H("tail_ad_brand_name")},ge=K=>{K.stopPropagation(),H("tail_ad_cta")},Z=K=>{K.stopPropagation(),H("tail_ad_logo")},ne=()=>{C||!I||(H("tail_ad_card"),typeof window<"u"&&window.open(I,"_blank","noopener,noreferrer"))},_e=K=>{C||!I||(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),ne())},[Ge,Ee]=a.useState(!1),[ve,le]=a.useState(!1),ue=a.useRef(null);a.useEffect(()=>()=>{ue.current&&(ue.current(!1),ue.current=null)},[]);const Re=K=>{var $e;K&&le(!0),($e=ue.current)==null||$e.call(ue,K),ue.current=null,K||(le(!1),Ee(!1))},be=async()=>u?await u(c):await new Promise(K=>{ue.current=K,Ee(!0)}),se=async()=>{if(j&&i)try{const K=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",$e=await fetch(`${K}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:j,session_id:i,is_test:!1})});$e.ok||l.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",$e.statusText)}catch(K){l.error("[AdMesh Tail Ad] Error tracking delegation engagement:",K)}},xt=async K=>{var vt,Dt,qt,kt;if(K.preventDefault(),K.stopPropagation(),!c||!M)return;if(H("tail_ad_delegation_cta"),!await be()){l.log("[AdMesh Tail Ad] Delegation consent declined");return}se();const ae=c.delegation,_t=ae!=null&&ae.available?{recommendation_id:c.recommendation_id,brand_id:ft(ae.brand_id),brand_name:ft(ae.brand_name||((Dt=(vt=c.recommendation)==null?void 0:vt.creative)==null?void 0:Dt.brand_name)),mcp_endpoint:ft(ae.mcp_endpoint),eligibility_reason:ft(ae.eligibility_reason),delegate_reason:ft(ae.delegate_reason),session_goal:ft(ae.session_goal),desired_outcome_type:ae.desired_outcome_type,required_user_inputs:Array.isArray(ae.required_user_inputs)?ae.required_user_inputs.filter(mt=>typeof mt=="string"):[],required_consent_types:Array.isArray(ae.required_consent_types)?ae.required_consent_types.filter(mt=>typeof mt=="string"):[],success_outcome:ft(ae.success_outcome),fallback_message:ft(ae.fallback_message),session_mode:ft(ae.session_mode),status:ft(ae.status),capabilities:ae.capabilities||[],allowed_data_types:ae.allowed_data_types||[],consent_requirements:ae.consent_requirements||[],auth_model:ft(ae.auth_model),handoff_protocol:ae.handoff_protocol&&typeof ae.handoff_protocol=="object"?ae.handoff_protocol:void 0,supported_actions:ae.supported_actions||[],metadata:ae.metadata&&typeof ae.metadata=="object"?ae.metadata:void 0,platform_response:c}:null;if(w&&_t){try{await w(_t)}finally{le(!1),Ee(!1)}return}if(g){try{await g(c)}finally{le(!1),Ee(!1)}return}const rt=((kt=(qt=c.recommendation)==null?void 0:qt.creative)==null?void 0:kt.follow_up_suggestion)||"";if(rt&&_){_(rt),le(!1),Ee(!1);return}if(rt&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(rt),le(!1),Ee(!1);return}le(!1),Ee(!1)},[N,Q]=a.useState(!1),X=f?f.charAt(0).toUpperCase():"B",ee=xe.surface,re=xe.border,Ie=(e==null?void 0:e.borderRadius)||((Rt=(ut=e==null?void 0:e.components)==null?void 0:ut.card)==null?void 0:Rt.borderRadius)||"8px",T="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",ie="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",D=((It=e==null?void 0:e.shadows)==null?void 0:It.medium)||((Tt=(Ht=e==null?void 0:e.components)==null?void 0:Ht.card)==null?void 0:Tt.boxShadow)||T,fe=((wt=e==null?void 0:e.shadows)==null?void 0:wt.large)||ie;return n.jsxs(hn,{productId:m,recommendationId:j,exposureUrl:k,sessionId:i,triggerExposureUrl:d,className:`admesh-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[n.jsx("style",{children:`
|
|
152
152
|
.admesh-tail-product-scroll {
|
|
153
153
|
-ms-overflow-style: none;
|
|
154
154
|
scrollbar-width: none;
|
|
@@ -159,23 +159,23 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
159
159
|
width: 0;
|
|
160
160
|
height: 0;
|
|
161
161
|
}
|
|
162
|
-
`}),n.jsxs("div",{className:"tail-ad-container flex flex-col gap-3 sm:flex-row",role:!C&&I?"link":void 0,tabIndex:!C&&I?0:void 0,style:{...(
|
|
162
|
+
`}),n.jsxs("div",{className:"tail-ad-container flex flex-col gap-3 sm:flex-row",role:!C&&I?"link":void 0,tabIndex:!C&&I?0:void 0,style:{...(Xe=e==null?void 0:e.components)==null?void 0:Xe.card,backgroundColor:ee,borderRadius:Ie,padding:"16px",boxShadow:D,border:`1px solid ${re}`,color:xe.text,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",cursor:!C&&I?"pointer":void 0},onClick:ne,onKeyDown:_e,onMouseEnter:K=>{K.currentTarget.style.boxShadow=fe,K.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:K=>{K.currentTarget.style.boxShadow=D,K.currentTarget.style.transform="translateY(0)"},children:[S&&n.jsx("div",{className:"flex-shrink-0 flex items-center justify-start pr-0 sm:justify-center sm:pr-2",style:{width:"auto",minWidth:"48px"},children:!N&&Nn(S)?n.jsx("a",{href:I||"#",target:I?"_blank":void 0,rel:I?"noopener noreferrer":void 0,onClick:I?Z:void 0,className:"block",style:{cursor:I?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:n.jsx("img",{src:S,alt:`${f} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{Q(!0),l.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):n.jsx("div",{className:"flex items-center justify-center text-lg font-semibold",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px",backgroundColor:xe.logoFallbackBg,color:xe.logoFallbackText,fontSize:"18px"},children:X})}),n.jsxs("div",{className:"flex-1",style:{width:"100%",minWidth:0},children:[Y&&!C&&n.jsx("div",{className:"mb-2",children:n.jsx("h3",{className:"font-semibold text-base",style:{fontSize:"14px",lineHeight:1.35,color:xe.text},children:I&&f?n.jsxs(n.Fragment,{children:[n.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-semibold",style:{color:xe.link,textDecoration:"underline",textDecorationColor:xe.link,textUnderlineOffset:"2px"},onClick:te,children:f}),U&&` โ ${U}`]}):Y})}),p&&!C&&n.jsx("p",{className:"text-sm mb-3 leading-relaxed",style:{fontSize:"13px",lineHeight:1.45,color:xe.textSecondary},children:p}),C&&L.length>0&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"admesh-tail-product-scroll",style:{marginBottom:"8px",overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch",overscrollBehaviorX:"contain",overscrollBehaviorY:"none",scrollBehavior:"smooth",paddingBottom:"2px"},children:n.jsx("div",{style:{display:"flex",gap:"10px",minWidth:"max-content",scrollSnapType:"x proximity",paddingRight:0},children:L.map(K=>{const $e=Bt(K.product_name)||"Product",ae=Bt(K.product_link)||Bt(K.product_url)||I||"#",_t=hs(Bt(K.product_description),10),rt=fs(K.product_price,K.product_currency),vt=gs(K.product_discount,K.product_discount_type,K.product_currency),Dt=Bt(K.product_image_url),qt=S&&Nn(S)?S:"",kt=Dt&&Nn(Dt)?Dt:qt,mt=Cr(K.product_cta_label),Jt=ae!=="#";return n.jsx("a",{href:ae,target:Jt?"_blank":void 0,rel:Jt?"noopener noreferrer":void 0,onClick:kn=>H(`tail_ad_product_${K.product_id||"item"}`,kn),className:"block",style:{border:`1px solid ${re}`,borderRadius:"8px",padding:"10px",backgroundColor:xe.surfaceMuted,textDecoration:"none",color:xe.text,minWidth:"min(264px, 82vw)",width:"clamp(220px, 72vw, 312px)",flex:"0 0 clamp(220px, 72vw, 312px)",scrollSnapAlign:"start"},children:n.jsxs("div",{className:"flex items-start gap-2",children:[kt?n.jsx("img",{src:kt,alt:$e,style:{width:"44px",height:"44px",objectFit:"cover",borderRadius:"6px",flexShrink:0}}):n.jsx("div",{className:"flex items-center justify-center text-xs font-semibold",style:{width:"44px",height:"44px",borderRadius:"6px",flexShrink:0,backgroundColor:xe.productImageFallbackBg,color:xe.textSecondary,fontSize:"12px"},children:$e.charAt(0).toUpperCase()}),n.jsxs("div",{style:{minWidth:0,flex:1},children:[n.jsx("p",{className:"font-medium text-sm",style:{fontSize:"13px",lineHeight:1.3,color:xe.text,marginBottom:"4px"},children:$e}),_t&&n.jsx("p",{className:"text-xs",style:{fontSize:"12px",lineHeight:1.3,color:xe.textSecondary,marginBottom:"6px"},children:_t}),(rt||vt)&&n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{marginBottom:mt?"6px":0},children:[rt&&n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("span",{style:{fontSize:"10px",color:xe.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Price"}),n.jsx("span",{className:"font-semibold",style:{fontSize:"13px",color:xe.text},children:rt})]}),vt&&n.jsx("span",{className:"text-xs",style:{fontSize:"11px",color:xe.successText,backgroundColor:xe.successBg,borderRadius:"999px",padding:"2px 8px",fontWeight:600},children:vt})]}),mt&&n.jsx("span",{className:"font-medium",style:{fontSize:"12px",color:xe.link,textDecoration:"underline",textUnderlineOffset:"2px"},children:mt})]})]})},K.product_id||`${j}-${$e}`)})})})}),n.jsxs("div",{className:"mt-2 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[C&&f&&n.jsx("span",{className:"text-sm",style:{fontSize:"13px",color:xe.textSecondary,fontWeight:400},children:f}),M?n.jsx("button",{type:"button",onClick:xt,className:"underline transition-colors duration-200 font-medium text-sm",style:{color:xe.link,textDecoration:"underline",textDecorationColor:xe.link,textUnderlineOffset:"2px",fontSize:"13px",background:"none",border:"none",padding:0,cursor:"pointer"},children:W}):null,V&&n.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-medium text-sm",style:{color:xe.link,textDecoration:"underline",textDecorationColor:xe.link,textUnderlineOffset:"2px",fontSize:"13px"},onClick:ge,children:G}),C&&A.length>L.length&&n.jsxs("span",{className:"text-xs",style:{fontSize:"11px",color:xe.textMuted},children:["+",A.length-L.length," more"]})]}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("p",{className:"text-xs",style:{fontSize:"11px",color:xe.textMuted},children:x})})]}),Ge?n.jsxs("div",{style:{marginTop:"10px",border:`1px solid ${re}`,borderRadius:"12px",backgroundColor:xe.surfaceSubtle,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:xe.link},children:"Confirm Agent Access"}),n.jsxs("div",{style:{fontSize:"14px",lineHeight:1.4,color:xe.text,fontWeight:600},children:["Allow ",P||"this brand"," to start a delegated session?"]}),n.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:xe.textSecondary},children:"The agent will only use the details you choose to share for this request."})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[n.jsx("button",{type:"button",disabled:ve,onClick:K=>{K.preventDefault(),K.stopPropagation(),!ve&&Re(!1)},style:{borderRadius:"10px",border:`1px solid ${re}`,background:ee,color:xe.text,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:ve?"not-allowed":"pointer",opacity:ve?.65:1},children:"Not now"}),n.jsx("button",{type:"button",disabled:ve,onClick:K=>{K.preventDefault(),K.stopPropagation(),!ve&&Re(!0)},style:{borderRadius:"10px",border:"none",background:"#2563eb",color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:ve?"wait":"pointer",opacity:ve?.86:1},children:ve?"Connecting...":"Allow agent"})]})]}):null]})]})]})},Vr=({recommendationId:t,admeshLink:e,productId:o,children:s,trackingData:i,className:d,style:u})=>{const w=a.useRef(null);a.useEffect(()=>{if(!w.current)return;w.current.querySelectorAll("a").forEach(c=>{(!c.hasAttribute("target")||c.getAttribute("target")!=="_blank")&&(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer"))})},[s]);const g=a.useCallback(_=>{const m=_.target.closest("a");m?((!m.href||m.href==="#"||m.href==="")&&e&&(m.href=e),(!m.hasAttribute("target")||m.getAttribute("target")!=="_blank")&&(m.setAttribute("target","_blank"),m.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):l.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return n.jsx("div",{ref:w,className:d,onClick:g,style:{cursor:"pointer",...u},children:s})};Vr.displayName="AdMeshLinkTracker";function bs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $n={exports:{}};/*!
|
|
163
163
|
Copyright (c) 2018 Jed Watson.
|
|
164
164
|
Licensed under the MIT License (MIT), see
|
|
165
165
|
http://jedwatson.github.io/classnames
|
|
166
|
-
*/var
|
|
166
|
+
*/var Mr;function ys(){return Mr||(Mr=1,(function(t){(function(){var e={}.hasOwnProperty;function o(){for(var d="",u=0;u<arguments.length;u++){var w=arguments[u];w&&(d=i(d,s(w)))}return d}function s(d){if(typeof d=="string"||typeof d=="number")return d;if(typeof d!="object")return"";if(Array.isArray(d))return o.apply(null,d);if(d.toString!==Object.prototype.toString&&!d.toString.toString().includes("[native code]"))return d.toString();var u="";for(var w in d)e.call(d,w)&&d[w]&&(u=i(u,w));return u}function i(d,u){return u?d?d+" "+u:d+u:d}t.exports?(o.default=o,t.exports=o):window.classNames=o})()})($n)),$n.exports}var ws=ys();const _s=bs(ws),vs={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},ks={"Top Match":"โ
","Free Tier":"โ","AI Powered":"โ",Popular:"โฒ",New:"โ","Trial Available":"โ"},Kr=({type:t,variant:e,size:o="md",className:s,style:i})=>{const d=e||vs[t]||"secondary",u=ks[t],w=_s("admesh-component","admesh-badge",`admesh-badge--${d}`,`admesh-badge--${o}`,s);return n.jsxs("span",{className:w,style:i,children:[u&&n.jsx("span",{className:"admesh-badge__icon",children:u}),n.jsx("span",{className:"admesh-badge__text",children:t})]})};Kr.displayName="AdMeshBadge";const nt=":not([data-admesh-ad-content], [data-admesh-ad-content] *)",Gr=`
|
|
167
167
|
.admesh-publisher-panel {
|
|
168
168
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
169
169
|
text-align: left;
|
|
170
170
|
line-height: 1.5;
|
|
171
171
|
-webkit-font-smoothing: antialiased;
|
|
172
172
|
}
|
|
173
|
-
.admesh-publisher-panel *${
|
|
173
|
+
.admesh-publisher-panel *${nt}, .admesh-publisher-panel *${nt}::before, .admesh-publisher-panel *${nt}::after {
|
|
174
174
|
box-sizing: border-box;
|
|
175
175
|
}
|
|
176
|
-
.admesh-publisher-panel button${
|
|
177
|
-
.admesh-publisher-panel button${
|
|
178
|
-
.admesh-publisher-panel button${
|
|
176
|
+
.admesh-publisher-panel button${nt}, .admesh-publisher-panel input${nt} { font-family: inherit; }
|
|
177
|
+
.admesh-publisher-panel button${nt} { transition: border-color 150ms ease, background-color 150ms ease; }
|
|
178
|
+
.admesh-publisher-panel button${nt}:focus-visible, .admesh-publisher-panel a${nt}:focus-visible {
|
|
179
179
|
outline: 2px solid var(--publisher-accent);
|
|
180
180
|
outline-offset: 2px;
|
|
181
181
|
}
|
|
@@ -189,19 +189,19 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
189
189
|
}
|
|
190
190
|
.admesh-publisher-panel .admesh-publisher-source { transition: border-color 150ms ease; }
|
|
191
191
|
.admesh-publisher-panel .admesh-publisher-suggestion { overflow-wrap: anywhere; }
|
|
192
|
-
.admesh-publisher-panel input${
|
|
193
|
-
.admesh-publisher-panel a${
|
|
192
|
+
.admesh-publisher-panel input${nt} { min-width: 0; }
|
|
193
|
+
.admesh-publisher-panel a${nt} { text-underline-offset: 3px; }
|
|
194
194
|
@media (prefers-reduced-motion: reduce) {
|
|
195
|
-
.admesh-publisher-panel *${
|
|
195
|
+
.admesh-publisher-panel *${nt}, .admesh-publisher-panel *${nt}::before, .admesh-publisher-panel *${nt}::after {
|
|
196
196
|
animation: none !important;
|
|
197
197
|
transition: none !important;
|
|
198
198
|
scroll-behavior: auto !important;
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
201
|
@media (max-width: 767px) {
|
|
202
|
-
.admesh-publisher-panel:not([data-compact="true"]) input${
|
|
202
|
+
.admesh-publisher-panel:not([data-compact="true"]) input${nt} { font-size: 16px !important; }
|
|
203
203
|
}
|
|
204
|
-
`;function
|
|
204
|
+
`;function Ss({value:t,onChange:e,onSend:o,onStop:s,onSuggestion:i,suggestions:d,registerSuggestion:u,open:w,onOpenChange:g,loading:_,analyzing:c,compact:m,expanded:k,suggestionPlacement:j="below",showLogo:p=!0,logoUrl:x,title:f,placeholder:h,colors:S}){const I=a.useId(),G=a.useRef(null),A=a.useRef(null),C=a.useRef(null),[L,$]=a.useState({visibility:"hidden"}),F=w&&!_&&(c||d.length>0);a.useLayoutEffect(()=>{var V;if(!F)return;const M=()=>{var ne,_e;const Y=(ne=G.current)==null?void 0:ne.getBoundingClientRect();if(!Y)return;const U=((_e=window.visualViewport)==null?void 0:_e.height)??window.innerHeight,H=document.documentElement.clientWidth,te=U-Y.bottom-16,ge=Y.top-16,Z=j==="above"?!(ge<96&&te>ge):te<96&&ge>te;$({position:"fixed",left:Math.max(8,Math.min(Y.left,H-Y.width-8)),width:Math.min(Y.width,H-16),maxHeight:Math.max(40,Math.min(300,Z?ge:te)),...Z?{bottom:window.innerHeight-Y.top+8}:{top:Y.bottom+8},zIndex:2147483002})},W=Y=>{var H,te;const U=Y.target;!((H=G.current)!=null&&H.contains(U))&&!((te=C.current)!=null&&te.contains(U))&&g(!1)};return M(),window.addEventListener("resize",M),window.addEventListener("scroll",M,!0),(V=window.visualViewport)==null||V.addEventListener("resize",M),document.addEventListener("pointerdown",W),()=>{var Y;window.removeEventListener("resize",M),window.removeEventListener("scroll",M,!0),(Y=window.visualViewport)==null||Y.removeEventListener("resize",M),document.removeEventListener("pointerdown",W)}},[F,j,g]);const P=M=>{var W,V;!((W=G.current)!=null&&W.contains(M))&&!((V=C.current)!=null&&V.contains(M))&&g(!1)},z=()=>{!t.trim()||_||(g(!1),o())};return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:G,className:"admesh-publisher-composer",onBlur:M=>P(M.relatedTarget),onClick:M=>{var W;M.target.closest("button, a")||((W=A.current)==null||W.focus(),g(!0))},style:{display:"flex",alignItems:"center",gap:m?8:12,minWidth:0,width:"100%",flexShrink:0,border:`1px solid ${S.border}`,borderRadius:8,background:S.surface,cursor:"text",padding:m?"6px":"8px 8px 8px 12px"},children:[p&&!k&&n.jsx("div",{style:{width:m?24:32,height:m?24:32,display:"grid",placeItems:"center",flexShrink:0,color:S.accent},children:x?n.jsx("img",{src:x,alt:`${f} logo`,style:{width:"100%",height:"100%",objectFit:"contain"}}):n.jsx(Un,{size:m?18:21,strokeWidth:1.5,"aria-label":f})}),n.jsx("input",{ref:A,type:"text",value:t,placeholder:h,"aria-label":"Ask the publisher assistant","aria-expanded":F,"aria-controls":F?I:void 0,onFocus:()=>g(!0),onChange:M=>{e(M.target.value),g(!0)},onKeyDown:M=>{var W,V;M.nativeEvent.isComposing||(M.key==="Escape"&&(M.preventDefault(),g(!1)),M.key==="ArrowDown"&&(M.preventDefault(),F?(V=(W=C.current)==null?void 0:W.querySelector("button"))==null||V.focus():g(!0)),M.key==="Enter"&&(M.preventDefault(),z()))},style:{flex:1,minWidth:0,border:"none",outline:"none",padding:m?"6px 0":"10px 0",fontSize:m?13:15,color:S.text,background:"transparent"}}),n.jsxs("span",{style:{flexShrink:0,fontSize:m?8:9,lineHeight:1.3,color:S.muted,textAlign:"right",whiteSpace:"nowrap"},children:["powered by",n.jsx("br",{}),n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{fontWeight:600,color:"inherit",textDecoration:"underline",textUnderlineOffset:2,cursor:"pointer"},children:"AdMesh"})]}),n.jsx("button",{type:"button","aria-label":_?"Stop generating":"Send message",disabled:!_&&!t.trim(),onClick:_?s:z,style:{display:"grid",placeItems:"center",flexShrink:0,width:m?32:40,height:m?32:40,border:"none",borderRadius:6,background:S.accent,color:S.accentText,cursor:"pointer",opacity:!_&&!t.trim()?.5:1},children:_?n.jsx($o,{size:14,fill:"currentColor","aria-hidden":"true"}):n.jsx(jo,{size:18,"aria-hidden":"true"})})]}),F&&Hn.createPortal(n.jsxs("div",{ref:C,id:I,role:"group","aria-label":"Suggested questions",className:"admesh-publisher-panel",onBlur:M=>P(M.relatedTarget),onKeyDown:M=>{var W,V,Y,U;if(M.key==="Escape"&&(M.preventDefault(),(W=A.current)==null||W.focus(),g(!1)),M.key==="ArrowDown"||M.key==="ArrowUp"){M.preventDefault();const H=Array.from(((V=C.current)==null?void 0:V.querySelectorAll("button"))??[]),te=H.indexOf(document.activeElement)+(M.key==="ArrowDown"?1:-1);te<0?(Y=A.current)==null||Y.focus():(U=H[Math.min(te,H.length-1)])==null||U.focus()}},style:{...L,"--publisher-accent":S.accent,padding:6,border:`1px solid ${S.border}`,borderRadius:10,background:S.surface,overflowY:"auto",overscrollBehavior:"contain",boxShadow:"0 8px 24px rgba(15,23,42,0.1)"},children:[n.jsx("style",{children:Gr}),c&&!d.length?n.jsx("div",{role:"status",style:{padding:12,color:S.muted,fontSize:13},children:"Finding suggested questionsโฆ"}):d.map(M=>n.jsxs("button",{ref:u(M.id),type:"button",className:"admesh-publisher-suggestion","data-admesh-sponsored":M.is_sponsored?"true":void 0,onClick:()=>{g(!1),i(M)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,width:"100%",minWidth:0,margin:"0 0 4px",padding:"10px 12px",border:`1px solid ${M.is_sponsored?S.accent:S.border}`,borderRadius:6,textAlign:"left",fontSize:13,fontWeight:500,lineHeight:1.4,cursor:"pointer",background:M.is_sponsored?S.accent:S.surface,color:M.is_sponsored?S.accentText:S.text},children:[n.jsx("span",{children:M.text}),M.is_sponsored&&n.jsx("span",{style:{fontSize:10,flexShrink:0},children:"Ad"})]},M.id))]}),document.body)]})}const Ln="admesh-ui-sdk-styles",Fn="admesh-ui-sdk-reset",As=`
|
|
205
205
|
/* AdMesh UI SDK - CSS Reset & Normalization */
|
|
206
206
|
.admesh-component,
|
|
207
207
|
.admesh-component * {
|
|
@@ -290,7 +290,7 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
290
290
|
.admesh-component[data-admesh-theme="light"] {
|
|
291
291
|
color-scheme: light;
|
|
292
292
|
}
|
|
293
|
-
`,
|
|
293
|
+
`,Cs=`
|
|
294
294
|
/* AdMesh Core Component Styles */
|
|
295
295
|
|
|
296
296
|
.admesh-component {
|
|
@@ -501,7 +501,7 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
501
501
|
font-size: 0.875rem;
|
|
502
502
|
}
|
|
503
503
|
}
|
|
504
|
-
`,
|
|
504
|
+
`,Ms=()=>{if(!(typeof document>"u")&&!(document.getElementById(Fn)&&document.getElementById(Ln))){if(!document.getElementById(Fn)){const t=document.createElement("style");t.id=Fn,t.textContent=As,document.head.appendChild(t)}if(!document.getElementById(Ln)){const t=document.createElement("style");t.id=Ln,t.textContent=Cs,document.head.appendChild(t)}}},js=`
|
|
505
505
|
/* AdMesh UI SDK - Complete Self-Contained Styles */
|
|
506
506
|
|
|
507
507
|
/* CSS Reset for AdMesh components */
|
|
@@ -1169,7 +1169,7 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
1169
1169
|
.admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
1170
1170
|
.admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
|
|
1171
1171
|
}
|
|
1172
|
-
`;let
|
|
1172
|
+
`;let jr=!1;const Yr=()=>{a.useEffect(()=>{if(!jr){try{Ms();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=js,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),jr=!0}catch{l.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])},Es=()=>{};function Rs(t){const e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;const o=Math.floor(e/60),s=e%60;return s>0?`${o}m ${s}s`:`${o}m`}function Is(t){return Rs(t/1e3)}const Wn=({content:t,theme:e,fontSize:o})=>{const s=p=>p.split(/(\*\*[^*]+\*\*|\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g).map((f,h)=>{if(f.startsWith("**")&&f.endsWith("**")&&f.length>4)return n.jsx("strong",{style:{fontWeight:"600",color:e.textColor},children:f.slice(2,-2)},h);const S=f.match(/^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/);return S?n.jsx("a",{href:S[2],target:"_blank",rel:"noopener noreferrer",style:{color:e.primaryColor,textDecoration:"underline",textUnderlineOffset:"2px"},children:S[1]},h):n.jsx(a.Fragment,{children:f},h)}),i=p=>p.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(f=>f.trim()).filter((f,h,S)=>f.length>0||h<S.length-1),d=p=>{const x=i(p);return x.length>1&&x.every(f=>/^:?-{3,}:?$/.test(f))},u=p=>{const x=p.indexOf("|");if(x<=0)return{heading:null,headerLine:p};const f=p.slice(0,x).trim();return!f||/^[-|:\s]+$/.test(f)?{heading:null,headerLine:p}:{heading:f,headerLine:p.slice(x).trim()}},w=(p,x)=>{const f=i(p).length,h=i(x).length;return f<=1||f===h?x:`| ${Array.from({length:f},()=>"---").join(" | ")} |`},g=p=>{if(p.length<2||!p[0].includes("|"))return{heading:null,lines:p};const{heading:x,headerLine:f}=u(p[0]),h=f.startsWith("|")?f:`| ${f}`,S=w(h,p[1]);return{heading:x,lines:[h,S,...p.slice(2)]}},_=p=>{if(p.length<2||!p[0].includes("|"))return!1;const{lines:x}=g(p);return d(x[1])&&i(x[0]).length>=2},c=p=>{if(!p.includes("|"))return[p];let x=p.trim();const f=[],h=x.indexOf("|");if(h>0){const S=x.slice(0,h).trim();S&&!/^[-|:\s]+$/.test(S)&&(f.push(S),x=x.slice(h).trim())}return x=x.replace(/\|\s*(\|(?:\s*:?-{3,}:?\s*\|)+)/g,(S,I)=>`
|
|
1173
1173
|
${I}`),x=x.replace(/\|\s*\|\s*(?=[A-Za-z0-9*])/g,`|
|
|
1174
1174
|
| `),x=x.replace(/\|\s+(?=\|(?!\s*:?-{3,}:?\s*\|)[^|\n])/g,`|
|
|
1175
1175
|
`),f.push(...x.split(`
|
|
@@ -1178,6 +1178,6 @@ ${I}`),x=x.replace(/\|\s*\|\s*(?=[A-Za-z0-9*])/g,`|
|
|
|
1178
1178
|
`)},j=(p=>{const x=m(p).split(`
|
|
1179
1179
|
`),f=[];let h=0;for(;h<x.length;){const S=x[h],I=x[h+1]||"";if(S.includes("|")&&d(I)){f.length>0&&f[f.length-1].trim()&&f.push("");const{heading:G,headerLine:A}=u(S);for(G&&f.push(G),f.push(A,w(A,I)),h+=2;h<x.length&&x[h].includes("|")&&x[h].trim();)f.push(x[h]),h+=1;h<x.length&&x[h].trim()&&f.push("");continue}f.push(S),h+=1}return f.join(`
|
|
1180
1180
|
`)})(t).split(/\n\s*\n/).map(p=>p.trim()).filter(Boolean);return n.jsx("div",{style:{margin:0,color:e.textColor,fontSize:o},children:j.map((p,x)=>{const f=p.split(`
|
|
1181
|
-
`).map(A=>A.trim()).filter(Boolean),h=f.every(A=>/^[-*]\s+/.test(A)),S=f.every(A=>/^\d+\.\s+/.test(A)),I=f.length===1&&/^#{1,3}\s+/.test(f[0]),G=v(f);if(I){const A=f[0].replace(/^#{1,3}\s+/,"");return n.jsx("h3",{style:{marginTop:x===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(A)},x)}if(G){const{heading:A,lines:C}=g(f),L=i(C[0]),N=C.slice(2).map(i).filter(F=>F.length===L.length);return n.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[A?n.jsx("p",{style:{marginTop:x===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(A)}):null,n.jsx("div",{style:{border:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,borderRadius:8,overflowX:"auto"},children:n.jsxs("table",{style:{width:"100%",minWidth:L.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[n.jsx("thead",{children:n.jsx("tr",{children:L.map((F,P)=>n.jsx("th",{style:{textAlign:"left",padding:"9px 10px",fontWeight:600,background:e.surfaceColor||"rgba(148, 163, 184, 0.12)",borderBottom:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,whiteSpace:"normal"},children:s(F)},P))})}),n.jsx("tbody",{children:N.map((F,P)=>n.jsx("tr",{children:F.map((z,M)=>n.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:P===N.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(z)},M))},P))})]})})]},x)}if(h||S){const A=S?"ol":"ul";return n.jsx(A,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:f.map((C,L)=>n.jsx("li",{style:{marginBottom:"0.45rem"},children:s(C.replace(/^([-*]|\d+\.)\s+/,""))},L))},x)}return n.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:f.map((A,C)=>n.jsxs(a.Fragment,{children:[C>0&&n.jsx("br",{}),s(A)]},C))},x)})})};function ln(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function jr(t){if(typeof t=="number")return t;if(typeof t!="string")return;const e=Number(t.trim().replace(/px$/i,""));return Number.isFinite(e)&&e>0?e:void 0}function Yt(t){return t.replace(/\s+/g," ").trim()}function Es(t,e){const o=t.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),s=e.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),i=e.find(u=>u==null?void 0:u.is_sponsored);if(!i)return s.length?s:o;const d=s.length?s:o;return[i,...d].slice(0,4)}function Rs(t,e,o,s){const i=new Set,d=[],u=(j,p="information")=>{const x=Yt(j);if(!x)return;const f=x.toLowerCase();i.has(f)||(i.add(f),d.push({id:`followup_${d.length}_${f.replace(/[^a-z0-9]+/g,"_")}`,text:x,type:p,is_sponsored:!1}))},w=new Set,g=j=>{const p=Yt(j||"");if(!p)return;const x=p.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();x&&w.add(x)};(s||[]).forEach(j=>g(j==null?void 0:j.title)),(o||[]).forEach(j=>g(j==null?void 0:j.title)),e.split(/\n+/).map(j=>Yt(j.replace(/^[-*]\s+/,""))).filter(Boolean).filter(j=>j.length>=24&&j.length<=90).forEach(j=>{w.size>=6||g(j)});const c=Yt(t.replace(/[?.!]+$/g,"")),m=Array.from(w).slice(0,3);return[m[0]?`Tell me more about ${m[0]}`:"",m[1]?`Show me examples related to ${m[1]}`:"",m[2]?`Compare the main options for ${m[2]}`:"","Break this down more simply",`What should I look at next about ${c}`,"Give me the practical takeaway here"].forEach((j,p)=>{d.length>=3||u(j,p===0?"comparison":"information")}),d.slice(0,3)}function Is(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function Er(t){return t?{shell:{position:"fixed",left:0,right:0,bottom:0,width:"100%",maxWidth:"100%",height:"calc(100dvh - env(safe-area-inset-bottom, 0px))",maxHeight:"calc(100dvh - env(safe-area-inset-bottom, 0px))",padding:0,margin:0,zIndex:2147483001,boxSizing:"border-box"},panelWidth:"100%",panelMaxWidth:"100%",panelHeight:"100%",panelMaxHeight:"100%",panelBorderRadius:"0"}:{shell:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",maxWidth:"100%",maxHeight:"calc(100vh - 24px)",zIndex:2147483001,boxSizing:"border-box"},panelWidth:"min(960px, calc(100vw - 24px))",panelMaxWidth:"100%",panelHeight:"min(78vh, 760px)",panelMaxHeight:void 0,panelBorderRadius:"12px"}}function Yr(t){const e=t==null?void 0:t.trim();if(!e||/%%[^%]+%%/.test(e))return!1;try{const o=new URL(e);return!!(o.protocol&&o.hostname)}catch{return!1}}function Rr(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Yr(e))return e}catch{return}}function Ir(t){if(typeof window>"u")return{page_url:void 0,page_path:void 0,article_slug:void 0,page_title:void 0,referrer:void 0,device_type:"unknown"};const e=Rr()||(Yr(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=Rr()?window.location.pathname||"/":void 0}const s=(o||"").split("/").filter(Boolean);return{page_url:e,page_path:o,article_slug:s[s.length-1],page_title:document.title||void 0,referrer:document.referrer||void 0,device_type:Is()}}function Ts(t){var s,i;const e=(i=(s=t==null?void 0:t.recommendation)==null?void 0:s.creative)==null?void 0:i.follow_up_suggestion,o=t==null?void 0:t.recommendation_id;return!e||!o?null:{id:o,text:Yt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Wn(t){return[...t].sort((e,o)=>{const s=!!e.is_sponsored,i=!!o.is_sponsored;return s===i?0:s?-1:1})}const Ds={mode:"light",primaryColor:"#3b82f6",secondaryColor:"#64748b",backgroundColor:"#ffffff",surfaceColor:"#f8fafc",borderColor:"#e2e8f0",textColor:"#1e293b",textSecondaryColor:"#64748b",borderRadius:"0.5rem",spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},shadows:{small:"0 1px 2px 0 rgb(0 0 0 / 0.05)",medium:"0 4px 6px -1px rgb(0 0 0 / 0.1)",large:"0 10px 15px -3px rgb(0 0 0 / 0.1)"}},Ps={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},zs={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},Ns=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:d,showHeader:u=!0,showHeaderTitle:w=!0,showSubtitle:g=!0,layout:v="floating",surface:c="page",adSlotBehavior:m="expand",showCompactSlotHeader:k=!0,showCompactWelcomeMessage:j=!0,showCompactSlotInput:p=!0,showCompactSlotDisclaimer:x=!0,panelWidth:f,panelHeight:h,analyticsPageUrl:S,fontScale:I=1,position:G="bottom-right",size:A="md",defaultOpen:C,open:L,onOpenChange:N,autoOpen:F=!1,showWelcomeMessage:P=!1,welcomeMessage:z="Hi, Iโm Ava. Iโll help you find the best options.",placeholder:M="Ask me anything about products...",adsEnabled:B=!0,suggestions:K,maxSuggestions:X=6,suggestionStyle:U="carousel",suggestionTrigger:H="always",suggestionPlacement:ne="below",onlyShowWhenSponsored:ce=!1,variant:q="default",queryHandler:Ce,suggestionsLoader:ke,disclaimerText:tt,poweredByLabel:Ee="Powered by AdMesh",subtitle:be="Publisher Assistant",onOpen:se,onClose:ue})=>{const{sdk:le,sessionId:me,theme:Re,apiKey:nt,userId:$}=tn(),{suggestions:Q,isAnalyzingIntent:J,intentError:ee,retryIntentAnalysis:oe,activeDelegationSession:Se,hasActiveDelegationSession:D,stopDelegationSession:ie,refreshDelegationActivity:T}=On();Gr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:le,sessionId:me,hasContextTheme:!!Re});const E=t||Re||Ds,fe=(E==null?void 0:E.mode)||"light",te=c==="ad-slot",Ge=(r=!1)=>te&&!(r&&m==="expand"),[pe,Be]=a.useState(C||F),Ie=L!==void 0,Ae=Ie?L:pe,[ye,Pe]=a.useState(""),[Lt,ht]=a.useState(!1),[Te,We]=a.useState([]),[ge,ot]=a.useState(!1),[Mt,jt]=a.useState(null),[O,st]=a.useState(!1),[wt,Ft]=a.useState(new Set),[qt,it]=a.useState(K||Q||[]),[Y,we]=a.useState(0),[at,lt]=a.useState(0),[_t,Ot]=a.useState({}),vt=a.useRef(null),dt=a.useRef(!1),Ye=a.useRef(null),Qt=a.useRef(new Map),V=a.useRef([]),Fe=a.useRef(null),ae=a.useRef(null),kt=a.useRef(null),ct=a.useRef(!1),Et=a.useRef(!1),Rt=a.useRef(null),It=a.useRef(null),Tt=a.useRef(null),[ft,mn]=a.useState(!1),[nn,Xr]=a.useState(!1),St=a.useRef(null),Qe=a.useRef(null),Jr=!!(nt!=null&&nt.toLowerCase().startsWith("pub_")),Xe=D()&&(Se==null?void 0:Se.session_id)===me?Se:null,kn=a.useRef(new Set),Kn=a.useRef(new Set),Gn=a.useRef(!1),Xt=te&&m==="expand"&&(O||ge),[pn,Zr]=a.useState(!1);a.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia("(max-width: 767px)"),b=()=>Zr(r.matches);return b(),r.addEventListener("change",b),()=>r.removeEventListener("change",b)},[]),a.useEffect(()=>{if(!Xt||typeof document>"u")return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[Xt]);const Sn=te&&m==="sticky"&&(O||Te.length>0||ge),Dt=ln(f)??"100%",Jt=ln(h)??"100%",eo=jr(f),Yn=jr(h),Qn=te&&(Yn??Number.POSITIVE_INFINITY)<=60,ut=te&&(eo??Number.POSITIVE_INFINITY)<=360&&(Yn??Number.POSITIVE_INFINITY)<=120,rn=a.useCallback(r=>b=>{b?Qt.current.set(r,b):Qt.current.delete(r)},[]),De=a.useCallback(async(r,b={})=>{if(!(!le||!me))try{await le.trackPublisherAssistantEvent({event_name:r,timestamp:new Date().toISOString(),session_id:me,...Ir(S),...b})}catch(y){console.warn(`[AdMeshIntentAssistant] Failed to track ${r}`,y)}},[S,le,me]),hn=a.useCallback((r,b,y)=>{var W,he;const _=b==null?void 0:b.recommendation_id;if(!_)return;const R=`${r}:${_}`;Kn.current.has(R)||(Kn.current.add(R),De("recommendation_shown",{message_id:r,query:y,recommendation_id:_,brand_name:(he=(W=b.recommendation)==null?void 0:W.creative)==null?void 0:he.brand_name,is_sponsored:!0}))},[De]),An=a.useCallback((r,b,y,_,R,W)=>{const he=Array.isArray(W)&&W.length?W.map((je,Me)=>{const $e=Yt(je.text||"");return $e?{id:`followup_llm_${Me}_${$e.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:$e,type:je.type||"information",is_sponsored:!1}:null}).filter(je=>!!je).slice(0,3):Rs(r,b,y,_),ze=Ts(R),ve=ze?[ze,...he.slice(0,2)]:he.slice(0,3);ve.length&&it(Wn(ve))},[]),fn=a.useCallback((r,b)=>{const y=Yt(r.query||r.label||"");if(!y||!b)return;const _={id:b,text:y,type:"action",is_sponsored:!0,recommendation:{recommendation_id:b,recommendation:{creative:{follow_up_suggestion:y}},tracking:{followup_engagement_url:r.engagement_url,followup_exposure_url:r.exposure_url}}};it(R=>{const W=R.filter(he=>!he.is_sponsored).slice(0,3);return Wn([_,...W].slice(0,4))})},[]),Xn=a.useCallback(()=>{const r=Fe.current,b=ae.current;if(!r||!b)return!1;const y=r.getBoundingClientRect(),_=b.getBoundingClientRect(),R=Math.max(0,r.scrollTop+_.top-y.top);return r.scrollTop=R,!0},[]);a.useLayoutEffect(()=>{var r;if(ct.current){Xn()&&(ct.current=!1);return}Et.current||(r=It.current)==null||r.scrollIntoView({behavior:"smooth"})},[Te,Xn]),a.useLayoutEffect(()=>{if(!te||Xt)return;const r=Rt.current;if(!r)return;const b=r.closest(".admesh-publisher-assistant-reactMount"),y=Jt;[r,b].forEach(R=>{R&&(R.style.width=Dt,R.style.maxWidth=Dt,R.style.height=y,R.style.maxHeight=y,R.style.overflow="hidden",R.style.boxSizing="border-box",R.dataset.admeshAdSlotExpanded=Sn?"true":"false")});const _=b==null?void 0:b.parentElement;_&&_!==document.body&&_!==document.documentElement&&(_.style.width=Dt,_.style.maxWidth=Dt,_.style.height=y,_.style.maxHeight=y,_.style.overflow="hidden",_.style.boxSizing="border-box")},[Jt,Dt,Xt,te,Sn]),a.useEffect(()=>{if(K&&K.length){it(K);return}Q&&Q.length&&it(r=>Es(r,Q))},[K,Q]),a.useEffect(()=>{if(q!=="default"||!ke)return;let r=!1;return ke().then(b=>{!r&&Array.isArray(b)&&b.length&&it(b)}).catch(b=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",b)}),()=>{r=!0}},[ke,q]),a.useEffect(()=>{if(!ge){lt(0),vt.current=null;return}vt.current==null&&(vt.current=typeof performance<"u"?performance.now():Date.now());const r=()=>{const y=vt.current;if(y==null)return;const _=typeof performance<"u"?performance.now():Date.now();lt(Math.floor((_-y)/1e3))};r();const b=window.setInterval(r,1e3);return()=>window.clearInterval(b)},[ge]),a.useEffect(()=>{if(!ge||q!=="default"){we(0);return}const r=window.setInterval(()=>{we(b=>Math.min(b+1,7))},3e3);return()=>window.clearInterval(r)},[ge,q]),a.useEffect(()=>{Gn.current||!le||!me||(Gn.current=!0,De("assistant_loaded",{metadata:{layout:v,surface:c,variant:q,default_open:C||F}}))},[F,C,v,le,me,c,De,q]);const Wt=a.useCallback(r=>{Ie?N==null||N(r):Be(r),r?(De("assistant_opened",{metadata:{layout:v,surface:c,ad_slot_behavior:m,variant:q,expanded:O}}),se==null||se()):ue==null||ue()},[Ie,O,v,N,se,ue,c,De,q]),Jn=a.useCallback(()=>{Wt(!0)},[Wt]),to=a.useCallback(()=>{Wt(!1)},[Wt]),no=a.useCallback(()=>{st(r=>!r)},[]),Zn=a.useCallback(async(r,b,y,_,R,W,he)=>{var ze,ve,je;if(!le)return console.warn("[AdMeshIntentAssistant] SDK not available - using fallback response"),{text:"I'm a demo assistant. The SDK is not properly configured, but I can still help with suggestions! Try clicking on one of the suggested questions above."};try{Xe&&await T("turn_started",{source:"publisher_assistant",recommendation_id:Xe.recommendation_id}).catch(de=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",de)});const Me=await fetch(`${le.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:W,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${nt}`},body:JSON.stringify({message:r,session_id:me||"default-session",message_id:b,user_id:$,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:Ir(S),conversation_history:he,sponsored_recommendation:R!=null&&R.recommendation_id?{recommendation_id:R.recommendation_id,brand_name:(ve=(ze=R.recommendation)==null?void 0:ze.creative)==null?void 0:ve.brand_name}:void 0,active_delegation_session:Xe?{delegation_session_id:Xe.delegation_session_id,recommendation_id:Xe.recommendation_id,session_id:Xe.session_id,brand_name:Xe.brand_name,mcp_endpoint:Xe.mcp_endpoint,status:Xe.status}:void 0}})});if(!Me.ok)throw new Error(`API request failed: ${Me.status} ${Me.statusText}`);const $e=(je=Me.body)==null?void 0:je.getReader(),zt=new TextDecoder;if(!$e)throw new Error("Response body is not readable");let Ve="",Je,Nt,$t,Z,re;return await(async()=>{try{for(;;){const{done:de,value:gt}=await $e.read();if(de)break;const rt=zt.decode(gt,{stream:!0}).split(`
|
|
1182
|
-
`);for(const Kt of rt)if(Kt.startsWith("data: ")){const Dn=Kt.slice(6);if(Dn.trim()==="[DONE]")return Xe&&T("turn_completed",{source:"publisher_assistant",recommendation_id:Xe.recommendation_id}).catch(Le=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",Le)}),{text:Ve,source_links:Je,related_items:Nt,followup_suggestions:$t,used_capability:Z,response_time_ms:re};try{const Le=JSON.parse(Dn);switch(Le.type){case"content":{const mr=Le.content||"";Ve+=mr,y==null||y(mr);break}case"final":{Ve=Le.reply||Ve,Je=Array.isArray(Le.source_links)?Le.source_links:void 0,Nt=Array.isArray(Le.related_items)?Le.related_items:void 0,$t=Array.isArray(Le.followup_suggestions)?Le.followup_suggestions:void 0,Z=typeof Le.used_capability=="string"?Le.used_capability:Z,re=typeof Le.response_time_ms=="number"?Le.response_time_ms:re;break}case"followup_suggestions":{$t=Array.isArray(Le.followup_suggestions)?Le.followup_suggestions:$t;break}case"error":throw new Error(Le.message||"Unknown streaming error");case"session_start":_==null||_(),console.log("Session started:",Le.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",Dn);continue}}}}catch(de){if(W!=null&&W.aborted)return{text:Ve,source_links:Je,related_items:Nt,followup_suggestions:$t,used_capability:Z,response_time_ms:re,error:"aborted"};throw console.error("Stream processing error:",de),de}finally{$e.releaseLock()}return{text:Ve,source_links:Je,related_items:Nt,followup_suggestions:$t,used_capability:Z,response_time_ms:re}})()}catch(Me){return W!=null&&W.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",Me),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:Me instanceof Error?Me.message:"request_failed"})}},[le,me,nt,$,Xe,T]),Cn=a.useCallback(()=>{const r=St.current;if(!r||r.signal.aborted)return;r.abort(),ot(!1),Ye.current=null,dt.current=!1;const b=Qe.current;b&&We(y=>y.map(_=>_.id===b&&!_.content.trim()?{..._,content:"Generation stopped."}:_))},[]),Vt=a.useCallback(async r=>{var je,Me,$e,zt,Ve,Je,Nt,$t;if(!r.trim()||ge)return;const b=typeof performance<"u"?performance.now():Date.now(),y=r.trim(),_=Date.now().toString(),R=new AbortController,W=Ye.current,he=(W==null?void 0:W.recommendation)||null,ze=Te.filter(Z=>(Z.role==="user"||Z.role==="assistant")&&Z.content.trim()).slice(-6).map(Z=>({role:Z.role,content:Z.content.trim().slice(0,1200)}));St.current=R,Qe.current=null,kt.current=_,ct.current=!0,Et.current=!0,Ye.current=null,it(Z=>Z.some(re=>re.is_sponsored)?Z.filter(re=>!re.is_sponsored):Z),jt(null);const ve={id:_,role:"user",content:y,timestamp:new Date};if(De("query_submitted",{message_id:_,query:y}),We(Z=>[...Z,ve]),Pe(""),ot(!0),q==="default"&&Ce){try{const Z=(Date.now()+1).toString(),re={id:Z,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:null};dt.current&&(Ft(gt=>new Set([...gt,Z])),dt.current=!1),We(gt=>[...gt,re]),Qe.current=Z;const He=await Ce(y,{sponsoredSuggestion:W});if(R.signal.aborted){Ye.current=null;return}const de=He.recommendation||he||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:r,hasResponseRecommendation:!!He.recommendation,hasSponsoredSuggestionRecommendation:!!he,finalRecommendationId:de==null?void 0:de.recommendation_id}),We(gt=>gt.map(Ze=>Ze.id===Z?{...Ze,content:He.answer,sourceLinks:He.source_links,relatedItems:He.related_items,initialRecommendation:de,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-b}:Ze)),An(y,He.answer,He.source_links,He.related_items,He.recommendation||null,He.followup_suggestions),De("answer_completed",{message_id:Z,query:y,recommendation_id:de==null?void 0:de.recommendation_id,brand_name:(Me=(je=de==null?void 0:de.recommendation)==null?void 0:je.creative)==null?void 0:Me.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"completed",metadata:{variant:q,source:"query_handler"}}),Ye.current=null}catch(Z){console.error("Error sending message:",Z);const re=Z instanceof Error?Z.message:"Unknown error occurred";jt(re);const He={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};We(de=>[...de,He]),De("answer_failed",{query:y,status:re,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,metadata:{variant:q,source:"query_handler"}}),Ye.current=null}finally{St.current===R&&(St.current=null,Qe.current=null,ot(!1))}return}if(!le){setTimeout(()=>{if(R.signal.aborted){St.current===R&&(St.current=null,Qe.current=null);return}const Z={id:(Date.now()+1).toString(),role:"assistant",content:"I'm a demo assistant. The SDK is not properly configured, but I can still help! Try clicking on the suggested questions above, or check your AdMesh API key configuration.",timestamp:new Date,recommendations:[],userQuery:r};We(re=>[...re,Z]),St.current===R&&(St.current=null,Qe.current=null,ot(!1))},1e3);return}try{const Z=(Date.now()+1).toString(),re=he,He={id:Z,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:re};dt.current&&(Ft(Ze=>new Set([...Ze,Z])),dt.current=!1),We(Ze=>[...Ze,He]),Qe.current=Z;const de=await Zn(y,_,Ze=>{We(rt=>rt.map(Kt=>Kt.id===Z?{...Kt,content:Kt.content+Ze}:Kt))},()=>{ot(!0),we(0)},re,R.signal,ze);if(R.signal.aborted){de.text.trim()||We(Ze=>Ze.map(rt=>rt.id===Z&&!rt.content.trim()?{...rt,content:"Generation stopped."}:rt)),De("answer_failed",{message_id:Z,query:y,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(zt=($e=re==null?void 0:re.recommendation)==null?void 0:$e.creative)==null?void 0:zt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"aborted",metadata:{variant:q,source:"api_chat_assistant"}}),Ye.current=null;return}const gt=typeof de.response_time_ms=="number"?de.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-b;We(Ze=>Ze.map(rt=>rt.id===Z?{...rt,content:de.text,sourceLinks:de.source_links,relatedItems:de.related_items,initialRecommendation:rt.initialRecommendation||re,responseTimeMs:gt}:rt)),An(y,de.text,de.source_links,de.related_items,null,de.followup_suggestions),de.error?De("answer_failed",{message_id:Z,query:y,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(Je=(Ve=re==null?void 0:re.recommendation)==null?void 0:Ve.creative)==null?void 0:Je.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:de.error,metadata:{variant:q,source:"api_chat_assistant"}}):De("answer_completed",{message_id:Z,query:y,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:($t=(Nt=re==null?void 0:re.recommendation)==null?void 0:Nt.creative)==null?void 0:$t.brand_name,used_capability:de.used_capability,latency_ms:gt,status:"completed",metadata:{variant:q,source:"api_chat_assistant",response_time_ms:gt}}),Ye.current=null}catch(Z){console.error("Error sending message:",Z);const re=Z instanceof Error?Z.message:"Unknown error occurred";jt(re);const He={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};We(de=>[...de,He]),De("answer_failed",{query:y,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:re,metadata:{variant:q,source:"api_chat_assistant"}}),Ye.current=null}finally{St.current===R&&(St.current=null,Qe.current=null,ot(!1))}},[ge,Zn,Ce,An,le,De,q]),Bt=qt,gn=a.useMemo(()=>Bt.some(r=>r==null?void 0:r.is_sponsored),[Bt]),xn=a.useMemo(()=>Bt.filter(r=>!(r&&typeof r.id=="string")?!1:ce?gn:!0),[gn,ce,Bt]),qe=a.useMemo(()=>Wn(xn),[xn]),on=a.useCallback(async r=>{var y,_,R,W,he,ze,ve;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:r.text,is_sponsored:r.is_sponsored,hasRecommendation:!!r.recommendation,recommendationId:((y=r.recommendation)==null?void 0:y.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((R=(_=r.recommendation)==null?void 0:_.tracking)!=null&&R.followup_engagement_url),sessionId:me}),dt.current=r.is_sponsored||!1,Ye.current=r.is_sponsored?r:null;const b=qe.findIndex(je=>je.id===r.id);De("suggestion_clicked",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b>=0?b:void 0,is_sponsored:r.is_sponsored,recommendation_id:(W=r.recommendation)==null?void 0:W.recommendation_id,brand_name:(ve=(ze=(he=r.recommendation)==null?void 0:he.recommendation)==null?void 0:ze.creative)==null?void 0:ve.brand_name,query:r.text}),Vt(r.text),r.is_sponsored&&r.recommendation&&le?setTimeout(async()=>{var je;try{const Me=(je=r.recommendation.tracking)==null?void 0:je.followup_engagement_url,$e=r.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:Me,recommendationId:$e,sessionId:me}),Me&&$e&&me?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await le.fireFollowupEngagement(Me,$e,me),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!Me,hasRecommendationId:!!$e,hasSessionId:!!me})}catch(Me){console.error("[AdMeshIntentAssistant] โ Error firing sponsored suggestion engagement:",Me)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[Vt,qe,le,me,De]),bn=zs[G],er=Ps[A];a.useEffect(()=>{if(V.current.forEach(r=>r()),V.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return qe.forEach((r,b)=>{const y=Qt.current.get(r.id);if(!y)return;const _=`${me||"anonymous"}:${r.id}:${r.is_sponsored?"s":"o"}`;if(kn.current.has(_))return;let R=null,W=null;const he=()=>{R&&(clearTimeout(R),R=null),W==null||W.disconnect(),W=null},ze=()=>{var ve,je,Me,$e,zt;if(kn.current.has(_)){he();return}if(kn.current.add(_),he(),De("suggestion_exposure",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b,is_sponsored:r.is_sponsored,recommendation_id:(ve=r.recommendation)==null?void 0:ve.recommendation_id,brand_name:($e=(Me=(je=r.recommendation)==null?void 0:je.recommendation)==null?void 0:Me.creative)==null?void 0:$e.brand_name}),le&&me&&r.is_sponsored&&r.recommendation){const Ve=(zt=r.recommendation.tracking)==null?void 0:zt.followup_exposure_url,Je=r.recommendation.recommendation_id;Ve&&Je?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Ve,recommendationId:Je,suggestionText:r.text,sessionId:me}),le.fireFollowupExposure(Ve,Je,me)):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Ve,hasRecommendationId:!!Je,suggestionText:r.text})}};W=new IntersectionObserver(ve=>{const je=ve[0];if(je){if(je.intersectionRatio>=.5){R||(R=setTimeout(ze,1e3));return}R&&(clearTimeout(R),R=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),W.observe(y),V.current.push(he)}),()=>{V.current.forEach(r=>r()),V.current=[]}},[qe,le,me,De,Lt]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:Bt.length,safeSuggestions:xn.length,isAnalyzingIntent:J,hasIntentError:!!ee,onlyShowWhenSponsored:ce,hasSponsoredSuggestions:gn,sponsoredCount:Bt.filter(r=>r==null?void 0:r.is_sponsored).length,nonSponsoredCount:Bt.filter(r=>r&&!(r!=null&&r.is_sponsored)).length,modalShouldAppear:ce?gn:!0,suggestions:Bt.map(r=>{var b,y,_;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((_=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&_.followup_engagement_url)}}),renderedSuggestions:qe.map(r=>{var b,y,_;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((_=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&_.followup_engagement_url)}})});const _e={base:`${16*I}px`,sm:`${14*I}px`,xs:`${12*I}px`},Mn=tt||"AI-generated responses may contain errors. Please verify important information independently.",ro=["Searching trusted sources...","Reviewing publisher coverage...","Checking relevant context...","Comparing supporting signals...","Identifying the strongest examples...","Organizing the most useful details...","Shaping the response for clarity...","Preparing the clearest answer...","Finishing the response..."],sn=r=>{const b=(r==null?void 0:r.accentColor)||At,y=(r==null?void 0:r.metaColor)||or,_=(r==null?void 0:r.includeSteps)??q==="default",R=`${at}s`,W=_?`${ro[Y]} (${R})`:`Generating answer... ${R}`;return n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:r!=null&&r.compact?"8px":"10px",color:y,fontSize:r!=null&&r.compact?_e.xs:_e.sm},children:[n.jsx("span",{style:{width:r!=null&&r.compact?8:9,height:r!=null&&r.compact?8:9,borderRadius:999,background:b,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${Ne(Oe,.28)}`,flexShrink:0}}),n.jsx("span",{children:W})]})},tr=a.useCallback((r,b)=>{if(_t[r.id])return;const y=b?"helpful":"not_helpful";Ot(_=>({..._,[r.id]:y})),De("answer_feedback",{message_id:r.id,query:r.userQuery,status:y,latency_ms:r.responseTimeMs,metadata:{helpful:b}})},[_t,De]);function jn(r,b){if(r.role!=="assistant"||!r.content.trim()||ge&&r.id===Qe.current)return null;const y=(b==null?void 0:b.accentColor)||At,_=(b==null?void 0:b.metaColor)||or,R=_t[r.id],W=typeof r.responseTimeMs=="number";return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${pt}`,flexWrap:"wrap"},children:[n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto",flexWrap:"wrap"},children:[n.jsx("span",{style:{fontSize:_e.xs,color:_,whiteSpace:"nowrap"},children:R?"Thanks for your feedback":"Is this helpful?"}),R?n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",background:Ne(y,.12),color:y,flexShrink:0},children:R==="helpful"?n.jsx(xr,{size:14}):n.jsx(gr,{size:14})}):n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[n.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>tr(r,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${pt}`,background:mt,color:_,cursor:"pointer"},children:n.jsx(xr,{size:14})}),n.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>tr(r,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${pt}`,background:mt,color:_,cursor:"pointer"},children:n.jsx(gr,{size:14})})]})]}),W?n.jsxs("span",{style:{fontSize:_e.xs,color:_,whiteSpace:"nowrap",flex:"0 1 auto",marginLeft:"auto"},children:["Answer Completed in ",js(r.responseTimeMs)]}):null]})}const an=a.useCallback(()=>{const r=Tt.current;if(!r)return;const b=Math.max(0,r.scrollWidth-r.clientWidth);mn(r.scrollLeft>4),Xr(r.scrollLeft<b-4)},[]);a.useEffect(()=>(an(),window.addEventListener("resize",an),()=>window.removeEventListener("resize",an)),[an,qe.length]);const nr=a.useCallback(r=>{const b=Tt.current;b&&b.scrollBy({left:r==="left"?-Math.max(160,Math.floor(b.clientWidth*.75)):Math.max(160,Math.floor(b.clientWidth*.75)),behavior:"smooth"})},[]),Ne=(r,b)=>{if(!r||!r.startsWith("#"))return`rgba(15, 23, 42, ${b})`;const y=r.slice(1),_=y.length===3?y.split("").map(ze=>`${ze}${ze}`).join(""):y;if(_.length!==6)return r;const R=parseInt(_.slice(0,2),16),W=parseInt(_.slice(2,4),16),he=parseInt(_.slice(4,6),16);return`rgba(${R}, ${W}, ${he}, ${b})`},Oe=E.primaryColor||"#3F037F",mt=E.surfaceColor||"#ffffff",oo=E.backgroundColor||"#eef2ff",pt=E.borderColor||"#e5e7eb",Ue=E.textColor||"#111827",Pt=E.textSecondaryColor||"#6b7280";Ne(Oe,.12);const rr=Ne(Oe,.24);Ne(Oe,.38);const so=mt,At=Oe,yn=E.primaryTextColor||"#ffffff",or=Pt,sr=be||"Publisher Assistant",Zt=J&&qe.length===0&&Te.length===0,En=mt,Rn=mt,Ut=pt,ir=pt,ar="0 16px 64px rgba(15, 23, 42, 0.14)",In=Pt,lr=Pt,io=At,dr=oo,ao="none",lo="rgba(15, 23, 42, 0.18)";function cr(r){return Xe?n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:r==="default"?"10px 12px":"8px 10px",borderRadius:r==="default"?"14px":"12px",border:`1px solid ${rr}`,background:Ne("#ffffff",.9),marginBottom:"4px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{color:At,fontSize:_e.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),n.jsxs("div",{style:{color:Ue,fontSize:_e.sm,fontWeight:600,lineHeight:1.3},children:[Xe.brand_name," agent is active"]})]}),n.jsx("button",{type:"button",onClick:()=>{ie("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${rr}`,borderRadius:999,background:Ne("#ffffff",.92),color:At,padding:"7px 12px",fontSize:_e.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function ur(r,b=te){const y=pn&&!b,_=b||y,R=b?"9.5px":y?"10px":"11px",W=b||y?"9px":"11px";return n.jsxs("div",{style:{display:"flex",flexDirection:_?"column":"row",alignItems:_||r==="default"?"center":"flex-start",justifyContent:_?"center":"space-between",gap:_?y?"4px":"2px":"12px",flexWrap:"wrap",paddingTop:b||r==="default"?"2px":"8px",borderTop:r==="default"?`1px solid ${Ut}`:"none",marginTop:b?"0":r==="default"?"4px":0,flexShrink:0,textAlign:_?"center":void 0,width:_?"100%":void 0},children:[n.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:_?"center":void 0,gap:b?"4px":"8px",color:lr,fontSize:R,fontWeight:700,letterSpacing:"0.01em"},children:n.jsxs("span",{children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]})}),n.jsx("div",{style:{color:lr,fontSize:W,lineHeight:_?1.3:1.45,maxWidth:_?"100%":r==="default"?"68%":"100%",textAlign:_?"center":r==="default"?"right":"left"},children:Mn})]})}function Tn(r){const b=r==="publisher"?[180,220,196]:["100%","82%","68%"];return r==="publisher"?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:Ne(Ue,.06),flexShrink:0}}),n.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:b.map((y,_)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:40,borderRadius:"6px",background:Ne(Ue,.06),backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:"none",flexShrink:0}},`suggestion-skeleton-${_}`))}),n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:Ne(Ue,.06),flexShrink:0}})]}):n.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:r==="publisher"?"10px":"12px"},children:b.map((y,_)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:r==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${Ne(Oe,.08)} 0%, ${Ne(Oe,.18)} 50%, ${Ne(Oe,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:r==="publisher"?`0 8px 22px ${Ne(Oe,.08)}`:"none"}},`suggestion-skeleton-${_}`))})}function co(r=te){if(ge)return null;if(Zt)return Tn("publisher");if(!qe.length)return null;const b=r&&Qn,y=qe.slice(0,X);return U==="stacked"?n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:r?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:r?"240px":void 0,paddingRight:r?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:y.map(_=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":_.is_sponsored?"true":void 0,ref:rn(_.id),onClick:()=>{q==="default"&&(st(!0),v==="floating"&&Wt(!0)),on(_)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:"8px",border:`1px solid ${_.is_sponsored?Oe:pt}`,background:_.is_sponsored?Oe:mt,color:_.is_sponsored?yn:Ue,padding:r?"8px 10px":"10px 14px",fontSize:r?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{style:{minWidth:0},children:_.text}),B&&_.is_sponsored&&n.jsx("span",{style:{flexShrink:0,borderRadius:"6px",background:Ne("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},_.id))}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:b?"4px":ut?"5px":r?"6px":"10px",flexShrink:0},children:[!b&&n.jsx("button",{type:"button",onClick:()=>nr("left"),disabled:!ft,"aria-label":"Scroll suggestions left",style:{width:ut?20:r?24:28,height:ut?20:r?24:28,borderRadius:"6px",border:`1px solid ${pt}`,background:mt,color:"#6b7280",fontSize:ut?"13px":void 0,lineHeight:1,cursor:ft?"pointer":"default",opacity:ft?1:.55},children:"โน"}),n.jsx("div",{ref:Tt,onScroll:an,style:{display:"flex",gap:b?"4px":ut?"5px":r?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:y.map(_=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":_.is_sponsored?"true":void 0,ref:rn(_.id),onClick:()=>{q==="default"&&(st(!0),v==="floating"&&Wt(!0)),on(_)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:b?"4px":ut?"5px":"8px",whiteSpace:"nowrap",borderRadius:"6px",border:`1px solid ${_.is_sponsored?Oe:pt}`,background:_.is_sponsored?Oe:mt,color:_.is_sponsored?yn:Ue,padding:b?"4px 8px":ut?"5px 8px":r?"7px 10px":"8px 14px",fontSize:b?"10px":ut?"11px":r?"12px":"13px",fontWeight:500,lineHeight:b?1:ut?1.1:void 0,boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{children:_.text}),B&&_.is_sponsored&&n.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},_.id))}),!b&&n.jsx("button",{type:"button",onClick:()=>nr("right"),disabled:!nn,"aria-label":"Scroll suggestions right",style:{width:ut?20:r?24:28,height:ut?20:r?24:28,borderRadius:"6px",border:`1px solid ${pt}`,background:mt,color:"#6b7280",fontSize:ut?"13px":void 0,lineHeight:1,cursor:nn?"pointer":"default",opacity:nn?1:.55},children:"โบ"})]})}function uo(r){var b,y;return(b=r.relatedItems)!=null&&b.length||!((y=r.sourceLinks)!=null&&y.length)?null:n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"16px"},children:[n.jsx("div",{style:{width:"100%",fontSize:"11px",fontWeight:600,color:Pt},children:"Sources"}),r.sourceLinks.map(_=>n.jsxs("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{De("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:_.title,source_url:_.url}})},style:{color:At,fontSize:_e.xs,textDecoration:"none",borderBottom:`1px solid ${Ne(Oe,.18)}`},children:[_.title||_.url," ",n.jsx(ko,{size:12,style:{display:"inline",verticalAlign:"middle"},"aria-hidden":"true"})]},`${r.id}-${_.url}`))]})}function mo(r,b=te){var y;return(y=r.relatedItems)!=null&&y.length?n.jsxs("div",{style:{marginTop:"14px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,color:Pt,marginBottom:"8px"},children:"Related reading"}),n.jsx("div",{style:{display:"flex",gap:b?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:r.relatedItems.slice(0,4).map(_=>n.jsxs("a",{className:"admesh-publisher-source",href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{De("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:_.title,source_url:_.url,source_publisher:_.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:b?"6px":"10px",padding:b?"10px":"14px",borderRadius:"8px",textDecoration:"none",color:Ue,border:`1px solid ${pt}`,background:mt,boxShadow:"none",flex:b?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:b?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[n.jsx("div",{style:{fontSize:b?"12px":"14px",fontWeight:650,lineHeight:1.35,color:Ue,overflowWrap:"anywhere"},children:_.title||_.url}),_.publisher&&n.jsx("div",{style:{fontSize:b?"11px":"12px",color:Pt,lineHeight:1.4,overflowWrap:"anywhere"},children:_.publisher})]},`${r.id}-${_.url}`))})]}):null}function po(r=te){const b=r?"13px":"15px";return n.jsxs("div",{ref:Fe,style:{flex:r?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"thin",padding:r?"0 2px 4px":O?"16px 16px 8px":0},children:[Te.map(y=>{const _=y.role==="user"&&y.id===kt.current;return n.jsx("div",{ref:_?ae:void 0,style:{marginBottom:r?"16px":"28px",textAlign:y.role==="user"?"right":"left"},children:(()=>{const W=!!y.content.trim()||!ge;return n.jsx(n.Fragment,{children:n.jsxs("div",{style:{display:y.role==="assistant"?"block":"inline-block",width:y.role==="assistant"?"100%":void 0,maxWidth:y.role==="assistant"?"100%":"76%",padding:y.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:y.role==="assistant"?0:"8px",background:y.role==="user"?Ne(Ue,.05):"transparent",color:Ue,boxShadow:"none",border:"none",fontSize:y.role==="assistant"?b:r?"12px":"13px",lineHeight:y.role==="assistant"?1.62:1.4},children:[y.role==="assistant"?y.content.trim()?n.jsx(Fn,{content:y.content,theme:{...E,textColor:Ue},fontSize:b}):ge&&y.id===Qe.current?sn({includeSteps:!0}):null:n.jsx("p",{style:{margin:0,color:Ue},children:y.content}),y.role==="assistant"&&uo(y),y.role==="assistant"&&mo(y,r),y.role==="assistant"&&jn(y),y.role==="assistant"&&W&&wt.has(y.id)&&y.initialRecommendation&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(dn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation,onFollowupDetected:fn,onRecommendationsShown:(he,ze)=>{hn(he,ze,y.userQuery)},onError:he=>{console.error("[AdMeshIntentAssistant] Recommendation error:",he)}})}),y.role==="assistant"&&W&&!wt.has(y.id)&&(y.initialRecommendation||Jr)&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(dn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation||void 0,onFollowupDetected:fn,onRecommendationsShown:(he,ze)=>{hn(he,ze,y.userQuery)},onError:he=>{console.error("[AdMeshIntentAssistant] Recommendation error:",he)}})})]})})})()},y.id)}),Mt&&n.jsx("div",{role:"alert",style:{color:Ue,fontSize:_e.sm,border:`1px solid ${pt}`,borderLeft:"3px solid #b45309",borderRadius:"6px",padding:"12px"},children:"Unable to complete the answer. Please try again."}),n.jsx("div",{ref:It})]})}if(q==="default"){let r=function(_){const R=Er(pn);return Un.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:y}),n.jsx("div",{style:R.shell,children:_})]}),document.body)},b=function(_=!1){const R=Ge(_),W=_||R&&O,he=R&&!W&&Qn,ze=W&&!(te&&m==="expand"&&!_&&Xt),ve=W?Er(pn):null,je=!!(ve&&pn&&!R),Me=R?Dt:ve?ve.panelWidth:v==="inline"?"100%":"min(420px, calc(100vw - 32px))",$e=R?Jt:ve?ve.panelHeight:"auto",zt=R?Dt:(ve==null?void 0:ve.panelMaxWidth)??"100%",Ve=R?Jt:ve==null?void 0:ve.panelMaxHeight,Je=u&&!he&&(W||H==="always"&&(!R||k));return n.jsxs("div",{className:"admesh-publisher-panel","data-compact":R?"true":"false",style:{"--publisher-accent":At,color:Ue,width:Me,maxWidth:zt,height:$e,maxHeight:Ve,boxSizing:"border-box",display:"flex",flexDirection:"column",background:W?En:so,borderRadius:!R&&ve?ve.panelBorderRadius:"12px",padding:W?0:R?"6px":0,boxShadow:je?"none":W?ar:"none",border:je||!W&&H==="input"?"none":`1px solid ${ir}`,overflow:"hidden",minHeight:R?0:void 0},children:[n.jsx("style",{children:Kr}),Je&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:R?"8px 10px":"14px 20px",background:Rn,color:Ue,borderBottom:`1px solid ${Ut}`,flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px",minWidth:0},children:[n.jsx("div",{style:{width:R?26:32,height:R?26:32,flexShrink:0,borderRadius:"6px",background:Ne(Ue,.04),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:At,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:mt,padding:4}}):n.jsx(Bn,{size:R?14:17,strokeWidth:1.5,"aria-hidden":"true"})}),(w||g)&&n.jsxs("div",{style:{minWidth:0,overflowWrap:"anywhere"},children:[w&&n.jsx("div",{style:{fontSize:R?"13px":"14px",fontWeight:600,lineHeight:1.1,letterSpacing:0},children:i}),g&&n.jsx("div",{style:{fontSize:R?"10px":"12px",color:In,marginTop:"2px"},children:sr})]})]}),W&&(!R||_)&&n.jsx("button",{type:"button",onClick:()=>st(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"8px",border:`1px solid ${Ut}`,background:mt,color:In,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(hr,{size:16,strokeWidth:1.5,"aria-hidden":"true"})})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:he?"2px":R?"6px":"16px",minHeight:0,flex:R||W?"1 1 0":void 0,overflow:R||W?"hidden":void 0,overscrollBehavior:"contain",padding:W||H==="always"?R?"8px":"20px":R?"4px":"8px",justifyContent:W?void 0:"center",background:En},children:[cr("default"),ze&&po(R),H==="always"&&n.jsxs(n.Fragment,{children:[R&&!W&&!he&&n.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),R&&!W&&P&&j&&Te.length===0&&n.jsx("div",{style:{fontSize:15,fontWeight:600,textAlign:"center"},children:z}),!R&&!W&&qe.length>0&&n.jsx("div",{style:{fontSize:11,color:Pt},children:"Explore this article"}),co(R)]}),(H==="input"||!R||W||p)&&n.jsx(_s,{value:ye,onChange:Pe,open:H==="input"&&Lt&&(W||!O),onOpenChange:H==="input"?ht:Cs,suggestions:qe.slice(0,X),registerSuggestion:rn,loading:ge,analyzing:Zt,compact:R,expanded:W,showLogo:H==="input",suggestionPlacement:ne,logoUrl:d,title:i,placeholder:M,colors:{accent:At,accentText:yn,surface:dr,text:Ue,muted:Pt,border:pt},onStop:Cn,onSend:()=>{Ye.current=null,dt.current=!1,st(!0),v==="floating"&&Wt(!0),Vt(ye)},onSuggestion:Nt=>{st(!0),v==="floating"&&Wt(!0),on(Nt)}}),W&&ur("default",R),!W&&H==="always"&&n.jsxs("div",{style:{fontSize:R?9:11,color:Pt,textAlign:R?"center":"left"},children:["Powered by ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit"},children:"AdMesh"}),x&&n.jsx("div",{children:Mn})]})]})]})};const y={position:"fixed",inset:0,background:lo,backdropFilter:"blur(2px)",zIndex:2147483e3};return v==="inline"?te?n.jsxs("div",{ref:Rt,className:"admesh-component","data-admesh-theme":fe,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-behavior":m,"data-admesh-ad-slot-expanded":Sn?"true":"false",style:{width:Dt,height:Jt,maxWidth:Dt,maxHeight:Jt,position:"relative",overflow:"hidden"},children:[b(!1),Xt&&typeof document<"u"&&r(b(!0))]}):n.jsxs("div",{className:"admesh-component","data-admesh-theme":fe,style:{width:"100%",position:"relative"},children:[b(!1),O&&typeof document<"u"&&r(b(!0))]}):Ae?n.jsxs("div",{className:"admesh-component","data-admesh-theme":fe,children:[!O&&n.jsx("div",{style:{position:"fixed",...bn,zIndex:2147483001},children:b(!1)}),O&&typeof document<"u"&&r(b(!0))]}):n.jsx("div",{className:"admesh-component","data-admesh-theme":fe,children:n.jsxs("button",{type:"button",onClick:Jn,style:{position:"fixed",...bn,zIndex:2147483e3,border:"none",borderRadius:"6px",background:E.primaryColor,color:yn,display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",fontWeight:600,padding:"12px 16px",boxShadow:"0 4px 16px rgba(15, 23, 42, 0.12)",cursor:"pointer"},children:[n.jsx(Bn,{size:16,strokeWidth:1.5,"aria-hidden":"true"}),s]})})}return qe.length===0&&!Zt?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):v==="inline"?n.jsx("div",{className:"admesh-component","data-admesh-theme":fe,children:n.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:ln(f)??"100%",backgroundColor:"#eef2ff",fontSize:_e.base,...o},children:n.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[Zt?Tn("legacy"):qe.length>0&&n.jsx("div",{className:"flex flex-col gap-3",children:qe.slice(0,X).map((r,b)=>n.jsxs("button",{ref:rn(r.id),onClick:()=>on(r),className:"rounded-full px-5 py-4 text-left shadow-sm transition-transform duration-200 hover:scale-[1.01] active:scale-[0.99]",style:{width:b===0?"100%":b===1?"82%":"68%",backgroundColor:E.surfaceColor||"#ffffff",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:_e.sm},children:[n.jsx("span",{className:"leading-tight",children:r.text}),B&&r.is_sponsored&&n.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},r.id))}),Te.length>0&&n.jsxs("div",{ref:Fe,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:E.textColor,overscrollBehavior:"contain",WebkitOverflowScrolling:"touch"},children:[Te.map(r=>{const b=r.role==="user"&&r.id===kt.current;return n.jsx("div",{ref:b?ae:void 0,className:r.role==="user"?"text-right":"text-left",children:n.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:r.role==="user"?E.primaryColor:"#ffffff",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,fontSize:_e.sm},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx(Fn,{content:r.content,theme:E,fontSize:_e.sm}),jn(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):ge&&r.id===Qe.current?sn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:r.content})})},r.id)}),ge&&!Te.some(r=>r.role==="assistant"&&r.id===Qe.current&&!r.content.trim())&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:sn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})}),Mt&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:"Connection issue. Please try again."}),n.jsx("div",{ref:It})]}),n.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"text",value:ye,onChange:r=>Pe(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(ge){r.preventDefault();return}Vt(ye)}},placeholder:M,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textColor,fontSize:_e.sm}}),n.jsx("button",{onClick:()=>{if(ge){Cn();return}Vt(ye)},disabled:!ge&&!ye.trim(),className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50",style:{backgroundColor:ge?"#dc2626":E.primaryColor,color:"#ffffff"},children:ge?n.jsx(Pn,{size:18}):n.jsx(fr,{size:18})})]})}),n.jsxs("div",{className:"space-y-2 text-center",children:[n.jsxs("p",{style:{color:E.textSecondaryColor,fontSize:_e.xs,fontWeight:600},children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),n.jsx("p",{style:{color:E.textSecondaryColor,fontSize:_e.xs,lineHeight:1.5},children:Mn})]})]})})}):Ae?n.jsx("div",{className:"admesh-component","data-admesh-theme":fe,children:n.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...O?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...bn,width:ln(f)??er.width,height:ln(h)??er.height},backgroundColor:O?En:E.backgroundColor,zIndex:9999,fontSize:_e.base,borderRadius:O?"20px":"16px",border:O?`1px solid ${ir}`:"1px solid transparent",boxShadow:O?ar:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[u&&n.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between p-4 border-b",style:{position:"sticky",top:0,zIndex:10,borderColor:O?Ut:"transparent",background:O?Rn:E.backgroundColor,padding:O?"18px 20px":"16px"},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{style:{width:O?40:32,height:O?40:32,borderRadius:O?"14px":"10px",background:Ne(Oe,.08),color:At,display:"flex",alignItems:"center",justifyContent:"center",fontSize:O?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(w||g&&O)&&n.jsxs("div",{children:[w&&n.jsx("div",{className:"font-medium",style:{color:E.textColor,fontSize:O?"20px":_e.base,fontWeight:700,letterSpacing:O?"-0.02em":0},children:i}),g&&O&&n.jsx("div",{style:{color:In,fontSize:"12px",marginTop:"2px"},children:sr})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[!te&&n.jsx("button",{onClick:no,className:"transition-colors",title:O?"Minimize":"Expand",style:{width:O?36:28,height:O?36:28,borderRadius:O?"12px":"10px",border:`1px solid ${O?Ut:"transparent"}`,background:O?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:O?n.jsx(hr,{size:16,style:{color:E.textSecondaryColor}}):n.jsx(Eo,{size:16,style:{color:E.textSecondaryColor}})}),n.jsx("button",{onClick:to,className:"transition-colors",style:{width:O?36:28,height:O?36:28,borderRadius:O?"12px":"10px",border:`1px solid ${O?Ut:"transparent"}`,background:O?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(Pn,{size:16,style:{color:E.textSecondaryColor}})})]})]}),n.jsxs("div",{ref:Fe,className:"flex-1 min-h-0 overflow-y-auto p-4",style:{flex:"1 1 0%",minHeight:0,overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",padding:O?"20px":"16px"},children:[cr("legacy"),P&&Te.length===0&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",children:n.jsx("p",{style:{color:E.textColor,margin:0,fontSize:_e.sm},children:z})})}),Te.map(r=>{const b=r.role==="user"&&r.id===kt.current;return n.jsxs("div",{ref:b?ae:void 0,className:"mb-3",children:[n.jsx("div",{className:r.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:r.role==="user"?io:"transparent",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,border:"none",borderRadius:r.role==="user"?O?"14px":"12px":0,padding:r.role==="user"?O?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{fontSize:`calc(${_e.sm} * 1.3)`,lineHeight:1.65},children:n.jsx(Fn,{content:r.content,theme:E,fontSize:`calc(${_e.sm} * 1.3)`})}),jn(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):ge&&r.id===Qe.current?sn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,fontSize:_e.sm,lineHeight:"1.4"},children:r.content})}),r.role==="assistant"&&!wt.has(r.id)&&n.jsx(dn,{messageId:r.id,query:r.userQuery,onFollowupDetected:fn,onRecommendationsShown:(y,_)=>{hn(y,_,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}}),r.role==="assistant"&&wt.has(r.id)&&r.initialRecommendation&&!ge&&n.jsxs("div",{className:"mb-4",children:[n.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),n.jsx(dn,{messageId:r.id,query:r.userQuery,initialRecommendation:r.initialRecommendation,onFollowupDetected:fn,onRecommendationsShown:(y,_)=>{hn(y,_,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}})]})]},r.id)}),ge&&!Te.some(r=>r.role==="assistant"&&r.id===Qe.current&&!r.content.trim())&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:sn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})})}),Mt&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textSecondaryColor},children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{style:{fontSize:_e.xs},children:"โ ๏ธ"}),n.jsx("span",{style:{fontSize:_e.sm},children:"Connection issue. Please try again."})]})})}),n.jsx("div",{ref:It})]}),Te.length===0&&Zt&&n.jsx("div",{className:"px-4 pb-2",children:Tn("legacy")}),qe.length>0&&Te.length===0&&!Zt&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:qe.slice(0,X).map(r=>n.jsxs("button",{ref:rn(r.id),onClick:()=>on(r),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:E.surfaceColor||"#f8fafc",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:_e.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[n.jsx("span",{className:"leading-tight",children:r.text}),B&&r.is_sponsored&&n.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b"},children:"Ad"})]},r.id))})}),ee&&!J&&xn.length===0&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:n.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:E.surfaceColor,borderColor:E.borderColor,color:E.textSecondaryColor},children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("span",{style:{fontSize:_e.sm},children:"Intent analysis failed"}),n.jsx("button",{onClick:oe,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:E.primaryColor,color:"#ffffff"},children:"Retry"})]}),n.jsx("span",{style:{fontSize:_e.xs},children:ee})]})})}),n.jsxs("div",{className:"p-3 border-t",style:{borderColor:O?Ut:"transparent",padding:O?"18px 20px":void 0,background:O?Rn:void 0},children:[n.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${Ut}`,borderRadius:O?"16px":"12px",background:dr,boxShadow:O?ao:"none",padding:O?"8px 8px 8px 14px":void 0},children:[n.jsx("input",{type:"text",value:ye,onChange:r=>Pe(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(ge){r.preventDefault();return}Vt(ye)}},placeholder:M,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textColor,fontSize:O?"15px":_e.sm,"--tw-ring-color":E.primaryColor}}),n.jsx("button",{onClick:()=>{if(ge){Cn();return}Vt(ye)},disabled:!ge&&!ye.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:ge?"#dc2626":E.primaryColor,color:"#ffffff",borderRadius:O?"12px":"10px",width:O?"46px":void 0,height:O?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:O?`0 10px 20px ${Ne(Oe,.18)}`:"none"},children:ge?n.jsx(Pn,{size:14}):n.jsx(fr,{size:14})})]}),ur("legacy")]})]})}):n.jsx("div",{className:"admesh-component","data-admesh-theme":fe,children:n.jsx("button",{onClick:Jn,className:"flex items-center gap-2 px-4 py-3 rounded-full shadow-lg transition-all duration-200 hover:scale-105 active:scale-95",style:{position:"fixed",...bn,backgroundColor:E.primaryColor,color:"#ffffff",zIndex:9999,fontSize:_e.base,...o},children:n.jsx("span",{className:"font-medium",children:s})})})},wn="admesh:streamingStart",_n="admesh:streamingComplete";function $s(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(wn,{detail:o});window.dispatchEvent(s),l.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function Ls(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(_n,{detail:s});window.dispatchEvent(i),l.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function Fs(t,e,o){const s=i=>{const d=i;d.detail.messageId===t&&d.detail.sessionId===e&&(l.log("[StreamingEvents] ๐จ Received streamingStart event"),o(d.detail))};return window.addEventListener(wn,s),()=>{window.removeEventListener(wn,s)}}function Qr(t,e,o){l.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const d=i;l.log("[StreamingEvents] ๐จ Received streamingComplete event (checking match)",{receivedMessageId:d.detail.messageId,receivedSessionId:d.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:d.detail.messageId===t,sessionIdMatch:d.detail.sessionId===e}),d.detail.messageId===t&&d.detail.sessionId===e?(l.log("[StreamingEvents] โ
Event matched! Calling callback"),o(d.detail)):l.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(_n,s),()=>{l.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(_n,s)}}const vn=()=>{const t=new Set,e=new Map,o=d=>{const u=e.get(d);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(d))};return{startTracking:({exposureUrl:d,recommendationId:u,linkElement:w,sessionId:g,logPrefix:v="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!d||!w){v&&l.warn(`${v} โ ๏ธ Missing exposure tracking data`);return}const c=`${g||"anonymous"}::${u||d}`;if(t.has(c)||e.has(c))return;const m={observer:void 0,timeoutId:null,viewableStart:null},k=()=>{o(c),t.add(c),fetch(d,{method:"GET",keepalive:!0}).then(()=>{v&&l.log(`${v} โ
Exposure pixel fired`)}).catch(()=>{v&&l.warn(`${v} โ ๏ธ Failed to fire exposure pixel`),t.delete(c)})},j=new IntersectionObserver(p=>{p.forEach(x=>{x.intersectionRatio>=.5?m.viewableStart===null&&(m.viewableStart=performance.now(),m.timeoutId=setTimeout(k,1e3)):(m.viewableStart=null,m.timeoutId&&(clearTimeout(m.timeoutId),m.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});m.observer=j,j.observe(w),e.set(c,m)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},Ws=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:d=[],onLinksFound:u,onNoLinksFound:w,children:g})=>{const[v,c]=a.useState(!1),[m,k]=a.useState(!0),[j,p]=a.useState(!1),x=a.useRef(vn()),f=a.useRef(u),h=a.useRef(w),S=a.useRef(t),I=a.useRef(s),G=a.useRef(o),A=a.useRef(i);a.useEffect(()=>{f.current=u,h.current=w,S.current=t,I.current=s,G.current=o,A.current=i},[u,w,t,s,o,i]),a.useEffect(()=>()=>{x.current.cleanup()},[]);const C=a.useCallback(({exposureUrl:N,recommendationId:F,linkElement:P})=>{x.current.startTracking({exposureUrl:N,recommendationId:F,linkElement:P,sessionId:G.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),L=a.useCallback(()=>{l.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const N=document.getElementById(S.current);if(!N){l.warn("[FinalLinkDetectionCheck] โ Container not found"),c(!0),w();return}const F=new Vn({autoAddLabels:!0,fireExposurePixels:!0}),P=d.length>0?d:[];l.log(`[FinalLinkDetectionCheck] ๐ Using ${P.length} recommendations for link detection`),P.length>0&&process.env.NODE_ENV==="development"&&P.forEach((M,B)=>{var K,X,U,H,ne,ce,q,Ce,ke;l.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${B+1} (DEV):`,{recommendation_id:M==null?void 0:M.recommendation_id,click_url:((K=M==null?void 0:M.tracking)==null?void 0:K.click_url)||((U=(X=M==null?void 0:M.recommendation)==null?void 0:X.creative)==null?void 0:U.landing_page_url),format:(H=M==null?void 0:M.recommendation)==null?void 0:H.format,brand_name:(q=(ce=(ne=M.render)==null?void 0:ne.creative)==null?void 0:ce.advertiser)==null?void 0:q.brand_name,cta_url:(ke=(Ce=M.render)==null?void 0:Ce.creative)==null?void 0:ke.landing_page_url})});const z=F.scanAndProcessLinks(N,P,({exposureUrl:M,recommendationId:B,linkElement:K})=>C({exposureUrl:M,recommendationId:B,linkElement:K}));l.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${z.length} links`),z.length>0?(l.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),p(!0),f.current(z.length)):(l.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${P.length} previous recommendation(s) if available)`),p(!1),h.current()),c(!0)}catch{l.error("[FinalLinkDetectionCheck] โ Error during final check"),c(!0),h.current()}},[C,d]);return a.useEffect(()=>{l.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:d.length});let N=null,F=!1;const P=Qr(e,o,z=>{l.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:z.messageId,sessionId:z.sessionId,timestamp:z.timestamp}),F=!0,N&&(clearTimeout(N),N=null),k(!1),setTimeout(()=>{L()},100)});return N=setTimeout(()=>{F||(l.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),k(!1),setTimeout(()=>{L()},100))},5e3),()=>{l.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),N&&clearTimeout(N),P()}},[e,o]),m?n.jsx(n.Fragment,{}):v?j?(l.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),n.jsx(n.Fragment,{})):(l.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),n.jsx(n.Fragment,{children:g})):n.jsx(n.Fragment,{})},Bs=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:d,className:u,query:w,onFallbackChange:g,onWeaveAttempt:v,onWeaveOutcome:c})=>{var M,B;const{sessionId:m,sdk:k,language:j,location:p,userId:x,model:f,messages:h}=tn(),S=a.useRef(null),I=`weave-ad-container-${t}`,G=a.useRef(vn()),A=a.useRef(!1),C=a.useRef(null),[L,N]=a.useState([]),F=a.useRef([]);a.useEffect(()=>(C.current||(C.current=new Vn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{C.current&&(C.current.stopWatching(),C.current.clearCache())}),[]),a.useEffect(()=>()=>{G.current.cleanup()},[]),a.useEffect(()=>{(async()=>{var X;if(!k||!(w!=null&&w.trim())||!t){l.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{l.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const U=await k.fetchPlatformResponse({query:w.trim(),sessionId:m,messageId:t,language:j,location:p,userId:x,model:f,messages:h}),H=(U==null?void 0:U.status)==="generated"?[U]:[];if(N(H),F.current=H,l.log("[WeaveAdFormatContainer] ๐ฅ Got platform response:",{status:U==null?void 0:U.status,recommendationId:U==null?void 0:U.recommendation_id,hasRecommendation:!!(U!=null&&U.recommendation),format:(X=U==null?void 0:U.recommendation)==null?void 0:X.format}),U!=null&&U.recommendation){const ne=U.recommendation.creative,ce=ne.landing_page_url;l.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:ne.brand_name,headline:ne.headline,description:ne.description,brandUrl:ce})}else l.log("[WeaveAdFormatContainer] โ ๏ธ No recommendation found in platform response")}catch(U){l.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",U),N([])}})()},[k,m,t,w]),a.useEffect(()=>{const K=S.current;if(!K||!C.current)return;const X=C.current,U=({exposureUrl:ce,recommendationId:q,linkElement:Ce})=>{G.current.startTracking({exposureUrl:ce,recommendationId:q,linkElement:Ce,sessionId:m,logPrefix:"[WeaveAdFormatContainer]"})},ne=setTimeout(()=>{l.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),v==null||v(t);const ce=F.current.length>0?F.current:[];l.log(`[WeaveAdFormatContainer] ๐ Using ${ce.length} recommendations for link detection`);try{const q=X.scanAndProcessLinks(K,ce,U);q.length>0&&!A.current?(A.current=!0,l.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${q.length} links detected`),c==null||c(t,!0,`Found ${q.length} links`),s==null||s(q.length),g==null||g(!1)):A.current||l.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(q){const Ce=q instanceof Error?q.message:String(q);l.error(`[WeaveAdFormatContainer] โ Weave injection failed: ${Ce}`),c==null||c(t,!1,Ce),i==null||i(),g==null||g(!0)}},100);return X.watchForNewLinks(K,F.current,U),()=>{clearTimeout(ne),X.stopWatching()}},[e,m,t,s,g,v,c]);const P=(B=(M=L[0])==null?void 0:M.recommendation)==null?void 0:B.format,z=P==="weave";return a.useEffect(()=>{w&&z&&l.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${P}) - skipping fallback recommendations`)},[w,z,P]),n.jsxs(n.Fragment,{children:[n.jsx("div",{ref:S,id:I,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),w&&!z&&n.jsx(Ws,{containerId:I,messageId:t,sessionId:m,sdk:k,query:w,recommendations:L,onLinksFound:K=>{l.log(`[WeaveAdFormatContainer] โ
Links found (${K}) - no fallback needed`),c==null||c(t,!0,`Found ${K} links in final check`),s==null||s(K),g==null||g(!1)},onNoLinksFound:()=>{l.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),l.log(`[WeaveAdFormatContainer] ๐ Passing ${L.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),i==null||i(),g==null||g(!0)},children:n.jsx(Hr,{format:o,messageId:t,query:w,fallback:!0,onError:d,previousRecommendations:L.length>0?L:void 0})})]})},Us=t=>{const{sdk:e,sessionId:o}=tn(),s=a.useRef(!1),i=a.useRef(0),d=a.useRef(!1),u=a.useRef(!1),w=a.useRef(null),g=a.useRef(vn());a.useEffect(()=>()=>{g.current.cleanup()},[]);const v=a.useCallback(({exposureUrl:h,recommendationId:S,linkElement:I})=>{g.current.startTracking({exposureUrl:h,recommendationId:S,linkElement:I,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),c=a.useRef(Date.now()),m=a.useRef(0),k=a.useRef(null),j=a.useRef([]),p=a.useRef(300),x=a.useCallback(async()=>{var h,S,I,G;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const A=document.getElementById(t.llmOutputContainerId);if(!A)return;const C=(h=e.getWeaveProcessor)==null?void 0:h.call(e);if(!C)return;const L=C.scanAndProcessLinks(A,[],({exposureUrl:F,recommendationId:P,linkElement:z})=>v({exposureUrl:F,recommendationId:P,linkElement:z}));i.current=L.length;const N=L.length>0;if(N&&!d.current)d.current=!0,(S=t.onLinksDetected)==null||S.call(t,L.length),u.current=!0;else if(!N&&d.current)d.current=!1,u.current=!1;else if(!N&&!u.current){w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current),m.current=0,c.current=Date.now();const F=Math.max(100,p.current/3);k.current=setInterval(()=>{var B;const z=Date.now()-c.current,M=p.current;z>=M?(m.current++,m.current>=2&&(k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((B=t.onNoLinksDetected)==null||B.call(t),u.current=!0))):m.current=0},F);const P=Math.max(1500,p.current*5);w.current=setTimeout(()=>{var z;k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((z=t.onNoLinksDetected)==null||z.call(t),u.current=!0)},P)}else N&&u.current&&!d.current&&(w.current&&(clearTimeout(w.current),w.current=null),d.current=!0,(I=t.onLinksDetected)==null||I.call(t,L.length),u.current=!0)}catch(A){const C=A instanceof Error?A:new Error(String(A));(G=t.onError)==null||G.call(t,C)}finally{s.current=!1}}},[e,o,t,v]),f=a.useCallback(()=>{const h=j.current;if(h.length<2){p.current=300;return}const S=[];for(let A=1;A<h.length;A++)S.push(h[A]-h[A-1]);const I=S.reduce((A,C)=>A+C,0)/S.length,G=Math.max(100,Math.min(I*3,1e3));p.current=G},[]);return a.useEffect(()=>{const h=document.getElementById(t.llmOutputContainerId);if(!h)return;x();const S=new MutationObserver(()=>{const I=Date.now();c.current=I,m.current=0,j.current.push(I),j.current.length>10&&j.current.shift(),f(),x()});return S.observe(h,{childList:!0,subtree:!0,characterData:!1}),()=>{S.disconnect(),w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current)}},[t.llmOutputContainerId,x,f]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:d.current,shouldRenderFallback:!d.current&&u.current,processWeaveFormat:x}},Hs="1.0.31";exports.AdMeshBadge=Vr;exports.AdMeshCompactCard=Hn;exports.AdMeshContext=qn;exports.AdMeshFollowup=Ur;exports.AdMeshIntentAssistant=Ns;exports.AdMeshLayout=zr;exports.AdMeshLinkTracker=Or;exports.AdMeshProvider=Wr;exports.AdMeshRecommendations=dn;exports.AdMeshRenderer=Br;exports.AdMeshSDK=cn;exports.AdMeshTailAd=hs;exports.AdMeshTracker=Nr;exports.AdMeshViewabilityTracker=un;exports.STREAMING_COMPLETE_EVENT=_n;exports.STREAMING_START_EVENT=wn;exports.VERSION=Hs;exports.WeaveAdFormatContainer=Bs;exports.WeaveAdFormatProvider=ds;exports.WeaveFallbackRecommendations=Hr;exports.WeaveResponseProcessor=Vn;exports.callAnalyzeIntentEndpoint=Lr;exports.createInlineExposureTracker=vn;exports.dispatchStreamingCompleteEvent=Ls;exports.dispatchStreamingStartEvent=$s;exports.extractHeadingsDirectly=$r;exports.onStreamingComplete=Qr;exports.onStreamingStart=Fs;exports.useAdMesh=tn;exports.useAdMeshContext=On;exports.useAdMeshStyles=Gr;exports.useViewabilityTracker=Pr;exports.useWeaveAdFormat=Us;exports.useWeaveAdFormatContext=cs;
|
|
1181
|
+
`).map(A=>A.trim()).filter(Boolean),h=f.every(A=>/^[-*]\s+/.test(A)),S=f.every(A=>/^\d+\.\s+/.test(A)),I=f.length===1&&/^#{1,3}\s+/.test(f[0]),G=_(f);if(I){const A=f[0].replace(/^#{1,3}\s+/,"");return n.jsx("h3",{style:{marginTop:x===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(A)},x)}if(G){const{heading:A,lines:C}=g(f),L=i(C[0]),$=C.slice(2).map(i).filter(F=>F.length===L.length);return n.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[A?n.jsx("p",{style:{marginTop:x===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(A)}):null,n.jsx("div",{style:{border:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,borderRadius:8,overflowX:"auto"},children:n.jsxs("table",{style:{width:"100%",minWidth:L.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[n.jsx("thead",{children:n.jsx("tr",{children:L.map((F,P)=>n.jsx("th",{style:{textAlign:"left",padding:"9px 10px",fontWeight:600,background:e.surfaceColor||"rgba(148, 163, 184, 0.12)",borderBottom:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,whiteSpace:"normal"},children:s(F)},P))})}),n.jsx("tbody",{children:$.map((F,P)=>n.jsx("tr",{children:F.map((z,M)=>n.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:P===$.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(z)},M))},P))})]})})]},x)}if(h||S){const A=S?"ol":"ul";return n.jsx(A,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:f.map((C,L)=>n.jsx("li",{style:{marginBottom:"0.45rem"},children:s(C.replace(/^([-*]|\d+\.)\s+/,""))},L))},x)}return n.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:f.map((A,C)=>n.jsxs(a.Fragment,{children:[C>0&&n.jsx("br",{}),s(A)]},C))},x)})})};function mn(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function Er(t){if(typeof t=="number")return t;if(typeof t!="string")return;const e=Number(t.trim().replace(/px$/i,""));return Number.isFinite(e)&&e>0?e:void 0}function Xt(t){return t.replace(/\s+/g," ").trim()}function Ts(t,e){const o=t.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),s=e.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),i=e.find(u=>u==null?void 0:u.is_sponsored);if(!i)return s.length?s:o;const d=s.length?s:o;return[i,...d].slice(0,4)}function Ds(t,e,o,s){const i=new Set,d=[],u=(j,p="information")=>{const x=Xt(j);if(!x)return;const f=x.toLowerCase();i.has(f)||(i.add(f),d.push({id:`followup_${d.length}_${f.replace(/[^a-z0-9]+/g,"_")}`,text:x,type:p,is_sponsored:!1}))},w=new Set,g=j=>{const p=Xt(j||"");if(!p)return;const x=p.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();x&&w.add(x)};(s||[]).forEach(j=>g(j==null?void 0:j.title)),(o||[]).forEach(j=>g(j==null?void 0:j.title)),e.split(/\n+/).map(j=>Xt(j.replace(/^[-*]\s+/,""))).filter(Boolean).filter(j=>j.length>=24&&j.length<=90).forEach(j=>{w.size>=6||g(j)});const c=Xt(t.replace(/[?.!]+$/g,"")),m=Array.from(w).slice(0,3);return[m[0]?`Tell me more about ${m[0]}`:"",m[1]?`Show me examples related to ${m[1]}`:"",m[2]?`Compare the main options for ${m[2]}`:"","Break this down more simply",`What should I look at next about ${c}`,"Give me the practical takeaway here"].forEach((j,p)=>{d.length>=3||u(j,p===0?"comparison":"information")}),d.slice(0,3)}function Ps(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function Rr(t){return t?{shell:{position:"fixed",left:0,right:0,bottom:0,width:"100%",maxWidth:"100%",height:"calc(100dvh - env(safe-area-inset-bottom, 0px))",maxHeight:"calc(100dvh - env(safe-area-inset-bottom, 0px))",padding:0,margin:0,zIndex:2147483001,boxSizing:"border-box"},panelWidth:"100%",panelMaxWidth:"100%",panelHeight:"100%",panelMaxHeight:"100%",panelBorderRadius:"0"}:{shell:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",maxWidth:"100%",maxHeight:"calc(100vh - 24px)",zIndex:2147483001,boxSizing:"border-box"},panelWidth:"min(960px, calc(100vw - 24px))",panelMaxWidth:"100%",panelHeight:"min(78vh, 760px)",panelMaxHeight:void 0,panelBorderRadius:"12px"}}function Qr(t){const e=t==null?void 0:t.trim();if(!e||/%%[^%]+%%/.test(e))return!1;try{const o=new URL(e);return!!(o.protocol&&o.hostname)}catch{return!1}}function Ir(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Qr(e))return e}catch{return}}function Tr(t){if(typeof window>"u")return{page_url:void 0,page_path:void 0,article_slug:void 0,page_title:void 0,referrer:void 0,device_type:"unknown"};const e=Ir()||(Qr(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=Ir()?window.location.pathname||"/":void 0}const s=(o||"").split("/").filter(Boolean);return{page_url:e,page_path:o,article_slug:s[s.length-1],page_title:document.title||void 0,referrer:document.referrer||void 0,device_type:Ps()}}function zs(t){var s,i;const e=(i=(s=t==null?void 0:t.recommendation)==null?void 0:s.creative)==null?void 0:i.follow_up_suggestion,o=t==null?void 0:t.recommendation_id;return!e||!o?null:{id:o,text:Xt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Bn(t){return[...t].sort((e,o)=>{const s=!!e.is_sponsored,i=!!o.is_sponsored;return s===i?0:s?-1:1})}const Ns={mode:"light",primaryColor:"#3b82f6",secondaryColor:"#64748b",backgroundColor:"#ffffff",surfaceColor:"#f8fafc",borderColor:"#e2e8f0",textColor:"#1e293b",textSecondaryColor:"#64748b",borderRadius:"0.5rem",spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},shadows:{small:"0 1px 2px 0 rgb(0 0 0 / 0.05)",medium:"0 4px 6px -1px rgb(0 0 0 / 0.1)",large:"0 10px 15px -3px rgb(0 0 0 / 0.1)"}},$s={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},Ls={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},Fs=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:d,showHeader:u=!0,showHeaderTitle:w=!0,showSubtitle:g=!0,layout:_="floating",surface:c="page",adSlotBehavior:m="expand",showCompactSlotHeader:k=!0,showCompactWelcomeMessage:j=!0,showCompactSlotInput:p=!0,showCompactSlotDisclaimer:x=!0,panelWidth:f,panelHeight:h,analyticsPageUrl:S,fontScale:I=1,position:G="bottom-right",size:A="md",defaultOpen:C,open:L,onOpenChange:$,autoOpen:F=!1,showWelcomeMessage:P=!1,welcomeMessage:z="Hi, Iโm Ava. Iโll help you find the best options.",placeholder:M="Ask me anything about products...",adsEnabled:W=!0,suggestions:V,maxSuggestions:Y=6,suggestionStyle:U="carousel",suggestionTrigger:H="always",suggestionPlacement:te="below",sponsoredCreativePlacement:ge="none",onlyShowWhenSponsored:Z=!1,variant:ne="default",queryHandler:_e,suggestionsLoader:Ge,disclaimerText:Ee,poweredByLabel:ve="Powered by AdMesh",subtitle:le="Publisher Assistant",onOpen:ue,onClose:Re})=>{const{sdk:be,sessionId:se,theme:xt,apiKey:N,userId:Q}=on(),{suggestions:X,isAnalyzingIntent:ee,intentError:re,retryIntentAnalysis:Ie,activeDelegationSession:T,hasActiveDelegationSession:ie,stopDelegationSession:D,refreshDelegationActivity:fe}=Vn();Yr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:be,sessionId:se,hasContextTheme:!!xt});const E=t||xt||Ns,de=(E==null?void 0:E.mode)||"light",ke=c==="ad-slot",me=(r=!1)=>ke&&!(r&&m==="expand"),[Be,Ne]=a.useState(C||F),Se=L!==void 0,De=Se?L:Be,[Ae,bt]=a.useState(""),[st,Mt]=a.useState(!1),[Pe,Oe]=a.useState([]),[pe,it]=a.useState(!1),[jt,Et]=a.useState(null),[q,at]=a.useState(!1),[yt,Lt]=a.useState(new Set),[Ut,O]=a.useState(V||X||[]),[Ce,Qe]=a.useState(0),[ut,Rt]=a.useState(0),[It,Ht]=a.useState({}),Tt=a.useRef(null),wt=a.useRef(!1),Xe=a.useRef(null),K=a.useRef(new Map),$e=a.useRef([]),ae=a.useRef(null),_t=a.useRef(null),rt=a.useRef(null),vt=a.useRef(!1),Dt=a.useRef(!1),qt=a.useRef(null),kt=a.useRef(null),mt=a.useRef(null),[Jt,kn]=a.useState(!1),[Sn,Jr]=a.useState(!1),St=a.useRef(null),Je=a.useRef(null),Zr=!!(N!=null&&N.toLowerCase().startsWith("pub_")),Ze=ie()&&(T==null?void 0:T.session_id)===se?T:null,An=a.useRef(new Set),Gn=a.useRef(new Set),Yn=a.useRef(!1),Zt=ke&&m==="expand"&&(q||pe),[fn,eo]=a.useState(!1);a.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia("(max-width: 767px)"),b=()=>eo(r.matches);return b(),r.addEventListener("change",b),()=>r.removeEventListener("change",b)},[]),a.useEffect(()=>{if(!Zt||typeof document>"u")return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[Zt]);const Cn=ke&&m==="sticky"&&(q||Pe.length>0||pe),Pt=mn(f)??"100%",en=mn(h)??"100%",to=Er(f),Qn=Er(h),Xn=ke&&(Qn??Number.POSITIVE_INFINITY)<=60,lt=ke&&(to??Number.POSITIVE_INFINITY)<=360&&(Qn??Number.POSITIVE_INFINITY)<=120,sn=a.useCallback(r=>b=>{b?K.current.set(r,b):K.current.delete(r)},[]),Te=a.useCallback(async(r,b={})=>{if(!(!be||!se))try{await be.trackPublisherAssistantEvent({event_name:r,timestamp:new Date().toISOString(),session_id:se,...Tr(S),...b})}catch(y){console.warn(`[AdMeshIntentAssistant] Failed to track ${r}`,y)}},[S,be,se]),an=a.useCallback((r,b,y)=>{var B,he;const v=b==null?void 0:b.recommendation_id;if(!v)return;const R=`${r}:${v}`;Gn.current.has(R)||(Gn.current.add(R),Te("recommendation_shown",{message_id:r,query:y,recommendation_id:v,brand_name:(he=(B=b.recommendation)==null?void 0:B.creative)==null?void 0:he.brand_name,is_sponsored:!0}))},[Te]),Mn=a.useCallback((r,b,y,v,R,B)=>{const he=Array.isArray(B)&&B.length?B.map((je,Me)=>{const Fe=Xt(je.text||"");return Fe?{id:`followup_llm_${Me}_${Fe.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:Fe,type:je.type||"information",is_sponsored:!1}:null}).filter(je=>!!je).slice(0,3):Ds(r,b,y,v),ze=zs(R),we=ze?[ze,...he.slice(0,2)]:he.slice(0,3);we.length&&O(Bn(we))},[]),ln=a.useCallback((r,b)=>{const y=Xt(r.query||r.label||"");if(!y||!b)return;const v={id:b,text:y,type:"action",is_sponsored:!0,recommendation:{recommendation_id:b,recommendation:{creative:{follow_up_suggestion:y}},tracking:{followup_engagement_url:r.engagement_url,followup_exposure_url:r.exposure_url}}};O(R=>{const B=R.filter(he=>!he.is_sponsored).slice(0,3);return Bn([v,...B].slice(0,4))})},[]),Jn=a.useCallback(()=>{const r=ae.current,b=_t.current;if(!r||!b)return!1;const y=r.getBoundingClientRect(),v=b.getBoundingClientRect(),R=Math.max(0,r.scrollTop+v.top-y.top);return r.scrollTop=R,!0},[]);a.useLayoutEffect(()=>{var r;if(vt.current){Jn()&&(vt.current=!1);return}Dt.current||(r=kt.current)==null||r.scrollIntoView({behavior:"smooth"})},[Pe,Jn]),a.useLayoutEffect(()=>{if(!ke||Zt)return;const r=qt.current;if(!r)return;const b=r.closest(".admesh-publisher-assistant-reactMount"),y=en;[r,b].forEach(R=>{R&&(R.style.width=Pt,R.style.maxWidth=Pt,R.style.height=y,R.style.maxHeight=y,R.style.overflow="hidden",R.style.boxSizing="border-box",R.dataset.admeshAdSlotExpanded=Cn?"true":"false")});const v=b==null?void 0:b.parentElement;v&&v!==document.body&&v!==document.documentElement&&(v.style.width=Pt,v.style.maxWidth=Pt,v.style.height=y,v.style.maxHeight=y,v.style.overflow="hidden",v.style.boxSizing="border-box")},[en,Pt,Zt,ke,Cn]),a.useEffect(()=>{if(V&&V.length){O(V);return}X&&X.length&&O(r=>Ts(r,X))},[V,X]),a.useEffect(()=>{if(ne!=="default"||!Ge)return;let r=!1;return Ge().then(b=>{!r&&Array.isArray(b)&&b.length&&O(b)}).catch(b=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",b)}),()=>{r=!0}},[Ge,ne]),a.useEffect(()=>{if(!pe){Rt(0),Tt.current=null;return}Tt.current==null&&(Tt.current=typeof performance<"u"?performance.now():Date.now());const r=()=>{const y=Tt.current;if(y==null)return;const v=typeof performance<"u"?performance.now():Date.now();Rt(Math.floor((v-y)/1e3))};r();const b=window.setInterval(r,1e3);return()=>window.clearInterval(b)},[pe]),a.useEffect(()=>{if(!pe||ne!=="default"){Qe(0);return}const r=window.setInterval(()=>{Qe(b=>Math.min(b+1,7))},3e3);return()=>window.clearInterval(r)},[pe,ne]),a.useEffect(()=>{Yn.current||!be||!se||(Yn.current=!0,Te("assistant_loaded",{metadata:{layout:_,surface:c,variant:ne,default_open:C||F}}))},[F,C,_,be,se,c,Te,ne]);const Ft=a.useCallback(r=>{Se?$==null||$(r):Ne(r),r?(Te("assistant_opened",{metadata:{layout:_,surface:c,ad_slot_behavior:m,variant:ne,expanded:q}}),ue==null||ue()):Re==null||Re()},[Se,q,_,$,ue,Re,c,Te,ne]),Zn=a.useCallback(()=>{Ft(!0)},[Ft]),no=a.useCallback(()=>{Ft(!1)},[Ft]),ro=a.useCallback(()=>{at(r=>!r)},[]),er=a.useCallback(async(r,b,y,v,R,B,he)=>{var ze,we,je;if(!be)return console.warn("[AdMeshIntentAssistant] SDK not available - using fallback response"),{text:"I'm a demo assistant. The SDK is not properly configured, but I can still help with suggestions! Try clicking on one of the suggested questions above."};try{Ze&&await fe("turn_started",{source:"publisher_assistant",recommendation_id:Ze.recommendation_id}).catch(ce=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",ce)});const Me=await fetch(`${be.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:B,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${N}`},body:JSON.stringify({message:r,session_id:se||"default-session",message_id:b,user_id:Q,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:Tr(S),conversation_history:he,sponsored_recommendation:R!=null&&R.recommendation_id?{recommendation_id:R.recommendation_id,brand_name:(we=(ze=R.recommendation)==null?void 0:ze.creative)==null?void 0:we.brand_name}:void 0,active_delegation_session:Ze?{delegation_session_id:Ze.delegation_session_id,recommendation_id:Ze.recommendation_id,session_id:Ze.session_id,brand_name:Ze.brand_name,mcp_endpoint:Ze.mcp_endpoint,status:Ze.status}:void 0}})});if(!Me.ok)throw new Error(`API request failed: ${Me.status} ${Me.statusText}`);const Fe=(je=Me.body)==null?void 0:je.getReader(),zt=new TextDecoder;if(!Fe)throw new Error("Response body is not readable");let Ke="",et,Nt,$t,J,oe;return await(async()=>{try{for(;;){const{done:ce,value:pt}=await Fe.read();if(ce)break;const ot=zt.decode(pt,{stream:!0}).split(`
|
|
1182
|
+
`);for(const Yt of ot)if(Yt.startsWith("data: ")){const Pn=Yt.slice(6);if(Pn.trim()==="[DONE]")return Ze&&fe("turn_completed",{source:"publisher_assistant",recommendation_id:Ze.recommendation_id}).catch(We=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",We)}),{text:Ke,source_links:et,related_items:Nt,followup_suggestions:$t,used_capability:J,response_time_ms:oe};try{const We=JSON.parse(Pn);switch(We.type){case"content":{const pr=We.content||"";Ke+=pr,y==null||y(pr);break}case"final":{Ke=We.reply||Ke,et=Array.isArray(We.source_links)?We.source_links:void 0,Nt=Array.isArray(We.related_items)?We.related_items:void 0,$t=Array.isArray(We.followup_suggestions)?We.followup_suggestions:void 0,J=typeof We.used_capability=="string"?We.used_capability:J,oe=typeof We.response_time_ms=="number"?We.response_time_ms:oe;break}case"followup_suggestions":{$t=Array.isArray(We.followup_suggestions)?We.followup_suggestions:$t;break}case"error":throw new Error(We.message||"Unknown streaming error");case"session_start":v==null||v(),console.log("Session started:",We.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",Pn);continue}}}}catch(ce){if(B!=null&&B.aborted)return{text:Ke,source_links:et,related_items:Nt,followup_suggestions:$t,used_capability:J,response_time_ms:oe,error:"aborted"};throw console.error("Stream processing error:",ce),ce}finally{Fe.releaseLock()}return{text:Ke,source_links:et,related_items:Nt,followup_suggestions:$t,used_capability:J,response_time_ms:oe}})()}catch(Me){return B!=null&&B.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",Me),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:Me instanceof Error?Me.message:"request_failed"})}},[be,se,N,Q,Ze,fe]),jn=a.useCallback(()=>{const r=St.current;if(!r||r.signal.aborted)return;r.abort(),it(!1),Xe.current=null,wt.current=!1;const b=Je.current;b&&Oe(y=>y.map(v=>v.id===b&&!v.content.trim()?{...v,content:"Generation stopped."}:v))},[]),Ot=a.useCallback(async r=>{var je,Me,Fe,zt,Ke,et,Nt,$t;if(!r.trim()||pe)return;const b=typeof performance<"u"?performance.now():Date.now(),y=r.trim(),v=Date.now().toString(),R=new AbortController,B=Xe.current,he=(B==null?void 0:B.recommendation)||null,ze=Pe.filter(J=>(J.role==="user"||J.role==="assistant")&&J.content.trim()).slice(-6).map(J=>({role:J.role,content:J.content.trim().slice(0,1200)}));St.current=R,Je.current=null,rt.current=v,vt.current=!0,Dt.current=!0,Xe.current=null,O(J=>J.some(oe=>oe.is_sponsored)?J.filter(oe=>!oe.is_sponsored):J),Et(null);const we={id:v,role:"user",content:y,timestamp:new Date};if(Te("query_submitted",{message_id:v,query:y}),Oe(J=>[...J,we]),bt(""),it(!0),ne==="default"&&_e){try{const J=(Date.now()+1).toString(),oe={id:J,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:null};wt.current&&(Lt(pt=>new Set([...pt,J])),wt.current=!1),Oe(pt=>[...pt,oe]),Je.current=J;const qe=await _e(y,{sponsoredSuggestion:B});if(R.signal.aborted){Xe.current=null;return}const ce=qe.recommendation||he||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:r,hasResponseRecommendation:!!qe.recommendation,hasSponsoredSuggestionRecommendation:!!he,finalRecommendationId:ce==null?void 0:ce.recommendation_id}),Oe(pt=>pt.map(tt=>tt.id===J?{...tt,content:qe.answer,sourceLinks:qe.source_links,relatedItems:qe.related_items,initialRecommendation:ce,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-b}:tt)),Mn(y,qe.answer,qe.source_links,qe.related_items,qe.recommendation||null,qe.followup_suggestions),Te("answer_completed",{message_id:J,query:y,recommendation_id:ce==null?void 0:ce.recommendation_id,brand_name:(Me=(je=ce==null?void 0:ce.recommendation)==null?void 0:je.creative)==null?void 0:Me.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"completed",metadata:{variant:ne,source:"query_handler"}}),Xe.current=null}catch(J){console.error("Error sending message:",J);const oe=J instanceof Error?J.message:"Unknown error occurred";Et(oe);const qe={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Oe(ce=>[...ce,qe]),Te("answer_failed",{query:y,status:oe,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,metadata:{variant:ne,source:"query_handler"}}),Xe.current=null}finally{St.current===R&&(St.current=null,Je.current=null,it(!1))}return}if(!be){setTimeout(()=>{if(R.signal.aborted){St.current===R&&(St.current=null,Je.current=null);return}const J={id:(Date.now()+1).toString(),role:"assistant",content:"I'm a demo assistant. The SDK is not properly configured, but I can still help! Try clicking on the suggested questions above, or check your AdMesh API key configuration.",timestamp:new Date,recommendations:[],userQuery:r};Oe(oe=>[...oe,J]),St.current===R&&(St.current=null,Je.current=null,it(!1))},1e3);return}try{const J=(Date.now()+1).toString(),oe=he,qe={id:J,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:oe};wt.current&&(Lt(tt=>new Set([...tt,J])),wt.current=!1),Oe(tt=>[...tt,qe]),Je.current=J;const ce=await er(y,v,tt=>{Oe(ot=>ot.map(Yt=>Yt.id===J?{...Yt,content:Yt.content+tt}:Yt))},()=>{it(!0),Qe(0)},oe,R.signal,ze);if(R.signal.aborted){ce.text.trim()||Oe(tt=>tt.map(ot=>ot.id===J&&!ot.content.trim()?{...ot,content:"Generation stopped."}:ot)),Te("answer_failed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(zt=(Fe=oe==null?void 0:oe.recommendation)==null?void 0:Fe.creative)==null?void 0:zt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"aborted",metadata:{variant:ne,source:"api_chat_assistant"}}),Xe.current=null;return}const pt=typeof ce.response_time_ms=="number"?ce.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-b;Oe(tt=>tt.map(ot=>ot.id===J?{...ot,content:ce.text,sourceLinks:ce.source_links,relatedItems:ce.related_items,initialRecommendation:ot.initialRecommendation||oe,responseTimeMs:pt}:ot)),Mn(y,ce.text,ce.source_links,ce.related_items,null,ce.followup_suggestions),ce.error?Te("answer_failed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(et=(Ke=oe==null?void 0:oe.recommendation)==null?void 0:Ke.creative)==null?void 0:et.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:ce.error,metadata:{variant:ne,source:"api_chat_assistant"}}):Te("answer_completed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:($t=(Nt=oe==null?void 0:oe.recommendation)==null?void 0:Nt.creative)==null?void 0:$t.brand_name,used_capability:ce.used_capability,latency_ms:pt,status:"completed",metadata:{variant:ne,source:"api_chat_assistant",response_time_ms:pt}}),Xe.current=null}catch(J){console.error("Error sending message:",J);const oe=J instanceof Error?J.message:"Unknown error occurred";Et(oe);const qe={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Oe(ce=>[...ce,qe]),Te("answer_failed",{query:y,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:oe,metadata:{variant:ne,source:"api_chat_assistant"}}),Xe.current=null}finally{St.current===R&&(St.current=null,Je.current=null,it(!1))}},[pe,er,_e,Mn,be,Te,ne]),Wt=Ut,gn=a.useMemo(()=>Wt.some(r=>r==null?void 0:r.is_sponsored),[Wt]),xn=a.useMemo(()=>Wt.filter(r=>!(r&&typeof r.id=="string")?!1:Z?gn:!0),[gn,Z,Wt]),Ue=a.useMemo(()=>Bn(xn),[xn]),Vt=a.useMemo(()=>ge==="below-input-container"&&W?Ue.find(r=>r.is_sponsored&&r.recommendation)??null:null,[W,Ue,ge]),dn=a.useCallback(async r=>{var y,v,R,B,he,ze,we;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:r.text,is_sponsored:r.is_sponsored,hasRecommendation:!!r.recommendation,recommendationId:((y=r.recommendation)==null?void 0:y.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((R=(v=r.recommendation)==null?void 0:v.tracking)!=null&&R.followup_engagement_url),sessionId:se}),wt.current=r.is_sponsored||!1,Xe.current=r.is_sponsored?r:null;const b=Ue.findIndex(je=>je.id===r.id);Te("suggestion_clicked",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b>=0?b:void 0,is_sponsored:r.is_sponsored,recommendation_id:(B=r.recommendation)==null?void 0:B.recommendation_id,brand_name:(we=(ze=(he=r.recommendation)==null?void 0:he.recommendation)==null?void 0:ze.creative)==null?void 0:we.brand_name,query:r.text}),Ot(r.text),r.is_sponsored&&r.recommendation&&be?setTimeout(async()=>{var je;try{const Me=(je=r.recommendation.tracking)==null?void 0:je.followup_engagement_url,Fe=r.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:Me,recommendationId:Fe,sessionId:se}),Me&&Fe&&se?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await be.fireFollowupEngagement(Me,Fe,se),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!Me,hasRecommendationId:!!Fe,hasSessionId:!!se})}catch(Me){console.error("[AdMeshIntentAssistant] โ Error firing sponsored suggestion engagement:",Me)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[Ot,Ue,be,se,Te]),bn=Ls[G],tr=$s[A];a.useEffect(()=>{if($e.current.forEach(r=>r()),$e.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return Ue.forEach((r,b)=>{const y=K.current.get(r.id);if(!y)return;const v=`${se||"anonymous"}:${r.id}:${r.is_sponsored?"s":"o"}`;if(An.current.has(v))return;let R=null,B=null;const he=()=>{R&&(clearTimeout(R),R=null),B==null||B.disconnect(),B=null},ze=()=>{var we,je,Me,Fe,zt;if(An.current.has(v)){he();return}if(An.current.add(v),he(),Te("suggestion_exposure",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b,is_sponsored:r.is_sponsored,recommendation_id:(we=r.recommendation)==null?void 0:we.recommendation_id,brand_name:(Fe=(Me=(je=r.recommendation)==null?void 0:je.recommendation)==null?void 0:Me.creative)==null?void 0:Fe.brand_name}),be&&se&&r.is_sponsored&&r.recommendation){const Ke=(zt=r.recommendation.tracking)==null?void 0:zt.followup_exposure_url,et=r.recommendation.recommendation_id;Ke&&et?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Ke,recommendationId:et,suggestionText:r.text,sessionId:se}),be.fireFollowupExposure(Ke,et,se)):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Ke,hasRecommendationId:!!et,suggestionText:r.text})}};B=new IntersectionObserver(we=>{const je=we[0];if(je){if(je.intersectionRatio>=.5){R||(R=setTimeout(ze,1e3));return}R&&(clearTimeout(R),R=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),B.observe(y),$e.current.push(he)}),()=>{$e.current.forEach(r=>r()),$e.current=[]}},[Ue,be,se,Te,st]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:Wt.length,safeSuggestions:xn.length,isAnalyzingIntent:ee,hasIntentError:!!re,onlyShowWhenSponsored:Z,hasSponsoredSuggestions:gn,sponsoredCount:Wt.filter(r=>r==null?void 0:r.is_sponsored).length,nonSponsoredCount:Wt.filter(r=>r&&!(r!=null&&r.is_sponsored)).length,modalShouldAppear:Z?gn:!0,suggestions:Wt.map(r=>{var b,y,v;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&v.followup_engagement_url)}}),renderedSuggestions:Ue.map(r=>{var b,y,v;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&v.followup_engagement_url)}})});const ye={base:`${16*I}px`,sm:`${14*I}px`,xs:`${12*I}px`},nr=Ee||"AI-generated responses may contain errors. Please verify important information independently.",oo=["Searching trusted sources...","Reviewing publisher coverage...","Checking relevant context...","Comparing supporting signals...","Identifying the strongest examples...","Organizing the most useful details...","Shaping the response for clarity...","Preparing the clearest answer...","Finishing the response..."],cn=r=>{const b=(r==null?void 0:r.accentColor)||At,y=(r==null?void 0:r.metaColor)||ir,v=(r==null?void 0:r.includeSteps)??ne==="default",R=`${ut}s`,B=v?`${oo[Ce]} (${R})`:`Generating answer... ${R}`;return n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:r!=null&&r.compact?"8px":"10px",color:y,fontSize:r!=null&&r.compact?ye.xs:ye.sm},children:[n.jsx("span",{style:{width:r!=null&&r.compact?8:9,height:r!=null&&r.compact?8:9,borderRadius:999,background:b,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${Le(Ve,.28)}`,flexShrink:0}}),n.jsx("span",{children:B})]})},rr=a.useCallback((r,b)=>{if(It[r.id])return;const y=b?"helpful":"not_helpful";Ht(v=>({...v,[r.id]:y})),Te("answer_feedback",{message_id:r.id,query:r.userQuery,status:y,latency_ms:r.responseTimeMs,metadata:{helpful:b}})},[It,Te]);function En(r,b){if(r.role!=="assistant"||!r.content.trim()||pe&&r.id===Je.current)return null;const y=(b==null?void 0:b.accentColor)||At,v=(b==null?void 0:b.metaColor)||ir,R=It[r.id],B=typeof r.responseTimeMs=="number";return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${ct}`,flexWrap:"wrap"},children:[n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto",flexWrap:"wrap"},children:[n.jsx("span",{style:{fontSize:ye.xs,color:v,whiteSpace:"nowrap"},children:R?"Thanks for your feedback":"Is this helpful?"}),R?n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",background:Le(y,.12),color:y,flexShrink:0},children:R==="helpful"?n.jsx(br,{size:14}):n.jsx(xr,{size:14})}):n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[n.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>rr(r,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:v,cursor:"pointer"},children:n.jsx(br,{size:14})}),n.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>rr(r,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:v,cursor:"pointer"},children:n.jsx(xr,{size:14})})]})]}),B?n.jsxs("span",{style:{fontSize:ye.xs,color:v,whiteSpace:"nowrap",flex:"0 1 auto",marginLeft:"auto"},children:["Answer Completed in ",Is(r.responseTimeMs)]}):null]})}const un=a.useCallback(()=>{const r=mt.current;if(!r)return;const b=Math.max(0,r.scrollWidth-r.clientWidth);kn(r.scrollLeft>4),Jr(r.scrollLeft<b-4)},[]);a.useEffect(()=>(un(),window.addEventListener("resize",un),()=>window.removeEventListener("resize",un)),[un,Ue.length]);const or=a.useCallback(r=>{const b=mt.current;b&&b.scrollBy({left:r==="left"?-Math.max(160,Math.floor(b.clientWidth*.75)):Math.max(160,Math.floor(b.clientWidth*.75)),behavior:"smooth"})},[]),Le=(r,b)=>{if(!r||!r.startsWith("#"))return`rgba(15, 23, 42, ${b})`;const y=r.slice(1),v=y.length===3?y.split("").map(ze=>`${ze}${ze}`).join(""):y;if(v.length!==6)return r;const R=parseInt(v.slice(0,2),16),B=parseInt(v.slice(2,4),16),he=parseInt(v.slice(4,6),16);return`rgba(${R}, ${B}, ${he}, ${b})`},Ve=E.primaryColor||"#3F037F",dt=E.surfaceColor||"#ffffff",so=E.backgroundColor||"#eef2ff",ct=E.borderColor||"#e5e7eb",He=E.textColor||"#111827",Kt=E.textSecondaryColor||"#6b7280";Le(Ve,.12);const sr=Le(Ve,.24);Le(Ve,.38);const io=dt,At=Ve,yn=E.primaryTextColor||"#ffffff",ir=Kt,ar=le||"Publisher Assistant",tn=ee&&Ue.length===0&&Pe.length===0,Rn=dt,In=dt,Gt=ct,lr=ct,dr="0 16px 64px rgba(15, 23, 42, 0.14)",Tn=Kt,ao=Kt,lo=At,cr=so,co="none",uo="rgba(15, 23, 42, 0.18)";function ur(r){return Ze?n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:r==="default"?"10px 12px":"8px 10px",borderRadius:r==="default"?"14px":"12px",border:`1px solid ${sr}`,background:Le("#ffffff",.9),marginBottom:"4px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{color:At,fontSize:ye.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),n.jsxs("div",{style:{color:He,fontSize:ye.sm,fontWeight:600,lineHeight:1.3},children:[Ze.brand_name," agent is active"]})]}),n.jsx("button",{type:"button",onClick:()=>{D("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${sr}`,borderRadius:999,background:Le("#ffffff",.92),color:At,padding:"7px 12px",fontSize:ye.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function mr(r,b=ke){const y=fn&&!b,v=b||y?"9px":"11px";return n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",paddingTop:b||r==="default"?"2px":"8px",marginTop:b?"0":r==="default"?"4px":0,flexShrink:0,textAlign:"center",width:"100%"},children:n.jsx("div",{style:{color:ao,fontSize:v,lineHeight:y?1.3:1.45,maxWidth:"100%",textAlign:"center"},children:nr})})}function Dn(r){const b=r==="publisher"?[180,220,196]:["100%","82%","68%"];return r==="publisher"?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:Le(He,.06),flexShrink:0}}),n.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:b.map((y,v)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:40,borderRadius:"6px",background:Le(He,.06),backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:"none",flexShrink:0}},`suggestion-skeleton-${v}`))}),n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:Le(He,.06),flexShrink:0}})]}):n.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:r==="publisher"?"10px":"12px"},children:b.map((y,v)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:r==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${Le(Ve,.08)} 0%, ${Le(Ve,.18)} 50%, ${Le(Ve,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:r==="publisher"?`0 8px 22px ${Le(Ve,.08)}`:"none"}},`suggestion-skeleton-${v}`))})}function mo(r=ke){if(pe)return null;if(tn)return Dn("publisher");if(!Ue.length)return null;const b=r&&Xn,y=Ue.slice(0,Y);return U==="stacked"?n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:r?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:r?"240px":void 0,paddingRight:r?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:y.map(v=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":v.is_sponsored?"true":void 0,ref:sn(v.id),onClick:()=>{ne==="default"&&(at(!0),_==="floating"&&Ft(!0)),dn(v)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:"8px",border:`1px solid ${v.is_sponsored?Ve:ct}`,background:v.is_sponsored?Ve:dt,color:v.is_sponsored?yn:He,padding:r?"8px 10px":"10px 14px",fontSize:r?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{style:{minWidth:0},children:v.text}),W&&v.is_sponsored&&n.jsx("span",{style:{flexShrink:0,borderRadius:"6px",background:Le("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},v.id))}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:b?"4px":lt?"5px":r?"6px":"10px",flexShrink:0},children:[!b&&n.jsx("button",{type:"button",onClick:()=>or("left"),disabled:!Jt,"aria-label":"Scroll suggestions left",style:{width:lt?20:r?24:28,height:lt?20:r?24:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:"#6b7280",fontSize:lt?"13px":void 0,lineHeight:1,cursor:Jt?"pointer":"default",opacity:Jt?1:.55},children:"โน"}),n.jsx("div",{ref:mt,onScroll:un,style:{display:"flex",gap:b?"4px":lt?"5px":r?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:y.map(v=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":v.is_sponsored?"true":void 0,ref:sn(v.id),onClick:()=>{ne==="default"&&(at(!0),_==="floating"&&Ft(!0)),dn(v)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:b?"4px":lt?"5px":"8px",whiteSpace:"nowrap",borderRadius:"6px",border:`1px solid ${v.is_sponsored?Ve:ct}`,background:v.is_sponsored?Ve:dt,color:v.is_sponsored?yn:He,padding:b?"4px 8px":lt?"5px 8px":r?"7px 10px":"8px 14px",fontSize:b?"10px":lt?"11px":r?"12px":"13px",fontWeight:500,lineHeight:b?1:lt?1.1:void 0,boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{children:v.text}),W&&v.is_sponsored&&n.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},v.id))}),!b&&n.jsx("button",{type:"button",onClick:()=>or("right"),disabled:!Sn,"aria-label":"Scroll suggestions right",style:{width:lt?20:r?24:28,height:lt?20:r?24:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:"#6b7280",fontSize:lt?"13px":void 0,lineHeight:1,cursor:Sn?"pointer":"default",opacity:Sn?1:.55},children:"โบ"})]})}function po(r=ke){if(r||!(Vt!=null&&Vt.recommendation))return null;const b=`publisher-sponsored-creative-${Vt.id}`;return n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"2px"},children:n.jsx(nn,{messageId:b,query:Vt.text,initialRecommendation:Vt.recommendation,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,Vt.text)},onError:y=>{console.error("[AdMeshIntentAssistant] Sponsored creative error:",y)}})})}function ho(r){var b,y;return(b=r.relatedItems)!=null&&b.length||!((y=r.sourceLinks)!=null&&y.length)?null:n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"16px"},children:[n.jsx("div",{style:{width:"100%",fontSize:"11px",fontWeight:600,color:Kt},children:"Sources"}),r.sourceLinks.map(v=>n.jsxs("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Te("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:v.title,source_url:v.url}})},style:{color:At,fontSize:ye.xs,textDecoration:"none",borderBottom:`1px solid ${Le(Ve,.18)}`},children:[v.title||v.url," ",n.jsx(Co,{size:12,style:{display:"inline",verticalAlign:"middle"},"aria-hidden":"true"})]},`${r.id}-${v.url}`))]})}function fo(r,b=ke){var y;return(y=r.relatedItems)!=null&&y.length?n.jsxs("div",{style:{marginTop:"14px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,color:Kt,marginBottom:"8px"},children:"Related reading"}),n.jsx("div",{style:{display:"flex",gap:b?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:r.relatedItems.slice(0,4).map(v=>n.jsxs("a",{className:"admesh-publisher-source",href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Te("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:v.title,source_url:v.url,source_publisher:v.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:b?"6px":"10px",padding:b?"10px":"14px",borderRadius:"8px",textDecoration:"none",color:He,border:`1px solid ${ct}`,background:dt,boxShadow:"none",flex:b?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:b?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[n.jsx("div",{style:{fontSize:b?"12px":"14px",fontWeight:650,lineHeight:1.35,color:He,overflowWrap:"anywhere"},children:v.title||v.url}),v.publisher&&n.jsx("div",{style:{fontSize:b?"11px":"12px",color:Kt,lineHeight:1.4,overflowWrap:"anywhere"},children:v.publisher})]},`${r.id}-${v.url}`))})]}):null}function go(r=ke){const b=r?"13px":"15px";return n.jsxs("div",{ref:ae,style:{flex:r?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"thin",padding:r?"0 2px 4px":q?"16px 16px 8px":0},children:[Pe.map(y=>{const v=y.role==="user"&&y.id===rt.current;return n.jsx("div",{ref:v?_t:void 0,style:{marginBottom:r?"16px":"28px",textAlign:y.role==="user"?"right":"left"},children:(()=>{const B=!!y.content.trim()||!pe;return n.jsx(n.Fragment,{children:n.jsxs("div",{style:{display:y.role==="assistant"?"block":"inline-block",width:y.role==="assistant"?"100%":void 0,maxWidth:y.role==="assistant"?"100%":"76%",padding:y.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:y.role==="assistant"?0:"8px",background:y.role==="user"?Le(He,.05):"transparent",color:He,boxShadow:"none",border:"none",fontSize:y.role==="assistant"?b:r?"12px":"13px",lineHeight:y.role==="assistant"?1.62:1.4},children:[y.role==="assistant"?y.content.trim()?n.jsx(Wn,{content:y.content,theme:{...E,textColor:He},fontSize:b}):pe&&y.id===Je.current?cn({includeSteps:!0}):null:n.jsx("p",{style:{margin:0,color:He},children:y.content}),y.role==="assistant"&&ho(y),y.role==="assistant"&&fo(y,r),y.role==="assistant"&&En(y),y.role==="assistant"&&B&&yt.has(y.id)&&y.initialRecommendation&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(nn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation,onFollowupDetected:ln,onRecommendationsShown:(he,ze)=>{an(he,ze,y.userQuery)},onError:he=>{console.error("[AdMeshIntentAssistant] Recommendation error:",he)}})}),y.role==="assistant"&&B&&!yt.has(y.id)&&(y.initialRecommendation||Zr)&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(nn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation||void 0,onFollowupDetected:ln,onRecommendationsShown:(he,ze)=>{an(he,ze,y.userQuery)},onError:he=>{console.error("[AdMeshIntentAssistant] Recommendation error:",he)}})})]})})})()},y.id)}),jt&&n.jsx("div",{role:"alert",style:{color:He,fontSize:ye.sm,border:`1px solid ${ct}`,borderLeft:"3px solid #b45309",borderRadius:"6px",padding:"12px"},children:"Unable to complete the answer. Please try again."}),n.jsx("div",{ref:kt})]})}if(ne==="default"){let r=function(v){const R=Rr(fn);return Hn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:y}),n.jsx("div",{style:R.shell,children:v})]}),document.body)},b=function(v=!1){const R=me(v),B=v||R&&q,he=R&&!B&&Xn,ze=B&&!(ke&&m==="expand"&&!v&&Zt),we=B?Rr(fn):null,je=!!(we&&fn&&!R),Me=R?Pt:we?we.panelWidth:_==="inline"?"100%":"min(420px, calc(100vw - 32px))",Fe=R?en:we?we.panelHeight:"auto",zt=R?Pt:(we==null?void 0:we.panelMaxWidth)??"100%",Ke=R?en:we==null?void 0:we.panelMaxHeight,et=u&&!he&&B;return n.jsxs("div",{className:"admesh-publisher-panel","data-compact":R?"true":"false",style:{"--publisher-accent":At,color:He,width:Me,maxWidth:zt,height:Fe,maxHeight:Ke,boxSizing:"border-box",display:"flex",flexDirection:"column",background:B?Rn:io,borderRadius:!R&&we?we.panelBorderRadius:"12px",padding:B?0:R?"6px":0,boxShadow:je?"none":B?dr:"none",border:je||!B&&H==="input"?"none":`1px solid ${lr}`,overflow:"hidden",minHeight:R?0:void 0},children:[n.jsx("style",{children:Gr}),et&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:R?"8px 10px":"14px 20px",background:In,color:He,borderBottom:`1px solid ${Gt}`,flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px",minWidth:0},children:[n.jsx("div",{style:{width:R?26:32,height:R?26:32,flexShrink:0,borderRadius:"6px",background:Le(He,.04),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:At,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:dt,padding:4}}):n.jsx(Un,{size:R?14:17,strokeWidth:1.5,"aria-hidden":"true"})}),(w||g)&&n.jsxs("div",{style:{minWidth:0,overflowWrap:"anywhere"},children:[w&&n.jsx("div",{style:{fontSize:R?"13px":"14px",fontWeight:600,lineHeight:1.1,letterSpacing:0},children:i}),g&&n.jsx("div",{style:{fontSize:R?"10px":"12px",color:Tn,marginTop:"2px"},children:ar})]})]}),B&&(!R||v)&&n.jsx("button",{type:"button",onClick:()=>at(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"8px",border:`1px solid ${Gt}`,background:dt,color:Tn,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(fr,{size:16,strokeWidth:1.5,"aria-hidden":"true"})})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:he?"2px":R?"6px":"16px",minHeight:0,flex:R||B?"1 1 0":void 0,overflow:R||B?"hidden":void 0,overscrollBehavior:"contain",padding:B||H==="always"?R?"8px":"20px":R?"4px":"8px",justifyContent:B?void 0:"center",background:Rn},children:[ur("default"),ze&&go(R),H==="always"&&n.jsxs(n.Fragment,{children:[R&&!B&&!he&&n.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),R&&!B&&P&&j&&Pe.length===0&&n.jsx("div",{style:{fontSize:15,fontWeight:600,textAlign:"center"},children:z}),mo(R)]}),(H==="input"||!R||B||p)&&n.jsx(Ss,{value:Ae,onChange:bt,open:H==="input"&&st&&(B||!q),onOpenChange:H==="input"?Mt:Es,suggestions:Ue.slice(0,Y),registerSuggestion:sn,loading:pe,analyzing:tn,compact:R,expanded:B,showLogo:!B,suggestionPlacement:te,logoUrl:d,title:i,placeholder:M,colors:{accent:At,accentText:yn,surface:cr,text:He,muted:Kt,border:ct},onStop:jn,onSend:()=>{Xe.current=null,wt.current=!1,at(!0),_==="floating"&&Ft(!0),Ot(Ae)},onSuggestion:Nt=>{at(!0),_==="floating"&&Ft(!0),dn(Nt)}}),B&&mr("default",R),!B&&H==="always"&&po(R)]})]})};const y={position:"fixed",inset:0,background:uo,backdropFilter:"blur(2px)",zIndex:2147483e3};return _==="inline"?ke?n.jsxs("div",{ref:qt,className:"admesh-component","data-admesh-theme":de,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-behavior":m,"data-admesh-ad-slot-expanded":Cn?"true":"false",style:{width:Pt,height:en,maxWidth:Pt,maxHeight:en,position:"relative",overflow:"hidden"},children:[b(!1),Zt&&typeof document<"u"&&r(b(!0))]}):n.jsxs("div",{className:"admesh-component","data-admesh-theme":de,style:{width:"100%",position:"relative"},children:[b(!1),q&&typeof document<"u"&&r(b(!0))]}):De?n.jsxs("div",{className:"admesh-component","data-admesh-theme":de,children:[!q&&n.jsx("div",{style:{position:"fixed",...bn,zIndex:2147483001},children:b(!1)}),q&&typeof document<"u"&&r(b(!0))]}):n.jsx("div",{className:"admesh-component","data-admesh-theme":de,children:n.jsxs("button",{type:"button",onClick:Zn,style:{position:"fixed",...bn,zIndex:2147483e3,border:"none",borderRadius:"6px",background:E.primaryColor,color:yn,display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",fontWeight:600,padding:"12px 16px",boxShadow:"0 4px 16px rgba(15, 23, 42, 0.12)",cursor:"pointer"},children:[n.jsx(Un,{size:16,strokeWidth:1.5,"aria-hidden":"true"}),s]})})}return Ue.length===0&&!tn?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):_==="inline"?n.jsx("div",{className:"admesh-component","data-admesh-theme":de,children:n.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:mn(f)??"100%",backgroundColor:"#eef2ff",fontSize:ye.base,...o},children:n.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[tn?Dn("legacy"):Ue.length>0&&n.jsx("div",{className:"flex flex-col gap-3",children:Ue.slice(0,Y).map((r,b)=>n.jsxs("button",{ref:sn(r.id),onClick:()=>dn(r),className:"rounded-full px-5 py-4 text-left shadow-sm transition-transform duration-200 hover:scale-[1.01] active:scale-[0.99]",style:{width:b===0?"100%":b===1?"82%":"68%",backgroundColor:E.surfaceColor||"#ffffff",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:ye.sm},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},r.id))}),Pe.length>0&&n.jsxs("div",{ref:ae,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:E.textColor,overscrollBehavior:"contain",WebkitOverflowScrolling:"touch"},children:[Pe.map(r=>{const b=r.role==="user"&&r.id===rt.current;return n.jsx("div",{ref:b?_t:void 0,className:r.role==="user"?"text-right":"text-left",children:n.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:r.role==="user"?E.primaryColor:"#ffffff",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,fontSize:ye.sm},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx(Wn,{content:r.content,theme:E,fontSize:ye.sm}),En(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):pe&&r.id===Je.current?cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:r.content})})},r.id)}),pe&&!Pe.some(r=>r.role==="assistant"&&r.id===Je.current&&!r.content.trim())&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})}),jt&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:"Connection issue. Please try again."}),n.jsx("div",{ref:kt})]}),n.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"text",value:Ae,onChange:r=>bt(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(pe){r.preventDefault();return}Ot(Ae)}},placeholder:M,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textColor,fontSize:ye.sm}}),n.jsx("button",{onClick:()=>{if(pe){jn();return}Ot(Ae)},disabled:!pe&&!Ae.trim(),className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50",style:{backgroundColor:pe?"#dc2626":E.primaryColor,color:"#ffffff"},children:pe?n.jsx(zn,{size:18}):n.jsx(gr,{size:18})})]})}),n.jsxs("div",{className:"space-y-2 text-center",children:[n.jsxs("p",{style:{color:E.textSecondaryColor,fontSize:ye.xs,fontWeight:600},children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),n.jsx("p",{style:{color:E.textSecondaryColor,fontSize:ye.xs,lineHeight:1.5},children:nr})]})]})})}):De?n.jsx("div",{className:"admesh-component","data-admesh-theme":de,children:n.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...q?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...bn,width:mn(f)??tr.width,height:mn(h)??tr.height},backgroundColor:q?Rn:E.backgroundColor,zIndex:9999,fontSize:ye.base,borderRadius:q?"20px":"16px",border:q?`1px solid ${lr}`:"1px solid transparent",boxShadow:q?dr:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[u&&n.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between p-4 border-b",style:{position:"sticky",top:0,zIndex:10,borderColor:q?Gt:"transparent",background:q?In:E.backgroundColor,padding:q?"18px 20px":"16px"},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{style:{width:q?40:32,height:q?40:32,borderRadius:q?"14px":"10px",background:Le(Ve,.08),color:At,display:"flex",alignItems:"center",justifyContent:"center",fontSize:q?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(w||g&&q)&&n.jsxs("div",{children:[w&&n.jsx("div",{className:"font-medium",style:{color:E.textColor,fontSize:q?"20px":ye.base,fontWeight:700,letterSpacing:q?"-0.02em":0},children:i}),g&&q&&n.jsx("div",{style:{color:Tn,fontSize:"12px",marginTop:"2px"},children:ar})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[!ke&&n.jsx("button",{onClick:ro,className:"transition-colors",title:q?"Minimize":"Expand",style:{width:q?36:28,height:q?36:28,borderRadius:q?"12px":"10px",border:`1px solid ${q?Gt:"transparent"}`,background:q?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:q?n.jsx(fr,{size:16,style:{color:E.textSecondaryColor}}):n.jsx(To,{size:16,style:{color:E.textSecondaryColor}})}),n.jsx("button",{onClick:no,className:"transition-colors",style:{width:q?36:28,height:q?36:28,borderRadius:q?"12px":"10px",border:`1px solid ${q?Gt:"transparent"}`,background:q?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(zn,{size:16,style:{color:E.textSecondaryColor}})})]})]}),n.jsxs("div",{ref:ae,className:"flex-1 min-h-0 overflow-y-auto p-4",style:{flex:"1 1 0%",minHeight:0,overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",padding:q?"20px":"16px"},children:[ur("legacy"),P&&Pe.length===0&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",children:n.jsx("p",{style:{color:E.textColor,margin:0,fontSize:ye.sm},children:z})})}),Pe.map(r=>{const b=r.role==="user"&&r.id===rt.current;return n.jsxs("div",{ref:b?_t:void 0,className:"mb-3",children:[n.jsx("div",{className:r.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:r.role==="user"?lo:"transparent",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,border:"none",borderRadius:r.role==="user"?q?"14px":"12px":0,padding:r.role==="user"?q?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{fontSize:`calc(${ye.sm} * 1.3)`,lineHeight:1.65},children:n.jsx(Wn,{content:r.content,theme:E,fontSize:`calc(${ye.sm} * 1.3)`})}),En(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):pe&&r.id===Je.current?cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,fontSize:ye.sm,lineHeight:"1.4"},children:r.content})}),r.role==="assistant"&&!yt.has(r.id)&&n.jsx(nn,{messageId:r.id,query:r.userQuery,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}}),r.role==="assistant"&&yt.has(r.id)&&r.initialRecommendation&&!pe&&n.jsxs("div",{className:"mb-4",children:[n.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),n.jsx(nn,{messageId:r.id,query:r.userQuery,initialRecommendation:r.initialRecommendation,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}})]})]},r.id)}),pe&&!Pe.some(r=>r.role==="assistant"&&r.id===Je.current&&!r.content.trim())&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})})}),jt&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textSecondaryColor},children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{style:{fontSize:ye.xs},children:"โ ๏ธ"}),n.jsx("span",{style:{fontSize:ye.sm},children:"Connection issue. Please try again."})]})})}),n.jsx("div",{ref:kt})]}),Pe.length===0&&tn&&n.jsx("div",{className:"px-4 pb-2",children:Dn("legacy")}),Ue.length>0&&Pe.length===0&&!tn&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:Ue.slice(0,Y).map(r=>n.jsxs("button",{ref:sn(r.id),onClick:()=>dn(r),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:E.surfaceColor||"#f8fafc",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:ye.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b"},children:"Ad"})]},r.id))})}),re&&!ee&&xn.length===0&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:n.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:E.surfaceColor,borderColor:E.borderColor,color:E.textSecondaryColor},children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("span",{style:{fontSize:ye.sm},children:"Intent analysis failed"}),n.jsx("button",{onClick:Ie,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:E.primaryColor,color:"#ffffff"},children:"Retry"})]}),n.jsx("span",{style:{fontSize:ye.xs},children:re})]})})}),n.jsxs("div",{className:"p-3 border-t",style:{borderColor:q?Gt:"transparent",padding:q?"18px 20px":void 0,background:q?In:void 0},children:[n.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${Gt}`,borderRadius:q?"16px":"12px",background:cr,boxShadow:q?co:"none",padding:q?"8px 8px 8px 14px":void 0},children:[n.jsx("input",{type:"text",value:Ae,onChange:r=>bt(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(pe){r.preventDefault();return}Ot(Ae)}},placeholder:M,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textColor,fontSize:q?"15px":ye.sm,"--tw-ring-color":E.primaryColor}}),n.jsx("button",{onClick:()=>{if(pe){jn();return}Ot(Ae)},disabled:!pe&&!Ae.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:pe?"#dc2626":E.primaryColor,color:"#ffffff",borderRadius:q?"12px":"10px",width:q?"46px":void 0,height:q?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:q?`0 10px 20px ${Le(Ve,.18)}`:"none"},children:pe?n.jsx(zn,{size:14}):n.jsx(gr,{size:14})})]}),mr("legacy")]})]})}):n.jsx("div",{className:"admesh-component","data-admesh-theme":de,children:n.jsx("button",{onClick:Zn,className:"flex items-center gap-2 px-4 py-3 rounded-full shadow-lg transition-all duration-200 hover:scale-105 active:scale-95",style:{position:"fixed",...bn,backgroundColor:E.primaryColor,color:"#ffffff",zIndex:9999,fontSize:ye.base,...o},children:n.jsx("span",{className:"font-medium",children:s})})})},wn="admesh:streamingStart",_n="admesh:streamingComplete";function Ws(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(wn,{detail:o});window.dispatchEvent(s),l.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function Bs(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(_n,{detail:s});window.dispatchEvent(i),l.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function Us(t,e,o){const s=i=>{const d=i;d.detail.messageId===t&&d.detail.sessionId===e&&(l.log("[StreamingEvents] ๐จ Received streamingStart event"),o(d.detail))};return window.addEventListener(wn,s),()=>{window.removeEventListener(wn,s)}}function Xr(t,e,o){l.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const d=i;l.log("[StreamingEvents] ๐จ Received streamingComplete event (checking match)",{receivedMessageId:d.detail.messageId,receivedSessionId:d.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:d.detail.messageId===t,sessionIdMatch:d.detail.sessionId===e}),d.detail.messageId===t&&d.detail.sessionId===e?(l.log("[StreamingEvents] โ
Event matched! Calling callback"),o(d.detail)):l.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(_n,s),()=>{l.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(_n,s)}}const vn=()=>{const t=new Set,e=new Map,o=d=>{const u=e.get(d);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(d))};return{startTracking:({exposureUrl:d,recommendationId:u,linkElement:w,sessionId:g,logPrefix:_="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!d||!w){_&&l.warn(`${_} โ ๏ธ Missing exposure tracking data`);return}const c=`${g||"anonymous"}::${u||d}`;if(t.has(c)||e.has(c))return;const m={observer:void 0,timeoutId:null,viewableStart:null},k=()=>{o(c),t.add(c),fetch(d,{method:"GET",keepalive:!0}).then(()=>{_&&l.log(`${_} โ
Exposure pixel fired`)}).catch(()=>{_&&l.warn(`${_} โ ๏ธ Failed to fire exposure pixel`),t.delete(c)})},j=new IntersectionObserver(p=>{p.forEach(x=>{x.intersectionRatio>=.5?m.viewableStart===null&&(m.viewableStart=performance.now(),m.timeoutId=setTimeout(k,1e3)):(m.viewableStart=null,m.timeoutId&&(clearTimeout(m.timeoutId),m.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});m.observer=j,j.observe(w),e.set(c,m)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},Hs=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:d=[],onLinksFound:u,onNoLinksFound:w,children:g})=>{const[_,c]=a.useState(!1),[m,k]=a.useState(!0),[j,p]=a.useState(!1),x=a.useRef(vn()),f=a.useRef(u),h=a.useRef(w),S=a.useRef(t),I=a.useRef(s),G=a.useRef(o),A=a.useRef(i);a.useEffect(()=>{f.current=u,h.current=w,S.current=t,I.current=s,G.current=o,A.current=i},[u,w,t,s,o,i]),a.useEffect(()=>()=>{x.current.cleanup()},[]);const C=a.useCallback(({exposureUrl:$,recommendationId:F,linkElement:P})=>{x.current.startTracking({exposureUrl:$,recommendationId:F,linkElement:P,sessionId:G.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),L=a.useCallback(()=>{l.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const $=document.getElementById(S.current);if(!$){l.warn("[FinalLinkDetectionCheck] โ Container not found"),c(!0),w();return}const F=new Kn({autoAddLabels:!0,fireExposurePixels:!0}),P=d.length>0?d:[];l.log(`[FinalLinkDetectionCheck] ๐ Using ${P.length} recommendations for link detection`),P.length>0&&process.env.NODE_ENV==="development"&&P.forEach((M,W)=>{var V,Y,U,H,te,ge,Z,ne,_e;l.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${W+1} (DEV):`,{recommendation_id:M==null?void 0:M.recommendation_id,click_url:((V=M==null?void 0:M.tracking)==null?void 0:V.click_url)||((U=(Y=M==null?void 0:M.recommendation)==null?void 0:Y.creative)==null?void 0:U.landing_page_url),format:(H=M==null?void 0:M.recommendation)==null?void 0:H.format,brand_name:(Z=(ge=(te=M.render)==null?void 0:te.creative)==null?void 0:ge.advertiser)==null?void 0:Z.brand_name,cta_url:(_e=(ne=M.render)==null?void 0:ne.creative)==null?void 0:_e.landing_page_url})});const z=F.scanAndProcessLinks($,P,({exposureUrl:M,recommendationId:W,linkElement:V})=>C({exposureUrl:M,recommendationId:W,linkElement:V}));l.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${z.length} links`),z.length>0?(l.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),p(!0),f.current(z.length)):(l.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${P.length} previous recommendation(s) if available)`),p(!1),h.current()),c(!0)}catch{l.error("[FinalLinkDetectionCheck] โ Error during final check"),c(!0),h.current()}},[C,d]);return a.useEffect(()=>{l.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:d.length});let $=null,F=!1;const P=Xr(e,o,z=>{l.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:z.messageId,sessionId:z.sessionId,timestamp:z.timestamp}),F=!0,$&&(clearTimeout($),$=null),k(!1),setTimeout(()=>{L()},100)});return $=setTimeout(()=>{F||(l.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),k(!1),setTimeout(()=>{L()},100))},5e3),()=>{l.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),$&&clearTimeout($),P()}},[e,o]),m?n.jsx(n.Fragment,{}):_?j?(l.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),n.jsx(n.Fragment,{})):(l.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),n.jsx(n.Fragment,{children:g})):n.jsx(n.Fragment,{})},qs=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:d,className:u,query:w,onFallbackChange:g,onWeaveAttempt:_,onWeaveOutcome:c})=>{var M,W;const{sessionId:m,sdk:k,language:j,location:p,userId:x,model:f,messages:h}=on(),S=a.useRef(null),I=`weave-ad-container-${t}`,G=a.useRef(vn()),A=a.useRef(!1),C=a.useRef(null),[L,$]=a.useState([]),F=a.useRef([]);a.useEffect(()=>(C.current||(C.current=new Kn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{C.current&&(C.current.stopWatching(),C.current.clearCache())}),[]),a.useEffect(()=>()=>{G.current.cleanup()},[]),a.useEffect(()=>{(async()=>{var Y;if(!k||!(w!=null&&w.trim())||!t){l.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{l.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const U=await k.fetchPlatformResponse({query:w.trim(),sessionId:m,messageId:t,language:j,location:p,userId:x,model:f,messages:h}),H=(U==null?void 0:U.status)==="generated"?[U]:[];if($(H),F.current=H,l.log("[WeaveAdFormatContainer] ๐ฅ Got platform response:",{status:U==null?void 0:U.status,recommendationId:U==null?void 0:U.recommendation_id,hasRecommendation:!!(U!=null&&U.recommendation),format:(Y=U==null?void 0:U.recommendation)==null?void 0:Y.format}),U!=null&&U.recommendation){const te=U.recommendation.creative,ge=te.landing_page_url;l.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:te.brand_name,headline:te.headline,description:te.description,brandUrl:ge})}else l.log("[WeaveAdFormatContainer] โ ๏ธ No recommendation found in platform response")}catch(U){l.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",U),$([])}})()},[k,m,t,w]),a.useEffect(()=>{const V=S.current;if(!V||!C.current)return;const Y=C.current,U=({exposureUrl:ge,recommendationId:Z,linkElement:ne})=>{G.current.startTracking({exposureUrl:ge,recommendationId:Z,linkElement:ne,sessionId:m,logPrefix:"[WeaveAdFormatContainer]"})},te=setTimeout(()=>{l.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),_==null||_(t);const ge=F.current.length>0?F.current:[];l.log(`[WeaveAdFormatContainer] ๐ Using ${ge.length} recommendations for link detection`);try{const Z=Y.scanAndProcessLinks(V,ge,U);Z.length>0&&!A.current?(A.current=!0,l.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${Z.length} links detected`),c==null||c(t,!0,`Found ${Z.length} links`),s==null||s(Z.length),g==null||g(!1)):A.current||l.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(Z){const ne=Z instanceof Error?Z.message:String(Z);l.error(`[WeaveAdFormatContainer] โ Weave injection failed: ${ne}`),c==null||c(t,!1,ne),i==null||i(),g==null||g(!0)}},100);return Y.watchForNewLinks(V,F.current,U),()=>{clearTimeout(te),Y.stopWatching()}},[e,m,t,s,g,_,c]);const P=(W=(M=L[0])==null?void 0:M.recommendation)==null?void 0:W.format,z=P==="weave";return a.useEffect(()=>{w&&z&&l.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${P}) - skipping fallback recommendations`)},[w,z,P]),n.jsxs(n.Fragment,{children:[n.jsx("div",{ref:S,id:I,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),w&&!z&&n.jsx(Hs,{containerId:I,messageId:t,sessionId:m,sdk:k,query:w,recommendations:L,onLinksFound:V=>{l.log(`[WeaveAdFormatContainer] โ
Links found (${V}) - no fallback needed`),c==null||c(t,!0,`Found ${V} links in final check`),s==null||s(V),g==null||g(!1)},onNoLinksFound:()=>{l.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),l.log(`[WeaveAdFormatContainer] ๐ Passing ${L.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),i==null||i(),g==null||g(!0)},children:n.jsx(qr,{format:o,messageId:t,query:w,fallback:!0,onError:d,previousRecommendations:L.length>0?L:void 0})})]})},Os=t=>{const{sdk:e,sessionId:o}=on(),s=a.useRef(!1),i=a.useRef(0),d=a.useRef(!1),u=a.useRef(!1),w=a.useRef(null),g=a.useRef(vn());a.useEffect(()=>()=>{g.current.cleanup()},[]);const _=a.useCallback(({exposureUrl:h,recommendationId:S,linkElement:I})=>{g.current.startTracking({exposureUrl:h,recommendationId:S,linkElement:I,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),c=a.useRef(Date.now()),m=a.useRef(0),k=a.useRef(null),j=a.useRef([]),p=a.useRef(300),x=a.useCallback(async()=>{var h,S,I,G;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const A=document.getElementById(t.llmOutputContainerId);if(!A)return;const C=(h=e.getWeaveProcessor)==null?void 0:h.call(e);if(!C)return;const L=C.scanAndProcessLinks(A,[],({exposureUrl:F,recommendationId:P,linkElement:z})=>_({exposureUrl:F,recommendationId:P,linkElement:z}));i.current=L.length;const $=L.length>0;if($&&!d.current)d.current=!0,(S=t.onLinksDetected)==null||S.call(t,L.length),u.current=!0;else if(!$&&d.current)d.current=!1,u.current=!1;else if(!$&&!u.current){w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current),m.current=0,c.current=Date.now();const F=Math.max(100,p.current/3);k.current=setInterval(()=>{var W;const z=Date.now()-c.current,M=p.current;z>=M?(m.current++,m.current>=2&&(k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((W=t.onNoLinksDetected)==null||W.call(t),u.current=!0))):m.current=0},F);const P=Math.max(1500,p.current*5);w.current=setTimeout(()=>{var z;k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((z=t.onNoLinksDetected)==null||z.call(t),u.current=!0)},P)}else $&&u.current&&!d.current&&(w.current&&(clearTimeout(w.current),w.current=null),d.current=!0,(I=t.onLinksDetected)==null||I.call(t,L.length),u.current=!0)}catch(A){const C=A instanceof Error?A:new Error(String(A));(G=t.onError)==null||G.call(t,C)}finally{s.current=!1}}},[e,o,t,_]),f=a.useCallback(()=>{const h=j.current;if(h.length<2){p.current=300;return}const S=[];for(let A=1;A<h.length;A++)S.push(h[A]-h[A-1]);const I=S.reduce((A,C)=>A+C,0)/S.length,G=Math.max(100,Math.min(I*3,1e3));p.current=G},[]);return a.useEffect(()=>{const h=document.getElementById(t.llmOutputContainerId);if(!h)return;x();const S=new MutationObserver(()=>{const I=Date.now();c.current=I,m.current=0,j.current.push(I),j.current.length>10&&j.current.shift(),f(),x()});return S.observe(h,{childList:!0,subtree:!0,characterData:!1}),()=>{S.disconnect(),w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current)}},[t.llmOutputContainerId,x,f]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:d.current,shouldRenderFallback:!d.current&&u.current,processWeaveFormat:x}},Vs="1.0.31";exports.AdMeshBadge=Kr;exports.AdMeshCompactCard=qn;exports.AdMeshContext=On;exports.AdMeshFollowup=Hr;exports.AdMeshIntentAssistant=Fs;exports.AdMeshLayout=Nr;exports.AdMeshLinkTracker=Vr;exports.AdMeshProvider=Br;exports.AdMeshRecommendations=nn;exports.AdMeshRenderer=Ur;exports.AdMeshSDK=pn;exports.AdMeshTailAd=xs;exports.AdMeshTracker=$r;exports.AdMeshViewabilityTracker=hn;exports.STREAMING_COMPLETE_EVENT=_n;exports.STREAMING_START_EVENT=wn;exports.VERSION=Vs;exports.WeaveAdFormatContainer=qs;exports.WeaveAdFormatProvider=ms;exports.WeaveFallbackRecommendations=qr;exports.WeaveResponseProcessor=Kn;exports.callAnalyzeIntentEndpoint=Fr;exports.createInlineExposureTracker=vn;exports.dispatchStreamingCompleteEvent=Bs;exports.dispatchStreamingStartEvent=Ws;exports.extractHeadingsDirectly=Lr;exports.onStreamingComplete=Xr;exports.onStreamingStart=Us;exports.useAdMesh=on;exports.useAdMeshContext=Vn;exports.useAdMeshStyles=Yr;exports.useViewabilityTracker=zr;exports.useWeaveAdFormat=Os;exports.useWeaveAdFormatContext=ps;
|
|
1183
1183
|
//# sourceMappingURL=index.js.map
|