admesh-ui-sdk 1.0.42 โ 1.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/AdMeshIntentAssistant.d.ts +11 -0
- package/dist/components/AdMeshIntentAssistant.d.ts.map +1 -1
- package/dist/index.js +34 -34
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2973 -2930
- package/dist/index.mjs.map +1 -1
- package/dist/publisher-assistant.js +45 -45
- package/dist/publisher-assistant.js.map +1 -1
- package/dist/publisherAssistantEmbed.d.ts +5 -1
- package/dist/publisherAssistantEmbed.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,79 +1,79 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Yr=Object.defineProperty;var Qr=(t,e,o)=>e in t?Yr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var Ke=(t,e,o)=>Qr(t,typeof e!="symbol"?e+"":e,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),Xr=require("react-dom/client"),l=require("react"),yr=require("react-dom");let Ft=!1;var br;try{typeof globalThis.importMeta<"u"&&((br=globalThis.importMeta.env)!=null&&br.PROD)&&(Ft=!0)}catch{}Ft||(Ft=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const a={log:(...t)=>{Ft||console.log(...t)},warn:(...t)=>{Ft||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{Ft||console.info(...t)},debug:(...t)=>{Ft||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 _r=(...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 Jr=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 Zr=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 nr=t=>{const e=Zr(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 eo={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 to=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 no=l.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:o=2,absoluteStrokeWidth:s,className:i="",children:d,iconNode:u,...w},b)=>l.createElement("svg",{ref:b,...eo,width:e,height:e,stroke:t,strokeWidth:s?Number(o)*24/Number(e):o,className:_r("lucide",i),...!d&&!to(w)&&{"aria-hidden":"true"},...w},[...u.map(([k,c])=>l.createElement(k,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 Bt=(t,e)=>{const o=l.forwardRef(({className:s,...i},d)=>l.createElement(no,{ref:d,iconNode:e,className:_r(`lucide-${Jr(nr(t))}`,`lucide-${t}`,s),...i}));return o.displayName=nr(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 ro=[["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"}]],oo=Bt("flag",ro);/**
|
|
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 so=[["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"}]],io=Bt("maximize-2",so);/**
|
|
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 ao=[["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"}]],lo=Bt("minimize-2",ao);/**
|
|
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 co=[["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"}]],rr=Bt("send",co);/**
|
|
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 uo=[["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"}]],or=Bt("thumbs-down",uo);/**
|
|
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 mo=[["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"}]],sr=Bt("thumbs-up",mo);/**
|
|
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 co=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],wn=Ft("x",co);function uo(t,e,o){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...o}}function mo(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function po(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,i=e.height,c=e.width;if(i===0||c===0)return 0;const u=Math.max(0,e.top),y=Math.min(o,e.bottom),g=Math.max(0,e.left),v=Math.min(s,e.right),d=Math.max(0,y-u),h=Math.max(0,v-g),w=d*h,C=i*c;return C>0?w/C:0}function tr(){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 ho(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 fo(t){const e=t.getBoundingClientRect(),o=ho(t),s=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,c=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:mo(s),viewportWidth:s,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:c,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function go(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function xo(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function nr(t=new Date){return t.toISOString()}function bo(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function rr(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 _o=yo,wo=!1;function fr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:i,config:c}){const u={..._o,...c},y=l.useRef(go()),[g,v]=l.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:nr(),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}),d=l.useRef(null),h=l.useRef(null),w=l.useRef(null),C=l.useRef(null),m=l.useRef(null),b=l.useRef([]),f=l.useRef([]),p=l.useRef(null),E=l.useCallback(S=>{u.debug&&a.log(`[AdMesh Viewability] ${S}`)},[u.debug]),I=l.useCallback(async(S,L)=>{if(!(!u.enabled||wo||!i.current||!d.current)&&(E(`Analytics disabled - skipping event: ${S}`),u.onEvent)){const N=fo(i.current),B={eventType:S,timestamp:nr(),sessionId:y.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:g.timeMetrics,engagementMetrics:g.engagementMetrics,contextMetrics:N,mrcStandards:d.current,isViewable:g.isViewable,metadata:L};u.onEvent(B)}},[u,t,e,o,s,i,g,E]),G=l.useCallback(async()=>{f.current.length!==0&&(E("Analytics disabled - clearing batch without sending"),f.current=[],p.current&&(clearTimeout(p.current),p.current=null))},[E]),k=l.useCallback(rr(()=>{if(!i.current)return;const S=po(i.current),L=Date.now(),N=new Date(g.timeMetrics.loadedAt).getTime();v(B=>{const $={...B};S>0&&b.current.push(S);const z=B.isVisible,D=S>0;if(D&&!z)h.current=L,$.engagementMetrics.viewportEnterCount++,$.timeMetrics.timeToFirstVisible||($.timeMetrics.timeToFirstVisible=L-N,$.engagementMetrics.scrollDepthAtFirstVisible=tr(),I("ad_visible"));else if(!D&&z){if(h.current){const Q=L-h.current;$.timeMetrics.totalVisibleDuration+=Q,h.current=null}$.engagementMetrics.viewportExitCount++,I("ad_hidden")}else if(D&&z&&h.current){const Q=L-h.current;$.timeMetrics.totalVisibleDuration+=Q,h.current=L}if($.isVisible=D,$.visibilityPercentage=S,S>$.engagementMetrics.maxVisibilityPercentage&&($.engagementMetrics.maxVisibilityPercentage=S),b.current.length>0&&($.engagementMetrics.averageVisibilityPercentage=bo(b.current)),d.current){const Q=B.isViewable,J=xo(S,$.timeMetrics.totalVisibleDuration,d.current);if(J&&!Q)$.isViewable=!0,$.timeMetrics.timeToViewable=L-N,w.current=L,I("ad_viewable");else if(J&&Q&&w.current){const ge=L-w.current;$.timeMetrics.totalViewableDuration+=ge,w.current=L}}return $.engagementMetrics.currentScrollDepth=tr(),$})},100),[i,g.timeMetrics.loadedAt,I]);return l.useEffect(()=>{if(!i.current)return;const S=i.current.getBoundingClientRect();d.current=uo(S.width,S.height,u.mrcStandards),E("Initialized MRC standards"),I("ad_loaded")},[i,u.mrcStandards,E,I]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=new IntersectionObserver(L=>{L.forEach(()=>{k()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return S.observe(i.current),()=>{S.disconnect()}},[u.enabled,i,k]),l.useEffect(()=>{if(!u.enabled)return;const S=rr(()=>{k()},100);return window.addEventListener("scroll",S,{passive:!0}),()=>window.removeEventListener("scroll",S)},[u.enabled,k]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{C.current=Date.now(),v(B=>({...B,engagementMetrics:{...B.engagementMetrics,hoverCount:B.engagementMetrics.hoverCount+1}})),I("ad_hover_start")},N=()=>{if(C.current){const B=Date.now()-C.current;v($=>({...$,timeMetrics:{...$.timeMetrics,totalHoverDuration:$.timeMetrics.totalHoverDuration+B}})),C.current=null,I("ad_hover_end",{hoverDuration:B})}};return S.addEventListener("mouseenter",L),S.addEventListener("mouseleave",N),()=>{S.removeEventListener("mouseenter",L),S.removeEventListener("mouseleave",N)}},[u.enabled,i,I]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{m.current=Date.now(),I("ad_focus")},N=()=>{if(m.current){const B=Date.now()-m.current;v($=>({...$,timeMetrics:{...$.timeMetrics,totalFocusDuration:$.timeMetrics.totalFocusDuration+B}})),m.current=null,I("ad_blur",{focusDuration:B})}};return S.addEventListener("focus",L),S.addEventListener("blur",N),()=>{S.removeEventListener("focus",L),S.removeEventListener("blur",N)}},[u.enabled,i,I]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{v(N=>({...N,engagementMetrics:{...N.engagementMetrics,wasClicked:!0}})),I("ad_click")};return S.addEventListener("click",L),()=>{S.removeEventListener("click",L)}},[u.enabled,i,I]),l.useEffect(()=>()=>{const S=Date.now(),L=new Date(g.timeMetrics.loadedAt).getTime(),N=S-L;v(B=>({...B,timeMetrics:{...B.timeMetrics,sessionDuration:N}})),I("ad_unloaded",{sessionDuration:N}),G()},[]),g}const Zt=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:i,sessionId:c,triggerExposureUrl:u=!0,children:y,config:g,className:v,style:d,onViewabilityChange:h,onVisible:w,onViewable:C,onClick:m})=>{const b=l.useRef(null),f=l.useRef(!1),p=fr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:b,config:g}),E=l.useRef(p.isViewable);l.useEffect(()=>{f.current=!1,E.current=!1},[i,s,c]),l.useEffect(()=>{p.isViewable!==E.current&&(E.current=p.isViewable,h&&h(p.isViewable),p.isViewable&&C&&C(),p.isViewable&&!f.current&&u&&(a.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:i?"present":"MISSING",sessionId:c?"present":"MISSING",recommendationId:s}),i&&c?(f.current=!0,a.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",i),fetch(i,{method:"GET",keepalive:!0}).then(()=>{a.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(k=>{a.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",k),f.current=!1})):a.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!i,hasSessionId:!!c})))},[p.isViewable,h,C,i,c,s,u]);const I=l.useRef(p.isVisible);l.useEffect(()=>{p.isVisible!==I.current&&(I.current=p.isVisible,p.isVisible&&w&&w())},[p.isVisible,w]);const G=()=>{m&&m()};return r.jsx("div",{ref:b,className:v,style:d,onClick:G,"data-admesh-viewability-tracker":!0,"data-recommendation-id":s,"data-is-viewable":p.isViewable,"data-is-visible":p.isVisible,"data-visibility-percentage":p.visibilityPercentage.toFixed(2),children:y})};Zt.displayName="AdMeshViewabilityTracker";const or=t=>{try{return new URL(t),!0}catch{return!1}},Ut=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",lt=t=>Ut(t)||void 0,vo=t=>t&&t.trim()?t.trim():"",ko=(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 Ut(t)},jn=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:c=!0,onDelegationConsent:u,onDelegationActivated:y,onStartDelegation:g,onRecommendationReport:v})=>{var jt,ut,Et,_t,mt,Rt,st,Ve,ze;if(!t||t.length===0)return a.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const d=t[0],h=d==null?void 0:d.recommendation,w=h==null?void 0:h.creative,C=d==null?void 0:d.tracking,m=d==null?void 0:d.delegation,b=(d==null?void 0:d.recommendation_id)||"",f=(h==null?void 0:h.offerId)||"",p=(w==null?void 0:w.brand_name)||"",E=(w==null?void 0:w.headline)||"",I=(w==null?void 0:w.description)||"",G=(w==null?void 0:w.logo_url)||"",k=(C==null?void 0:C.click_url)||(w==null?void 0:w.landing_page_url)||"",S=(C==null?void 0:C.exposure_url)||"",L=(h==null?void 0:h.disclosure)||"Sponsored",N=(w==null?void 0:w.products)||[],B=N.slice(0,4),$=N.length>1,D=((h==null?void 0:h.format)||"tail")==="bridge",Q=(m==null?void 0:m.available)===!0,J=D&&Q,ge=(m==null?void 0:m.brand_name)||p,V="Talk to Agent",ee=vo(w==null?void 0:w.cta_text),me=!$&&!!ee&&!!k;if(!p&&!E&&!I)return a.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:b}),null;const xe=E&&E!==p?E:p,q=I,oe=p.trim().toLowerCase(),ve=xe.trim().toLowerCase(),Ne=!!p&&oe!==ve,[Pe,be]=l.useState(!1),[we,Se]=l.useState(!1),[_e,Fe]=l.useState(null),Ee=l.useRef(null);l.useEffect(()=>()=>{Ee.current&&(Ee.current(!1),Ee.current=null)},[]);const rt=O=>{var fe;(fe=Ee.current)==null||fe.call(Ee,O),Ee.current=null,be(!1)},F=async()=>u?await u(d):await new Promise(O=>{Ee.current=O,be(!0)}),_=(O,fe)=>{fe&&fe.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:b,productId:f,clickUrl:k,source:O}).catch(()=>{a.error(`[AdMesh] Failed to track ${O} click`)})},H=[{value:"irrelevant",label:"Not relevant"},{value:"misleading",label:"Misleading"},{value:"inappropriate",label:"Inappropriate"},{value:"broken_link",label:"Broken link"},{value:"other",label:"Other"}],A=O=>{O.preventDefault(),O.stopPropagation(),!_e&&Se(fe=>!fe)},ie=async(O,fe)=>{if(O.preventDefault(),O.stopPropagation(),Se(!1),Fe(fe),!!v)try{await v({recommendation:d,recommendation_id:b,reason:fe,session_id:i})}catch(Ue){a.warn("[AdMesh Compact Tail Ad] Failed to submit recommendation report:",Ue)}},ke=()=>{$||!k||(_("compact_tail_ad_card"),typeof window<"u"&&window.open(k,"_blank","noopener,noreferrer"))},T=O=>{$||!k||(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),ke())},se=async()=>{if(b&&i)try{const O=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",fe=await fetch(`${O}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:b,session_id:i,is_test:!1})});fe.ok||a.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",fe.statusText)}catch(O){a.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",O)}},j=async O=>{if(O.preventDefault(),O.stopPropagation(),!d||!J||(_("compact_tail_ad_delegation_cta"),await se(),!await F()))return;const Ue=m!=null&&m.available?{recommendation_id:d.recommendation_id,brand_id:lt(m.brand_id),brand_name:lt(m.brand_name||(w==null?void 0:w.brand_name)),eligibility_reason:lt(m.eligibility_reason),delegate_reason:lt(m.delegate_reason),session_goal:lt(m.session_goal),desired_outcome_type:m.desired_outcome_type,required_user_inputs:Array.isArray(m.required_user_inputs)?m.required_user_inputs.filter(Ke=>typeof Ke=="string"):[],required_consent_types:Array.isArray(m.required_consent_types)?m.required_consent_types.filter(Ke=>typeof Ke=="string"):[],success_outcome:lt(m.success_outcome),fallback_message:lt(m.fallback_message),session_mode:lt(m.session_mode),status:lt(m.status),capabilities:m.capabilities||[],allowed_data_types:m.allowed_data_types||[],consent_requirements:m.consent_requirements||[],auth_model:lt(m.auth_model),handoff_protocol:m.handoff_protocol&&typeof m.handoff_protocol=="object"?m.handoff_protocol:void 0,supported_actions:m.supported_actions||[],metadata:m.metadata&&typeof m.metadata=="object"?m.metadata:void 0,platform_response:d}:null;if(y&&Ue){await y(Ue);return}if(g){await g(d);return}},[ce,re]=l.useState(!1),Y=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,K=(e==null?void 0:e.surfaceColor)||((ut=(jt=e==null?void 0:e.components)==null?void 0:jt.card)==null?void 0:ut.backgroundColor)||(Y?"#111827":"#ffffff"),ae=(e==null?void 0:e.borderColor)||((_t=(Et=e==null?void 0:e.components)==null?void 0:Et.card)==null?void 0:_t.borderColor)||(Y?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),Be=((mt=e==null?void 0:e.shadows)==null?void 0:mt.medium)||((st=(Rt=e==null?void 0:e.components)==null?void 0:Rt.card)==null?void 0:st.boxShadow)||(Y?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),Te="#2563eb",M=Y?"#9ca3af":"#6b7280",Ce=Y?"#e5e7eb":"#374151",Ie=Y?"#f9fafb":"#0f172a",ot=Y?"rgba(255, 255, 255, 0.04)":"#f8fafc",yt="50px",et=J||me?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[J?r.jsx("button",{type:"button",onClick:j,style:{background:"none",border:"none",padding:0,color:Te,fontSize:"12px",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:V}):null,me?r.jsx("a",{href:k,target:"_blank",rel:"noopener noreferrer",onClick:O=>_("compact_tail_ad_cta",O),style:{color:Te,fontSize:"12px",fontWeight:600,textDecoration:"none"},children:ee}):null]}):null;return r.jsxs(Zt,{productId:f,recommendationId:b,exposureUrl:S,sessionId:i,triggerExposureUrl:c,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:[r.jsx("style",{children:`
|
|
76
|
+
*/const po=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Mn=Bt("x",po);function ho(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 go(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),b=Math.max(0,e.left),k=Math.min(s,e.right),c=Math.max(0,w-u),g=Math.max(0,k-b),S=c*g,M=i*d;return M>0?S/M:0}function ir(){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 xo(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 bo(t){const e=t.getBoundingClientRect(),o=xo(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 yo(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function _o(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function ar(t=new Date){return t.toISOString()}function wo(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function lr(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,So=!1;function wr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:i,config:d}){const u={...ko,...d},w=l.useRef(yo()),[b,k]=l.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:ar(),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=l.useRef(null),g=l.useRef(null),S=l.useRef(null),M=l.useRef(null),f=l.useRef(null),y=l.useRef([]),x=l.useRef([]),h=l.useRef(null),E=l.useCallback(C=>{u.debug&&a.log(`[AdMesh Viewability] ${C}`)},[u.debug]),R=l.useCallback(async(C,D)=>{if(!(!u.enabled||So||!i.current||!c.current)&&(E(`Analytics disabled - skipping event: ${C}`),u.onEvent)){const P=bo(i.current),N={eventType:C,timestamp:ar(),sessionId:w.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:b.timeMetrics,engagementMetrics:b.engagementMetrics,contextMetrics:P,mrcStandards:c.current,isViewable:b.isViewable,metadata:D};u.onEvent(N)}},[u,t,e,o,s,i,b,E]),K=l.useCallback(async()=>{x.current.length!==0&&(E("Analytics disabled - clearing batch without sending"),x.current=[],h.current&&(clearTimeout(h.current),h.current=null))},[E]),A=l.useCallback(lr(()=>{if(!i.current)return;const C=go(i.current),D=Date.now(),P=new Date(b.timeMetrics.loadedAt).getTime();k(N=>{const T={...N};C>0&&y.current.push(C);const I=N.isVisible,$=C>0;if($&&!I)g.current=D,T.engagementMetrics.viewportEnterCount++,T.timeMetrics.timeToFirstVisible||(T.timeMetrics.timeToFirstVisible=D-P,T.engagementMetrics.scrollDepthAtFirstVisible=ir(),R("ad_visible"));else if(!$&&I){if(g.current){const G=D-g.current;T.timeMetrics.totalVisibleDuration+=G,g.current=null}T.engagementMetrics.viewportExitCount++,R("ad_hidden")}else if($&&I&&g.current){const G=D-g.current;T.timeMetrics.totalVisibleDuration+=G,g.current=D}if(T.isVisible=$,T.visibilityPercentage=C,C>T.engagementMetrics.maxVisibilityPercentage&&(T.engagementMetrics.maxVisibilityPercentage=C),y.current.length>0&&(T.engagementMetrics.averageVisibilityPercentage=wo(y.current)),c.current){const G=N.isViewable,X=_o(C,T.timeMetrics.totalVisibleDuration,c.current);if(X&&!G)T.isViewable=!0,T.timeMetrics.timeToViewable=D-P,S.current=D,R("ad_viewable");else if(X&&G&&S.current){const be=D-S.current;T.timeMetrics.totalViewableDuration+=be,S.current=D}}return T.engagementMetrics.currentScrollDepth=ir(),T})},100),[i,b.timeMetrics.loadedAt,R]);return l.useEffect(()=>{if(!i.current)return;const C=i.current.getBoundingClientRect();c.current=ho(C.width,C.height,u.mrcStandards),E("Initialized MRC standards"),R("ad_loaded")},[i,u.mrcStandards,E,R]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const C=new IntersectionObserver(D=>{D.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]),l.useEffect(()=>{if(!u.enabled)return;const C=lr(()=>{A()},100);return window.addEventListener("scroll",C,{passive:!0}),()=>window.removeEventListener("scroll",C)},[u.enabled,A]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,D=()=>{M.current=Date.now(),k(N=>({...N,engagementMetrics:{...N.engagementMetrics,hoverCount:N.engagementMetrics.hoverCount+1}})),R("ad_hover_start")},P=()=>{if(M.current){const N=Date.now()-M.current;k(T=>({...T,timeMetrics:{...T.timeMetrics,totalHoverDuration:T.timeMetrics.totalHoverDuration+N}})),M.current=null,R("ad_hover_end",{hoverDuration:N})}};return C.addEventListener("mouseenter",D),C.addEventListener("mouseleave",P),()=>{C.removeEventListener("mouseenter",D),C.removeEventListener("mouseleave",P)}},[u.enabled,i,R]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,D=()=>{f.current=Date.now(),R("ad_focus")},P=()=>{if(f.current){const N=Date.now()-f.current;k(T=>({...T,timeMetrics:{...T.timeMetrics,totalFocusDuration:T.timeMetrics.totalFocusDuration+N}})),f.current=null,R("ad_blur",{focusDuration:N})}};return C.addEventListener("focus",D),C.addEventListener("blur",P),()=>{C.removeEventListener("focus",D),C.removeEventListener("blur",P)}},[u.enabled,i,R]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const C=i.current,D=()=>{k(P=>({...P,engagementMetrics:{...P.engagementMetrics,wasClicked:!0}})),R("ad_click")};return C.addEventListener("click",D),()=>{C.removeEventListener("click",D)}},[u.enabled,i,R]),l.useEffect(()=>()=>{const C=Date.now(),D=new Date(b.timeMetrics.loadedAt).getTime(),P=C-D;k(N=>({...N,timeMetrics:{...N.timeMetrics,sessionDuration:P}})),R("ad_unloaded",{sessionDuration:P}),K()},[]),b}const Zt=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:i,sessionId:d,triggerExposureUrl:u=!0,children:w,config:b,className:k,style:c,onViewabilityChange:g,onVisible:S,onViewable:M,onClick:f})=>{const y=l.useRef(null),x=l.useRef(!1),h=wr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:y,config:b}),E=l.useRef(h.isViewable);l.useEffect(()=>{x.current=!1,E.current=!1},[i,s,d]),l.useEffect(()=>{h.isViewable!==E.current&&(E.current=h.isViewable,g&&g(h.isViewable),h.isViewable&&M&&M(),h.isViewable&&!x.current&&u&&(a.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:i?"present":"MISSING",sessionId:d?"present":"MISSING",recommendationId:s}),i&&d?(x.current=!0,a.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",i),fetch(i,{method:"GET",keepalive:!0}).then(()=>{a.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(A=>{a.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",A),x.current=!1})):a.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!i,hasSessionId:!!d})))},[h.isViewable,g,M,i,d,s,u]);const R=l.useRef(h.isVisible);l.useEffect(()=>{h.isVisible!==R.current&&(R.current=h.isVisible,h.isVisible&&S&&S())},[h.isVisible,S]);const K=()=>{f&&f()};return r.jsx("div",{ref:y,className:k,style:c,onClick:K,"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})};Zt.displayName="AdMeshViewabilityTracker";const dr=t=>{try{return new URL(t),!0}catch{return!1}},qt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",pt=t=>qt(t)||void 0,Ao=t=>t&&t.trim()?t.trim():"",Co=(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 qt(t)},Pn=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:b,onRecommendationReport:k})=>{var F,rt,dt,At,Tt,ot,It,gt,Dt;if(!t||t.length===0)return a.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],g=c==null?void 0:c.recommendation,S=g==null?void 0:g.creative,M=c==null?void 0:c.tracking,f=c==null?void 0:c.delegation,y=(c==null?void 0:c.recommendation_id)||"",x=(g==null?void 0:g.offerId)||"",h=(S==null?void 0:S.brand_name)||"",E=(S==null?void 0:S.headline)||"",R=(S==null?void 0:S.description)||"",K=(S==null?void 0:S.logo_url)||"",A=(M==null?void 0:M.click_url)||(S==null?void 0:S.landing_page_url)||"",C=(M==null?void 0:M.exposure_url)||"",D=(g==null?void 0:g.disclosure)||"Sponsored",P=(S==null?void 0:S.products)||[],N=P.slice(0,4),T=P.length>1,$=((g==null?void 0:g.format)||"tail")==="bridge",G=(f==null?void 0:f.available)===!0,X=$&&G,be=(f==null?void 0:f.brand_name)||h,B="Talk to Agent",L=Ao(S==null?void 0:S.cta_text),ue=!T&&!!L&&!!A;if(!h&&!E&&!R)return a.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:y}),null;const _e=E&&E!==h?E:h,se=R,$e=h.trim().toLowerCase(),Me=_e.trim().toLowerCase(),qe=!!h&&$e!==Me,[Te,ne]=l.useState(!1),[ee,Ee]=l.useState(!1),[xe,Oe]=l.useState(null),Ce=l.useRef(null);l.useEffect(()=>()=>{Ce.current&&(Ce.current(!1),Ce.current=null)},[]);const nt=q=>{var ye;(ye=Ce.current)==null||ye.call(Ce,q),Ce.current=null,ne(!1)},z=async()=>u?await u(c):await new Promise(q=>{Ce.current=q,ne(!0)}),O=(q,ye)=>{ye&&ye.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:y,productId:x,clickUrl:A,source:q}).catch(()=>{a.error(`[AdMesh] Failed to track ${q} click`)})},V=[{value:"irrelevant",label:"Not relevant"},{value:"misleading",label:"Misleading"},{value:"inappropriate",label:"Inappropriate"},{value:"broken_link",label:"Broken link"},{value:"other",label:"Other"}],ie=q=>{q.preventDefault(),q.stopPropagation(),!xe&&Ee(ye=>!ye)},ae=async(q,ye)=>{if(q.preventDefault(),q.stopPropagation(),Ee(!1),Oe(ye),!!k)try{await k({recommendation:c,recommendation_id:y,reason:ye,session_id:i})}catch(st){a.warn("[AdMesh Compact Tail Ad] Failed to submit recommendation report:",st)}},Ae=()=>{T||!A||(O("compact_tail_ad_card"),typeof window<"u"&&window.open(A,"_blank","noopener,noreferrer"))},p=q=>{T||!A||(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),Ae())},J=async()=>{if(y&&i)try{const q=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",ye=await fetch(`${q}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:y,session_id:i,is_test:!1})});ye.ok||a.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",ye.statusText)}catch(q){a.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",q)}},j=async q=>{if(q.preventDefault(),q.stopPropagation(),!c||!X||(O("compact_tail_ad_delegation_cta"),await J(),!await z()))return;const st=f!=null&&f.available?{recommendation_id:c.recommendation_id,brand_id:pt(f.brand_id),brand_name:pt(f.brand_name||(S==null?void 0:S.brand_name)),eligibility_reason:pt(f.eligibility_reason),delegate_reason:pt(f.delegate_reason),session_goal:pt(f.session_goal),desired_outcome_type:f.desired_outcome_type,required_user_inputs:Array.isArray(f.required_user_inputs)?f.required_user_inputs.filter(Ye=>typeof Ye=="string"):[],required_consent_types:Array.isArray(f.required_consent_types)?f.required_consent_types.filter(Ye=>typeof Ye=="string"):[],success_outcome:pt(f.success_outcome),fallback_message:pt(f.fallback_message),session_mode:pt(f.session_mode),status:pt(f.status),capabilities:f.capabilities||[],allowed_data_types:f.allowed_data_types||[],consent_requirements:f.consent_requirements||[],auth_model:pt(f.auth_model),handoff_protocol:f.handoff_protocol&&typeof f.handoff_protocol=="object"?f.handoff_protocol:void 0,supported_actions:f.supported_actions||[],metadata:f.metadata&&typeof f.metadata=="object"?f.metadata:void 0,platform_response:c}:null;if(w&&st){await w(st);return}if(b){await b(c);return}},[he,ve]=l.useState(!1),oe=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,ze=(e==null?void 0:e.surfaceColor)||((rt=(F=e==null?void 0:e.components)==null?void 0:F.card)==null?void 0:rt.backgroundColor)||(oe?"#111827":"#ffffff"),me=(e==null?void 0:e.borderColor)||((At=(dt=e==null?void 0:e.components)==null?void 0:dt.card)==null?void 0:At.borderColor)||(oe?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),ke=((Tt=e==null?void 0:e.shadows)==null?void 0:Tt.medium)||((It=(ot=e==null?void 0:e.components)==null?void 0:ot.card)==null?void 0:It.boxShadow)||(oe?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),Ie="#2563eb",Y=oe?"#9ca3af":"#6b7280",Se=oe?"#e5e7eb":"#374151",H=oe?"#f9fafb":"#0f172a",Ge=oe?"rgba(255, 255, 255, 0.04)":"#f8fafc",lt="50px",St=X||ue?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[X?r.jsx("button",{type:"button",onClick:j,style:{background:"none",border:"none",padding:0,color:Ie,fontSize:"12px",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:B}):null,ue?r.jsx("a",{href:A,target:"_blank",rel:"noopener noreferrer",onClick:q=>O("compact_tail_ad_cta",q),style:{color:Ie,fontSize:"12px",fontWeight:600,textDecoration:"none"},children:L}):null]}):null;return r.jsxs(Zt,{productId:x,recommendationId:y,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:[r.jsx("style",{children:`
|
|
77
77
|
.admesh-compact-tail-ad,
|
|
78
78
|
.admesh-compact-tail-ad * {
|
|
79
79
|
box-sizing: border-box;
|
|
@@ -126,9 +126,9 @@
|
|
|
126
126
|
min-height: 34px;
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
|
-
`}),r.jsxs("div",{role:!$&&k?"link":void 0,tabIndex:!$&&k?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((ze=(Ve=e==null?void 0:e.components)==null?void 0:Ve.card)==null?void 0:ze.borderRadius)||"14px",border:`1px solid ${ae}`,background:K,boxShadow:Be,minWidth:0,cursor:!$&&k?"pointer":void 0},onClick:ke,onKeyDown:T,children:[r.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[r.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:Y?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!ce&&G&&or(G)?r.jsx("img",{src:G,alt:`${p} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>re(!0)}):r.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:M},children:(p||"A").charAt(0).toUpperCase()})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("div",{className:"admesh-compact-meta-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[r.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"11px",color:M},children:Ne?p:""}),r.jsx("span",{style:{flexShrink:0,fontSize:"10px",color:M,textTransform:"uppercase",letterSpacing:"0.08em"},children:L})]}),!$&&r.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",lineHeight:1.3,fontWeight:700,color:Ie,marginBottom:"4px"},title:xe,children:xe}),q&&r.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"12px",lineHeight:1.35,color:Ce},title:q,children:q})]})]}),$&&r.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:B.map(O=>{const fe=Ut(O.product_name)||"Product",Ue=Ut(O.product_link)||Ut(O.product_url)||k||"#",Ke=ko(O.product_price,O.product_currency),tt=Ut(O.product_image_url),pt=tt&&or(tt)?tt:"",wt=Ue!=="#";return r.jsx("a",{href:Ue,target:wt?"_blank":void 0,rel:wt?"noopener noreferrer":void 0,onClick:Tt=>_(`compact_tail_ad_product_${O.product_id||"item"}`,Tt),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${ae}`,borderRadius:"12px",background:ot,padding:"8px",flexShrink:0},children:r.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[r.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:Y?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:M,fontSize:"12px",fontWeight:700},children:pt?r.jsx("img",{src:pt,alt:fe,style:{width:"100%",height:"100%",objectFit:"cover"}}):fe.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("div",{style:{fontSize:"12px",lineHeight:1.25,fontWeight:600,color:Ie,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:fe,children:fe}),r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:Ke&&r.jsx("span",{style:{fontSize:"12px",fontWeight:700,color:Ie},children:Ke})})]})]})},O.product_id||`${b}-${fe}`)})}),r.jsxs("div",{className:"admesh-compact-footer-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:$?0:yt},children:[r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:et}),r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",marginLeft:"auto",flexShrink:0},children:[$&&N.length>B.length?r.jsxs("span",{style:{fontSize:"10px",color:M},children:["+",N.length-B.length," more"]}):null,r.jsx("button",{type:"button","aria-label":_e?"Recommendation reported":"Report recommendation",title:_e?"Reported":"Report recommendation",disabled:!!_e,onClick:A,style:{width:"28px",height:"28px",borderRadius:"999px",border:`1px solid ${ae}`,background:_e?ot:K,color:_e?Te:M,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,cursor:_e?"default":"pointer",flexShrink:0},children:r.jsx(to,{size:13})})]})]}),we?r.jsx("div",{className:"admesh-compact-report-panel",onClick:O=>O.stopPropagation(),style:{marginLeft:$?0:yt,border:`1px solid ${ae}`,borderRadius:"12px",background:ot,padding:"8px",display:"flex",flexWrap:"wrap",gap:"6px"},children:H.map(O=>r.jsx("button",{className:"admesh-compact-report-option",type:"button",onClick:fe=>ie(fe,O.value),style:{borderRadius:"999px",border:`1px solid ${ae}`,background:K,color:Ie,fontSize:"11px",fontWeight:600,padding:"6px 9px",cursor:"pointer"},children:O.label},O.value))}):null,_e?r.jsx("div",{className:"admesh-compact-report-status",style:{marginLeft:$?0:yt,fontSize:"11px",color:M},children:"Thanks for reporting this recommendation."}):null,Pe?r.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${ae}`,borderRadius:"12px",background:ot,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:Te},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:Ie,fontWeight:600},children:["Allow ",ge||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:Ce},children:"The agent will only use the details you choose to share for this request."})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[r.jsx("button",{type:"button",onClick:O=>{O.preventDefault(),O.stopPropagation(),rt(!1)},style:{borderRadius:"10px",border:`1px solid ${ae}`,background:K,color:Ie,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:O=>{O.preventDefault(),O.stopPropagation(),rt(!0)},style:{borderRadius:"10px",border:"none",background:Te,color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})},gr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:c,onDelegationActivated:u,onStartDelegation:y})=>{const g=t.filter(d=>d&&typeof d=="object"&&typeof d.recommendation_id=="string"&&d.recommendation_id.length>0);if(!g||g.length===0)return a.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;a.log(`[AdMeshLayout] Rendering with ${g.length} valid recommendations`);const v=()=>{var d;if(g.length>0){const h=g[0],w=(d=h.recommendation)==null?void 0:d.format;a.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:w,recommendationKeys:Object.keys(h||{})}),(w==="product_card"||w==="weave"||w==="bridge")&&a.warn(`[AdMeshLayout] ${w} format requested, falling back to tail for canonical render payload`)}return r.jsx(jn,{recommendations:g,theme:e,sessionId:i,onDelegationConsent:c,onDelegationActivated:u,onStartDelegation:y})};return r.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 xr{constructor(e){Oe(this,"firedExposures",new Set);Oe(this,"debug",!1);Oe(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&&a.log("[Tracker] Exposure already fired");return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&a.warn("[Tracker] Failed to fire exposure")}),this.debug&&a.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&a.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,i){const c=`${s}_${o}`;if(this.firedExposures.has(c)){this.debug&&a.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let y=null,g=null;const v=new IntersectionObserver(w=>{w.forEach(C=>{C.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?y===null&&(y=Date.now(),this.debug&&a.log("[Tracker] Ad reached MRC visibility threshold"),g=setTimeout(()=>{this.fireExposure(e,o,s),v.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):y!==null&&(g&&(clearTimeout(g),g=null),y=null,this.debug&&a.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 h=setTimeout(()=>{v.disconnect(),g&&clearTimeout(g),u()},3e4);i.__admeshTrackerCleanup=()=>{v.disconnect(),g&&clearTimeout(g),clearTimeout(h)}})}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&&a.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const En=l.createContext(void 0);function Rn(){const t=l.useContext(En);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function So(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,c=>c.toUpperCase()):"This page"}function br(){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"],d=["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(","),C=(((f=v.map(p=>document.querySelector(p)).filter(p=>!!p).map(p=>{const E=p.cloneNode(!0);E.querySelectorAll(d).forEach(G=>G.remove());const I=e(E.textContent||"");return{element:p,text:I}}).filter(p=>p.text.length>=200).sort((p,E)=>E.text.length-p.text.length)[0])==null?void 0:f.element)||document.body).cloneNode(!0);C.querySelectorAll(d).forEach(p=>p.remove());const m=Array.from(C.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(p=>e(p.textContent||"")).filter(p=>p.length>=24);return(m.length>0?m.join(`
|
|
130
|
-
`):e(
|
|
131
|
-
Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const Io=6e4,ar=3;function Do(t){const e=Ro();if(e)return e;const o=t==null?void 0:t.trim();return _r(o)?o:null}const wr=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:c,location:u,userId:y,model:g,messages:v,pageContext:d,articleUrl:h,contextMode:w="auto",agentDisplayId:C,children:m})=>{const[b,f]=l.useState(null),[p,E]=l.useState(new Set),[I,G]=l.useState(new Map),[k,S]=l.useState(null),[L,N]=l.useState([]),[B,$]=l.useState(!1),[z,D]=l.useState(null),[Q,J]=l.useState(!1),ge=l.useRef(!1),V=l.useRef(0),ee=l.useRef(null),me=l.useRef(null);me.current=k;const xe=!!d||w==="ad-slot"||w==="auto"&&(!!(h!=null&&h.trim())||Eo()),q=l.useCallback(async()=>{if(d)return d;if(!xe)return br();const F=Do(h);if(!F)return a.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),D("Article URL is required for ad-slot context"),null;if(!t||!i)return a.warn("[AdMeshProvider] Cannot fetch page context: missing API key or base URL"),ir(F);try{J(!0);const _=await jo(F,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:C});return a.log("[AdMeshProvider] Page context resolved",{source:_.source,cache_hit:_.cache_hit,domain:_.context.domain}),_.context}catch(_){return a.error("[AdMeshProvider] Failed to fetch page context:",_),a.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),ir(F)}finally{J(!1)}},[C,i,t,h,d,xe]),oe=l.useCallback((F,_)=>{const H=F.filter(A=>!A.is_sponsored).slice(0,3);return[_,...H]},[]),ve=l.useCallback((F,_)=>{const H=F.find(ie=>ie.is_sponsored),A=_.filter(ie=>!ie.is_sponsored).slice(0,3);return H?[H,...A]:A},[]);l.useEffect(()=>{if(!e||e.trim()===""){a.error("[AdMeshProvider] โ sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}a.log("[AdMeshProvider] โ
Session ID available:",e)},[e]),l.useEffect(()=>{if(!t){a.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){a.error("[AdMeshProvider] โ Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const F=new Jt({apiKey:t,theme:s,apiBaseUrl:i,extension:o});f(F),a.log("[AdMeshProvider] โ
AdMesh SDK initialized with session:",e),i&&a.log("[AdMeshProvider] ๐ Using custom API base URL")}catch(F){a.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK:",F)}return()=>{a.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,s,i,e,o]);const Ne=l.useCallback(async F=>{var _;if(!t||!i){a.warn("[AdMeshProvider] โ ๏ธ Cannot perform intent analysis: missing API key or base URL");return}if(o)a.log("[AdMeshProvider] โน๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){a.log('[AdMeshProvider] โน๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{$(!0),D(null),a.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const H=F??await q();if(!H){a.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),D("Failed to extract page content");return}a.log("[AdMeshProvider] ๐ Extracted headings:",{title:H.title,headingsCount:H.headings.length,articleTextLength:((_=H.article_text)==null?void 0:_.length)||0,domain:H.domain});const ie=await yr(H,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:y});ie?(a.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:ie.suggestions.length,suggestions:(ie.suggestions||[]).map(ke=>{var T;return{id:ke.id,text:ke.text,is_sponsored:ke.is_sponsored,recommendationId:((T=ke.recommendation)==null?void 0:T.recommendation_id)||null}})}),N(ke=>ve(ke,ie.suggestions||[]))):(a.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),D("Intent analysis failed"),N(ke=>ke.length>0?(a.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),ke):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(H){a.error("[AdMeshProvider] โ Error in intent analysis:",H),D("Intent analysis error"),N(A=>A.length>0?(a.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),A):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{$(!1)}},[t,i,o,y,ve,q]),Pe=l.useCallback(async F=>{var A,ie,ke,T,se,j;if(!b||!t||!t.toLowerCase().startsWith("pub_"))return;const _=F??await q();if(!_){a.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const H=((ie=(A=_.headings)==null?void 0:A[0])==null?void 0:ie.trim())||((ke=_.title)==null?void 0:ke.trim());if(!H){a.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{a.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const ce=await b.fetchPlatformResponse({query:H,sessionId:e,messageId:Jt.createMessageId(e),platformSurface:"embedded_assistant",model:g,messages:[],language:c,location:u,userId:y}),re=(j=(se=(T=ce.recommendation)==null?void 0:T.creative)==null?void 0:se.follow_up_suggestion)==null?void 0:j.trim(),Y=ce.recommendation_id;if(!re||!Y){a.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const K={id:Y,text:re,type:"action",is_sponsored:!0,recommendation:ce,metadata:{source:"aip_context_prefetch",recommendation_id:Y}};N(ae=>oe(ae,K)),a.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:Y,suggestionText:re})}catch(ce){a.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",ce)}},[t,c,u,g,b,e,y,oe,q]),be=l.useCallback(async()=>{a.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await Ne()},[Ne]);l.useEffect(()=>{!b||ge.current||(ge.current=!0,(async()=>{const F=await q();await Promise.allSettled([Pe(F),Ne(F)])})())},[b,Ne,Pe,q]);const we=l.useCallback(F=>{if(!F||F.status!=="active")return!1;const _=Date.parse(F.expires_at);return Number.isNaN(_)?!1:_>Date.now()},[]),Se=l.useCallback(async(F,_,H,A)=>{const ie=A??k;if(!ie||!b){a.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:F,eventType:_,hasSession:!!ie,hasSdk:!!b});return}const ke=new Date().toISOString();a.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:F,eventType:_,recommendationId:ie.recommendation_id,delegationSessionId:ie.delegation_session_id,sessionId:ie.session_id});const T=await fetch(`${b.getApiBaseUrl()}${F}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:ie.delegation_session_id,recommendation_id:ie.recommendation_id,session_id:ie.session_id,event_type:_,timestamp:ke,metadata:H||{}})});if(!T.ok){const ce=await T.text();throw a.error("[AdMeshProvider] โ Delegation event failed",{endpoint:F,eventType:_,status:T.status,errorBody:ce,recommendationId:ie.recommendation_id,delegationSessionId:ie.delegation_session_id}),new Error(`Delegation event failed (${T.status}): ${ce}`)}const se=await T.json(),j=se==null?void 0:se.session;a.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:F,eventType:_,recommendationId:ie.recommendation_id,delegationSessionId:ie.delegation_session_id,returnedStatus:(j==null?void 0:j.status)||(se==null?void 0:se.status)}),j&&S(j)},[k,t,b]),_e=l.useCallback(()=>{V.current=0},[]),Fe=l.useCallback(async(F="user_stopped",_)=>{const H=k;if(!H){a.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}a.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:F,recommendationId:H.recommendation_id,delegationSessionId:H.delegation_session_id}),await Se("/aip/delegation/stop","session_stopped",{reason:F,..._||{}},H),await(b==null?void 0:b.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:H.session_id,recommendation_id:H.recommendation_id,delegation_session_id:H.delegation_session_id,brand_name:H.brand_name,status:"stopped",metadata:{reason:F,..._||{}}}).catch(A=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",A)})),V.current=0,ee.current=null,S(null),a.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},[k,Se,b]),Ee=l.useCallback(async(F="turn_completed",_)=>{F==="turn_started"&&_e(),await Se("/aip/delegation/activity",F,_)},[Se,_e]);l.useEffect(()=>{const F=(k==null?void 0:k.delegation_session_id)??null;F!==ee.current&&(ee.current=F,V.current=0)},[k==null?void 0:k.delegation_session_id]),l.useEffect(()=>{if(!((k==null?void 0:k.delegation_session_id)??null)||!b)return;const _=me.current;if(!_||!we(_)){S(A=>A?{...A,status:"expired"}:null);return}const H=window.setInterval(()=>{const A=me.current;if(!(!A||!we(A))){if(V.current+=1,V.current>=ar){a.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:A.delegation_session_id,heartbeatsSinceLastUserTurn:V.current,idleHeartbeatLimit:ar}),Fe("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:V.current}).catch(ie=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to stop idle delegation session:",ie)});return}Se("/aip/delegation/heartbeat","heartbeat").catch(ie=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",ie)})}},Io);return()=>{window.clearInterval(H)}},[k==null?void 0:k.delegation_session_id,we,Se,b,Fe]);const rt={sdk:b,apiKey:t,sessionId:e,theme:s,language:c,location:u,userId:y,model:g,messages:v,processedMessageIds:p,recommendationResults:I,activeDelegationSession:k,suggestions:L,isAnalyzingIntent:B||Q,intentError:z,markMessageAsProcessed:F=>{E(_=>{const H=new Set(_);return H.add(F),H})},isMessageProcessed:F=>p.has(F),setRecommendationResult:(F,_)=>{G(H=>{const A=new Map(H);return A.set(F,_),A}),E(H=>{const A=new Set(H);return A.add(F),A})},getRecommendationResult:F=>I.get(F),hasRecommendationResult:F=>I.has(F),setActiveDelegationSession:F=>{S(F)},getActiveDelegationSession:()=>we(k)?k:null,hasActiveDelegationSession:()=>we(k),refreshDelegationActivity:Ee,stopDelegationSession:Fe,retryIntentAnalysis:be};return r.jsx(En.Provider,{value:rt,children:m})};class vr{constructor(){Oe(this,"roots",new Map)}async render(e){try{a.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){a.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw a.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);a.log("[AdMeshRenderer] โ
Container ready");const i=this.roots.get(e.containerId);i&&(a.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const c=Kr.createRoot(s);a.log("[AdMeshRenderer] ๐ Rendering recommendations"),c.render(r.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:r.jsx(gr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",a.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,c)}catch(o){throw a.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 Po=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},dt=class dt{constructor(e){Oe(this,"config");Oe(this,"apiBaseUrl");Oe(this,"renderer",null);Oe(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 dt.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),c=i[i.length-1];return c?`session_${Date.now()}_${c}`:dt.createSession()}catch{return dt.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 vr),this.renderer}getTracker(){return this.tracker||(this.tracker=new xr({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const c=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(!c.ok){const y=await c.text();throw new Error(`Delegation event failed (${c.status}): ${y}`)}const u=await c.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(),c=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:c,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 a.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var f,p,E,I,G,k,S,L,N,B,$,z,D;const o=`${this.apiBaseUrl}/aip/context`;if(a.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const Q=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw a.error("[AdMeshSDK] โ sessionId not provided by platform - cannot process request"),Q}const s=e.messageId;if(!s||s.trim()===""){const Q=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw a.error("[AdMeshSDK] โ messageId not provided by platform - cannot process request"),Q}const i=dt.buildPlatformResponseCacheKey(e.sessionId,s),c=dt.inFlightPlatformResponses.get(i);if(c)return a.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),c;const u=e.messages?e.messages.length:0,y=(typeof window<"u"&&window.navigator,"web"),g=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",v=Po((f=e.location)==null?void 0:f.countryCode)||"US",d=typeof window<"u"&&window.location?{url:window.location.href,origin:window.location.origin,referrer:document.referrer||void 0,host:window.location.hostname}:void 0,h=e.userId??this.config.userId,w={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:h||"",confidence:h?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:y,form_factor:g,locale:e.language||"en-US",country:v,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((p=e.location)==null?void 0:p.city)||void 0,state:((E=e.location)==null?void 0:E.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:((k=e.location)==null?void 0:k.zipcode)||void 0,latitude:(S=e.location)==null?void 0:S.latitude,longitude:(L=e.location)==null?void 0:L.longitude},page:d}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(B=(N=w.classification_input.interaction)==null?void 0:N.input.query_text)!=null&&B.trim()||a.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const C=JSON.stringify(w);a.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:w.message_id,specVersion:w.spec_version,classificationType:w.classification_input.type,platformId:w.platform.platform_id,surfaceChannel:($=w.classification_input.interaction)==null?void 0:$.surface.channel,sessionId:(D=(z=w.classification_input.interaction)==null?void 0:z.session)==null?void 0:D.id});const m={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){m["X-AdMesh-Source"]="extension";const Q=this.getExtensionSourceDomain();Q&&(m["X-AdMesh-Source-Domain"]=Q)}const b=(async()=>{const Q=await fetch(o,{method:"POST",headers:m,body:C});if(!Q.ok){const V=(await Q.json().catch(()=>({}))).detail||`HTTP ${Q.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${V}`)}const J=await Q.json();return a.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{status:J.status,recommendationId:J.recommendation_id,hasRecommendation:!!J.recommendation,hasTracking:!!J.tracking,hasDelegation:!!J.delegation,topLevelKeys:Object.keys(J)}),a.log("[AdMeshSDK] ๐ฆ Full PlatformResponse received from /aip/context",J),J})();dt.inFlightPlatformResponses.set(i,b);try{return await b}finally{dt.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)}};Oe(dt,"inFlightPlatformResponses",new Map);let Jt=dt;class Tn{constructor(e={}){Oe(this,"autoAddLabels");Oe(this,"fireExposurePixels");Oe(this,"labelStyle");Oe(this,"processedLinks",new Set);Oe(this,"mutationObserver",null);var o,s,i,c;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:((c=e.labelStyle)==null?void 0:c.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 c=this.getLinksToProcess(e),u=new Map(o.map(g=>{var v,d,h;return[((v=g==null?void 0:g.tracking)==null?void 0:v.click_url)||((h=(d=g==null?void 0:g.recommendation)==null?void 0:d.creative)==null?void 0:h.landing_page_url)||"",g]}).filter(([g])=>!!g)),y=new Map;o.forEach(g=>{var d,h;const v=(h=(d=g==null?void 0:g.recommendation)==null?void 0:d.creative)==null?void 0:h.landing_page_url;if(v&&typeof v=="string"){const w=v.trim().replace(/\/$/,"");y.set(w,g),y.set(`${w}/`,g)}}),c.forEach(g=>{var C,m,b,f,p,E,I,G;const v=g.getAttribute("href")||"",d=`${v}`;if(this.processedLinks.has(d))return;let h=u.get(v),w=v;if(!h){const k=v.trim().replace(/\/$/,"");h=y.get(k)||y.get(`${k}/`);const S=((C=h==null?void 0:h.tracking)==null?void 0:C.click_url)||((b=(m=h==null?void 0:h.recommendation)==null?void 0:m.creative)==null?void 0:b.landing_page_url);h&&S&&(a.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",v),g.setAttribute("href",S),w=S)}if(h){this.processedLinks.add(d),g.setAttribute("target","_blank"),g.setAttribute("rel","noopener noreferrer");const k={element:g,href:w,text:g.textContent||"",hasAdLabel:this.hasAdLabel(g),matchedRecommendation:{recommendation_id:(h==null?void 0:h.recommendation_id)||"",click_url:((f=h==null?void 0:h.tracking)==null?void 0:f.click_url)||((E=(p=h==null?void 0:h.recommendation)==null?void 0:p.creative)==null?void 0:E.landing_page_url)||"",exposure_url:(I=h==null?void 0:h.tracking)==null?void 0:I.exposure_url}};this.autoAddLabels&&!k.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",w),this.addAdLabel(g),k.hasAdLabel=!0):this.autoAddLabels?k.hasAdLabel&&a.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const S=(G=h==null?void 0:h.tracking)==null?void 0:G.exposure_url;this.fireExposurePixels&&S&&s&&k.matchedRecommendation&&s({exposureUrl:S,recommendationId:k.matchedRecommendation.recommendation_id,linkElement:g}),i.push(k)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const y=u.getAttribute("href")||"",g=`${y}`;if(this.processedLinks.has(g))return;if(this.isAdMeshLink(y)){this.processedLinks.add(g);const d={element:u,href:y,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:void 0};if(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!d.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to pattern-matched AdMesh link:",y),this.addAdLabel(u),d.hasAdLabel=!0):this.autoAddLabels?d.hasAdLabel&&a.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const h=this.convertClickUrlToExposureUrl(y);s({exposureUrl:h,recommendationId:this.extractRecommendationIdFromUrl(y),linkElement:u})}i.push(d)}});return i}hasAdLabel(e){var u,y,g;if((e.textContent||"").includes("Ad"))return a.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 a.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 a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const v=i,d=v.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((y=v.textContent)!=null&&y.includes("Ad")))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",d),!0}let c=e.nextSibling;for(;c&&c.nodeType===Node.TEXT_NODE;){const v=c.textContent||"";if(v.trim()===""){c=c.nextSibling;continue}if(v.includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(c&&c.nodeType===Node.ELEMENT_NODE){const v=c,d=v.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((g=v.textContent)!=null&&g.includes("Ad")))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next element sibling:",d),!0}return a.log("[WeaveResponseProcessor] โน๏ธ No existing Ad label found"),!1}addAdLabel(e){if(a.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){a.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){a.log("[WeaveResponseProcessor] โน๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){a.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 c=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",c);try{const u=e.nextSibling;u?(o.insertBefore(s,u),a.log("[WeaveResponseProcessor] โ
Ad label inserted before next sibling")):(o.appendChild(s),a.log("[WeaveResponseProcessor] โ
Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?a.log("[WeaveResponseProcessor] โ
Ad label successfully added to link:",e.href):a.error("[WeaveResponseProcessor] โ Ad label insertion failed - label not in DOM")}catch(u){a.error("[WeaveResponseProcessor] โ Error inserting Ad label:",u)}}removeLeftAdLabel(e){var s,i,c;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"))&&((c=u.parentNode)==null||c.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`,c=new URLSearchParams(o.search);return c.has("cpx")||c.set("cpx","0"),`${i}?${c.toString()}`}catch{return a.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 Ht(){const t=Rn();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 $o=({className:t,size:e=20})=>r.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:[r.jsx("path",{d:"M5 12h14"}),r.jsx("path",{d:"M12 5v14"})]}),kr=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var w,C,m,b,f;const c=(C=(w=t.recommendation)==null?void 0:w.creative)!=null&&C.follow_up_suggestion&&((m=t.tracking)!=null&&m.followup_engagement_url)&&((b=t.tracking)!=null&&b.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=c==null?void 0:c.query,y=c==null?void 0:c.engagement_url,g=c==null?void 0:c.exposure_url,v=t.recommendation_id,d=((f=t.recommendation)==null?void 0:f.offerId)||v;if(!u||!y||!g)return a.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const h=async()=>{try{y&&v&&(a.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(y,v,s)),i&&u?(a.log(`[AdMeshFollowup] ๐ Executing query: ${u}`),await i(u)):a.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(p){a.error("[AdMeshFollowup] โ Error handling follow-up click:",p)}};return r.jsx(Zt,{productId:d,recommendationId:v||"",exposureUrl:g,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:r.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[r.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),r.jsxs("div",{onClick:h,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&h()},"aria-label":`Sponsored follow-up: ${u}`,children:[r.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),r.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[r.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),r.jsx($o,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},Xt=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:c,triggerExposureUrl:u=!0,followups_container_id:y,onPasteToInput:g,onDelegationConsent:v,onDelegationActivated:d,onStartDelegation:h,onRecommendationReport:w,onExecuteQuery:C,onFollowupDetected:m,isContainerReady:b})=>{var H,A,ie,ke;const{sdk:f,sessionId:p,apiKey:E,language:I,location:G,userId:k,model:S,messages:L,theme:N,getRecommendationResult:B,hasRecommendationResult:$,setRecommendationResult:z,activeDelegationSession:D,setActiveDelegationSession:Q,hasActiveDelegationSession:J}=Ht(),ge=T=>!!T&&T.status==="generated"&&!!T.recommendation,V=i||k,[ee,me]=l.useState(null),[xe,q]=l.useState(null),[oe,ve]=l.useState(!0),[Ne,Pe]=l.useState(null),be=l.useRef(null),we=l.useRef(!1),Se=l.useRef(!1),_e=l.useRef(t),Fe=l.useRef(e);l.useEffect(()=>{_e.current=t,Fe.current=e},[t,e]),l.useEffect(()=>{be.current!==o&&(be.current=null,Se.current=!1,me(null),q(null))},[o]);const Ee=J()&&(D==null?void 0:D.session_id)===p;l.useEffect(()=>{var j,ce,re;if(!o||!$(o)||Ee)return;const T=B(o);if(!T){a.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),me(null),q(null),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0;return}let se=((j=T.recommendation)==null?void 0:j.format)||"tail";(se==="weave"||se==="product_card")&&(se="tail"),a.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:T.recommendation_id,format:(ce=T.recommendation)==null?void 0:ce.format}),me(T),q(se),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0,(re=_e.current)==null||re.call(_e,o,T)},[B,$,Ee,o]),l.useEffect(()=>{var T,se,j,ce,re,Y,K;if(!(!c||!o)&&!Ee)try{const ae=c,Be=c.status||"unknown";if(!ge(ae)){if(Be==="no_match"){a.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),me(null),q(null),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${Be})`)}let Te=((T=ae.recommendation)==null?void 0:T.format)||"tail";(Te==="weave"||Te==="product_card")&&(Te="tail"),me(ae),q(Te),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0,z(o,ae),(se=_e.current)==null||se.call(_e,o,ae),a.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),a.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:ae.recommendation_id,format:(j=ae.recommendation)==null?void 0:j.format,brandName:(re=(ce=ae.recommendation)==null?void 0:ce.creative)==null?void 0:re.brand_name,headline:(K=(Y=ae.recommendation)==null?void 0:Y.creative)==null?void 0:K.headline,hasTracking:!!ae.tracking})}catch(ae){const Be=ae instanceof Error?ae:new Error(String(ae));Se.current=!1,a.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${Be.message}`)}},[Ee,c,o,z]),l.useEffect(()=>{if(!o||!s||s.trim()===""){a.log("[AdMeshRecommendations] โ Validation failed - missing required parameters"),ve(!1);return}if(Ee){a.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:p,delegationSessionId:D==null?void 0:D.delegation_session_id}),me(null),q(null),Pe(null),ve(!1),we.current=!1;return}if(!(f!=null&&f.fetchPlatformResponse)){a.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),ve(!1);return}if(Se.current){a.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(be.current===o){a.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(we.current){a.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}a.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var se,j,ce,re,Y,K,ae,Be,Te;try{we.current=!0,ve(!0),Pe(null);const M=await f.fetchPlatformResponse({query:s.trim(),sessionId:p,messageId:o,language:I,location:G,userId:V,model:S,...L&&L.length>0&&{messages:L}}),Ce=(M==null?void 0:M.status)||"unknown";if(!ge(M)){if(Ce==="no_match"){a.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),me(null),q(null),Pe(null),ve(!1),we.current=!1,be.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${Ce})`)}me(M),a.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:M.recommendation_id,format:(se=M.recommendation)==null?void 0:se.format,brandName:(ce=(j=M.recommendation)==null?void 0:j.creative)==null?void 0:ce.brand_name,headline:(Y=(re=M.recommendation)==null?void 0:re.creative)==null?void 0:Y.headline,hasTracking:!!M.tracking});let Ie=((K=M.recommendation)==null?void 0:K.format)||"tail";(Ie==="weave"||Ie==="product_card")&&(Ie="tail"),q(Ie),be.current=o,z(o,M),a.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(ae=M.recommendation)==null?void 0:ae.format,selected_format:Ie}),ve(!1),we.current=!1,(Be=_e.current)==null||Be.call(_e,o,M)}catch(M){const Ce=M instanceof Error?M:new Error(String(M));Ce.message.includes("Failed to fetch")||Ce.message.includes("NetworkError")?a.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${Ce.message} `):a.error(`[AdMeshRecommendations] โ Error fetching recommendations: ${Ce.message} `),Pe(Ce),ve(!1),we.current=!1,(Te=Fe.current)==null||Te.call(Fe,Ce)}})()},[D==null?void 0:D.delegation_session_id,Ee,f,p,o,s,I,G,V,S,c,z]),l.useEffect(()=>{var se,j,ce,re;if(!ee||!m)return;const T=(j=(se=ee.recommendation)==null?void 0:se.creative)!=null&&j.follow_up_suggestion&&((ce=ee.tracking)!=null&&ce.followup_engagement_url)&&((re=ee.tracking)!=null&&re.followup_exposure_url)?{label:ee.recommendation.creative.follow_up_suggestion,query:ee.recommendation.creative.follow_up_suggestion,engagement_url:ee.tracking.followup_engagement_url,exposure_url:ee.tracking.followup_exposure_url}:null;T&&m(T,ee.recommendation_id)},[ee,m]);const rt=l.useCallback(async T=>{if(!f||!p)throw new Error("AdMesh SDK activation requires an initialized session");const se=await fetch(`${f.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${E}`},body:JSON.stringify({session_id:p,recommendation_id:T.recommendation_id,metadata:T.metadata})});if(!se.ok){const Y=await se.text();throw new Error(`Failed to activate delegation session: ${se.status} ${Y}`)}const j=await se.json(),ce={...T,delegation_session_id:j.delegation_session_id||T.delegation_session_id,session_id:j.session_id||p,brand_id:j.brand_id||T.brand_id,brand_name:j.brand_name||T.brand_name,mcp_endpoint:j.mcp_endpoint,eligibility_reason:j.eligibility_reason||T.eligibility_reason,delegate_reason:j.delegate_reason||T.delegate_reason,session_goal:j.session_goal||T.session_goal,desired_outcome_type:j.desired_outcome_type||T.desired_outcome_type,required_user_inputs:j.required_user_inputs||T.required_user_inputs||[],required_consent_types:j.required_consent_types||T.required_consent_types||[],success_outcome:j.success_outcome||T.success_outcome,fallback_message:j.fallback_message||T.fallback_message,session_mode:"inline",status:j.status||"active",capabilities:j.capabilities||T.capabilities||[],allowed_data_types:j.allowed_data_types||T.allowed_data_types||[],auth_model:j.auth_model||T.auth_model,handoff_protocol:j.handoff_protocol||T.handoff_protocol,supported_actions:j.supported_actions||T.supported_actions||[],metadata:j.metadata||T.metadata},re={delegation_session_id:j.delegation_session_id,recommendation_id:T.recommendation_id,session_id:j.session_id||p,brand_agent_id:j.brand_agent_id,brand_id:j.brand_id||T.brand_id,brand_name:j.brand_name||T.brand_name||"Brand",mcp_endpoint:j.mcp_endpoint,status:j.status||"active",activated_at:j.created_at,last_activity_at:j.updated_at,expires_at:j.expires_at||j.updated_at,eligibility_reason:j.eligibility_reason||T.eligibility_reason,delegate_reason:j.delegate_reason||T.delegate_reason,session_goal:j.session_goal||T.session_goal,desired_outcome_type:j.desired_outcome_type||T.desired_outcome_type,required_user_inputs:j.required_user_inputs||T.required_user_inputs||[],required_consent_types:j.required_consent_types||T.required_consent_types||[],success_outcome:j.success_outcome||T.success_outcome,fallback_message:j.fallback_message||T.fallback_message,capabilities:j.capabilities||T.capabilities||[],allowed_data_types:j.allowed_data_types||T.allowed_data_types||[],consent_requirements:j.consent_requirements||T.consent_requirements||[],auth_model:j.auth_model||T.auth_model,handoff_protocol:j.handoff_protocol||T.handoff_protocol,supported_actions:j.supported_actions||T.supported_actions||[],metadata:j.metadata||T.metadata};if(Q(re),await f.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:p,recommendation_id:T.recommendation_id,delegation_session_id:j.delegation_session_id,brand_name:re.brand_name,status:j.status||"active",metadata:{brand_agent_id:j.brand_agent_id,source:"recommendation_card"}}).catch(Y=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",Y)}),await f.reportDelegationSessionStarted(re,{brand_agent_id:j.brand_agent_id,brand_name:re.brand_name}).then(Y=>{Y&&Q(Y)}).catch(Y=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",Y)}),d){try{await d(ce)}catch(Y){a.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",Y)}return}if(h)try{await h({...T.platform_response,delegation:{...T.platform_response.delegation,...ce,delegation_session_id:j.delegation_session_id,available:!0,status:j.status||"active"}})}catch(Y){a.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",Y)}},[E,d,h,f,p,Q]),F=l.useCallback(async T=>{var se,j;if(w){await w(T);return}!f||!p||await f.reportSponsoredRecommendation({session_id:p,message_id:o,recommendation_id:T.recommendation_id,reason:T.reason,brand_name:(j=(se=T.recommendation.recommendation)==null?void 0:se.creative)==null?void 0:j.brand_name,metadata:{reason:T.reason,source:"recommendation_card"}}).catch(ce=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to report sponsored recommendation:",ce)})},[o,w,f,p]);if(!o||!s||s.trim()===""||oe||Ne)return null;if(!ee||!xe)return a.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!ee,detectedFormat:xe,isLoading:oe,hasError:!!Ne}),null;a.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:ee.recommendation_id,detectedFormat:xe,brandName:(A=(H=ee.recommendation)==null?void 0:H.creative)==null?void 0:A.brand_name,headline:(ke=(ie=ee.recommendation)==null?void 0:ie.creative)==null?void 0:ke.headline});const _=typeof document<"u"&&y&&(b??!0)?document.getElementById(y):null;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:r.jsx(jn,{recommendations:[ee],theme:N,sessionId:p,triggerExposureUrl:u,onPasteToInput:g,onDelegationConsent:v,onDelegationActivated:rt,onStartDelegation:h,onRecommendationReport:F})}),_&&f&&p?Gr.createPortal(r.jsx(kr,{recommendation:ee,theme:N,sdk:f,sessionId:p,onExecuteQuery:C}),_):null]})},Sr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:c})=>{const{sdk:u,sessionId:y,theme:g,apiKey:v,language:d,location:h,userId:w,model:C,messages:m}=Ht(),b=l.useRef(null),[f,p]=l.useState("");return l.useEffect(()=>{o&&p(`admesh-weave-fallback-${o}`)},[o]),a.log("[WeaveFallbackRecommendations] ๐จ Component render"),l.useEffect(()=>{if(a.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:i,hasPreviousRecommendations:c&&c.length>0,previousRecommendationsCount:(c==null?void 0:c.length)||0}),!i){a.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(a.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){a.log("[WeaveFallbackRecommendations] โ Validation failed - returning early");return}if(a.log("[WeaveFallbackRecommendations] โ
Validation passed"),!u||!f){a.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const E=c&&c.length>0;a.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:E,count:(c==null?void 0:c.length)||0,fallback:i,messageId:o}),E?(a.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${c.length} previous recommendation(s), skipping API call`),(async()=>{var G,k,S,L,N,B,$;try{const z=c[0];if(a.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"&&a.log("[WeaveFallbackRecommendations] ๐ Recommendation received (DEV):",{recommendation_id:z==null?void 0:z.recommendation_id,click_url:((k=z==null?void 0:z.tracking)==null?void 0:k.click_url)||((L=(S=z==null?void 0:z.recommendation)==null?void 0:S.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){a.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o});return}const D=u,Q=D.getRenderer,J=D.getTracker,ge=(B=D.config)==null?void 0:B.theme;if(Q&&J){const V={sessionId:y,messageId:o,recommendations:[z]},ee=Q.call(u),me=J.call(u),xe=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await ee.render({containerId:f,response:V,theme:g||ge,tracker:me,sessionId:y,apiKey:v||(($=u==null?void 0:u.config)==null?void 0:$.apiKey),apiBaseUrl:xe,language:d,location:h,userId:w,model:C,messages:m}),a.log("[WeaveFallbackRecommendations] โ
Recommendations rendered from previous response (no API call)")}else a.warn("[WeaveFallbackRecommendations] โ ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o})}catch(z){const D=z instanceof Error?z:new Error(String(z));a.error(`[WeaveFallbackRecommendations] โ Error rendering previous recommendations: ${D.message}`);try{await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o})}catch{e==null||e(D)}}})()):(a.log("[WeaveFallbackRecommendations] ๐ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){a.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o}),a.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(G){const k=G instanceof Error?G:new Error(String(G));a.log(`[WeaveFallbackRecommendations] โ Error: ${k.message}`),e==null||e(k)}})())},[u,y,f,t,o,s,i,e,c,g]),!i||!o||!s||s.trim()===""?null:r.jsx("div",{ref:b,id:f,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Ar=l.createContext(void 0),zo=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>r.jsx(Ar.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),Lo=()=>l.useContext(Ar),vn=t=>{try{return new URL(t),!0}catch{return!1}},lr=t=>t&&t.trim()?t.trim():"",Mt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",ct=t=>Mt(t)||void 0,No=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},Fo=(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 Mt(t)},Wo=(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=Mt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},he={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"},Bo=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:c=!0,onDelegationConsent:u,onDelegationActivated:y,onStartDelegation:g,onPasteToInput:v})=>{var j,ce,re,Y,K,ae,Be,Te,M,Ce,Ie,ot,yt,et,jt,ut,Et,_t,mt,Rt,st,Ve,ze,O,fe,Ue,Ke,tt,pt,wt,Tt,It,Wt;if(!t||t.length===0)return a.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const d=t[0],h=((j=d==null?void 0:d.recommendation)==null?void 0:j.offerId)||"",w=((ce=d==null?void 0:d.tracking)==null?void 0:ce.exposure_url)||"",C=(d==null?void 0:d.recommendation_id)||"",m=((Y=(re=d==null?void 0:d.recommendation)==null?void 0:re.creative)==null?void 0:Y.description)||"",b=((K=d==null?void 0:d.recommendation)==null?void 0:K.disclosure)||"Sponsored",f=((Be=(ae=d==null?void 0:d.recommendation)==null?void 0:ae.creative)==null?void 0:Be.brand_name)||"",p=((M=(Te=d==null?void 0:d.recommendation)==null?void 0:Te.creative)==null?void 0:M.headline)||((Ie=(Ce=d==null?void 0:d.recommendation)==null?void 0:Ce.creative)==null?void 0:Ie.brand_name)||"",E=((yt=(ot=d==null?void 0:d.recommendation)==null?void 0:ot.creative)==null?void 0:yt.logo_url)||"",I=((et=d==null?void 0:d.tracking)==null?void 0:et.click_url)||((ut=(jt=d==null?void 0:d.recommendation)==null?void 0:jt.creative)==null?void 0:ut.landing_page_url)||"",G=lr((_t=(Et=d==null?void 0:d.recommendation)==null?void 0:Et.creative)==null?void 0:_t.cta_text),k=((Rt=(mt=d==null?void 0:d.recommendation)==null?void 0:mt.creative)==null?void 0:Rt.products)||[],S=k.length>1,L=S?k.slice(0,4):[],N=((st=d==null?void 0:d.recommendation)==null?void 0:st.format)||"tail",B=N==="bridge",$=((Ve=d==null?void 0:d.delegation)==null?void 0:Ve.brand_name)||f,z=((ze=d==null?void 0:d.delegation)==null?void 0:ze.available)===!0,D=B&&z,Q="Talk to Agent",J=!S&&!!G&&!!I;if(!f&&!p&&!m)return a.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:f,hasFirstRecommendation:!!d,recommendationId:C,recommendationKeys:d?Object.keys(d):[]}),null;let ge=f,V="";p&&p!==f&&(V=p),V&&(ge=`${f} โ ${V}`),a.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:C,productId:h,exposureUrl:w?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:I||"MISSING",clickUrlSource:(O=d==null?void 0:d.tracking)!=null&&O.click_url?"tracking.click_url":(Ue=(fe=d==null?void 0:d.recommendation)==null?void 0:fe.creative)!=null&&Ue.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:m?"present":"MISSING",brandName:f,productName:p,headlineText:ge,triggerExposureUrl:c}),a.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:C,brandName:f,productName:p,hasDescription:!!m,hasClickUrl:!!I,hasLogoUrl:!!E,recommendationFormat:N});const ee=(U,ye)=>{ye&&ye.stopPropagation(),a.log(`AdMesh tail ad ${U} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:C,productId:h,clickUrl:I,source:U}).catch(()=>{a.error(`[AdMesh] Failed to track ${U} click`)})},me=U=>{U.stopPropagation(),ee("tail_ad_brand_name")},xe=U=>{U.stopPropagation(),ee("tail_ad_cta")},q=U=>{U.stopPropagation(),ee("tail_ad_logo")},oe=()=>{S||!I||(ee("tail_ad_card"),typeof window<"u"&&window.open(I,"_blank","noopener,noreferrer"))},ve=U=>{S||!I||(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),oe())},[Ne,Pe]=l.useState(!1),be=l.useRef(null);l.useEffect(()=>()=>{be.current&&(be.current(!1),be.current=null)},[]);const we=U=>{var ye;(ye=be.current)==null||ye.call(be,U),be.current=null,Pe(!1)},Se=async()=>u?await u(d):await new Promise(U=>{be.current=U,Pe(!0)}),_e=async()=>{if(C&&i)try{const U=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",ye=await fetch(`${U}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:C,session_id:i,is_test:!1})});ye.ok||a.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",ye.statusText)}catch(U){a.error("[AdMesh Tail Ad] Error tracking delegation engagement:",U)}},Fe=async U=>{var vt,kt,$e,ht;if(U.preventDefault(),U.stopPropagation(),!d||!D)return;if(ee("tail_ad_delegation_cta"),await _e(),!await Se()){a.log("[AdMesh Tail Ad] Delegation consent declined");return}const de=d.delegation,Dt=de!=null&&de.available?{recommendation_id:d.recommendation_id,brand_id:ct(de.brand_id),brand_name:ct(de.brand_name||((kt=(vt=d.recommendation)==null?void 0:vt.creative)==null?void 0:kt.brand_name)),eligibility_reason:ct(de.eligibility_reason),delegate_reason:ct(de.delegate_reason),session_goal:ct(de.session_goal),desired_outcome_type:de.desired_outcome_type,required_user_inputs:Array.isArray(de.required_user_inputs)?de.required_user_inputs.filter(it=>typeof it=="string"):[],required_consent_types:Array.isArray(de.required_consent_types)?de.required_consent_types.filter(it=>typeof it=="string"):[],success_outcome:ct(de.success_outcome),fallback_message:ct(de.fallback_message),session_mode:ct(de.session_mode),status:ct(de.status),capabilities:de.capabilities||[],allowed_data_types:de.allowed_data_types||[],consent_requirements:de.consent_requirements||[],auth_model:ct(de.auth_model),handoff_protocol:de.handoff_protocol&&typeof de.handoff_protocol=="object"?de.handoff_protocol:void 0,supported_actions:de.supported_actions||[],metadata:de.metadata&&typeof de.metadata=="object"?de.metadata:void 0,platform_response:d}:null;if(y&&Dt){await y(Dt);return}if(g){await g(d);return}const Je=((ht=($e=d.recommendation)==null?void 0:$e.creative)==null?void 0:ht.follow_up_suggestion)||"";if(Je&&v){v(Je);return}if(Je&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(Je);return}},[Ee,rt]=l.useState(!1),F=f?f.charAt(0).toUpperCase():"B",_=he.surface,H=he.border,A=(e==null?void 0:e.borderRadius)||((tt=(Ke=e==null?void 0:e.components)==null?void 0:Ke.card)==null?void 0:tt.borderRadius)||"8px",ie="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",ke="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",T=((pt=e==null?void 0:e.shadows)==null?void 0:pt.medium)||((Tt=(wt=e==null?void 0:e.components)==null?void 0:wt.card)==null?void 0:Tt.boxShadow)||ie,se=((It=e==null?void 0:e.shadows)==null?void 0:It.large)||ke;return r.jsxs(Zt,{productId:h,recommendationId:C,exposureUrl:w,sessionId:i,triggerExposureUrl:c,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:[r.jsx("style",{children:`
|
|
129
|
+
`}),r.jsxs("div",{role:!T&&A?"link":void 0,tabIndex:!T&&A?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((Dt=(gt=e==null?void 0:e.components)==null?void 0:gt.card)==null?void 0:Dt.borderRadius)||"14px",border:`1px solid ${me}`,background:ze,boxShadow:ke,minWidth:0,cursor:!T&&A?"pointer":void 0},onClick:Ae,onKeyDown:p,children:[r.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[r.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:oe?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!he&&K&&dr(K)?r.jsx("img",{src:K,alt:`${h} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>ve(!0)}):r.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:Y},children:(h||"A").charAt(0).toUpperCase()})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("div",{className:"admesh-compact-meta-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[r.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"11px",color:Y},children:qe?h:""}),r.jsx("span",{style:{flexShrink:0,fontSize:"10px",color:Y,textTransform:"uppercase",letterSpacing:"0.08em"},children:D})]}),!T&&r.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",lineHeight:1.3,fontWeight:700,color:H,marginBottom:"4px"},title:_e,children:_e}),se&&r.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"12px",lineHeight:1.35,color:Se},title:se,children:se})]})]}),T&&r.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:N.map(q=>{const ye=qt(q.product_name)||"Product",st=qt(q.product_link)||qt(q.product_url)||A||"#",Ye=Co(q.product_price,q.product_currency),Ve=qt(q.product_image_url),Ne=Ve&&dr(Ve)?Ve:"",xt=st!=="#";return r.jsx("a",{href:st,target:xt?"_blank":void 0,rel:xt?"noopener noreferrer":void 0,onClick:ct=>O(`compact_tail_ad_product_${q.product_id||"item"}`,ct),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${me}`,borderRadius:"12px",background:Ge,padding:"8px",flexShrink:0},children:r.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[r.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:oe?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:Y,fontSize:"12px",fontWeight:700},children:Ne?r.jsx("img",{src:Ne,alt:ye,style:{width:"100%",height:"100%",objectFit:"cover"}}):ye.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("div",{style:{fontSize:"12px",lineHeight:1.25,fontWeight:600,color:H,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:ye,children:ye}),r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:Ye&&r.jsx("span",{style:{fontSize:"12px",fontWeight:700,color:H},children:Ye})})]})]})},q.product_id||`${y}-${ye}`)})}),r.jsxs("div",{className:"admesh-compact-footer-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:T?0:lt},children:[r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:St}),r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",marginLeft:"auto",flexShrink:0},children:[T&&P.length>N.length?r.jsxs("span",{style:{fontSize:"10px",color:Y},children:["+",P.length-N.length," more"]}):null,r.jsx("button",{type:"button","aria-label":xe?"Recommendation reported":"Report recommendation",title:xe?"Reported":"Report recommendation",disabled:!!xe,onClick:ie,style:{width:"28px",height:"28px",borderRadius:"999px",border:`1px solid ${me}`,background:xe?Ge:ze,color:xe?Ie:Y,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,cursor:xe?"default":"pointer",flexShrink:0},children:r.jsx(oo,{size:13})})]})]}),ee?r.jsx("div",{className:"admesh-compact-report-panel",onClick:q=>q.stopPropagation(),style:{marginLeft:T?0:lt,border:`1px solid ${me}`,borderRadius:"12px",background:Ge,padding:"8px",display:"flex",flexWrap:"wrap",gap:"6px"},children:V.map(q=>r.jsx("button",{className:"admesh-compact-report-option",type:"button",onClick:ye=>ae(ye,q.value),style:{borderRadius:"999px",border:`1px solid ${me}`,background:ze,color:H,fontSize:"11px",fontWeight:600,padding:"6px 9px",cursor:"pointer"},children:q.label},q.value))}):null,xe?r.jsx("div",{className:"admesh-compact-report-status",style:{marginLeft:T?0:lt,fontSize:"11px",color:Y},children:"Thanks for reporting this recommendation."}):null,Te?r.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${me}`,borderRadius:"12px",background:Ge,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:Ie},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:H,fontWeight:600},children:["Allow ",be||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:Se},children:"The agent will only use the details you choose to share for this request."})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[r.jsx("button",{type:"button",onClick:q=>{q.preventDefault(),q.stopPropagation(),nt(!1)},style:{borderRadius:"10px",border:`1px solid ${me}`,background:ze,color:H,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:q=>{q.preventDefault(),q.stopPropagation(),nt(!0)},style:{borderRadius:"10px",border:"none",background:Ie,color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})},vr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})=>{const b=t.filter(c=>c&&typeof c=="object"&&typeof c.recommendation_id=="string"&&c.recommendation_id.length>0);if(!b||b.length===0)return a.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;a.log(`[AdMeshLayout] Rendering with ${b.length} valid recommendations`);const k=()=>{var c;if(b.length>0){const g=b[0],S=(c=g.recommendation)==null?void 0:c.format;a.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:S,recommendationKeys:Object.keys(g||{})}),(S==="product_card"||S==="weave"||S==="bridge")&&a.warn(`[AdMeshLayout] ${S} format requested, falling back to tail for canonical render payload`)}return r.jsx(Pn,{recommendations:b,theme:e,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})};return r.jsx("div",{className:`admesh-layout ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:k()})};class kr{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&&a.log("[Tracker] Exposure already fired");return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&a.warn("[Tracker] Failed to fire exposure")}),this.debug&&a.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&a.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,i){const d=`${s}_${o}`;if(this.firedExposures.has(d)){this.debug&&a.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let w=null,b=null;const k=new IntersectionObserver(S=>{S.forEach(M=>{M.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?w===null&&(w=Date.now(),this.debug&&a.log("[Tracker] Ad reached MRC visibility threshold"),b=setTimeout(()=>{this.fireExposure(e,o,s),k.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):w!==null&&(b&&(clearTimeout(b),b=null),w=null,this.debug&&a.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});k.observe(i);const g=setTimeout(()=>{k.disconnect(),b&&clearTimeout(b),u()},3e4);i.__admeshTrackerCleanup=()=>{k.disconnect(),b&&clearTimeout(b),clearTimeout(g)}})}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&&a.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const $n=l.createContext(void 0);function zn(){const t=l.useContext($n);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function Mo(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 Sr(){var t;try{console.log("[AdMesh] Starting direct headings extraction...");const e=k=>k.replace(/\s+/g," ").trim(),o=()=>{var x;const k=["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(","),M=(((x=k.map(h=>document.querySelector(h)).filter(h=>!!h).map(h=>{const E=h.cloneNode(!0);E.querySelectorAll(c).forEach(K=>K.remove());const R=e(E.textContent||"");return{element:h,text:R}}).filter(h=>h.text.length>=200).sort((h,E)=>E.text.length-h.text.length)[0])==null?void 0:x.element)||document.body).cloneNode(!0);M.querySelectorAll(c).forEach(h=>h.remove());const f=Array.from(M.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(h=>e(h.textContent||"")).filter(h=>h.length>=24);return(f.length>0?f.join(`
|
|
130
|
+
`):e(M.textContent||"")).slice(0,6e3)},s=Mo(window.location.pathname||"/"),i=e(document.title||"")||s,u=(()=>{const k=[],c=document.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(c).forEach(g=>{const S=e(g.textContent||"");S.length>0&&k.push(S)}),k})(),w=u.length>0?u:[i||s],b={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:b.title,headingsCount:b.headings.length,articleTextLength:((t=b.article_text)==null?void 0:t.length)||0,domain:b.domain}),b}catch(e){return console.error("[AdMesh] Error in direct headings extraction:",e),null}}function jo(t){return!!(t&&typeof t=="object"&&"recommendation_id"in t&&"status"in t)}function Eo(t){var s,i,d,u,w,b,k,c,g,S,M;if(!t||typeof t!="object")return;if(jo(t))return t;const e=t;if(!e.recommendation_id)return;const o=(e.products||[]).map(f=>{var y,x;return{product_id:f.product_id||"",product_link:f.product_link||f.product_click_url||e.click_url||e.url||"",product_name:f.product_name||e.title||((y=e.creative_input)==null?void 0:y.product_name)||"",product_description:f.product_description||"",product_price:f.product_price??void 0,product_discount:f.product_discount??void 0,product_currency:f.product_currency,product_discount_type:f.product_discount_type,product_cta_label:f.product_cta_label||((x=e.creative_input)==null?void 0:x.cta_label),product_image_url:f.product_image_url,product_features:f.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)||((b=o[0])==null?void 0:b.product_cta_label)||"Learn more",follow_up_suggestion:e.follow_up_suggestion,logo_url:(c=(k=e.creative_input)==null?void 0:k.assets)==null?void 0:c.logo_url,image_urls:((S=(g=e.creative_input)==null?void 0:g.assets)==null?void 0:S.image_urls)||[],landing_page_url:e.url||e.click_url||((M=e.creative_input)==null?void 0:M.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 Ro(t){return{...t,suggestions:(t.suggestions||[]).map(e=>({...e,recommendation:Eo(e.recommendation)}))}}function cr(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 Ar(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:[],b=(o=cr(t.url))==null?void 0:o.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),k=b?b.replace(/\b\w/g,E=>E.toUpperCase()):void 0,c=e.apiKey.toLowerCase().startsWith("pub_")?cr(t.url):void 0,g=e.extension?"extension":"admesh_ui_sdk",S=(t.domain||(typeof window<"u"?window.location.hostname:"")).trim().toLowerCase(),M={url:t.url,title:t.title||void 0,headings:w.length>0?w:k?[k]:void 0,article_text:((s=t.article_text)==null?void 0:s.trim())||void 0,domain:S,article_slug:c,agent_id:void 0,cpx_floor:void 0,source:g,api_key:e.apiKey,user_id:e.userId||void 0};console.log("[AdMesh SDK] Payload prepared:",{url:M.url,titleLength:((i=M.title)==null?void 0:i.length)||0,headingsCount:((d=M.headings)==null?void 0:d.length)||0,articleTextLength:((u=M.article_text)==null?void 0:u.length)||0,domain:M.domain,article_slug:M.article_slug,source:M.source,has_user_id:!!M.user_id});const f=`${e.apiBaseUrl}/acie/analyze-intent`;console.log("[AdMesh SDK] Calling ACIE API:",f);const y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(M)});if(console.log("[AdMesh SDK] ACIE API response received:",{status:y.status,statusText:y.statusText,ok:y.ok}),!y.ok){const E=await y.text();throw console.error("[AdMesh SDK] ACIE API error:",{status:y.status,statusText:y.statusText,errorText:E}),new Error(`ACIE API error: ${y.status} - ${E}`)}const x=await y.json(),h=Ro(x);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 To(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 Io(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function Do(){var t;if(typeof window>"u")return null;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Cr(e))return e}catch{return null}return null}function Cr(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 Po(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 ur(t){const e=new URL(t),o=Po(t);return{title:o,headings:[o],article_text:`Article URL: ${t}
|
|
131
|
+
Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const $o=6e4,mr=3;function zo(t){const e=Do();if(e)return e;const o=t==null?void 0:t.trim();return Cr(o)?o:null}const Mr=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:d,location:u,userId:w,model:b,messages:k,pageContext:c,articleUrl:g,contextMode:S="auto",agentDisplayId:M,children:f})=>{const[y,x]=l.useState(null),[h,E]=l.useState(new Set),[R,K]=l.useState(new Map),[A,C]=l.useState(null),[D,P]=l.useState([]),[N,T]=l.useState(!1),[I,$]=l.useState(null),[G,X]=l.useState(!1),be=l.useRef(!1),B=l.useRef(0),L=l.useRef(null),ue=l.useRef(null);ue.current=A;const _e=!!c||S==="ad-slot"||S==="auto"&&(!!(g!=null&&g.trim())||Io()),se=l.useCallback(async()=>{if(c)return c;if(!_e)return Sr();const z=zo(g);if(!z)return a.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),$("Article URL is required for ad-slot context"),null;if(!t||!i)return a.warn("[AdMeshProvider] Cannot fetch page context: missing API key or base URL"),ur(z);try{X(!0);const O=await To(z,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:M});return a.log("[AdMeshProvider] Page context resolved",{source:O.source,cache_hit:O.cache_hit,domain:O.context.domain}),O.context}catch(O){return a.error("[AdMeshProvider] Failed to fetch page context:",O),a.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),ur(z)}finally{X(!1)}},[M,i,t,g,c,_e]),$e=l.useCallback((z,O)=>{const V=z.filter(ie=>!ie.is_sponsored).slice(0,3);return[O,...V]},[]),Me=l.useCallback((z,O)=>{const V=z.find(ae=>ae.is_sponsored),ie=O.filter(ae=>!ae.is_sponsored).slice(0,3);return V?[V,...ie]:ie},[]);l.useEffect(()=>{if(!e||e.trim()===""){a.error("[AdMeshProvider] โ sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}a.log("[AdMeshProvider] โ
Session ID available:",e)},[e]),l.useEffect(()=>{if(!t){a.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){a.error("[AdMeshProvider] โ Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const z=new Jt({apiKey:t,theme:s,apiBaseUrl:i,extension:o});x(z),a.log("[AdMeshProvider] โ
AdMesh SDK initialized with session:",e),i&&a.log("[AdMeshProvider] ๐ Using custom API base URL")}catch(z){a.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK:",z)}return()=>{a.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,s,i,e,o]);const qe=l.useCallback(async z=>{var O;if(!t||!i){a.warn("[AdMeshProvider] โ ๏ธ Cannot perform intent analysis: missing API key or base URL");return}if(o)a.log("[AdMeshProvider] โน๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){a.log('[AdMeshProvider] โน๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{T(!0),$(null),a.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const V=z??await se();if(!V){a.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),$("Failed to extract page content");return}a.log("[AdMeshProvider] ๐ Extracted headings:",{title:V.title,headingsCount:V.headings.length,articleTextLength:((O=V.article_text)==null?void 0:O.length)||0,domain:V.domain});const ae=await Ar(V,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:w});ae?(a.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:ae.suggestions.length,suggestions:(ae.suggestions||[]).map(Ae=>{var p;return{id:Ae.id,text:Ae.text,is_sponsored:Ae.is_sponsored,recommendationId:((p=Ae.recommendation)==null?void 0:p.recommendation_id)||null}})}),P(Ae=>Me(Ae,ae.suggestions||[]))):(a.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),$("Intent analysis failed"),P(Ae=>Ae.length>0?(a.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),Ae):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(V){a.error("[AdMeshProvider] โ Error in intent analysis:",V),$("Intent analysis error"),P(ie=>ie.length>0?(a.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),ie):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{T(!1)}},[t,i,o,w,Me,se]),Te=l.useCallback(async z=>{var ie,ae,Ae,p,J,j;if(!y||!t||!t.toLowerCase().startsWith("pub_"))return;const O=z??await se();if(!O){a.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const V=((ae=(ie=O.headings)==null?void 0:ie[0])==null?void 0:ae.trim())||((Ae=O.title)==null?void 0:Ae.trim());if(!V){a.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{a.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const he=await y.fetchPlatformResponse({query:V,sessionId:e,messageId:Jt.createMessageId(e),platformSurface:"embedded_assistant",model:b,messages:[],language:d,location:u,userId:w}),ve=(j=(J=(p=he.recommendation)==null?void 0:p.creative)==null?void 0:J.follow_up_suggestion)==null?void 0:j.trim(),oe=he.recommendation_id;if(!ve||!oe){a.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const ze={id:oe,text:ve,type:"action",is_sponsored:!0,recommendation:he,metadata:{source:"aip_context_prefetch",recommendation_id:oe}};P(me=>$e(me,ze)),a.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:oe,suggestionText:ve})}catch(he){a.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",he)}},[t,d,u,b,y,e,w,$e,se]),ne=l.useCallback(async()=>{a.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await qe()},[qe]);l.useEffect(()=>{!y||be.current||(be.current=!0,(async()=>{const z=await se();await Promise.allSettled([Te(z),qe(z)])})())},[y,qe,Te,se]);const ee=l.useCallback(z=>{if(!z||z.status!=="active")return!1;const O=Date.parse(z.expires_at);return Number.isNaN(O)?!1:O>Date.now()},[]),Ee=l.useCallback(async(z,O,V,ie)=>{const ae=ie??A;if(!ae||!y){a.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:z,eventType:O,hasSession:!!ae,hasSdk:!!y});return}const Ae=new Date().toISOString();a.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:z,eventType:O,recommendationId:ae.recommendation_id,delegationSessionId:ae.delegation_session_id,sessionId:ae.session_id});const p=await fetch(`${y.getApiBaseUrl()}${z}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:ae.delegation_session_id,recommendation_id:ae.recommendation_id,session_id:ae.session_id,event_type:O,timestamp:Ae,metadata:V||{}})});if(!p.ok){const he=await p.text();throw a.error("[AdMeshProvider] โ Delegation event failed",{endpoint:z,eventType:O,status:p.status,errorBody:he,recommendationId:ae.recommendation_id,delegationSessionId:ae.delegation_session_id}),new Error(`Delegation event failed (${p.status}): ${he}`)}const J=await p.json(),j=J==null?void 0:J.session;a.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:z,eventType:O,recommendationId:ae.recommendation_id,delegationSessionId:ae.delegation_session_id,returnedStatus:(j==null?void 0:j.status)||(J==null?void 0:J.status)}),j&&C(j)},[A,t,y]),xe=l.useCallback(()=>{B.current=0},[]),Oe=l.useCallback(async(z="user_stopped",O)=>{const V=A;if(!V){a.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}a.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:z,recommendationId:V.recommendation_id,delegationSessionId:V.delegation_session_id}),await Ee("/aip/delegation/stop","session_stopped",{reason:z,...O||{}},V),await(y==null?void 0:y.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:V.session_id,recommendation_id:V.recommendation_id,delegation_session_id:V.delegation_session_id,brand_name:V.brand_name,status:"stopped",metadata:{reason:z,...O||{}}}).catch(ie=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",ie)})),B.current=0,L.current=null,C(null),a.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},[A,Ee,y]),Ce=l.useCallback(async(z="turn_completed",O)=>{z==="turn_started"&&xe(),await Ee("/aip/delegation/activity",z,O)},[Ee,xe]);l.useEffect(()=>{const z=(A==null?void 0:A.delegation_session_id)??null;z!==L.current&&(L.current=z,B.current=0)},[A==null?void 0:A.delegation_session_id]),l.useEffect(()=>{if(!((A==null?void 0:A.delegation_session_id)??null)||!y)return;const O=ue.current;if(!O||!ee(O)){C(ie=>ie?{...ie,status:"expired"}:null);return}const V=window.setInterval(()=>{const ie=ue.current;if(!(!ie||!ee(ie))){if(B.current+=1,B.current>=mr){a.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:ie.delegation_session_id,heartbeatsSinceLastUserTurn:B.current,idleHeartbeatLimit:mr}),Oe("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:B.current}).catch(ae=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to stop idle delegation session:",ae)});return}Ee("/aip/delegation/heartbeat","heartbeat").catch(ae=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",ae)})}},$o);return()=>{window.clearInterval(V)}},[A==null?void 0:A.delegation_session_id,ee,Ee,y,Oe]);const nt={sdk:y,apiKey:t,sessionId:e,theme:s,language:d,location:u,userId:w,model:b,messages:k,processedMessageIds:h,recommendationResults:R,activeDelegationSession:A,suggestions:D,isAnalyzingIntent:N||G,intentError:I,markMessageAsProcessed:z=>{E(O=>{const V=new Set(O);return V.add(z),V})},isMessageProcessed:z=>h.has(z),setRecommendationResult:(z,O)=>{K(V=>{const ie=new Map(V);return ie.set(z,O),ie}),E(V=>{const ie=new Set(V);return ie.add(z),ie})},getRecommendationResult:z=>R.get(z),hasRecommendationResult:z=>R.has(z),setActiveDelegationSession:z=>{C(z)},getActiveDelegationSession:()=>ee(A)?A:null,hasActiveDelegationSession:()=>ee(A),refreshDelegationActivity:Ce,stopDelegationSession:Oe,retryIntentAnalysis:ne};return r.jsx($n.Provider,{value:nt,children:f})};class jr{constructor(){Ke(this,"roots",new Map)}async render(e){try{a.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){a.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw a.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);a.log("[AdMeshRenderer] โ
Container ready");const i=this.roots.get(e.containerId);i&&(a.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const d=Xr.createRoot(s);a.log("[AdMeshRenderer] ๐ Rendering recommendations"),d.render(r.jsx(Mr,{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:r.jsx(vr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",a.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,d)}catch(o){throw a.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 Lo=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},ft=class ft{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 ft.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}`:ft.createSession()}catch{return ft.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 jr),this.renderer}getTracker(){return this.tracker||(this.tracker=new kr({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 a.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var x,h,E,R,K,A,C,D,P,N,T,I,$;const o=`${this.apiBaseUrl}/aip/context`;if(a.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const G=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw a.error("[AdMeshSDK] โ sessionId not provided by platform - cannot process request"),G}const s=e.messageId;if(!s||s.trim()===""){const G=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw a.error("[AdMeshSDK] โ messageId not provided by platform - cannot process request"),G}const i=ft.buildPlatformResponseCacheKey(e.sessionId,s),d=ft.inFlightPlatformResponses.get(i);if(d)return a.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"),b=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",k=Lo((x=e.location)==null?void 0:x.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,g=e.userId??this.config.userId,S={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:g||"",confidence:g?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:b,locale:e.language||"en-US",country:k,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((h=e.location)==null?void 0:h.city)||void 0,state:((E=e.location)==null?void 0:E.state)||void 0,state_code:((R=e.location)==null?void 0:R.stateCode)||void 0,country:((K=e.location)==null?void 0:K.country)||void 0,country_code:k,zipcode:((A=e.location)==null?void 0:A.zipcode)||void 0,latitude:(C=e.location)==null?void 0:C.latitude,longitude:(D=e.location)==null?void 0:D.longitude},page:c}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(N=(P=S.classification_input.interaction)==null?void 0:P.input.query_text)!=null&&N.trim()||a.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const M=JSON.stringify(S);a.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:S.message_id,specVersion:S.spec_version,classificationType:S.classification_input.type,platformId:S.platform.platform_id,surfaceChannel:(T=S.classification_input.interaction)==null?void 0:T.surface.channel,sessionId:($=(I=S.classification_input.interaction)==null?void 0:I.session)==null?void 0:$.id});const f={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){f["X-AdMesh-Source"]="extension";const G=this.getExtensionSourceDomain();G&&(f["X-AdMesh-Source-Domain"]=G)}const y=(async()=>{const G=await fetch(o,{method:"POST",headers:f,body:M});if(!G.ok){const B=(await G.json().catch(()=>({}))).detail||`HTTP ${G.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${B}`)}const X=await G.json();return a.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{status:X.status,recommendationId:X.recommendation_id,hasRecommendation:!!X.recommendation,hasTracking:!!X.tracking,hasDelegation:!!X.delegation,topLevelKeys:Object.keys(X)}),a.log("[AdMeshSDK] ๐ฆ Full PlatformResponse received from /aip/context",X),X})();ft.inFlightPlatformResponses.set(i,y);try{return await y}finally{ft.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(ft,"inFlightPlatformResponses",new Map);let Jt=ft;class Ln{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(b=>{var k,c,g;return[((k=b==null?void 0:b.tracking)==null?void 0:k.click_url)||((g=(c=b==null?void 0:b.recommendation)==null?void 0:c.creative)==null?void 0:g.landing_page_url)||"",b]}).filter(([b])=>!!b)),w=new Map;o.forEach(b=>{var c,g;const k=(g=(c=b==null?void 0:b.recommendation)==null?void 0:c.creative)==null?void 0:g.landing_page_url;if(k&&typeof k=="string"){const S=k.trim().replace(/\/$/,"");w.set(S,b),w.set(`${S}/`,b)}}),d.forEach(b=>{var M,f,y,x,h,E,R,K;const k=b.getAttribute("href")||"",c=`${k}`;if(this.processedLinks.has(c))return;let g=u.get(k),S=k;if(!g){const A=k.trim().replace(/\/$/,"");g=w.get(A)||w.get(`${A}/`);const C=((M=g==null?void 0:g.tracking)==null?void 0:M.click_url)||((y=(f=g==null?void 0:g.recommendation)==null?void 0:f.creative)==null?void 0:y.landing_page_url);g&&C&&(a.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",k),b.setAttribute("href",C),S=C)}if(g){this.processedLinks.add(c),b.setAttribute("target","_blank"),b.setAttribute("rel","noopener noreferrer");const A={element:b,href:S,text:b.textContent||"",hasAdLabel:this.hasAdLabel(b),matchedRecommendation:{recommendation_id:(g==null?void 0:g.recommendation_id)||"",click_url:((x=g==null?void 0:g.tracking)==null?void 0:x.click_url)||((E=(h=g==null?void 0:g.recommendation)==null?void 0:h.creative)==null?void 0:E.landing_page_url)||"",exposure_url:(R=g==null?void 0:g.tracking)==null?void 0:R.exposure_url}};this.autoAddLabels&&!A.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",S),this.addAdLabel(b),A.hasAdLabel=!0):this.autoAddLabels?A.hasAdLabel&&a.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const C=(K=g==null?void 0:g.tracking)==null?void 0:K.exposure_url;this.fireExposurePixels&&C&&s&&A.matchedRecommendation&&s({exposureUrl:C,recommendationId:A.matchedRecommendation.recommendation_id,linkElement:b}),i.push(A)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const w=u.getAttribute("href")||"",b=`${w}`;if(this.processedLinks.has(b))return;if(this.isAdMeshLink(w)){this.processedLinks.add(b);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?(a.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to pattern-matched AdMesh link:",w),this.addAdLabel(u),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&a.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const g=this.convertClickUrlToExposureUrl(w);s({exposureUrl:g,recommendationId:this.extractRecommendationIdFromUrl(w),linkElement:u})}i.push(c)}});return i}hasAdLabel(e){var u,w,b;if((e.textContent||"").includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Link text contains Ad label"),!0;const s=e.querySelectorAll("sub, span");for(const k of Array.from(s))if((u=k.textContent)!=null&&u.includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Link has Ad label as child element"),!0;let i=e.previousSibling;for(;i&&i.nodeType===Node.TEXT_NODE;){const k=i.textContent||"";if(k.trim()===""){i=i.previousSibling;continue}if(k.includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const k=i,c=k.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((w=k.textContent)!=null&&w.includes("Ad")))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",c),!0}let d=e.nextSibling;for(;d&&d.nodeType===Node.TEXT_NODE;){const k=d.textContent||"";if(k.trim()===""){d=d.nextSibling;continue}if(k.includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(d&&d.nodeType===Node.ELEMENT_NODE){const k=d,c=k.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((b=k.textContent)!=null&&b.includes("Ad")))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next element sibling:",c),!0}return a.log("[WeaveResponseProcessor] โน๏ธ No existing Ad label found"),!1}addAdLabel(e){if(a.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){a.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){a.log("[WeaveResponseProcessor] โน๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){a.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),a.log("[WeaveResponseProcessor] โ
Ad label inserted before next sibling")):(o.appendChild(s),a.log("[WeaveResponseProcessor] โ
Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?a.log("[WeaveResponseProcessor] โ
Ad label successfully added to link:",e.href):a.error("[WeaveResponseProcessor] โ Ad label insertion failed - label not in DOM")}catch(u){a.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 a.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 Ot(){const t=zn();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 No=({className:t,size:e=20})=>r.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:[r.jsx("path",{d:"M5 12h14"}),r.jsx("path",{d:"M12 5v14"})]}),Er=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var S,M,f,y,x;const d=(M=(S=t.recommendation)==null?void 0:S.creative)!=null&&M.follow_up_suggestion&&((f=t.tracking)!=null&&f.followup_engagement_url)&&((y=t.tracking)!=null&&y.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,b=d==null?void 0:d.exposure_url,k=t.recommendation_id,c=((x=t.recommendation)==null?void 0:x.offerId)||k;if(!u||!w||!b)return a.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const g=async()=>{try{w&&k&&(a.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(w,k,s)),i&&u?(a.log(`[AdMeshFollowup] ๐ Executing query: ${u}`),await i(u)):a.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(h){a.error("[AdMeshFollowup] โ Error handling follow-up click:",h)}};return r.jsx(Zt,{productId:c,recommendationId:k||"",exposureUrl:b,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:r.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[r.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),r.jsxs("div",{onClick:g,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===" ")&&g()},"aria-label":`Sponsored follow-up: ${u}`,children:[r.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),r.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[r.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),r.jsx(No,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},Xt=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:d,triggerExposureUrl:u=!0,followups_container_id:w,onPasteToInput:b,onDelegationConsent:k,onDelegationActivated:c,onStartDelegation:g,onRecommendationReport:S,onExecuteQuery:M,onFollowupDetected:f,isContainerReady:y})=>{var V,ie,ae,Ae;const{sdk:x,sessionId:h,apiKey:E,language:R,location:K,userId:A,model:C,messages:D,theme:P,getRecommendationResult:N,hasRecommendationResult:T,setRecommendationResult:I,activeDelegationSession:$,setActiveDelegationSession:G,hasActiveDelegationSession:X}=Ot(),be=p=>!!p&&p.status==="generated"&&!!p.recommendation,B=i||A,[L,ue]=l.useState(null),[_e,se]=l.useState(null),[$e,Me]=l.useState(!0),[qe,Te]=l.useState(null),ne=l.useRef(null),ee=l.useRef(!1),Ee=l.useRef(!1),xe=l.useRef(t),Oe=l.useRef(e);l.useEffect(()=>{xe.current=t,Oe.current=e},[t,e]),l.useEffect(()=>{ne.current!==o&&(ne.current=null,Ee.current=!1,ue(null),se(null))},[o]);const Ce=X()&&($==null?void 0:$.session_id)===h;l.useEffect(()=>{var j,he,ve;if(!o||!T(o)||Ce)return;const p=N(o);if(!p){a.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),ue(null),se(null),Te(null),Me(!1),ne.current=o,ee.current=!1,Ee.current=!0;return}let J=((j=p.recommendation)==null?void 0:j.format)||"tail";(J==="weave"||J==="product_card")&&(J="tail"),a.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:p.recommendation_id,format:(he=p.recommendation)==null?void 0:he.format}),ue(p),se(J),Te(null),Me(!1),ne.current=o,ee.current=!1,Ee.current=!0,(ve=xe.current)==null||ve.call(xe,o,p)},[N,T,Ce,o]),l.useEffect(()=>{var p,J,j,he,ve,oe,ze;if(!(!d||!o)&&!Ce)try{const me=d,ke=d.status||"unknown";if(!be(me)){if(ke==="no_match"){a.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),ue(null),se(null),Te(null),Me(!1),ne.current=o,ee.current=!1,Ee.current=!0,I(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${ke})`)}let Ie=((p=me.recommendation)==null?void 0:p.format)||"tail";(Ie==="weave"||Ie==="product_card")&&(Ie="tail"),ue(me),se(Ie),Te(null),Me(!1),ne.current=o,ee.current=!1,Ee.current=!0,I(o,me),(J=xe.current)==null||J.call(xe,o,me),a.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),a.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:me.recommendation_id,format:(j=me.recommendation)==null?void 0:j.format,brandName:(ve=(he=me.recommendation)==null?void 0:he.creative)==null?void 0:ve.brand_name,headline:(ze=(oe=me.recommendation)==null?void 0:oe.creative)==null?void 0:ze.headline,hasTracking:!!me.tracking})}catch(me){const ke=me instanceof Error?me:new Error(String(me));Ee.current=!1,a.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${ke.message}`)}},[Ce,d,o,I]),l.useEffect(()=>{if(!o||!s||s.trim()===""){a.log("[AdMeshRecommendations] โ Validation failed - missing required parameters"),Me(!1);return}if(Ce){a.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:h,delegationSessionId:$==null?void 0:$.delegation_session_id}),ue(null),se(null),Te(null),Me(!1),ee.current=!1;return}if(!(x!=null&&x.fetchPlatformResponse)){a.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),Me(!1);return}if(Ee.current){a.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(ne.current===o){a.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(ee.current){a.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}a.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var J,j,he,ve,oe,ze,me,ke,Ie;try{ee.current=!0,Me(!0),Te(null);const Y=await x.fetchPlatformResponse({query:s.trim(),sessionId:h,messageId:o,language:R,location:K,userId:B,model:C,...D&&D.length>0&&{messages:D}}),Se=(Y==null?void 0:Y.status)||"unknown";if(!be(Y)){if(Se==="no_match"){a.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),ue(null),se(null),Te(null),Me(!1),ee.current=!1,ne.current=o,I(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${Se})`)}ue(Y),a.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:Y.recommendation_id,format:(J=Y.recommendation)==null?void 0:J.format,brandName:(he=(j=Y.recommendation)==null?void 0:j.creative)==null?void 0:he.brand_name,headline:(oe=(ve=Y.recommendation)==null?void 0:ve.creative)==null?void 0:oe.headline,hasTracking:!!Y.tracking});let H=((ze=Y.recommendation)==null?void 0:ze.format)||"tail";(H==="weave"||H==="product_card")&&(H="tail"),se(H),ne.current=o,I(o,Y),a.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(me=Y.recommendation)==null?void 0:me.format,selected_format:H}),Me(!1),ee.current=!1,(ke=xe.current)==null||ke.call(xe,o,Y)}catch(Y){const Se=Y instanceof Error?Y:new Error(String(Y));Se.message.includes("Failed to fetch")||Se.message.includes("NetworkError")?a.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${Se.message} `):a.error(`[AdMeshRecommendations] โ Error fetching recommendations: ${Se.message} `),Te(Se),Me(!1),ee.current=!1,(Ie=Oe.current)==null||Ie.call(Oe,Se)}})()},[$==null?void 0:$.delegation_session_id,Ce,x,h,o,s,R,K,B,C,d,I]),l.useEffect(()=>{var J,j,he,ve;if(!L||!f)return;const p=(j=(J=L.recommendation)==null?void 0:J.creative)!=null&&j.follow_up_suggestion&&((he=L.tracking)!=null&&he.followup_engagement_url)&&((ve=L.tracking)!=null&&ve.followup_exposure_url)?{label:L.recommendation.creative.follow_up_suggestion,query:L.recommendation.creative.follow_up_suggestion,engagement_url:L.tracking.followup_engagement_url,exposure_url:L.tracking.followup_exposure_url}:null;p&&f(p,L.recommendation_id)},[L,f]);const nt=l.useCallback(async p=>{if(!x||!h)throw new Error("AdMesh SDK activation requires an initialized session");const J=await fetch(`${x.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${E}`},body:JSON.stringify({session_id:h,recommendation_id:p.recommendation_id,metadata:p.metadata})});if(!J.ok){const oe=await J.text();throw new Error(`Failed to activate delegation session: ${J.status} ${oe}`)}const j=await J.json(),he={...p,delegation_session_id:j.delegation_session_id||p.delegation_session_id,session_id:j.session_id||h,brand_id:j.brand_id||p.brand_id,brand_name:j.brand_name||p.brand_name,mcp_endpoint:j.mcp_endpoint,eligibility_reason:j.eligibility_reason||p.eligibility_reason,delegate_reason:j.delegate_reason||p.delegate_reason,session_goal:j.session_goal||p.session_goal,desired_outcome_type:j.desired_outcome_type||p.desired_outcome_type,required_user_inputs:j.required_user_inputs||p.required_user_inputs||[],required_consent_types:j.required_consent_types||p.required_consent_types||[],success_outcome:j.success_outcome||p.success_outcome,fallback_message:j.fallback_message||p.fallback_message,session_mode:"inline",status:j.status||"active",capabilities:j.capabilities||p.capabilities||[],allowed_data_types:j.allowed_data_types||p.allowed_data_types||[],auth_model:j.auth_model||p.auth_model,handoff_protocol:j.handoff_protocol||p.handoff_protocol,supported_actions:j.supported_actions||p.supported_actions||[],metadata:j.metadata||p.metadata},ve={delegation_session_id:j.delegation_session_id,recommendation_id:p.recommendation_id,session_id:j.session_id||h,brand_agent_id:j.brand_agent_id,brand_id:j.brand_id||p.brand_id,brand_name:j.brand_name||p.brand_name||"Brand",mcp_endpoint:j.mcp_endpoint,status:j.status||"active",activated_at:j.created_at,last_activity_at:j.updated_at,expires_at:j.expires_at||j.updated_at,eligibility_reason:j.eligibility_reason||p.eligibility_reason,delegate_reason:j.delegate_reason||p.delegate_reason,session_goal:j.session_goal||p.session_goal,desired_outcome_type:j.desired_outcome_type||p.desired_outcome_type,required_user_inputs:j.required_user_inputs||p.required_user_inputs||[],required_consent_types:j.required_consent_types||p.required_consent_types||[],success_outcome:j.success_outcome||p.success_outcome,fallback_message:j.fallback_message||p.fallback_message,capabilities:j.capabilities||p.capabilities||[],allowed_data_types:j.allowed_data_types||p.allowed_data_types||[],consent_requirements:j.consent_requirements||p.consent_requirements||[],auth_model:j.auth_model||p.auth_model,handoff_protocol:j.handoff_protocol||p.handoff_protocol,supported_actions:j.supported_actions||p.supported_actions||[],metadata:j.metadata||p.metadata};if(G(ve),await x.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:h,recommendation_id:p.recommendation_id,delegation_session_id:j.delegation_session_id,brand_name:ve.brand_name,status:j.status||"active",metadata:{brand_agent_id:j.brand_agent_id,source:"recommendation_card"}}).catch(oe=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",oe)}),await x.reportDelegationSessionStarted(ve,{brand_agent_id:j.brand_agent_id,brand_name:ve.brand_name}).then(oe=>{oe&&G(oe)}).catch(oe=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",oe)}),c){try{await c(he)}catch(oe){a.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",oe)}return}if(g)try{await g({...p.platform_response,delegation:{...p.platform_response.delegation,...he,delegation_session_id:j.delegation_session_id,available:!0,status:j.status||"active"}})}catch(oe){a.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",oe)}},[E,c,g,x,h,G]),z=l.useCallback(async p=>{var J,j;if(S){await S(p);return}!x||!h||await x.reportSponsoredRecommendation({session_id:h,message_id:o,recommendation_id:p.recommendation_id,reason:p.reason,brand_name:(j=(J=p.recommendation.recommendation)==null?void 0:J.creative)==null?void 0:j.brand_name,metadata:{reason:p.reason,source:"recommendation_card"}}).catch(he=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to report sponsored recommendation:",he)})},[o,S,x,h]);if(!o||!s||s.trim()===""||$e||qe)return null;if(!L||!_e)return a.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!L,detectedFormat:_e,isLoading:$e,hasError:!!qe}),null;a.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:L.recommendation_id,detectedFormat:_e,brandName:(ie=(V=L.recommendation)==null?void 0:V.creative)==null?void 0:ie.brand_name,headline:(Ae=(ae=L.recommendation)==null?void 0:ae.creative)==null?void 0:Ae.headline});const O=typeof document<"u"&&w&&(y??!0)?document.getElementById(w):null;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:r.jsx(Pn,{recommendations:[L],theme:P,sessionId:h,triggerExposureUrl:u,onPasteToInput:b,onDelegationConsent:k,onDelegationActivated:nt,onStartDelegation:g,onRecommendationReport:z})}),O&&x&&h?yr.createPortal(r.jsx(Er,{recommendation:L,theme:P,sdk:x,sessionId:h,onExecuteQuery:M}),O):null]})},Rr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:d})=>{const{sdk:u,sessionId:w,theme:b,apiKey:k,language:c,location:g,userId:S,model:M,messages:f}=Ot(),y=l.useRef(null),[x,h]=l.useState("");return l.useEffect(()=>{o&&h(`admesh-weave-fallback-${o}`)},[o]),a.log("[WeaveFallbackRecommendations] ๐จ Component render"),l.useEffect(()=>{if(a.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:i,hasPreviousRecommendations:d&&d.length>0,previousRecommendationsCount:(d==null?void 0:d.length)||0}),!i){a.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(a.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){a.log("[WeaveFallbackRecommendations] โ Validation failed - returning early");return}if(a.log("[WeaveFallbackRecommendations] โ
Validation passed"),!u||!x){a.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const E=d&&d.length>0;a.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:E,count:(d==null?void 0:d.length)||0,fallback:i,messageId:o}),E?(a.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${d.length} previous recommendation(s), skipping API call`),(async()=>{var K,A,C,D,P,N,T;try{const I=d[0];if(a.log("[WeaveFallbackRecommendations] ๐ฆ Processing AIP response:",{hasAipResponse:!!I,recommendationId:(I==null?void 0:I.recommendation_id)||"",format:((K=I==null?void 0:I.recommendation)==null?void 0:K.format)||"unknown"}),I&&process.env.NODE_ENV==="development"&&a.log("[WeaveFallbackRecommendations] ๐ Recommendation received (DEV):",{recommendation_id:I==null?void 0:I.recommendation_id,click_url:((A=I==null?void 0:I.tracking)==null?void 0:A.click_url)||((D=(C=I==null?void 0:I.recommendation)==null?void 0:C.creative)==null?void 0:D.landing_page_url),format:(P=I==null?void 0:I.recommendation)==null?void 0:P.format,full_response:I}),!I){a.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:x,sessionId:w,messageId:o});return}const $=u,G=$.getRenderer,X=$.getTracker,be=(N=$.config)==null?void 0:N.theme;if(G&&X){const B={sessionId:w,messageId:o,recommendations:[I]},L=G.call(u),ue=X.call(u),_e=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await L.render({containerId:x,response:B,theme:b||be,tracker:ue,sessionId:w,apiKey:k||((T=u==null?void 0:u.config)==null?void 0:T.apiKey),apiBaseUrl:_e,language:c,location:g,userId:S,model:M,messages:f}),a.log("[WeaveFallbackRecommendations] โ
Recommendations rendered from previous response (no API call)")}else a.warn("[WeaveFallbackRecommendations] โ ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:x,sessionId:w,messageId:o})}catch(I){const $=I instanceof Error?I:new Error(String(I));a.error(`[WeaveFallbackRecommendations] โ Error rendering previous recommendations: ${$.message}`);try{await u.showRecommendations({query:s.trim(),containerId:x,sessionId:w,messageId:o})}catch{e==null||e($)}}})()):(a.log("[WeaveFallbackRecommendations] ๐ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){a.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:x,sessionId:w,messageId:o}),a.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(K){const A=K instanceof Error?K:new Error(String(K));a.log(`[WeaveFallbackRecommendations] โ Error: ${A.message}`),e==null||e(A)}})())},[u,w,x,t,o,s,i,e,d,b]),!i||!o||!s||s.trim()===""?null:r.jsx("div",{ref:y,id:x,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Tr=l.createContext(void 0),Fo=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>r.jsx(Tr.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),Wo=()=>l.useContext(Tr),jn=t=>{try{return new URL(t),!0}catch{return!1}},pr=t=>t&&t.trim()?t.trim():"",Rt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",ht=t=>Rt(t)||void 0,Bo=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},Uo=(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 Rt(t)},Ho=(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=Rt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},ge={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"},qo=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:b,onPasteToInput:k})=>{var j,he,ve,oe,ze,me,ke,Ie,Y,Se,H,Ge,lt,St,F,rt,dt,At,Tt,ot,It,gt,Dt,q,ye,st,Ye,Ve,Ne,xt,ct,Pt,$t;if(!t||t.length===0)return a.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],g=((j=c==null?void 0:c.recommendation)==null?void 0:j.offerId)||"",S=((he=c==null?void 0:c.tracking)==null?void 0:he.exposure_url)||"",M=(c==null?void 0:c.recommendation_id)||"",f=((oe=(ve=c==null?void 0:c.recommendation)==null?void 0:ve.creative)==null?void 0:oe.description)||"",y=((ze=c==null?void 0:c.recommendation)==null?void 0:ze.disclosure)||"Sponsored",x=((ke=(me=c==null?void 0:c.recommendation)==null?void 0:me.creative)==null?void 0:ke.brand_name)||"",h=((Y=(Ie=c==null?void 0:c.recommendation)==null?void 0:Ie.creative)==null?void 0:Y.headline)||((H=(Se=c==null?void 0:c.recommendation)==null?void 0:Se.creative)==null?void 0:H.brand_name)||"",E=((lt=(Ge=c==null?void 0:c.recommendation)==null?void 0:Ge.creative)==null?void 0:lt.logo_url)||"",R=((St=c==null?void 0:c.tracking)==null?void 0:St.click_url)||((rt=(F=c==null?void 0:c.recommendation)==null?void 0:F.creative)==null?void 0:rt.landing_page_url)||"",K=pr((At=(dt=c==null?void 0:c.recommendation)==null?void 0:dt.creative)==null?void 0:At.cta_text),A=((ot=(Tt=c==null?void 0:c.recommendation)==null?void 0:Tt.creative)==null?void 0:ot.products)||[],C=A.length>1,D=C?A.slice(0,4):[],P=((It=c==null?void 0:c.recommendation)==null?void 0:It.format)||"tail",N=P==="bridge",T=((gt=c==null?void 0:c.delegation)==null?void 0:gt.brand_name)||x,I=((Dt=c==null?void 0:c.delegation)==null?void 0:Dt.available)===!0,$=N&&I,G="Talk to Agent",X=!C&&!!K&&!!R;if(!x&&!h&&!f)return a.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:x,hasFirstRecommendation:!!c,recommendationId:M,recommendationKeys:c?Object.keys(c):[]}),null;let be=x,B="";h&&h!==x&&(B=h),B&&(be=`${x} โ ${B}`),a.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:M,productId:g,exposureUrl:S?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:R||"MISSING",clickUrlSource:(q=c==null?void 0:c.tracking)!=null&&q.click_url?"tracking.click_url":(st=(ye=c==null?void 0:c.recommendation)==null?void 0:ye.creative)!=null&&st.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:f?"present":"MISSING",brandName:x,productName:h,headlineText:be,triggerExposureUrl:d}),a.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:M,brandName:x,productName:h,hasDescription:!!f,hasClickUrl:!!R,hasLogoUrl:!!E,recommendationFormat:P});const L=(U,Fe)=>{Fe&&Fe.stopPropagation(),a.log(`AdMesh tail ad ${U} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:M,productId:g,clickUrl:R,source:U}).catch(()=>{a.error(`[AdMesh] Failed to track ${U} click`)})},ue=U=>{U.stopPropagation(),L("tail_ad_brand_name")},_e=U=>{U.stopPropagation(),L("tail_ad_cta")},se=U=>{U.stopPropagation(),L("tail_ad_logo")},$e=()=>{C||!R||(L("tail_ad_card"),typeof window<"u"&&window.open(R,"_blank","noopener,noreferrer"))},Me=U=>{C||!R||(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),$e())},[qe,Te]=l.useState(!1),ne=l.useRef(null);l.useEffect(()=>()=>{ne.current&&(ne.current(!1),ne.current=null)},[]);const ee=U=>{var Fe;(Fe=ne.current)==null||Fe.call(ne,U),ne.current=null,Te(!1)},Ee=async()=>u?await u(c):await new Promise(U=>{ne.current=U,Te(!0)}),xe=async()=>{if(M&&i)try{const U=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",Fe=await fetch(`${U}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:M,session_id:i,is_test:!1})});Fe.ok||a.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",Fe.statusText)}catch(U){a.error("[AdMesh Tail Ad] Error tracking delegation engagement:",U)}},Oe=async U=>{var ut,Be,Le,bt;if(U.preventDefault(),U.stopPropagation(),!c||!$)return;if(L("tail_ad_delegation_cta"),await xe(),!await Ee()){a.log("[AdMesh Tail Ad] Delegation consent declined");return}const ce=c.delegation,Ct=ce!=null&&ce.available?{recommendation_id:c.recommendation_id,brand_id:ht(ce.brand_id),brand_name:ht(ce.brand_name||((Be=(ut=c.recommendation)==null?void 0:ut.creative)==null?void 0:Be.brand_name)),eligibility_reason:ht(ce.eligibility_reason),delegate_reason:ht(ce.delegate_reason),session_goal:ht(ce.session_goal),desired_outcome_type:ce.desired_outcome_type,required_user_inputs:Array.isArray(ce.required_user_inputs)?ce.required_user_inputs.filter(yt=>typeof yt=="string"):[],required_consent_types:Array.isArray(ce.required_consent_types)?ce.required_consent_types.filter(yt=>typeof yt=="string"):[],success_outcome:ht(ce.success_outcome),fallback_message:ht(ce.fallback_message),session_mode:ht(ce.session_mode),status:ht(ce.status),capabilities:ce.capabilities||[],allowed_data_types:ce.allowed_data_types||[],consent_requirements:ce.consent_requirements||[],auth_model:ht(ce.auth_model),handoff_protocol:ce.handoff_protocol&&typeof ce.handoff_protocol=="object"?ce.handoff_protocol:void 0,supported_actions:ce.supported_actions||[],metadata:ce.metadata&&typeof ce.metadata=="object"?ce.metadata:void 0,platform_response:c}:null;if(w&&Ct){await w(Ct);return}if(b){await b(c);return}const et=((bt=(Le=c.recommendation)==null?void 0:Le.creative)==null?void 0:bt.follow_up_suggestion)||"";if(et&&k){k(et);return}if(et&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(et);return}},[Ce,nt]=l.useState(!1),z=x?x.charAt(0).toUpperCase():"B",O=ge.surface,V=ge.border,ie=(e==null?void 0:e.borderRadius)||((Ve=(Ye=e==null?void 0:e.components)==null?void 0:Ye.card)==null?void 0:Ve.borderRadius)||"8px",ae="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",Ae="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",p=((Ne=e==null?void 0:e.shadows)==null?void 0:Ne.medium)||((ct=(xt=e==null?void 0:e.components)==null?void 0:xt.card)==null?void 0:ct.boxShadow)||ae,J=((Pt=e==null?void 0:e.shadows)==null?void 0:Pt.large)||Ae;return r.jsxs(Zt,{productId:g,recommendationId:M,exposureUrl:S,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:[r.jsx("style",{children:`
|
|
132
132
|
.admesh-tail-product-scroll {
|
|
133
133
|
-ms-overflow-style: none;
|
|
134
134
|
scrollbar-width: none;
|
|
@@ -139,11 +139,11 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
139
139
|
width: 0;
|
|
140
140
|
height: 0;
|
|
141
141
|
}
|
|
142
|
-
`}),r.jsxs("div",{className:"tail-ad-container flex flex-col gap-3 sm:flex-row",role:!
|
|
142
|
+
`}),r.jsxs("div",{className:"tail-ad-container flex flex-col gap-3 sm:flex-row",role:!C&&R?"link":void 0,tabIndex:!C&&R?0:void 0,style:{...($t=e==null?void 0:e.components)==null?void 0:$t.card,backgroundColor:O,borderRadius:ie,padding:"16px",boxShadow:p,border:`1px solid ${V}`,color:ge.text,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",cursor:!C&&R?"pointer":void 0},onClick:$e,onKeyDown:Me,onMouseEnter:U=>{U.currentTarget.style.boxShadow=J,U.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:U=>{U.currentTarget.style.boxShadow=p,U.currentTarget.style.transform="translateY(0)"},children:[E&&r.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:!Ce&&jn(E)?r.jsx("a",{href:R||"#",target:R?"_blank":void 0,rel:R?"noopener noreferrer":void 0,onClick:R?se:void 0,className:"block",style:{cursor:R?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:r.jsx("img",{src:E,alt:`${x} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{nt(!0),a.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):r.jsx("div",{className:"flex items-center justify-center text-lg font-semibold",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px",backgroundColor:ge.logoFallbackBg,color:ge.logoFallbackText,fontSize:"18px"},children:z})}),r.jsxs("div",{className:"flex-1",style:{width:"100%",minWidth:0},children:[be&&!C&&r.jsx("div",{className:"mb-2",children:r.jsx("h3",{className:"font-semibold text-base",style:{fontSize:"14px",lineHeight:1.35,color:ge.text},children:R&&x?r.jsxs(r.Fragment,{children:[r.jsx("a",{href:R,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-semibold",style:{color:ge.link,textDecoration:"underline",textDecorationColor:ge.link,textUnderlineOffset:"2px"},onClick:ue,children:x}),B&&` โ ${B}`]}):be})}),f&&!C&&r.jsx("p",{className:"text-sm mb-3 leading-relaxed",style:{fontSize:"13px",lineHeight:1.45,color:ge.textSecondary},children:f}),C&&D.length>0&&r.jsx("div",{className:"mb-3",children:r.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:r.jsx("div",{style:{display:"flex",gap:"10px",minWidth:"max-content",scrollSnapType:"x proximity",paddingRight:0},children:D.map(U=>{const Fe=Rt(U.product_name)||"Product",ce=Rt(U.product_link)||Rt(U.product_url)||R||"#",Ct=Bo(Rt(U.product_description),10),et=Uo(U.product_price,U.product_currency),ut=Ho(U.product_discount,U.product_discount_type,U.product_currency),Be=Rt(U.product_image_url),Le=E&&jn(E)?E:"",bt=Be&&jn(Be)?Be:Le,yt=pr(U.product_cta_label),Ut=ce!=="#";return r.jsx("a",{href:ce,target:Ut?"_blank":void 0,rel:Ut?"noopener noreferrer":void 0,onClick:mn=>L(`tail_ad_product_${U.product_id||"item"}`,mn),className:"block",style:{border:`1px solid ${V}`,borderRadius:"8px",padding:"10px",backgroundColor:ge.surfaceMuted,textDecoration:"none",color:ge.text,minWidth:"min(264px, 82vw)",width:"clamp(220px, 72vw, 312px)",flex:"0 0 clamp(220px, 72vw, 312px)",scrollSnapAlign:"start"},children:r.jsxs("div",{className:"flex items-start gap-2",children:[bt?r.jsx("img",{src:bt,alt:Fe,style:{width:"44px",height:"44px",objectFit:"cover",borderRadius:"6px",flexShrink:0}}):r.jsx("div",{className:"flex items-center justify-center text-xs font-semibold",style:{width:"44px",height:"44px",borderRadius:"6px",flexShrink:0,backgroundColor:ge.productImageFallbackBg,color:ge.textSecondary,fontSize:"12px"},children:Fe.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("p",{className:"font-medium text-sm",style:{fontSize:"13px",lineHeight:1.3,color:ge.text,marginBottom:"4px"},children:Fe}),Ct&&r.jsx("p",{className:"text-xs",style:{fontSize:"12px",lineHeight:1.3,color:ge.textSecondary,marginBottom:"6px"},children:Ct}),(et||ut)&&r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{marginBottom:yt?"6px":0},children:[et&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{style:{fontSize:"10px",color:ge.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Price"}),r.jsx("span",{className:"font-semibold",style:{fontSize:"13px",color:ge.text},children:et})]}),ut&&r.jsx("span",{className:"text-xs",style:{fontSize:"11px",color:ge.successText,backgroundColor:ge.successBg,borderRadius:"999px",padding:"2px 8px",fontWeight:600},children:ut})]}),yt&&r.jsx("span",{className:"font-medium",style:{fontSize:"12px",color:ge.link,textDecoration:"underline",textUnderlineOffset:"2px"},children:yt})]})]})},U.product_id||`${M}-${Fe}`)})})})}),r.jsxs("div",{className:"mt-2 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[C&&x&&r.jsx("span",{className:"text-sm",style:{fontSize:"13px",color:ge.textSecondary,fontWeight:400},children:x}),$?r.jsx("button",{type:"button",onClick:Oe,className:"underline transition-colors duration-200 font-medium text-sm",style:{color:ge.link,textDecoration:"underline",textDecorationColor:ge.link,textUnderlineOffset:"2px",fontSize:"13px",background:"none",border:"none",padding:0,cursor:"pointer"},children:G}):null,X&&r.jsx("a",{href:R,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-medium text-sm",style:{color:ge.link,textDecoration:"underline",textDecorationColor:ge.link,textUnderlineOffset:"2px",fontSize:"13px"},onClick:_e,children:K}),C&&A.length>D.length&&r.jsxs("span",{className:"text-xs",style:{fontSize:"11px",color:ge.textMuted},children:["+",A.length-D.length," more"]})]}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsx("p",{className:"text-xs",style:{fontSize:"11px",color:ge.textMuted},children:y})})]}),qe?r.jsxs("div",{style:{marginTop:"10px",border:`1px solid ${V}`,borderRadius:"12px",backgroundColor:ge.surfaceSubtle,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:ge.link},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"14px",lineHeight:1.4,color:ge.text,fontWeight:600},children:["Allow ",T||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:ge.textSecondary},children:"The agent will only use the details you choose to share for this request."})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[r.jsx("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),ee(!1)},style:{borderRadius:"10px",border:`1px solid ${V}`,background:O,color:ge.text,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),ee(!0)},style:{borderRadius:"10px",border:"none",background:"#2563eb",color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})]})},Ir=({recommendationId:t,admeshLink:e,productId:o,children:s,trackingData:i,className:d,style:u})=>{const w=l.useRef(null);l.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 b=l.useCallback(k=>{const g=k.target.closest("a");g?((!g.href||g.href==="#"||g.href==="")&&e&&(g.href=e),(!g.hasAttribute("target")||g.getAttribute("target")!=="_blank")&&(g.setAttribute("target","_blank"),g.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):a.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return r.jsx("div",{ref:w,className:d,onClick:b,style:{cursor:"pointer",...u},children:s})};Ir.displayName="AdMeshLinkTracker";function Oo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var En={exports:{}};/*!
|
|
143
143
|
Copyright (c) 2018 Jed Watson.
|
|
144
144
|
Licensed under the MIT License (MIT), see
|
|
145
145
|
http://jedwatson.github.io/classnames
|
|
146
|
-
*/var
|
|
146
|
+
*/var hr;function Vo(){return hr||(hr=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})()})(En)),En.exports}var Ko=Vo();const Go=Oo(Ko),Yo={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Qo={"Top Match":"โ
","Free Tier":"โ","AI Powered":"โ",Popular:"โฒ",New:"โ","Trial Available":"โ"},Dr=({type:t,variant:e,size:o="md",className:s,style:i})=>{const d=e||Yo[t]||"secondary",u=Qo[t],w=Go("admesh-component","admesh-badge",`admesh-badge--${d}`,`admesh-badge--${o}`,s);return r.jsxs("span",{className:w,style:i,children:[u&&r.jsx("span",{className:"admesh-badge__icon",children:u}),r.jsx("span",{className:"admesh-badge__text",children:t})]})};Dr.displayName="AdMeshBadge";const Rn="admesh-ui-sdk-styles",Tn="admesh-ui-sdk-reset",Xo=`
|
|
147
147
|
/* AdMesh UI SDK - CSS Reset & Normalization */
|
|
148
148
|
.admesh-component,
|
|
149
149
|
.admesh-component * {
|
|
@@ -232,7 +232,7 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
232
232
|
.admesh-component[data-admesh-theme="light"] {
|
|
233
233
|
color-scheme: light;
|
|
234
234
|
}
|
|
235
|
-
`,
|
|
235
|
+
`,Jo=`
|
|
236
236
|
/* AdMesh Core Component Styles */
|
|
237
237
|
|
|
238
238
|
.admesh-component {
|
|
@@ -443,7 +443,7 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
443
443
|
font-size: 0.875rem;
|
|
444
444
|
}
|
|
445
445
|
}
|
|
446
|
-
`,
|
|
446
|
+
`,Zo=()=>{if(!(typeof document>"u")&&!(document.getElementById(Tn)&&document.getElementById(Rn))){if(!document.getElementById(Tn)){const t=document.createElement("style");t.id=Tn,t.textContent=Xo,document.head.appendChild(t)}if(!document.getElementById(Rn)){const t=document.createElement("style");t.id=Rn,t.textContent=Jo,document.head.appendChild(t)}}},es=`
|
|
447
447
|
/* AdMesh UI SDK - Complete Self-Contained Styles */
|
|
448
448
|
|
|
449
449
|
/* CSS Reset for AdMesh components */
|
|
@@ -1111,15 +1111,15 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
|
|
|
1111
1111
|
.admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
1112
1112
|
.admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
|
|
1113
1113
|
}
|
|
1114
|
-
`;let
|
|
1115
|
-
${
|
|
1116
|
-
| `),
|
|
1117
|
-
`),
|
|
1118
|
-
`).map(E=>E.trim()).filter(Boolean)),
|
|
1119
|
-
`),
|
|
1120
|
-
`)},
|
|
1121
|
-
`),
|
|
1122
|
-
`)})(t).split(/\n\s*\n/).map(
|
|
1123
|
-
`).map(k=>k.trim()).filter(Boolean),p=f.every(k=>/^[-*]\s+/.test(k)),E=f.every(k=>/^\d+\.\s+/.test(k)),I=f.length===1&&/^#{1,3}\s+/.test(f[0]),G=v(f);if(I){const k=f[0].replace(/^#{1,3}\s+/,"");return r.jsx("h3",{style:{marginTop:b===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(k)},b)}if(G){const{heading:k,lines:S}=g(f),L=i(S[0]),N=S.slice(2).map(i).filter(B=>B.length===L.length);return r.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[k?r.jsx("p",{style:{marginTop:b===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(k)}):null,r.jsx("div",{style:{border:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,borderRadius:8,overflowX:"auto"},children:r.jsxs("table",{style:{width:"100%",minWidth:L.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[r.jsx("thead",{children:r.jsx("tr",{children:L.map((B,$)=>r.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(B)},$))})}),r.jsx("tbody",{children:N.map((B,$)=>r.jsx("tr",{children:B.map((z,D)=>r.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:$===N.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(z)},D))},$))})]})})]},b)}if(p||E){const k=E?"ol":"ul";return r.jsx(k,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:f.map((S,L)=>r.jsx("li",{style:{marginBottom:"0.45rem"},children:s(S.replace(/^([-*]|\d+\.)\s+/,""))},L))},b)}return r.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:f.map((k,S)=>r.jsxs(l.Fragment,{children:[S>0&&r.jsx("br",{}),s(k)]},S))},b)})})};function Qt(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function Nt(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 c=s.length?s:o;return[i,...c].slice(0,4)}function ts(t,e,o,s){const i=new Set,c=[],u=(C,m="information")=>{const b=Nt(C);if(!b)return;const f=b.toLowerCase();i.has(f)||(i.add(f),c.push({id:`followup_${c.length}_${f.replace(/[^a-z0-9]+/g,"_")}`,text:b,type:m,is_sponsored:!1}))},y=new Set,g=C=>{const m=Nt(C||"");if(!m)return;const b=m.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();b&&y.add(b)};(s||[]).forEach(C=>g(C==null?void 0:C.title)),(o||[]).forEach(C=>g(C==null?void 0:C.title)),e.split(/\n+/).map(C=>Nt(C.replace(/^[-*]\s+/,""))).filter(Boolean).filter(C=>C.length>=24&&C.length<=90).forEach(C=>{y.size>=6||g(C)});const d=Nt(t.replace(/[?.!]+$/g,"")),h=Array.from(y).slice(0,3);return[h[0]?`Tell me more about ${h[0]}`:"",h[1]?`Show me examples related to ${h[1]}`:"",h[2]?`Compare the main options for ${h[2]}`:"","Break this down more simply",`What should I look at next about ${d}`,"Give me the practical takeaway here"].forEach((C,m)=>{c.length>=3||u(C,m===0?"comparison":"information")}),c.slice(0,3)}function ns(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function Er(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 ur(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Er(e))return e}catch{return}}function mr(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=ur()||(Er(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=ur()?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:ns()}}function rs(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:Nt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Mn(t){return[...t].sort((e,o)=>{const s=!!e.is_sponsored,i=!!o.is_sponsored;return s===i?0:s?-1:1})}const os={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)"}},ss={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},is={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},as=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:c,showHeaderTitle:u=!0,showSubtitle:y=!0,layout:g="floating",surface:v="page",panelWidth:d,panelHeight:h,analyticsPageUrl:w,fontScale:C=1,position:m="bottom-right",size:b="md",defaultOpen:f,open:p,onOpenChange:E,autoOpen:I=!1,showWelcomeMessage:G=!1,welcomeMessage:k="Hi, Iโm Ava. Iโll help you find the best options.",placeholder:S="Ask me anything about products...",adsEnabled:L=!0,suggestions:N,maxSuggestions:B=6,suggestionStyle:$="carousel",onlyShowWhenSponsored:z=!1,variant:D="default",queryHandler:Q,suggestionsLoader:J,disclaimerText:ge,poweredByLabel:V="Powered by AdMesh",subtitle:ee="Publisher Assistant",onOpen:me,onClose:xe})=>{const{sdk:q,sessionId:oe,theme:ve,apiKey:Ne,userId:Pe}=Ht(),{suggestions:be,isAnalyzingIntent:we,intentError:Se,retryIntentAnalysis:_e,activeDelegationSession:Fe,hasActiveDelegationSession:Ee,stopDelegationSession:rt,refreshDelegationActivity:F}=Rn();jr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:q,sessionId:oe,hasContextTheme:!!ve});const _=t||ve||os,H=(_==null?void 0:_.mode)||"light",A=v==="ad-slot",[ie,ke]=l.useState(f||I),T=p!==void 0,se=T?p:ie,[j,ce]=l.useState(""),[re,Y]=l.useState([]),[K,ae]=l.useState(!1),[Be,Te]=l.useState(null),[M,Ce]=l.useState(!1),[Ie,ot]=l.useState(new Set),[yt,et]=l.useState(N||be||[]),[jt,ut]=l.useState(0),[Et,_t]=l.useState(0),[mt,Rt]=l.useState({}),st=l.useRef(null),Ve=l.useRef(!1),ze=l.useRef(null),O=l.useRef(new Map),fe=l.useRef([]),Ue=l.useRef(null),Ke=l.useRef(null),tt=l.useRef(null),pt=l.useRef(!1),wt=l.useRef(!1),Tt=l.useRef(null),It=l.useRef(null),Wt=l.useRef(null),U=l.useRef(null),ye=l.useRef(null),[de,Dt]=l.useState(!1),[Je,vt]=l.useState(!1),kt=!!(Ne!=null&&Ne.toLowerCase().startsWith("pub_")),$e=Ee()&&(Fe==null?void 0:Fe.session_id)===oe?Fe:null,ht=l.useRef(new Set),it=l.useRef(new Set),qt=l.useRef(!1),Ot=A&&(M||re.length>0||K),ft=Qt(d)??"100%",Bt=Qt(h)??"100%",en=l.useCallback(n=>x=>{x?O.current.set(n,x):O.current.delete(n)},[]),Me=l.useCallback(async(n,x={})=>{if(!(!q||!oe))try{await q.trackPublisherAssistantEvent({event_name:n,timestamp:new Date().toISOString(),session_id:oe,...mr(w),...x})}catch(R){console.warn(`[AdMeshIntentAssistant] Failed to track ${n}`,R)}},[w,q,oe]),tn=l.useCallback((n,x,R)=>{var te,je;const P=x==null?void 0:x.recommendation_id;if(!P)return;const W=`${n}:${P}`;it.current.has(W)||(it.current.add(W),Me("recommendation_shown",{message_id:n,query:R,recommendation_id:P,brand_name:(je=(te=x.recommendation)==null?void 0:te.creative)==null?void 0:je.brand_name,is_sponsored:!0}))},[Me]),un=l.useCallback((n,x,R,P,W,te)=>{const je=Array.isArray(te)&&te.length?te.map((Re,Ae)=>{const Le=Nt(Re.text||"");return Le?{id:`followup_llm_${Ae}_${Le.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:Le,type:Re.type||"information",is_sponsored:!1}:null}).filter(Re=>!!Re).slice(0,3):ts(n,x,R,P),He=rs(W),qe=He?[He,...je.slice(0,2)]:je.slice(0,3);qe.length&&et(Mn(qe))},[]),nn=l.useCallback((n,x)=>{const R=Nt(n.query||n.label||"");if(!R||!x)return;const P={id:x,text:R,type:"action",is_sponsored:!0,recommendation:{recommendation_id:x,recommendation:{creative:{follow_up_suggestion:R}},tracking:{followup_engagement_url:n.engagement_url,followup_exposure_url:n.exposure_url}}};et(W=>{const te=W.filter(je=>!je.is_sponsored).slice(0,3);return Mn([P,...te].slice(0,4))})},[]),In=l.useCallback(()=>{const n=Ue.current,x=Ke.current;if(!n||!x)return!1;const R=n.getBoundingClientRect(),P=x.getBoundingClientRect(),W=Math.max(0,n.scrollTop+P.top-R.top);return n.scrollTop=W,!0},[]);l.useLayoutEffect(()=>{var n;if(pt.current){In()&&(pt.current=!1);return}wt.current||(n=It.current)==null||n.scrollIntoView({behavior:"smooth"})},[re,In]),l.useLayoutEffect(()=>{if(!A)return;const n=Tt.current;if(!n)return;const x=n.closest(".admesh-publisher-assistant-reactMount"),R=Bt;[n,x].forEach(W=>{W&&(W.style.width=ft,W.style.maxWidth=ft,W.style.height=R,W.style.maxHeight=R,W.style.overflow="hidden",W.style.boxSizing="border-box",W.dataset.admeshAdSlotExpanded=Ot?"true":"false")});const P=x==null?void 0:x.parentElement;P&&P!==document.body&&P!==document.documentElement&&(P.style.width=ft,P.style.maxWidth=ft,P.style.height=R,P.style.maxHeight=R,P.style.overflow="hidden",P.style.boxSizing="border-box")},[Bt,ft,A,Ot]),l.useEffect(()=>{if(N&&N.length){et(N);return}be&&be.length&&et(n=>es(n,be))},[N,be]),l.useEffect(()=>{if(D!=="default"||!J)return;let n=!1;return J().then(x=>{!n&&Array.isArray(x)&&x.length&&et(x)}).catch(x=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",x)}),()=>{n=!0}},[J,D]),l.useEffect(()=>{if(!K){_t(0),st.current=null;return}st.current==null&&(st.current=typeof performance<"u"?performance.now():Date.now());const n=()=>{const R=st.current;if(R==null)return;const P=typeof performance<"u"?performance.now():Date.now();_t(Math.floor((P-R)/1e3))};n();const x=window.setInterval(n,1e3);return()=>window.clearInterval(x)},[K]),l.useEffect(()=>{if(!K||D!=="default"){ut(0);return}const n=window.setInterval(()=>{ut(x=>Math.min(x+1,7))},3e3);return()=>window.clearInterval(n)},[K,D]),l.useEffect(()=>{qt.current||!q||!oe||(qt.current=!0,Me("assistant_loaded",{metadata:{layout:g,surface:v,variant:D,default_open:f||I}}))},[I,f,g,q,oe,v,Me,D]);const St=l.useCallback(n=>{T?E==null||E(n):ke(n),n?(Me("assistant_opened",{metadata:{layout:g,surface:v,variant:D,expanded:M}}),me==null||me()):xe==null||xe()},[T,M,g,E,me,xe,v,Me,D]),Dn=l.useCallback(()=>{St(!0)},[St]),Tr=l.useCallback(()=>{St(!1)},[St]),Ir=l.useCallback(()=>{Ce(n=>!n)},[]),Pn=l.useCallback(async(n,x,R,P,W,te,je)=>{var He,qe,Re;if(!q)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{$e&&await F("turn_started",{source:"publisher_assistant",recommendation_id:$e.recommendation_id}).catch(ue=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",ue)});const Ae=await fetch(`${q.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:te,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${Ne}`},body:JSON.stringify({message:n,session_id:oe||"default-session",message_id:x,user_id:Pe,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:mr(w),conversation_history:je,sponsored_recommendation:W!=null&&W.recommendation_id?{recommendation_id:W.recommendation_id,brand_name:(qe=(He=W.recommendation)==null?void 0:He.creative)==null?void 0:qe.brand_name}:void 0,active_delegation_session:$e?{delegation_session_id:$e.delegation_session_id,recommendation_id:$e.recommendation_id,session_id:$e.session_id,brand_name:$e.brand_name,mcp_endpoint:$e.mcp_endpoint,status:$e.status}:void 0}})});if(!Ae.ok)throw new Error(`API request failed: ${Ae.status} ${Ae.statusText}`);const Le=(Re=Ae.body)==null?void 0:Re.getReader(),Pt=new TextDecoder;if(!Le)throw new Error("Response body is not readable");let Ye="",Ze,$t,bt,X,ne;return await(async()=>{try{for(;;){const{done:ue,value:nt}=await Le.read();if(ue)break;const Xe=Pt.decode(nt,{stream:!0}).split(`
|
|
1124
|
-
`);for(const zt of Xe)if(zt.startsWith("data: ")){const _n=zt.slice(6);if(_n.trim()==="[DONE]")return $e&&F("turn_completed",{source:"publisher_assistant",recommendation_id:$e.recommendation_id}).catch(De=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",De)}),{text:Ye,source_links:Ze,related_items:$t,followup_suggestions:bt,used_capability:X,response_time_ms:ne};try{const De=JSON.parse(_n);switch(De.type){case"content":{const Qn=De.content||"";Ye+=Qn,R==null||R(Qn);break}case"final":{Ye=De.reply||Ye,Ze=Array.isArray(De.source_links)?De.source_links:void 0,$t=Array.isArray(De.related_items)?De.related_items:void 0,bt=Array.isArray(De.followup_suggestions)?De.followup_suggestions:void 0,X=typeof De.used_capability=="string"?De.used_capability:X,ne=typeof De.response_time_ms=="number"?De.response_time_ms:ne;break}case"followup_suggestions":{bt=Array.isArray(De.followup_suggestions)?De.followup_suggestions:bt;break}case"error":throw new Error(De.message||"Unknown streaming error");case"session_start":P==null||P(),console.log("Session started:",De.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",_n);continue}}}}catch(ue){if(te!=null&&te.aborted)return{text:Ye,source_links:Ze,related_items:$t,followup_suggestions:bt,used_capability:X,response_time_ms:ne,error:"aborted"};throw console.error("Stream processing error:",ue),ue}finally{Le.releaseLock()}return{text:Ye,source_links:Ze,related_items:$t,followup_suggestions:bt,used_capability:X,response_time_ms:ne}})()}catch(Ae){return te!=null&&te.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",Ae),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:Ae instanceof Error?Ae.message:"request_failed"})}},[q,oe,Ne,Pe,$e,F]),mn=l.useCallback(()=>{const n=U.current;if(!n||n.signal.aborted)return;n.abort(),ae(!1),ze.current=null,Ve.current=!1;const x=ye.current;x&&Y(R=>R.map(P=>P.id===x&&!P.content.trim()?{...P,content:"Generation stopped."}:P))},[]),At=l.useCallback(async n=>{var Re,Ae,Le,Pt,Ye,Ze,$t,bt;if(!n.trim()||K)return;const x=typeof performance<"u"?performance.now():Date.now(),R=n.trim(),P=Date.now().toString(),W=new AbortController,te=ze.current,je=(te==null?void 0:te.recommendation)||null,He=re.filter(X=>(X.role==="user"||X.role==="assistant")&&X.content.trim()).slice(-6).map(X=>({role:X.role,content:X.content.trim().slice(0,1200)}));U.current=W,ye.current=null,tt.current=P,pt.current=!0,wt.current=!0,ze.current=null,et(X=>X.some(ne=>ne.is_sponsored)?X.filter(ne=>!ne.is_sponsored):X),Te(null);const qe={id:P,role:"user",content:R,timestamp:new Date};if(Me("query_submitted",{message_id:P,query:R}),Y(X=>[...X,qe]),ce(""),ae(!0),D==="default"&&Q){try{const X=(Date.now()+1).toString(),ne={id:X,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:null};Ve.current&&(ot(nt=>new Set([...nt,X])),Ve.current=!1),Y(nt=>[...nt,ne]),ye.current=X;const We=await Q(R,{sponsoredSuggestion:te});if(W.signal.aborted){ze.current=null;return}const ue=We.recommendation||je||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:n,hasResponseRecommendation:!!We.recommendation,hasSponsoredSuggestionRecommendation:!!je,finalRecommendationId:ue==null?void 0:ue.recommendation_id}),Y(nt=>nt.map(Qe=>Qe.id===X?{...Qe,content:We.answer,sourceLinks:We.source_links,relatedItems:We.related_items,initialRecommendation:ue,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-x}:Qe)),un(R,We.answer,We.source_links,We.related_items,We.recommendation||null,We.followup_suggestions),Me("answer_completed",{message_id:X,query:R,recommendation_id:ue==null?void 0:ue.recommendation_id,brand_name:(Ae=(Re=ue==null?void 0:ue.recommendation)==null?void 0:Re.creative)==null?void 0:Ae.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:"completed",metadata:{variant:D,source:"query_handler"}}),ze.current=null}catch(X){console.error("Error sending message:",X);const ne=X instanceof Error?X.message:"Unknown error occurred";Te(ne);const We={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Y(ue=>[...ue,We]),Me("answer_failed",{query:R,status:ne,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,metadata:{variant:D,source:"query_handler"}}),ze.current=null}finally{U.current===W&&(U.current=null,ye.current=null,ae(!1))}return}if(!q){setTimeout(()=>{if(W.signal.aborted){U.current===W&&(U.current=null,ye.current=null);return}const X={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:n};Y(ne=>[...ne,X]),U.current===W&&(U.current=null,ye.current=null,ae(!1))},1e3);return}try{const X=(Date.now()+1).toString(),ne=je,We={id:X,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:ne};Ve.current&&(ot(Qe=>new Set([...Qe,X])),Ve.current=!1),Y(Qe=>[...Qe,We]),ye.current=X;const ue=await Pn(R,P,Qe=>{Y(Xe=>Xe.map(zt=>zt.id===X?{...zt,content:zt.content+Qe}:zt))},()=>{ae(!0),ut(0)},ne,W.signal,He);if(W.signal.aborted){ue.text.trim()||Y(Qe=>Qe.map(Xe=>Xe.id===X&&!Xe.content.trim()?{...Xe,content:"Generation stopped."}:Xe)),Me("answer_failed",{message_id:X,query:R,recommendation_id:ne==null?void 0:ne.recommendation_id,brand_name:(Pt=(Le=ne==null?void 0:ne.recommendation)==null?void 0:Le.creative)==null?void 0:Pt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:"aborted",metadata:{variant:D,source:"api_chat_assistant"}}),ze.current=null;return}const nt=typeof ue.response_time_ms=="number"?ue.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-x;Y(Qe=>Qe.map(Xe=>Xe.id===X?{...Xe,content:ue.text,sourceLinks:ue.source_links,relatedItems:ue.related_items,initialRecommendation:Xe.initialRecommendation||ne,responseTimeMs:nt}:Xe)),un(R,ue.text,ue.source_links,ue.related_items,null,ue.followup_suggestions),ue.error?Me("answer_failed",{message_id:X,query:R,recommendation_id:ne==null?void 0:ne.recommendation_id,brand_name:(Ze=(Ye=ne==null?void 0:ne.recommendation)==null?void 0:Ye.creative)==null?void 0:Ze.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:ue.error,metadata:{variant:D,source:"api_chat_assistant"}}):Me("answer_completed",{message_id:X,query:R,recommendation_id:ne==null?void 0:ne.recommendation_id,brand_name:(bt=($t=ne==null?void 0:ne.recommendation)==null?void 0:$t.creative)==null?void 0:bt.brand_name,used_capability:ue.used_capability,latency_ms:nt,status:"completed",metadata:{variant:D,source:"api_chat_assistant",response_time_ms:nt}}),ze.current=null}catch(X){console.error("Error sending message:",X);const ne=X instanceof Error?X.message:"Unknown error occurred";Te(ne);const We={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Y(ue=>[...ue,We]),Me("answer_failed",{query:R,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:ne,metadata:{variant:D,source:"api_chat_assistant"}}),ze.current=null}finally{U.current===W&&(U.current=null,ye.current=null,ae(!1))}},[K,Pn,Q,un,q,Me,D]),Ct=yt,rn=l.useMemo(()=>Ct.some(n=>n==null?void 0:n.is_sponsored),[Ct]),on=l.useMemo(()=>Ct.filter(n=>!(n&&typeof n.id=="string")?!1:z?rn:!0),[rn,z,Ct]),Ge=l.useMemo(()=>Mn(on),[on]),sn=l.useCallback(async n=>{var R,P,W,te,je,He,qe;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:n.text,is_sponsored:n.is_sponsored,hasRecommendation:!!n.recommendation,recommendationId:((R=n.recommendation)==null?void 0:R.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((W=(P=n.recommendation)==null?void 0:P.tracking)!=null&&W.followup_engagement_url),sessionId:oe}),Ve.current=n.is_sponsored||!1,ze.current=n.is_sponsored?n:null;const x=Ge.findIndex(Re=>Re.id===n.id);Me("suggestion_clicked",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:x>=0?x:void 0,is_sponsored:n.is_sponsored,recommendation_id:(te=n.recommendation)==null?void 0:te.recommendation_id,brand_name:(qe=(He=(je=n.recommendation)==null?void 0:je.recommendation)==null?void 0:He.creative)==null?void 0:qe.brand_name,query:n.text}),At(n.text),n.is_sponsored&&n.recommendation&&q?setTimeout(async()=>{var Re;try{const Ae=(Re=n.recommendation.tracking)==null?void 0:Re.followup_engagement_url,Le=n.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:Ae,recommendationId:Le,sessionId:oe}),Ae&&Le&&oe?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await q.fireFollowupEngagement(Ae,Le,oe),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!Ae,hasRecommendationId:!!Le,hasSessionId:!!oe})}catch(Ae){console.error("[AdMeshIntentAssistant] โ Error firing sponsored suggestion engagement:",Ae)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[At,Ge,q,oe,Me]),an=is[m],$n=ss[b];l.useEffect(()=>{if(fe.current.forEach(n=>n()),fe.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return Ge.forEach((n,x)=>{const R=O.current.get(n.id);if(!R)return;const P=`${oe||"anonymous"}:${n.id}:${n.is_sponsored?"s":"o"}`;if(ht.current.has(P))return;let W=null,te=null;const je=()=>{W&&(clearTimeout(W),W=null),te==null||te.disconnect(),te=null},He=()=>{var qe,Re,Ae,Le,Pt;if(ht.current.has(P)){je();return}if(ht.current.add(P),je(),Me("suggestion_exposure",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:x,is_sponsored:n.is_sponsored,recommendation_id:(qe=n.recommendation)==null?void 0:qe.recommendation_id,brand_name:(Le=(Ae=(Re=n.recommendation)==null?void 0:Re.recommendation)==null?void 0:Ae.creative)==null?void 0:Le.brand_name}),q&&oe&&n.is_sponsored&&n.recommendation){const Ye=(Pt=n.recommendation.tracking)==null?void 0:Pt.followup_exposure_url,Ze=n.recommendation.recommendation_id;Ye&&Ze?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Ye,recommendationId:Ze,suggestionText:n.text,sessionId:oe}),q.fireFollowupExposure(Ye,Ze,oe)):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Ye,hasRecommendationId:!!Ze,suggestionText:n.text})}};te=new IntersectionObserver(qe=>{const Re=qe[0];if(Re){if(Re.intersectionRatio>=.5){W||(W=setTimeout(He,1e3));return}W&&(clearTimeout(W),W=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),te.observe(R),fe.current.push(je)}),()=>{fe.current.forEach(n=>n()),fe.current=[]}},[Ge,q,oe,Me]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:Ct.length,safeSuggestions:on.length,isAnalyzingIntent:we,hasIntentError:!!Se,onlyShowWhenSponsored:z,hasSponsoredSuggestions:rn,sponsoredCount:Ct.filter(n=>n==null?void 0:n.is_sponsored).length,nonSponsoredCount:Ct.filter(n=>n&&!(n!=null&&n.is_sponsored)).length,modalShouldAppear:z?rn:!0,suggestions:Ct.map(n=>{var x,R,P;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((x=n==null?void 0:n.recommendation)==null?void 0:x.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((P=(R=n==null?void 0:n.recommendation)==null?void 0:R.tracking)!=null&&P.followup_engagement_url)}}),renderedSuggestions:Ge.map(n=>{var x,R,P;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((x=n==null?void 0:n.recommendation)==null?void 0:x.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((P=(R=n==null?void 0:n.recommendation)==null?void 0:R.tracking)!=null&&P.followup_engagement_url)}})});const pe={base:`${16*C}px`,sm:`${14*C}px`,xs:`${12*C}px`},pn=ge||"AI-generated responses may contain errors. Please verify important information independently.",Dr=["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..."],Vt=n=>{const x=(n==null?void 0:n.accentColor)||at,R=(n==null?void 0:n.metaColor)||Gt,P=(n==null?void 0:n.includeSteps)??D==="default",W=`${Et}s`,te=P?`${Dr[jt]} (${W})`:`Generating answer... ${W}`;return r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:n!=null&&n.compact?"8px":"10px",color:R,fontSize:n!=null&&n.compact?pe.xs:pe.sm},children:[r.jsx("span",{style:{width:n!=null&&n.compact?8:9,height:n!=null&&n.compact?8:9,borderRadius:999,background:x,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${Z(le,.28)}`,flexShrink:0}}),r.jsx("span",{children:te})]})},zn=l.useCallback((n,x)=>{if(mt[n.id])return;const R=x?"helpful":"not_helpful";Rt(P=>({...P,[n.id]:R})),Me("answer_feedback",{message_id:n.id,query:n.userQuery,status:R,latency_ms:n.responseTimeMs,metadata:{helpful:x}})},[mt,Me]);function hn(n,x){if(n.role!=="assistant"||!n.content.trim()||K&&n.id===ye.current)return null;const R=(x==null?void 0:x.accentColor)||at,P=(x==null?void 0:x.metaColor)||Gt,W=mt[n.id],te=typeof n.responseTimeMs=="number";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${Z(le,.08)}`,flexWrap:"wrap"},children:[r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto",flexWrap:"wrap"},children:[r.jsx("span",{style:{fontSize:pe.xs,color:P,whiteSpace:"nowrap"},children:W?"Thanks for your feedback":"Is this helpful?"}),W?r.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,background:Z(R,.12),color:R,flexShrink:0},children:W==="helpful"?r.jsx(er,{size:14}):r.jsx(Zn,{size:14})}):r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[r.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>zn(n,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${Z(le,.12)}`,background:"#ffffff",color:P,cursor:"pointer"},children:r.jsx(er,{size:14})}),r.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>zn(n,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${Z(le,.12)}`,background:"#ffffff",color:P,cursor:"pointer"},children:r.jsx(Zn,{size:14})})]})]}),te?r.jsxs("span",{style:{fontSize:pe.xs,color:P,whiteSpace:"nowrap",flex:"0 1 auto",marginLeft:"auto"},children:["Answer Completed in ",Zo(n.responseTimeMs)]}):null]})}const Kt=l.useCallback(()=>{const n=Wt.current;if(!n)return;const x=Math.max(0,n.scrollWidth-n.clientWidth);Dt(n.scrollLeft>4),vt(n.scrollLeft<x-4)},[]);l.useEffect(()=>(Kt(),window.addEventListener("resize",Kt),()=>window.removeEventListener("resize",Kt)),[Kt,Ge.length]);const Ln=l.useCallback(n=>{const x=Wt.current;x&&x.scrollBy({left:n==="left"?-Math.max(160,Math.floor(x.clientWidth*.75)):Math.max(160,Math.floor(x.clientWidth*.75)),behavior:"smooth"})},[]),Z=(n,x)=>{if(!n||!n.startsWith("#"))return`rgba(15, 23, 42, ${x})`;const R=n.slice(1),P=R.length===3?R.split("").map(He=>`${He}${He}`).join(""):R;if(P.length!==6)return n;const W=parseInt(P.slice(0,2),16),te=parseInt(P.slice(2,4),16),je=parseInt(P.slice(4,6),16);return`rgba(${W}, ${te}, ${je}, ${x})`},le=_.primaryColor||"#3F037F";_.surfaceColor,_.backgroundColor;const Nn=_.borderColor||"#e5e7eb",gt=_.textColor||"#111827",Pr=_.textSecondaryColor||"#6b7280";Z(le,.12);const fn=Z(le,.24);Z(le,.38);const $r=Z(le,.12),zr=A?ft:M?"min(960px, calc(100vw - 24px))":g==="inline"?"100%":"min(420px, calc(100vw - 32px))",Fn=A?Bt:M?"min(78vh, 760px)":"auto",Lr=A?ft:"100%",Nr=A?Bt:void 0,Wn=A?"13px":"16.25px",Fr=`linear-gradient(180deg, ${Z(le,.04)} 0%, ${Z(le,.08)} 100%)`,at=le,Gt=Pr,Bn=ee||"Publisher Assistant",Yt=we&&Ge.length===0&&re.length===0,gn="#f7f8fc",xn="linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(248,250,252,0.98) 100%)",xt="rgba(15, 23, 42, 0.08)",Un="rgba(15, 23, 42, 0.12)",Hn="0 24px 60px rgba(15, 23, 42, 0.16)",bn="#667085",qn="#98a2b3",Wr=at,On="#ffffff",Vn="0 8px 24px rgba(15, 23, 42, 0.08)",Kn="rgba(15, 23, 42, 0.18)";function Gn(n){return $e?r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:n==="default"?"10px 12px":"8px 10px",borderRadius:n==="default"?"14px":"12px",border:`1px solid ${fn}`,background:Z("#ffffff",.9),marginBottom:"4px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{color:at,fontSize:pe.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),r.jsxs("div",{style:{color:gt,fontSize:pe.sm,fontWeight:600,lineHeight:1.3},children:[$e.brand_name," agent is active"]})]}),r.jsx("button",{type:"button",onClick:()=>{rt("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${fn}`,borderRadius:999,background:Z("#ffffff",.92),color:at,padding:"7px 12px",fontSize:pe.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function Yn(n){const x=A;return r.jsxs("div",{style:{display:"flex",flexDirection:x?"column":"row",alignItems:x||n==="default"?"center":"flex-start",justifyContent:x?"center":"space-between",gap:x?"2px":"12px",flexWrap:"wrap",paddingTop:x||n==="default"?"2px":"8px",borderTop:n==="default"?`1px solid ${xt}`:"none",marginTop:x?"0":n==="default"?"4px":0,flexShrink:0},children:[r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:x?"4px":"8px",color:qn,fontSize:x?"9.5px":"11px",fontWeight:700,letterSpacing:"0.01em"},children:r.jsxs("span",{children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]})}),r.jsx("div",{style:{color:qn,fontSize:x?"9px":"11px",lineHeight:x?1.25:1.45,maxWidth:x?"100%":n==="default"?"68%":"100%",textAlign:x?"center":n==="default"?"right":"left"},children:pn})]})}function yn(n){const x=n==="publisher"?[180,220,196]:["100%","82%","68%"];return n==="publisher"?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Z(le,.1),flexShrink:0}}),r.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:x.map((R,P)=>r.jsx("div",{style:{width:R,maxWidth:"100%",height:40,borderRadius:999,background:`linear-gradient(90deg, ${Z(le,.08)} 0%, ${Z(le,.18)} 50%, ${Z(le,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:`0 8px 22px ${Z(le,.08)}`,flexShrink:0}},`suggestion-skeleton-${P}`))}),r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Z(le,.1),flexShrink:0}})]}):r.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:n==="publisher"?"10px":"12px"},children:x.map((R,P)=>r.jsx("div",{style:{width:R,maxWidth:"100%",height:n==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${Z(le,.08)} 0%, ${Z(le,.18)} 50%, ${Z(le,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:n==="publisher"?`0 8px 22px ${Z(le,.08)}`:"none"}},`suggestion-skeleton-${P}`))})}function Br(){if(K)return null;if(Yt)return yn("publisher");if(!Ge.length)return null;const n=Ge.slice(0,B);return $==="stacked"?r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:A?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:A?"240px":void 0,paddingRight:A?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:n.map(x=>r.jsxs("button",{ref:en(x.id),onClick:()=>{D==="default"&&(Ce(!0),g==="floating"&&St(!0)),sn(x)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:A?"12px":"14px",border:x.is_sponsored?`1px solid ${Z(le,.32)}`:`1px solid ${Z(le,.42)}`,background:x.is_sponsored?le:Z("#ffffff",.94),color:x.is_sponsored?"#ffffff":gt,padding:A?"8px 10px":"10px 14px",fontSize:A?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:x.is_sponsored?`0 8px 18px ${Z(le,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{style:{minWidth:0},children:x.text}),L&&x.is_sponsored&&r.jsx("span",{style:{flexShrink:0,borderRadius:999,background:Z("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},x.id))}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:A?"6px":"10px",flexShrink:0},children:[r.jsx("button",{type:"button",onClick:()=>Ln("left"),disabled:!de,"aria-label":"Scroll suggestions left",style:{width:A?24:28,height:A?24:28,borderRadius:999,border:`1px solid ${Z(Nn,.8)}`,background:Z("#ffffff",.9),color:"#6b7280",cursor:de?"pointer":"default",opacity:de?1:.55},children:"โน"}),r.jsx("div",{ref:Wt,onScroll:Kt,style:{display:"flex",gap:A?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:n.map(x=>r.jsxs("button",{ref:en(x.id),onClick:()=>{D==="default"&&(Ce(!0),g==="floating"&&St(!0)),sn(x)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:"8px",whiteSpace:"nowrap",borderRadius:999,border:x.is_sponsored?`1px solid ${Z(le,.32)}`:`1px solid ${Z(le,.42)}`,background:x.is_sponsored?le:Z("#ffffff",.94),color:x.is_sponsored?"#ffffff":gt,padding:A?"7px 10px":"8px 14px",fontSize:A?"12px":"13px",fontWeight:500,boxShadow:x.is_sponsored?`0 8px 18px ${Z(le,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{children:x.text}),L&&x.is_sponsored&&r.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},x.id))}),r.jsx("button",{type:"button",onClick:()=>Ln("right"),disabled:!Je,"aria-label":"Scroll suggestions right",style:{width:A?24:28,height:A?24:28,borderRadius:999,border:`1px solid ${Z(Nn,.8)}`,background:Z("#ffffff",.9),color:"#6b7280",cursor:Je?"pointer":"default",opacity:Je?1:.55},children:"โบ"})]})}function Ur(n){var x,R;return(x=n.relatedItems)!=null&&x.length||!((R=n.sourceLinks)!=null&&R.length)?null:r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:n.sourceLinks.map(P=>r.jsx("a",{href:P.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Me("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:P.title,source_url:P.url}})},style:{color:at,fontSize:pe.xs,textDecoration:"none",borderBottom:`1px solid ${Z(le,.18)}`},children:P.title||P.url},`${n.id}-${P.url}`))})}function Hr(n){var x;return(x=n.relatedItems)!=null&&x.length?r.jsxs("div",{style:{marginTop:"14px"},children:[r.jsx("div",{style:{fontSize:pe.xs,fontWeight:700,color:"#4b5563",marginBottom:"8px"},children:"Related"}),r.jsx("div",{style:{display:"flex",gap:A?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:n.relatedItems.slice(0,4).map(R=>r.jsxs("a",{href:R.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Me("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:R.title,source_url:R.url,source_publisher:R.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:A?"6px":"10px",padding:A?"10px":"14px",borderRadius:A?"12px":"14px",textDecoration:"none",color:gt,border:`1px solid ${Z(le,.18)}`,background:"#ffffff",boxShadow:"0 10px 24px rgba(15, 23, 42, 0.08)",flex:A?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:A?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[r.jsx("div",{style:{fontSize:A?"13px":"18px",fontWeight:650,lineHeight:1.35,color:le,overflowWrap:"anywhere"},children:R.title||R.url}),R.publisher&&r.jsx("div",{style:{fontSize:A?"11px":"15px",color:"#6b7280",lineHeight:1.4,overflowWrap:"anywhere"},children:R.publisher})]},`${n.id}-${R.url}`))})]}):null}function qr(){return r.jsxs("div",{ref:Ue,style:{flex:A?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none",padding:A?"0 2px 4px":M?"16px 16px 8px":0},children:[re.map(n=>{const x=n.role==="user"&&n.id===tt.current;return r.jsx("div",{ref:x?Ke:void 0,style:{marginBottom:"12px",textAlign:n.role==="user"?"right":"left"},children:(()=>{const P=!!n.content.trim()||!K;return r.jsx(r.Fragment,{children:r.jsxs("div",{style:{display:n.role==="assistant"?"block":"inline-block",width:n.role==="assistant"?"100%":void 0,maxWidth:n.role==="assistant"?"100%":"76%",padding:n.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:n.role==="assistant"?0:"18px",background:n.role==="user"?at:"transparent",color:n.role==="user"?"#ffffff":gt,boxShadow:"none",border:"none",fontSize:n.role==="assistant"?Wn:A?"12px":"13px",lineHeight:n.role==="assistant"?1.62:1.4},children:[n.role==="assistant"?n.content.trim()?r.jsx(Cn,{content:n.content,theme:{..._,textColor:gt},fontSize:Wn}):K&&n.id===ye.current?Vt({includeSteps:!0}):null:r.jsx("p",{style:{margin:0},children:n.content}),n.role==="assistant"&&Ur(n),n.role==="assistant"&&Hr(n),n.role==="assistant"&&hn(n),n.role==="assistant"&&P&&Ie.has(n.id)&&n.initialRecommendation&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:nn,onRecommendationsShown:(W,te)=>{tn(W,te,n.userQuery)},onError:W=>{console.error("[AdMeshIntentAssistant] Recommendation error:",W)}})}),n.role==="assistant"&&P&&!Ie.has(n.id)&&(n.initialRecommendation||kt)&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation||void 0,onFollowupDetected:nn,onRecommendationsShown:(W,te)=>{tn(W,te,n.userQuery)},onError:W=>{console.error("[AdMeshIntentAssistant] Recommendation error:",W)}})})]})})})()},n.id)}),Be&&r.jsx("div",{style:{color:Gt,fontSize:pe.sm},children:"Connection issue. Please try again."}),r.jsx("div",{ref:It})]})}if(D==="default"){const n=r.jsxs("div",{style:{width:zr,maxWidth:Lr,height:Fn,maxHeight:Nr,boxSizing:"border-box",display:"flex",flexDirection:"column",background:M?gn:Fr,borderRadius:A?"12px":M?"18px":"20px",padding:M?0:A?"8px":"12px",boxShadow:M?Hn:"none",border:M?`1px solid ${Un}`:"none",overflow:"hidden",minHeight:A?0:void 0},children:[(M||A)&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:A?"10px 12px":"16px 18px",background:M?xn:"#ffffff29",color:gt,borderBottom:`1px solid ${xt}`,flexShrink:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("div",{style:{width:A?30:40,height:A?30:40,borderRadius:A?"10px":"14px",background:Z(le,.08),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:at,overflow:"hidden"},children:c?r.jsx("img",{src:c,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||y)&&r.jsxs("div",{children:[u&&r.jsx("div",{style:{fontSize:A?"14px":"20px",fontWeight:700,lineHeight:1.1,letterSpacing:0},children:i}),y&&r.jsx("div",{style:{fontSize:A?"10px":"12px",color:bn,marginTop:"2px"},children:Bn})]})]}),!A&&r.jsx("button",{type:"button",onClick:()=>Ce(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"12px",border:`1px solid ${xt}`,background:"#ffffff",color:bn,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx("span",{style:{fontSize:"18px",lineHeight:1,fontWeight:700,transform:"translateY(-1px)"},children:"-"})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:A?"6px":"16px",minHeight:0,flex:A?"1 1 0":void 0,overflow:A?"hidden":void 0,overscrollBehavior:"contain",padding:A?"8px 10px 6px":M?"18px":"14px",background:M?gn:Z("#ffffff",.16),height:A?void 0:M?Fn:"auto"},children:[Gn("default"),M&&qr(),A&&!M&&r.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),A&&!M&&G&&re.length===0&&r.jsx("div",{style:{color:gt,fontSize:"15px",lineHeight:1.3,fontWeight:700,letterSpacing:0,padding:"2px 2px 0",textAlign:"center"},children:k}),Br(),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",borderRadius:A?"12px":"16px",background:On,padding:A?"6px 6px 6px 10px":"8px 8px 8px 14px",boxShadow:M?Vn:`0 8px 22px ${$r}`,border:`1px solid ${M?xt:fn}`,flexShrink:0},children:[r.jsx("input",{type:"text",value:j,onChange:x=>ce(x.target.value),onKeyPress:x=>{if(x.key==="Enter"){if(x.preventDefault(),K)return;ze.current=null,Ve.current=!1,Ce(!0),g==="floating"&&St(!0),At(j)}},placeholder:S,style:{flex:1,border:"none",outline:"none",borderRadius:"12px",padding:A?"8px 2px":"10px 4px",color:gt,fontSize:A?"13px":"15px",background:"transparent"}}),r.jsx("button",{type:"button",onClick:()=>{if(K){mn();return}ze.current=null,Ve.current=!1,Ce(!0),g==="floating"&&St(!0),At(j)},disabled:!K&&!j.trim(),style:{border:"none",borderRadius:"12px",background:K?"#dc2626":at,color:"#ffffff",minWidth:A?"40px":"48px",height:A?"36px":"44px",padding:A?"0 10px":"0 16px",fontSize:A?"12px":"14px",fontWeight:700,cursor:!K&&!j.trim()?"default":"pointer",opacity:!K&&!j.trim()?.6:1,boxShadow:`0 10px 20px ${K?"rgba(220, 38, 38, 0.18)":Z(le,.18)}`},children:K?"Stop":"Send"})]}),M&&Yn("default"),!M&&r.jsxs("div",{style:{textAlign:"center",paddingTop:"2px"},children:[r.jsxs("div",{style:{color:Gt,fontSize:A?"9.5px":pe.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),r.jsx("div",{style:{color:Gt,fontSize:A?"9px":pe.xs,lineHeight:A?1.25:1.5},children:pn})]})]})]});return g==="inline"?A?r.jsx("div",{ref:Tt,className:"admesh-component","data-admesh-theme":H,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-expanded":Ot?"true":"false",style:{width:ft,height:Bt,maxWidth:ft,maxHeight:Bt,position:"relative",overflow:"hidden"},children:n}):r.jsxs("div",{className:"admesh-component","data-admesh-theme":H,style:{width:"100%",position:"relative"},children:[n,M&&r.jsx("div",{style:{position:"fixed",inset:0,background:Kn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),M&&r.jsx("div",{style:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",zIndex:2147483001},children:n})]}):se?r.jsxs("div",{className:"admesh-component","data-admesh-theme":H,children:[M&&r.jsx("div",{style:{position:"fixed",inset:0,background:Kn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),r.jsx("div",{style:{position:"fixed",...M?{left:"50%",bottom:"12px",transform:"translateX(-50%)"}:an,zIndex:2147483001},children:n})]}):r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsx("button",{type:"button",onClick:Dn,style:{position:"fixed",...an,zIndex:2147483e3,border:"none",borderRadius:999,background:_.primaryColor,color:"#ffffff",padding:"14px 18px",boxShadow:"0 18px 40px rgba(15, 23, 42, 0.18)",cursor:"pointer"},children:s})})}return Ge.length===0&&!Yt?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):g==="inline"?r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:Qt(d)??"100%",backgroundColor:"#eef2ff",fontSize:pe.base,...o},children:r.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[Yt?yn("legacy"):Ge.length>0&&r.jsx("div",{className:"flex flex-col gap-3",children:Ge.slice(0,B).map((n,x)=>r.jsxs("button",{ref:en(n.id),onClick:()=>sn(n),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:x===0?"100%":x===1?"82%":"68%",backgroundColor:_.surfaceColor||"#ffffff",color:_.textColor||"#1e293b",border:`1px solid ${_.borderColor||"#e2e8f0"}`,fontSize:pe.sm},children:[r.jsx("span",{className:"leading-tight",children:n.text}),L&&n.is_sponsored&&r.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:_.backgroundColor||"#ffffff",color:_.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},n.id))}),re.length>0&&r.jsxs("div",{ref:Ue,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:_.textColor,overscrollBehavior:"contain",WebkitOverflowScrolling:"touch"},children:[re.map(n=>{const x=n.role==="user"&&n.id===tt.current;return r.jsx("div",{ref:x?Ke:void 0,className:n.role==="user"?"text-right":"text-left",children:r.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:n.role==="user"?_.primaryColor:"#ffffff",color:n.role==="user"?"#ffffff":_.textColor,fontSize:pe.sm},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx(Cn,{content:n.content,theme:_,fontSize:pe.sm}),hn(n,{accentColor:_.primaryColor,metaColor:_.textSecondaryColor})]}):K&&n.id===ye.current?Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:n.content})})},n.id)}),K&&!re.some(n=>n.role==="assistant"&&n.id===ye.current&&!n.content.trim())&&r.jsx("div",{className:"text-sm",style:{color:_.textSecondaryColor},children:Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1})}),Be&&r.jsx("div",{className:"text-sm",style:{color:_.textSecondaryColor},children:"Connection issue. Please try again."}),r.jsx("div",{ref:It})]}),r.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{type:"text",value:j,onChange:n=>ce(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(K){n.preventDefault();return}At(j)}},placeholder:S,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:_.backgroundColor||"#ffffff",color:_.textColor,fontSize:pe.sm}}),r.jsx("button",{onClick:()=>{if(K){mn();return}At(j)},disabled:!K&&!j.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:K?"#dc2626":_.primaryColor,color:"#ffffff"},children:K?r.jsx(wn,{size:18}):r.jsx(Jn,{size:18})})]})}),r.jsxs("div",{className:"space-y-2 text-center",children:[r.jsxs("p",{style:{color:_.textSecondaryColor,fontSize:pe.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),r.jsx("p",{style:{color:_.textSecondaryColor,fontSize:pe.xs,lineHeight:1.5},children:pn})]})]})})}):se?r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...M?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...an,width:Qt(d)??$n.width,height:Qt(h)??$n.height},backgroundColor:M?gn:_.backgroundColor,zIndex:9999,fontSize:pe.base,borderRadius:M?"20px":"16px",border:M?`1px solid ${Un}`:"1px solid transparent",boxShadow:M?Hn:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[r.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:M?xt:"transparent",background:M?xn:_.backgroundColor,padding:M?"18px 20px":"16px"},children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{style:{width:M?40:32,height:M?40:32,borderRadius:M?"14px":"10px",background:Z(le,.08),color:at,display:"flex",alignItems:"center",justifyContent:"center",fontSize:M?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:c?r.jsx("img",{src:c,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||y&&M)&&r.jsxs("div",{children:[u&&r.jsx("div",{className:"font-medium",style:{color:_.textColor,fontSize:M?"20px":pe.base,fontWeight:700,letterSpacing:M?"-0.02em":0},children:i}),y&&M&&r.jsx("div",{style:{color:bn,fontSize:"12px",marginTop:"2px"},children:Bn})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[!A&&r.jsx("button",{onClick:Ir,className:"transition-colors",title:M?"Minimize":"Expand",style:{width:M?36:28,height:M?36:28,borderRadius:M?"12px":"10px",border:`1px solid ${M?xt:"transparent"}`,background:M?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:M?r.jsx(so,{size:16,style:{color:_.textSecondaryColor}}):r.jsx(ro,{size:16,style:{color:_.textSecondaryColor}})}),r.jsx("button",{onClick:Tr,className:"transition-colors",style:{width:M?36:28,height:M?36:28,borderRadius:M?"12px":"10px",border:`1px solid ${M?xt:"transparent"}`,background:M?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx(wn,{size:16,style:{color:_.textSecondaryColor}})})]})]}),r.jsxs("div",{ref:Ue,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:M?"20px":"16px"},children:[Gn("legacy"),G&&re.length===0&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",children:r.jsx("p",{style:{color:_.textColor,margin:0,fontSize:pe.sm},children:k})})}),re.map(n=>{const x=n.role==="user"&&n.id===tt.current;return r.jsxs("div",{ref:x?Ke:void 0,className:"mb-3",children:[r.jsx("div",{className:n.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:n.role==="user"?Wr:"transparent",color:n.role==="user"?"#ffffff":_.textColor,border:"none",borderRadius:n.role==="user"?M?"14px":"12px":0,padding:n.role==="user"?M?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{fontSize:`calc(${pe.sm} * 1.3)`,lineHeight:1.65},children:r.jsx(Cn,{content:n.content,theme:_,fontSize:`calc(${pe.sm} * 1.3)`})}),hn(n,{accentColor:_.primaryColor,metaColor:_.textSecondaryColor})]}):K&&n.id===ye.current?Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,fontSize:pe.sm,lineHeight:"1.4"},children:n.content})}),n.role==="assistant"&&!Ie.has(n.id)&&r.jsx(Xt,{messageId:n.id,query:n.userQuery,onFollowupDetected:nn,onRecommendationsShown:(R,P)=>{tn(R,P,n.userQuery)},onError:R=>{console.error("[AdMeshIntentAssistant] Recommendations error:",R)}}),n.role==="assistant"&&Ie.has(n.id)&&n.initialRecommendation&&!K&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:nn,onRecommendationsShown:(R,P)=>{tn(R,P,n.userQuery)},onError:R=>{console.error("[AdMeshIntentAssistant] Recommendations error:",R)}})]})]},n.id)}),K&&!re.some(n=>n.role==="assistant"&&n.id===ye.current&&!n.content.trim())&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1})})}),Be&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:_.textSecondaryColor},children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{style:{fontSize:pe.xs},children:"โ ๏ธ"}),r.jsx("span",{style:{fontSize:pe.sm},children:"Connection issue. Please try again."})]})})}),r.jsx("div",{ref:It})]}),re.length===0&&Yt&&r.jsx("div",{className:"px-4 pb-2",children:yn("legacy")}),Ge.length>0&&re.length===0&&!Yt&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:Ge.slice(0,B).map(n=>r.jsxs("button",{ref:en(n.id),onClick:()=>sn(n),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:_.surfaceColor||"#f8fafc",color:_.textColor||"#1e293b",border:`1px solid ${_.borderColor||"#e2e8f0"}`,fontSize:pe.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[r.jsx("span",{className:"leading-tight",children:n.text}),L&&n.is_sponsored&&r.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:_.backgroundColor||"#ffffff",color:_.textSecondaryColor||"#64748b"},children:"Ad"})]},n.id))})}),Se&&!we&&on.length===0&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:r.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:_.surfaceColor,borderColor:_.borderColor,color:_.textSecondaryColor},children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{style:{fontSize:pe.sm},children:"Intent analysis failed"}),r.jsx("button",{onClick:_e,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:_.primaryColor,color:"#ffffff"},children:"Retry"})]}),r.jsx("span",{style:{fontSize:pe.xs},children:Se})]})})}),r.jsxs("div",{className:"p-3 border-t",style:{borderColor:M?xt:"transparent",padding:M?"18px 20px":void 0,background:M?xn:void 0},children:[r.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${xt}`,borderRadius:M?"16px":"12px",background:On,boxShadow:M?Vn:"none",padding:M?"8px 8px 8px 14px":void 0},children:[r.jsx("input",{type:"text",value:j,onChange:n=>ce(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(K){n.preventDefault();return}At(j)}},placeholder:S,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:_.textColor,fontSize:M?"15px":pe.sm,"--tw-ring-color":_.primaryColor}}),r.jsx("button",{onClick:()=>{if(K){mn();return}At(j)},disabled:!K&&!j.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:K?"#dc2626":_.primaryColor,color:"#ffffff",borderRadius:M?"12px":"10px",width:M?"46px":void 0,height:M?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:M?`0 10px 20px ${Z(le,.18)}`:"none"},children:K?r.jsx(wn,{size:14}):r.jsx(Jn,{size:14})})]}),Yn("legacy")]})]})}):r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsx("button",{onClick:Dn,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",...an,backgroundColor:_.primaryColor,color:"#ffffff",zIndex:9999,fontSize:pe.base,...o},children:r.jsx("span",{className:"font-medium",children:s})})})},ln="admesh:streamingStart",cn="admesh:streamingComplete";function ls(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(ln,{detail:o});window.dispatchEvent(s),a.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function cs(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(cn,{detail:s});window.dispatchEvent(i),a.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function ds(t,e,o){const s=i=>{const c=i;c.detail.messageId===t&&c.detail.sessionId===e&&(a.log("[StreamingEvents] ๐จ Received streamingStart event"),o(c.detail))};return window.addEventListener(ln,s),()=>{window.removeEventListener(ln,s)}}function Rr(t,e,o){a.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const c=i;a.log("[StreamingEvents] ๐จ Received streamingComplete event (checking match)",{receivedMessageId:c.detail.messageId,receivedSessionId:c.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:c.detail.messageId===t,sessionIdMatch:c.detail.sessionId===e}),c.detail.messageId===t&&c.detail.sessionId===e?(a.log("[StreamingEvents] โ
Event matched! Calling callback"),o(c.detail)):a.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(cn,s),()=>{a.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(cn,s)}}const dn=()=>{const t=new Set,e=new Map,o=c=>{const u=e.get(c);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(c))};return{startTracking:({exposureUrl:c,recommendationId:u,linkElement:y,sessionId:g,logPrefix:v="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!c||!y){v&&a.warn(`${v} โ ๏ธ Missing exposure tracking data`);return}const d=`${g||"anonymous"}::${u||c}`;if(t.has(d)||e.has(d))return;const h={observer:void 0,timeoutId:null,viewableStart:null},w=()=>{o(d),t.add(d),fetch(c,{method:"GET",keepalive:!0}).then(()=>{v&&a.log(`${v} โ
Exposure pixel fired`)}).catch(()=>{v&&a.warn(`${v} โ ๏ธ Failed to fire exposure pixel`),t.delete(d)})},C=new IntersectionObserver(m=>{m.forEach(b=>{b.intersectionRatio>=.5?h.viewableStart===null&&(h.viewableStart=performance.now(),h.timeoutId=setTimeout(w,1e3)):(h.viewableStart=null,h.timeoutId&&(clearTimeout(h.timeoutId),h.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});h.observer=C,C.observe(y),e.set(d,h)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},us=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:c=[],onLinksFound:u,onNoLinksFound:y,children:g})=>{const[v,d]=l.useState(!1),[h,w]=l.useState(!0),[C,m]=l.useState(!1),b=l.useRef(dn()),f=l.useRef(u),p=l.useRef(y),E=l.useRef(t),I=l.useRef(s),G=l.useRef(o),k=l.useRef(i);l.useEffect(()=>{f.current=u,p.current=y,E.current=t,I.current=s,G.current=o,k.current=i},[u,y,t,s,o,i]),l.useEffect(()=>()=>{b.current.cleanup()},[]);const S=l.useCallback(({exposureUrl:N,recommendationId:B,linkElement:$})=>{b.current.startTracking({exposureUrl:N,recommendationId:B,linkElement:$,sessionId:G.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),L=l.useCallback(()=>{a.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const N=document.getElementById(E.current);if(!N){a.warn("[FinalLinkDetectionCheck] โ Container not found"),d(!0),y();return}const B=new Tn({autoAddLabels:!0,fireExposurePixels:!0}),$=c.length>0?c:[];a.log(`[FinalLinkDetectionCheck] ๐ Using ${$.length} recommendations for link detection`),$.length>0&&process.env.NODE_ENV==="development"&&$.forEach((D,Q)=>{var J,ge,V,ee,me,xe,q,oe,ve;a.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${Q+1} (DEV):`,{recommendation_id:D==null?void 0:D.recommendation_id,click_url:((J=D==null?void 0:D.tracking)==null?void 0:J.click_url)||((V=(ge=D==null?void 0:D.recommendation)==null?void 0:ge.creative)==null?void 0:V.landing_page_url),format:(ee=D==null?void 0:D.recommendation)==null?void 0:ee.format,brand_name:(q=(xe=(me=D.render)==null?void 0:me.creative)==null?void 0:xe.advertiser)==null?void 0:q.brand_name,cta_url:(ve=(oe=D.render)==null?void 0:oe.creative)==null?void 0:ve.landing_page_url})});const z=B.scanAndProcessLinks(N,$,({exposureUrl:D,recommendationId:Q,linkElement:J})=>S({exposureUrl:D,recommendationId:Q,linkElement:J}));a.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${z.length} links`),z.length>0?(a.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),m(!0),f.current(z.length)):(a.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${$.length} previous recommendation(s) if available)`),m(!1),p.current()),d(!0)}catch{a.error("[FinalLinkDetectionCheck] โ Error during final check"),d(!0),p.current()}},[S,c]);return l.useEffect(()=>{a.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:c.length});let N=null,B=!1;const $=Rr(e,o,z=>{a.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:z.messageId,sessionId:z.sessionId,timestamp:z.timestamp}),B=!0,N&&(clearTimeout(N),N=null),w(!1),setTimeout(()=>{L()},100)});return N=setTimeout(()=>{B||(a.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),w(!1),setTimeout(()=>{L()},100))},5e3),()=>{a.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),N&&clearTimeout(N),$()}},[e,o]),h?r.jsx(r.Fragment,{}):v?C?(a.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),r.jsx(r.Fragment,{})):(a.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),r.jsx(r.Fragment,{children:g})):r.jsx(r.Fragment,{})},ms=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:c,className:u,query:y,onFallbackChange:g,onWeaveAttempt:v,onWeaveOutcome:d})=>{var D,Q;const{sessionId:h,sdk:w,language:C,location:m,userId:b,model:f,messages:p}=Ht(),E=l.useRef(null),I=`weave-ad-container-${t}`,G=l.useRef(dn()),k=l.useRef(!1),S=l.useRef(null),[L,N]=l.useState([]),B=l.useRef([]);l.useEffect(()=>(S.current||(S.current=new Tn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{S.current&&(S.current.stopWatching(),S.current.clearCache())}),[]),l.useEffect(()=>()=>{G.current.cleanup()},[]),l.useEffect(()=>{(async()=>{var ge;if(!w||!(y!=null&&y.trim())||!t){a.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{a.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const V=await w.fetchPlatformResponse({query:y.trim(),sessionId:h,messageId:t,language:C,location:m,userId:b,model:f,messages:p}),ee=(V==null?void 0:V.status)==="generated"?[V]:[];if(N(ee),B.current=ee,a.log("[WeaveAdFormatContainer] ๐ฅ Got platform response:",{status:V==null?void 0:V.status,recommendationId:V==null?void 0:V.recommendation_id,hasRecommendation:!!(V!=null&&V.recommendation),format:(ge=V==null?void 0:V.recommendation)==null?void 0:ge.format}),V!=null&&V.recommendation){const me=V.recommendation.creative,xe=me.landing_page_url;a.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:me.brand_name,headline:me.headline,description:me.description,brandUrl:xe})}else a.log("[WeaveAdFormatContainer] โ ๏ธ No recommendation found in platform response")}catch(V){a.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",V),N([])}})()},[w,h,t,y]),l.useEffect(()=>{const J=E.current;if(!J||!S.current)return;const ge=S.current,V=({exposureUrl:xe,recommendationId:q,linkElement:oe})=>{G.current.startTracking({exposureUrl:xe,recommendationId:q,linkElement:oe,sessionId:h,logPrefix:"[WeaveAdFormatContainer]"})},me=setTimeout(()=>{a.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),v==null||v(t);const xe=B.current.length>0?B.current:[];a.log(`[WeaveAdFormatContainer] ๐ Using ${xe.length} recommendations for link detection`);try{const q=ge.scanAndProcessLinks(J,xe,V);q.length>0&&!k.current?(k.current=!0,a.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${q.length} links detected`),d==null||d(t,!0,`Found ${q.length} links`),s==null||s(q.length),g==null||g(!1)):k.current||a.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(q){const oe=q instanceof Error?q.message:String(q);a.error(`[WeaveAdFormatContainer] โ Weave injection failed: ${oe}`),d==null||d(t,!1,oe),i==null||i(),g==null||g(!0)}},100);return ge.watchForNewLinks(J,B.current,V),()=>{clearTimeout(me),ge.stopWatching()}},[e,h,t,s,g,v,d]);const $=(Q=(D=L[0])==null?void 0:D.recommendation)==null?void 0:Q.format,z=$==="weave";return l.useEffect(()=>{y&&z&&a.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${$}) - skipping fallback recommendations`)},[y,z,$]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:E,id:I,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),y&&!z&&r.jsx(us,{containerId:I,messageId:t,sessionId:h,sdk:w,query:y,recommendations:L,onLinksFound:J=>{a.log(`[WeaveAdFormatContainer] โ
Links found (${J}) - no fallback needed`),d==null||d(t,!0,`Found ${J} links in final check`),s==null||s(J),g==null||g(!1)},onNoLinksFound:()=>{a.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),a.log(`[WeaveAdFormatContainer] ๐ Passing ${L.length} recommendation(s) to fallback component`),d==null||d(t,!1,"No links detected in final check"),i==null||i(),g==null||g(!0)},children:r.jsx(Sr,{format:o,messageId:t,query:y,fallback:!0,onError:c,previousRecommendations:L.length>0?L:void 0})})]})},ps=t=>{const{sdk:e,sessionId:o}=Ht(),s=l.useRef(!1),i=l.useRef(0),c=l.useRef(!1),u=l.useRef(!1),y=l.useRef(null),g=l.useRef(dn());l.useEffect(()=>()=>{g.current.cleanup()},[]);const v=l.useCallback(({exposureUrl:p,recommendationId:E,linkElement:I})=>{g.current.startTracking({exposureUrl:p,recommendationId:E,linkElement:I,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),d=l.useRef(Date.now()),h=l.useRef(0),w=l.useRef(null),C=l.useRef([]),m=l.useRef(300),b=l.useCallback(async()=>{var p,E,I,G;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const k=document.getElementById(t.llmOutputContainerId);if(!k)return;const S=(p=e.getWeaveProcessor)==null?void 0:p.call(e);if(!S)return;const L=S.scanAndProcessLinks(k,[],({exposureUrl:B,recommendationId:$,linkElement:z})=>v({exposureUrl:B,recommendationId:$,linkElement:z}));i.current=L.length;const N=L.length>0;if(N&&!c.current)c.current=!0,(E=t.onLinksDetected)==null||E.call(t,L.length),u.current=!0;else if(!N&&c.current)c.current=!1,u.current=!1;else if(!N&&!u.current){y.current&&clearTimeout(y.current),w.current&&clearInterval(w.current),h.current=0,d.current=Date.now();const B=Math.max(100,m.current/3);w.current=setInterval(()=>{var Q;const z=Date.now()-d.current,D=m.current;z>=D?(h.current++,h.current>=2&&(w.current&&(clearInterval(w.current),w.current=null),!c.current&&!u.current&&((Q=t.onNoLinksDetected)==null||Q.call(t),u.current=!0))):h.current=0},B);const $=Math.max(1500,m.current*5);y.current=setTimeout(()=>{var z;w.current&&(clearInterval(w.current),w.current=null),!c.current&&!u.current&&((z=t.onNoLinksDetected)==null||z.call(t),u.current=!0)},$)}else N&&u.current&&!c.current&&(y.current&&(clearTimeout(y.current),y.current=null),c.current=!0,(I=t.onLinksDetected)==null||I.call(t,L.length),u.current=!0)}catch(k){const S=k instanceof Error?k:new Error(String(k));(G=t.onError)==null||G.call(t,S)}finally{s.current=!1}}},[e,o,t,v]),f=l.useCallback(()=>{const p=C.current;if(p.length<2){m.current=300;return}const E=[];for(let k=1;k<p.length;k++)E.push(p[k]-p[k-1]);const I=E.reduce((k,S)=>k+S,0)/E.length,G=Math.max(100,Math.min(I*3,1e3));m.current=G},[]);return l.useEffect(()=>{const p=document.getElementById(t.llmOutputContainerId);if(!p)return;b();const E=new MutationObserver(()=>{const I=Date.now();d.current=I,h.current=0,C.current.push(I),C.current.length>10&&C.current.shift(),f(),b()});return E.observe(p,{childList:!0,subtree:!0,characterData:!1}),()=>{E.disconnect(),y.current&&clearTimeout(y.current),w.current&&clearInterval(w.current)}},[t.llmOutputContainerId,b,f]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:c.current,shouldRenderFallback:!c.current&&u.current,processWeaveFormat:b}},hs="1.0.31";exports.AdMeshBadge=Mr;exports.AdMeshCompactCard=jn;exports.AdMeshContext=En;exports.AdMeshFollowup=kr;exports.AdMeshIntentAssistant=as;exports.AdMeshLayout=gr;exports.AdMeshLinkTracker=Cr;exports.AdMeshProvider=wr;exports.AdMeshRecommendations=Xt;exports.AdMeshRenderer=vr;exports.AdMeshSDK=Jt;exports.AdMeshTailAd=Bo;exports.AdMeshTracker=xr;exports.AdMeshViewabilityTracker=Zt;exports.STREAMING_COMPLETE_EVENT=cn;exports.STREAMING_START_EVENT=ln;exports.VERSION=hs;exports.WeaveAdFormatContainer=ms;exports.WeaveAdFormatProvider=zo;exports.WeaveFallbackRecommendations=Sr;exports.WeaveResponseProcessor=Tn;exports.callAnalyzeIntentEndpoint=yr;exports.createInlineExposureTracker=dn;exports.dispatchStreamingCompleteEvent=cs;exports.dispatchStreamingStartEvent=ls;exports.extractHeadingsDirectly=br;exports.onStreamingComplete=Rr;exports.onStreamingStart=ds;exports.useAdMesh=Ht;exports.useAdMeshContext=Rn;exports.useAdMeshStyles=jr;exports.useViewabilityTracker=fr;exports.useWeaveAdFormat=ps;exports.useWeaveAdFormatContext=Lo;
|
|
1114
|
+
`;let fr=!1;const Pr=()=>{l.useEffect(()=>{if(!fr){try{Zo();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=es,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),fr=!0}catch{a.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])};function ts(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 ns(t){return ts(t/1e3)}const In=({content:t,theme:e,fontSize:o})=>{const s=f=>f.split(/(\*\*[^*]+\*\*|\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g).map((x,h)=>{if(x.startsWith("**")&&x.endsWith("**")&&x.length>4)return r.jsx("strong",{style:{fontWeight:"600",color:e.textColor},children:x.slice(2,-2)},h);const E=x.match(/^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/);return E?r.jsx("a",{href:E[2],target:"_blank",rel:"noopener noreferrer",style:{color:e.primaryColor,textDecoration:"underline",textUnderlineOffset:"2px"},children:E[1]},h):r.jsx(l.Fragment,{children:x},h)}),i=f=>f.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(x=>x.trim()).filter((x,h,E)=>x.length>0||h<E.length-1),d=f=>{const y=i(f);return y.length>1&&y.every(x=>/^:?-{3,}:?$/.test(x))},u=f=>{const y=f.indexOf("|");if(y<=0)return{heading:null,headerLine:f};const x=f.slice(0,y).trim();return!x||/^[-|:\s]+$/.test(x)?{heading:null,headerLine:f}:{heading:x,headerLine:f.slice(y).trim()}},w=(f,y)=>{const x=i(f).length,h=i(y).length;return x<=1||x===h?y:`| ${Array.from({length:x},()=>"---").join(" | ")} |`},b=f=>{if(f.length<2||!f[0].includes("|"))return{heading:null,lines:f};const{heading:y,headerLine:x}=u(f[0]),h=x.startsWith("|")?x:`| ${x}`,E=w(h,f[1]);return{heading:y,lines:[h,E,...f.slice(2)]}},k=f=>{if(f.length<2||!f[0].includes("|"))return!1;const{lines:y}=b(f);return d(y[1])&&i(y[0]).length>=2},c=f=>{if(!f.includes("|"))return[f];let y=f.trim();const x=[],h=y.indexOf("|");if(h>0){const E=y.slice(0,h).trim();E&&!/^[-|:\s]+$/.test(E)&&(x.push(E),y=y.slice(h).trim())}return y=y.replace(/\|\s*(\|(?:\s*:?-{3,}:?\s*\|)+)/g,(E,R)=>`
|
|
1115
|
+
${R}`),y=y.replace(/\|\s*\|\s*(?=[A-Za-z0-9*])/g,`|
|
|
1116
|
+
| `),y=y.replace(/\|\s+(?=\|(?!\s*:?-{3,}:?\s*\|)[^|\n])/g,`|
|
|
1117
|
+
`),x.push(...y.split(`
|
|
1118
|
+
`).map(E=>E.trim()).filter(Boolean)),x},g=f=>{const y=f.split(`
|
|
1119
|
+
`),x=[];for(const h of y){if(!h.includes("|")){x.push(h);continue}x.push(...c(h))}return x.join(`
|
|
1120
|
+
`)},M=(f=>{const y=g(f).split(`
|
|
1121
|
+
`),x=[];let h=0;for(;h<y.length;){const E=y[h],R=y[h+1]||"";if(E.includes("|")&&d(R)){x.length>0&&x[x.length-1].trim()&&x.push("");const{heading:K,headerLine:A}=u(E);for(K&&x.push(K),x.push(A,w(A,R)),h+=2;h<y.length&&y[h].includes("|")&&y[h].trim();)x.push(y[h]),h+=1;h<y.length&&y[h].trim()&&x.push("");continue}x.push(E),h+=1}return x.join(`
|
|
1122
|
+
`)})(t).split(/\n\s*\n/).map(f=>f.trim()).filter(Boolean);return r.jsx("div",{style:{margin:0,color:e.textColor,fontSize:o},children:M.map((f,y)=>{const x=f.split(`
|
|
1123
|
+
`).map(A=>A.trim()).filter(Boolean),h=x.every(A=>/^[-*]\s+/.test(A)),E=x.every(A=>/^\d+\.\s+/.test(A)),R=x.length===1&&/^#{1,3}\s+/.test(x[0]),K=k(x);if(R){const A=x[0].replace(/^#{1,3}\s+/,"");return r.jsx("h3",{style:{marginTop:y===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(A)},y)}if(K){const{heading:A,lines:C}=b(x),D=i(C[0]),P=C.slice(2).map(i).filter(N=>N.length===D.length);return r.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[A?r.jsx("p",{style:{marginTop:y===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(A)}):null,r.jsx("div",{style:{border:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,borderRadius:8,overflowX:"auto"},children:r.jsxs("table",{style:{width:"100%",minWidth:D.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[r.jsx("thead",{children:r.jsx("tr",{children:D.map((N,T)=>r.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(N)},T))})}),r.jsx("tbody",{children:P.map((N,T)=>r.jsx("tr",{children:N.map((I,$)=>r.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:T===P.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(I)},$))},T))})]})})]},y)}if(h||E){const A=E?"ol":"ul";return r.jsx(A,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:x.map((C,D)=>r.jsx("li",{style:{marginBottom:"0.45rem"},children:s(C.replace(/^([-*]|\d+\.)\s+/,""))},D))},y)}return r.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:x.map((A,C)=>r.jsxs(l.Fragment,{children:[C>0&&r.jsx("br",{}),s(A)]},C))},y)})})};function Qt(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function Wt(t){return t.replace(/\s+/g," ").trim()}function rs(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 os(t,e,o,s){const i=new Set,d=[],u=(M,f="information")=>{const y=Wt(M);if(!y)return;const x=y.toLowerCase();i.has(x)||(i.add(x),d.push({id:`followup_${d.length}_${x.replace(/[^a-z0-9]+/g,"_")}`,text:y,type:f,is_sponsored:!1}))},w=new Set,b=M=>{const f=Wt(M||"");if(!f)return;const y=f.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();y&&w.add(y)};(s||[]).forEach(M=>b(M==null?void 0:M.title)),(o||[]).forEach(M=>b(M==null?void 0:M.title)),e.split(/\n+/).map(M=>Wt(M.replace(/^[-*]\s+/,""))).filter(Boolean).filter(M=>M.length>=24&&M.length<=90).forEach(M=>{w.size>=6||b(M)});const c=Wt(t.replace(/[?.!]+$/g,"")),g=Array.from(w).slice(0,3);return[g[0]?`Tell me more about ${g[0]}`:"",g[1]?`Show me examples related to ${g[1]}`:"",g[2]?`Compare the main options for ${g[2]}`:"","Break this down more simply",`What should I look at next about ${c}`,"Give me the practical takeaway here"].forEach((M,f)=>{d.length>=3||u(M,f===0?"comparison":"information")}),d.slice(0,3)}function ss(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function $r(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 gr(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if($r(e))return e}catch{return}}function xr(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=gr()||($r(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=gr()?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:ss()}}function is(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:Wt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Dn(t){return[...t].sort((e,o)=>{const s=!!e.is_sponsored,i=!!o.is_sponsored;return s===i?0:s?-1:1})}const as={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)"}},ls={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},ds={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},cs=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:d,showHeaderTitle:u=!0,showSubtitle:w=!0,layout:b="floating",surface:k="page",adSlotBehavior:c="expand",showCompactSlotHeader:g=!0,showCompactWelcomeMessage:S=!0,showCompactSlotInput:M=!0,showCompactSlotDisclaimer:f=!0,panelWidth:y,panelHeight:x,analyticsPageUrl:h,fontScale:E=1,position:R="bottom-right",size:K="md",defaultOpen:A,open:C,onOpenChange:D,autoOpen:P=!1,showWelcomeMessage:N=!1,welcomeMessage:T="Hi, Iโm Ava. Iโll help you find the best options.",placeholder:I="Ask me anything about products...",adsEnabled:$=!0,suggestions:G,maxSuggestions:X=6,suggestionStyle:be="carousel",onlyShowWhenSponsored:B=!1,variant:L="default",queryHandler:ue,suggestionsLoader:_e,disclaimerText:se,poweredByLabel:$e="Powered by AdMesh",subtitle:Me="Publisher Assistant",onOpen:qe,onClose:Te})=>{const{sdk:ne,sessionId:ee,theme:Ee,apiKey:xe,userId:Oe}=Ot(),{suggestions:Ce,isAnalyzingIntent:nt,intentError:z,retryIntentAnalysis:O,activeDelegationSession:V,hasActiveDelegationSession:ie,stopDelegationSession:ae,refreshDelegationActivity:Ae}=zn();Pr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:ne,sessionId:ee,hasContextTheme:!!Ee});const p=t||Ee||as,J=(p==null?void 0:p.mode)||"light",j=k==="ad-slot",he=(n=!1)=>j&&!(n&&c==="expand"),[ve,oe]=l.useState(A||P),ze=C!==void 0,me=ze?C:ve,[ke,Ie]=l.useState(""),[Y,Se]=l.useState([]),[H,Ge]=l.useState(!1),[lt,St]=l.useState(null),[F,rt]=l.useState(!1),[dt,At]=l.useState(new Set),[Tt,ot]=l.useState(G||Ce||[]),[It,gt]=l.useState(0),[Dt,q]=l.useState(0),[ye,st]=l.useState({}),Ye=l.useRef(null),Ve=l.useRef(!1),Ne=l.useRef(null),xt=l.useRef(new Map),ct=l.useRef([]),Pt=l.useRef(null),$t=l.useRef(null),U=l.useRef(null),Fe=l.useRef(!1),ce=l.useRef(!1),Ct=l.useRef(null),et=l.useRef(null),ut=l.useRef(null),Be=l.useRef(null),Le=l.useRef(null),[bt,yt]=l.useState(!1),[Ut,mn]=l.useState(!1),Lr=!!(xe!=null&&xe.toLowerCase().startsWith("pub_")),Qe=ie()&&(V==null?void 0:V.session_id)===ee?V:null,pn=l.useRef(new Set),Nn=l.useRef(new Set),Fn=l.useRef(!1),en=j&&c==="expand"&&(F||H),hn=j&&c==="sticky"&&(F||Y.length>0||H),_t=Qt(y)??"100%",Ht=Qt(x)??"100%",tn=l.useCallback(n=>_=>{_?xt.current.set(n,_):xt.current.delete(n)},[]),Re=l.useCallback(async(n,_={})=>{if(!(!ne||!ee))try{await ne.trackPublisherAssistantEvent({event_name:n,timestamp:new Date().toISOString(),session_id:ee,...xr(h),..._})}catch(m){console.warn(`[AdMeshIntentAssistant] Failed to track ${n}`,m)}},[h,ne,ee]),nn=l.useCallback((n,_,m)=>{var te,pe;const v=_==null?void 0:_.recommendation_id;if(!v)return;const W=`${n}:${v}`;Nn.current.has(W)||(Nn.current.add(W),Re("recommendation_shown",{message_id:n,query:m,recommendation_id:v,brand_name:(pe=(te=_.recommendation)==null?void 0:te.creative)==null?void 0:pe.brand_name,is_sponsored:!0}))},[Re]),fn=l.useCallback((n,_,m,v,W,te)=>{const pe=Array.isArray(te)&&te.length?te.map((je,we)=>{const We=Wt(je.text||"");return We?{id:`followup_llm_${we}_${We.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:We,type:je.type||"information",is_sponsored:!1}:null}).filter(je=>!!je).slice(0,3):os(n,_,m,v),De=is(W),Ue=De?[De,...pe.slice(0,2)]:pe.slice(0,3);Ue.length&&ot(Dn(Ue))},[]),rn=l.useCallback((n,_)=>{const m=Wt(n.query||n.label||"");if(!m||!_)return;const v={id:_,text:m,type:"action",is_sponsored:!0,recommendation:{recommendation_id:_,recommendation:{creative:{follow_up_suggestion:m}},tracking:{followup_engagement_url:n.engagement_url,followup_exposure_url:n.exposure_url}}};ot(W=>{const te=W.filter(pe=>!pe.is_sponsored).slice(0,3);return Dn([v,...te].slice(0,4))})},[]),Wn=l.useCallback(()=>{const n=Pt.current,_=$t.current;if(!n||!_)return!1;const m=n.getBoundingClientRect(),v=_.getBoundingClientRect(),W=Math.max(0,n.scrollTop+v.top-m.top);return n.scrollTop=W,!0},[]);l.useLayoutEffect(()=>{var n;if(Fe.current){Wn()&&(Fe.current=!1);return}ce.current||(n=et.current)==null||n.scrollIntoView({behavior:"smooth"})},[Y,Wn]),l.useLayoutEffect(()=>{if(!j||en)return;const n=Ct.current;if(!n)return;const _=n.closest(".admesh-publisher-assistant-reactMount"),m=Ht;[n,_].forEach(W=>{W&&(W.style.width=_t,W.style.maxWidth=_t,W.style.height=m,W.style.maxHeight=m,W.style.overflow="hidden",W.style.boxSizing="border-box",W.dataset.admeshAdSlotExpanded=hn?"true":"false")});const v=_==null?void 0:_.parentElement;v&&v!==document.body&&v!==document.documentElement&&(v.style.width=_t,v.style.maxWidth=_t,v.style.height=m,v.style.maxHeight=m,v.style.overflow="hidden",v.style.boxSizing="border-box")},[Ht,_t,en,j,hn]),l.useEffect(()=>{if(G&&G.length){ot(G);return}Ce&&Ce.length&&ot(n=>rs(n,Ce))},[G,Ce]),l.useEffect(()=>{if(L!=="default"||!_e)return;let n=!1;return _e().then(_=>{!n&&Array.isArray(_)&&_.length&&ot(_)}).catch(_=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",_)}),()=>{n=!0}},[_e,L]),l.useEffect(()=>{if(!H){q(0),Ye.current=null;return}Ye.current==null&&(Ye.current=typeof performance<"u"?performance.now():Date.now());const n=()=>{const m=Ye.current;if(m==null)return;const v=typeof performance<"u"?performance.now():Date.now();q(Math.floor((v-m)/1e3))};n();const _=window.setInterval(n,1e3);return()=>window.clearInterval(_)},[H]),l.useEffect(()=>{if(!H||L!=="default"){gt(0);return}const n=window.setInterval(()=>{gt(_=>Math.min(_+1,7))},3e3);return()=>window.clearInterval(n)},[H,L]),l.useEffect(()=>{Fn.current||!ne||!ee||(Fn.current=!0,Re("assistant_loaded",{metadata:{layout:b,surface:k,variant:L,default_open:A||P}}))},[P,A,b,ne,ee,k,Re,L]);const Mt=l.useCallback(n=>{ze?D==null||D(n):oe(n),n?(Re("assistant_opened",{metadata:{layout:b,surface:k,ad_slot_behavior:c,variant:L,expanded:F}}),qe==null||qe()):Te==null||Te()},[ze,F,b,D,qe,Te,k,Re,L]),Bn=l.useCallback(()=>{Mt(!0)},[Mt]),Nr=l.useCallback(()=>{Mt(!1)},[Mt]),Fr=l.useCallback(()=>{rt(n=>!n)},[]),Un=l.useCallback(async(n,_,m,v,W,te,pe)=>{var De,Ue,je;if(!ne)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{Qe&&await Ae("turn_started",{source:"publisher_assistant",recommendation_id:Qe.recommendation_id}).catch(de=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",de)});const we=await fetch(`${ne.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:te,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${xe}`},body:JSON.stringify({message:n,session_id:ee||"default-session",message_id:_,user_id:Oe,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:xr(h),conversation_history:pe,sponsored_recommendation:W!=null&&W.recommendation_id?{recommendation_id:W.recommendation_id,brand_name:(Ue=(De=W.recommendation)==null?void 0:De.creative)==null?void 0:Ue.brand_name}:void 0,active_delegation_session:Qe?{delegation_session_id:Qe.delegation_session_id,recommendation_id:Qe.recommendation_id,session_id:Qe.session_id,brand_name:Qe.brand_name,mcp_endpoint:Qe.mcp_endpoint,status:Qe.status}:void 0}})});if(!we.ok)throw new Error(`API request failed: ${we.status} ${we.statusText}`);const We=(je=we.body)==null?void 0:je.getReader(),zt=new TextDecoder;if(!We)throw new Error("Response body is not readable");let Je="",it,Lt,kt,Q,re;return await(async()=>{try{for(;;){const{done:de,value:at}=await We.read();if(de)break;const tt=zt.decode(at,{stream:!0}).split(`
|
|
1124
|
+
`);for(const Nt of tt)if(Nt.startsWith("data: ")){const Cn=Nt.slice(6);if(Cn.trim()==="[DONE]")return Qe&&Ae("turn_completed",{source:"publisher_assistant",recommendation_id:Qe.recommendation_id}).catch(Pe=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",Pe)}),{text:Je,source_links:it,related_items:Lt,followup_suggestions:kt,used_capability:Q,response_time_ms:re};try{const Pe=JSON.parse(Cn);switch(Pe.type){case"content":{const tr=Pe.content||"";Je+=tr,m==null||m(tr);break}case"final":{Je=Pe.reply||Je,it=Array.isArray(Pe.source_links)?Pe.source_links:void 0,Lt=Array.isArray(Pe.related_items)?Pe.related_items:void 0,kt=Array.isArray(Pe.followup_suggestions)?Pe.followup_suggestions:void 0,Q=typeof Pe.used_capability=="string"?Pe.used_capability:Q,re=typeof Pe.response_time_ms=="number"?Pe.response_time_ms:re;break}case"followup_suggestions":{kt=Array.isArray(Pe.followup_suggestions)?Pe.followup_suggestions:kt;break}case"error":throw new Error(Pe.message||"Unknown streaming error");case"session_start":v==null||v(),console.log("Session started:",Pe.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",Cn);continue}}}}catch(de){if(te!=null&&te.aborted)return{text:Je,source_links:it,related_items:Lt,followup_suggestions:kt,used_capability:Q,response_time_ms:re,error:"aborted"};throw console.error("Stream processing error:",de),de}finally{We.releaseLock()}return{text:Je,source_links:it,related_items:Lt,followup_suggestions:kt,used_capability:Q,response_time_ms:re}})()}catch(we){return te!=null&&te.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",we),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:we instanceof Error?we.message:"request_failed"})}},[ne,ee,xe,Oe,Qe,Ae]),gn=l.useCallback(()=>{const n=Be.current;if(!n||n.signal.aborted)return;n.abort(),Ge(!1),Ne.current=null,Ve.current=!1;const _=Le.current;_&&Se(m=>m.map(v=>v.id===_&&!v.content.trim()?{...v,content:"Generation stopped."}:v))},[]),jt=l.useCallback(async n=>{var je,we,We,zt,Je,it,Lt,kt;if(!n.trim()||H)return;const _=typeof performance<"u"?performance.now():Date.now(),m=n.trim(),v=Date.now().toString(),W=new AbortController,te=Ne.current,pe=(te==null?void 0:te.recommendation)||null,De=Y.filter(Q=>(Q.role==="user"||Q.role==="assistant")&&Q.content.trim()).slice(-6).map(Q=>({role:Q.role,content:Q.content.trim().slice(0,1200)}));Be.current=W,Le.current=null,U.current=v,Fe.current=!0,ce.current=!0,Ne.current=null,ot(Q=>Q.some(re=>re.is_sponsored)?Q.filter(re=>!re.is_sponsored):Q),St(null);const Ue={id:v,role:"user",content:m,timestamp:new Date};if(Re("query_submitted",{message_id:v,query:m}),Se(Q=>[...Q,Ue]),Ie(""),Ge(!0),L==="default"&&ue){try{const Q=(Date.now()+1).toString(),re={id:Q,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:null};Ve.current&&(At(at=>new Set([...at,Q])),Ve.current=!1),Se(at=>[...at,re]),Le.current=Q;const He=await ue(m,{sponsoredSuggestion:te});if(W.signal.aborted){Ne.current=null;return}const de=He.recommendation||pe||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:n,hasResponseRecommendation:!!He.recommendation,hasSponsoredSuggestionRecommendation:!!pe,finalRecommendationId:de==null?void 0:de.recommendation_id}),Se(at=>at.map(Ze=>Ze.id===Q?{...Ze,content:He.answer,sourceLinks:He.source_links,relatedItems:He.related_items,initialRecommendation:de,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-_}:Ze)),fn(m,He.answer,He.source_links,He.related_items,He.recommendation||null,He.followup_suggestions),Re("answer_completed",{message_id:Q,query:m,recommendation_id:de==null?void 0:de.recommendation_id,brand_name:(we=(je=de==null?void 0:de.recommendation)==null?void 0:je.creative)==null?void 0:we.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-_,status:"completed",metadata:{variant:L,source:"query_handler"}}),Ne.current=null}catch(Q){console.error("Error sending message:",Q);const re=Q instanceof Error?Q.message:"Unknown error occurred";St(re);const He={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Se(de=>[...de,He]),Re("answer_failed",{query:m,status:re,latency_ms:(typeof performance<"u"?performance.now():Date.now())-_,metadata:{variant:L,source:"query_handler"}}),Ne.current=null}finally{Be.current===W&&(Be.current=null,Le.current=null,Ge(!1))}return}if(!ne){setTimeout(()=>{if(W.signal.aborted){Be.current===W&&(Be.current=null,Le.current=null);return}const Q={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:n};Se(re=>[...re,Q]),Be.current===W&&(Be.current=null,Le.current=null,Ge(!1))},1e3);return}try{const Q=(Date.now()+1).toString(),re=pe,He={id:Q,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:re};Ve.current&&(At(Ze=>new Set([...Ze,Q])),Ve.current=!1),Se(Ze=>[...Ze,He]),Le.current=Q;const de=await Un(m,v,Ze=>{Se(tt=>tt.map(Nt=>Nt.id===Q?{...Nt,content:Nt.content+Ze}:Nt))},()=>{Ge(!0),gt(0)},re,W.signal,De);if(W.signal.aborted){de.text.trim()||Se(Ze=>Ze.map(tt=>tt.id===Q&&!tt.content.trim()?{...tt,content:"Generation stopped."}:tt)),Re("answer_failed",{message_id:Q,query:m,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(zt=(We=re==null?void 0:re.recommendation)==null?void 0:We.creative)==null?void 0:zt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-_,status:"aborted",metadata:{variant:L,source:"api_chat_assistant"}}),Ne.current=null;return}const at=typeof de.response_time_ms=="number"?de.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-_;Se(Ze=>Ze.map(tt=>tt.id===Q?{...tt,content:de.text,sourceLinks:de.source_links,relatedItems:de.related_items,initialRecommendation:tt.initialRecommendation||re,responseTimeMs:at}:tt)),fn(m,de.text,de.source_links,de.related_items,null,de.followup_suggestions),de.error?Re("answer_failed",{message_id:Q,query:m,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(it=(Je=re==null?void 0:re.recommendation)==null?void 0:Je.creative)==null?void 0:it.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-_,status:de.error,metadata:{variant:L,source:"api_chat_assistant"}}):Re("answer_completed",{message_id:Q,query:m,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(kt=(Lt=re==null?void 0:re.recommendation)==null?void 0:Lt.creative)==null?void 0:kt.brand_name,used_capability:de.used_capability,latency_ms:at,status:"completed",metadata:{variant:L,source:"api_chat_assistant",response_time_ms:at}}),Ne.current=null}catch(Q){console.error("Error sending message:",Q);const re=Q instanceof Error?Q.message:"Unknown error occurred";St(re);const He={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Se(de=>[...de,He]),Re("answer_failed",{query:m,latency_ms:(typeof performance<"u"?performance.now():Date.now())-_,status:re,metadata:{variant:L,source:"api_chat_assistant"}}),Ne.current=null}finally{Be.current===W&&(Be.current=null,Le.current=null,Ge(!1))}},[H,Un,ue,fn,ne,Re,L]),Et=Tt,on=l.useMemo(()=>Et.some(n=>n==null?void 0:n.is_sponsored),[Et]),sn=l.useMemo(()=>Et.filter(n=>!(n&&typeof n.id=="string")?!1:B?on:!0),[on,B,Et]),Xe=l.useMemo(()=>Dn(sn),[sn]),an=l.useCallback(async n=>{var m,v,W,te,pe,De,Ue;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:n.text,is_sponsored:n.is_sponsored,hasRecommendation:!!n.recommendation,recommendationId:((m=n.recommendation)==null?void 0:m.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((W=(v=n.recommendation)==null?void 0:v.tracking)!=null&&W.followup_engagement_url),sessionId:ee}),Ve.current=n.is_sponsored||!1,Ne.current=n.is_sponsored?n:null;const _=Xe.findIndex(je=>je.id===n.id);Re("suggestion_clicked",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:_>=0?_:void 0,is_sponsored:n.is_sponsored,recommendation_id:(te=n.recommendation)==null?void 0:te.recommendation_id,brand_name:(Ue=(De=(pe=n.recommendation)==null?void 0:pe.recommendation)==null?void 0:De.creative)==null?void 0:Ue.brand_name,query:n.text}),jt(n.text),n.is_sponsored&&n.recommendation&&ne?setTimeout(async()=>{var je;try{const we=(je=n.recommendation.tracking)==null?void 0:je.followup_engagement_url,We=n.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:we,recommendationId:We,sessionId:ee}),we&&We&&ee?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await ne.fireFollowupEngagement(we,We,ee),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!we,hasRecommendationId:!!We,hasSessionId:!!ee})}catch(we){console.error("[AdMeshIntentAssistant] โ Error firing sponsored suggestion engagement:",we)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[jt,Xe,ne,ee,Re]),ln=ds[R],Hn=ls[K];l.useEffect(()=>{if(ct.current.forEach(n=>n()),ct.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return Xe.forEach((n,_)=>{const m=xt.current.get(n.id);if(!m)return;const v=`${ee||"anonymous"}:${n.id}:${n.is_sponsored?"s":"o"}`;if(pn.current.has(v))return;let W=null,te=null;const pe=()=>{W&&(clearTimeout(W),W=null),te==null||te.disconnect(),te=null},De=()=>{var Ue,je,we,We,zt;if(pn.current.has(v)){pe();return}if(pn.current.add(v),pe(),Re("suggestion_exposure",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:_,is_sponsored:n.is_sponsored,recommendation_id:(Ue=n.recommendation)==null?void 0:Ue.recommendation_id,brand_name:(We=(we=(je=n.recommendation)==null?void 0:je.recommendation)==null?void 0:we.creative)==null?void 0:We.brand_name}),ne&&ee&&n.is_sponsored&&n.recommendation){const Je=(zt=n.recommendation.tracking)==null?void 0:zt.followup_exposure_url,it=n.recommendation.recommendation_id;Je&&it?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Je,recommendationId:it,suggestionText:n.text,sessionId:ee}),ne.fireFollowupExposure(Je,it,ee)):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Je,hasRecommendationId:!!it,suggestionText:n.text})}};te=new IntersectionObserver(Ue=>{const je=Ue[0];if(je){if(je.intersectionRatio>=.5){W||(W=setTimeout(De,1e3));return}W&&(clearTimeout(W),W=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),te.observe(m),ct.current.push(pe)}),()=>{ct.current.forEach(n=>n()),ct.current=[]}},[Xe,ne,ee,Re]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:Et.length,safeSuggestions:sn.length,isAnalyzingIntent:nt,hasIntentError:!!z,onlyShowWhenSponsored:B,hasSponsoredSuggestions:on,sponsoredCount:Et.filter(n=>n==null?void 0:n.is_sponsored).length,nonSponsoredCount:Et.filter(n=>n&&!(n!=null&&n.is_sponsored)).length,modalShouldAppear:B?on:!0,suggestions:Et.map(n=>{var _,m,v;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((_=n==null?void 0:n.recommendation)==null?void 0:_.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(m=n==null?void 0:n.recommendation)==null?void 0:m.tracking)!=null&&v.followup_engagement_url)}}),renderedSuggestions:Xe.map(n=>{var _,m,v;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((_=n==null?void 0:n.recommendation)==null?void 0:_.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(m=n==null?void 0:n.recommendation)==null?void 0:m.tracking)!=null&&v.followup_engagement_url)}})});const fe={base:`${16*E}px`,sm:`${14*E}px`,xs:`${12*E}px`},xn=se||"AI-generated responses may contain errors. Please verify important information independently.",Wr=["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..."],Vt=n=>{const _=(n==null?void 0:n.accentColor)||mt,m=(n==null?void 0:n.metaColor)||Gt,v=(n==null?void 0:n.includeSteps)??L==="default",W=`${Dt}s`,te=v?`${Wr[It]} (${W})`:`Generating answer... ${W}`;return r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:n!=null&&n.compact?"8px":"10px",color:m,fontSize:n!=null&&n.compact?fe.xs:fe.sm},children:[r.jsx("span",{style:{width:n!=null&&n.compact?8:9,height:n!=null&&n.compact?8:9,borderRadius:999,background:_,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${Z(le,.28)}`,flexShrink:0}}),r.jsx("span",{children:te})]})},qn=l.useCallback((n,_)=>{if(ye[n.id])return;const m=_?"helpful":"not_helpful";st(v=>({...v,[n.id]:m})),Re("answer_feedback",{message_id:n.id,query:n.userQuery,status:m,latency_ms:n.responseTimeMs,metadata:{helpful:_}})},[ye,Re]);function bn(n,_){if(n.role!=="assistant"||!n.content.trim()||H&&n.id===Le.current)return null;const m=(_==null?void 0:_.accentColor)||mt,v=(_==null?void 0:_.metaColor)||Gt,W=ye[n.id],te=typeof n.responseTimeMs=="number";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${Z(le,.08)}`,flexWrap:"wrap"},children:[r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto",flexWrap:"wrap"},children:[r.jsx("span",{style:{fontSize:fe.xs,color:v,whiteSpace:"nowrap"},children:W?"Thanks for your feedback":"Is this helpful?"}),W?r.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,background:Z(m,.12),color:m,flexShrink:0},children:W==="helpful"?r.jsx(sr,{size:14}):r.jsx(or,{size:14})}):r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[r.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>qn(n,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${Z(le,.12)}`,background:"#ffffff",color:v,cursor:"pointer"},children:r.jsx(sr,{size:14})}),r.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>qn(n,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${Z(le,.12)}`,background:"#ffffff",color:v,cursor:"pointer"},children:r.jsx(or,{size:14})})]})]}),te?r.jsxs("span",{style:{fontSize:fe.xs,color:v,whiteSpace:"nowrap",flex:"0 1 auto",marginLeft:"auto"},children:["Answer Completed in ",ns(n.responseTimeMs)]}):null]})}const Kt=l.useCallback(()=>{const n=ut.current;if(!n)return;const _=Math.max(0,n.scrollWidth-n.clientWidth);yt(n.scrollLeft>4),mn(n.scrollLeft<_-4)},[]);l.useEffect(()=>(Kt(),window.addEventListener("resize",Kt),()=>window.removeEventListener("resize",Kt)),[Kt,Xe.length]);const On=l.useCallback(n=>{const _=ut.current;_&&_.scrollBy({left:n==="left"?-Math.max(160,Math.floor(_.clientWidth*.75)):Math.max(160,Math.floor(_.clientWidth*.75)),behavior:"smooth"})},[]),Z=(n,_)=>{if(!n||!n.startsWith("#"))return`rgba(15, 23, 42, ${_})`;const m=n.slice(1),v=m.length===3?m.split("").map(De=>`${De}${De}`).join(""):m;if(v.length!==6)return n;const W=parseInt(v.slice(0,2),16),te=parseInt(v.slice(2,4),16),pe=parseInt(v.slice(4,6),16);return`rgba(${W}, ${te}, ${pe}, ${_})`},le=p.primaryColor||"#3F037F";p.surfaceColor,p.backgroundColor;const Vn=p.borderColor||"#e5e7eb",wt=p.textColor||"#111827",Br=p.textSecondaryColor||"#6b7280";Z(le,.12);const yn=Z(le,.24);Z(le,.38);const Ur=Z(le,.12),Hr=`linear-gradient(180deg, ${Z(le,.04)} 0%, ${Z(le,.08)} 100%)`,mt=le,_n=p.primaryTextColor||"#ffffff",Gt=Br,Kn=Me||"Publisher Assistant",Yt=nt&&Xe.length===0&&Y.length===0,wn="#f7f8fc",vn="linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(248,250,252,0.98) 100%)",vt="rgba(15, 23, 42, 0.08)",Gn="rgba(15, 23, 42, 0.12)",Yn="0 24px 60px rgba(15, 23, 42, 0.16)",kn="#667085",Qn="#98a2b3",qr=mt,Xn="#ffffff",Jn="0 8px 24px rgba(15, 23, 42, 0.08)",Sn="rgba(15, 23, 42, 0.18)";function Zn(n){return Qe?r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:n==="default"?"10px 12px":"8px 10px",borderRadius:n==="default"?"14px":"12px",border:`1px solid ${yn}`,background:Z("#ffffff",.9),marginBottom:"4px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{color:mt,fontSize:fe.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),r.jsxs("div",{style:{color:wt,fontSize:fe.sm,fontWeight:600,lineHeight:1.3},children:[Qe.brand_name," agent is active"]})]}),r.jsx("button",{type:"button",onClick:()=>{ae("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${yn}`,borderRadius:999,background:Z("#ffffff",.92),color:mt,padding:"7px 12px",fontSize:fe.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function er(n,_=j){return r.jsxs("div",{style:{display:"flex",flexDirection:_?"column":"row",alignItems:_||n==="default"?"center":"flex-start",justifyContent:_?"center":"space-between",gap:_?"2px":"12px",flexWrap:"wrap",paddingTop:_||n==="default"?"2px":"8px",borderTop:n==="default"?`1px solid ${vt}`:"none",marginTop:_?"0":n==="default"?"4px":0,flexShrink:0},children:[r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:_?"4px":"8px",color:Qn,fontSize:_?"9.5px":"11px",fontWeight:700,letterSpacing:"0.01em"},children:r.jsxs("span",{children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]})}),r.jsx("div",{style:{color:Qn,fontSize:_?"9px":"11px",lineHeight:_?1.25:1.45,maxWidth:_?"100%":n==="default"?"68%":"100%",textAlign:_?"center":n==="default"?"right":"left"},children:xn})]})}function An(n){const _=n==="publisher"?[180,220,196]:["100%","82%","68%"];return n==="publisher"?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Z(le,.1),flexShrink:0}}),r.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:_.map((m,v)=>r.jsx("div",{style:{width:m,maxWidth:"100%",height:40,borderRadius:999,background:`linear-gradient(90deg, ${Z(le,.08)} 0%, ${Z(le,.18)} 50%, ${Z(le,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:`0 8px 22px ${Z(le,.08)}`,flexShrink:0}},`suggestion-skeleton-${v}`))}),r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Z(le,.1),flexShrink:0}})]}):r.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:n==="publisher"?"10px":"12px"},children:_.map((m,v)=>r.jsx("div",{style:{width:m,maxWidth:"100%",height:n==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${Z(le,.08)} 0%, ${Z(le,.18)} 50%, ${Z(le,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:n==="publisher"?`0 8px 22px ${Z(le,.08)}`:"none"}},`suggestion-skeleton-${v}`))})}function Or(n=j){if(H)return null;if(Yt)return An("publisher");if(!Xe.length)return null;const _=Xe.slice(0,X);return be==="stacked"?r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:n?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:n?"240px":void 0,paddingRight:n?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:_.map(m=>r.jsxs("button",{ref:tn(m.id),onClick:()=>{L==="default"&&(rt(!0),b==="floating"&&Mt(!0)),an(m)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:n?"12px":"14px",border:m.is_sponsored?`1px solid ${Z(le,.32)}`:`1px solid ${Z(le,.42)}`,background:m.is_sponsored?le:Z("#ffffff",.94),color:m.is_sponsored?"#ffffff":wt,padding:n?"8px 10px":"10px 14px",fontSize:n?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:m.is_sponsored?`0 8px 18px ${Z(le,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{style:{minWidth:0},children:m.text}),$&&m.is_sponsored&&r.jsx("span",{style:{flexShrink:0,borderRadius:999,background:Z("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},m.id))}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n?"6px":"10px",flexShrink:0},children:[r.jsx("button",{type:"button",onClick:()=>On("left"),disabled:!bt,"aria-label":"Scroll suggestions left",style:{width:n?24:28,height:n?24:28,borderRadius:999,border:`1px solid ${Z(Vn,.8)}`,background:Z("#ffffff",.9),color:"#6b7280",cursor:bt?"pointer":"default",opacity:bt?1:.55},children:"โน"}),r.jsx("div",{ref:ut,onScroll:Kt,style:{display:"flex",gap:n?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:_.map(m=>r.jsxs("button",{ref:tn(m.id),onClick:()=>{L==="default"&&(rt(!0),b==="floating"&&Mt(!0)),an(m)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:"8px",whiteSpace:"nowrap",borderRadius:999,border:m.is_sponsored?`1px solid ${Z(le,.32)}`:`1px solid ${Z(le,.42)}`,background:m.is_sponsored?le:Z("#ffffff",.94),color:m.is_sponsored?"#ffffff":wt,padding:n?"7px 10px":"8px 14px",fontSize:n?"12px":"13px",fontWeight:500,boxShadow:m.is_sponsored?`0 8px 18px ${Z(le,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{children:m.text}),$&&m.is_sponsored&&r.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},m.id))}),r.jsx("button",{type:"button",onClick:()=>On("right"),disabled:!Ut,"aria-label":"Scroll suggestions right",style:{width:n?24:28,height:n?24:28,borderRadius:999,border:`1px solid ${Z(Vn,.8)}`,background:Z("#ffffff",.9),color:"#6b7280",cursor:Ut?"pointer":"default",opacity:Ut?1:.55},children:"โบ"})]})}function Vr(n){var _,m;return(_=n.relatedItems)!=null&&_.length||!((m=n.sourceLinks)!=null&&m.length)?null:r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:n.sourceLinks.map(v=>r.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Re("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:v.title,source_url:v.url}})},style:{color:mt,fontSize:fe.xs,textDecoration:"none",borderBottom:`1px solid ${Z(le,.18)}`},children:v.title||v.url},`${n.id}-${v.url}`))})}function Kr(n,_=j){var m;return(m=n.relatedItems)!=null&&m.length?r.jsxs("div",{style:{marginTop:"14px"},children:[r.jsx("div",{style:{fontSize:fe.xs,fontWeight:700,color:"#4b5563",marginBottom:"8px"},children:"Related"}),r.jsx("div",{style:{display:"flex",gap:_?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:n.relatedItems.slice(0,4).map(v=>r.jsxs("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Re("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:v.title,source_url:v.url,source_publisher:v.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:_?"6px":"10px",padding:_?"10px":"14px",borderRadius:_?"12px":"14px",textDecoration:"none",color:wt,border:`1px solid ${Z(le,.18)}`,background:"#ffffff",boxShadow:"0 10px 24px rgba(15, 23, 42, 0.08)",flex:_?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:_?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[r.jsx("div",{style:{fontSize:_?"13px":"18px",fontWeight:650,lineHeight:1.35,color:le,overflowWrap:"anywhere"},children:v.title||v.url}),v.publisher&&r.jsx("div",{style:{fontSize:_?"11px":"15px",color:"#6b7280",lineHeight:1.4,overflowWrap:"anywhere"},children:v.publisher})]},`${n.id}-${v.url}`))})]}):null}function Gr(n=j){const _=n?"13px":"16.25px";return r.jsxs("div",{ref:Pt,style:{flex:n?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none",padding:n?"0 2px 4px":F?"16px 16px 8px":0},children:[Y.map(m=>{const v=m.role==="user"&&m.id===U.current;return r.jsx("div",{ref:v?$t:void 0,style:{marginBottom:"12px",textAlign:m.role==="user"?"right":"left"},children:(()=>{const te=!!m.content.trim()||!H;return r.jsx(r.Fragment,{children:r.jsxs("div",{style:{display:m.role==="assistant"?"block":"inline-block",width:m.role==="assistant"?"100%":void 0,maxWidth:m.role==="assistant"?"100%":"76%",padding:m.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:m.role==="assistant"?0:"18px",background:m.role==="user"?mt:"transparent",color:m.role==="user"?_n:wt,boxShadow:m.role==="user"?"0 10px 24px rgba(15, 23, 42, 0.12)":"none",border:"none",fontSize:m.role==="assistant"?_:n?"12px":"13px",lineHeight:m.role==="assistant"?1.62:1.4},children:[m.role==="assistant"?m.content.trim()?r.jsx(In,{content:m.content,theme:{...p,textColor:wt},fontSize:_}):H&&m.id===Le.current?Vt({includeSteps:!0}):null:r.jsx("p",{style:{margin:0,color:_n},children:m.content}),m.role==="assistant"&&Vr(m),m.role==="assistant"&&Kr(m,n),m.role==="assistant"&&bn(m),m.role==="assistant"&&te&&dt.has(m.id)&&m.initialRecommendation&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:m.id,query:m.userQuery,initialRecommendation:m.initialRecommendation,onFollowupDetected:rn,onRecommendationsShown:(pe,De)=>{nn(pe,De,m.userQuery)},onError:pe=>{console.error("[AdMeshIntentAssistant] Recommendation error:",pe)}})}),m.role==="assistant"&&te&&!dt.has(m.id)&&(m.initialRecommendation||Lr)&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:m.id,query:m.userQuery,initialRecommendation:m.initialRecommendation||void 0,onFollowupDetected:rn,onRecommendationsShown:(pe,De)=>{nn(pe,De,m.userQuery)},onError:pe=>{console.error("[AdMeshIntentAssistant] Recommendation error:",pe)}})})]})})})()},m.id)}),lt&&r.jsx("div",{style:{color:Gt,fontSize:fe.sm},children:"Connection issue. Please try again."}),r.jsx("div",{ref:et})]})}if(L==="default"){let n=function(_=!1){const m=he(_),v=_?!0:F,W=v&&!(j&&c==="expand"&&!_&&en),te=m?_t:v?"min(960px, calc(100vw - 24px))":b==="inline"?"100%":"min(420px, calc(100vw - 32px))",pe=m?Ht:v?"min(78vh, 760px)":"auto",De=m?_t:"100%",Ue=m?Ht:void 0,je=(v||m)&&(_||v||g);return r.jsxs("div",{style:{width:te,maxWidth:De,height:pe,maxHeight:Ue,boxSizing:"border-box",display:"flex",flexDirection:"column",background:v?wn:Hr,borderRadius:m?"12px":v?"18px":"20px",padding:v?0:m?"8px":"12px",boxShadow:v?Yn:"none",border:v?`1px solid ${Gn}`:"none",overflow:"hidden",minHeight:m?0:void 0},children:[je&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:m?"10px 12px":"16px 18px",background:v?vn:"#ffffff29",color:wt,borderBottom:`1px solid ${vt}`,flexShrink:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("div",{style:{width:m?30:40,height:m?30:40,borderRadius:m?"10px":"14px",background:Z(le,.08),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:mt,overflow:"hidden"},children:d?r.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()}),(u||w)&&r.jsxs("div",{children:[u&&r.jsx("div",{style:{fontSize:m?"14px":"20px",fontWeight:700,lineHeight:1.1,letterSpacing:0},children:i}),w&&r.jsx("div",{style:{fontSize:m?"10px":"12px",color:kn,marginTop:"2px"},children:Kn})]})]}),v&&(!m||_)&&r.jsx("button",{type:"button",onClick:()=>rt(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"12px",border:`1px solid ${vt}`,background:"#ffffff",color:kn,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx("span",{style:{fontSize:"18px",lineHeight:1,fontWeight:700,transform:"translateY(-1px)"},children:"-"})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:m?"6px":"16px",minHeight:0,flex:m?"1 1 0":void 0,overflow:m?"hidden":void 0,overscrollBehavior:"contain",padding:m?"8px 10px 6px":v?"18px":"14px",background:v?wn:Z("#ffffff",.16),height:m?void 0:v?pe:"auto"},children:[Zn("default"),W&&Gr(m),m&&!v&&r.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),m&&!v&&N&&S&&Y.length===0&&r.jsx("div",{style:{color:wt,fontSize:"15px",lineHeight:1.3,fontWeight:700,letterSpacing:0,padding:"2px 2px 0",textAlign:"center"},children:T}),Or(m),(!m||v||M)&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",borderRadius:m?"12px":"16px",background:Xn,padding:m?"6px 6px 6px 10px":"8px 8px 8px 14px",boxShadow:v?Jn:`0 8px 22px ${Ur}`,border:`1px solid ${v?vt:yn}`,flexShrink:0},children:[r.jsx("input",{type:"text",value:ke,onChange:we=>Ie(we.target.value),onKeyPress:we=>{if(we.key==="Enter"){if(we.preventDefault(),H)return;Ne.current=null,Ve.current=!1,rt(!0),b==="floating"&&Mt(!0),jt(ke)}},placeholder:I,style:{flex:1,border:"none",outline:"none",borderRadius:"12px",padding:m?"8px 2px":"10px 4px",color:wt,fontSize:m?"13px":"15px",background:"transparent"}}),r.jsx("button",{type:"button",onClick:()=>{if(H){gn();return}Ne.current=null,Ve.current=!1,rt(!0),b==="floating"&&Mt(!0),jt(ke)},disabled:!H&&!ke.trim(),style:{border:"none",borderRadius:"12px",background:H?"#dc2626":mt,color:H?"#ffffff":_n,minWidth:m?"40px":"48px",height:m?"36px":"44px",padding:m?"0 10px":"0 16px",fontSize:m?"12px":"14px",fontWeight:700,cursor:!H&&!ke.trim()?"default":"pointer",opacity:!H&&!ke.trim()?.6:1,boxShadow:`0 10px 20px ${H?"rgba(220, 38, 38, 0.18)":Z(le,.18)}`},children:H?"Stop":"Send"})]}),v&&er("default",m),!v&&r.jsxs("div",{style:{textAlign:"center",paddingTop:"2px"},children:[r.jsxs("div",{style:{color:Gt,fontSize:m?"9.5px":fe.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),f&&r.jsx("div",{style:{color:Gt,fontSize:m?"9px":fe.xs,lineHeight:m?1.25:1.5},children:xn})]})]})]})};return b==="inline"?j?r.jsxs("div",{ref:Ct,className:"admesh-component","data-admesh-theme":J,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-behavior":c,"data-admesh-ad-slot-expanded":hn?"true":"false",style:{width:_t,height:Ht,maxWidth:_t,maxHeight:Ht,position:"relative",overflow:"hidden"},children:[n(!1),en&&typeof document<"u"&&yr.createPortal(r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"fixed",inset:0,background:Sn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),r.jsx("div",{style:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",zIndex:2147483001},children:n(!0)})]}),document.body)]}):r.jsxs("div",{className:"admesh-component","data-admesh-theme":J,style:{width:"100%",position:"relative"},children:[n(!1),F&&r.jsx("div",{style:{position:"fixed",inset:0,background:Sn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),F&&r.jsx("div",{style:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",zIndex:2147483001},children:n(!0)})]}):me?r.jsxs("div",{className:"admesh-component","data-admesh-theme":J,children:[F&&r.jsx("div",{style:{position:"fixed",inset:0,background:Sn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),r.jsx("div",{style:{position:"fixed",...F?{left:"50%",bottom:"12px",transform:"translateX(-50%)"}:ln,zIndex:2147483001},children:n(!1)})]}):r.jsx("div",{className:"admesh-component","data-admesh-theme":J,children:r.jsx("button",{type:"button",onClick:Bn,style:{position:"fixed",...ln,zIndex:2147483e3,border:"none",borderRadius:999,background:p.primaryColor,color:"#ffffff",padding:"14px 18px",boxShadow:"0 18px 40px rgba(15, 23, 42, 0.18)",cursor:"pointer"},children:s})})}return Xe.length===0&&!Yt?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):b==="inline"?r.jsx("div",{className:"admesh-component","data-admesh-theme":J,children:r.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:Qt(y)??"100%",backgroundColor:"#eef2ff",fontSize:fe.base,...o},children:r.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[Yt?An("legacy"):Xe.length>0&&r.jsx("div",{className:"flex flex-col gap-3",children:Xe.slice(0,X).map((n,_)=>r.jsxs("button",{ref:tn(n.id),onClick:()=>an(n),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:_===0?"100%":_===1?"82%":"68%",backgroundColor:p.surfaceColor||"#ffffff",color:p.textColor||"#1e293b",border:`1px solid ${p.borderColor||"#e2e8f0"}`,fontSize:fe.sm},children:[r.jsx("span",{className:"leading-tight",children:n.text}),$&&n.is_sponsored&&r.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:p.backgroundColor||"#ffffff",color:p.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},n.id))}),Y.length>0&&r.jsxs("div",{ref:Pt,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:p.textColor,overscrollBehavior:"contain",WebkitOverflowScrolling:"touch"},children:[Y.map(n=>{const _=n.role==="user"&&n.id===U.current;return r.jsx("div",{ref:_?$t:void 0,className:n.role==="user"?"text-right":"text-left",children:r.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:n.role==="user"?p.primaryColor:"#ffffff",color:n.role==="user"?p.primaryTextColor||"#ffffff":p.textColor,fontSize:fe.sm},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx(In,{content:n.content,theme:p,fontSize:fe.sm}),bn(n,{accentColor:p.primaryColor,metaColor:p.textSecondaryColor})]}):H&&n.id===Le.current?Vt({compact:!0,accentColor:p.primaryColor,metaColor:p.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:n.content})})},n.id)}),H&&!Y.some(n=>n.role==="assistant"&&n.id===Le.current&&!n.content.trim())&&r.jsx("div",{className:"text-sm",style:{color:p.textSecondaryColor},children:Vt({compact:!0,accentColor:p.primaryColor,metaColor:p.textSecondaryColor,includeSteps:!1})}),lt&&r.jsx("div",{className:"text-sm",style:{color:p.textSecondaryColor},children:"Connection issue. Please try again."}),r.jsx("div",{ref:et})]}),r.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{type:"text",value:ke,onChange:n=>Ie(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(H){n.preventDefault();return}jt(ke)}},placeholder:I,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:p.backgroundColor||"#ffffff",color:p.textColor,fontSize:fe.sm}}),r.jsx("button",{onClick:()=>{if(H){gn();return}jt(ke)},disabled:!H&&!ke.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:H?"#dc2626":p.primaryColor,color:"#ffffff"},children:H?r.jsx(Mn,{size:18}):r.jsx(rr,{size:18})})]})}),r.jsxs("div",{className:"space-y-2 text-center",children:[r.jsxs("p",{style:{color:p.textSecondaryColor,fontSize:fe.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),r.jsx("p",{style:{color:p.textSecondaryColor,fontSize:fe.xs,lineHeight:1.5},children:xn})]})]})})}):me?r.jsx("div",{className:"admesh-component","data-admesh-theme":J,children:r.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...F?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...ln,width:Qt(y)??Hn.width,height:Qt(x)??Hn.height},backgroundColor:F?wn:p.backgroundColor,zIndex:9999,fontSize:fe.base,borderRadius:F?"20px":"16px",border:F?`1px solid ${Gn}`:"1px solid transparent",boxShadow:F?Yn:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[r.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:F?vt:"transparent",background:F?vn:p.backgroundColor,padding:F?"18px 20px":"16px"},children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{style:{width:F?40:32,height:F?40:32,borderRadius:F?"14px":"10px",background:Z(le,.08),color:mt,display:"flex",alignItems:"center",justifyContent:"center",fontSize:F?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:d?r.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()}),(u||w&&F)&&r.jsxs("div",{children:[u&&r.jsx("div",{className:"font-medium",style:{color:p.textColor,fontSize:F?"20px":fe.base,fontWeight:700,letterSpacing:F?"-0.02em":0},children:i}),w&&F&&r.jsx("div",{style:{color:kn,fontSize:"12px",marginTop:"2px"},children:Kn})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[!j&&r.jsx("button",{onClick:Fr,className:"transition-colors",title:F?"Minimize":"Expand",style:{width:F?36:28,height:F?36:28,borderRadius:F?"12px":"10px",border:`1px solid ${F?vt:"transparent"}`,background:F?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:F?r.jsx(lo,{size:16,style:{color:p.textSecondaryColor}}):r.jsx(io,{size:16,style:{color:p.textSecondaryColor}})}),r.jsx("button",{onClick:Nr,className:"transition-colors",style:{width:F?36:28,height:F?36:28,borderRadius:F?"12px":"10px",border:`1px solid ${F?vt:"transparent"}`,background:F?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx(Mn,{size:16,style:{color:p.textSecondaryColor}})})]})]}),r.jsxs("div",{ref:Pt,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:F?"20px":"16px"},children:[Zn("legacy"),N&&Y.length===0&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",children:r.jsx("p",{style:{color:p.textColor,margin:0,fontSize:fe.sm},children:T})})}),Y.map(n=>{const _=n.role==="user"&&n.id===U.current;return r.jsxs("div",{ref:_?$t:void 0,className:"mb-3",children:[r.jsx("div",{className:n.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:n.role==="user"?qr:"transparent",color:n.role==="user"?p.primaryTextColor||"#ffffff":p.textColor,border:"none",borderRadius:n.role==="user"?F?"14px":"12px":0,padding:n.role==="user"?F?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{fontSize:`calc(${fe.sm} * 1.3)`,lineHeight:1.65},children:r.jsx(In,{content:n.content,theme:p,fontSize:`calc(${fe.sm} * 1.3)`})}),bn(n,{accentColor:p.primaryColor,metaColor:p.textSecondaryColor})]}):H&&n.id===Le.current?Vt({compact:!0,accentColor:p.primaryColor,metaColor:p.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,fontSize:fe.sm,lineHeight:"1.4"},children:n.content})}),n.role==="assistant"&&!dt.has(n.id)&&r.jsx(Xt,{messageId:n.id,query:n.userQuery,onFollowupDetected:rn,onRecommendationsShown:(m,v)=>{nn(m,v,n.userQuery)},onError:m=>{console.error("[AdMeshIntentAssistant] Recommendations error:",m)}}),n.role==="assistant"&&dt.has(n.id)&&n.initialRecommendation&&!H&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:rn,onRecommendationsShown:(m,v)=>{nn(m,v,n.userQuery)},onError:m=>{console.error("[AdMeshIntentAssistant] Recommendations error:",m)}})]})]},n.id)}),H&&!Y.some(n=>n.role==="assistant"&&n.id===Le.current&&!n.content.trim())&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:Vt({compact:!0,accentColor:p.primaryColor,metaColor:p.textSecondaryColor,includeSteps:!1})})}),lt&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:p.textSecondaryColor},children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{style:{fontSize:fe.xs},children:"โ ๏ธ"}),r.jsx("span",{style:{fontSize:fe.sm},children:"Connection issue. Please try again."})]})})}),r.jsx("div",{ref:et})]}),Y.length===0&&Yt&&r.jsx("div",{className:"px-4 pb-2",children:An("legacy")}),Xe.length>0&&Y.length===0&&!Yt&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:Xe.slice(0,X).map(n=>r.jsxs("button",{ref:tn(n.id),onClick:()=>an(n),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:p.surfaceColor||"#f8fafc",color:p.textColor||"#1e293b",border:`1px solid ${p.borderColor||"#e2e8f0"}`,fontSize:fe.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[r.jsx("span",{className:"leading-tight",children:n.text}),$&&n.is_sponsored&&r.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:p.backgroundColor||"#ffffff",color:p.textSecondaryColor||"#64748b"},children:"Ad"})]},n.id))})}),z&&!nt&&sn.length===0&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:r.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:p.surfaceColor,borderColor:p.borderColor,color:p.textSecondaryColor},children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{style:{fontSize:fe.sm},children:"Intent analysis failed"}),r.jsx("button",{onClick:O,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:p.primaryColor,color:"#ffffff"},children:"Retry"})]}),r.jsx("span",{style:{fontSize:fe.xs},children:z})]})})}),r.jsxs("div",{className:"p-3 border-t",style:{borderColor:F?vt:"transparent",padding:F?"18px 20px":void 0,background:F?vn:void 0},children:[r.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${vt}`,borderRadius:F?"16px":"12px",background:Xn,boxShadow:F?Jn:"none",padding:F?"8px 8px 8px 14px":void 0},children:[r.jsx("input",{type:"text",value:ke,onChange:n=>Ie(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(H){n.preventDefault();return}jt(ke)}},placeholder:I,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:p.textColor,fontSize:F?"15px":fe.sm,"--tw-ring-color":p.primaryColor}}),r.jsx("button",{onClick:()=>{if(H){gn();return}jt(ke)},disabled:!H&&!ke.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:H?"#dc2626":p.primaryColor,color:"#ffffff",borderRadius:F?"12px":"10px",width:F?"46px":void 0,height:F?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:F?`0 10px 20px ${Z(le,.18)}`:"none"},children:H?r.jsx(Mn,{size:14}):r.jsx(rr,{size:14})})]}),er("legacy")]})]})}):r.jsx("div",{className:"admesh-component","data-admesh-theme":J,children:r.jsx("button",{onClick:Bn,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",...ln,backgroundColor:p.primaryColor,color:"#ffffff",zIndex:9999,fontSize:fe.base,...o},children:r.jsx("span",{className:"font-medium",children:s})})})},dn="admesh:streamingStart",cn="admesh:streamingComplete";function us(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(dn,{detail:o});window.dispatchEvent(s),a.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function ms(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(cn,{detail:s});window.dispatchEvent(i),a.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function ps(t,e,o){const s=i=>{const d=i;d.detail.messageId===t&&d.detail.sessionId===e&&(a.log("[StreamingEvents] ๐จ Received streamingStart event"),o(d.detail))};return window.addEventListener(dn,s),()=>{window.removeEventListener(dn,s)}}function zr(t,e,o){a.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const d=i;a.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?(a.log("[StreamingEvents] โ
Event matched! Calling callback"),o(d.detail)):a.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(cn,s),()=>{a.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(cn,s)}}const un=()=>{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:b,logPrefix:k="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!d||!w){k&&a.warn(`${k} โ ๏ธ Missing exposure tracking data`);return}const c=`${b||"anonymous"}::${u||d}`;if(t.has(c)||e.has(c))return;const g={observer:void 0,timeoutId:null,viewableStart:null},S=()=>{o(c),t.add(c),fetch(d,{method:"GET",keepalive:!0}).then(()=>{k&&a.log(`${k} โ
Exposure pixel fired`)}).catch(()=>{k&&a.warn(`${k} โ ๏ธ Failed to fire exposure pixel`),t.delete(c)})},M=new IntersectionObserver(f=>{f.forEach(y=>{y.intersectionRatio>=.5?g.viewableStart===null&&(g.viewableStart=performance.now(),g.timeoutId=setTimeout(S,1e3)):(g.viewableStart=null,g.timeoutId&&(clearTimeout(g.timeoutId),g.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});g.observer=M,M.observe(w),e.set(c,g)},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:b})=>{const[k,c]=l.useState(!1),[g,S]=l.useState(!0),[M,f]=l.useState(!1),y=l.useRef(un()),x=l.useRef(u),h=l.useRef(w),E=l.useRef(t),R=l.useRef(s),K=l.useRef(o),A=l.useRef(i);l.useEffect(()=>{x.current=u,h.current=w,E.current=t,R.current=s,K.current=o,A.current=i},[u,w,t,s,o,i]),l.useEffect(()=>()=>{y.current.cleanup()},[]);const C=l.useCallback(({exposureUrl:P,recommendationId:N,linkElement:T})=>{y.current.startTracking({exposureUrl:P,recommendationId:N,linkElement:T,sessionId:K.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),D=l.useCallback(()=>{a.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const P=document.getElementById(E.current);if(!P){a.warn("[FinalLinkDetectionCheck] โ Container not found"),c(!0),w();return}const N=new Ln({autoAddLabels:!0,fireExposurePixels:!0}),T=d.length>0?d:[];a.log(`[FinalLinkDetectionCheck] ๐ Using ${T.length} recommendations for link detection`),T.length>0&&process.env.NODE_ENV==="development"&&T.forEach(($,G)=>{var X,be,B,L,ue,_e,se,$e,Me;a.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${G+1} (DEV):`,{recommendation_id:$==null?void 0:$.recommendation_id,click_url:((X=$==null?void 0:$.tracking)==null?void 0:X.click_url)||((B=(be=$==null?void 0:$.recommendation)==null?void 0:be.creative)==null?void 0:B.landing_page_url),format:(L=$==null?void 0:$.recommendation)==null?void 0:L.format,brand_name:(se=(_e=(ue=$.render)==null?void 0:ue.creative)==null?void 0:_e.advertiser)==null?void 0:se.brand_name,cta_url:(Me=($e=$.render)==null?void 0:$e.creative)==null?void 0:Me.landing_page_url})});const I=N.scanAndProcessLinks(P,T,({exposureUrl:$,recommendationId:G,linkElement:X})=>C({exposureUrl:$,recommendationId:G,linkElement:X}));a.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${I.length} links`),I.length>0?(a.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),f(!0),x.current(I.length)):(a.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${T.length} previous recommendation(s) if available)`),f(!1),h.current()),c(!0)}catch{a.error("[FinalLinkDetectionCheck] โ Error during final check"),c(!0),h.current()}},[C,d]);return l.useEffect(()=>{a.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:d.length});let P=null,N=!1;const T=zr(e,o,I=>{a.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:I.messageId,sessionId:I.sessionId,timestamp:I.timestamp}),N=!0,P&&(clearTimeout(P),P=null),S(!1),setTimeout(()=>{D()},100)});return P=setTimeout(()=>{N||(a.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),S(!1),setTimeout(()=>{D()},100))},5e3),()=>{a.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),P&&clearTimeout(P),T()}},[e,o]),g?r.jsx(r.Fragment,{}):k?M?(a.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),r.jsx(r.Fragment,{})):(a.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),r.jsx(r.Fragment,{children:b})):r.jsx(r.Fragment,{})},fs=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:d,className:u,query:w,onFallbackChange:b,onWeaveAttempt:k,onWeaveOutcome:c})=>{var $,G;const{sessionId:g,sdk:S,language:M,location:f,userId:y,model:x,messages:h}=Ot(),E=l.useRef(null),R=`weave-ad-container-${t}`,K=l.useRef(un()),A=l.useRef(!1),C=l.useRef(null),[D,P]=l.useState([]),N=l.useRef([]);l.useEffect(()=>(C.current||(C.current=new Ln({autoAddLabels:!0,fireExposurePixels:!0})),()=>{C.current&&(C.current.stopWatching(),C.current.clearCache())}),[]),l.useEffect(()=>()=>{K.current.cleanup()},[]),l.useEffect(()=>{(async()=>{var be;if(!S||!(w!=null&&w.trim())||!t){a.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{a.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const B=await S.fetchPlatformResponse({query:w.trim(),sessionId:g,messageId:t,language:M,location:f,userId:y,model:x,messages:h}),L=(B==null?void 0:B.status)==="generated"?[B]:[];if(P(L),N.current=L,a.log("[WeaveAdFormatContainer] ๐ฅ Got platform response:",{status:B==null?void 0:B.status,recommendationId:B==null?void 0:B.recommendation_id,hasRecommendation:!!(B!=null&&B.recommendation),format:(be=B==null?void 0:B.recommendation)==null?void 0:be.format}),B!=null&&B.recommendation){const ue=B.recommendation.creative,_e=ue.landing_page_url;a.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:ue.brand_name,headline:ue.headline,description:ue.description,brandUrl:_e})}else a.log("[WeaveAdFormatContainer] โ ๏ธ No recommendation found in platform response")}catch(B){a.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",B),P([])}})()},[S,g,t,w]),l.useEffect(()=>{const X=E.current;if(!X||!C.current)return;const be=C.current,B=({exposureUrl:_e,recommendationId:se,linkElement:$e})=>{K.current.startTracking({exposureUrl:_e,recommendationId:se,linkElement:$e,sessionId:g,logPrefix:"[WeaveAdFormatContainer]"})},ue=setTimeout(()=>{a.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),k==null||k(t);const _e=N.current.length>0?N.current:[];a.log(`[WeaveAdFormatContainer] ๐ Using ${_e.length} recommendations for link detection`);try{const se=be.scanAndProcessLinks(X,_e,B);se.length>0&&!A.current?(A.current=!0,a.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${se.length} links detected`),c==null||c(t,!0,`Found ${se.length} links`),s==null||s(se.length),b==null||b(!1)):A.current||a.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(se){const $e=se instanceof Error?se.message:String(se);a.error(`[WeaveAdFormatContainer] โ Weave injection failed: ${$e}`),c==null||c(t,!1,$e),i==null||i(),b==null||b(!0)}},100);return be.watchForNewLinks(X,N.current,B),()=>{clearTimeout(ue),be.stopWatching()}},[e,g,t,s,b,k,c]);const T=(G=($=D[0])==null?void 0:$.recommendation)==null?void 0:G.format,I=T==="weave";return l.useEffect(()=>{w&&I&&a.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${T}) - skipping fallback recommendations`)},[w,I,T]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:E,id:R,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),w&&!I&&r.jsx(hs,{containerId:R,messageId:t,sessionId:g,sdk:S,query:w,recommendations:D,onLinksFound:X=>{a.log(`[WeaveAdFormatContainer] โ
Links found (${X}) - no fallback needed`),c==null||c(t,!0,`Found ${X} links in final check`),s==null||s(X),b==null||b(!1)},onNoLinksFound:()=>{a.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),a.log(`[WeaveAdFormatContainer] ๐ Passing ${D.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),i==null||i(),b==null||b(!0)},children:r.jsx(Rr,{format:o,messageId:t,query:w,fallback:!0,onError:d,previousRecommendations:D.length>0?D:void 0})})]})},gs=t=>{const{sdk:e,sessionId:o}=Ot(),s=l.useRef(!1),i=l.useRef(0),d=l.useRef(!1),u=l.useRef(!1),w=l.useRef(null),b=l.useRef(un());l.useEffect(()=>()=>{b.current.cleanup()},[]);const k=l.useCallback(({exposureUrl:h,recommendationId:E,linkElement:R})=>{b.current.startTracking({exposureUrl:h,recommendationId:E,linkElement:R,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),c=l.useRef(Date.now()),g=l.useRef(0),S=l.useRef(null),M=l.useRef([]),f=l.useRef(300),y=l.useCallback(async()=>{var h,E,R,K;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 D=C.scanAndProcessLinks(A,[],({exposureUrl:N,recommendationId:T,linkElement:I})=>k({exposureUrl:N,recommendationId:T,linkElement:I}));i.current=D.length;const P=D.length>0;if(P&&!d.current)d.current=!0,(E=t.onLinksDetected)==null||E.call(t,D.length),u.current=!0;else if(!P&&d.current)d.current=!1,u.current=!1;else if(!P&&!u.current){w.current&&clearTimeout(w.current),S.current&&clearInterval(S.current),g.current=0,c.current=Date.now();const N=Math.max(100,f.current/3);S.current=setInterval(()=>{var G;const I=Date.now()-c.current,$=f.current;I>=$?(g.current++,g.current>=2&&(S.current&&(clearInterval(S.current),S.current=null),!d.current&&!u.current&&((G=t.onNoLinksDetected)==null||G.call(t),u.current=!0))):g.current=0},N);const T=Math.max(1500,f.current*5);w.current=setTimeout(()=>{var I;S.current&&(clearInterval(S.current),S.current=null),!d.current&&!u.current&&((I=t.onNoLinksDetected)==null||I.call(t),u.current=!0)},T)}else P&&u.current&&!d.current&&(w.current&&(clearTimeout(w.current),w.current=null),d.current=!0,(R=t.onLinksDetected)==null||R.call(t,D.length),u.current=!0)}catch(A){const C=A instanceof Error?A:new Error(String(A));(K=t.onError)==null||K.call(t,C)}finally{s.current=!1}}},[e,o,t,k]),x=l.useCallback(()=>{const h=M.current;if(h.length<2){f.current=300;return}const E=[];for(let A=1;A<h.length;A++)E.push(h[A]-h[A-1]);const R=E.reduce((A,C)=>A+C,0)/E.length,K=Math.max(100,Math.min(R*3,1e3));f.current=K},[]);return l.useEffect(()=>{const h=document.getElementById(t.llmOutputContainerId);if(!h)return;y();const E=new MutationObserver(()=>{const R=Date.now();c.current=R,g.current=0,M.current.push(R),M.current.length>10&&M.current.shift(),x(),y()});return E.observe(h,{childList:!0,subtree:!0,characterData:!1}),()=>{E.disconnect(),w.current&&clearTimeout(w.current),S.current&&clearInterval(S.current)}},[t.llmOutputContainerId,y,x]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:d.current,shouldRenderFallback:!d.current&&u.current,processWeaveFormat:y}},xs="1.0.31";exports.AdMeshBadge=Dr;exports.AdMeshCompactCard=Pn;exports.AdMeshContext=$n;exports.AdMeshFollowup=Er;exports.AdMeshIntentAssistant=cs;exports.AdMeshLayout=vr;exports.AdMeshLinkTracker=Ir;exports.AdMeshProvider=Mr;exports.AdMeshRecommendations=Xt;exports.AdMeshRenderer=jr;exports.AdMeshSDK=Jt;exports.AdMeshTailAd=qo;exports.AdMeshTracker=kr;exports.AdMeshViewabilityTracker=Zt;exports.STREAMING_COMPLETE_EVENT=cn;exports.STREAMING_START_EVENT=dn;exports.VERSION=xs;exports.WeaveAdFormatContainer=fs;exports.WeaveAdFormatProvider=Fo;exports.WeaveFallbackRecommendations=Rr;exports.WeaveResponseProcessor=Ln;exports.callAnalyzeIntentEndpoint=Ar;exports.createInlineExposureTracker=un;exports.dispatchStreamingCompleteEvent=ms;exports.dispatchStreamingStartEvent=us;exports.extractHeadingsDirectly=Sr;exports.onStreamingComplete=zr;exports.onStreamingStart=ps;exports.useAdMesh=Ot;exports.useAdMeshContext=zn;exports.useAdMeshStyles=Pr;exports.useViewabilityTracker=wr;exports.useWeaveAdFormat=gs;exports.useWeaveAdFormatContext=Wo;
|
|
1125
1125
|
//# sourceMappingURL=index.js.map
|