admesh-ui-sdk 1.0.37 β†’ 1.0.38

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.
@@ -1 +1 @@
1
- {"version":3,"file":"AdMeshCompactCard.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshCompactCard.tsx"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,EAAE,EAAE,MAAM,OAAO,CAAC;AAI7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAqDxD,eAAO,MAAM,iBAAiB,EAAE,EAAE,CAAC,iBAAiB,CA2nBnD,CAAC;AAEF,eAAe,iBAAiB,CAAC"}
1
+ {"version":3,"file":"AdMeshCompactCard.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshCompactCard.tsx"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,EAAE,EAAE,MAAM,OAAO,CAAC;AAI7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAqDxD,eAAO,MAAM,iBAAiB,EAAE,EAAE,CAAC,iBAAiB,CAqoBnD,CAAC;AAEF,eAAe,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
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:`
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:"12px",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:"12px",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:{all:"initial",boxSizing:"border-box",display:"block",fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[r.jsx("style",{children:`
2
+ .admesh-compact-tail-ad,
3
+ .admesh-compact-tail-ad * {
4
+ box-sizing: border-box;
5
+ }
6
+
2
7
  .admesh-compact-line-clamp-1 {
3
8
  overflow: hidden;
4
9
  display: -webkit-box;
@@ -21,7 +26,7 @@
21
26
  .admesh-compact-tail-scroll::-webkit-scrollbar {
22
27
  display: none;
23
28
  }
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(`
29
+ `}),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:"14px",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:"11px",color:ne},children:He?p:""}),r.jsx("div",{style:{flexShrink:0,fontSize:"10px",color:ne,textTransform:"uppercase",letterSpacing:"0.08em"},children:v})]}),!N&&r.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",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:"12px",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:"12px",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:"12px",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:"12px",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:"10px",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:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:Se},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:_e,fontWeight:600},children:["Allow ",J||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",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:"12px",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:"12px",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
30
  `):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
31
  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:`
27
32
  .admesh-tail-product-scroll {