admesh-ui-sdk 1.0.35 โ 1.0.37
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/admesh-ui-sdk.css +1 -1
- package/dist/components/AdMeshCompactCard.d.ts.map +1 -1
- package/dist/components/AdMeshIntentAssistant.d.ts +7 -0
- package/dist/components/AdMeshIntentAssistant.d.ts.map +1 -1
- package/dist/components/AdMeshTailAd.d.ts.map +1 -1
- package/dist/components/AdMeshViewabilityTracker.d.ts.map +1 -1
- package/dist/context/AdMeshProvider.d.ts +10 -0
- package/dist/context/AdMeshProvider.d.ts.map +1 -1
- package/dist/index.js +45 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3758 -2768
- package/dist/index.mjs.map +1 -1
- package/dist/publisher-assistant.js +1891 -0
- package/dist/publisher-assistant.js.map +1 -0
- package/dist/sdk/AdMeshSDK.d.ts +1 -1
- package/dist/sdk/AdMeshSDK.d.ts.map +1 -1
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/acieApi.d.ts +2 -0
- package/dist/utils/acieApi.d.ts.map +1 -1
- package/dist/utils/extractHeadings.d.ts +1 -0
- package/dist/utils/extractHeadings.d.ts.map +1 -1
- package/dist/utils/pageContextApi.d.ts +17 -0
- package/dist/utils/pageContextApi.d.ts.map +1 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Vn=Object.defineProperty;var Kn=(t,e,o)=>e in t?Vn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var qe=(t,e,o)=>Kn(t,typeof e!="symbol"?e+"":e,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),Gn=require("react-dom/client"),u=require("react"),Yn=require("react-dom");let xt=!1;var wn;try{typeof globalThis.importMeta<"u"&&((wn=globalThis.importMeta.env)!=null&&wn.PROD)&&(xt=!0)}catch{}xt||(xt=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const d={log:(...t)=>{xt||console.log(...t)},warn:(...t)=>{xt||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{xt||console.info(...t)},debug:(...t)=>{xt||console.debug(...t)}};function Qn(t,e,o){const a=t*e>242500;return{...{visibilityThreshold:a?.3:.5,minimumDuration:1e3,isLargeAd:a},...o}}function Xn(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function Jn(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,a=e.height,i=e.width;if(a===0||i===0)return 0;const c=Math.max(0,e.top),h=Math.min(o,e.bottom),p=Math.max(0,e.left),g=Math.min(s,e.right),l=Math.max(0,h-c),m=Math.max(0,g-p),_=l*m,f=a*i;return f>0?_/f:0}function un(){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 Zn(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 er(t){const e=t.getBoundingClientRect(),o=Zn(t),s=window.innerWidth||document.documentElement.clientWidth,a=window.innerHeight||document.documentElement.clientHeight,i=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Xn(s),viewportWidth:s,viewportHeight:a,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:i,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function tr(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function nr(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function pn(t=new Date){return t.toISOString()}function rr(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function hn(t,e){let o;return function(...a){o||(t(...a),o=!0,setTimeout(()=>o=!1,e))}}const or={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let sr=or,ir=!1;function vn({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:a,config:i}){const c={...sr,...i},h=u.useRef(tr()),[p,g]=u.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:pn(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:c.enabled}),l=u.useRef(null),m=u.useRef(null),_=u.useRef(null),f=u.useRef(null),A=u.useRef(null),N=u.useRef([]),y=u.useRef([]),k=u.useRef(null),W=u.useCallback(x=>{c.debug&&d.log(`[AdMesh Viewability] ${x}`)},[c.debug]),j=u.useCallback(async(x,F)=>{if(!(!c.enabled||ir||!a.current||!l.current)&&(W(`Analytics disabled - skipping event: ${x}`),c.onEvent)){const z=er(a.current),B={eventType:x,timestamp:pn(),sessionId:h.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:p.timeMetrics,engagementMetrics:p.engagementMetrics,contextMetrics:z,mrcStandards:l.current,isViewable:p.isViewable,metadata:F};c.onEvent(B)}},[c,t,e,o,s,a,p,W]),K=u.useCallback(async()=>{y.current.length!==0&&(W("Analytics disabled - clearing batch without sending"),y.current=[],k.current&&(clearTimeout(k.current),k.current=null))},[W]),L=u.useCallback(hn(()=>{if(!a.current)return;const x=Jn(a.current),F=Date.now(),z=new Date(p.timeMetrics.loadedAt).getTime();g(B=>{const T={...B};x>0&&N.current.push(x);const E=B.isVisible,P=x>0;if(P&&!E)m.current=F,T.engagementMetrics.viewportEnterCount++,T.timeMetrics.timeToFirstVisible||(T.timeMetrics.timeToFirstVisible=F-z,T.engagementMetrics.scrollDepthAtFirstVisible=un(),j("ad_visible"));else if(!P&&E){if(m.current){const G=F-m.current;T.timeMetrics.totalVisibleDuration+=G,m.current=null}T.engagementMetrics.viewportExitCount++,j("ad_hidden")}else if(P&&E&&m.current){const G=F-m.current;T.timeMetrics.totalVisibleDuration+=G,m.current=F}if(T.isVisible=P,T.visibilityPercentage=x,x>T.engagementMetrics.maxVisibilityPercentage&&(T.engagementMetrics.maxVisibilityPercentage=x),N.current.length>0&&(T.engagementMetrics.averageVisibilityPercentage=rr(N.current)),l.current){const G=B.isViewable,V=nr(x,T.timeMetrics.totalVisibleDuration,l.current);if(V&&!G)T.isViewable=!0,T.timeMetrics.timeToViewable=F-z,_.current=F,j("ad_viewable");else if(V&&G&&_.current){const H=F-_.current;T.timeMetrics.totalViewableDuration+=H,_.current=F}}return T.engagementMetrics.currentScrollDepth=un(),T})},100),[a,p.timeMetrics.loadedAt,j]);return u.useEffect(()=>{if(!a.current)return;const x=a.current.getBoundingClientRect();l.current=Qn(x.width,x.height,c.mrcStandards),W("Initialized MRC standards"),j("ad_loaded")},[a,c.mrcStandards,W,j]),u.useEffect(()=>{if(!c.enabled||!a.current)return;const x=new IntersectionObserver(F=>{F.forEach(()=>{L()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return x.observe(a.current),()=>{x.disconnect()}},[c.enabled,a,L]),u.useEffect(()=>{if(!c.enabled)return;const x=hn(()=>{L()},100);return window.addEventListener("scroll",x,{passive:!0}),()=>window.removeEventListener("scroll",x)},[c.enabled,L]),u.useEffect(()=>{if(!c.enabled||!a.current)return;const x=a.current,F=()=>{f.current=Date.now(),g(B=>({...B,engagementMetrics:{...B.engagementMetrics,hoverCount:B.engagementMetrics.hoverCount+1}})),j("ad_hover_start")},z=()=>{if(f.current){const B=Date.now()-f.current;g(T=>({...T,timeMetrics:{...T.timeMetrics,totalHoverDuration:T.timeMetrics.totalHoverDuration+B}})),f.current=null,j("ad_hover_end",{hoverDuration:B})}};return x.addEventListener("mouseenter",F),x.addEventListener("mouseleave",z),()=>{x.removeEventListener("mouseenter",F),x.removeEventListener("mouseleave",z)}},[c.enabled,a,j]),u.useEffect(()=>{if(!c.enabled||!a.current)return;const x=a.current,F=()=>{A.current=Date.now(),j("ad_focus")},z=()=>{if(A.current){const B=Date.now()-A.current;g(T=>({...T,timeMetrics:{...T.timeMetrics,totalFocusDuration:T.timeMetrics.totalFocusDuration+B}})),A.current=null,j("ad_blur",{focusDuration:B})}};return x.addEventListener("focus",F),x.addEventListener("blur",z),()=>{x.removeEventListener("focus",F),x.removeEventListener("blur",z)}},[c.enabled,a,j]),u.useEffect(()=>{if(!c.enabled||!a.current)return;const x=a.current,F=()=>{g(z=>({...z,engagementMetrics:{...z.engagementMetrics,wasClicked:!0}})),j("ad_click")};return x.addEventListener("click",F),()=>{x.removeEventListener("click",F)}},[c.enabled,a,j]),u.useEffect(()=>()=>{const x=Date.now(),F=new Date(p.timeMetrics.loadedAt).getTime(),z=x-F;g(B=>({...B,timeMetrics:{...B.timeMetrics,sessionDuration:z}})),j("ad_unloaded",{sessionDuration:z}),K()},[]),p}const It=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:a,sessionId:i,triggerExposureUrl:c=!0,children:h,config:p,className:g,style:l,onViewabilityChange:m,onVisible:_,onViewable:f,onClick:A})=>{const N=u.useRef(null),y=u.useRef(!1),k=vn({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:N,config:p}),W=u.useRef(k.isViewable);u.useEffect(()=>{k.isViewable!==W.current&&(W.current=k.isViewable,m&&m(k.isViewable),k.isViewable&&f&&f(),k.isViewable&&!y.current&&c&&(d.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:a?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationId:s}),a&&i?(y.current=!0,d.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",a),fetch(a,{method:"GET",keepalive:!0}).then(()=>{d.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(L=>{d.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",L),y.current=!1})):d.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!a,hasSessionId:!!i})))},[k.isViewable,m,f,a,i,s,c]);const j=u.useRef(k.isVisible);u.useEffect(()=>{k.isVisible!==j.current&&(j.current=k.isVisible,k.isVisible&&_&&_())},[k.isVisible,_]);const K=()=>{A&&A()};return n.jsx("div",{ref:N,className:g,style:l,onClick:K,"data-admesh-viewability-tracker":!0,"data-recommendation-id":s,"data-is-viewable":k.isViewable,"data-is-visible":k.isVisible,"data-visibility-percentage":k.visibilityPercentage.toFixed(2),children:h})};It.displayName="AdMeshViewabilityTracker";const fn=t=>{try{return new URL(t),!0}catch{return!1}},St=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",Je=t=>St(t)||void 0,ar=t=>t&&t.trim()?t.trim():"",dr=(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 St(t)},Xt=({recommendations:t,theme:e,className:o="",style:s={},sessionId:a,triggerExposureUrl:i=!0,onDelegationConsent:c,onDelegationActivated:h,onStartDelegation:p})=>{var Be,Ce,ue,Ee,Me,Ie,Ye,tt,nt;if(!t||t.length===0)return d.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const g=t[0],l=g==null?void 0:g.recommendation,m=l==null?void 0:l.creative,_=g==null?void 0:g.tracking,f=g==null?void 0:g.delegation,A=(g==null?void 0:g.recommendation_id)||"",N=(l==null?void 0:l.offerId)||"",y=(m==null?void 0:m.brand_name)||"",k=(m==null?void 0:m.headline)||"",W=(m==null?void 0:m.description)||"",j=(m==null?void 0:m.logo_url)||"",K=(_==null?void 0:_.click_url)||(m==null?void 0:m.landing_page_url)||"",L=(_==null?void 0:_.exposure_url)||"",x=(l==null?void 0:l.disclosure)||"Sponsored",F=(m==null?void 0:m.products)||[],z=F.slice(0,4),B=F.length>1,E=((l==null?void 0:l.format)||"tail")==="bridge",P=(f==null?void 0:f.available)===!0,G=E&&P,V=(f==null?void 0:f.brand_name)||y,H="Talk to Agent",D=ar(m==null?void 0:m.cta_text),ne=!B&&!!D&&!!K;if(!y&&!k&&!W)return d.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:A}),null;const C=k&&k!==y?k:y,R=W,U=y.trim().toLowerCase(),O=C.trim().toLowerCase(),Y=!!y&&U!==O,[ae,me]=u.useState(!1),Z=u.useRef(null);u.useEffect(()=>()=>{Z.current&&(Z.current(!1),Z.current=null)},[]);const M=ee=>{var _e;(_e=Z.current)==null||_e.call(Z,ee),Z.current=null,me(!1)},le=async()=>c?await c(g):await new Promise(ee=>{Z.current=ee,me(!0)}),ze=(ee,_e)=>{_e&&_e.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:A,productId:N,clickUrl:K,source:ee}).catch(()=>{d.error(`[AdMesh] Failed to track ${ee} click`)})},Le=async()=>{if(A&&a)try{const ee=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",_e=await fetch(`${ee}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:A,session_id:a,is_test:!1})});_e.ok||d.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",_e.statusText)}catch(ee){d.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",ee)}},$e=async ee=>{if(ee.preventDefault(),ee.stopPropagation(),!g||!G||(ze("compact_tail_ad_delegation_cta"),await Le(),!await le()))return;const Qe=f!=null&&f.available?{recommendation_id:g.recommendation_id,brand_id:Je(f.brand_id),brand_name:Je(f.brand_name||(m==null?void 0:m.brand_name)),eligibility_reason:Je(f.eligibility_reason),delegate_reason:Je(f.delegate_reason),session_goal:Je(f.session_goal),desired_outcome_type:f.desired_outcome_type,required_user_inputs:Array.isArray(f.required_user_inputs)?f.required_user_inputs.filter(Ke=>typeof Ke=="string"):[],required_consent_types:Array.isArray(f.required_consent_types)?f.required_consent_types.filter(Ke=>typeof Ke=="string"):[],success_outcome:Je(f.success_outcome),fallback_message:Je(f.fallback_message),session_mode:Je(f.session_mode),status:Je(f.status),capabilities:f.capabilities||[],allowed_data_types:f.allowed_data_types||[],consent_requirements:f.consent_requirements||[],auth_model:Je(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:g}:null;if(h&&Qe){await h(Qe);return}if(p){await p(g);return}},[de,ce]=u.useState(!1),xe=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,Se=(e==null?void 0:e.surfaceColor)||((Ce=(Be=e==null?void 0:e.components)==null?void 0:Be.card)==null?void 0:Ce.backgroundColor)||(xe?"#111827":"#ffffff"),Ae=(e==null?void 0:e.borderColor)||((Ee=(ue=e==null?void 0:e.components)==null?void 0:ue.card)==null?void 0:Ee.borderColor)||(xe?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),w=((Me=e==null?void 0:e.shadows)==null?void 0:Me.medium)||((Ye=(Ie=e==null?void 0:e.components)==null?void 0:Ie.card)==null?void 0:Ye.boxShadow)||(xe?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),oe="#2563eb",S=xe?"#9ca3af":"#6b7280",be=xe?"#e5e7eb":"#374151",b=xe?"#f9fafb":"#0f172a",re=xe?"rgba(255, 255, 255, 0.04)":"#f8fafc",We="50px",fe=G||ne?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[G?n.jsx("button",{type:"button",onClick:$e,style:{background:"none",border:"none",padding:0,color:oe,fontSize:"0.68rem",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:H}):null,ne?n.jsx("a",{href:K,target:"_blank",rel:"noopener noreferrer",onClick:ee=>ze("compact_tail_ad_cta",ee),style:{color:oe,fontSize:"0.68rem",fontWeight:600,textDecoration:"none"},children:D}):null]}):null;return n.jsxs(It,{productId:N,recommendationId:A,exposureUrl:L,sessionId:a,triggerExposureUrl:i,className:`admesh-compact-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:[n.jsx("style",{children:`
|
|
1
|
+
"use strict";var Hr=Object.defineProperty;var qr=(t,e,o)=>e in t?Hr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var Ue=(t,e,o)=>qr(t,typeof e!="symbol"?e+"":e,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),Or=require("react-dom/client"),c=require("react"),Vr=require("react-dom");let It=!1;var ur;try{typeof globalThis.importMeta<"u"&&((ur=globalThis.importMeta.env)!=null&&ur.PROD)&&(It=!0)}catch{}It||(It=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const a={log:(...t)=>{It||console.log(...t)},warn:(...t)=>{It||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{It||console.info(...t)},debug:(...t)=>{It||console.debug(...t)}};function Kr(t,e,o){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...o}}function Gr(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function Yr(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,i=e.height,l=e.width;if(i===0||l===0)return 0;const u=Math.max(0,e.top),b=Math.min(o,e.bottom),h=Math.max(0,e.left),_=Math.min(s,e.right),d=Math.max(0,b-u),m=Math.max(0,_-h),k=d*m,x=i*l;return x>0?k/x:0}function Qn(){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 Qr(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 Xr(t){const e=t.getBoundingClientRect(),o=Qr(t),s=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,l=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Gr(s),viewportWidth:s,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:l,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function Jr(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Zr(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function Xn(t=new Date){return t.toISOString()}function eo(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function Jn(t,e){let o;return function(...i){o||(t(...i),o=!0,setTimeout(()=>o=!1,e))}}const to={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let no=to,ro=!1;function mr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:i,config:l}){const u={...no,...l},b=c.useRef(Jr()),[h,_]=c.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:Xn(),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=c.useRef(null),m=c.useRef(null),k=c.useRef(null),x=c.useRef(null),w=c.useRef(null),g=c.useRef([]),p=c.useRef([]),y=c.useRef(null),C=c.useCallback(v=>{u.debug&&a.log(`[AdMesh Viewability] ${v}`)},[u.debug]),j=c.useCallback(async(v,$)=>{if(!(!u.enabled||ro||!i.current||!d.current)&&(C(`Analytics disabled - skipping event: ${v}`),u.onEvent)){const W=Xr(i.current),N={eventType:v,timestamp:Xn(),sessionId:b.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:h.timeMetrics,engagementMetrics:h.engagementMetrics,contextMetrics:W,mrcStandards:d.current,isViewable:h.isViewable,metadata:$};u.onEvent(N)}},[u,t,e,o,s,i,h,C]),O=c.useCallback(async()=>{p.current.length!==0&&(C("Analytics disabled - clearing batch without sending"),p.current=[],y.current&&(clearTimeout(y.current),y.current=null))},[C]),M=c.useCallback(Jn(()=>{if(!i.current)return;const v=Yr(i.current),$=Date.now(),W=new Date(h.timeMetrics.loadedAt).getTime();_(N=>{const z={...N};v>0&&g.current.push(v);const I=N.isVisible,P=v>0;if(P&&!I)m.current=$,z.engagementMetrics.viewportEnterCount++,z.timeMetrics.timeToFirstVisible||(z.timeMetrics.timeToFirstVisible=$-W,z.engagementMetrics.scrollDepthAtFirstVisible=Qn(),j("ad_visible"));else if(!P&&I){if(m.current){const Y=$-m.current;z.timeMetrics.totalVisibleDuration+=Y,m.current=null}z.engagementMetrics.viewportExitCount++,j("ad_hidden")}else if(P&&I&&m.current){const Y=$-m.current;z.timeMetrics.totalVisibleDuration+=Y,m.current=$}if(z.isVisible=P,z.visibilityPercentage=v,v>z.engagementMetrics.maxVisibilityPercentage&&(z.engagementMetrics.maxVisibilityPercentage=v),g.current.length>0&&(z.engagementMetrics.averageVisibilityPercentage=eo(g.current)),d.current){const Y=N.isViewable,J=Zr(v,z.timeMetrics.totalVisibleDuration,d.current);if(J&&!Y)z.isViewable=!0,z.timeMetrics.timeToViewable=$-W,k.current=$,j("ad_viewable");else if(J&&Y&&k.current){const ge=$-k.current;z.timeMetrics.totalViewableDuration+=ge,k.current=$}}return z.engagementMetrics.currentScrollDepth=Qn(),z})},100),[i,h.timeMetrics.loadedAt,j]);return c.useEffect(()=>{if(!i.current)return;const v=i.current.getBoundingClientRect();d.current=Kr(v.width,v.height,u.mrcStandards),C("Initialized MRC standards"),j("ad_loaded")},[i,u.mrcStandards,C,j]),c.useEffect(()=>{if(!u.enabled||!i.current)return;const v=new IntersectionObserver($=>{$.forEach(()=>{M()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return v.observe(i.current),()=>{v.disconnect()}},[u.enabled,i,M]),c.useEffect(()=>{if(!u.enabled)return;const v=Jn(()=>{M()},100);return window.addEventListener("scroll",v,{passive:!0}),()=>window.removeEventListener("scroll",v)},[u.enabled,M]),c.useEffect(()=>{if(!u.enabled||!i.current)return;const v=i.current,$=()=>{x.current=Date.now(),_(N=>({...N,engagementMetrics:{...N.engagementMetrics,hoverCount:N.engagementMetrics.hoverCount+1}})),j("ad_hover_start")},W=()=>{if(x.current){const N=Date.now()-x.current;_(z=>({...z,timeMetrics:{...z.timeMetrics,totalHoverDuration:z.timeMetrics.totalHoverDuration+N}})),x.current=null,j("ad_hover_end",{hoverDuration:N})}};return v.addEventListener("mouseenter",$),v.addEventListener("mouseleave",W),()=>{v.removeEventListener("mouseenter",$),v.removeEventListener("mouseleave",W)}},[u.enabled,i,j]),c.useEffect(()=>{if(!u.enabled||!i.current)return;const v=i.current,$=()=>{w.current=Date.now(),j("ad_focus")},W=()=>{if(w.current){const N=Date.now()-w.current;_(z=>({...z,timeMetrics:{...z.timeMetrics,totalFocusDuration:z.timeMetrics.totalFocusDuration+N}})),w.current=null,j("ad_blur",{focusDuration:N})}};return v.addEventListener("focus",$),v.addEventListener("blur",W),()=>{v.removeEventListener("focus",$),v.removeEventListener("blur",W)}},[u.enabled,i,j]),c.useEffect(()=>{if(!u.enabled||!i.current)return;const v=i.current,$=()=>{_(W=>({...W,engagementMetrics:{...W.engagementMetrics,wasClicked:!0}})),j("ad_click")};return v.addEventListener("click",$),()=>{v.removeEventListener("click",$)}},[u.enabled,i,j]),c.useEffect(()=>()=>{const v=Date.now(),$=new Date(h.timeMetrics.loadedAt).getTime(),W=v-$;_(N=>({...N,timeMetrics:{...N.timeMetrics,sessionDuration:W}})),j("ad_unloaded",{sessionDuration:W}),O()},[]),h}const Jt=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:i,sessionId:l,triggerExposureUrl:u=!0,children:b,config:h,className:_,style:d,onViewabilityChange:m,onVisible:k,onViewable:x,onClick:w})=>{const g=c.useRef(null),p=c.useRef(!1),y=mr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:g,config:h}),C=c.useRef(y.isViewable);c.useEffect(()=>{p.current=!1,C.current=!1},[i,s,l]),c.useEffect(()=>{y.isViewable!==C.current&&(C.current=y.isViewable,m&&m(y.isViewable),y.isViewable&&x&&x(),y.isViewable&&!p.current&&u&&(a.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:i?"present":"MISSING",sessionId:l?"present":"MISSING",recommendationId:s}),i&&l?(p.current=!0,a.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",i),fetch(i,{method:"GET",keepalive:!0}).then(()=>{a.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(M=>{a.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",M),p.current=!1})):a.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!i,hasSessionId:!!l})))},[y.isViewable,m,x,i,l,s,u]);const j=c.useRef(y.isVisible);c.useEffect(()=>{y.isVisible!==j.current&&(j.current=y.isVisible,y.isVisible&&k&&k())},[y.isVisible,k]);const O=()=>{w&&w()};return r.jsx("div",{ref:g,className:_,style:d,onClick:O,"data-admesh-viewability-tracker":!0,"data-recommendation-id":s,"data-is-viewable":y.isViewable,"data-is-visible":y.isVisible,"data-visibility-percentage":y.visibilityPercentage.toFixed(2),children:b})};Jt.displayName="AdMeshViewabilityTracker";const Zn=t=>{try{return new URL(t),!0}catch{return!1}},Nt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",at=t=>Nt(t)||void 0,oo=t=>t&&t.trim()?t.trim():"",so=(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 Nt(t)},Mn=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:l=!0,onDelegationConsent:u,onDelegationActivated:b,onStartDelegation:h})=>{var we,Pe,E,qe,rt,ft,St,Qe,At;if(!t||t.length===0)return a.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const _=t[0],d=_==null?void 0:_.recommendation,m=d==null?void 0:d.creative,k=_==null?void 0:_.tracking,x=_==null?void 0:_.delegation,w=(_==null?void 0:_.recommendation_id)||"",g=(d==null?void 0:d.offerId)||"",p=(m==null?void 0:m.brand_name)||"",y=(m==null?void 0:m.headline)||"",C=(m==null?void 0:m.description)||"",j=(m==null?void 0:m.logo_url)||"",O=(k==null?void 0:k.click_url)||(m==null?void 0:m.landing_page_url)||"",M=(k==null?void 0:k.exposure_url)||"",v=(d==null?void 0:d.disclosure)||"Sponsored",$=(m==null?void 0:m.products)||[],W=$.slice(0,4),N=$.length>1,I=((d==null?void 0:d.format)||"tail")==="bridge",P=(x==null?void 0:x.available)===!0,Y=I&&P,J=(x==null?void 0:x.brand_name)||p,ge="Talk to Agent",B=oo(m==null?void 0:m.cta_text),se=!N&&!!B&&!!O;if(!p&&!y&&!C)return a.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:w}),null;const xe=y&&y!==p?y:p,ue=C,Q=p.trim().toLowerCase(),V=xe.trim().toLowerCase(),He=!!p&&Q!==V,[Ae,Ce]=c.useState(!1),ie=c.useRef(null);c.useEffect(()=>()=>{ie.current&&(ie.current(!1),ie.current=null)},[]);const F=Z=>{var Te;(Te=ie.current)==null||Te.call(ie,Z),ie.current=null,Ce(!1)},q=async()=>u?await u(_):await new Promise(Z=>{ie.current=Z,Ce(!0)}),K=(Z,Te)=>{Te&&Te.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:w,productId:g,clickUrl:O,source:Z}).catch(()=>{a.error(`[AdMesh] Failed to track ${Z} click`)})},re=()=>{N||!O||(K("compact_tail_ad_card"),typeof window<"u"&&window.open(O,"_blank","noopener,noreferrer"))},me=Z=>{N||!O||(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),re())},Me=async()=>{if(w&&i)try{const Z=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",Te=await fetch(`${Z}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:w,session_id:i,is_test:!1})});Te.ok||a.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",Te.statusText)}catch(Z){a.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",Z)}},Ee=async Z=>{if(Z.preventDefault(),Z.stopPropagation(),!_||!Y||(K("compact_tail_ad_delegation_cta"),await Me(),!await q()))return;const tt=x!=null&&x.available?{recommendation_id:_.recommendation_id,brand_id:at(x.brand_id),brand_name:at(x.brand_name||(m==null?void 0:m.brand_name)),eligibility_reason:at(x.eligibility_reason),delegate_reason:at(x.delegate_reason),session_goal:at(x.session_goal),desired_outcome_type:x.desired_outcome_type,required_user_inputs:Array.isArray(x.required_user_inputs)?x.required_user_inputs.filter(Ge=>typeof Ge=="string"):[],required_consent_types:Array.isArray(x.required_consent_types)?x.required_consent_types.filter(Ge=>typeof Ge=="string"):[],success_outcome:at(x.success_outcome),fallback_message:at(x.fallback_message),session_mode:at(x.session_mode),status:at(x.status),capabilities:x.capabilities||[],allowed_data_types:x.allowed_data_types||[],consent_requirements:x.consent_requirements||[],auth_model:at(x.auth_model),handoff_protocol:x.handoff_protocol&&typeof x.handoff_protocol=="object"?x.handoff_protocol:void 0,supported_actions:x.supported_actions||[],metadata:x.metadata&&typeof x.metadata=="object"?x.metadata:void 0,platform_response:_}:null;if(b&&tt){await b(tt);return}if(h){await h(_);return}},[R,ke]=c.useState(!1),S=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,L=(e==null?void 0:e.surfaceColor)||((Pe=(we=e==null?void 0:e.components)==null?void 0:we.card)==null?void 0:Pe.backgroundColor)||(S?"#111827":"#ffffff"),pe=(e==null?void 0:e.borderColor)||((qe=(E=e==null?void 0:e.components)==null?void 0:E.card)==null?void 0:qe.borderColor)||(S?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),D=((rt=e==null?void 0:e.shadows)==null?void 0:rt.medium)||((St=(ft=e==null?void 0:e.components)==null?void 0:ft.card)==null?void 0:St.boxShadow)||(S?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),Se="#2563eb",ne=S?"#9ca3af":"#6b7280",be=S?"#e5e7eb":"#374151",_e=S?"#f9fafb":"#0f172a",le=S?"rgba(255, 255, 255, 0.04)":"#f8fafc",G="50px",De=Y||se?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[Y?r.jsx("button",{type:"button",onClick:Ee,style:{background:"none",border:"none",padding:0,color:Se,fontSize:"0.68rem",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:ge}):null,se?r.jsx("a",{href:O,target:"_blank",rel:"noopener noreferrer",onClick:Z=>K("compact_tail_ad_cta",Z),style:{color:Se,fontSize:"0.68rem",fontWeight:600,textDecoration:"none"},children:B}):null]}):null;return r.jsxs(Jt,{productId:g,recommendationId:w,exposureUrl:M,sessionId:i,triggerExposureUrl:l,className:`admesh-compact-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:[r.jsx("style",{children:`
|
|
2
2
|
.admesh-compact-line-clamp-1 {
|
|
3
3
|
overflow: hidden;
|
|
4
4
|
display: -webkit-box;
|
|
@@ -21,7 +21,9 @@
|
|
|
21
21
|
.admesh-compact-tail-scroll::-webkit-scrollbar {
|
|
22
22
|
display: none;
|
|
23
23
|
}
|
|
24
|
-
`}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((nt=(tt=e==null?void 0:e.components)==null?void 0:tt.card)==null?void 0:nt.borderRadius)||"14px",border:`1px solid ${Ae}`,background:Se,boxShadow:w,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[n.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:xe?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!de&&j&&fn(j)?n.jsx("img",{src:j,alt:`${y} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>ce(!0)}):n.jsx("span",{style:{fontSize:"0.85rem",fontWeight:700,color:S},children:(y||"A").charAt(0).toUpperCase()})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[n.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"0.68rem",color:S},children:Y?y:""}),n.jsx("div",{style:{flexShrink:0,fontSize:"0.62rem",color:S,textTransform:"uppercase",letterSpacing:"0.08em"},children:x})]}),!B&&n.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"0.84rem",lineHeight:1.3,fontWeight:700,color:b,marginBottom:"4px"},title:C,children:C}),R&&n.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"0.7rem",lineHeight:1.35,color:be},title:R,children:R})]})]}),B&&n.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:z.map(ee=>{const _e=St(ee.product_name)||"Product",Qe=St(ee.product_link)||St(ee.product_url)||K||"#",Ke=dr(ee.product_price,ee.product_currency),ve=St(ee.product_image_url),dt=ve&&fn(ve)?ve:"",lt=Qe!=="#";return n.jsx("a",{href:Qe,target:lt?"_blank":void 0,rel:lt?"noopener noreferrer":void 0,onClick:ut=>ze(`compact_tail_ad_product_${ee.product_id||"item"}`,ut),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${Ae}`,borderRadius:"12px",background:re,padding:"8px",flexShrink:0},children:n.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[n.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:xe?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:S,fontSize:"0.75rem",fontWeight:700},children:dt?n.jsx("img",{src:dt,alt:_e,style:{width:"100%",height:"100%",objectFit:"cover"}}):_e.charAt(0).toUpperCase()}),n.jsxs("div",{style:{minWidth:0,flex:1},children:[n.jsx("div",{style:{fontSize:"0.68rem",lineHeight:1.25,fontWeight:600,color:b,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:_e,children:_e}),n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:Ke&&n.jsx("span",{style:{fontSize:"0.66rem",fontWeight:700,color:b},children:Ke})})]})]})},ee.product_id||`${A}-${_e}`)})}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:B?0:We},children:[n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:fe}),B&&F.length>z.length?n.jsxs("span",{style:{fontSize:"0.62rem",color:S},children:["+",F.length-z.length," more"]}):null]}),ae?n.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${Ae}`,borderRadius:"12px",background:re,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[n.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:oe},children:"Confirm Agent Access"}),n.jsxs("div",{style:{fontSize:"0.74rem",lineHeight:1.4,color:b,fontWeight:600},children:["Allow ",V||"this brand"," to start a delegated session?"]}),n.jsx("div",{style:{fontSize:"0.68rem",lineHeight:1.45,color:be},children:"The agent will only use the details you choose to share for this request."})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[n.jsx("button",{type:"button",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),M(!1)},style:{borderRadius:"10px",border:`1px solid ${Ae}`,background:Se,color:b,fontSize:"0.68rem",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),n.jsx("button",{type:"button",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),M(!0)},style:{borderRadius:"10px",border:"none",background:oe,color:"#ffffff",fontSize:"0.68rem",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})},kn=({recommendations:t,theme:e,className:o,style:s,sessionId:a,onDelegationConsent:i,onDelegationActivated:c,onStartDelegation:h})=>{const p=t.filter(l=>l&&typeof l=="object"&&typeof l.recommendation_id=="string"&&l.recommendation_id.length>0);if(!p||p.length===0)return d.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;d.log(`[AdMeshLayout] Rendering with ${p.length} valid recommendations`);const g=()=>{var l;if(p.length>0){const m=p[0],_=(l=m.recommendation)==null?void 0:l.format;d.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:_,recommendationKeys:Object.keys(m||{})}),(_==="product_card"||_==="weave"||_==="bridge")&&d.warn(`[AdMeshLayout] ${_} format requested, falling back to tail for canonical render payload`)}return n.jsx(Xt,{recommendations:p,theme:e,sessionId:a,onDelegationConsent:i,onDelegationActivated:c,onStartDelegation:h})};return n.jsx("div",{className:`admesh-layout ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:g()})};class Sn{constructor(e){qe(this,"firedExposures",new Set);qe(this,"debug",!1);qe(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,o,s){const a=`${s}_${o}`;if(this.firedExposures.has(a)){this.debug&&d.log("[Tracker] Exposure already fired");return}this.firedExposures.add(a);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&d.warn("[Tracker] Failed to fire exposure")}),this.debug&&d.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&d.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,a){const i=`${s}_${o}`;if(this.firedExposures.has(i)){this.debug&&d.log("[Tracker] MRC exposure already fired");return}return new Promise(c=>{let h=null,p=null;const g=new IntersectionObserver(_=>{_.forEach(f=>{f.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?h===null&&(h=Date.now(),this.debug&&d.log("[Tracker] Ad reached MRC visibility threshold"),p=setTimeout(()=>{this.fireExposure(e,o,s),g.disconnect(),c()},this.mrcThreshold.minimumDurationMs)):h!==null&&(p&&(clearTimeout(p),p=null),h=null,this.debug&&d.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});g.observe(a);const m=setTimeout(()=>{g.disconnect(),p&&clearTimeout(p),c()},3e4);a.__admeshTrackerCleanup=()=>{g.disconnect(),p&&clearTimeout(p),clearTimeout(m)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,o,s){this.fireExposure(e,o,s)}fireFollowupEngagement(e,o,s){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s})}).catch(a=>{this.debug&&d.warn("[Tracker] Failed to fire followup engagement (non-critical):",a)}).then(()=>{})}}const Jt=u.createContext(void 0);function Zt(){const t=u.useContext(Jt);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function Nt(){try{console.log("[AdMesh] Starting direct headings extraction...");const t=i=>i.replace(/\s+/g," ").trim(),e=t(document.title||""),s=(()=>{const i=[],c=document.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(c).forEach(h=>{const p=t(h.textContent||"");p.length>0&&i.push(p)}),i})(),a={title:e,headings:s,url:window.location.href,domain:window.location.hostname,extracted_at:new Date().toISOString()};return console.log("[AdMesh] Extracted headings:",{title:a.title,headingsCount:a.headings.length,domain:a.domain}),a}catch(t){return console.error("[AdMesh] Error in direct headings extraction:",t),null}}function lr(t){return!!(t&&typeof t=="object"&&"recommendation_id"in t&&"status"in t)}function cr(t){var s,a,i,c,h,p,g,l,m,_,f;if(!t||typeof t!="object")return;if(lr(t))return t;const e=t;if(!e.recommendation_id)return;const o=(e.products||[]).map(A=>{var N,y;return{product_id:A.product_id||"",product_link:A.product_link||A.product_click_url||e.click_url||e.url||"",product_name:A.product_name||e.title||((N=e.creative_input)==null?void 0:N.product_name)||"",product_description:A.product_description||"",product_price:A.product_price??void 0,product_discount:A.product_discount??void 0,product_currency:A.product_currency,product_discount_type:A.product_discount_type,product_cta_label:A.product_cta_label||((y=e.creative_input)==null?void 0:y.cta_label),product_image_url:A.product_image_url,product_features:A.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||((a=e.creative_input)==null?void 0:a.product_name)||"",description:((i=e.creative_input)==null?void 0:i.short_description)||((c=e.creative_input)==null?void 0:c.long_description)||"",cta_text:((h=e.creative_input)==null?void 0:h.cta_label)||((p=o[0])==null?void 0:p.product_cta_label)||"Learn more",follow_up_suggestion:e.follow_up_suggestion,logo_url:(l=(g=e.creative_input)==null?void 0:g.assets)==null?void 0:l.logo_url,image_urls:((_=(m=e.creative_input)==null?void 0:m.assets)==null?void 0:_.image_urls)||[],landing_page_url:e.url||e.click_url||((f=e.creative_input)==null?void 0:f.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 mr(t){return{...t,suggestions:(t.suggestions||[]).map(e=>({...e,recommendation:cr(e.recommendation)}))}}function ur(t){try{const o=new URL(t).pathname.split("/").filter(a=>a.length>0);return o[o.length-1]||void 0}catch{return}}async function An(t,e){var o,s;try{console.log("[AdMesh SDK] Starting ACIE analyze-intent call...",{url:t.url});const a=Array.isArray(t.headings)?t.headings:[],i=e.apiKey.toLowerCase().startsWith("pub_")?ur(t.url):void 0,c=e.extension?"extension":"admesh_ui_sdk",h=(t.domain||(typeof window<"u"?window.location.hostname:"")).trim().toLowerCase(),p={url:t.url,title:t.title||void 0,headings:a.length>0?a:void 0,domain:h,article_slug:i,agent_id:void 0,cpx_floor:void 0,source:c,api_key:e.apiKey,user_id:e.userId||void 0};console.log("[AdMesh SDK] Payload prepared:",{url:p.url,titleLength:((o=p.title)==null?void 0:o.length)||0,headingsCount:((s=p.headings)==null?void 0:s.length)||0,domain:p.domain,article_slug:p.article_slug,source:p.source,has_user_id:!!p.user_id});const g=`${e.apiBaseUrl}/acie/analyze-intent`;console.log("[AdMesh SDK] Calling ACIE API:",g);const l=await fetch(g,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(p)});if(console.log("[AdMesh SDK] ACIE API response received:",{status:l.status,statusText:l.statusText,ok:l.ok}),!l.ok){const f=await l.text();throw console.error("[AdMesh SDK] ACIE API error:",{status:l.status,statusText:l.statusText,errorText:f}),new Error(`ACIE API error: ${l.status} - ${f}`)}const m=await l.json(),_=mr(m);return console.log("[AdMesh SDK] ACIE analysis completed:",{url:t.url,suggestionsCount:_.suggestions.length}),_}catch(a){return console.error("[AdMesh SDK] Error calling ACIE analyze-intent endpoint:",a),null}}const Cn=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:a,language:i,location:c,userId:h,model:p,messages:g,children:l})=>{const[m,_]=u.useState(null),[f,A]=u.useState(new Set),[N,y]=u.useState(new Map),[k,W]=u.useState(null),[j,K]=u.useState([]),[L,x]=u.useState(!1),[F,z]=u.useState(null),B=u.useRef(!1),T=u.useCallback((C,R)=>{const U=C.filter(O=>!O.is_sponsored).slice(0,3);return[R,...U]},[]),E=u.useCallback((C,R)=>{const U=C.find(Y=>Y.is_sponsored),O=R.filter(Y=>!Y.is_sponsored).slice(0,3);return U?[U,...O]:O},[]);u.useEffect(()=>{if(!e||e.trim()===""){d.error("[AdMeshProvider] โ sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}d.log("[AdMeshProvider] โ
Session ID available:",e)},[e]),u.useEffect(()=>{if(!t){d.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){d.error("[AdMeshProvider] โ Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const C=new Rt({apiKey:t,theme:s,apiBaseUrl:a,extension:o});_(C),d.log("[AdMeshProvider] โ
AdMesh SDK initialized with session:",e),a&&d.log("[AdMeshProvider] ๐ Using custom API base URL")}catch(C){d.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK:",C)}return()=>{d.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,s,a,e,o]);const P=u.useCallback(async C=>{if(!t||!a){d.warn("[AdMeshProvider] โ ๏ธ Cannot perform intent analysis: missing API key or base URL");return}if(o)d.log("[AdMeshProvider] โน๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){d.log('[AdMeshProvider] โน๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{x(!0),z(null),d.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const R=C??Nt();if(!R){d.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),z("Failed to extract page content");return}d.log("[AdMeshProvider] ๐ Extracted headings:",{title:R.title,headingsCount:R.headings.length,domain:R.domain});const O=await An(R,{apiKey:t,apiBaseUrl:a||"https://api.useadmesh.com",extension:o,userId:h});O?(d.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:O.suggestions.length,suggestions:(O.suggestions||[]).map(Y=>{var ae;return{id:Y.id,text:Y.text,is_sponsored:Y.is_sponsored,recommendationId:((ae=Y.recommendation)==null?void 0:ae.recommendation_id)||null}})}),K(Y=>E(Y,O.suggestions||[]))):(d.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),z("Intent analysis failed"),K(Y=>Y.length>0?(d.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),Y):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(R){d.error("[AdMeshProvider] โ Error in intent analysis:",R),z("Intent analysis error"),K(U=>U.length>0?(d.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),U):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{x(!1)}},[t,a,o,h,E]),G=u.useCallback(async C=>{var Y,ae,me,Z,M,le,ze,Le;if(!m||!t||!t.toLowerCase().startsWith("pub_"))return;const R=C??Nt();if(!R){d.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const O=(typeof document<"u"?(ae=(Y=document.querySelector("h1"))==null?void 0:Y.textContent)==null?void 0:ae.replace(/\s+/g," ").trim():void 0)||((Z=(me=R.headings)==null?void 0:me[0])==null?void 0:Z.trim())||((M=R.title)==null?void 0:M.trim());if(!O){d.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{d.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const $e=await m.fetchPlatformResponse({query:O,sessionId:e,messageId:Rt.createMessageId(e),platformSurface:"embedded_assistant",model:p,messages:[],language:i,location:c,userId:h}),de=(Le=(ze=(le=$e.recommendation)==null?void 0:le.creative)==null?void 0:ze.follow_up_suggestion)==null?void 0:Le.trim(),ce=$e.recommendation_id;if(!de||!ce){d.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const xe={id:ce,text:de,type:"action",is_sponsored:!0,recommendation:$e,metadata:{source:"aip_context_prefetch",recommendation_id:ce}};K(Se=>T(Se,xe)),d.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:ce,suggestionText:de})}catch($e){d.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",$e)}},[t,i,c,p,m,e,h,T]),V=u.useCallback(async()=>{d.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await P()},[P]);u.useEffect(()=>{if(!m||B.current)return;B.current=!0;const C=Nt();Promise.allSettled([G(C),P(C)])},[m,P,G]);const H=u.useCallback(C=>{if(!C||C.status!=="active")return!1;const R=Date.parse(C.expires_at);return Number.isNaN(R)?!1:R>Date.now()},[]),D=u.useCallback(async(C,R,U,O)=>{const Y=O??k;if(!Y||!m){d.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:C,eventType:R,hasSession:!!Y,hasSdk:!!m});return}const ae=new Date().toISOString();d.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:C,eventType:R,recommendationId:Y.recommendation_id,delegationSessionId:Y.delegation_session_id,sessionId:Y.session_id});const me=await fetch(`${m.getApiBaseUrl()}${C}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:Y.delegation_session_id,recommendation_id:Y.recommendation_id,session_id:Y.session_id,event_type:R,timestamp:ae,metadata:U||{}})});if(!me.ok){const le=await me.text();throw d.error("[AdMeshProvider] โ Delegation event failed",{endpoint:C,eventType:R,status:me.status,errorBody:le,recommendationId:Y.recommendation_id,delegationSessionId:Y.delegation_session_id}),new Error(`Delegation event failed (${me.status}): ${le}`)}const Z=await me.json(),M=Z==null?void 0:Z.session;d.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:C,eventType:R,recommendationId:Y.recommendation_id,delegationSessionId:Y.delegation_session_id,returnedStatus:(M==null?void 0:M.status)||(Z==null?void 0:Z.status)}),M&&W(M)},[k,t,m]);u.useEffect(()=>{if(!k||!m)return;if(!H(k)){W(R=>R?{...R,status:"expired"}:null);return}const C=window.setInterval(()=>{D("/aip/delegation/heartbeat","heartbeat").catch(R=>{d.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",R)})},6e4);return()=>{window.clearInterval(C)}},[k,H,D,m]);const ne={sdk:m,apiKey:t,sessionId:e,theme:s,language:i,location:c,userId:h,model:p,messages:g,processedMessageIds:f,recommendationResults:N,activeDelegationSession:k,suggestions:j,isAnalyzingIntent:L,intentError:F,markMessageAsProcessed:C=>{A(R=>{const U=new Set(R);return U.add(C),U})},isMessageProcessed:C=>f.has(C),setRecommendationResult:(C,R)=>{y(U=>{const O=new Map(U);return O.set(C,R),O}),A(U=>{const O=new Set(U);return O.add(C),O})},getRecommendationResult:C=>N.get(C),hasRecommendationResult:C=>N.has(C),setActiveDelegationSession:C=>{W(C)},getActiveDelegationSession:()=>H(k)?k:null,hasActiveDelegationSession:()=>H(k),refreshDelegationActivity:async(C="turn_completed",R)=>{await D("/aip/delegation/activity",C,R)},stopDelegationSession:async(C="user_stopped",R)=>{const U=k;if(!U){d.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}d.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:C,recommendationId:U.recommendation_id,delegationSessionId:U.delegation_session_id}),await D("/aip/delegation/stop","session_stopped",{reason:C,...R||{}},U),await(m==null?void 0:m.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:U.session_id,recommendation_id:U.recommendation_id,delegation_session_id:U.delegation_session_id,brand_name:U.brand_name,status:"stopped",metadata:{reason:C,...R||{}}}).catch(O=>{d.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",O)})),W(null),d.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},retryIntentAnalysis:V};return n.jsx(Jt.Provider,{value:ne,children:l})};class Mn{constructor(){qe(this,"roots",new Map)}async render(e){try{d.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){d.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw d.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);d.log("[AdMeshRenderer] โ
Container ready");const a=this.roots.get(e.containerId);a&&(d.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),a.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const i=Gn.createRoot(s);d.log("[AdMeshRenderer] ๐ Rendering recommendations"),i.render(n.jsx(Cn,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:n.jsx(kn,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",d.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,i)}catch(o){throw d.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 pr=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},et=class et{constructor(e){qe(this,"config");qe(this,"apiBaseUrl");qe(this,"renderer",null);qe(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 et.createSession();try{const a=new URL(o).pathname.split("/").filter(c=>c.length>0),i=a[a.length-1];return i?`session_${Date.now()}_${i}`:et.createSession()}catch{return et.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 Mn),this.renderer}getTracker(){return this.tracker||(this.tracker=new Sn({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,a){const i=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:a||{}})});if(!i.ok){const h=await i.text();throw new Error(`Delegation event failed (${i.status}): ${h}`)}const c=await i.json();return(c==null?void 0:c.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]},a=this.getRenderer(),i=this.getTracker();await a.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:i,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 d.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var N,y,k,W,j,K,L,x,F,z,B,T,E;const o=`${this.apiBaseUrl}/aip/context`;if(d.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const P=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw d.error("[AdMeshSDK] โ sessionId not provided by platform - cannot process request"),P}const s=e.messageId;if(!s||s.trim()===""){const P=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw d.error("[AdMeshSDK] โ messageId not provided by platform - cannot process request"),P}const a=et.buildPlatformResponseCacheKey(e.sessionId,s),i=et.inFlightPlatformResponses.get(a);if(i)return d.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),i;const c=e.messages?e.messages.length:0,h=(typeof window<"u"&&window.navigator,"web"),p=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",g=pr((N=e.location)==null?void 0:N.countryCode)||"US",l=e.userId??this.config.userId,m={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:l||"",confidence:l?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:c},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:h,form_factor:p,locale:e.language||"en-US",country:g,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((y=e.location)==null?void 0:y.city)||void 0,state:((k=e.location)==null?void 0:k.state)||void 0,state_code:((W=e.location)==null?void 0:W.stateCode)||void 0,country:((j=e.location)==null?void 0:j.country)||void 0,country_code:g,zipcode:((K=e.location)==null?void 0:K.zipcode)||void 0,latitude:(L=e.location)==null?void 0:L.latitude,longitude:(x=e.location)==null?void 0:x.longitude}}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(z=(F=m.classification_input.interaction)==null?void 0:F.input.query_text)!=null&&z.trim()||d.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const _=JSON.stringify(m);d.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:m.message_id,specVersion:m.spec_version,classificationType:m.classification_input.type,platformId:m.platform.platform_id,surfaceChannel:(B=m.classification_input.interaction)==null?void 0:B.surface.channel,sessionId:(E=(T=m.classification_input.interaction)==null?void 0:T.session)==null?void 0:E.id});const f={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){f["X-AdMesh-Source"]="extension";const P=this.getExtensionSourceDomain();P&&(f["X-AdMesh-Source-Domain"]=P)}const A=(async()=>{const P=await fetch(o,{method:"POST",headers:f,body:_});if(!P.ok){const H=(await P.json().catch(()=>({}))).detail||`HTTP ${P.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${H}`)}const G=await P.json();return d.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{status:G.status,recommendationId:G.recommendation_id,hasRecommendation:!!G.recommendation,hasTracking:!!G.tracking,hasDelegation:!!G.delegation,topLevelKeys:Object.keys(G)}),d.log("[AdMeshSDK] ๐ฆ Full PlatformResponse received from /aip/context",G),G})();et.inFlightPlatformResponses.set(a,A);try{return await A}finally{et.inFlightPlatformResponses.delete(a)}}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 a=await s.text().catch(()=>"");throw new Error(`Failed to track publisher assistant analytics (${s.status}): ${a}`)}}fireFollowupExposure(e,o,s){this.getTracker().fireFollowupExposure(e,o,s)}async fireFollowupEngagement(e,o,s){return this.getTracker().fireFollowupEngagement(e,o,s)}};qe(et,"inFlightPlatformResponses",new Map);let Rt=et;class en{constructor(e={}){qe(this,"autoAddLabels");qe(this,"fireExposurePixels");qe(this,"labelStyle");qe(this,"processedLinks",new Set);qe(this,"mutationObserver",null);var o,s,a,i;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:((a=e.labelStyle)==null?void 0:a.color)||"#666",marginLeft:((i=e.labelStyle)==null?void 0:i.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 a=[];if(o.length>0){const i=this.getLinksToProcess(e),c=new Map(o.map(p=>{var g,l,m;return[((g=p==null?void 0:p.tracking)==null?void 0:g.click_url)||((m=(l=p==null?void 0:p.recommendation)==null?void 0:l.creative)==null?void 0:m.landing_page_url)||"",p]}).filter(([p])=>!!p)),h=new Map;o.forEach(p=>{var l,m;const g=(m=(l=p==null?void 0:p.recommendation)==null?void 0:l.creative)==null?void 0:m.landing_page_url;if(g&&typeof g=="string"){const _=g.trim().replace(/\/$/,"");h.set(_,p),h.set(`${_}/`,p)}}),i.forEach(p=>{var f,A,N,y,k,W,j,K;const g=p.getAttribute("href")||"",l=`${g}`;if(this.processedLinks.has(l))return;let m=c.get(g),_=g;if(!m){const L=g.trim().replace(/\/$/,"");m=h.get(L)||h.get(`${L}/`);const x=((f=m==null?void 0:m.tracking)==null?void 0:f.click_url)||((N=(A=m==null?void 0:m.recommendation)==null?void 0:A.creative)==null?void 0:N.landing_page_url);m&&x&&(d.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",g),p.setAttribute("href",x),_=x)}if(m){this.processedLinks.add(l),p.setAttribute("target","_blank"),p.setAttribute("rel","noopener noreferrer");const L={element:p,href:_,text:p.textContent||"",hasAdLabel:this.hasAdLabel(p),matchedRecommendation:{recommendation_id:(m==null?void 0:m.recommendation_id)||"",click_url:((y=m==null?void 0:m.tracking)==null?void 0:y.click_url)||((W=(k=m==null?void 0:m.recommendation)==null?void 0:k.creative)==null?void 0:W.landing_page_url)||"",exposure_url:(j=m==null?void 0:m.tracking)==null?void 0:j.exposure_url}};this.autoAddLabels&&!L.hasAdLabel?(d.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",_),this.addAdLabel(p),L.hasAdLabel=!0):this.autoAddLabels?L.hasAdLabel&&d.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):d.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const x=(K=m==null?void 0:m.tracking)==null?void 0:K.exposure_url;this.fireExposurePixels&&x&&s&&L.matchedRecommendation&&s({exposureUrl:x,recommendationId:L.matchedRecommendation.recommendation_id,linkElement:p}),a.push(L)}})}else Array.from(e.querySelectorAll("a")).forEach(c=>{const h=c.getAttribute("href")||"",p=`${h}`;if(this.processedLinks.has(p))return;if(this.isAdMeshLink(h)){this.processedLinks.add(p);const l={element:c,href:h,text:c.textContent||"",hasAdLabel:this.hasAdLabel(c),matchedRecommendation:void 0};if(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!l.hasAdLabel?(d.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to pattern-matched AdMesh link:",h),this.addAdLabel(c),l.hasAdLabel=!0):this.autoAddLabels?l.hasAdLabel&&d.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):d.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const m=this.convertClickUrlToExposureUrl(h);s({exposureUrl:m,recommendationId:this.extractRecommendationIdFromUrl(h),linkElement:c})}a.push(l)}});return a}hasAdLabel(e){var c,h,p;if((e.textContent||"").includes("Ad"))return d.log("[WeaveResponseProcessor] โน๏ธ Link text contains Ad label"),!0;const s=e.querySelectorAll("sub, span");for(const g of Array.from(s))if((c=g.textContent)!=null&&c.includes("Ad"))return d.log("[WeaveResponseProcessor] โน๏ธ Link has Ad label as child element"),!0;let a=e.previousSibling;for(;a&&a.nodeType===Node.TEXT_NODE;){const g=a.textContent||"";if(g.trim()===""){a=a.previousSibling;continue}if(g.includes("Ad"))return d.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(a&&a.nodeType===Node.ELEMENT_NODE){const g=a,l=g.tagName.toUpperCase();if((l==="SUB"||l==="SPAN")&&((h=g.textContent)!=null&&h.includes("Ad")))return d.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",l),!0}let i=e.nextSibling;for(;i&&i.nodeType===Node.TEXT_NODE;){const g=i.textContent||"";if(g.trim()===""){i=i.nextSibling;continue}if(g.includes("Ad"))return d.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const g=i,l=g.tagName.toUpperCase();if((l==="SUB"||l==="SPAN")&&((p=g.textContent)!=null&&p.includes("Ad")))return d.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next element sibling:",l),!0}return d.log("[WeaveResponseProcessor] โน๏ธ No existing Ad label found"),!1}addAdLabel(e){if(d.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){d.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){d.log("[WeaveResponseProcessor] โน๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){d.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 a=!1;s.addEventListener("mouseenter",()=>{s.style.opacity="0.7"}),s.addEventListener("mouseleave",()=>{s.style.opacity="1",a&&(a=!1)}),s.addEventListener("click",c=>{c.stopPropagation(),a=!a,a?(s.style.textDecoration="underline",s.style.opacity="0.7"):(s.style.textDecoration="none",s.style.opacity="1")});const i=c=>{a&&c.target!==s&&(a=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",i);try{const c=e.nextSibling;c?(o.insertBefore(s,c),d.log("[WeaveResponseProcessor] โ
Ad label inserted before next sibling")):(o.appendChild(s),d.log("[WeaveResponseProcessor] โ
Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?d.log("[WeaveResponseProcessor] โ
Ad label successfully added to link:",e.href):d.error("[WeaveResponseProcessor] โ Ad label insertion failed - label not in DOM")}catch(c){d.error("[WeaveResponseProcessor] โ Error inserting Ad label:",c)}}removeLeftAdLabel(e){var s,a,i;let o=e.previousSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const c=o.textContent||"";if(c.trim()===""){o=o.previousSibling;continue}if(c.includes("Ad")){(s=o.parentNode)==null||s.removeChild(o);return}break}if(o&&o.nodeType===Node.ELEMENT_NODE){const c=o;(c.tagName==="SUB"||c.tagName==="SPAN")&&((a=c.textContent)!=null&&a.includes("Ad"))&&((i=c.parentNode)==null||i.removeChild(c))}}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(a=>e.includes(a)))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),a=`${`${o.protocol}//${o.host}`}/exposure`,i=new URLSearchParams(o.search);return i.has("cpx")||i.set("cpx","0"),`${a}?${i.toString()}`}catch{return d.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 At(){const t=Zt();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 hr=({className:t,size:e=20})=>n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M5 12h14"}),n.jsx("path",{d:"M12 5v14"})]}),En=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:a})=>{var _,f,A,N,y;const i=(f=(_=t.recommendation)==null?void 0:_.creative)!=null&&f.follow_up_suggestion&&((A=t.tracking)!=null&&A.followup_engagement_url)&&((N=t.tracking)!=null&&N.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,c=i==null?void 0:i.query,h=i==null?void 0:i.engagement_url,p=i==null?void 0:i.exposure_url,g=t.recommendation_id,l=((y=t.recommendation)==null?void 0:y.offerId)||g;if(!c||!h||!p)return d.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const m=async()=>{try{h&&g&&(d.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(h,g,s)),a&&c?(d.log(`[AdMeshFollowup] ๐ Executing query: ${c}`),await a(c)):d.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(k){d.error("[AdMeshFollowup] โ Error handling follow-up click:",k)}};return n.jsx(It,{productId:l,recommendationId:g||"",exposureUrl:p,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:n.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[n.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),n.jsxs("div",{onClick:m,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&m()},"aria-label":`Sponsored follow-up: ${c}`,children:[n.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:c}),n.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),n.jsx(hr,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},jt=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:a,initialRecommendation:i,triggerExposureUrl:c=!0,followups_container_id:h,onPasteToInput:p,onDelegationConsent:g,onDelegationActivated:l,onStartDelegation:m,onExecuteQuery:_,onFollowupDetected:f,isContainerReady:A})=>{var ce,xe,Se,Ae;const{sdk:N,sessionId:y,apiKey:k,language:W,location:j,userId:K,model:L,messages:x,theme:F,getRecommendationResult:z,hasRecommendationResult:B,setRecommendationResult:T,activeDelegationSession:E,setActiveDelegationSession:P,hasActiveDelegationSession:G}=At(),V=w=>!!w&&w.status==="generated"&&!!w.recommendation,H=a||K,[D,ne]=u.useState(null),[C,R]=u.useState(null),[U,O]=u.useState(!0),[Y,ae]=u.useState(null),me=u.useRef(null),Z=u.useRef(!1),M=u.useRef(!1),le=u.useRef(t),ze=u.useRef(e);u.useEffect(()=>{le.current=t,ze.current=e},[t,e]),u.useEffect(()=>{me.current!==o&&(me.current=null,M.current=!1,ne(null),R(null))},[o]);const Le=G()&&(E==null?void 0:E.session_id)===y;u.useEffect(()=>{var S,be,b;if(!o||!B(o)||Le)return;const w=z(o);if(!w){d.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),ne(null),R(null),ae(null),O(!1),me.current=o,Z.current=!1,M.current=!0;return}let oe=((S=w.recommendation)==null?void 0:S.format)||"tail";(oe==="weave"||oe==="product_card")&&(oe="tail"),d.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:w.recommendation_id,format:(be=w.recommendation)==null?void 0:be.format}),ne(w),R(oe),ae(null),O(!1),me.current=o,Z.current=!1,M.current=!0,(b=le.current)==null||b.call(le,o,w)},[z,B,Le,o]),u.useEffect(()=>{var w,oe,S,be,b,re,We;if(!(!i||!o)&&!Le)try{const fe=i,Be=i.status||"unknown";if(!V(fe)){if(Be==="no_match"){d.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),ne(null),R(null),ae(null),O(!1),me.current=o,Z.current=!1,M.current=!0,T(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${Be})`)}let Ce=((w=fe.recommendation)==null?void 0:w.format)||"tail";(Ce==="weave"||Ce==="product_card")&&(Ce="tail"),ne(fe),R(Ce),ae(null),O(!1),me.current=o,Z.current=!1,M.current=!0,T(o,fe),(oe=le.current)==null||oe.call(le,o,fe),d.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),d.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:fe.recommendation_id,format:(S=fe.recommendation)==null?void 0:S.format,brandName:(b=(be=fe.recommendation)==null?void 0:be.creative)==null?void 0:b.brand_name,headline:(We=(re=fe.recommendation)==null?void 0:re.creative)==null?void 0:We.headline,hasTracking:!!fe.tracking})}catch(fe){const Be=fe instanceof Error?fe:new Error(String(fe));M.current=!1,d.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${Be.message}`)}},[Le,i,o,T]),u.useEffect(()=>{if(!o||!s||s.trim()===""){d.log("[AdMeshRecommendations] โ Validation failed - missing required parameters"),O(!1);return}if(Le){d.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:y,delegationSessionId:E==null?void 0:E.delegation_session_id}),ne(null),R(null),ae(null),O(!1),Z.current=!1;return}if(!(N!=null&&N.fetchPlatformResponse)){d.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),O(!1);return}if(M.current){d.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(me.current===o){d.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(Z.current){d.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}d.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var oe,S,be,b,re,We,fe,Be,Ce;try{Z.current=!0,O(!0),ae(null);const ue=await N.fetchPlatformResponse({query:s.trim(),sessionId:y,messageId:o,language:W,location:j,userId:H,model:L,...x&&x.length>0&&{messages:x}}),Ee=(ue==null?void 0:ue.status)||"unknown";if(!V(ue)){if(Ee==="no_match"){d.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),ne(null),R(null),ae(null),O(!1),Z.current=!1,me.current=o,T(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${Ee})`)}ne(ue),d.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:ue.recommendation_id,format:(oe=ue.recommendation)==null?void 0:oe.format,brandName:(be=(S=ue.recommendation)==null?void 0:S.creative)==null?void 0:be.brand_name,headline:(re=(b=ue.recommendation)==null?void 0:b.creative)==null?void 0:re.headline,hasTracking:!!ue.tracking});let Me=((We=ue.recommendation)==null?void 0:We.format)||"tail";(Me==="weave"||Me==="product_card")&&(Me="tail"),R(Me),me.current=o,T(o,ue),d.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(fe=ue.recommendation)==null?void 0:fe.format,selected_format:Me}),O(!1),Z.current=!1,(Be=le.current)==null||Be.call(le,o,ue)}catch(ue){const Ee=ue instanceof Error?ue:new Error(String(ue));Ee.message.includes("Failed to fetch")||Ee.message.includes("NetworkError")?d.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${Ee.message} `):d.error(`[AdMeshRecommendations] โ Error fetching recommendations: ${Ee.message} `),ae(Ee),O(!1),Z.current=!1,(Ce=ze.current)==null||Ce.call(ze,Ee)}})()},[E==null?void 0:E.delegation_session_id,Le,N,y,o,s,W,j,H,L,i,T]),u.useEffect(()=>{var oe,S,be,b;if(!D||!f)return;const w=(S=(oe=D.recommendation)==null?void 0:oe.creative)!=null&&S.follow_up_suggestion&&((be=D.tracking)!=null&&be.followup_engagement_url)&&((b=D.tracking)!=null&&b.followup_exposure_url)?{label:D.recommendation.creative.follow_up_suggestion,query:D.recommendation.creative.follow_up_suggestion,engagement_url:D.tracking.followup_engagement_url,exposure_url:D.tracking.followup_exposure_url}:null;w&&f(w,D.recommendation_id)},[D,f]);const $e=u.useCallback(async w=>{if(!N||!y)throw new Error("AdMesh SDK activation requires an initialized session");const oe=await fetch(`${N.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${k}`},body:JSON.stringify({session_id:y,recommendation_id:w.recommendation_id,metadata:w.metadata})});if(!oe.ok){const re=await oe.text();throw new Error(`Failed to activate delegation session: ${oe.status} ${re}`)}const S=await oe.json(),be={...w,delegation_session_id:S.delegation_session_id||w.delegation_session_id,session_id:S.session_id||y,brand_id:S.brand_id||w.brand_id,brand_name:S.brand_name||w.brand_name,mcp_endpoint:S.mcp_endpoint,eligibility_reason:S.eligibility_reason||w.eligibility_reason,delegate_reason:S.delegate_reason||w.delegate_reason,session_goal:S.session_goal||w.session_goal,desired_outcome_type:S.desired_outcome_type||w.desired_outcome_type,required_user_inputs:S.required_user_inputs||w.required_user_inputs||[],required_consent_types:S.required_consent_types||w.required_consent_types||[],success_outcome:S.success_outcome||w.success_outcome,fallback_message:S.fallback_message||w.fallback_message,session_mode:"inline",status:S.status||"active",capabilities:S.capabilities||w.capabilities||[],allowed_data_types:S.allowed_data_types||w.allowed_data_types||[],auth_model:S.auth_model||w.auth_model,handoff_protocol:S.handoff_protocol||w.handoff_protocol,supported_actions:S.supported_actions||w.supported_actions||[],metadata:S.metadata||w.metadata},b={delegation_session_id:S.delegation_session_id,recommendation_id:w.recommendation_id,session_id:S.session_id||y,brand_agent_id:S.brand_agent_id,brand_id:S.brand_id||w.brand_id,brand_name:S.brand_name||w.brand_name||"Brand",mcp_endpoint:S.mcp_endpoint,status:S.status||"active",activated_at:S.created_at,last_activity_at:S.updated_at,expires_at:S.expires_at||S.updated_at,eligibility_reason:S.eligibility_reason||w.eligibility_reason,delegate_reason:S.delegate_reason||w.delegate_reason,session_goal:S.session_goal||w.session_goal,desired_outcome_type:S.desired_outcome_type||w.desired_outcome_type,required_user_inputs:S.required_user_inputs||w.required_user_inputs||[],required_consent_types:S.required_consent_types||w.required_consent_types||[],success_outcome:S.success_outcome||w.success_outcome,fallback_message:S.fallback_message||w.fallback_message,capabilities:S.capabilities||w.capabilities||[],allowed_data_types:S.allowed_data_types||w.allowed_data_types||[],consent_requirements:S.consent_requirements||w.consent_requirements||[],auth_model:S.auth_model||w.auth_model,handoff_protocol:S.handoff_protocol||w.handoff_protocol,supported_actions:S.supported_actions||w.supported_actions||[],metadata:S.metadata||w.metadata};if(P(b),await N.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:y,recommendation_id:w.recommendation_id,delegation_session_id:S.delegation_session_id,brand_name:b.brand_name,status:S.status||"active",metadata:{brand_agent_id:S.brand_agent_id,source:"recommendation_card"}}).catch(re=>{d.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",re)}),await N.reportDelegationSessionStarted(b,{brand_agent_id:S.brand_agent_id,brand_name:b.brand_name}).then(re=>{re&&P(re)}).catch(re=>{d.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",re)}),l){try{await l(be)}catch(re){d.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",re)}return}if(m)try{await m({...w.platform_response,delegation:{...w.platform_response.delegation,...be,delegation_session_id:S.delegation_session_id,available:!0,status:S.status||"active"}})}catch(re){d.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",re)}},[k,l,m,N,y,P]);if(!o||!s||s.trim()===""||U||Y)return null;if(!D||!C)return d.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!D,detectedFormat:C,isLoading:U,hasError:!!Y}),null;d.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:D.recommendation_id,detectedFormat:C,brandName:(xe=(ce=D.recommendation)==null?void 0:ce.creative)==null?void 0:xe.brand_name,headline:(Ae=(Se=D.recommendation)==null?void 0:Se.creative)==null?void 0:Ae.headline});const de=typeof document<"u"&&h&&(A??!0)?document.getElementById(h):null;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:n.jsx(Xt,{recommendations:[D],theme:F,sessionId:y,triggerExposureUrl:c,onPasteToInput:p,onDelegationConsent:g,onDelegationActivated:$e,onStartDelegation:m})}),de&&N&&y?Yn.createPortal(n.jsx(En,{recommendation:D,theme:F,sdk:N,sessionId:y,onExecuteQuery:_}),de):null]})},jn=({format:t="tail",onError:e,messageId:o,query:s,fallback:a,previousRecommendations:i})=>{const{sdk:c,sessionId:h,theme:p,apiKey:g,language:l,location:m,userId:_,model:f,messages:A}=At(),N=u.useRef(null),[y,k]=u.useState("");return u.useEffect(()=>{o&&k(`admesh-weave-fallback-${o}`)},[o]),d.log("[WeaveFallbackRecommendations] ๐จ Component render"),u.useEffect(()=>{if(d.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:a,hasPreviousRecommendations:i&&i.length>0,previousRecommendationsCount:(i==null?void 0:i.length)||0}),!a){d.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(d.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){d.log("[WeaveFallbackRecommendations] โ Validation failed - returning early");return}if(d.log("[WeaveFallbackRecommendations] โ
Validation passed"),!c||!y){d.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const W=i&&i.length>0;d.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:W,count:(i==null?void 0:i.length)||0,fallback:a,messageId:o}),W?(d.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${i.length} previous recommendation(s), skipping API call`),(async()=>{var K,L,x,F,z,B,T;try{const E=i[0];if(d.log("[WeaveFallbackRecommendations] ๐ฆ Processing AIP response:",{hasAipResponse:!!E,recommendationId:(E==null?void 0:E.recommendation_id)||"",format:((K=E==null?void 0:E.recommendation)==null?void 0:K.format)||"unknown"}),E&&process.env.NODE_ENV==="development"&&d.log("[WeaveFallbackRecommendations] ๐ Recommendation received (DEV):",{recommendation_id:E==null?void 0:E.recommendation_id,click_url:((L=E==null?void 0:E.tracking)==null?void 0:L.click_url)||((F=(x=E==null?void 0:E.recommendation)==null?void 0:x.creative)==null?void 0:F.landing_page_url),format:(z=E==null?void 0:E.recommendation)==null?void 0:z.format,full_response:E}),!E){d.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await c.showRecommendations({query:s.trim(),containerId:y,sessionId:h,messageId:o});return}const P=c,G=P.getRenderer,V=P.getTracker,H=(B=P.config)==null?void 0:B.theme;if(G&&V){const D={sessionId:h,messageId:o,recommendations:[E]},ne=G.call(c),C=V.call(c),R=(c==null?void 0:c.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await ne.render({containerId:y,response:D,theme:p||H,tracker:C,sessionId:h,apiKey:g||((T=c==null?void 0:c.config)==null?void 0:T.apiKey),apiBaseUrl:R,language:l,location:m,userId:_,model:f,messages:A}),d.log("[WeaveFallbackRecommendations] โ
Recommendations rendered from previous response (no API call)")}else d.warn("[WeaveFallbackRecommendations] โ ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await c.showRecommendations({query:s.trim(),containerId:y,sessionId:h,messageId:o})}catch(E){const P=E instanceof Error?E:new Error(String(E));d.error(`[WeaveFallbackRecommendations] โ Error rendering previous recommendations: ${P.message}`);try{await c.showRecommendations({query:s.trim(),containerId:y,sessionId:h,messageId:o})}catch{e==null||e(P)}}})()):(d.log("[WeaveFallbackRecommendations] ๐ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(c!=null&&c.showRecommendations)){d.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await c.showRecommendations({query:s.trim(),containerId:y,sessionId:h,messageId:o}),d.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(K){const L=K instanceof Error?K:new Error(String(K));d.log(`[WeaveFallbackRecommendations] โ Error: ${L.message}`),e==null||e(L)}})())},[c,h,y,t,o,s,a,e,i,p]),!a||!o||!s||s.trim()===""?null:n.jsx("div",{ref:N,id:y,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Rn=u.createContext(void 0),fr=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:a})=>n.jsx(Rn.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:a},children:t}),gr=()=>u.useContext(Rn),Ot=t=>{try{return new URL(t),!0}catch{return!1}},gn=t=>t&&t.trim()?t.trim():"",mt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",Ze=t=>mt(t)||void 0,xr=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},br=(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)},yr=(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 a=mt(t);return a?/%|off/i.test(a)?a:s==="amount"||s==="fixed"||s==="fixed_amount"?`${a} off`:`${a}% off`:""},_r=({recommendations:t,theme:e,className:o="",style:s={},sessionId:a,triggerExposureUrl:i=!0,onDelegationConsent:c,onDelegationActivated:h,onStartDelegation:p,onPasteToInput:g})=>{var be,b,re,We,fe,Be,Ce,ue,Ee,Me,Ie,Ye,tt,nt,ee,_e,Qe,Ke,ve,dt,lt,ut,we,pt,yt,ht,Xe,Ct,Dt,Tt,Mt,Ge,rt,_t,wt,je,vt;if(!t||t.length===0)return d.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const l=t[0],m=((be=l==null?void 0:l.recommendation)==null?void 0:be.offerId)||"",_=((b=l==null?void 0:l.tracking)==null?void 0:b.exposure_url)||"",f=(l==null?void 0:l.recommendation_id)||"",A=((We=(re=l==null?void 0:l.recommendation)==null?void 0:re.creative)==null?void 0:We.description)||"",N=((fe=l==null?void 0:l.recommendation)==null?void 0:fe.disclosure)||"Sponsored",y=((Ce=(Be=l==null?void 0:l.recommendation)==null?void 0:Be.creative)==null?void 0:Ce.brand_name)||"",k=((Ee=(ue=l==null?void 0:l.recommendation)==null?void 0:ue.creative)==null?void 0:Ee.headline)||((Ie=(Me=l==null?void 0:l.recommendation)==null?void 0:Me.creative)==null?void 0:Ie.brand_name)||"",W=((tt=(Ye=l==null?void 0:l.recommendation)==null?void 0:Ye.creative)==null?void 0:tt.logo_url)||"",j=((nt=l==null?void 0:l.tracking)==null?void 0:nt.click_url)||((_e=(ee=l==null?void 0:l.recommendation)==null?void 0:ee.creative)==null?void 0:_e.landing_page_url)||"",K=gn((Ke=(Qe=l==null?void 0:l.recommendation)==null?void 0:Qe.creative)==null?void 0:Ke.cta_text),L=((dt=(ve=l==null?void 0:l.recommendation)==null?void 0:ve.creative)==null?void 0:dt.products)||[],x=L.length>1,F=x?L.slice(0,4):[],z=((lt=l==null?void 0:l.recommendation)==null?void 0:lt.format)||"tail",B=z==="bridge",T=((ut=l==null?void 0:l.delegation)==null?void 0:ut.brand_name)||y,E=((we=l==null?void 0:l.delegation)==null?void 0:we.available)===!0,P=B&&E,G="Talk to Agent",V=!x&&!!K&&!!j;if(!y&&!k&&!A)return d.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:y,hasFirstRecommendation:!!l,recommendationId:f,recommendationKeys:l?Object.keys(l):[]}),null;let H=y,D="";k&&k!==y&&(D=k),D&&(H=`${y} โ ${D}`),d.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:f,productId:m,exposureUrl:_?"present":"MISSING",sessionId:a?"present":"MISSING",recommendationsCount:t.length,clickUrl:j||"MISSING",clickUrlSource:(pt=l==null?void 0:l.tracking)!=null&&pt.click_url?"tracking.click_url":(ht=(yt=l==null?void 0:l.recommendation)==null?void 0:yt.creative)!=null&&ht.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:A?"present":"MISSING",brandName:y,productName:k,headlineText:H,triggerExposureUrl:i}),d.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:f,brandName:y,productName:k,hasDescription:!!A,hasClickUrl:!!j,hasLogoUrl:!!W,recommendationFormat:z});const ne=(q,De)=>{De&&De.stopPropagation(),d.log(`AdMesh tail ad ${q} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:f,productId:m,clickUrl:j,source:q}).catch(()=>{d.error(`[AdMesh] Failed to track ${q} click`)})},C=q=>{q.stopPropagation(),ne("tail_ad_brand_name")},R=q=>{q.stopPropagation(),ne("tail_ad_cta")},U=q=>{q.stopPropagation(),ne("tail_ad_logo")},[O,Y]=u.useState(!1),ae=u.useRef(null);u.useEffect(()=>()=>{ae.current&&(ae.current(!1),ae.current=null)},[]);const me=q=>{var De;(De=ae.current)==null||De.call(ae,q),ae.current=null,Y(!1)},Z=async()=>c?await c(l):await new Promise(q=>{ae.current=q,Y(!0)}),M=async()=>{if(f&&a)try{const q=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",De=await fetch(`${q}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:f,session_id:a,is_test:!1})});De.ok||d.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",De.statusText)}catch(q){d.error("[AdMesh Tail Ad] Error tracking delegation engagement:",q)}},le=async q=>{var ct,Oe,ft,Q;if(q.preventDefault(),q.stopPropagation(),!l||!P)return;if(ne("tail_ad_delegation_cta"),await M(),!await Z()){d.log("[AdMesh Tail Ad] Delegation consent declined");return}const te=l.delegation,X=te!=null&&te.available?{recommendation_id:l.recommendation_id,brand_id:Ze(te.brand_id),brand_name:Ze(te.brand_name||((Oe=(ct=l.recommendation)==null?void 0:ct.creative)==null?void 0:Oe.brand_name)),eligibility_reason:Ze(te.eligibility_reason),delegate_reason:Ze(te.delegate_reason),session_goal:Ze(te.session_goal),desired_outcome_type:te.desired_outcome_type,required_user_inputs:Array.isArray(te.required_user_inputs)?te.required_user_inputs.filter(J=>typeof J=="string"):[],required_consent_types:Array.isArray(te.required_consent_types)?te.required_consent_types.filter(J=>typeof J=="string"):[],success_outcome:Ze(te.success_outcome),fallback_message:Ze(te.fallback_message),session_mode:Ze(te.session_mode),status:Ze(te.status),capabilities:te.capabilities||[],allowed_data_types:te.allowed_data_types||[],consent_requirements:te.consent_requirements||[],auth_model:Ze(te.auth_model),handoff_protocol:te.handoff_protocol&&typeof te.handoff_protocol=="object"?te.handoff_protocol:void 0,supported_actions:te.supported_actions||[],metadata:te.metadata&&typeof te.metadata=="object"?te.metadata:void 0,platform_response:l}:null;if(h&&X){await h(X);return}if(p){await p(l);return}const He=((Q=(ft=l.recommendation)==null?void 0:ft.creative)==null?void 0:Q.follow_up_suggestion)||"";if(He&&g){g(He);return}if(He&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(He);return}},[ze,Le]=u.useState(!1),$e=y?y.charAt(0).toUpperCase():"B",de=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,ce=(e==null?void 0:e.surfaceColor)||((Ct=(Xe=e==null?void 0:e.components)==null?void 0:Xe.card)==null?void 0:Ct.backgroundColor)||(de?"#1f2937":"#ffffff"),xe=(e==null?void 0:e.borderColor)||((Tt=(Dt=e==null?void 0:e.components)==null?void 0:Dt.card)==null?void 0:Tt.borderColor)||(de?"rgba(255, 255, 255, 0.1)":"rgba(0, 0, 0, 0.05)"),Se=(e==null?void 0:e.borderRadius)||((Ge=(Mt=e==null?void 0:e.components)==null?void 0:Mt.card)==null?void 0:Ge.borderRadius)||"8px",Ae=de?"0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2)":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",w=de?"0 10px 15px -3px rgba(0, 0, 0, 0.4), 0 4px 6px -2px rgba(0, 0, 0, 0.3)":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",oe=((rt=e==null?void 0:e.shadows)==null?void 0:rt.medium)||((wt=(_t=e==null?void 0:e.components)==null?void 0:_t.card)==null?void 0:wt.boxShadow)||Ae,S=((je=e==null?void 0:e.shadows)==null?void 0:je.large)||w;return n.jsxs(It,{productId:m,recommendationId:f,exposureUrl:_,sessionId:a,triggerExposureUrl:i,className:`admesh-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:[n.jsx("style",{children:`
|
|
24
|
+
`}),r.jsxs("div",{role:!N&&O?"link":void 0,tabIndex:!N&&O?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((At=(Qe=e==null?void 0:e.components)==null?void 0:Qe.card)==null?void 0:At.borderRadius)||"14px",border:`1px solid ${pe}`,background:L,boxShadow:D,minWidth:0,cursor:!N&&O?"pointer":void 0},onClick:re,onKeyDown:me,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:S?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!R&&j&&Zn(j)?r.jsx("img",{src:j,alt:`${p} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>ke(!0)}):r.jsx("span",{style:{fontSize:"0.85rem",fontWeight:700,color:ne},children:(p||"A").charAt(0).toUpperCase()})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[r.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"0.68rem",color:ne},children:He?p:""}),r.jsx("div",{style:{flexShrink:0,fontSize:"0.62rem",color:ne,textTransform:"uppercase",letterSpacing:"0.08em"},children:v})]}),!N&&r.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"0.84rem",lineHeight:1.3,fontWeight:700,color:_e,marginBottom:"4px"},title:xe,children:xe}),ue&&r.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"0.7rem",lineHeight:1.35,color:be},title:ue,children:ue})]})]}),N&&r.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:W.map(Z=>{const Te=Nt(Z.product_name)||"Product",tt=Nt(Z.product_link)||Nt(Z.product_url)||O||"#",Ge=so(Z.product_price,Z.product_currency),gt=Nt(Z.product_image_url),ot=gt&&Zn(gt)?gt:"",Oe=tt!=="#";return r.jsx("a",{href:tt,target:Oe?"_blank":void 0,rel:Oe?"noopener noreferrer":void 0,onClick:Le=>K(`compact_tail_ad_product_${Z.product_id||"item"}`,Le),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${pe}`,borderRadius:"12px",background:le,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:S?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:ne,fontSize:"0.75rem",fontWeight:700},children:ot?r.jsx("img",{src:ot,alt:Te,style:{width:"100%",height:"100%",objectFit:"cover"}}):Te.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("div",{style:{fontSize:"0.68rem",lineHeight:1.25,fontWeight:600,color:_e,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:Te,children:Te}),r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:Ge&&r.jsx("span",{style:{fontSize:"0.66rem",fontWeight:700,color:_e},children:Ge})})]})]})},Z.product_id||`${w}-${Te}`)})}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:N?0:G},children:[r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:De}),N&&$.length>W.length?r.jsxs("span",{style:{fontSize:"0.62rem",color:ne},children:["+",$.length-W.length," more"]}):null]}),Ae?r.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${pe}`,borderRadius:"12px",background:le,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:"0.65rem",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:Se},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"0.74rem",lineHeight:1.4,color:_e,fontWeight:600},children:["Allow ",J||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"0.68rem",lineHeight:1.45,color:be},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:Z=>{Z.preventDefault(),Z.stopPropagation(),F(!1)},style:{borderRadius:"10px",border:`1px solid ${pe}`,background:L,color:_e,fontSize:"0.68rem",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),F(!0)},style:{borderRadius:"10px",border:"none",background:Se,color:"#ffffff",fontSize:"0.68rem",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})},pr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:l,onDelegationActivated:u,onStartDelegation:b})=>{const h=t.filter(d=>d&&typeof d=="object"&&typeof d.recommendation_id=="string"&&d.recommendation_id.length>0);if(!h||h.length===0)return a.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;a.log(`[AdMeshLayout] Rendering with ${h.length} valid recommendations`);const _=()=>{var d;if(h.length>0){const m=h[0],k=(d=m.recommendation)==null?void 0:d.format;a.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:k,recommendationKeys:Object.keys(m||{})}),(k==="product_card"||k==="weave"||k==="bridge")&&a.warn(`[AdMeshLayout] ${k} format requested, falling back to tail for canonical render payload`)}return r.jsx(Mn,{recommendations:h,theme:e,sessionId:i,onDelegationConsent:l,onDelegationActivated:u,onStartDelegation:b})};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:_()})};class hr{constructor(e){Ue(this,"firedExposures",new Set);Ue(this,"debug",!1);Ue(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 l=`${s}_${o}`;if(this.firedExposures.has(l)){this.debug&&a.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let b=null,h=null;const _=new IntersectionObserver(k=>{k.forEach(x=>{x.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?b===null&&(b=Date.now(),this.debug&&a.log("[Tracker] Ad reached MRC visibility threshold"),h=setTimeout(()=>{this.fireExposure(e,o,s),_.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):b!==null&&(h&&(clearTimeout(h),h=null),b=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"});_.observe(i);const m=setTimeout(()=>{_.disconnect(),h&&clearTimeout(h),u()},3e4);i.__admeshTrackerCleanup=()=>{_.disconnect(),h&&clearTimeout(h),clearTimeout(m)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,o,s){this.fireExposure(e,o,s)}fireFollowupEngagement(e,o,s){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s})}).catch(i=>{this.debug&&a.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const jn=c.createContext(void 0);function En(){const t=c.useContext(jn);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function io(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,l=>l.toUpperCase()):"This page"}function fr(){var t;try{console.log("[AdMesh] Starting direct headings extraction...");const e=_=>_.replace(/\s+/g," ").trim(),o=()=>{var p;const _=["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(","),x=(((p=_.map(y=>document.querySelector(y)).filter(y=>!!y).map(y=>{const C=y.cloneNode(!0);C.querySelectorAll(d).forEach(O=>O.remove());const j=e(C.textContent||"");return{element:y,text:j}}).filter(y=>y.text.length>=200).sort((y,C)=>C.text.length-y.text.length)[0])==null?void 0:p.element)||document.body).cloneNode(!0);x.querySelectorAll(d).forEach(y=>y.remove());const w=Array.from(x.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(y=>e(y.textContent||"")).filter(y=>y.length>=24);return(w.length>0?w.join(`
|
|
25
|
+
`):e(x.textContent||"")).slice(0,6e3)},s=io(window.location.pathname||"/"),i=e(document.title||"")||s,u=(()=>{const _=[],d=document.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(d).forEach(m=>{const k=e(m.textContent||"");k.length>0&&_.push(k)}),_})(),b=u.length>0?u:[i||s],h={title:i,headings:b,article_text:o(),url:window.location.href,domain:window.location.hostname,extracted_at:new Date().toISOString()};return console.log("[AdMesh] Extracted headings:",{title:h.title,headingsCount:h.headings.length,articleTextLength:((t=h.article_text)==null?void 0:t.length)||0,domain:h.domain}),h}catch(e){return console.error("[AdMesh] Error in direct headings extraction:",e),null}}function ao(t){return!!(t&&typeof t=="object"&&"recommendation_id"in t&&"status"in t)}function lo(t){var s,i,l,u,b,h,_,d,m,k,x;if(!t||typeof t!="object")return;if(ao(t))return t;const e=t;if(!e.recommendation_id)return;const o=(e.products||[]).map(w=>{var g,p;return{product_id:w.product_id||"",product_link:w.product_link||w.product_click_url||e.click_url||e.url||"",product_name:w.product_name||e.title||((g=e.creative_input)==null?void 0:g.product_name)||"",product_description:w.product_description||"",product_price:w.product_price??void 0,product_discount:w.product_discount??void 0,product_currency:w.product_currency,product_discount_type:w.product_discount_type,product_cta_label:w.product_cta_label||((p=e.creative_input)==null?void 0:p.cta_label),product_image_url:w.product_image_url,product_features:w.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:((l=e.creative_input)==null?void 0:l.short_description)||((u=e.creative_input)==null?void 0:u.long_description)||"",cta_text:((b=e.creative_input)==null?void 0:b.cta_label)||((h=o[0])==null?void 0:h.product_cta_label)||"Learn more",follow_up_suggestion:e.follow_up_suggestion,logo_url:(d=(_=e.creative_input)==null?void 0:_.assets)==null?void 0:d.logo_url,image_urls:((k=(m=e.creative_input)==null?void 0:m.assets)==null?void 0:k.image_urls)||[],landing_page_url:e.url||e.click_url||((x=e.creative_input)==null?void 0:x.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 co(t){return{...t,suggestions:(t.suggestions||[]).map(e=>({...e,recommendation:lo(e.recommendation)}))}}function er(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 gr(t,e){var o,s,i,l,u;try{console.log("[AdMesh SDK] Starting ACIE analyze-intent call...",{url:t.url});const b=Array.isArray(t.headings)?t.headings:[],h=(o=er(t.url))==null?void 0:o.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),_=h?h.replace(/\b\w/g,C=>C.toUpperCase()):void 0,d=e.apiKey.toLowerCase().startsWith("pub_")?er(t.url):void 0,m=e.extension?"extension":"admesh_ui_sdk",k=(t.domain||(typeof window<"u"?window.location.hostname:"")).trim().toLowerCase(),x={url:t.url,title:t.title||void 0,headings:b.length>0?b:_?[_]:void 0,article_text:((s=t.article_text)==null?void 0:s.trim())||void 0,domain:k,article_slug:d,agent_id:void 0,cpx_floor:void 0,source:m,api_key:e.apiKey,user_id:e.userId||void 0};console.log("[AdMesh SDK] Payload prepared:",{url:x.url,titleLength:((i=x.title)==null?void 0:i.length)||0,headingsCount:((l=x.headings)==null?void 0:l.length)||0,articleTextLength:((u=x.article_text)==null?void 0:u.length)||0,domain:x.domain,article_slug:x.article_slug,source:x.source,has_user_id:!!x.user_id});const w=`${e.apiBaseUrl}/acie/analyze-intent`;console.log("[AdMesh SDK] Calling ACIE API:",w);const g=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(x)});if(console.log("[AdMesh SDK] ACIE API response received:",{status:g.status,statusText:g.statusText,ok:g.ok}),!g.ok){const C=await g.text();throw console.error("[AdMesh SDK] ACIE API error:",{status:g.status,statusText:g.statusText,errorText:C}),new Error(`ACIE API error: ${g.status} - ${C}`)}const p=await g.json(),y=co(p);return console.log("[AdMesh SDK] ACIE analysis completed:",{url:t.url,suggestionsCount:y.suggestions.length}),y}catch(b){return console.error("[AdMesh SDK] Error calling ACIE analyze-intent endpoint:",b),null}}async function uo(t,e){var l,u;const o=(e.apiBaseUrl||"https://api.useadmesh.com").replace(/\/$/,""),s=new URLSearchParams({url:t.trim()});(l=e.agentDisplayId)!=null&&l.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 b=await i.text().catch(()=>"");throw new Error(`Page context request failed (${i.status}): ${b||i.statusText}`)}return await i.json()}function mo(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function po(){var t;if(typeof window>"u")return null;try{const e=(t=window.location.href)==null?void 0:t.trim();if(xr(e))return e}catch{return null}return null}function xr(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 ho(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,l=>l.toUpperCase()):e.hostname}catch{return"This page"}}function tr(t){const e=new URL(t),o=ho(t);return{title:o,headings:[o],article_text:`Article URL: ${t}
|
|
26
|
+
Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}function fo(t){const e=po();if(e)return e;const o=t==null?void 0:t.trim();return xr(o)?o:null}const br=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:l,location:u,userId:b,model:h,messages:_,pageContext:d,articleUrl:m,contextMode:k="auto",agentDisplayId:x,children:w})=>{const[g,p]=c.useState(null),[y,C]=c.useState(new Set),[j,O]=c.useState(new Map),[M,v]=c.useState(null),[$,W]=c.useState([]),[N,z]=c.useState(!1),[I,P]=c.useState(null),[Y,J]=c.useState(!1),ge=c.useRef(!1),B=!!d||k==="ad-slot"||k==="auto"&&(!!(m!=null&&m.trim())||mo()),se=c.useCallback(async()=>{if(d)return d;if(!B)return fr();const F=fo(m);if(!F)return a.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),P("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"),tr(F);try{J(!0);const q=await uo(F,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:x});return a.log("[AdMeshProvider] Page context resolved",{source:q.source,cache_hit:q.cache_hit,domain:q.context.domain}),q.context}catch(q){return a.error("[AdMeshProvider] Failed to fetch page context:",q),a.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),tr(F)}finally{J(!1)}},[x,i,t,m,d,B]),xe=c.useCallback((F,q)=>{const K=F.filter(re=>!re.is_sponsored).slice(0,3);return[q,...K]},[]),ue=c.useCallback((F,q)=>{const K=F.find(me=>me.is_sponsored),re=q.filter(me=>!me.is_sponsored).slice(0,3);return K?[K,...re]:re},[]);c.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]),c.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 Xt({apiKey:t,theme:s,apiBaseUrl:i,extension:o});p(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 Q=c.useCallback(async F=>{var q;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{z(!0),P(null),a.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const K=F??await se();if(!K){a.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),P("Failed to extract page content");return}a.log("[AdMeshProvider] ๐ Extracted headings:",{title:K.title,headingsCount:K.headings.length,articleTextLength:((q=K.article_text)==null?void 0:q.length)||0,domain:K.domain});const me=await gr(K,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:b});me?(a.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:me.suggestions.length,suggestions:(me.suggestions||[]).map(Me=>{var Ee;return{id:Me.id,text:Me.text,is_sponsored:Me.is_sponsored,recommendationId:((Ee=Me.recommendation)==null?void 0:Ee.recommendation_id)||null}})}),W(Me=>ue(Me,me.suggestions||[]))):(a.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),P("Intent analysis failed"),W(Me=>Me.length>0?(a.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),Me):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(K){a.error("[AdMeshProvider] โ Error in intent analysis:",K),P("Intent analysis error"),W(re=>re.length>0?(a.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),re):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{z(!1)}},[t,i,o,b,ue,se]),V=c.useCallback(async F=>{var re,me,Me,Ee,R,ke;if(!g||!t||!t.toLowerCase().startsWith("pub_"))return;const q=F??await se();if(!q){a.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const K=((me=(re=q.headings)==null?void 0:re[0])==null?void 0:me.trim())||((Me=q.title)==null?void 0:Me.trim());if(!K){a.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{a.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const S=await g.fetchPlatformResponse({query:K,sessionId:e,messageId:Xt.createMessageId(e),platformSurface:"embedded_assistant",model:h,messages:[],language:l,location:u,userId:b}),L=(ke=(R=(Ee=S.recommendation)==null?void 0:Ee.creative)==null?void 0:R.follow_up_suggestion)==null?void 0:ke.trim(),pe=S.recommendation_id;if(!L||!pe){a.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const D={id:pe,text:L,type:"action",is_sponsored:!0,recommendation:S,metadata:{source:"aip_context_prefetch",recommendation_id:pe}};W(Se=>xe(Se,D)),a.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:pe,suggestionText:L})}catch(S){a.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",S)}},[t,l,u,h,g,e,b,xe,se]),He=c.useCallback(async()=>{a.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await Q()},[Q]);c.useEffect(()=>{!g||ge.current||(ge.current=!0,(async()=>{const F=await se();await Promise.allSettled([V(F),Q(F)])})())},[g,Q,V,se]);const Ae=c.useCallback(F=>{if(!F||F.status!=="active")return!1;const q=Date.parse(F.expires_at);return Number.isNaN(q)?!1:q>Date.now()},[]),Ce=c.useCallback(async(F,q,K,re)=>{const me=re??M;if(!me||!g){a.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:F,eventType:q,hasSession:!!me,hasSdk:!!g});return}const Me=new Date().toISOString();a.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:F,eventType:q,recommendationId:me.recommendation_id,delegationSessionId:me.delegation_session_id,sessionId:me.session_id});const Ee=await fetch(`${g.getApiBaseUrl()}${F}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:me.delegation_session_id,recommendation_id:me.recommendation_id,session_id:me.session_id,event_type:q,timestamp:Me,metadata:K||{}})});if(!Ee.ok){const S=await Ee.text();throw a.error("[AdMeshProvider] โ Delegation event failed",{endpoint:F,eventType:q,status:Ee.status,errorBody:S,recommendationId:me.recommendation_id,delegationSessionId:me.delegation_session_id}),new Error(`Delegation event failed (${Ee.status}): ${S}`)}const R=await Ee.json(),ke=R==null?void 0:R.session;a.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:F,eventType:q,recommendationId:me.recommendation_id,delegationSessionId:me.delegation_session_id,returnedStatus:(ke==null?void 0:ke.status)||(R==null?void 0:R.status)}),ke&&v(ke)},[M,t,g]);c.useEffect(()=>{if(!M||!g)return;if(!Ae(M)){v(q=>q?{...q,status:"expired"}:null);return}const F=window.setInterval(()=>{Ce("/aip/delegation/heartbeat","heartbeat").catch(q=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",q)})},6e4);return()=>{window.clearInterval(F)}},[M,Ae,Ce,g]);const ie={sdk:g,apiKey:t,sessionId:e,theme:s,language:l,location:u,userId:b,model:h,messages:_,processedMessageIds:y,recommendationResults:j,activeDelegationSession:M,suggestions:$,isAnalyzingIntent:N||Y,intentError:I,markMessageAsProcessed:F=>{C(q=>{const K=new Set(q);return K.add(F),K})},isMessageProcessed:F=>y.has(F),setRecommendationResult:(F,q)=>{O(K=>{const re=new Map(K);return re.set(F,q),re}),C(K=>{const re=new Set(K);return re.add(F),re})},getRecommendationResult:F=>j.get(F),hasRecommendationResult:F=>j.has(F),setActiveDelegationSession:F=>{v(F)},getActiveDelegationSession:()=>Ae(M)?M:null,hasActiveDelegationSession:()=>Ae(M),refreshDelegationActivity:async(F="turn_completed",q)=>{await Ce("/aip/delegation/activity",F,q)},stopDelegationSession:async(F="user_stopped",q)=>{const K=M;if(!K){a.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}a.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:F,recommendationId:K.recommendation_id,delegationSessionId:K.delegation_session_id}),await Ce("/aip/delegation/stop","session_stopped",{reason:F,...q||{}},K),await(g==null?void 0:g.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:K.session_id,recommendation_id:K.recommendation_id,delegation_session_id:K.delegation_session_id,brand_name:K.brand_name,status:"stopped",metadata:{reason:F,...q||{}}}).catch(re=>{a.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",re)})),v(null),a.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},retryIntentAnalysis:He};return r.jsx(jn.Provider,{value:ie,children:w})};class yr{constructor(){Ue(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 l=Or.createRoot(s);a.log("[AdMeshRenderer] ๐ Rendering recommendations"),l.render(r.jsx(br,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:r.jsx(pr,{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,l)}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 go=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},ct=class ct{constructor(e){Ue(this,"config");Ue(this,"apiBaseUrl");Ue(this,"renderer",null);Ue(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl,extension:e.extension,extensionSourceDomain:e.extensionSourceDomain,userId:e.userId},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static buildPlatformResponseCacheKey(e,o){return`${e}::${o}`}getExtensionSourceDomain(){var o,s;const e=(o=this.config.extensionSourceDomain)==null?void 0:o.trim();if(e)return e.toLowerCase();if(typeof window<"u"&&((s=window.location)!=null&&s.hostname))return window.location.hostname.trim().toLowerCase()||void 0}static createSession(){const e=Date.now(),o=Math.random().toString(36).substring(2,15);return`session_${e}_${o}`}static generateSessionIdFromUrl(e){const o=e||(typeof window<"u"?window.location.href:"");if(!o)return ct.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),l=i[i.length-1];return l?`session_${Date.now()}_${l}`:ct.createSession()}catch{return ct.createSession()}}static createMessageId(e){const o=Date.now(),s=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${o}_${s}`:`msg_${o}_${s}`}getRenderer(){return this.renderer||(this.renderer=new yr),this.renderer}getTracker(){return this.tracker||(this.tracker=new hr({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const l=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(!l.ok){const b=await l.text();throw new Error(`Delegation event failed (${l.status}): ${b}`)}const u=await l.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(),l=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:l,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 p,y,C,j,O,M,v,$,W,N,z,I,P;const o=`${this.apiBaseUrl}/aip/context`;if(a.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const Y=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"),Y}const s=e.messageId;if(!s||s.trim()===""){const Y=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"),Y}const i=ct.buildPlatformResponseCacheKey(e.sessionId,s),l=ct.inFlightPlatformResponses.get(i);if(l)return a.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),l;const u=e.messages?e.messages.length:0,b=(typeof window<"u"&&window.navigator,"web"),h=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",_=go((p=e.location)==null?void 0:p.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,m=e.userId??this.config.userId,k={spec_version:"1.0",message_id:s,timestamp:new Date().toISOString(),platform:{platform_id:"placeholder",role:"platform",software:{name:"admesh_ui_sdk",version:e.model||"1.0.0"}},identity:{namespace:"platform_user",value_hash:m||"",confidence:m?1:0},consent:{status:"granted",source:"admesh_ui_sdk",scope:{intent_based_monetization:!0,agent_participation:!0,measurement:!0},constraints:{allow_identity_downstream:!1}},classification_input:{type:"interaction",interaction:{session:{id:e.sessionId,turn_index:u},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:b,form_factor:h,locale:e.language||"en-US",country:_,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((y=e.location)==null?void 0:y.city)||void 0,state:((C=e.location)==null?void 0:C.state)||void 0,state_code:((j=e.location)==null?void 0:j.stateCode)||void 0,country:((O=e.location)==null?void 0:O.country)||void 0,country_code:_,zipcode:((M=e.location)==null?void 0:M.zipcode)||void 0,latitude:(v=e.location)==null?void 0:v.latitude,longitude:($=e.location)==null?void 0:$.longitude},page:d}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(N=(W=k.classification_input.interaction)==null?void 0:W.input.query_text)!=null&&N.trim()||a.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const x=JSON.stringify(k);a.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:k.message_id,specVersion:k.spec_version,classificationType:k.classification_input.type,platformId:k.platform.platform_id,surfaceChannel:(z=k.classification_input.interaction)==null?void 0:z.surface.channel,sessionId:(P=(I=k.classification_input.interaction)==null?void 0:I.session)==null?void 0:P.id});const w={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){w["X-AdMesh-Source"]="extension";const Y=this.getExtensionSourceDomain();Y&&(w["X-AdMesh-Source-Domain"]=Y)}const g=(async()=>{const Y=await fetch(o,{method:"POST",headers:w,body:x});if(!Y.ok){const B=(await Y.json().catch(()=>({}))).detail||`HTTP ${Y.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${B}`)}const J=await Y.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})();ct.inFlightPlatformResponses.set(i,g);try{return await g}finally{ct.inFlightPlatformResponses.delete(i)}}async trackPublisherAssistantEvent(e){const o=Array.isArray(e)?{events:e}:e,s=await fetch(`${this.apiBaseUrl}/analytics/publisher-assistant/events`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),keepalive:!0});if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Failed to track publisher assistant analytics (${s.status}): ${i}`)}}fireFollowupExposure(e,o,s){this.getTracker().fireFollowupExposure(e,o,s)}async fireFollowupEngagement(e,o,s){return this.getTracker().fireFollowupEngagement(e,o,s)}};Ue(ct,"inFlightPlatformResponses",new Map);let Xt=ct;class Rn{constructor(e={}){Ue(this,"autoAddLabels");Ue(this,"fireExposurePixels");Ue(this,"labelStyle");Ue(this,"processedLinks",new Set);Ue(this,"mutationObserver",null);var o,s,i,l;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:((l=e.labelStyle)==null?void 0:l.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 l=this.getLinksToProcess(e),u=new Map(o.map(h=>{var _,d,m;return[((_=h==null?void 0:h.tracking)==null?void 0:_.click_url)||((m=(d=h==null?void 0:h.recommendation)==null?void 0:d.creative)==null?void 0:m.landing_page_url)||"",h]}).filter(([h])=>!!h)),b=new Map;o.forEach(h=>{var d,m;const _=(m=(d=h==null?void 0:h.recommendation)==null?void 0:d.creative)==null?void 0:m.landing_page_url;if(_&&typeof _=="string"){const k=_.trim().replace(/\/$/,"");b.set(k,h),b.set(`${k}/`,h)}}),l.forEach(h=>{var x,w,g,p,y,C,j,O;const _=h.getAttribute("href")||"",d=`${_}`;if(this.processedLinks.has(d))return;let m=u.get(_),k=_;if(!m){const M=_.trim().replace(/\/$/,"");m=b.get(M)||b.get(`${M}/`);const v=((x=m==null?void 0:m.tracking)==null?void 0:x.click_url)||((g=(w=m==null?void 0:m.recommendation)==null?void 0:w.creative)==null?void 0:g.landing_page_url);m&&v&&(a.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",_),h.setAttribute("href",v),k=v)}if(m){this.processedLinks.add(d),h.setAttribute("target","_blank"),h.setAttribute("rel","noopener noreferrer");const M={element:h,href:k,text:h.textContent||"",hasAdLabel:this.hasAdLabel(h),matchedRecommendation:{recommendation_id:(m==null?void 0:m.recommendation_id)||"",click_url:((p=m==null?void 0:m.tracking)==null?void 0:p.click_url)||((C=(y=m==null?void 0:m.recommendation)==null?void 0:y.creative)==null?void 0:C.landing_page_url)||"",exposure_url:(j=m==null?void 0:m.tracking)==null?void 0:j.exposure_url}};this.autoAddLabels&&!M.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",k),this.addAdLabel(h),M.hasAdLabel=!0):this.autoAddLabels?M.hasAdLabel&&a.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const v=(O=m==null?void 0:m.tracking)==null?void 0:O.exposure_url;this.fireExposurePixels&&v&&s&&M.matchedRecommendation&&s({exposureUrl:v,recommendationId:M.matchedRecommendation.recommendation_id,linkElement:h}),i.push(M)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const b=u.getAttribute("href")||"",h=`${b}`;if(this.processedLinks.has(h))return;if(this.isAdMeshLink(b)){this.processedLinks.add(h);const d={element:u,href:b,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:",b),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 m=this.convertClickUrlToExposureUrl(b);s({exposureUrl:m,recommendationId:this.extractRecommendationIdFromUrl(b),linkElement:u})}i.push(d)}});return i}hasAdLabel(e){var u,b,h;if((e.textContent||"").includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Link text contains Ad label"),!0;const s=e.querySelectorAll("sub, span");for(const _ of Array.from(s))if((u=_.textContent)!=null&&u.includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Link has Ad label as child element"),!0;let i=e.previousSibling;for(;i&&i.nodeType===Node.TEXT_NODE;){const _=i.textContent||"";if(_.trim()===""){i=i.previousSibling;continue}if(_.includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const _=i,d=_.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((b=_.textContent)!=null&&b.includes("Ad")))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",d),!0}let l=e.nextSibling;for(;l&&l.nodeType===Node.TEXT_NODE;){const _=l.textContent||"";if(_.trim()===""){l=l.nextSibling;continue}if(_.includes("Ad"))return a.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(l&&l.nodeType===Node.ELEMENT_NODE){const _=l,d=_.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((h=_.textContent)!=null&&h.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 l=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",l);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,l;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"))&&((l=u.parentNode)==null||l.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`,l=new URLSearchParams(o.search);return l.has("cpx")||l.set("cpx","0"),`${i}?${l.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 Ft(){const t=En();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 xo=({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"})]}),_r=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var k,x,w,g,p;const l=(x=(k=t.recommendation)==null?void 0:k.creative)!=null&&x.follow_up_suggestion&&((w=t.tracking)!=null&&w.followup_engagement_url)&&((g=t.tracking)!=null&&g.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=l==null?void 0:l.query,b=l==null?void 0:l.engagement_url,h=l==null?void 0:l.exposure_url,_=t.recommendation_id,d=((p=t.recommendation)==null?void 0:p.offerId)||_;if(!u||!b||!h)return a.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const m=async()=>{try{b&&_&&(a.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(b,_,s)),i&&u?(a.log(`[AdMeshFollowup] ๐ Executing query: ${u}`),await i(u)):a.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(y){a.error("[AdMeshFollowup] โ Error handling follow-up click:",y)}};return r.jsx(Jt,{productId:d,recommendationId:_||"",exposureUrl:h,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:m,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&m()},"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(xo,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},Qt=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:l,triggerExposureUrl:u=!0,followups_container_id:b,onPasteToInput:h,onDelegationConsent:_,onDelegationActivated:d,onStartDelegation:m,onExecuteQuery:k,onFollowupDetected:x,isContainerReady:w})=>{var Ee,R,ke,S;const{sdk:g,sessionId:p,apiKey:y,language:C,location:j,userId:O,model:M,messages:v,theme:$,getRecommendationResult:W,hasRecommendationResult:N,setRecommendationResult:z,activeDelegationSession:I,setActiveDelegationSession:P,hasActiveDelegationSession:Y}=Ft(),J=L=>!!L&&L.status==="generated"&&!!L.recommendation,ge=i||O,[B,se]=c.useState(null),[xe,ue]=c.useState(null),[Q,V]=c.useState(!0),[He,Ae]=c.useState(null),Ce=c.useRef(null),ie=c.useRef(!1),F=c.useRef(!1),q=c.useRef(t),K=c.useRef(e);c.useEffect(()=>{q.current=t,K.current=e},[t,e]),c.useEffect(()=>{Ce.current!==o&&(Ce.current=null,F.current=!1,se(null),ue(null))},[o]);const re=Y()&&(I==null?void 0:I.session_id)===p;c.useEffect(()=>{var D,Se,ne;if(!o||!N(o)||re)return;const L=W(o);if(!L){a.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),se(null),ue(null),Ae(null),V(!1),Ce.current=o,ie.current=!1,F.current=!0;return}let pe=((D=L.recommendation)==null?void 0:D.format)||"tail";(pe==="weave"||pe==="product_card")&&(pe="tail"),a.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:L.recommendation_id,format:(Se=L.recommendation)==null?void 0:Se.format}),se(L),ue(pe),Ae(null),V(!1),Ce.current=o,ie.current=!1,F.current=!0,(ne=q.current)==null||ne.call(q,o,L)},[W,N,re,o]),c.useEffect(()=>{var L,pe,D,Se,ne,be,_e;if(!(!l||!o)&&!re)try{const le=l,G=l.status||"unknown";if(!J(le)){if(G==="no_match"){a.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),se(null),ue(null),Ae(null),V(!1),Ce.current=o,ie.current=!1,F.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${G})`)}let De=((L=le.recommendation)==null?void 0:L.format)||"tail";(De==="weave"||De==="product_card")&&(De="tail"),se(le),ue(De),Ae(null),V(!1),Ce.current=o,ie.current=!1,F.current=!0,z(o,le),(pe=q.current)==null||pe.call(q,o,le),a.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),a.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:le.recommendation_id,format:(D=le.recommendation)==null?void 0:D.format,brandName:(ne=(Se=le.recommendation)==null?void 0:Se.creative)==null?void 0:ne.brand_name,headline:(_e=(be=le.recommendation)==null?void 0:be.creative)==null?void 0:_e.headline,hasTracking:!!le.tracking})}catch(le){const G=le instanceof Error?le:new Error(String(le));F.current=!1,a.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${G.message}`)}},[re,l,o,z]),c.useEffect(()=>{if(!o||!s||s.trim()===""){a.log("[AdMeshRecommendations] โ Validation failed - missing required parameters"),V(!1);return}if(re){a.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:p,delegationSessionId:I==null?void 0:I.delegation_session_id}),se(null),ue(null),Ae(null),V(!1),ie.current=!1;return}if(!(g!=null&&g.fetchPlatformResponse)){a.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),V(!1);return}if(F.current){a.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(Ce.current===o){a.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(ie.current){a.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}a.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var pe,D,Se,ne,be,_e,le,G,De;try{ie.current=!0,V(!0),Ae(null);const we=await g.fetchPlatformResponse({query:s.trim(),sessionId:p,messageId:o,language:C,location:j,userId:ge,model:M,...v&&v.length>0&&{messages:v}}),Pe=(we==null?void 0:we.status)||"unknown";if(!J(we)){if(Pe==="no_match"){a.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),se(null),ue(null),Ae(null),V(!1),ie.current=!1,Ce.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${Pe})`)}se(we),a.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:we.recommendation_id,format:(pe=we.recommendation)==null?void 0:pe.format,brandName:(Se=(D=we.recommendation)==null?void 0:D.creative)==null?void 0:Se.brand_name,headline:(be=(ne=we.recommendation)==null?void 0:ne.creative)==null?void 0:be.headline,hasTracking:!!we.tracking});let E=((_e=we.recommendation)==null?void 0:_e.format)||"tail";(E==="weave"||E==="product_card")&&(E="tail"),ue(E),Ce.current=o,z(o,we),a.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(le=we.recommendation)==null?void 0:le.format,selected_format:E}),V(!1),ie.current=!1,(G=q.current)==null||G.call(q,o,we)}catch(we){const Pe=we instanceof Error?we:new Error(String(we));Pe.message.includes("Failed to fetch")||Pe.message.includes("NetworkError")?a.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${Pe.message} `):a.error(`[AdMeshRecommendations] โ Error fetching recommendations: ${Pe.message} `),Ae(Pe),V(!1),ie.current=!1,(De=K.current)==null||De.call(K,Pe)}})()},[I==null?void 0:I.delegation_session_id,re,g,p,o,s,C,j,ge,M,l,z]),c.useEffect(()=>{var pe,D,Se,ne;if(!B||!x)return;const L=(D=(pe=B.recommendation)==null?void 0:pe.creative)!=null&&D.follow_up_suggestion&&((Se=B.tracking)!=null&&Se.followup_engagement_url)&&((ne=B.tracking)!=null&&ne.followup_exposure_url)?{label:B.recommendation.creative.follow_up_suggestion,query:B.recommendation.creative.follow_up_suggestion,engagement_url:B.tracking.followup_engagement_url,exposure_url:B.tracking.followup_exposure_url}:null;L&&x(L,B.recommendation_id)},[B,x]);const me=c.useCallback(async L=>{if(!g||!p)throw new Error("AdMesh SDK activation requires an initialized session");const pe=await fetch(`${g.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({session_id:p,recommendation_id:L.recommendation_id,metadata:L.metadata})});if(!pe.ok){const be=await pe.text();throw new Error(`Failed to activate delegation session: ${pe.status} ${be}`)}const D=await pe.json(),Se={...L,delegation_session_id:D.delegation_session_id||L.delegation_session_id,session_id:D.session_id||p,brand_id:D.brand_id||L.brand_id,brand_name:D.brand_name||L.brand_name,mcp_endpoint:D.mcp_endpoint,eligibility_reason:D.eligibility_reason||L.eligibility_reason,delegate_reason:D.delegate_reason||L.delegate_reason,session_goal:D.session_goal||L.session_goal,desired_outcome_type:D.desired_outcome_type||L.desired_outcome_type,required_user_inputs:D.required_user_inputs||L.required_user_inputs||[],required_consent_types:D.required_consent_types||L.required_consent_types||[],success_outcome:D.success_outcome||L.success_outcome,fallback_message:D.fallback_message||L.fallback_message,session_mode:"inline",status:D.status||"active",capabilities:D.capabilities||L.capabilities||[],allowed_data_types:D.allowed_data_types||L.allowed_data_types||[],auth_model:D.auth_model||L.auth_model,handoff_protocol:D.handoff_protocol||L.handoff_protocol,supported_actions:D.supported_actions||L.supported_actions||[],metadata:D.metadata||L.metadata},ne={delegation_session_id:D.delegation_session_id,recommendation_id:L.recommendation_id,session_id:D.session_id||p,brand_agent_id:D.brand_agent_id,brand_id:D.brand_id||L.brand_id,brand_name:D.brand_name||L.brand_name||"Brand",mcp_endpoint:D.mcp_endpoint,status:D.status||"active",activated_at:D.created_at,last_activity_at:D.updated_at,expires_at:D.expires_at||D.updated_at,eligibility_reason:D.eligibility_reason||L.eligibility_reason,delegate_reason:D.delegate_reason||L.delegate_reason,session_goal:D.session_goal||L.session_goal,desired_outcome_type:D.desired_outcome_type||L.desired_outcome_type,required_user_inputs:D.required_user_inputs||L.required_user_inputs||[],required_consent_types:D.required_consent_types||L.required_consent_types||[],success_outcome:D.success_outcome||L.success_outcome,fallback_message:D.fallback_message||L.fallback_message,capabilities:D.capabilities||L.capabilities||[],allowed_data_types:D.allowed_data_types||L.allowed_data_types||[],consent_requirements:D.consent_requirements||L.consent_requirements||[],auth_model:D.auth_model||L.auth_model,handoff_protocol:D.handoff_protocol||L.handoff_protocol,supported_actions:D.supported_actions||L.supported_actions||[],metadata:D.metadata||L.metadata};if(P(ne),await g.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:p,recommendation_id:L.recommendation_id,delegation_session_id:D.delegation_session_id,brand_name:ne.brand_name,status:D.status||"active",metadata:{brand_agent_id:D.brand_agent_id,source:"recommendation_card"}}).catch(be=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",be)}),await g.reportDelegationSessionStarted(ne,{brand_agent_id:D.brand_agent_id,brand_name:ne.brand_name}).then(be=>{be&&P(be)}).catch(be=>{a.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",be)}),d){try{await d(Se)}catch(be){a.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",be)}return}if(m)try{await m({...L.platform_response,delegation:{...L.platform_response.delegation,...Se,delegation_session_id:D.delegation_session_id,available:!0,status:D.status||"active"}})}catch(be){a.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",be)}},[y,d,m,g,p,P]);if(!o||!s||s.trim()===""||Q||He)return null;if(!B||!xe)return a.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!B,detectedFormat:xe,isLoading:Q,hasError:!!He}),null;a.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:B.recommendation_id,detectedFormat:xe,brandName:(R=(Ee=B.recommendation)==null?void 0:Ee.creative)==null?void 0:R.brand_name,headline:(S=(ke=B.recommendation)==null?void 0:ke.creative)==null?void 0:S.headline});const Me=typeof document<"u"&&b&&(w??!0)?document.getElementById(b):null;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:r.jsx(Mn,{recommendations:[B],theme:$,sessionId:p,triggerExposureUrl:u,onPasteToInput:h,onDelegationConsent:_,onDelegationActivated:me,onStartDelegation:m})}),Me&&g&&p?Vr.createPortal(r.jsx(_r,{recommendation:B,theme:$,sdk:g,sessionId:p,onExecuteQuery:k}),Me):null]})},wr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:l})=>{const{sdk:u,sessionId:b,theme:h,apiKey:_,language:d,location:m,userId:k,model:x,messages:w}=Ft(),g=c.useRef(null),[p,y]=c.useState("");return c.useEffect(()=>{o&&y(`admesh-weave-fallback-${o}`)},[o]),a.log("[WeaveFallbackRecommendations] ๐จ Component render"),c.useEffect(()=>{if(a.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:i,hasPreviousRecommendations:l&&l.length>0,previousRecommendationsCount:(l==null?void 0:l.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||!p){a.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const C=l&&l.length>0;a.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:C,count:(l==null?void 0:l.length)||0,fallback:i,messageId:o}),C?(a.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${l.length} previous recommendation(s), skipping API call`),(async()=>{var O,M,v,$,W,N,z;try{const I=l[0];if(a.log("[WeaveFallbackRecommendations] ๐ฆ Processing AIP response:",{hasAipResponse:!!I,recommendationId:(I==null?void 0:I.recommendation_id)||"",format:((O=I==null?void 0:I.recommendation)==null?void 0:O.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:((M=I==null?void 0:I.tracking)==null?void 0:M.click_url)||(($=(v=I==null?void 0:I.recommendation)==null?void 0:v.creative)==null?void 0:$.landing_page_url),format:(W=I==null?void 0:I.recommendation)==null?void 0:W.format,full_response:I}),!I){a.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:p,sessionId:b,messageId:o});return}const P=u,Y=P.getRenderer,J=P.getTracker,ge=(N=P.config)==null?void 0:N.theme;if(Y&&J){const B={sessionId:b,messageId:o,recommendations:[I]},se=Y.call(u),xe=J.call(u),ue=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await se.render({containerId:p,response:B,theme:h||ge,tracker:xe,sessionId:b,apiKey:_||((z=u==null?void 0:u.config)==null?void 0:z.apiKey),apiBaseUrl:ue,language:d,location:m,userId:k,model:x,messages:w}),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:p,sessionId:b,messageId:o})}catch(I){const P=I instanceof Error?I:new Error(String(I));a.error(`[WeaveFallbackRecommendations] โ Error rendering previous recommendations: ${P.message}`);try{await u.showRecommendations({query:s.trim(),containerId:p,sessionId:b,messageId:o})}catch{e==null||e(P)}}})()):(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:p,sessionId:b,messageId:o}),a.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(O){const M=O instanceof Error?O:new Error(String(O));a.log(`[WeaveFallbackRecommendations] โ Error: ${M.message}`),e==null||e(M)}})())},[u,b,p,t,o,s,i,e,l,h]),!i||!o||!s||s.trim()===""?null:r.jsx("div",{ref:g,id:p,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},vr=c.createContext(void 0),bo=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>r.jsx(vr.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),yo=()=>c.useContext(vr),_n=t=>{try{return new URL(t),!0}catch{return!1}},nr=t=>t&&t.trim()?t.trim():"",kt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",lt=t=>kt(t)||void 0,_o=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},wo=(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 kt(t)},vo=(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=kt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},fe={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"},ko=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:l=!0,onDelegationConsent:u,onDelegationActivated:b,onStartDelegation:h,onPasteToInput:_})=>{var ne,be,_e,le,G,De,we,Pe,E,qe,rt,ft,St,Qe,At,Z,Te,tt,Ge,gt,ot,Oe,Le,Pt,xt,Ct,Mt,jt,$t,Bt,Ut,Et,zt;if(!t||t.length===0)return a.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const d=t[0],m=((ne=d==null?void 0:d.recommendation)==null?void 0:ne.offerId)||"",k=((be=d==null?void 0:d.tracking)==null?void 0:be.exposure_url)||"",x=(d==null?void 0:d.recommendation_id)||"",w=((le=(_e=d==null?void 0:d.recommendation)==null?void 0:_e.creative)==null?void 0:le.description)||"",g=((G=d==null?void 0:d.recommendation)==null?void 0:G.disclosure)||"Sponsored",p=((we=(De=d==null?void 0:d.recommendation)==null?void 0:De.creative)==null?void 0:we.brand_name)||"",y=((E=(Pe=d==null?void 0:d.recommendation)==null?void 0:Pe.creative)==null?void 0:E.headline)||((rt=(qe=d==null?void 0:d.recommendation)==null?void 0:qe.creative)==null?void 0:rt.brand_name)||"",C=((St=(ft=d==null?void 0:d.recommendation)==null?void 0:ft.creative)==null?void 0:St.logo_url)||"",j=((Qe=d==null?void 0:d.tracking)==null?void 0:Qe.click_url)||((Z=(At=d==null?void 0:d.recommendation)==null?void 0:At.creative)==null?void 0:Z.landing_page_url)||"",O=nr((tt=(Te=d==null?void 0:d.recommendation)==null?void 0:Te.creative)==null?void 0:tt.cta_text),M=((gt=(Ge=d==null?void 0:d.recommendation)==null?void 0:Ge.creative)==null?void 0:gt.products)||[],v=M.length>1,$=v?M.slice(0,4):[],W=((ot=d==null?void 0:d.recommendation)==null?void 0:ot.format)||"tail",N=W==="bridge",z=((Oe=d==null?void 0:d.delegation)==null?void 0:Oe.brand_name)||p,I=((Le=d==null?void 0:d.delegation)==null?void 0:Le.available)===!0,P=N&&I,Y="Talk to Agent",J=!v&&!!O&&!!j;if(!p&&!y&&!w)return a.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:p,hasFirstRecommendation:!!d,recommendationId:x,recommendationKeys:d?Object.keys(d):[]}),null;let ge=p,B="";y&&y!==p&&(B=y),B&&(ge=`${p} โ ${B}`),a.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:x,productId:m,exposureUrl:k?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:j||"MISSING",clickUrlSource:(Pt=d==null?void 0:d.tracking)!=null&&Pt.click_url?"tracking.click_url":(Ct=(xt=d==null?void 0:d.recommendation)==null?void 0:xt.creative)!=null&&Ct.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:w?"present":"MISSING",brandName:p,productName:y,headlineText:ge,triggerExposureUrl:l}),a.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:x,brandName:p,productName:y,hasDescription:!!w,hasClickUrl:!!j,hasLogoUrl:!!C,recommendationFormat:W});const se=(H,ye)=>{ye&&ye.stopPropagation(),a.log(`AdMesh tail ad ${H} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:x,productId:m,clickUrl:j,source:H}).catch(()=>{a.error(`[AdMesh] Failed to track ${H} click`)})},xe=H=>{H.stopPropagation(),se("tail_ad_brand_name")},ue=H=>{H.stopPropagation(),se("tail_ad_cta")},Q=H=>{H.stopPropagation(),se("tail_ad_logo")},V=()=>{v||!j||(se("tail_ad_card"),typeof window<"u"&&window.open(j,"_blank","noopener,noreferrer"))},He=H=>{v||!j||(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),V())},[Ae,Ce]=c.useState(!1),ie=c.useRef(null);c.useEffect(()=>()=>{ie.current&&(ie.current(!1),ie.current=null)},[]);const F=H=>{var ye;(ye=ie.current)==null||ye.call(ie,H),ie.current=null,Ce(!1)},q=async()=>u?await u(d):await new Promise(H=>{ie.current=H,Ce(!0)}),K=async()=>{if(x&&i)try{const H=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",ye=await fetch(`${H}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:x,session_id:i,is_test:!1})});ye.ok||a.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",ye.statusText)}catch(H){a.error("[AdMesh Tail Ad] Error tracking delegation engagement:",H)}},re=async H=>{var bt,yt,$e,dt;if(H.preventDefault(),H.stopPropagation(),!d||!P)return;if(se("tail_ad_delegation_cta"),await K(),!await q()){a.log("[AdMesh Tail Ad] Delegation consent declined");return}const ce=d.delegation,Rt=ce!=null&&ce.available?{recommendation_id:d.recommendation_id,brand_id:lt(ce.brand_id),brand_name:lt(ce.brand_name||((yt=(bt=d.recommendation)==null?void 0:bt.creative)==null?void 0:yt.brand_name)),eligibility_reason:lt(ce.eligibility_reason),delegate_reason:lt(ce.delegate_reason),session_goal:lt(ce.session_goal),desired_outcome_type:ce.desired_outcome_type,required_user_inputs:Array.isArray(ce.required_user_inputs)?ce.required_user_inputs.filter(st=>typeof st=="string"):[],required_consent_types:Array.isArray(ce.required_consent_types)?ce.required_consent_types.filter(st=>typeof st=="string"):[],success_outcome:lt(ce.success_outcome),fallback_message:lt(ce.fallback_message),session_mode:lt(ce.session_mode),status:lt(ce.status),capabilities:ce.capabilities||[],allowed_data_types:ce.allowed_data_types||[],consent_requirements:ce.consent_requirements||[],auth_model:lt(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:d}:null;if(b&&Rt){await b(Rt);return}if(h){await h(d);return}const Xe=((dt=($e=d.recommendation)==null?void 0:$e.creative)==null?void 0:dt.follow_up_suggestion)||"";if(Xe&&_){_(Xe);return}if(Xe&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(Xe);return}},[me,Me]=c.useState(!1),Ee=p?p.charAt(0).toUpperCase():"B",R=fe.surface,ke=fe.border,S=(e==null?void 0:e.borderRadius)||((jt=(Mt=e==null?void 0:e.components)==null?void 0:Mt.card)==null?void 0:jt.borderRadius)||"8px",L="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",pe="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",D=(($t=e==null?void 0:e.shadows)==null?void 0:$t.medium)||((Ut=(Bt=e==null?void 0:e.components)==null?void 0:Bt.card)==null?void 0:Ut.boxShadow)||L,Se=((Et=e==null?void 0:e.shadows)==null?void 0:Et.large)||pe;return r.jsxs(Jt,{productId:m,recommendationId:x,exposureUrl:k,sessionId:i,triggerExposureUrl:l,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:`
|
|
25
27
|
.admesh-tail-product-scroll {
|
|
26
28
|
-ms-overflow-style: none;
|
|
27
29
|
scrollbar-width: none;
|
|
@@ -32,66 +34,81 @@
|
|
|
32
34
|
width: 0;
|
|
33
35
|
height: 0;
|
|
34
36
|
}
|
|
35
|
-
`}),
|
|
37
|
+
`}),r.jsxs("div",{className:"tail-ad-container flex flex-col gap-3 sm:flex-row",role:!v&&j?"link":void 0,tabIndex:!v&&j?0:void 0,style:{...(zt=e==null?void 0:e.components)==null?void 0:zt.card,backgroundColor:R,borderRadius:S,padding:"16px",boxShadow:D,border:`1px solid ${ke}`,color:fe.text,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",cursor:!v&&j?"pointer":void 0},onClick:V,onKeyDown:He,onMouseEnter:H=>{H.currentTarget.style.boxShadow=Se,H.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:H=>{H.currentTarget.style.boxShadow=D,H.currentTarget.style.transform="translateY(0)"},children:[C&&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:!me&&_n(C)?r.jsx("a",{href:j||"#",target:j?"_blank":void 0,rel:j?"noopener noreferrer":void 0,onClick:j?Q:void 0,className:"block",style:{cursor:j?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:r.jsx("img",{src:C,alt:`${p} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{Me(!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:fe.logoFallbackBg,color:fe.logoFallbackText,fontSize:"18px"},children:Ee})}),r.jsxs("div",{className:"flex-1",style:{width:"100%",minWidth:0},children:[ge&&!v&&r.jsx("div",{className:"mb-2",children:r.jsx("h3",{className:"font-semibold text-base",style:{fontSize:"14px",lineHeight:1.35,color:fe.text},children:j&&p?r.jsxs(r.Fragment,{children:[r.jsx("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-semibold",style:{color:fe.link,textDecoration:"underline",textDecorationColor:fe.link,textUnderlineOffset:"2px"},onClick:xe,children:p}),B&&` โ ${B}`]}):ge})}),w&&!v&&r.jsx("p",{className:"text-sm mb-3 leading-relaxed",style:{fontSize:"13px",lineHeight:1.45,color:fe.textSecondary},children:w}),v&&$.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:$.map(H=>{const ye=kt(H.product_name)||"Product",ce=kt(H.product_link)||kt(H.product_url)||j||"#",Rt=_o(kt(H.product_description),10),Xe=wo(H.product_price,H.product_currency),bt=vo(H.product_discount,H.product_discount_type,H.product_currency),yt=kt(H.product_image_url),$e=C&&_n(C)?C:"",dt=yt&&_n(yt)?yt:$e,st=nr(H.product_cta_label),Ht=ce!=="#";return r.jsx("a",{href:ce,target:Ht?"_blank":void 0,rel:Ht?"noopener noreferrer":void 0,onClick:qt=>se(`tail_ad_product_${H.product_id||"item"}`,qt),className:"block",style:{border:`1px solid ${ke}`,borderRadius:"8px",padding:"10px",backgroundColor:fe.surfaceMuted,textDecoration:"none",color:fe.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:[dt?r.jsx("img",{src:dt,alt:ye,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:fe.productImageFallbackBg,color:fe.textSecondary,fontSize:"12px"},children:ye.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:fe.text,marginBottom:"4px"},children:ye}),Rt&&r.jsx("p",{className:"text-xs",style:{fontSize:"12px",lineHeight:1.3,color:fe.textSecondary,marginBottom:"6px"},children:Rt}),(Xe||bt)&&r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{marginBottom:st?"6px":0},children:[Xe&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{style:{fontSize:"10px",color:fe.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Price"}),r.jsx("span",{className:"font-semibold",style:{fontSize:"13px",color:fe.text},children:Xe})]}),bt&&r.jsx("span",{className:"text-xs",style:{fontSize:"11px",color:fe.successText,backgroundColor:fe.successBg,borderRadius:"999px",padding:"2px 8px",fontWeight:600},children:bt})]}),st&&r.jsx("span",{className:"font-medium",style:{fontSize:"12px",color:fe.link,textDecoration:"underline",textUnderlineOffset:"2px"},children:st})]})]})},H.product_id||`${x}-${ye}`)})})})}),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:[v&&p&&r.jsx("span",{className:"text-sm",style:{fontSize:"13px",color:fe.textSecondary,fontWeight:400},children:p}),P?r.jsx("button",{type:"button",onClick:re,className:"underline transition-colors duration-200 font-medium text-sm",style:{color:fe.link,textDecoration:"underline",textDecorationColor:fe.link,textUnderlineOffset:"2px",fontSize:"13px",background:"none",border:"none",padding:0,cursor:"pointer"},children:Y}):null,J&&r.jsx("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-medium text-sm",style:{color:fe.link,textDecoration:"underline",textDecorationColor:fe.link,textUnderlineOffset:"2px",fontSize:"13px"},onClick:ue,children:O}),v&&M.length>$.length&&r.jsxs("span",{className:"text-xs",style:{fontSize:"11px",color:fe.textMuted},children:["+",M.length-$.length," more"]})]}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsx("p",{className:"text-xs",style:{fontSize:"11px",color:fe.textMuted},children:g})})]}),Ae?r.jsxs("div",{style:{marginTop:"10px",border:`1px solid ${ke}`,borderRadius:"12px",backgroundColor:fe.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:fe.link},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"14px",lineHeight:1.4,color:fe.text,fontWeight:600},children:["Allow ",z||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:fe.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:H=>{H.preventDefault(),H.stopPropagation(),F(!1)},style:{borderRadius:"10px",border:`1px solid ${ke}`,background:R,color:fe.text,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:H=>{H.preventDefault(),H.stopPropagation(),F(!0)},style:{borderRadius:"10px",border:"none",background:"#2563eb",color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})]})},kr=({recommendationId:t,admeshLink:e,productId:o,children:s,trackingData:i,className:l,style:u})=>{const b=c.useRef(null);c.useEffect(()=>{if(!b.current)return;b.current.querySelectorAll("a").forEach(d=>{(!d.hasAttribute("target")||d.getAttribute("target")!=="_blank")&&(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer"))})},[s]);const h=c.useCallback(_=>{const m=_.target.closest("a");m?((!m.href||m.href==="#"||m.href==="")&&e&&(m.href=e),(!m.hasAttribute("target")||m.getAttribute("target")!=="_blank")&&(m.setAttribute("target","_blank"),m.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):a.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return r.jsx("div",{ref:b,className:l,onClick:h,style:{cursor:"pointer",...u},children:s})};kr.displayName="AdMeshLinkTracker";function So(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var wn={exports:{}};/*!
|
|
36
38
|
Copyright (c) 2018 Jed Watson.
|
|
37
39
|
Licensed under the MIT License (MIT), see
|
|
38
40
|
http://jedwatson.github.io/classnames
|
|
39
|
-
*/var
|
|
41
|
+
*/var rr;function Ao(){return rr||(rr=1,(function(t){(function(){var e={}.hasOwnProperty;function o(){for(var l="",u=0;u<arguments.length;u++){var b=arguments[u];b&&(l=i(l,s(b)))}return l}function s(l){if(typeof l=="string"||typeof l=="number")return l;if(typeof l!="object")return"";if(Array.isArray(l))return o.apply(null,l);if(l.toString!==Object.prototype.toString&&!l.toString.toString().includes("[native code]"))return l.toString();var u="";for(var b in l)e.call(l,b)&&l[b]&&(u=i(u,b));return u}function i(l,u){return u?l?l+" "+u:l+u:l}t.exports?(o.default=o,t.exports=o):window.classNames=o})()})(wn)),wn.exports}var Co=Ao();const Mo=So(Co),jo={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Eo={"Top Match":"โ
","Free Tier":"โ","AI Powered":"โ",Popular:"โฒ",New:"โ","Trial Available":"โ"},Sr=({type:t,variant:e,size:o="md",className:s,style:i})=>{const l=e||jo[t]||"secondary",u=Eo[t],b=Mo("admesh-component","admesh-badge",`admesh-badge--${l}`,`admesh-badge--${o}`,s);return r.jsxs("span",{className:b,style:i,children:[u&&r.jsx("span",{className:"admesh-badge__icon",children:u}),r.jsx("span",{className:"admesh-badge__text",children:t})]})};Sr.displayName="AdMeshBadge";/**
|
|
40
42
|
* @license lucide-react v0.563.0 - ISC
|
|
41
43
|
*
|
|
42
44
|
* This source code is licensed under the ISC license.
|
|
43
45
|
* See the LICENSE file in the root directory of this source tree.
|
|
44
|
-
*/const
|
|
46
|
+
*/const Ar=(...t)=>t.filter((e,o,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===o).join(" ").trim();/**
|
|
45
47
|
* @license lucide-react v0.563.0 - ISC
|
|
46
48
|
*
|
|
47
49
|
* This source code is licensed under the ISC license.
|
|
48
50
|
* See the LICENSE file in the root directory of this source tree.
|
|
49
|
-
*/const
|
|
51
|
+
*/const Ro=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
|
|
50
52
|
* @license lucide-react v0.563.0 - ISC
|
|
51
53
|
*
|
|
52
54
|
* This source code is licensed under the ISC license.
|
|
53
55
|
* See the LICENSE file in the root directory of this source tree.
|
|
54
|
-
*/const
|
|
56
|
+
*/const To=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,o,s)=>s?s.toUpperCase():o.toLowerCase());/**
|
|
55
57
|
* @license lucide-react v0.563.0 - ISC
|
|
56
58
|
*
|
|
57
59
|
* This source code is licensed under the ISC license.
|
|
58
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
59
|
-
*/const
|
|
61
|
+
*/const or=t=>{const e=To(t);return e.charAt(0).toUpperCase()+e.slice(1)};/**
|
|
60
62
|
* @license lucide-react v0.563.0 - ISC
|
|
61
63
|
*
|
|
62
64
|
* This source code is licensed under the ISC license.
|
|
63
65
|
* See the LICENSE file in the root directory of this source tree.
|
|
64
|
-
*/var
|
|
66
|
+
*/var Io={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"};/**
|
|
65
67
|
* @license lucide-react v0.563.0 - ISC
|
|
66
68
|
*
|
|
67
69
|
* This source code is licensed under the ISC license.
|
|
68
70
|
* See the LICENSE file in the root directory of this source tree.
|
|
69
|
-
*/const
|
|
71
|
+
*/const Do=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
|
|
70
72
|
* @license lucide-react v0.563.0 - ISC
|
|
71
73
|
*
|
|
72
74
|
* This source code is licensed under the ISC license.
|
|
73
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
74
|
-
*/const
|
|
76
|
+
*/const Po=c.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:o=2,absoluteStrokeWidth:s,className:i="",children:l,iconNode:u,...b},h)=>c.createElement("svg",{ref:h,...Io,width:e,height:e,stroke:t,strokeWidth:s?Number(o)*24/Number(e):o,className:Ar("lucide",i),...!l&&!Do(b)&&{"aria-hidden":"true"},...b},[...u.map(([_,d])=>c.createElement(_,d)),...Array.isArray(l)?l:[l]]));/**
|
|
75
77
|
* @license lucide-react v0.563.0 - ISC
|
|
76
78
|
*
|
|
77
79
|
* This source code is licensed under the ISC license.
|
|
78
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
79
|
-
*/const
|
|
81
|
+
*/const Wt=(t,e)=>{const o=c.forwardRef(({className:s,...i},l)=>c.createElement(Po,{ref:l,iconNode:e,className:Ar(`lucide-${Ro(or(t))}`,`lucide-${t}`,s),...i}));return o.displayName=or(t),o};/**
|
|
80
82
|
* @license lucide-react v0.563.0 - ISC
|
|
81
83
|
*
|
|
82
84
|
* This source code is licensed under the ISC license.
|
|
83
85
|
* See the LICENSE file in the root directory of this source tree.
|
|
84
|
-
*/const
|
|
86
|
+
*/const $o=[["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"}]],zo=Wt("maximize-2",$o);/**
|
|
85
87
|
* @license lucide-react v0.563.0 - ISC
|
|
86
88
|
*
|
|
87
89
|
* This source code is licensed under the ISC license.
|
|
88
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
89
|
-
*/const
|
|
91
|
+
*/const Lo=[["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"}]],No=Wt("minimize-2",Lo);/**
|
|
90
92
|
* @license lucide-react v0.563.0 - ISC
|
|
91
93
|
*
|
|
92
94
|
* This source code is licensed under the ISC license.
|
|
93
95
|
* See the LICENSE file in the root directory of this source tree.
|
|
94
|
-
*/const
|
|
96
|
+
*/const Fo=[["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"}]],sr=Wt("send",Fo);/**
|
|
97
|
+
* @license lucide-react v0.563.0 - ISC
|
|
98
|
+
*
|
|
99
|
+
* This source code is licensed under the ISC license.
|
|
100
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
+
*/const Wo=[["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"}]],ir=Wt("thumbs-down",Wo);/**
|
|
102
|
+
* @license lucide-react v0.563.0 - ISC
|
|
103
|
+
*
|
|
104
|
+
* This source code is licensed under the ISC license.
|
|
105
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
+
*/const Bo=[["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"}]],ar=Wt("thumbs-up",Bo);/**
|
|
107
|
+
* @license lucide-react v0.563.0 - ISC
|
|
108
|
+
*
|
|
109
|
+
* This source code is licensed under the ISC license.
|
|
110
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
+
*/const Uo=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],vn=Wt("x",Uo),kn="admesh-ui-sdk-styles",Sn="admesh-ui-sdk-reset",Ho=`
|
|
95
112
|
/* AdMesh UI SDK - CSS Reset & Normalization */
|
|
96
113
|
.admesh-component,
|
|
97
114
|
.admesh-component * {
|
|
@@ -180,7 +197,7 @@
|
|
|
180
197
|
.admesh-component[data-admesh-theme="light"] {
|
|
181
198
|
color-scheme: light;
|
|
182
199
|
}
|
|
183
|
-
`,
|
|
200
|
+
`,qo=`
|
|
184
201
|
/* AdMesh Core Component Styles */
|
|
185
202
|
|
|
186
203
|
.admesh-component {
|
|
@@ -391,7 +408,7 @@
|
|
|
391
408
|
font-size: 0.875rem;
|
|
392
409
|
}
|
|
393
410
|
}
|
|
394
|
-
|
|
411
|
+
`,Oo=()=>{if(!(typeof document>"u")&&!(document.getElementById(Sn)&&document.getElementById(kn))){if(!document.getElementById(Sn)){const t=document.createElement("style");t.id=Sn,t.textContent=Ho,document.head.appendChild(t)}if(!document.getElementById(kn)){const t=document.createElement("style");t.id=kn,t.textContent=qo,document.head.appendChild(t)}}},Vo=`
|
|
395
412
|
/* AdMesh UI SDK - Complete Self-Contained Styles */
|
|
396
413
|
|
|
397
414
|
/* CSS Reset for AdMesh components */
|
|
@@ -1059,7 +1076,15 @@
|
|
|
1059
1076
|
.admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
1060
1077
|
.admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
|
|
1061
1078
|
}
|
|
1062
|
-
`;let
|
|
1063
|
-
|
|
1064
|
-
`);for(const se of Te)if(se.startsWith("data: ")){const Pe=se.slice(6);if(Pe.trim()==="[DONE]")return ve&&Z("turn_completed",{source:"publisher_assistant",recommendation_id:ve.recommendation_id}).catch(ie=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",ie)}),{text:ye,source_links:Ue,related_items:Ve,followup_suggestions:Re,used_capability:Ne,response_time_ms:Fe};try{const ie=JSON.parse(Pe);switch(ie.type){case"content":{const gt=ie.content||"";ye+=gt,v==null||v(gt);break}case"final":{ye=ie.reply||ye,Ue=Array.isArray(ie.source_links)?ie.source_links:void 0,Ve=Array.isArray(ie.related_items)?ie.related_items:void 0,Re=Array.isArray(ie.followup_suggestions)?ie.followup_suggestions:void 0,Ne=typeof ie.used_capability=="string"?ie.used_capability:Ne,Fe=typeof ie.response_time_ms=="number"?ie.response_time_ms:Fe;break}case"followup_suggestions":{Re=Array.isArray(ie.followup_suggestions)?ie.followup_suggestions:Re;break}case"error":throw new Error(ie.message||"Unknown streaming error");case"session_start":console.log("Session started:",ie.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",Pe);continue}}}}catch(at){throw console.error("Stream processing error:",at),at}finally{pe.releaseLock()}return{text:ye,source_links:Ue,related_items:Ve,followup_suggestions:Re,used_capability:Ne,response_time_ms:Fe}})()}catch($){return console.error("Error calling assistant API:",$),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:$ instanceof Error?$.message:"request_failed"}}},[V,H,ne,ve,Z]),Ge=u.useCallback(async r=>{var ke,ye,Ue,Ve,Re,Ne,Fe,Ht,at;if(!r.trim()||w)return;const v=typeof performance<"u"?performance.now():Date.now(),I=r.trim(),$=Date.now().toString();be(null);const pe={id:$,role:"user",content:I,timestamp:new Date};if(we("query_submitted",{message_id:$,query:I}),Ae(ge=>[...ge,pe]),xe(""),oe(!0),x==="default"&&F){try{const ge=(Date.now()+1).toString(),he={id:ge,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:null};Me.current&&(fe(Pe=>new Set([...Pe,ge])),Me.current=!1),Ae(Pe=>[...Pe,he]);const Te=await F(I,{sponsoredSuggestion:Ie.current}),se=Te.recommendation||((ke=Ie.current)==null?void 0:ke.recommendation)||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:r,hasResponseRecommendation:!!Te.recommendation,hasSponsoredSuggestionRecommendation:!!((ye=Ie.current)!=null&&ye.recommendation),finalRecommendationId:se==null?void 0:se.recommendation_id}),Ae(Pe=>Pe.map(ie=>ie.id===ge?{...ie,content:Te.answer,sourceLinks:Te.source_links,relatedItems:Te.related_items,initialRecommendation:se}:ie)),yt(I,Te.answer,Te.source_links,Te.related_items,se,Te.followup_suggestions),we("answer_completed",{message_id:ge,query:I,recommendation_id:se==null?void 0:se.recommendation_id,brand_name:(Ve=(Ue=se==null?void 0:se.recommendation)==null?void 0:Ue.creative)==null?void 0:Ve.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-v,status:"completed",metadata:{variant:x,source:"query_handler"}}),Ie.current=null}catch(ge){console.error("Error sending message:",ge);const he=ge instanceof Error?ge.message:"Unknown error occurred";be(he);const Te={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Ae(se=>[...se,Te]),we("answer_failed",{query:I,status:he,latency_ms:(typeof performance<"u"?performance.now():Date.now())-v,metadata:{variant:x,source:"query_handler"}}),Ie.current=null}finally{oe(!1)}return}if(!V){setTimeout(()=>{const ge={id:(Date.now()+1).toString(),role:"assistant",content:"I'm a demo assistant. The SDK is not properly configured, but I can still help! Try clicking on the suggested questions above, or check your AdMesh API key configuration.",timestamp:new Date,recommendations:[],userQuery:r};Ae(he=>[...he,ge]),oe(!1)},1e3);return}try{const ge=(Date.now()+1).toString(),he=((Re=Ie.current)==null?void 0:Re.recommendation)||null,Te={id:ge,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:he};Me.current&&(fe(Pe=>new Set([...Pe,ge])),Me.current=!1),Ae(Pe=>[...Pe,Te]);const se=await Mt(I,Pe=>{Ae(ie=>ie.map(gt=>gt.id===ge?{...gt,content:gt.content+Pe}:gt))});Ae(Pe=>Pe.map(ie=>ie.id===ge?{...ie,content:se.text,sourceLinks:se.source_links,relatedItems:se.related_items,initialRecommendation:ie.initialRecommendation||he}:ie)),yt(I,se.text,se.source_links,se.related_items,he,se.followup_suggestions),se.error?we("answer_failed",{message_id:ge,query:I,recommendation_id:he==null?void 0:he.recommendation_id,brand_name:(Fe=(Ne=he==null?void 0:he.recommendation)==null?void 0:Ne.creative)==null?void 0:Fe.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-v,status:se.error,metadata:{variant:x,source:"api_chat_assistant"}}):we("answer_completed",{message_id:ge,query:I,recommendation_id:he==null?void 0:he.recommendation_id,brand_name:(at=(Ht=he==null?void 0:he.recommendation)==null?void 0:Ht.creative)==null?void 0:at.brand_name,used_capability:se.used_capability,latency_ms:typeof se.response_time_ms=="number"?se.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-v,status:"completed",metadata:{variant:x,source:"api_chat_assistant"}}),Ie.current=null}catch(ge){console.error("Error sending message:",ge);const he=ge instanceof Error?ge.message:"Unknown error occurred";be(he);const Te={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Ae(se=>[...se,Te]),we("answer_failed",{query:I,latency_ms:(typeof performance<"u"?performance.now():Date.now())-v,status:he,metadata:{variant:x,source:"api_chat_assistant"}}),Ie.current=null}finally{oe(!1)}},[w,Mt,F,yt,V,we,x]),rt=Be,_t=rt.some(r=>r==null?void 0:r.is_sponsored),wt=rt.filter(r=>!(r&&typeof r.id=="string")?!1:L?_t:!0),je=Qt(wt),vt=u.useCallback(async r=>{var I,$,pe,ke,ye,Ue,Ve;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:r.text,is_sponsored:r.is_sponsored,hasRecommendation:!!r.recommendation,recommendationId:((I=r.recommendation)==null?void 0:I.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((pe=($=r.recommendation)==null?void 0:$.tracking)!=null&&pe.followup_engagement_url),sessionId:H}),Me.current=r.is_sponsored||!1,Ie.current=r.is_sponsored?r:null;const v=je.findIndex(Re=>Re.id===r.id);we("suggestion_clicked",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:v>=0?v:void 0,is_sponsored:r.is_sponsored,recommendation_id:(ke=r.recommendation)==null?void 0:ke.recommendation_id,brand_name:(Ve=(Ue=(ye=r.recommendation)==null?void 0:ye.recommendation)==null?void 0:Ue.creative)==null?void 0:Ve.brand_name,query:r.text}),Ge(r.text),r.is_sponsored&&r.recommendation&&V?setTimeout(async()=>{var Re;try{const Ne=(Re=r.recommendation.tracking)==null?void 0:Re.followup_engagement_url,Fe=r.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:Ne,recommendationId:Fe,sessionId:H}),Ne&&Fe&&H?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await V.fireFollowupEngagement(Ne,Fe,H),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!Ne,hasRecommendationId:!!Fe,hasSessionId:!!H})}catch(Ne){console.error("[AdMeshIntentAssistant] โ Error firing sponsored suggestion engagement:",Ne)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[Ge,je,V,H,we]),q=Gr[g],De=Kr[l];u.useEffect(()=>{je.forEach((r,v)=>{var $,pe,ke,ye;const I=`${r.id}:${v}:${r.is_sponsored?"s":"o"}`;dt.current.has(I)||(dt.current.add(I),we("suggestion_impression",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:v,is_sponsored:r.is_sponsored,recommendation_id:($=r.recommendation)==null?void 0:$.recommendation_id,brand_name:(ye=(ke=(pe=r.recommendation)==null?void 0:pe.recommendation)==null?void 0:ke.creative)==null?void 0:ye.brand_name}))}),V&&H&&je.forEach(r=>{var v;if(r.is_sponsored&&r.recommendation){const I=(v=r.recommendation.tracking)==null?void 0:v.followup_exposure_url,$=r.recommendation.recommendation_id;I&&$?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion exposure:",{exposureUrl:I,recommendationId:$,suggestionText:r.text,sessionId:H}),(async()=>{try{await V.fireFollowupExposure(I,$,H),console.log("[AdMeshIntentAssistant] โ
Exposure tracking fired successfully for:",$)}catch(pe){console.error("[AdMeshIntentAssistant] โ Error firing sponsored suggestion exposure:",pe)}})()):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!I,hasRecommendationId:!!$,suggestionText:r.text})}})},[je,V,H,we]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:rt.length,safeSuggestions:wt.length,isAnalyzingIntent:R,hasIntentError:!!U,onlyShowWhenSponsored:L,hasSponsoredSuggestions:_t,sponsoredCount:rt.filter(r=>r==null?void 0:r.is_sponsored).length,nonSponsoredCount:rt.filter(r=>r&&!(r!=null&&r.is_sponsored)).length,modalShouldAppear:L?_t:!0,suggestions:rt.map(r=>{var v,I,$;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((v=r==null?void 0:r.recommendation)==null?void 0:v.recommendation_id)||void 0,hasFollowupEngagementUrl:!!(($=(I=r==null?void 0:r.recommendation)==null?void 0:I.tracking)!=null&&$.followup_engagement_url)}}),renderedSuggestions:je.map(r=>{var v,I,$;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((v=r==null?void 0:r.recommendation)==null?void 0:v.recommendation_id)||void 0,hasFollowupEngagementUrl:!!(($=(I=r==null?void 0:r.recommendation)==null?void 0:I.tracking)!=null&&$.followup_engagement_url)}})});const te=r=>r===void 0?void 0:typeof r=="number"?`${r}px`:r,X={base:`${16*p}px`,sm:`${14*p}px`,xs:`${12*p}px`},He=B||"AI-generated responses may contain errors. Please verify important information independently.",ct=["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..."],Oe=u.useCallback(()=>{const r=tt.current;if(!r)return;const v=Math.max(0,r.scrollWidth-r.clientWidth);ee(r.scrollLeft>4),Qe(r.scrollLeft<v-4)},[]);u.useEffect(()=>(Oe(),window.addEventListener("resize",Oe),()=>window.removeEventListener("resize",Oe)),[Oe,je.length]);const ft=u.useCallback(r=>{const v=tt.current;v&&v.scrollBy({left:r==="left"?-Math.max(160,Math.floor(v.clientWidth*.75)):Math.max(160,Math.floor(v.clientWidth*.75)),behavior:"smooth"})},[]),Q=(r,v)=>{if(!r||!r.startsWith("#"))return`rgba(15, 23, 42, ${v})`;const I=r.slice(1),$=I.length===3?I.split("").map(Ue=>`${Ue}${Ue}`).join(""):I;if($.length!==6)return r;const pe=parseInt($.slice(0,2),16),ke=parseInt($.slice(2,4),16),ye=parseInt($.slice(4,6),16);return`rgba(${pe}, ${ke}, ${ye}, ${v})`},J=M.primaryColor||"#3F037F";M.surfaceColor,M.backgroundColor;const kt=M.borderColor||"#e5e7eb",ot=M.textColor||"#111827",Fn=M.textSecondaryColor||"#6b7280";Q(J,.12);const $t=Q(J,.24);Q(J,.38);const zn=Q(J,.12),Ln=b?"min(960px, calc(100vw - 24px))":i==="inline"?"100%":"min(420px, calc(100vw - 32px))",$n=b?"min(78vh, 760px)":"auto",Wn=`linear-gradient(180deg, ${Q(J,.04)} 0%, ${Q(J,.08)} 100%)`,st=J,Pt=Fn,nn=E||"Publisher Assistant",Et=R&&je.length===0&&Se.length===0,Wt="#f7f8fc",Bt="linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(248,250,252,0.98) 100%)",it="rgba(15, 23, 42, 0.08)",rn="rgba(15, 23, 42, 0.12)",on="0 24px 60px rgba(15, 23, 42, 0.16)",Ut="#667085",sn="#98a2b3",Bn=st,an="#ffffff",dn="0 8px 24px rgba(15, 23, 42, 0.08)",ln="rgba(15, 23, 42, 0.18)";function cn(r){return ve?n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:r==="default"?"10px 12px":"8px 10px",borderRadius:r==="default"?"14px":"12px",border:`1px solid ${$t}`,background:Q("#ffffff",.9),marginBottom:"4px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{color:st,fontSize:X.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),n.jsxs("div",{style:{color:ot,fontSize:X.sm,fontWeight:600,lineHeight:1.3},children:[ve.brand_name," agent is active"]})]}),n.jsx("button",{type:"button",onClick:()=>{me("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${$t}`,borderRadius:999,background:Q("#ffffff",.92),color:st,padding:"7px 12px",fontSize:X.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function mn(r){return n.jsxs("div",{style:{display:"flex",alignItems:r==="default"?"center":"flex-start",justifyContent:"space-between",gap:"12px",flexWrap:"wrap",paddingTop:r==="default"?"2px":"8px",borderTop:r==="default"?`1px solid ${it}`:"none",marginTop:r==="default"?"4px":0},children:[n.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",color:sn,fontSize:"11px",fontWeight:700,letterSpacing:"0.01em"},children:n.jsxs("span",{children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]})}),n.jsx("div",{style:{color:sn,fontSize:"11px",lineHeight:1.45,maxWidth:r==="default"?"68%":"100%",textAlign:r==="default"?"right":"left"},children:He})]})}function qt(r){const v=r==="publisher"?[180,220,196]:["100%","82%","68%"];return r==="publisher"?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Q(J,.1),flexShrink:0}}),n.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:v.map((I,$)=>n.jsx("div",{style:{width:I,maxWidth:"100%",height:40,borderRadius:999,background:`linear-gradient(90deg, ${Q(J,.08)} 0%, ${Q(J,.18)} 50%, ${Q(J,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:`0 8px 22px ${Q(J,.08)}`,flexShrink:0}},`suggestion-skeleton-${$}`))}),n.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Q(J,.1),flexShrink:0}})]}):n.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:r==="publisher"?"10px":"12px"},children:v.map((I,$)=>n.jsx("div",{style:{width:I,maxWidth:"100%",height:r==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${Q(J,.08)} 0%, ${Q(J,.18)} 50%, ${Q(J,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:r==="publisher"?`0 8px 22px ${Q(J,.08)}`:"none"}},`suggestion-skeleton-${$}`))})}function Un(){return w?null:Et?qt("publisher"):je.length?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx("button",{type:"button",onClick:()=>ft("left"),disabled:!nt,"aria-label":"Scroll suggestions left",style:{width:28,height:28,borderRadius:999,border:`1px solid ${Q(kt,.8)}`,background:Q("#ffffff",.9),color:"#6b7280",cursor:nt?"pointer":"default",opacity:nt?1:.55},children:"โน"}),n.jsx("div",{ref:tt,onScroll:Oe,style:{display:"flex",gap:"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:je.slice(0,K).map(r=>n.jsxs("button",{onClick:()=>{x==="default"&&(re(!0),i==="floating"&&Xe(!0)),vt(r)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:"8px",whiteSpace:"nowrap",borderRadius:999,border:r.is_sponsored?`1px solid ${Q(J,.18)}`:`1px solid ${Q(kt,.85)}`,background:r.is_sponsored?J:Q("#ffffff",.94),color:r.is_sponsored?"#ffffff":ot,padding:"8px 14px",fontSize:"13px",fontWeight:500,boxShadow:r.is_sponsored?`0 8px 18px ${Q(J,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[n.jsx("span",{children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},r.id))}),n.jsx("button",{type:"button",onClick:()=>ft("right"),disabled:!_e,"aria-label":"Scroll suggestions right",style:{width:28,height:28,borderRadius:999,border:`1px solid ${Q(kt,.8)}`,background:Q("#ffffff",.9),color:"#6b7280",cursor:_e?"pointer":"default",opacity:_e?1:.55},children:"โบ"})]}):null}function qn(r){var v,I;return(v=r.relatedItems)!=null&&v.length||!((I=r.sourceLinks)!=null&&I.length)?null:n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:r.sourceLinks.map($=>n.jsx("a",{href:$.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{we("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:$.title,source_url:$.url}})},style:{color:st,fontSize:X.xs,textDecoration:"none",borderBottom:`1px solid ${Q(J,.18)}`},children:$.title||$.url},`${r.id}-${$.url}`))})}function Hn(r){var v;return(v=r.relatedItems)!=null&&v.length?n.jsxs("div",{style:{marginTop:"14px"},children:[n.jsx("div",{style:{fontSize:X.xs,fontWeight:700,color:"#4b5563",marginBottom:"8px"},children:"Related"}),n.jsx("div",{style:{display:"flex",gap:"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px"},children:r.relatedItems.slice(0,4).map(I=>n.jsxs("a",{href:I.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{we("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:I.title,source_url:I.url,source_publisher:I.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:"10px",padding:"14px",borderRadius:"14px",textDecoration:"none",color:ot,border:`1px solid ${Q(J,.18)}`,background:"#ffffff",boxShadow:"0 10px 24px rgba(15, 23, 42, 0.08)",minWidth:"250px",maxWidth:"250px",flexShrink:0},children:[n.jsx("div",{style:{fontSize:"18px",fontWeight:650,lineHeight:1.35,color:J},children:I.title||I.url}),I.publisher&&n.jsx("div",{style:{fontSize:"15px",color:"#6b7280",lineHeight:1.4},children:I.publisher})]},`${r.id}-${I.url}`))})]}):null}function On(){return n.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:b?"16px 16px 8px":0},children:[Se.map(r=>n.jsx("div",{style:{marginBottom:"12px",textAlign:r.role==="user"?"right":"left"},children:(()=>{const I=!!r.content.trim()||!w;return n.jsx(n.Fragment,{children:n.jsxs("div",{style:{display:r.role==="assistant"?"block":"inline-block",width:r.role==="assistant"?"100%":void 0,maxWidth:r.role==="assistant"?"100%":"76%",padding:r.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:r.role==="assistant"?0:"18px",background:r.role==="user"?st:"transparent",color:r.role==="user"?"#ffffff":ot,boxShadow:"none",border:"none",fontSize:r.role==="assistant"?"16.25px":"13px",lineHeight:r.role==="assistant"?1.62:1.4},children:[r.role==="assistant"?r.content.trim()?n.jsx(Yt,{content:r.content,theme:{...M,textColor:ot},fontSize:"16.25px"}):w?n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"10px",color:Pt,fontSize:X.sm},children:[n.jsx("span",{style:{width:9,height:9,borderRadius:999,background:st,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${Q(J,.28)}`,flexShrink:0}}),n.jsx("span",{children:ct[ue]})]}):null:n.jsx("p",{style:{margin:0},children:r.content}),r.role==="assistant"&&qn(r),r.role==="assistant"&&Hn(r),r.role==="assistant"&&I&&We.has(r.id)&&r.initialRecommendation&&n.jsx("div",{style:{marginTop:"14px"},children:n.jsx(jt,{messageId:r.id,query:r.userQuery,initialRecommendation:r.initialRecommendation,triggerExposureUrl:!1,onFollowupDetected:ht,onRecommendationsShown:($,pe)=>{pt($,pe,r.userQuery)},onError:$=>{console.error("[AdMeshIntentAssistant] Recommendation error:",$)}})}),r.role==="assistant"&&I&&!We.has(r.id)&&(r.initialRecommendation||Ke)&&n.jsx("div",{style:{marginTop:"14px"},children:n.jsx(jt,{messageId:r.id,query:r.userQuery,initialRecommendation:r.initialRecommendation||void 0,onFollowupDetected:ht,onRecommendationsShown:($,pe)=>{pt($,pe,r.userQuery)},onError:$=>{console.error("[AdMeshIntentAssistant] Recommendation error:",$)}})})]})})})()},r.id)),S&&n.jsx("div",{style:{color:Pt,fontSize:X.sm},children:"Connection issue. Please try again."}),n.jsx("div",{ref:Ye})]})}if(x==="default"){const r=n.jsxs("div",{style:{width:Ln,maxWidth:"100%",background:b?Wt:Wn,borderRadius:b?"18px":"20px",padding:b?0:"12px",boxShadow:b?on:"none",border:b?`1px solid ${rn}`:"none",overflow:"hidden"},children:[b&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 18px",background:Bt,color:ot,borderBottom:`1px solid ${it}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"14px",background:Q(J,.08),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:st},children:(a||"AA").slice(0,2).toUpperCase()}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"20px",fontWeight:700,lineHeight:1.1,letterSpacing:"-0.02em"},children:a}),n.jsx("div",{style:{fontSize:"12px",color:Ut,marginTop:"2px"},children:nn})]})]}),n.jsx("button",{type:"button",onClick:()=>re(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"12px",border:`1px solid ${it}`,background:"#ffffff",color:Ut,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx("span",{style:{fontSize:"18px",lineHeight:1,fontWeight:700,transform:"translateY(-1px)"},children:"-"})})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",minHeight:0,padding:b?"18px":"14px",background:b?Wt:Q("#ffffff",.16),height:b?$n:"auto"},children:[cn("default"),b&&On(),Un(),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",borderRadius:"16px",background:an,padding:"8px 8px 8px 14px",boxShadow:b?dn:`0 8px 22px ${zn}`,border:`1px solid ${b?it:$t}`},children:[n.jsx("input",{type:"text",value:ce,onChange:v=>xe(v.target.value),onKeyPress:v=>{v.key==="Enter"&&(v.preventDefault(),Ie.current=null,Me.current=!1,re(!0),i==="floating"&&Xe(!0),Ge(ce))},placeholder:k,disabled:w,style:{flex:1,border:"none",outline:"none",borderRadius:"12px",padding:"10px 4px",color:ot,fontSize:"15px",background:"transparent"}}),n.jsx("button",{type:"button",onClick:()=>{Ie.current=null,Me.current=!1,re(!0),i==="floating"&&Xe(!0),Ge(ce)},disabled:w||!ce.trim(),style:{border:"none",borderRadius:"12px",background:st,color:"#ffffff",minWidth:"48px",height:"44px",padding:"0 16px",fontSize:"14px",fontWeight:700,cursor:w||!ce.trim()?"default":"pointer",opacity:w||!ce.trim()?.6:1,boxShadow:`0 10px 20px ${Q(J,.18)}`},children:"Send"})]}),b&&mn("default"),!b&&n.jsxs("div",{style:{textAlign:"center",paddingTop:"2px"},children:[n.jsxs("div",{style:{color:Pt,fontSize:X.xs,fontWeight:600},children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),n.jsx("div",{style:{color:Pt,fontSize:X.xs,lineHeight:1.5},children:He})]})]})]});return i==="inline"?n.jsxs("div",{className:"admesh-component","data-admesh-theme":le,style:{width:"100%",position:"relative"},children:[r,b&&n.jsx("div",{onClick:()=>re(!1),style:{position:"fixed",inset:0,background:ln,backdropFilter:"blur(6px)",zIndex:2147483e3}}),b&&n.jsx("div",{style:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",zIndex:2147483001},children:r})]}):de?n.jsxs("div",{className:"admesh-component","data-admesh-theme":le,children:[b&&n.jsx("div",{onClick:()=>re(!1),style:{position:"fixed",inset:0,background:ln,backdropFilter:"blur(6px)",zIndex:2147483e3}}),n.jsx("div",{style:{position:"fixed",...b?{left:"50%",bottom:"12px",transform:"translateX(-50%)"}:q,zIndex:2147483001},children:r})]}):n.jsx("div",{className:"admesh-component","data-admesh-theme":le,children:n.jsx("button",{type:"button",onClick:Ct,style:{position:"fixed",...q,zIndex:2147483e3,border:"none",borderRadius:999,background:M.primaryColor,color:"#ffffff",padding:"14px 18px",boxShadow:"0 18px 40px rgba(15, 23, 42, 0.18)",cursor:"pointer"},children:s})})}return je.length===0&&!Et?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):i==="inline"?n.jsx("div",{className:"admesh-component","data-admesh-theme":le,children:n.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:te(c)??"100%",backgroundColor:"#eef2ff",fontSize:X.base,...o},children:n.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[Et?qt("legacy"):je.length>0&&n.jsx("div",{className:"flex flex-col gap-3",children:je.slice(0,K).map((r,v)=>n.jsxs("button",{onClick:()=>vt(r),className:"rounded-full px-5 py-4 text-left shadow-sm transition-transform duration-200 hover:scale-[1.01] active:scale-[0.99]",style:{width:v===0?"100%":v===1?"82%":"68%",backgroundColor:M.surfaceColor||"#ffffff",color:M.textColor||"#1e293b",border:`1px solid ${M.borderColor||"#e2e8f0"}`,fontSize:X.sm},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:M.backgroundColor||"#ffffff",color:M.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},r.id))}),Se.length>0&&n.jsxs("div",{className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:M.textColor},children:[Se.map(r=>n.jsx("div",{className:r.role==="user"?"text-right":"text-left",children:n.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:r.role==="user"?M.primaryColor:"#ffffff",color:r.role==="user"?"#ffffff":M.textColor,fontSize:X.sm},children:r.role==="assistant"?n.jsx(Yt,{content:r.content,theme:M,fontSize:X.sm}):n.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:r.content})})},r.id)),w&&n.jsx("div",{className:"text-sm",style:{color:M.textSecondaryColor},children:"Thinking..."}),S&&n.jsx("div",{className:"text-sm",style:{color:M.textSecondaryColor},children:"Connection issue. Please try again."}),n.jsx("div",{ref:Ye})]}),n.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"text",value:ce,onChange:r=>xe(r.target.value),onKeyPress:r=>r.key==="Enter"&&Ge(ce),placeholder:k,disabled:w,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:M.backgroundColor||"#ffffff",color:M.textColor,fontSize:X.sm}}),n.jsx("button",{onClick:()=>Ge(ce),disabled:w||!ce.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:M.primaryColor,color:"#ffffff"},children:n.jsx(yn,{size:18})})]})}),n.jsxs("div",{className:"space-y-2 text-center",children:[n.jsxs("p",{style:{color:M.textSecondaryColor,fontSize:X.xs,fontWeight:600},children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),n.jsx("p",{style:{color:M.textSecondaryColor,fontSize:X.xs,lineHeight:1.5},children:He})]})]})})}):de?n.jsx("div",{className:"admesh-component","data-admesh-theme":le,children:n.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...b?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...q,width:te(c)??De.width,height:te(h)??De.height},backgroundColor:b?Wt:M.backgroundColor,zIndex:9999,fontSize:X.base,borderRadius:b?"20px":"16px",border:b?`1px solid ${rn}`:"1px solid transparent",boxShadow:b?on:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[n.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between p-4 border-b",style:{position:"sticky",top:0,zIndex:10,borderColor:b?it:"transparent",background:b?Bt:M.backgroundColor,padding:b?"18px 20px":"16px"},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{style:{width:b?40:32,height:b?40:32,borderRadius:b?"14px":"10px",background:Q(J,.08),color:st,display:"flex",alignItems:"center",justifyContent:"center",fontSize:b?"15px":"13px",fontWeight:700,flexShrink:0},children:(a||"AA").slice(0,2).toUpperCase()}),n.jsxs("div",{children:[n.jsx("div",{className:"font-medium",style:{color:M.textColor,fontSize:b?"20px":X.base,fontWeight:700,letterSpacing:b?"-0.02em":0},children:a}),b&&n.jsx("div",{style:{color:Ut,fontSize:"12px",marginTop:"2px"},children:nn})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{onClick:Tt,className:"transition-colors",title:b?"Minimize":"Expand",style:{width:b?36:28,height:b?36:28,borderRadius:b?"12px":"10px",border:`1px solid ${b?it:"transparent"}`,background:b?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:b?n.jsx(Minimize2,{size:16,style:{color:M.textSecondaryColor}}):n.jsx(Tr,{size:16,style:{color:M.textSecondaryColor}})}),n.jsx("button",{onClick:Dt,className:"transition-colors",style:{width:b?36:28,height:b?36:28,borderRadius:b?"12px":"10px",border:`1px solid ${b?it:"transparent"}`,background:b?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(Fr,{size:16,style:{color:M.textSecondaryColor}})})]})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",style:{flex:"1 1 0%",minHeight:0,overflowY:"auto",padding:b?"20px":"16px"},children:[cn("legacy"),N&&Se.length===0&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",children:n.jsx("p",{style:{color:M.textColor,margin:0,fontSize:X.sm},children:y})})}),Se.map(r=>n.jsxs("div",{className:"mb-3",children:[n.jsx("div",{className:r.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:r.role==="user"?Bn:"transparent",color:r.role==="user"?"#ffffff":M.textColor,border:"none",borderRadius:r.role==="user"?b?"14px":"12px":0,padding:r.role==="user"?b?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:r.role==="assistant"?n.jsx("div",{style:{fontSize:`calc(${X.sm} * 1.3)`,lineHeight:1.65},children:n.jsx(Yt,{content:r.content,theme:M,fontSize:`calc(${X.sm} * 1.3)`})}):n.jsx("p",{style:{margin:0,fontSize:X.sm,lineHeight:"1.4"},children:r.content})}),r.role==="assistant"&&!We.has(r.id)&&n.jsx(jt,{messageId:r.id,query:r.userQuery,onFollowupDetected:ht,onRecommendationsShown:(v,I)=>{pt(v,I,r.userQuery)},onError:v=>{console.error("[AdMeshIntentAssistant] Recommendations error:",v)}}),r.role==="assistant"&&We.has(r.id)&&r.initialRecommendation&&!w&&n.jsxs("div",{className:"mb-4",children:[n.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),n.jsx(jt,{messageId:r.id,query:r.userQuery,initialRecommendation:r.initialRecommendation,triggerExposureUrl:!1,onFollowupDetected:ht,onRecommendationsShown:(v,I)=>{pt(v,I,r.userQuery)},onError:v=>{console.error("[AdMeshIntentAssistant] Recommendations error:",v)}})]})]},r.id)),w&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border-2 border-gray-300 border-t-blue-500"}),n.jsx("span",{style:{color:M.textSecondaryColor,fontSize:X.sm},children:"Thinking..."})]})})}),S&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:M.textSecondaryColor},children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{style:{fontSize:X.xs},children:"โ ๏ธ"}),n.jsx("span",{style:{fontSize:X.sm},children:"Connection issue. Please try again."})]})})}),n.jsx("div",{ref:Ye})]}),Se.length===0&&Et&&n.jsx("div",{className:"px-4 pb-2",children:qt("legacy")}),je.length>0&&Se.length===0&&!Et&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:je.slice(0,K).map(r=>n.jsxs("button",{onClick:()=>vt(r),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:M.surfaceColor||"#f8fafc",color:M.textColor||"#1e293b",border:`1px solid ${M.borderColor||"#e2e8f0"}`,fontSize:X.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:M.backgroundColor||"#ffffff",color:M.textSecondaryColor||"#64748b"},children:"Ad"})]},r.id))})}),U&&!R&&wt.length===0&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:n.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:M.surfaceColor,borderColor:M.borderColor,color:M.textSecondaryColor},children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("span",{style:{fontSize:X.sm},children:"Intent analysis failed"}),n.jsx("button",{onClick:O,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:M.primaryColor,color:"#ffffff"},children:"Retry"})]}),n.jsx("span",{style:{fontSize:X.xs},children:U})]})})}),n.jsxs("div",{className:"p-3 border-t",style:{borderColor:b?it:"transparent",padding:b?"18px 20px":void 0,background:b?Bt:void 0},children:[n.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${it}`,borderRadius:b?"16px":"12px",background:an,boxShadow:b?dn:"none",padding:b?"8px 8px 8px 14px":void 0},children:[n.jsx("input",{type:"text",value:ce,onChange:r=>xe(r.target.value),onKeyPress:r=>r.key==="Enter"&&Ge(ce),placeholder:k,disabled:w,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:M.textColor,fontSize:b?"15px":X.sm,"--tw-ring-color":M.primaryColor}}),n.jsx("button",{onClick:()=>Ge(ce),disabled:w||!ce.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:M.primaryColor,color:"#ffffff",borderRadius:b?"12px":"10px",width:b?"46px":void 0,height:b?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:b?`0 10px 20px ${Q(J,.18)}`:"none"},children:n.jsx(yn,{size:14})})]}),mn("legacy")]})]})}):n.jsx("div",{className:"admesh-component","data-admesh-theme":le,children:n.jsx("button",{onClick:Ct,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",...q,backgroundColor:M.primaryColor,color:"#ffffff",zIndex:9999,fontSize:X.base,...o},children:n.jsx("span",{className:"font-medium",children:s})})})},Ft="admesh:streamingStart",zt="admesh:streamingComplete";function Qr(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(Ft,{detail:o});window.dispatchEvent(s),d.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function Xr(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},a=new CustomEvent(zt,{detail:s});window.dispatchEvent(a),d.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function Jr(t,e,o){const s=a=>{const i=a;i.detail.messageId===t&&i.detail.sessionId===e&&(d.log("[StreamingEvents] ๐จ Received streamingStart event"),o(i.detail))};return window.addEventListener(Ft,s),()=>{window.removeEventListener(Ft,s)}}function Nn(t,e,o){d.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=a=>{const i=a;d.log("[StreamingEvents] ๐จ Received streamingComplete event (checking match)",{receivedMessageId:i.detail.messageId,receivedSessionId:i.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:i.detail.messageId===t,sessionIdMatch:i.detail.sessionId===e}),i.detail.messageId===t&&i.detail.sessionId===e?(d.log("[StreamingEvents] โ
Event matched! Calling callback"),o(i.detail)):d.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(zt,s),()=>{d.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(zt,s)}}const Lt=()=>{const t=new Set,e=new Map,o=i=>{const c=e.get(i);c&&(c.observer.disconnect(),c.timeoutId&&clearTimeout(c.timeoutId),e.delete(i))};return{startTracking:({exposureUrl:i,recommendationId:c,linkElement:h,sessionId:p,logPrefix:g="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!i||!h){g&&d.warn(`${g} โ ๏ธ Missing exposure tracking data`);return}const l=`${p||"anonymous"}::${c||i}`;if(t.has(l)||e.has(l))return;const m={observer:void 0,timeoutId:null,viewableStart:null},_=()=>{o(l),t.add(l),fetch(i,{method:"GET",keepalive:!0}).then(()=>{g&&d.log(`${g} โ
Exposure pixel fired`)}).catch(()=>{g&&d.warn(`${g} โ ๏ธ Failed to fire exposure pixel`),t.delete(l)})},f=new IntersectionObserver(A=>{A.forEach(N=>{N.intersectionRatio>=.5?m.viewableStart===null&&(m.viewableStart=performance.now(),m.timeoutId=setTimeout(_,1e3)):(m.viewableStart=null,m.timeoutId&&(clearTimeout(m.timeoutId),m.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});m.observer=f,f.observe(h),e.set(l,m)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},Zr=({containerId:t,messageId:e,sessionId:o,sdk:s,query:a,recommendations:i=[],onLinksFound:c,onNoLinksFound:h,children:p})=>{const[g,l]=u.useState(!1),[m,_]=u.useState(!0),[f,A]=u.useState(!1),N=u.useRef(Lt()),y=u.useRef(c),k=u.useRef(h),W=u.useRef(t),j=u.useRef(s),K=u.useRef(o),L=u.useRef(a);u.useEffect(()=>{y.current=c,k.current=h,W.current=t,j.current=s,K.current=o,L.current=a},[c,h,t,s,o,a]),u.useEffect(()=>()=>{N.current.cleanup()},[]);const x=u.useCallback(({exposureUrl:z,recommendationId:B,linkElement:T})=>{N.current.startTracking({exposureUrl:z,recommendationId:B,linkElement:T,sessionId:K.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),F=u.useCallback(()=>{d.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const z=document.getElementById(W.current);if(!z){d.warn("[FinalLinkDetectionCheck] โ Container not found"),l(!0),h();return}const B=new en({autoAddLabels:!0,fireExposurePixels:!0}),T=i.length>0?i:[];d.log(`[FinalLinkDetectionCheck] ๐ Using ${T.length} recommendations for link detection`),T.length>0&&process.env.NODE_ENV==="development"&&T.forEach((P,G)=>{var V,H,D,ne,C,R,U,O,Y;d.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${G+1} (DEV):`,{recommendation_id:P==null?void 0:P.recommendation_id,click_url:((V=P==null?void 0:P.tracking)==null?void 0:V.click_url)||((D=(H=P==null?void 0:P.recommendation)==null?void 0:H.creative)==null?void 0:D.landing_page_url),format:(ne=P==null?void 0:P.recommendation)==null?void 0:ne.format,brand_name:(U=(R=(C=P.render)==null?void 0:C.creative)==null?void 0:R.advertiser)==null?void 0:U.brand_name,cta_url:(Y=(O=P.render)==null?void 0:O.creative)==null?void 0:Y.landing_page_url})});const E=B.scanAndProcessLinks(z,T,({exposureUrl:P,recommendationId:G,linkElement:V})=>x({exposureUrl:P,recommendationId:G,linkElement:V}));d.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${E.length} links`),E.length>0?(d.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),A(!0),y.current(E.length)):(d.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${T.length} previous recommendation(s) if available)`),A(!1),k.current()),l(!0)}catch{d.error("[FinalLinkDetectionCheck] โ Error during final check"),l(!0),k.current()}},[x,i]);return u.useEffect(()=>{d.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:i.length});let z=null,B=!1;const T=Nn(e,o,E=>{d.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:E.messageId,sessionId:E.sessionId,timestamp:E.timestamp}),B=!0,z&&(clearTimeout(z),z=null),_(!1),setTimeout(()=>{F()},100)});return z=setTimeout(()=>{B||(d.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),_(!1),setTimeout(()=>{F()},100))},5e3),()=>{d.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),z&&clearTimeout(z),T()}},[e,o]),m?n.jsx(n.Fragment,{}):g?f?(d.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),n.jsx(n.Fragment,{})):(d.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),n.jsx(n.Fragment,{children:p})):n.jsx(n.Fragment,{})},eo=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:a,onError:i,className:c,query:h,onFallbackChange:p,onWeaveAttempt:g,onWeaveOutcome:l})=>{var P,G;const{sessionId:m,sdk:_,language:f,location:A,userId:N,model:y,messages:k}=At(),W=u.useRef(null),j=`weave-ad-container-${t}`,K=u.useRef(Lt()),L=u.useRef(!1),x=u.useRef(null),[F,z]=u.useState([]),B=u.useRef([]);u.useEffect(()=>(x.current||(x.current=new en({autoAddLabels:!0,fireExposurePixels:!0})),()=>{x.current&&(x.current.stopWatching(),x.current.clearCache())}),[]),u.useEffect(()=>()=>{K.current.cleanup()},[]),u.useEffect(()=>{(async()=>{var H;if(!_||!(h!=null&&h.trim())||!t){d.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{d.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const D=await _.fetchPlatformResponse({query:h.trim(),sessionId:m,messageId:t,language:f,location:A,userId:N,model:y,messages:k}),ne=(D==null?void 0:D.status)==="generated"?[D]:[];if(z(ne),B.current=ne,d.log("[WeaveAdFormatContainer] ๐ฅ Got platform response:",{status:D==null?void 0:D.status,recommendationId:D==null?void 0:D.recommendation_id,hasRecommendation:!!(D!=null&&D.recommendation),format:(H=D==null?void 0:D.recommendation)==null?void 0:H.format}),D!=null&&D.recommendation){const C=D.recommendation.creative,R=C.landing_page_url;d.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:C.brand_name,headline:C.headline,description:C.description,brandUrl:R})}else d.log("[WeaveAdFormatContainer] โ ๏ธ No recommendation found in platform response")}catch(D){d.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",D),z([])}})()},[_,m,t,h]),u.useEffect(()=>{const V=W.current;if(!V||!x.current)return;const H=x.current,D=({exposureUrl:R,recommendationId:U,linkElement:O})=>{K.current.startTracking({exposureUrl:R,recommendationId:U,linkElement:O,sessionId:m,logPrefix:"[WeaveAdFormatContainer]"})},C=setTimeout(()=>{d.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),g==null||g(t);const R=B.current.length>0?B.current:[];d.log(`[WeaveAdFormatContainer] ๐ Using ${R.length} recommendations for link detection`);try{const U=H.scanAndProcessLinks(V,R,D);U.length>0&&!L.current?(L.current=!0,d.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${U.length} links detected`),l==null||l(t,!0,`Found ${U.length} links`),s==null||s(U.length),p==null||p(!1)):L.current||d.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(U){const O=U instanceof Error?U.message:String(U);d.error(`[WeaveAdFormatContainer] โ Weave injection failed: ${O}`),l==null||l(t,!1,O),a==null||a(),p==null||p(!0)}},100);return H.watchForNewLinks(V,B.current,D),()=>{clearTimeout(C),H.stopWatching()}},[e,m,t,s,p,g,l]);const T=(G=(P=F[0])==null?void 0:P.recommendation)==null?void 0:G.format,E=T==="weave";return u.useEffect(()=>{h&&E&&d.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${T}) - skipping fallback recommendations`)},[h,E,T]),n.jsxs(n.Fragment,{children:[n.jsx("div",{ref:W,id:j,className:c,"data-weave-ad-format":"true","data-message-id":t,children:e}),h&&!E&&n.jsx(Zr,{containerId:j,messageId:t,sessionId:m,sdk:_,query:h,recommendations:F,onLinksFound:V=>{d.log(`[WeaveAdFormatContainer] โ
Links found (${V}) - no fallback needed`),l==null||l(t,!0,`Found ${V} links in final check`),s==null||s(V),p==null||p(!1)},onNoLinksFound:()=>{d.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),d.log(`[WeaveAdFormatContainer] ๐ Passing ${F.length} recommendation(s) to fallback component`),l==null||l(t,!1,"No links detected in final check"),a==null||a(),p==null||p(!0)},children:n.jsx(jn,{format:o,messageId:t,query:h,fallback:!0,onError:i,previousRecommendations:F.length>0?F:void 0})})]})},to=t=>{const{sdk:e,sessionId:o}=At(),s=u.useRef(!1),a=u.useRef(0),i=u.useRef(!1),c=u.useRef(!1),h=u.useRef(null),p=u.useRef(Lt());u.useEffect(()=>()=>{p.current.cleanup()},[]);const g=u.useCallback(({exposureUrl:k,recommendationId:W,linkElement:j})=>{p.current.startTracking({exposureUrl:k,recommendationId:W,linkElement:j,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),l=u.useRef(Date.now()),m=u.useRef(0),_=u.useRef(null),f=u.useRef([]),A=u.useRef(300),N=u.useCallback(async()=>{var k,W,j,K;if(!(!e||!o||s.current)){s.current=!0,a.current=0;try{const L=document.getElementById(t.llmOutputContainerId);if(!L)return;const x=(k=e.getWeaveProcessor)==null?void 0:k.call(e);if(!x)return;const F=x.scanAndProcessLinks(L,[],({exposureUrl:B,recommendationId:T,linkElement:E})=>g({exposureUrl:B,recommendationId:T,linkElement:E}));a.current=F.length;const z=F.length>0;if(z&&!i.current)i.current=!0,(W=t.onLinksDetected)==null||W.call(t,F.length),c.current=!0;else if(!z&&i.current)i.current=!1,c.current=!1;else if(!z&&!c.current){h.current&&clearTimeout(h.current),_.current&&clearInterval(_.current),m.current=0,l.current=Date.now();const B=Math.max(100,A.current/3);_.current=setInterval(()=>{var G;const E=Date.now()-l.current,P=A.current;E>=P?(m.current++,m.current>=2&&(_.current&&(clearInterval(_.current),_.current=null),!i.current&&!c.current&&((G=t.onNoLinksDetected)==null||G.call(t),c.current=!0))):m.current=0},B);const T=Math.max(1500,A.current*5);h.current=setTimeout(()=>{var E;_.current&&(clearInterval(_.current),_.current=null),!i.current&&!c.current&&((E=t.onNoLinksDetected)==null||E.call(t),c.current=!0)},T)}else z&&c.current&&!i.current&&(h.current&&(clearTimeout(h.current),h.current=null),i.current=!0,(j=t.onLinksDetected)==null||j.call(t,F.length),c.current=!0)}catch(L){const x=L instanceof Error?L:new Error(String(L));(K=t.onError)==null||K.call(t,x)}finally{s.current=!1}}},[e,o,t,g]),y=u.useCallback(()=>{const k=f.current;if(k.length<2){A.current=300;return}const W=[];for(let L=1;L<k.length;L++)W.push(k[L]-k[L-1]);const j=W.reduce((L,x)=>L+x,0)/W.length,K=Math.max(100,Math.min(j*3,1e3));A.current=K},[]);return u.useEffect(()=>{const k=document.getElementById(t.llmOutputContainerId);if(!k)return;N();const W=new MutationObserver(()=>{const j=Date.now();l.current=j,m.current=0,f.current.push(j),f.current.length>10&&f.current.shift(),y(),N()});return W.observe(k,{childList:!0,subtree:!0,characterData:!1}),()=>{W.disconnect(),h.current&&clearTimeout(h.current),_.current&&clearInterval(_.current)}},[t.llmOutputContainerId,N,y]),{isProcessing:s.current,detectedLinksCount:a.current,linksFound:i.current,shouldRenderFallback:!i.current&&c.current,processWeaveFormat:N}},no="1.0.31";exports.AdMeshBadge=Dn;exports.AdMeshCompactCard=Xt;exports.AdMeshContext=Jt;exports.AdMeshFollowup=En;exports.AdMeshIntentAssistant=Yr;exports.AdMeshLayout=kn;exports.AdMeshLinkTracker=In;exports.AdMeshProvider=Cn;exports.AdMeshRecommendations=jt;exports.AdMeshRenderer=Mn;exports.AdMeshSDK=Rt;exports.AdMeshTailAd=_r;exports.AdMeshTracker=Sn;exports.AdMeshViewabilityTracker=It;exports.STREAMING_COMPLETE_EVENT=zt;exports.STREAMING_START_EVENT=Ft;exports.VERSION=no;exports.WeaveAdFormatContainer=eo;exports.WeaveAdFormatProvider=fr;exports.WeaveFallbackRecommendations=jn;exports.WeaveResponseProcessor=en;exports.callAnalyzeIntentEndpoint=An;exports.createInlineExposureTracker=Lt;exports.dispatchStreamingCompleteEvent=Xr;exports.dispatchStreamingStartEvent=Qr;exports.extractHeadingsDirectly=Nt;exports.onStreamingComplete=Nn;exports.onStreamingStart=Jr;exports.useAdMesh=At;exports.useAdMeshContext=Zt;exports.useAdMeshStyles=Pn;exports.useViewabilityTracker=vn;exports.useWeaveAdFormat=to;exports.useWeaveAdFormatContext=gr;
|
|
1079
|
+
`;let lr=!1;const Cr=()=>{c.useEffect(()=>{if(!lr){try{Oo();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Vo,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),lr=!0}catch{a.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])};function Ko(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 Go(t){return Ko(t/1e3)}const An=({content:t,theme:e,fontSize:o})=>{const s=w=>w.split(/(\*\*[^*]+\*\*)/g).map((p,y)=>p.startsWith("**")&&p.endsWith("**")&&p.length>4?r.jsx("strong",{style:{fontWeight:"600",color:e.textColor},children:p.slice(2,-2)},y):r.jsx(c.Fragment,{children:p},y)),i=w=>w.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(p=>p.trim()).filter((p,y,C)=>p.length>0||y<C.length-1),l=w=>{const g=i(w);return g.length>1&&g.every(p=>/^:?-{3,}:?$/.test(p))},u=w=>{const g=w.indexOf("|");if(g<=0)return{heading:null,headerLine:w};const p=w.slice(0,g).trim();return!p||/^[-|:\s]+$/.test(p)?{heading:null,headerLine:w}:{heading:p,headerLine:w.slice(g).trim()}},b=(w,g)=>{const p=i(w).length,y=i(g).length;return p<=1||p===y?g:`| ${Array.from({length:p},()=>"---").join(" | ")} |`},h=w=>{if(w.length<2||!w[0].includes("|"))return{heading:null,lines:w};const{heading:g,headerLine:p}=u(w[0]),y=p.startsWith("|")?p:`| ${p}`,C=b(y,w[1]);return{heading:g,lines:[y,C,...w.slice(2)]}},_=w=>{if(w.length<2||!w[0].includes("|"))return!1;const{lines:g}=h(w);return l(g[1])&&i(g[0]).length>=2},d=w=>{if(!w.includes("|"))return[w];let g=w.trim();const p=[],y=g.indexOf("|");if(y>0){const C=g.slice(0,y).trim();C&&!/^[-|:\s]+$/.test(C)&&(p.push(C),g=g.slice(y).trim())}return g=g.replace(/\|\s*(\|(?:\s*:?-{3,}:?\s*\|)+)/g,(C,j)=>`
|
|
1080
|
+
${j}`),g=g.replace(/\|\s*\|\s*(?=[A-Za-z0-9*])/g,`|
|
|
1081
|
+
| `),g=g.replace(/\|\s+(?=\|(?!\s*:?-{3,}:?\s*\|)[^|\n])/g,`|
|
|
1082
|
+
`),p.push(...g.split(`
|
|
1083
|
+
`).map(C=>C.trim()).filter(Boolean)),p},m=w=>{const g=w.split(`
|
|
1084
|
+
`),p=[];for(const y of g){if(!y.includes("|")){p.push(y);continue}p.push(...d(y))}return p.join(`
|
|
1085
|
+
`)},x=(w=>{const g=m(w).split(`
|
|
1086
|
+
`),p=[];let y=0;for(;y<g.length;){const C=g[y],j=g[y+1]||"";if(C.includes("|")&&l(j)){p.length>0&&p[p.length-1].trim()&&p.push("");const{heading:O,headerLine:M}=u(C);for(O&&p.push(O),p.push(M,b(M,j)),y+=2;y<g.length&&g[y].includes("|")&&g[y].trim();)p.push(g[y]),y+=1;y<g.length&&g[y].trim()&&p.push("");continue}p.push(C),y+=1}return p.join(`
|
|
1087
|
+
`)})(t).split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);return r.jsx("div",{style:{margin:0,color:e.textColor,fontSize:o},children:x.map((w,g)=>{const p=w.split(`
|
|
1088
|
+
`).map(M=>M.trim()).filter(Boolean),y=p.every(M=>/^[-*]\s+/.test(M)),C=p.every(M=>/^\d+\.\s+/.test(M)),j=p.length===1&&/^#{1,3}\s+/.test(p[0]),O=_(p);if(j){const M=p[0].replace(/^#{1,3}\s+/,"");return r.jsx("h3",{style:{marginTop:g===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(M)},g)}if(O){const{heading:M,lines:v}=h(p),$=i(v[0]),W=v.slice(2).map(i).filter(N=>N.length===$.length);return r.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[M?r.jsx("p",{style:{marginTop:g===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(M)}):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:$.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[r.jsx("thead",{children:r.jsx("tr",{children:$.map((N,z)=>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)},z))})}),r.jsx("tbody",{children:W.map((N,z)=>r.jsx("tr",{children:N.map((I,P)=>r.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:z===W.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(I)},P))},z))})]})})]},g)}if(y||C){const M=C?"ol":"ul";return r.jsx(M,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:p.map((v,$)=>r.jsx("li",{style:{marginBottom:"0.45rem"},children:s(v.replace(/^([-*]|\d+\.)\s+/,""))},$))},g)}return r.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:p.map((M,v)=>r.jsxs(c.Fragment,{children:[v>0&&r.jsx("br",{}),s(M)]},v))},g)})})};function Yt(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function Dt(t){return t.replace(/\s+/g," ").trim()}function Yo(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 l=s.length?s:o;return[i,...l].slice(0,4)}function Qo(t,e,o,s){const i=new Set,l=[],u=(x,w="information")=>{const g=Dt(x);if(!g)return;const p=g.toLowerCase();i.has(p)||(i.add(p),l.push({id:`followup_${l.length}_${p.replace(/[^a-z0-9]+/g,"_")}`,text:g,type:w,is_sponsored:!1}))},b=new Set,h=x=>{const w=Dt(x||"");if(!w)return;const g=w.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();g&&b.add(g)};(s||[]).forEach(x=>h(x==null?void 0:x.title)),(o||[]).forEach(x=>h(x==null?void 0:x.title)),e.split(/\n+/).map(x=>Dt(x.replace(/^[-*]\s+/,""))).filter(Boolean).filter(x=>x.length>=24&&x.length<=90).forEach(x=>{b.size>=6||h(x)});const d=Dt(t.replace(/[?.!]+$/g,"")),m=Array.from(b).slice(0,3);return[m[0]?`Tell me more about ${m[0]}`:"",m[1]?`Show me examples related to ${m[1]}`:"",m[2]?`Compare the main options for ${m[2]}`:"","Break this down more simply",`What should I look at next about ${d}`,"Give me the practical takeaway here"].forEach((x,w)=>{l.length>=3||u(x,w===0?"comparison":"information")}),l.slice(0,3)}function Xo(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function Mr(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 cr(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Mr(e))return e}catch{return}}function dr(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=cr()||(Mr(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=cr()?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:Xo()}}function Jo(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:Dt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Cn(t){return[...t].sort((e,o)=>{const s=!!e.is_sponsored,i=!!o.is_sponsored;return s===i?0:s?-1:1})}const Zo={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)"}},es={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},ts={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},ns=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:l,showHeaderTitle:u=!0,showSubtitle:b=!0,layout:h="floating",surface:_="page",panelWidth:d,panelHeight:m,analyticsPageUrl:k,fontScale:x=1,position:w="bottom-right",size:g="md",defaultOpen:p,open:y,onOpenChange:C,autoOpen:j=!1,showWelcomeMessage:O=!1,welcomeMessage:M="Hi, Iโm Ava. Iโll help you find the best options.",placeholder:v="Ask me anything about products...",adsEnabled:$=!0,suggestions:W,maxSuggestions:N=6,suggestionStyle:z="carousel",onlyShowWhenSponsored:I=!1,variant:P="default",queryHandler:Y,suggestionsLoader:J,disclaimerText:ge,poweredByLabel:B="Powered by AdMesh",subtitle:se="Publisher Assistant",onOpen:xe,onClose:ue})=>{const{sdk:Q,sessionId:V,theme:He,apiKey:Ae,userId:Ce}=Ft(),{suggestions:ie,isAnalyzingIntent:F,intentError:q,retryIntentAnalysis:K,activeDelegationSession:re,hasActiveDelegationSession:me,stopDelegationSession:Me,refreshDelegationActivity:Ee}=En();Cr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:Q,sessionId:V,hasContextTheme:!!He});const R=t||He||Zo,ke=(R==null?void 0:R.mode)||"light",S=_==="ad-slot",[L,pe]=c.useState(p||j),D=y!==void 0,Se=D?y:L,[ne,be]=c.useState(""),[_e,le]=c.useState([]),[G,De]=c.useState(!1),[we,Pe]=c.useState(null),[E,qe]=c.useState(!1),[rt,ft]=c.useState(new Set),[St,Qe]=c.useState(W||ie||[]),[At,Z]=c.useState(0),[Te,tt]=c.useState(0),[Ge,gt]=c.useState({}),ot=c.useRef(null),Oe=c.useRef(!1),Le=c.useRef(null),Pt=c.useRef(new Map),xt=c.useRef([]),Ct=c.useRef(null),Mt=c.useRef(null),jt=c.useRef(null),$t=c.useRef(!1),Bt=c.useRef(!1),Ut=c.useRef(null),Et=c.useRef(null),zt=c.useRef(null),H=c.useRef(null),ye=c.useRef(null),[ce,Rt]=c.useState(!1),[Xe,bt]=c.useState(!1),yt=!!(Ae!=null&&Ae.toLowerCase().startsWith("pub_")),$e=me()&&(re==null?void 0:re.session_id)===V?re:null,dt=c.useRef(new Set),st=c.useRef(new Set),Ht=c.useRef(!1),qt=S&&(E||_e.length>0||G),ut=Yt(d)??"100%",Lt=Yt(m)??"100%",Zt=c.useCallback(n=>f=>{f?Pt.current.set(n,f):Pt.current.delete(n)},[]),Re=c.useCallback(async(n,f={})=>{if(!(!Q||!V))try{await Q.trackPublisherAssistantEvent({event_name:n,timestamp:new Date().toISOString(),session_id:V,...dr(k),...f})}catch(A){console.warn(`[AdMeshIntentAssistant] Failed to track ${n}`,A)}},[k,Q,V]),en=c.useCallback((n,f,A)=>{var ee,je;const T=f==null?void 0:f.recommendation_id;if(!T)return;const U=`${n}:${T}`;st.current.has(U)||(st.current.add(U),Re("recommendation_shown",{message_id:n,query:A,recommendation_id:T,brand_name:(je=(ee=f.recommendation)==null?void 0:ee.creative)==null?void 0:je.brand_name,is_sponsored:!0}))},[Re]),dn=c.useCallback((n,f,A,T,U,ee)=>{const je=Array.isArray(ee)&&ee.length?ee.map((ve,ze)=>{const We=Dt(ve.text||"");return We?{id:`followup_llm_${ze}_${We.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:We,type:ve.type||"information",is_sponsored:!1}:null}).filter(ve=>!!ve).slice(0,3):Qo(n,f,A,T),Be=Jo(U),Fe=Be?[Be,...je.slice(0,2)]:je.slice(0,3);Fe.length&&Qe(Cn(Fe))},[]),tn=c.useCallback((n,f)=>{const A=Dt(n.query||n.label||"");if(!A||!f)return;const T={id:f,text:A,type:"action",is_sponsored:!0,recommendation:{recommendation_id:f,recommendation:{creative:{follow_up_suggestion:A}},tracking:{followup_engagement_url:n.engagement_url,followup_exposure_url:n.exposure_url}}};Qe(U=>{const ee=U.filter(je=>!je.is_sponsored).slice(0,3);return Cn([T,...ee].slice(0,4))})},[]),Tn=c.useCallback(()=>{const n=Ct.current,f=Mt.current;if(!n||!f)return!1;const A=n.getBoundingClientRect(),T=f.getBoundingClientRect(),U=Math.max(0,n.scrollTop+T.top-A.top);return n.scrollTop=U,!0},[]);c.useLayoutEffect(()=>{var n;if($t.current){Tn()&&($t.current=!1);return}Bt.current||(n=Et.current)==null||n.scrollIntoView({behavior:"smooth"})},[_e,Tn]),c.useLayoutEffect(()=>{if(!S)return;const n=Ut.current;if(!n)return;const f=n.closest(".admesh-publisher-assistant-reactMount"),A=Lt;[n,f].forEach(U=>{U&&(U.style.width=ut,U.style.maxWidth=ut,U.style.height=A,U.style.maxHeight=A,U.style.overflow="hidden",U.style.boxSizing="border-box",U.dataset.admeshAdSlotExpanded=qt?"true":"false")});const T=f==null?void 0:f.parentElement;T&&T!==document.body&&T!==document.documentElement&&(T.style.width=ut,T.style.maxWidth=ut,T.style.height=A,T.style.maxHeight=A,T.style.overflow="hidden",T.style.boxSizing="border-box")},[Lt,ut,S,qt]),c.useEffect(()=>{if(W&&W.length){Qe(W);return}ie&&ie.length&&Qe(n=>Yo(n,ie))},[W,ie]),c.useEffect(()=>{if(P!=="default"||!J)return;let n=!1;return J().then(f=>{!n&&Array.isArray(f)&&f.length&&Qe(f)}).catch(f=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",f)}),()=>{n=!0}},[J,P]),c.useEffect(()=>{if(!G){tt(0),ot.current=null;return}ot.current==null&&(ot.current=typeof performance<"u"?performance.now():Date.now());const n=()=>{const A=ot.current;if(A==null)return;const T=typeof performance<"u"?performance.now():Date.now();tt(Math.floor((T-A)/1e3))};n();const f=window.setInterval(n,1e3);return()=>window.clearInterval(f)},[G]),c.useEffect(()=>{if(!G||P!=="default"){Z(0);return}const n=window.setInterval(()=>{Z(f=>Math.min(f+1,7))},3e3);return()=>window.clearInterval(n)},[G,P]),c.useEffect(()=>{Ht.current||!Q||!V||(Ht.current=!0,Re("assistant_loaded",{metadata:{layout:h,surface:_,variant:P,default_open:p||j}}))},[j,p,h,Q,V,_,Re,P]);const _t=c.useCallback(n=>{D?C==null||C(n):pe(n),n?(Re("assistant_opened",{metadata:{layout:h,surface:_,variant:P,expanded:E}}),xe==null||xe()):ue==null||ue()},[D,E,h,C,xe,ue,_,Re,P]),In=c.useCallback(()=>{_t(!0)},[_t]),Er=c.useCallback(()=>{_t(!1)},[_t]),Rr=c.useCallback(()=>{qe(n=>!n)},[]),Dn=c.useCallback(async(n,f,A,T,U,ee)=>{var je,Be,Fe;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 Ee("turn_started",{source:"publisher_assistant",recommendation_id:$e.recommendation_id}).catch(de=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",de)});const ve=await fetch(`${Q.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:ee,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${Ae}`},body:JSON.stringify({message:n,session_id:V||"default-session",message_id:f,user_id:Ce,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:dr(k),sponsored_recommendation:U!=null&&U.recommendation_id?{recommendation_id:U.recommendation_id,brand_name:(Be=(je=U.recommendation)==null?void 0:je.creative)==null?void 0:Be.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(!ve.ok)throw new Error(`API request failed: ${ve.status} ${ve.statusText}`);const ze=(Fe=ve.body)==null?void 0:Fe.getReader(),We=new TextDecoder;if(!ze)throw new Error("Response body is not readable");let Je="",Ze,et,ht,oe,te;return await(async()=>{try{for(;;){const{done:de,value:nt}=await ze.read();if(de)break;const Ye=We.decode(nt,{stream:!0}).split(`
|
|
1089
|
+
`);for(const Tt of Ye)if(Tt.startsWith("data: ")){const yn=Tt.slice(6);if(yn.trim()==="[DONE]")return $e&&Ee("turn_completed",{source:"publisher_assistant",recommendation_id:$e.recommendation_id}).catch(Ie=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",Ie)}),{text:Je,source_links:Ze,related_items:et,followup_suggestions:ht,used_capability:oe,response_time_ms:te};try{const Ie=JSON.parse(yn);switch(Ie.type){case"content":{const Yn=Ie.content||"";Je+=Yn,A==null||A(Yn);break}case"final":{Je=Ie.reply||Je,Ze=Array.isArray(Ie.source_links)?Ie.source_links:void 0,et=Array.isArray(Ie.related_items)?Ie.related_items:void 0,ht=Array.isArray(Ie.followup_suggestions)?Ie.followup_suggestions:void 0,oe=typeof Ie.used_capability=="string"?Ie.used_capability:oe,te=typeof Ie.response_time_ms=="number"?Ie.response_time_ms:te;break}case"followup_suggestions":{ht=Array.isArray(Ie.followup_suggestions)?Ie.followup_suggestions:ht;break}case"error":throw new Error(Ie.message||"Unknown streaming error");case"session_start":T==null||T(),console.log("Session started:",Ie.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",yn);continue}}}}catch(de){if(ee!=null&&ee.aborted)return{text:Je,source_links:Ze,related_items:et,followup_suggestions:ht,used_capability:oe,response_time_ms:te,error:"aborted"};throw console.error("Stream processing error:",de),de}finally{ze.releaseLock()}return{text:Je,source_links:Ze,related_items:et,followup_suggestions:ht,used_capability:oe,response_time_ms:te}})()}catch(ve){return ee!=null&&ee.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",ve),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:ve instanceof Error?ve.message:"request_failed"})}},[Q,V,Ae,Ce,$e,Ee]),un=c.useCallback(()=>{const n=H.current;if(!n||n.signal.aborted)return;n.abort(),De(!1),Le.current=null,Oe.current=!1;const f=ye.current;f&&le(A=>A.map(T=>T.id===f&&!T.content.trim()?{...T,content:"Generation stopped."}:T))},[]),wt=c.useCallback(async n=>{var Fe,ve,ze,We,Je,Ze,et,ht;if(!n.trim()||G)return;const f=typeof performance<"u"?performance.now():Date.now(),A=n.trim(),T=Date.now().toString(),U=new AbortController,ee=Le.current,je=(ee==null?void 0:ee.recommendation)||null;H.current=U,ye.current=null,jt.current=T,$t.current=!0,Bt.current=!0,Le.current=null,Qe(oe=>oe.some(te=>te.is_sponsored)?oe.filter(te=>!te.is_sponsored):oe),Pe(null);const Be={id:T,role:"user",content:A,timestamp:new Date};if(Re("query_submitted",{message_id:T,query:A}),le(oe=>[...oe,Be]),be(""),De(!0),P==="default"&&Y){try{const oe=(Date.now()+1).toString(),te={id:oe,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:null};Oe.current&&(ft(nt=>new Set([...nt,oe])),Oe.current=!1),le(nt=>[...nt,te]),ye.current=oe;const Ne=await Y(A,{sponsoredSuggestion:ee});if(U.signal.aborted){Le.current=null;return}const de=Ne.recommendation||je||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:n,hasResponseRecommendation:!!Ne.recommendation,hasSponsoredSuggestionRecommendation:!!je,finalRecommendationId:de==null?void 0:de.recommendation_id}),le(nt=>nt.map(Ke=>Ke.id===oe?{...Ke,content:Ne.answer,sourceLinks:Ne.source_links,relatedItems:Ne.related_items,initialRecommendation:de,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-f}:Ke)),dn(A,Ne.answer,Ne.source_links,Ne.related_items,Ne.recommendation||null,Ne.followup_suggestions),Re("answer_completed",{message_id:oe,query:A,recommendation_id:de==null?void 0:de.recommendation_id,brand_name:(ve=(Fe=de==null?void 0:de.recommendation)==null?void 0:Fe.creative)==null?void 0:ve.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:"completed",metadata:{variant:P,source:"query_handler"}}),Le.current=null}catch(oe){console.error("Error sending message:",oe);const te=oe instanceof Error?oe.message:"Unknown error occurred";Pe(te);const Ne={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};le(de=>[...de,Ne]),Re("answer_failed",{query:A,status:te,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,metadata:{variant:P,source:"query_handler"}}),Le.current=null}finally{H.current===U&&(H.current=null,ye.current=null,De(!1))}return}if(!Q){setTimeout(()=>{if(U.signal.aborted){H.current===U&&(H.current=null,ye.current=null);return}const oe={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};le(te=>[...te,oe]),H.current===U&&(H.current=null,ye.current=null,De(!1))},1e3);return}try{const oe=(Date.now()+1).toString(),te=je,Ne={id:oe,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:te};Oe.current&&(ft(Ke=>new Set([...Ke,oe])),Oe.current=!1),le(Ke=>[...Ke,Ne]),ye.current=oe;const de=await Dn(A,T,Ke=>{le(Ye=>Ye.map(Tt=>Tt.id===oe?{...Tt,content:Tt.content+Ke}:Tt))},()=>{De(!0),Z(0)},te,U.signal);if(U.signal.aborted){de.text.trim()||le(Ke=>Ke.map(Ye=>Ye.id===oe&&!Ye.content.trim()?{...Ye,content:"Generation stopped."}:Ye)),Re("answer_failed",{message_id:oe,query:A,recommendation_id:te==null?void 0:te.recommendation_id,brand_name:(We=(ze=te==null?void 0:te.recommendation)==null?void 0:ze.creative)==null?void 0:We.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:"aborted",metadata:{variant:P,source:"api_chat_assistant"}}),Le.current=null;return}const nt=typeof de.response_time_ms=="number"?de.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-f;le(Ke=>Ke.map(Ye=>Ye.id===oe?{...Ye,content:de.text,sourceLinks:de.source_links,relatedItems:de.related_items,initialRecommendation:Ye.initialRecommendation||te,responseTimeMs:nt}:Ye)),dn(A,de.text,de.source_links,de.related_items,null,de.followup_suggestions),de.error?Re("answer_failed",{message_id:oe,query:A,recommendation_id:te==null?void 0:te.recommendation_id,brand_name:(Ze=(Je=te==null?void 0:te.recommendation)==null?void 0:Je.creative)==null?void 0:Ze.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:de.error,metadata:{variant:P,source:"api_chat_assistant"}}):Re("answer_completed",{message_id:oe,query:A,recommendation_id:te==null?void 0:te.recommendation_id,brand_name:(ht=(et=te==null?void 0:te.recommendation)==null?void 0:et.creative)==null?void 0:ht.brand_name,used_capability:de.used_capability,latency_ms:nt,status:"completed",metadata:{variant:P,source:"api_chat_assistant",response_time_ms:nt}}),Le.current=null}catch(oe){console.error("Error sending message:",oe);const te=oe instanceof Error?oe.message:"Unknown error occurred";Pe(te);const Ne={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};le(de=>[...de,Ne]),Re("answer_failed",{query:A,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:te,metadata:{variant:P,source:"api_chat_assistant"}}),Le.current=null}finally{H.current===U&&(H.current=null,ye.current=null,De(!1))}},[G,Dn,Y,dn,Q,Re,P]),vt=St,nn=c.useMemo(()=>vt.some(n=>n==null?void 0:n.is_sponsored),[vt]),rn=c.useMemo(()=>vt.filter(n=>!(n&&typeof n.id=="string")?!1:I?nn:!0),[nn,I,vt]),Ve=c.useMemo(()=>Cn(rn),[rn]),on=c.useCallback(async n=>{var A,T,U,ee,je,Be,Fe;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:n.text,is_sponsored:n.is_sponsored,hasRecommendation:!!n.recommendation,recommendationId:((A=n.recommendation)==null?void 0:A.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((U=(T=n.recommendation)==null?void 0:T.tracking)!=null&&U.followup_engagement_url),sessionId:V}),Oe.current=n.is_sponsored||!1,Le.current=n.is_sponsored?n:null;const f=Ve.findIndex(ve=>ve.id===n.id);Re("suggestion_clicked",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:f>=0?f:void 0,is_sponsored:n.is_sponsored,recommendation_id:(ee=n.recommendation)==null?void 0:ee.recommendation_id,brand_name:(Fe=(Be=(je=n.recommendation)==null?void 0:je.recommendation)==null?void 0:Be.creative)==null?void 0:Fe.brand_name,query:n.text}),wt(n.text),n.is_sponsored&&n.recommendation&&Q?setTimeout(async()=>{var ve;try{const ze=(ve=n.recommendation.tracking)==null?void 0:ve.followup_engagement_url,We=n.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:ze,recommendationId:We,sessionId:V}),ze&&We&&V?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await Q.fireFollowupEngagement(ze,We,V),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!ze,hasRecommendationId:!!We,hasSessionId:!!V})}catch(ze){console.error("[AdMeshIntentAssistant] โ Error firing sponsored suggestion engagement:",ze)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[wt,Ve,Q,V,Re]),sn=ts[w],Pn=es[g];c.useEffect(()=>{if(xt.current.forEach(n=>n()),xt.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return Ve.forEach((n,f)=>{const A=Pt.current.get(n.id);if(!A)return;const T=`${V||"anonymous"}:${n.id}:${n.is_sponsored?"s":"o"}`;if(dt.current.has(T))return;let U=null,ee=null;const je=()=>{U&&(clearTimeout(U),U=null),ee==null||ee.disconnect(),ee=null},Be=()=>{var Fe,ve,ze,We,Je;if(dt.current.has(T)){je();return}if(dt.current.add(T),je(),Re("suggestion_exposure",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:f,is_sponsored:n.is_sponsored,recommendation_id:(Fe=n.recommendation)==null?void 0:Fe.recommendation_id,brand_name:(We=(ze=(ve=n.recommendation)==null?void 0:ve.recommendation)==null?void 0:ze.creative)==null?void 0:We.brand_name}),Q&&V&&n.is_sponsored&&n.recommendation){const Ze=(Je=n.recommendation.tracking)==null?void 0:Je.followup_exposure_url,et=n.recommendation.recommendation_id;Ze&&et?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Ze,recommendationId:et,suggestionText:n.text,sessionId:V}),Q.fireFollowupExposure(Ze,et,V)):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Ze,hasRecommendationId:!!et,suggestionText:n.text})}};ee=new IntersectionObserver(Fe=>{const ve=Fe[0];if(ve){if(ve.intersectionRatio>=.5){U||(U=setTimeout(Be,1e3));return}U&&(clearTimeout(U),U=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),ee.observe(A),xt.current.push(je)}),()=>{xt.current.forEach(n=>n()),xt.current=[]}},[Ve,Q,V,Re]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:vt.length,safeSuggestions:rn.length,isAnalyzingIntent:F,hasIntentError:!!q,onlyShowWhenSponsored:I,hasSponsoredSuggestions:nn,sponsoredCount:vt.filter(n=>n==null?void 0:n.is_sponsored).length,nonSponsoredCount:vt.filter(n=>n&&!(n!=null&&n.is_sponsored)).length,modalShouldAppear:I?nn:!0,suggestions:vt.map(n=>{var f,A,T;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:((f=n==null?void 0:n.recommendation)==null?void 0:f.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((T=(A=n==null?void 0:n.recommendation)==null?void 0:A.tracking)!=null&&T.followup_engagement_url)}}),renderedSuggestions:Ve.map(n=>{var f,A,T;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:((f=n==null?void 0:n.recommendation)==null?void 0:f.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((T=(A=n==null?void 0:n.recommendation)==null?void 0:A.tracking)!=null&&T.followup_engagement_url)}})});const he={base:`${16*x}px`,sm:`${14*x}px`,xs:`${12*x}px`},mn=ge||"AI-generated responses may contain errors. Please verify important information independently.",Tr=["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..."],Ot=n=>{const f=(n==null?void 0:n.accentColor)||it,A=(n==null?void 0:n.metaColor)||Kt,T=(n==null?void 0:n.includeSteps)??P==="default",U=`${Te}s`,ee=T?`${Tr[At]} (${U})`:`Generating answer... ${U}`;return r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:n!=null&&n.compact?"8px":"10px",color:A,fontSize:n!=null&&n.compact?he.xs:he.sm},children:[r.jsx("span",{style:{width:n!=null&&n.compact?8:9,height:n!=null&&n.compact?8:9,borderRadius:999,background:f,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${X(ae,.28)}`,flexShrink:0}}),r.jsx("span",{children:ee})]})},$n=c.useCallback((n,f)=>{if(Ge[n.id])return;const A=f?"helpful":"not_helpful";gt(T=>({...T,[n.id]:A})),Re("answer_feedback",{message_id:n.id,query:n.userQuery,status:A,latency_ms:n.responseTimeMs,metadata:{helpful:f}})},[Ge,Re]);function pn(n,f){if(n.role!=="assistant"||!n.content.trim()||G&&n.id===ye.current)return null;const A=(f==null?void 0:f.accentColor)||it,T=(f==null?void 0:f.metaColor)||Kt,U=Ge[n.id],ee=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 ${X(ae,.08)}`,flexWrap:"nowrap"},children:[r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto"},children:[r.jsx("span",{style:{fontSize:he.xs,color:T,whiteSpace:"nowrap"},children:U?"Thanks for your feedback":"Is this helpful?"}),U?r.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,background:X(A,.12),color:A,flexShrink:0},children:U==="helpful"?r.jsx(ar,{size:14}):r.jsx(ir,{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:()=>$n(n,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${X(ae,.12)}`,background:"#ffffff",color:T,cursor:"pointer"},children:r.jsx(ar,{size:14})}),r.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>$n(n,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${X(ae,.12)}`,background:"#ffffff",color:T,cursor:"pointer"},children:r.jsx(ir,{size:14})})]})]}),ee?r.jsxs("span",{style:{fontSize:he.xs,color:T,whiteSpace:"nowrap",flexShrink:0,marginLeft:"auto"},children:["Answer Completed in ",Go(n.responseTimeMs)]}):null]})}const Vt=c.useCallback(()=>{const n=zt.current;if(!n)return;const f=Math.max(0,n.scrollWidth-n.clientWidth);Rt(n.scrollLeft>4),bt(n.scrollLeft<f-4)},[]);c.useEffect(()=>(Vt(),window.addEventListener("resize",Vt),()=>window.removeEventListener("resize",Vt)),[Vt,Ve.length]);const zn=c.useCallback(n=>{const f=zt.current;f&&f.scrollBy({left:n==="left"?-Math.max(160,Math.floor(f.clientWidth*.75)):Math.max(160,Math.floor(f.clientWidth*.75)),behavior:"smooth"})},[]),X=(n,f)=>{if(!n||!n.startsWith("#"))return`rgba(15, 23, 42, ${f})`;const A=n.slice(1),T=A.length===3?A.split("").map(Be=>`${Be}${Be}`).join(""):A;if(T.length!==6)return n;const U=parseInt(T.slice(0,2),16),ee=parseInt(T.slice(2,4),16),je=parseInt(T.slice(4,6),16);return`rgba(${U}, ${ee}, ${je}, ${f})`},ae=R.primaryColor||"#3F037F";R.surfaceColor,R.backgroundColor;const Ln=R.borderColor||"#e5e7eb",mt=R.textColor||"#111827",Ir=R.textSecondaryColor||"#6b7280";X(ae,.12);const hn=X(ae,.24);X(ae,.38);const Dr=X(ae,.12),Pr=S?ut:E?"min(960px, calc(100vw - 24px))":h==="inline"?"100%":"min(420px, calc(100vw - 32px))",Nn=S?Lt:E?"min(78vh, 760px)":"auto",$r=S?ut:"100%",zr=S?Lt:void 0,Fn=S?"13px":"16.25px",Lr=`linear-gradient(180deg, ${X(ae,.04)} 0%, ${X(ae,.08)} 100%)`,it=ae,Kt=Ir,Wn=se||"Publisher Assistant",Gt=F&&Ve.length===0&&_e.length===0,fn="#f7f8fc",gn="linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(248,250,252,0.98) 100%)",pt="rgba(15, 23, 42, 0.08)",Bn="rgba(15, 23, 42, 0.12)",Un="0 24px 60px rgba(15, 23, 42, 0.16)",xn="#667085",Hn="#98a2b3",Nr=it,qn="#ffffff",On="0 8px 24px rgba(15, 23, 42, 0.08)",Vn="rgba(15, 23, 42, 0.18)";function Kn(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 ${hn}`,background:X("#ffffff",.9),marginBottom:"4px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{color:it,fontSize:he.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),r.jsxs("div",{style:{color:mt,fontSize:he.sm,fontWeight:600,lineHeight:1.3},children:[$e.brand_name," agent is active"]})]}),r.jsx("button",{type:"button",onClick:()=>{Me("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${hn}`,borderRadius:999,background:X("#ffffff",.92),color:it,padding:"7px 12px",fontSize:he.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function Gn(n){const f=S;return r.jsxs("div",{style:{display:"flex",flexDirection:f?"column":"row",alignItems:f||n==="default"?"center":"flex-start",justifyContent:f?"center":"space-between",gap:f?"2px":"12px",flexWrap:"wrap",paddingTop:f||n==="default"?"2px":"8px",borderTop:n==="default"?`1px solid ${pt}`:"none",marginTop:f?"0":n==="default"?"4px":0,flexShrink:0},children:[r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:f?"4px":"8px",color:Hn,fontSize:f?"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:Hn,fontSize:f?"9px":"11px",lineHeight:f?1.25:1.45,maxWidth:f?"100%":n==="default"?"68%":"100%",textAlign:f?"center":n==="default"?"right":"left"},children:mn})]})}function bn(n){const f=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:X(ae,.1),flexShrink:0}}),r.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:f.map((A,T)=>r.jsx("div",{style:{width:A,maxWidth:"100%",height:40,borderRadius:999,background:`linear-gradient(90deg, ${X(ae,.08)} 0%, ${X(ae,.18)} 50%, ${X(ae,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:`0 8px 22px ${X(ae,.08)}`,flexShrink:0}},`suggestion-skeleton-${T}`))}),r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:X(ae,.1),flexShrink:0}})]}):r.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:n==="publisher"?"10px":"12px"},children:f.map((A,T)=>r.jsx("div",{style:{width:A,maxWidth:"100%",height:n==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${X(ae,.08)} 0%, ${X(ae,.18)} 50%, ${X(ae,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:n==="publisher"?`0 8px 22px ${X(ae,.08)}`:"none"}},`suggestion-skeleton-${T}`))})}function Fr(){if(G)return null;if(Gt)return bn("publisher");if(!Ve.length)return null;const n=Ve.slice(0,N);return z==="stacked"?r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:S?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:S?"240px":void 0,paddingRight:S?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:n.map(f=>r.jsxs("button",{ref:Zt(f.id),onClick:()=>{P==="default"&&(qe(!0),h==="floating"&&_t(!0)),on(f)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:S?"12px":"14px",border:f.is_sponsored?`1px solid ${X(ae,.32)}`:`1px solid ${X(ae,.42)}`,background:f.is_sponsored?ae:X("#ffffff",.94),color:f.is_sponsored?"#ffffff":mt,padding:S?"8px 10px":"10px 14px",fontSize:S?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:f.is_sponsored?`0 8px 18px ${X(ae,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{style:{minWidth:0},children:f.text}),$&&f.is_sponsored&&r.jsx("span",{style:{flexShrink:0,borderRadius:999,background:X("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},f.id))}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:S?"6px":"10px",flexShrink:0},children:[r.jsx("button",{type:"button",onClick:()=>zn("left"),disabled:!ce,"aria-label":"Scroll suggestions left",style:{width:S?24:28,height:S?24:28,borderRadius:999,border:`1px solid ${X(Ln,.8)}`,background:X("#ffffff",.9),color:"#6b7280",cursor:ce?"pointer":"default",opacity:ce?1:.55},children:"โน"}),r.jsx("div",{ref:zt,onScroll:Vt,style:{display:"flex",gap:S?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:n.map(f=>r.jsxs("button",{ref:Zt(f.id),onClick:()=>{P==="default"&&(qe(!0),h==="floating"&&_t(!0)),on(f)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:"8px",whiteSpace:"nowrap",borderRadius:999,border:f.is_sponsored?`1px solid ${X(ae,.32)}`:`1px solid ${X(ae,.42)}`,background:f.is_sponsored?ae:X("#ffffff",.94),color:f.is_sponsored?"#ffffff":mt,padding:S?"7px 10px":"8px 14px",fontSize:S?"12px":"13px",fontWeight:500,boxShadow:f.is_sponsored?`0 8px 18px ${X(ae,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{children:f.text}),$&&f.is_sponsored&&r.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},f.id))}),r.jsx("button",{type:"button",onClick:()=>zn("right"),disabled:!Xe,"aria-label":"Scroll suggestions right",style:{width:S?24:28,height:S?24:28,borderRadius:999,border:`1px solid ${X(Ln,.8)}`,background:X("#ffffff",.9),color:"#6b7280",cursor:Xe?"pointer":"default",opacity:Xe?1:.55},children:"โบ"})]})}function Wr(n){var f,A;return(f=n.relatedItems)!=null&&f.length||!((A=n.sourceLinks)!=null&&A.length)?null:r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:n.sourceLinks.map(T=>r.jsx("a",{href:T.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Re("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:T.title,source_url:T.url}})},style:{color:it,fontSize:he.xs,textDecoration:"none",borderBottom:`1px solid ${X(ae,.18)}`},children:T.title||T.url},`${n.id}-${T.url}`))})}function Br(n){var f;return(f=n.relatedItems)!=null&&f.length?r.jsxs("div",{style:{marginTop:"14px"},children:[r.jsx("div",{style:{fontSize:he.xs,fontWeight:700,color:"#4b5563",marginBottom:"8px"},children:"Related"}),r.jsx("div",{style:{display:"flex",gap:S?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:n.relatedItems.slice(0,4).map(A=>r.jsxs("a",{href:A.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Re("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:A.title,source_url:A.url,source_publisher:A.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:S?"6px":"10px",padding:S?"10px":"14px",borderRadius:S?"12px":"14px",textDecoration:"none",color:mt,border:`1px solid ${X(ae,.18)}`,background:"#ffffff",boxShadow:"0 10px 24px rgba(15, 23, 42, 0.08)",flex:S?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:S?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[r.jsx("div",{style:{fontSize:S?"13px":"18px",fontWeight:650,lineHeight:1.35,color:ae,overflowWrap:"anywhere"},children:A.title||A.url}),A.publisher&&r.jsx("div",{style:{fontSize:S?"11px":"15px",color:"#6b7280",lineHeight:1.4,overflowWrap:"anywhere"},children:A.publisher})]},`${n.id}-${A.url}`))})]}):null}function Ur(){return r.jsxs("div",{ref:Ct,style:{flex:S?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:S?"contain":void 0,WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none",padding:S?"0 2px 4px":E?"16px 16px 8px":0},children:[_e.map(n=>{const f=n.role==="user"&&n.id===jt.current;return r.jsx("div",{ref:f?Mt:void 0,style:{marginBottom:"12px",textAlign:n.role==="user"?"right":"left"},children:(()=>{const T=!!n.content.trim()||!G;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"?it:"transparent",color:n.role==="user"?"#ffffff":mt,boxShadow:"none",border:"none",fontSize:n.role==="assistant"?Fn:S?"12px":"13px",lineHeight:n.role==="assistant"?1.62:1.4},children:[n.role==="assistant"?n.content.trim()?r.jsx(An,{content:n.content,theme:{...R,textColor:mt},fontSize:Fn}):G&&n.id===ye.current?Ot({includeSteps:!0}):null:r.jsx("p",{style:{margin:0},children:n.content}),n.role==="assistant"&&Wr(n),n.role==="assistant"&&Br(n),n.role==="assistant"&&pn(n),n.role==="assistant"&&T&&rt.has(n.id)&&n.initialRecommendation&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Qt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:tn,onRecommendationsShown:(U,ee)=>{en(U,ee,n.userQuery)},onError:U=>{console.error("[AdMeshIntentAssistant] Recommendation error:",U)}})}),n.role==="assistant"&&T&&!rt.has(n.id)&&(n.initialRecommendation||yt)&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Qt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation||void 0,onFollowupDetected:tn,onRecommendationsShown:(U,ee)=>{en(U,ee,n.userQuery)},onError:U=>{console.error("[AdMeshIntentAssistant] Recommendation error:",U)}})})]})})})()},n.id)}),we&&r.jsx("div",{style:{color:Kt,fontSize:he.sm},children:"Connection issue. Please try again."}),r.jsx("div",{ref:Et})]})}if(P==="default"){const n=r.jsxs("div",{style:{width:Pr,maxWidth:$r,height:Nn,maxHeight:zr,boxSizing:"border-box",display:"flex",flexDirection:"column",background:E?fn:Lr,borderRadius:S?"12px":E?"18px":"20px",padding:E?0:S?"8px":"12px",boxShadow:E?Un:"none",border:E?`1px solid ${Bn}`:"none",overflow:"hidden",minHeight:S?0:void 0},children:[(E||S)&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:S?"10px 12px":"16px 18px",background:E?gn:"#ffffff29",color:mt,borderBottom:`1px solid ${pt}`,flexShrink:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("div",{style:{width:S?30:40,height:S?30:40,borderRadius:S?"10px":"14px",background:X(ae,.08),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:it,overflow:"hidden"},children:l?r.jsx("img",{src:l,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||b)&&r.jsxs("div",{children:[u&&r.jsx("div",{style:{fontSize:S?"14px":"20px",fontWeight:700,lineHeight:1.1,letterSpacing:0},children:i}),b&&r.jsx("div",{style:{fontSize:S?"10px":"12px",color:xn,marginTop:"2px"},children:Wn})]})]}),!S&&r.jsx("button",{type:"button",onClick:()=>qe(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"12px",border:`1px solid ${pt}`,background:"#ffffff",color:xn,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:S?"6px":"16px",minHeight:0,flex:S?"1 1 0":void 0,overflow:S?"hidden":void 0,padding:S?"8px 10px 6px":E?"18px":"14px",background:E?fn:X("#ffffff",.16),height:S?void 0:E?Nn:"auto"},children:[Kn("default"),E&&Ur(),S&&!E&&r.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),S&&!E&&O&&_e.length===0&&r.jsx("div",{style:{color:mt,fontSize:"15px",lineHeight:1.3,fontWeight:700,letterSpacing:0,padding:"2px 2px 0",textAlign:"center"},children:M}),Fr(),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",borderRadius:S?"12px":"16px",background:qn,padding:S?"6px 6px 6px 10px":"8px 8px 8px 14px",boxShadow:E?On:`0 8px 22px ${Dr}`,border:`1px solid ${E?pt:hn}`,flexShrink:0},children:[r.jsx("input",{type:"text",value:ne,onChange:f=>be(f.target.value),onKeyPress:f=>{if(f.key==="Enter"){if(f.preventDefault(),G)return;Le.current=null,Oe.current=!1,qe(!0),h==="floating"&&_t(!0),wt(ne)}},placeholder:v,style:{flex:1,border:"none",outline:"none",borderRadius:"12px",padding:S?"8px 2px":"10px 4px",color:mt,fontSize:S?"13px":"15px",background:"transparent"}}),r.jsx("button",{type:"button",onClick:()=>{if(G){un();return}Le.current=null,Oe.current=!1,qe(!0),h==="floating"&&_t(!0),wt(ne)},disabled:!G&&!ne.trim(),style:{border:"none",borderRadius:"12px",background:G?"#dc2626":it,color:"#ffffff",minWidth:S?"40px":"48px",height:S?"36px":"44px",padding:S?"0 10px":"0 16px",fontSize:S?"12px":"14px",fontWeight:700,cursor:!G&&!ne.trim()?"default":"pointer",opacity:!G&&!ne.trim()?.6:1,boxShadow:`0 10px 20px ${G?"rgba(220, 38, 38, 0.18)":X(ae,.18)}`},children:G?"Stop":"Send"})]}),E&&Gn("default"),!E&&r.jsxs("div",{style:{textAlign:"center",paddingTop:"2px"},children:[r.jsxs("div",{style:{color:Kt,fontSize:S?"9.5px":he.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:Kt,fontSize:S?"9px":he.xs,lineHeight:S?1.25:1.5},children:mn})]})]})]});return h==="inline"?S?r.jsx("div",{ref:Ut,className:"admesh-component","data-admesh-theme":ke,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-expanded":qt?"true":"false",style:{width:ut,height:Lt,maxWidth:ut,maxHeight:Lt,position:"relative",overflow:"hidden"},children:n}):r.jsxs("div",{className:"admesh-component","data-admesh-theme":ke,style:{width:"100%",position:"relative"},children:[n,E&&r.jsx("div",{onClick:()=>qe(!1),style:{position:"fixed",inset:0,background:Vn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),E&&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":ke,children:[E&&r.jsx("div",{onClick:()=>qe(!1),style:{position:"fixed",inset:0,background:Vn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),r.jsx("div",{style:{position:"fixed",...E?{left:"50%",bottom:"12px",transform:"translateX(-50%)"}:sn,zIndex:2147483001},children:n})]}):r.jsx("div",{className:"admesh-component","data-admesh-theme":ke,children:r.jsx("button",{type:"button",onClick:In,style:{position:"fixed",...sn,zIndex:2147483e3,border:"none",borderRadius:999,background:R.primaryColor,color:"#ffffff",padding:"14px 18px",boxShadow:"0 18px 40px rgba(15, 23, 42, 0.18)",cursor:"pointer"},children:s})})}return Ve.length===0&&!Gt?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):h==="inline"?r.jsx("div",{className:"admesh-component","data-admesh-theme":ke,children:r.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:Yt(d)??"100%",backgroundColor:"#eef2ff",fontSize:he.base,...o},children:r.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[Gt?bn("legacy"):Ve.length>0&&r.jsx("div",{className:"flex flex-col gap-3",children:Ve.slice(0,N).map((n,f)=>r.jsxs("button",{ref:Zt(n.id),onClick:()=>on(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:f===0?"100%":f===1?"82%":"68%",backgroundColor:R.surfaceColor||"#ffffff",color:R.textColor||"#1e293b",border:`1px solid ${R.borderColor||"#e2e8f0"}`,fontSize:he.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:R.backgroundColor||"#ffffff",color:R.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},n.id))}),_e.length>0&&r.jsxs("div",{ref:Ct,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:R.textColor},children:[_e.map(n=>{const f=n.role==="user"&&n.id===jt.current;return r.jsx("div",{ref:f?Mt: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"?R.primaryColor:"#ffffff",color:n.role==="user"?"#ffffff":R.textColor,fontSize:he.sm},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx(An,{content:n.content,theme:R,fontSize:he.sm}),pn(n,{accentColor:R.primaryColor,metaColor:R.textSecondaryColor})]}):G&&n.id===ye.current?Ot({compact:!0,accentColor:R.primaryColor,metaColor:R.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:n.content})})},n.id)}),G&&!_e.some(n=>n.role==="assistant"&&n.id===ye.current&&!n.content.trim())&&r.jsx("div",{className:"text-sm",style:{color:R.textSecondaryColor},children:Ot({compact:!0,accentColor:R.primaryColor,metaColor:R.textSecondaryColor,includeSteps:!1})}),we&&r.jsx("div",{className:"text-sm",style:{color:R.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:ne,onChange:n=>be(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(G){n.preventDefault();return}wt(ne)}},placeholder:v,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:R.backgroundColor||"#ffffff",color:R.textColor,fontSize:he.sm}}),r.jsx("button",{onClick:()=>{if(G){un();return}wt(ne)},disabled:!G&&!ne.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:G?"#dc2626":R.primaryColor,color:"#ffffff"},children:G?r.jsx(vn,{size:18}):r.jsx(sr,{size:18})})]})}),r.jsxs("div",{className:"space-y-2 text-center",children:[r.jsxs("p",{style:{color:R.textSecondaryColor,fontSize:he.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:R.textSecondaryColor,fontSize:he.xs,lineHeight:1.5},children:mn})]})]})})}):Se?r.jsx("div",{className:"admesh-component","data-admesh-theme":ke,children:r.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...E?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...sn,width:Yt(d)??Pn.width,height:Yt(m)??Pn.height},backgroundColor:E?fn:R.backgroundColor,zIndex:9999,fontSize:he.base,borderRadius:E?"20px":"16px",border:E?`1px solid ${Bn}`:"1px solid transparent",boxShadow:E?Un:"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:E?pt:"transparent",background:E?gn:R.backgroundColor,padding:E?"18px 20px":"16px"},children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{style:{width:E?40:32,height:E?40:32,borderRadius:E?"14px":"10px",background:X(ae,.08),color:it,display:"flex",alignItems:"center",justifyContent:"center",fontSize:E?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:l?r.jsx("img",{src:l,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||b&&E)&&r.jsxs("div",{children:[u&&r.jsx("div",{className:"font-medium",style:{color:R.textColor,fontSize:E?"20px":he.base,fontWeight:700,letterSpacing:E?"-0.02em":0},children:i}),b&&E&&r.jsx("div",{style:{color:xn,fontSize:"12px",marginTop:"2px"},children:Wn})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[!S&&r.jsx("button",{onClick:Rr,className:"transition-colors",title:E?"Minimize":"Expand",style:{width:E?36:28,height:E?36:28,borderRadius:E?"12px":"10px",border:`1px solid ${E?pt:"transparent"}`,background:E?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:E?r.jsx(No,{size:16,style:{color:R.textSecondaryColor}}):r.jsx(zo,{size:16,style:{color:R.textSecondaryColor}})}),r.jsx("button",{onClick:Er,className:"transition-colors",style:{width:E?36:28,height:E?36:28,borderRadius:E?"12px":"10px",border:`1px solid ${E?pt:"transparent"}`,background:E?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx(vn,{size:16,style:{color:R.textSecondaryColor}})})]})]}),r.jsxs("div",{ref:Ct,className:"flex-1 min-h-0 overflow-y-auto p-4",style:{flex:"1 1 0%",minHeight:0,overflowY:"auto",padding:E?"20px":"16px"},children:[Kn("legacy"),O&&_e.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:R.textColor,margin:0,fontSize:he.sm},children:M})})}),_e.map(n=>{const f=n.role==="user"&&n.id===jt.current;return r.jsxs("div",{ref:f?Mt: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"?Nr:"transparent",color:n.role==="user"?"#ffffff":R.textColor,border:"none",borderRadius:n.role==="user"?E?"14px":"12px":0,padding:n.role==="user"?E?"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(${he.sm} * 1.3)`,lineHeight:1.65},children:r.jsx(An,{content:n.content,theme:R,fontSize:`calc(${he.sm} * 1.3)`})}),pn(n,{accentColor:R.primaryColor,metaColor:R.textSecondaryColor})]}):G&&n.id===ye.current?Ot({compact:!0,accentColor:R.primaryColor,metaColor:R.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,fontSize:he.sm,lineHeight:"1.4"},children:n.content})}),n.role==="assistant"&&!rt.has(n.id)&&r.jsx(Qt,{messageId:n.id,query:n.userQuery,onFollowupDetected:tn,onRecommendationsShown:(A,T)=>{en(A,T,n.userQuery)},onError:A=>{console.error("[AdMeshIntentAssistant] Recommendations error:",A)}}),n.role==="assistant"&&rt.has(n.id)&&n.initialRecommendation&&!G&&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(Qt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:tn,onRecommendationsShown:(A,T)=>{en(A,T,n.userQuery)},onError:A=>{console.error("[AdMeshIntentAssistant] Recommendations error:",A)}})]})]},n.id)}),G&&!_e.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:Ot({compact:!0,accentColor:R.primaryColor,metaColor:R.textSecondaryColor,includeSteps:!1})})}),we&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:R.textSecondaryColor},children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{style:{fontSize:he.xs},children:"โ ๏ธ"}),r.jsx("span",{style:{fontSize:he.sm},children:"Connection issue. Please try again."})]})})}),r.jsx("div",{ref:Et})]}),_e.length===0&&Gt&&r.jsx("div",{className:"px-4 pb-2",children:bn("legacy")}),Ve.length>0&&_e.length===0&&!Gt&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:Ve.slice(0,N).map(n=>r.jsxs("button",{ref:Zt(n.id),onClick:()=>on(n),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:R.surfaceColor||"#f8fafc",color:R.textColor||"#1e293b",border:`1px solid ${R.borderColor||"#e2e8f0"}`,fontSize:he.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:R.backgroundColor||"#ffffff",color:R.textSecondaryColor||"#64748b"},children:"Ad"})]},n.id))})}),q&&!F&&rn.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:R.surfaceColor,borderColor:R.borderColor,color:R.textSecondaryColor},children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{style:{fontSize:he.sm},children:"Intent analysis failed"}),r.jsx("button",{onClick:K,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:R.primaryColor,color:"#ffffff"},children:"Retry"})]}),r.jsx("span",{style:{fontSize:he.xs},children:q})]})})}),r.jsxs("div",{className:"p-3 border-t",style:{borderColor:E?pt:"transparent",padding:E?"18px 20px":void 0,background:E?gn:void 0},children:[r.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${pt}`,borderRadius:E?"16px":"12px",background:qn,boxShadow:E?On:"none",padding:E?"8px 8px 8px 14px":void 0},children:[r.jsx("input",{type:"text",value:ne,onChange:n=>be(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(G){n.preventDefault();return}wt(ne)}},placeholder:v,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:R.textColor,fontSize:E?"15px":he.sm,"--tw-ring-color":R.primaryColor}}),r.jsx("button",{onClick:()=>{if(G){un();return}wt(ne)},disabled:!G&&!ne.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:G?"#dc2626":R.primaryColor,color:"#ffffff",borderRadius:E?"12px":"10px",width:E?"46px":void 0,height:E?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:E?`0 10px 20px ${X(ae,.18)}`:"none"},children:G?r.jsx(vn,{size:14}):r.jsx(sr,{size:14})})]}),Gn("legacy")]})]})}):r.jsx("div",{className:"admesh-component","data-admesh-theme":ke,children:r.jsx("button",{onClick:In,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",...sn,backgroundColor:R.primaryColor,color:"#ffffff",zIndex:9999,fontSize:he.base,...o},children:r.jsx("span",{className:"font-medium",children:s})})})},an="admesh:streamingStart",ln="admesh:streamingComplete";function rs(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(an,{detail:o});window.dispatchEvent(s),a.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function os(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(ln,{detail:s});window.dispatchEvent(i),a.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function ss(t,e,o){const s=i=>{const l=i;l.detail.messageId===t&&l.detail.sessionId===e&&(a.log("[StreamingEvents] ๐จ Received streamingStart event"),o(l.detail))};return window.addEventListener(an,s),()=>{window.removeEventListener(an,s)}}function jr(t,e,o){a.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const l=i;a.log("[StreamingEvents] ๐จ Received streamingComplete event (checking match)",{receivedMessageId:l.detail.messageId,receivedSessionId:l.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:l.detail.messageId===t,sessionIdMatch:l.detail.sessionId===e}),l.detail.messageId===t&&l.detail.sessionId===e?(a.log("[StreamingEvents] โ
Event matched! Calling callback"),o(l.detail)):a.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(ln,s),()=>{a.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(ln,s)}}const cn=()=>{const t=new Set,e=new Map,o=l=>{const u=e.get(l);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(l))};return{startTracking:({exposureUrl:l,recommendationId:u,linkElement:b,sessionId:h,logPrefix:_="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!l||!b){_&&a.warn(`${_} โ ๏ธ Missing exposure tracking data`);return}const d=`${h||"anonymous"}::${u||l}`;if(t.has(d)||e.has(d))return;const m={observer:void 0,timeoutId:null,viewableStart:null},k=()=>{o(d),t.add(d),fetch(l,{method:"GET",keepalive:!0}).then(()=>{_&&a.log(`${_} โ
Exposure pixel fired`)}).catch(()=>{_&&a.warn(`${_} โ ๏ธ Failed to fire exposure pixel`),t.delete(d)})},x=new IntersectionObserver(w=>{w.forEach(g=>{g.intersectionRatio>=.5?m.viewableStart===null&&(m.viewableStart=performance.now(),m.timeoutId=setTimeout(k,1e3)):(m.viewableStart=null,m.timeoutId&&(clearTimeout(m.timeoutId),m.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});m.observer=x,x.observe(b),e.set(d,m)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},is=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:l=[],onLinksFound:u,onNoLinksFound:b,children:h})=>{const[_,d]=c.useState(!1),[m,k]=c.useState(!0),[x,w]=c.useState(!1),g=c.useRef(cn()),p=c.useRef(u),y=c.useRef(b),C=c.useRef(t),j=c.useRef(s),O=c.useRef(o),M=c.useRef(i);c.useEffect(()=>{p.current=u,y.current=b,C.current=t,j.current=s,O.current=o,M.current=i},[u,b,t,s,o,i]),c.useEffect(()=>()=>{g.current.cleanup()},[]);const v=c.useCallback(({exposureUrl:W,recommendationId:N,linkElement:z})=>{g.current.startTracking({exposureUrl:W,recommendationId:N,linkElement:z,sessionId:O.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),$=c.useCallback(()=>{a.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const W=document.getElementById(C.current);if(!W){a.warn("[FinalLinkDetectionCheck] โ Container not found"),d(!0),b();return}const N=new Rn({autoAddLabels:!0,fireExposurePixels:!0}),z=l.length>0?l:[];a.log(`[FinalLinkDetectionCheck] ๐ Using ${z.length} recommendations for link detection`),z.length>0&&process.env.NODE_ENV==="development"&&z.forEach((P,Y)=>{var J,ge,B,se,xe,ue,Q,V,He;a.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${Y+1} (DEV):`,{recommendation_id:P==null?void 0:P.recommendation_id,click_url:((J=P==null?void 0:P.tracking)==null?void 0:J.click_url)||((B=(ge=P==null?void 0:P.recommendation)==null?void 0:ge.creative)==null?void 0:B.landing_page_url),format:(se=P==null?void 0:P.recommendation)==null?void 0:se.format,brand_name:(Q=(ue=(xe=P.render)==null?void 0:xe.creative)==null?void 0:ue.advertiser)==null?void 0:Q.brand_name,cta_url:(He=(V=P.render)==null?void 0:V.creative)==null?void 0:He.landing_page_url})});const I=N.scanAndProcessLinks(W,z,({exposureUrl:P,recommendationId:Y,linkElement:J})=>v({exposureUrl:P,recommendationId:Y,linkElement:J}));a.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${I.length} links`),I.length>0?(a.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),w(!0),p.current(I.length)):(a.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${z.length} previous recommendation(s) if available)`),w(!1),y.current()),d(!0)}catch{a.error("[FinalLinkDetectionCheck] โ Error during final check"),d(!0),y.current()}},[v,l]);return c.useEffect(()=>{a.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:l.length});let W=null,N=!1;const z=jr(e,o,I=>{a.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:I.messageId,sessionId:I.sessionId,timestamp:I.timestamp}),N=!0,W&&(clearTimeout(W),W=null),k(!1),setTimeout(()=>{$()},100)});return W=setTimeout(()=>{N||(a.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),k(!1),setTimeout(()=>{$()},100))},5e3),()=>{a.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),W&&clearTimeout(W),z()}},[e,o]),m?r.jsx(r.Fragment,{}):_?x?(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:h})):r.jsx(r.Fragment,{})},as=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:l,className:u,query:b,onFallbackChange:h,onWeaveAttempt:_,onWeaveOutcome:d})=>{var P,Y;const{sessionId:m,sdk:k,language:x,location:w,userId:g,model:p,messages:y}=Ft(),C=c.useRef(null),j=`weave-ad-container-${t}`,O=c.useRef(cn()),M=c.useRef(!1),v=c.useRef(null),[$,W]=c.useState([]),N=c.useRef([]);c.useEffect(()=>(v.current||(v.current=new Rn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{v.current&&(v.current.stopWatching(),v.current.clearCache())}),[]),c.useEffect(()=>()=>{O.current.cleanup()},[]),c.useEffect(()=>{(async()=>{var ge;if(!k||!(b!=null&&b.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 k.fetchPlatformResponse({query:b.trim(),sessionId:m,messageId:t,language:x,location:w,userId:g,model:p,messages:y}),se=(B==null?void 0:B.status)==="generated"?[B]:[];if(W(se),N.current=se,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:(ge=B==null?void 0:B.recommendation)==null?void 0:ge.format}),B!=null&&B.recommendation){const xe=B.recommendation.creative,ue=xe.landing_page_url;a.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:xe.brand_name,headline:xe.headline,description:xe.description,brandUrl:ue})}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),W([])}})()},[k,m,t,b]),c.useEffect(()=>{const J=C.current;if(!J||!v.current)return;const ge=v.current,B=({exposureUrl:ue,recommendationId:Q,linkElement:V})=>{O.current.startTracking({exposureUrl:ue,recommendationId:Q,linkElement:V,sessionId:m,logPrefix:"[WeaveAdFormatContainer]"})},xe=setTimeout(()=>{a.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),_==null||_(t);const ue=N.current.length>0?N.current:[];a.log(`[WeaveAdFormatContainer] ๐ Using ${ue.length} recommendations for link detection`);try{const Q=ge.scanAndProcessLinks(J,ue,B);Q.length>0&&!M.current?(M.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),h==null||h(!1)):M.current||a.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(Q){const V=Q instanceof Error?Q.message:String(Q);a.error(`[WeaveAdFormatContainer] โ Weave injection failed: ${V}`),d==null||d(t,!1,V),i==null||i(),h==null||h(!0)}},100);return ge.watchForNewLinks(J,N.current,B),()=>{clearTimeout(xe),ge.stopWatching()}},[e,m,t,s,h,_,d]);const z=(Y=(P=$[0])==null?void 0:P.recommendation)==null?void 0:Y.format,I=z==="weave";return c.useEffect(()=>{b&&I&&a.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${z}) - skipping fallback recommendations`)},[b,I,z]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:C,id:j,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),b&&!I&&r.jsx(is,{containerId:j,messageId:t,sessionId:m,sdk:k,query:b,recommendations:$,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),h==null||h(!1)},onNoLinksFound:()=>{a.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),a.log(`[WeaveAdFormatContainer] ๐ Passing ${$.length} recommendation(s) to fallback component`),d==null||d(t,!1,"No links detected in final check"),i==null||i(),h==null||h(!0)},children:r.jsx(wr,{format:o,messageId:t,query:b,fallback:!0,onError:l,previousRecommendations:$.length>0?$:void 0})})]})},ls=t=>{const{sdk:e,sessionId:o}=Ft(),s=c.useRef(!1),i=c.useRef(0),l=c.useRef(!1),u=c.useRef(!1),b=c.useRef(null),h=c.useRef(cn());c.useEffect(()=>()=>{h.current.cleanup()},[]);const _=c.useCallback(({exposureUrl:y,recommendationId:C,linkElement:j})=>{h.current.startTracking({exposureUrl:y,recommendationId:C,linkElement:j,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),d=c.useRef(Date.now()),m=c.useRef(0),k=c.useRef(null),x=c.useRef([]),w=c.useRef(300),g=c.useCallback(async()=>{var y,C,j,O;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const M=document.getElementById(t.llmOutputContainerId);if(!M)return;const v=(y=e.getWeaveProcessor)==null?void 0:y.call(e);if(!v)return;const $=v.scanAndProcessLinks(M,[],({exposureUrl:N,recommendationId:z,linkElement:I})=>_({exposureUrl:N,recommendationId:z,linkElement:I}));i.current=$.length;const W=$.length>0;if(W&&!l.current)l.current=!0,(C=t.onLinksDetected)==null||C.call(t,$.length),u.current=!0;else if(!W&&l.current)l.current=!1,u.current=!1;else if(!W&&!u.current){b.current&&clearTimeout(b.current),k.current&&clearInterval(k.current),m.current=0,d.current=Date.now();const N=Math.max(100,w.current/3);k.current=setInterval(()=>{var Y;const I=Date.now()-d.current,P=w.current;I>=P?(m.current++,m.current>=2&&(k.current&&(clearInterval(k.current),k.current=null),!l.current&&!u.current&&((Y=t.onNoLinksDetected)==null||Y.call(t),u.current=!0))):m.current=0},N);const z=Math.max(1500,w.current*5);b.current=setTimeout(()=>{var I;k.current&&(clearInterval(k.current),k.current=null),!l.current&&!u.current&&((I=t.onNoLinksDetected)==null||I.call(t),u.current=!0)},z)}else W&&u.current&&!l.current&&(b.current&&(clearTimeout(b.current),b.current=null),l.current=!0,(j=t.onLinksDetected)==null||j.call(t,$.length),u.current=!0)}catch(M){const v=M instanceof Error?M:new Error(String(M));(O=t.onError)==null||O.call(t,v)}finally{s.current=!1}}},[e,o,t,_]),p=c.useCallback(()=>{const y=x.current;if(y.length<2){w.current=300;return}const C=[];for(let M=1;M<y.length;M++)C.push(y[M]-y[M-1]);const j=C.reduce((M,v)=>M+v,0)/C.length,O=Math.max(100,Math.min(j*3,1e3));w.current=O},[]);return c.useEffect(()=>{const y=document.getElementById(t.llmOutputContainerId);if(!y)return;g();const C=new MutationObserver(()=>{const j=Date.now();d.current=j,m.current=0,x.current.push(j),x.current.length>10&&x.current.shift(),p(),g()});return C.observe(y,{childList:!0,subtree:!0,characterData:!1}),()=>{C.disconnect(),b.current&&clearTimeout(b.current),k.current&&clearInterval(k.current)}},[t.llmOutputContainerId,g,p]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:l.current,shouldRenderFallback:!l.current&&u.current,processWeaveFormat:g}},cs="1.0.31";exports.AdMeshBadge=Sr;exports.AdMeshCompactCard=Mn;exports.AdMeshContext=jn;exports.AdMeshFollowup=_r;exports.AdMeshIntentAssistant=ns;exports.AdMeshLayout=pr;exports.AdMeshLinkTracker=kr;exports.AdMeshProvider=br;exports.AdMeshRecommendations=Qt;exports.AdMeshRenderer=yr;exports.AdMeshSDK=Xt;exports.AdMeshTailAd=ko;exports.AdMeshTracker=hr;exports.AdMeshViewabilityTracker=Jt;exports.STREAMING_COMPLETE_EVENT=ln;exports.STREAMING_START_EVENT=an;exports.VERSION=cs;exports.WeaveAdFormatContainer=as;exports.WeaveAdFormatProvider=bo;exports.WeaveFallbackRecommendations=wr;exports.WeaveResponseProcessor=Rn;exports.callAnalyzeIntentEndpoint=gr;exports.createInlineExposureTracker=cn;exports.dispatchStreamingCompleteEvent=os;exports.dispatchStreamingStartEvent=rs;exports.extractHeadingsDirectly=fr;exports.onStreamingComplete=jr;exports.onStreamingStart=ss;exports.useAdMesh=Ft;exports.useAdMeshContext=En;exports.useAdMeshStyles=Cr;exports.useViewabilityTracker=mr;exports.useWeaveAdFormat=ls;exports.useWeaveAdFormatContext=yo;
|
|
1065
1090
|
//# sourceMappingURL=index.js.map
|