admesh-ui-sdk 1.0.25 โ†’ 1.0.26

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":"AdMeshEcommerceCards.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshEcommerceCards.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAKpE;;;;;;;;;GASG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,KAAK,EAAE,oBAAoB,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IAC5C,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC/B,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;IAClC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC3C,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,KAAK,IAAI,CAAC;CACnE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,EAAE,CAAC,yBAAyB,CAgcpE,CAAC;AAEF,eAAe,oBAAoB,CAAC"}
1
+ {"version":3,"file":"AdMeshEcommerceCards.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshEcommerceCards.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAKpE;;;;;;;;;GASG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,KAAK,EAAE,oBAAoB,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IAC5C,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC/B,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;IAClC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC3C,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,KAAK,IAAI,CAAC;CACnE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,EAAE,CAAC,yBAAyB,CA6cpE,CAAC;AAEF,eAAe,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var st=Object.defineProperty;var it=(t,e,n)=>e in t?st(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var te=(t,e,n)=>it(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),ze=require("react-dom/client"),Ge=require("react-dom");let fe=!1;var Qe;try{typeof globalThis.importMeta<"u"&&((Qe=globalThis.importMeta.env)!=null&&Qe.PROD)&&(fe=!0)}catch{}fe||(fe=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const o={log:(...t)=>{fe||console.log(...t)},warn:(...t)=>{fe||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{fe||console.info(...t)},debug:(...t)=>{fe||console.debug(...t)}};function dt(t,e,n){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...n}}function ct(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function lt(t){const e=t.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth,s=e.height,a=e.width;if(s===0||a===0)return 0;const i=Math.max(0,e.top),l=Math.min(n,e.bottom),p=Math.max(0,e.left),h=Math.min(r,e.right),c=Math.max(0,l-i),u=Math.max(0,h-p),_=c*u,f=s*a;return f>0?_/f:0}function Ve(){const t=window.innerHeight,e=document.documentElement.scrollHeight,n=window.pageYOffset||document.documentElement.scrollTop,r=e-t;return r<=0?100:Math.min(100,n/r*100)}function mt(t){const e=t.getBoundingClientRect(),n=window.pageYOffset||document.documentElement.scrollTop,r=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+n,left:e.left+r}}function ut(t){const e=t.getBoundingClientRect(),n=mt(t),r=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,a=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ct(r),viewportWidth:r,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:n.top,adPositionLeft:n.left,isDarkMode:a,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function pt(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function ht(t,e,n){return t>=n.visibilityThreshold&&e>=n.minimumDuration}function He(t=new Date){return t.toISOString()}function gt(t){return t.length===0?0:t.reduce((n,r)=>n+r,0)/t.length}function Ke(t,e){let n;return function(...s){n||(t(...s),n=!0,setTimeout(()=>n=!1,e))}}const ft={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let bt=ft;function Ye({productId:t,offerId:e,agentId:n,recommendationId:r,elementRef:s,config:a}){const i={...bt,...a},l=m.useRef(pt()),[p,h]=m.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:He(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:i.enabled}),c=m.useRef(null),u=m.useRef(null),_=m.useRef(null),f=m.useRef(null),b=m.useRef(null),k=m.useRef([]),y=m.useRef([]),g=m.useRef(null),C=m.useCallback(v=>{i.debug&&o.log(`[AdMesh Viewability] ${v}`)},[i.debug]),x=m.useCallback(async(v,T)=>{if(!(!i.enabled||!s.current||!c.current)&&(C(`Analytics disabled - skipping event: ${v}`),i.onEvent)){const w=ut(s.current),I={eventType:v,timestamp:He(),sessionId:l.current,productId:t,offerId:e,agentId:n,recommendationId:r,timeMetrics:p.timeMetrics,engagementMetrics:p.engagementMetrics,contextMetrics:w,mrcStandards:c.current,isViewable:p.isViewable,metadata:T};i.onEvent(I)}},[i,t,e,n,r,s,p,C]),N=m.useCallback(async()=>{y.current.length!==0&&(C("Analytics disabled - clearing batch without sending"),y.current=[],g.current&&(clearTimeout(g.current),g.current=null))},[C]),E=m.useCallback(Ke(()=>{if(!s.current)return;const v=lt(s.current),T=Date.now(),w=new Date(p.timeMetrics.loadedAt).getTime();h(I=>{const S={...I};v>0&&k.current.push(v);const R=I.isVisible,M=v>0;if(M&&!R)u.current=T,S.engagementMetrics.viewportEnterCount++,S.timeMetrics.timeToFirstVisible||(S.timeMetrics.timeToFirstVisible=T-w,S.engagementMetrics.scrollDepthAtFirstVisible=Ve(),x("ad_visible"));else if(!M&&R){if(u.current){const D=T-u.current;S.timeMetrics.totalVisibleDuration+=D,u.current=null}S.engagementMetrics.viewportExitCount++,x("ad_hidden")}else if(M&&R&&u.current){const D=T-u.current;S.timeMetrics.totalVisibleDuration+=D,u.current=T}if(S.isVisible=M,S.visibilityPercentage=v,v>S.engagementMetrics.maxVisibilityPercentage&&(S.engagementMetrics.maxVisibilityPercentage=v),k.current.length>0&&(S.engagementMetrics.averageVisibilityPercentage=gt(k.current)),c.current){const D=I.isViewable,A=ht(v,S.timeMetrics.totalVisibleDuration,c.current);if(A&&!D)S.isViewable=!0,S.timeMetrics.timeToViewable=T-w,_.current=T,x("ad_viewable");else if(A&&D&&_.current){const j=T-_.current;S.timeMetrics.totalViewableDuration+=j,_.current=T}}return S.engagementMetrics.currentScrollDepth=Ve(),S})},100),[s,p.timeMetrics.loadedAt,x]);return m.useEffect(()=>{if(!s.current)return;const v=s.current.getBoundingClientRect();c.current=dt(v.width,v.height,i.mrcStandards),C("Initialized MRC standards"),x("ad_loaded")},[s,i.mrcStandards,C,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=new IntersectionObserver(T=>{T.forEach(()=>{E()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return v.observe(s.current),()=>{v.disconnect()}},[i.enabled,s,E]),m.useEffect(()=>{if(!i.enabled)return;const v=Ke(()=>{E()},100);return window.addEventListener("scroll",v,{passive:!0}),()=>window.removeEventListener("scroll",v)},[i.enabled,E]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,T=()=>{f.current=Date.now(),h(I=>({...I,engagementMetrics:{...I.engagementMetrics,hoverCount:I.engagementMetrics.hoverCount+1}})),x("ad_hover_start")},w=()=>{if(f.current){const I=Date.now()-f.current;h(S=>({...S,timeMetrics:{...S.timeMetrics,totalHoverDuration:S.timeMetrics.totalHoverDuration+I}})),f.current=null,x("ad_hover_end",{hoverDuration:I})}};return v.addEventListener("mouseenter",T),v.addEventListener("mouseleave",w),()=>{v.removeEventListener("mouseenter",T),v.removeEventListener("mouseleave",w)}},[i.enabled,s,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,T=()=>{b.current=Date.now(),x("ad_focus")},w=()=>{if(b.current){const I=Date.now()-b.current;h(S=>({...S,timeMetrics:{...S.timeMetrics,totalFocusDuration:S.timeMetrics.totalFocusDuration+I}})),b.current=null,x("ad_blur",{focusDuration:I})}};return v.addEventListener("focus",T),v.addEventListener("blur",w),()=>{v.removeEventListener("focus",T),v.removeEventListener("blur",w)}},[i.enabled,s,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,T=()=>{h(w=>({...w,engagementMetrics:{...w.engagementMetrics,wasClicked:!0}})),x("ad_click")};return v.addEventListener("click",T),()=>{v.removeEventListener("click",T)}},[i.enabled,s,x]),m.useEffect(()=>()=>{const v=Date.now(),T=new Date(p.timeMetrics.loadedAt).getTime(),w=v-T;h(I=>({...I,timeMetrics:{...I.timeMetrics,sessionDuration:w}})),x("ad_unloaded",{sessionDuration:w}),N()},[]),p}const ke=({productId:t,offerId:e,agentId:n,recommendationId:r,exposureUrl:s,sessionId:a,children:i,config:l,className:p,style:h,onViewabilityChange:c,onVisible:u,onViewable:_,onClick:f})=>{const b=m.useRef(null),k=m.useRef(!1),y=Ye({productId:t,offerId:e,agentId:n,recommendationId:r,elementRef:b,config:l}),g=m.useRef(y.isViewable);m.useEffect(()=>{y.isViewable!==g.current&&(g.current=y.isViewable,c&&c(y.isViewable),y.isViewable&&_&&_(),y.isViewable&&!k.current&&(o.log("[AdMeshViewabilityTracker] ๐ŸŽฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:s?"present":"MISSING",sessionId:a?"present":"MISSING",recommendationId:r}),s&&a?(k.current=!0,o.log("[AdMeshViewabilityTracker] ๐Ÿ”ฅ Firing exposure pixel:",s),fetch(s,{method:"GET",keepalive:!0}).then(()=>{o.log("[AdMesh] โœ… Exposure pixel fired successfully")}).catch(N=>{o.warn("[AdMesh] โš ๏ธ Failed to fire exposure pixel:",N),k.current=!1})):o.warn("[AdMeshViewabilityTracker] โš ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!s,hasSessionId:!!a})))},[y.isViewable,c,_,s,a,r]);const C=m.useRef(y.isVisible);m.useEffect(()=>{y.isVisible!==C.current&&(C.current=y.isVisible,y.isVisible&&u&&u())},[y.isVisible,u]);const x=()=>{f&&f()};return d.jsx("div",{ref:b,className:p,style:h,onClick:x,"data-admesh-viewability-tracker":!0,"data-recommendation-id":r,"data-is-viewable":y.isViewable,"data-is-visible":y.isVisible,"data-visibility-percentage":y.visibilityPercentage.toFixed(2),children:i})};ke.displayName="AdMeshViewabilityTracker";const Ee=m.createContext(void 0);function Ze(){const t=m.useContext(Ee);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}const xt=t=>{try{return new URL(t),!0}catch{return!1}},vt=t=>t&&t.trim()?t.trim():"",Pe=({recommendations:t,theme:e,className:n="",style:r={},sessionId:s})=>{var Y,se,ae,ie,oe,B,pe,xe,de,le,ve;const a=m.useContext(Ee),i=a==null?void 0:a.userId,l=a==null?void 0:a.model,p=a==null?void 0:a.sessionId,h=(a==null?void 0:a.sdk)||null,c=s||p,[u,_]=m.useState(!1),[f,b]=m.useState(!1),[k,y]=m.useState(!1);if(!t||t.length===0)return o.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;if(u)return null;const g=t[0],C=g==null?void 0:g.product_id,x=g==null?void 0:g.exposure_url,N=(g==null?void 0:g.recommendation_id)||"",E=(g==null?void 0:g.creative_input)||{},v=E.short_description||"",T=E.offer_summary||"",w=E.brand_name||(g==null?void 0:g.title)||"",I=E.product_name||"",R=(E.assets||{}).logo_url||"",M=(g==null?void 0:g.click_url)||(g==null?void 0:g.admesh_link)||E.cta_url||(g==null?void 0:g.url),D=vt(E.cta_label);if(!w)return o.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brandName is missing",brandName:w,hasFirstRecommendation:!!g,hasCreativeInput:!!E,creativeInputBrandName:E.brand_name,recommendationTitle:g==null?void 0:g.title,recommendationId:N,recommendationKeys:g?Object.keys(g):[]}),null;let A=w,j="";T?j=T:I&&(j=I),j&&(A=`${w} โ€” ${j}`),o.debug("[AdMeshTailAd] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:N,productId:C,exposureUrl:x?"present":"MISSING",sessionId:s?"present":"MISSING",recommendationsCount:t.length,clickUrl:M||"MISSING",clickUrlSource:g!=null&&g.click_url?"click_url":g!=null&&g.admesh_link?"admesh_link":E.cta_url?"cta_url":g!=null&&g.url?"url":"none",shortDescription:v?"present":"MISSING",offerSummary:T||"MISSING",brandName:w,productName:I,headlineText:A});const Q=(L,J)=>{o.log(`AdMesh tail ad ${L} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:g.recommendation_id,productId:g.product_id,clickUrl:M,source:L}).catch(()=>{o.error(`[AdMesh] Failed to track ${L} click`)})},G=L=>{L.stopPropagation(),Q("tail_ad_brand_name")},X=L=>{L.stopPropagation(),Q("tail_ad_cta")},re=L=>{L.stopPropagation(),Q("tail_ad_logo")},q=()=>h&&typeof h.getApiBaseUrl=="function"?h.getApiBaseUrl():h&&h.apiBaseUrl?h.apiBaseUrl:typeof window<"u"&&window.__ADMESH_API_BASE_URL__?window.__ADMESH_API_BASE_URL__:"https://api.useadmesh.com",ne=async L=>{if(!(f||k)){y(!0);try{const J=q(),he=(g==null?void 0:g.agent_id)||"",ge={message_index:0,feedback:L,session_id:c||null,user_id:i||null,agent_id:he||null,model_used:l||null,recommendationId:N||null},we=`${J}/user/feedback/submit`;o.log(`[AdMesh Tail Ad] Submitting feedback: ${L}`,{endpoint:we,payload:ge});const ee=await fetch(we,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ge)});if(o.log(`[AdMesh Tail Ad] Feedback response status: ${ee.status} ${ee.statusText}`),!ee.ok){let Ae=`Feedback submission failed: ${ee.status} ${ee.statusText}`;try{const me=await ee.json().catch(()=>null);me!=null&&me.detail&&(Ae=`Feedback submission failed: ${me.detail}`),o.error("[AdMesh Tail Ad] Error response body:",me)}catch{}throw new Error(Ae)}const ye=await ee.json();o.log(`[AdMesh Tail Ad] โœ… Feedback submitted successfully: ${L}`,ye),b(!0),L==="dislike"&&_(!0)}catch(J){const he=J instanceof Error?{message:J.message,name:J.name,stack:J.stack}:String(J);o.error(`[AdMesh Tail Ad] โŒ Failed to submit feedback: ${L}`,{error:he,apiBaseUrl:q(),endpoint:`${q()}/user/feedback/submit`}),y(!1)}}},F=L=>{L.stopPropagation(),L.preventDefault(),ne("like")},U=L=>{L.stopPropagation(),L.preventDefault(),ne("dislike")},[ce,ue]=m.useState(!1),z=w?w.charAt(0).toUpperCase():"B",V=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,P=(e==null?void 0:e.surfaceColor)||((se=(Y=e==null?void 0:e.components)==null?void 0:Y.card)==null?void 0:se.backgroundColor)||(V?"#1f2937":"#ffffff"),W=(e==null?void 0:e.borderColor)||((ie=(ae=e==null?void 0:e.components)==null?void 0:ae.card)==null?void 0:ie.borderColor)||(V?"rgba(255, 255, 255, 0.1)":"rgba(0, 0, 0, 0.05)"),H=(e==null?void 0:e.borderRadius)||((B=(oe=e==null?void 0:e.components)==null?void 0:oe.card)==null?void 0:B.borderRadius)||"8px",Z=V?"0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2)":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",K=V?"0 10px 15px -3px rgba(0, 0, 0, 0.4), 0 4px 6px -2px rgba(0, 0, 0, 0.3)":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",$=((pe=e==null?void 0:e.shadows)==null?void 0:pe.medium)||((de=(xe=e==null?void 0:e.components)==null?void 0:xe.card)==null?void 0:de.boxShadow)||Z,O=((le=e==null?void 0:e.shadows)==null?void 0:le.large)||K;return d.jsx(ke,{productId:C,recommendationId:N,exposureUrl:x,sessionId:s,className:`admesh-tail-ad ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...r},children:d.jsxs("div",{className:"tail-ad-container flex flex-row gap-3",style:{backgroundColor:P,borderRadius:H,padding:"16px",boxShadow:$,border:`1px solid ${W}`,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",...(ve=e==null?void 0:e.components)==null?void 0:ve.card},onMouseEnter:L=>{L.currentTarget.style.boxShadow=O,L.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:L=>{L.currentTarget.style.boxShadow=$,L.currentTarget.style.transform="translateY(0)"},children:[R&&d.jsx("div",{className:"flex-shrink-0 flex items-center justify-center pr-2",style:{width:"10%",minWidth:"48px"},children:!ce&&xt(R)?d.jsx("a",{href:M||"#",target:M?"_blank":void 0,rel:M?"noopener noreferrer":void 0,onClick:M?re:void 0,className:"block",style:{cursor:M?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:d.jsx("img",{src:R,alt:`${w} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{ue(!0),o.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):d.jsx("div",{className:"flex items-center justify-center text-lg font-semibold text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-800",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px"},children:z})}),d.jsxs("div",{className:"flex-1",style:{width:R?"90%":"100%",minWidth:0},children:[A&&d.jsx("div",{className:"mb-2",children:d.jsx("h3",{className:"text-black dark:text-white font-semibold text-base",style:{fontSize:"0.7rem"},children:M&&w?d.jsxs(d.Fragment,{children:[d.jsx("a",{href:M,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-semibold",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:G,children:w}),j&&` โ€” ${j}`]}):A})}),v&&d.jsx("p",{className:"text-gray-700 dark:text-gray-300 text-sm mb-3 leading-relaxed",style:{fontSize:"0.7rem"},children:v}),d.jsxs("div",{className:"flex items-center justify-between mt-2",children:[d.jsx("div",{className:"flex items-center gap-2",children:D&&M&&d.jsx("a",{href:M,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium text-sm",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:X,children:D})}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:F,disabled:f||k,"aria-label":"Mark as helpful",className:"flex items-center justify-center px-2 py-1 rounded transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",style:{color:f&&!u?"#10b981":V?"#9ca3af":"#6b7280",backgroundColor:"transparent",border:"none",cursor:f||k?"not-allowed":"pointer",fontSize:"0.75rem",fontWeight:"500",minHeight:"24px"},onMouseEnter:L=>{!f&&!k&&(L.currentTarget.style.color="#10b981",L.currentTarget.style.backgroundColor="rgba(16, 185, 129, 0.1)")},onMouseLeave:L=>{f||(L.currentTarget.style.color=f?"#10b981":V?"#9ca3af":"#6b7280",L.currentTarget.style.backgroundColor="transparent")},children:"Helpful"}),d.jsx("button",{onClick:U,disabled:f||k,"aria-label":"Mark as not helpful",className:"flex items-center justify-center px-2 py-1 rounded transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",style:{color:u?"#ef4444":V?"#9ca3af":"#6b7280",backgroundColor:"transparent",border:"none",cursor:f||k?"not-allowed":"pointer",fontSize:"0.75rem",fontWeight:"500",minHeight:"24px"},onMouseEnter:L=>{!f&&!k&&(L.currentTarget.style.color="#ef4444",L.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)")},onMouseLeave:L=>{u||(L.currentTarget.style.color=V?"#9ca3af":"#6b7280",L.currentTarget.style.backgroundColor="transparent")},children:"Not Helpful"}),d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})]})]})]})]})})};function be(){const t=Ze();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,language:t.language,geo_country:t.geo_country,userId:t.userId,model:t.model,messages:t.messages,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const wt=(t,e)=>{if(!t)return"Get Started";let n="";const r=[/(?:set up|setup|integrate|add|install|use)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,| by)/i,/(?:by|from)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,)/];for(const i of r){const l=t.match(i);if(l&&l[1]){n=l[1].trim();break}}const s=e||n;if(s)return`Integrate ${s.split(/\s+/).slice(0,2).join(" ")}`;const a=t.match(/to\s+set\s+up\s+([a-zA-Z0-9\s]+?)(?:\s+by|\s*[.,]|$)/i);return a&&a[1]?`Integrate ${a[1].trim().split(/\s+/).slice(0,2).join(" ")}`:"Integrate"},je=({recommendation:t,theme:e,className:n="",style:r={},sessionId:s,onLinkClick:a,onPasteToInput:i})=>{var E,v,T,w,I,S,R;const l=t.creative_input||{},p=l.bridge_headline||"",h=l.bridge_description||"",c=l.bridge_prompt||l.bridge_content||"",u=l.product_name||"",_=l.cta_label||"";if(!h&&!c)return null;const f=t.product_id||"",b=t.recommendation_id||"",{sdk:k,sessionId:y}=be(),g=s||y,C=async M=>{if(M.preventDefault(),!!c){if(b&&g)try{const D=(k==null?void 0:k.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",A=await fetch(`${D}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:b,session_id:g,agent_id:t.agent_id,user_id:t.user_id||void 0,is_test:!1})});A.ok?o.log("[AdMesh Bridge] โœ… Engagement tracked successfully"):o.warn("[AdMesh Bridge] โš ๏ธ Failed to track engagement:",A.statusText)}catch(D){o.error("[AdMesh Bridge] โŒ Error tracking engagement:",D)}a&&a(t),i?i(c):typeof window<"u"&&window.__admesh_setMessage&&window.__admesh_setMessage(c)}},x=_||wt(c,u),N=!!x;return d.jsx(ke,{productId:f,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:s,className:`admesh-bridge-format ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',padding:"1rem",border:"none",borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",backgroundColor:"transparent",color:(e==null?void 0:e.textColor)||"inherit",...r},children:d.jsxs("div",{"data-admesh-theme":(e==null?void 0:e.mode)||"light",children:[p&&d.jsx("div",{className:"admesh-bridge-headline",style:{marginBottom:h?"0.75rem":N?"1rem":"0",fontSize:((E=e==null?void 0:e.fontSize)==null?void 0:E.large)||"1rem",fontWeight:600,color:(e==null?void 0:e.textColor)||"inherit",lineHeight:"1.4"},children:p}),h&&d.jsx("div",{className:"admesh-bridge-description",style:{marginBottom:N||(v=t.creative_input)!=null&&v.offer_summary?"1rem":"0",lineHeight:"1.6",fontSize:((T=e==null?void 0:e.fontSize)==null?void 0:T.base)||"0.875rem",color:(e==null?void 0:e.textColor)||"inherit"},children:h}),((w=t.creative_input)==null?void 0:w.offer_summary)&&d.jsx("div",{className:"admesh-bridge-offer-summary",style:{marginBottom:N?"1rem":"0",lineHeight:"1.5",fontSize:((I=e==null?void 0:e.fontSize)==null?void 0:I.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:t.creative_input.offer_summary}),N&&d.jsx("div",{style:{marginBottom:"0.75rem"},children:d.jsx("button",{onClick:C,className:"admesh-bridge-cta-button",style:{padding:"0.5rem 1rem",backgroundColor:"#000000",color:"#ffffff",fontSize:((S=e==null?void 0:e.fontSize)==null?void 0:S.small)||"0.875rem",fontWeight:500,borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",border:"none",cursor:"pointer",transition:"background-color 0.2s, opacity 0.2s"},onMouseEnter:M=>{M.currentTarget.style.backgroundColor="#1a1a1a",M.currentTarget.style.opacity="0.9"},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="#000000",M.currentTarget.style.opacity="1"},children:x})}),d.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"0.5rem"},children:d.jsx("div",{className:"admesh-bridge-label",style:{fontSize:((R=e==null?void 0:e.fontSize)==null?void 0:R.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:"Sponsored"})})]})})};function yt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fe={exports:{}};/*!
1
+ "use strict";var st=Object.defineProperty;var it=(t,e,n)=>e in t?st(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var te=(t,e,n)=>it(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),ze=require("react-dom/client"),Ge=require("react-dom");let fe=!1;var Qe;try{typeof globalThis.importMeta<"u"&&((Qe=globalThis.importMeta.env)!=null&&Qe.PROD)&&(fe=!0)}catch{}fe||(fe=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const o={log:(...t)=>{fe||console.log(...t)},warn:(...t)=>{fe||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{fe||console.info(...t)},debug:(...t)=>{fe||console.debug(...t)}};function dt(t,e,n){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...n}}function ct(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function lt(t){const e=t.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth,s=e.height,a=e.width;if(s===0||a===0)return 0;const i=Math.max(0,e.top),l=Math.min(n,e.bottom),p=Math.max(0,e.left),h=Math.min(r,e.right),c=Math.max(0,l-i),u=Math.max(0,h-p),_=c*u,f=s*a;return f>0?_/f:0}function Ve(){const t=window.innerHeight,e=document.documentElement.scrollHeight,n=window.pageYOffset||document.documentElement.scrollTop,r=e-t;return r<=0?100:Math.min(100,n/r*100)}function mt(t){const e=t.getBoundingClientRect(),n=window.pageYOffset||document.documentElement.scrollTop,r=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+n,left:e.left+r}}function ut(t){const e=t.getBoundingClientRect(),n=mt(t),r=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,a=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ct(r),viewportWidth:r,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:n.top,adPositionLeft:n.left,isDarkMode:a,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function pt(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function ht(t,e,n){return t>=n.visibilityThreshold&&e>=n.minimumDuration}function He(t=new Date){return t.toISOString()}function gt(t){return t.length===0?0:t.reduce((n,r)=>n+r,0)/t.length}function Ke(t,e){let n;return function(...s){n||(t(...s),n=!0,setTimeout(()=>n=!1,e))}}const ft={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let bt=ft;function Ye({productId:t,offerId:e,agentId:n,recommendationId:r,elementRef:s,config:a}){const i={...bt,...a},l=m.useRef(pt()),[p,h]=m.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:He(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:i.enabled}),c=m.useRef(null),u=m.useRef(null),_=m.useRef(null),f=m.useRef(null),b=m.useRef(null),k=m.useRef([]),y=m.useRef([]),g=m.useRef(null),T=m.useCallback(v=>{i.debug&&o.log(`[AdMesh Viewability] ${v}`)},[i.debug]),x=m.useCallback(async(v,F)=>{if(!(!i.enabled||!s.current||!c.current)&&(T(`Analytics disabled - skipping event: ${v}`),i.onEvent)){const w=ut(s.current),I={eventType:v,timestamp:He(),sessionId:l.current,productId:t,offerId:e,agentId:n,recommendationId:r,timeMetrics:p.timeMetrics,engagementMetrics:p.engagementMetrics,contextMetrics:w,mrcStandards:c.current,isViewable:p.isViewable,metadata:F};i.onEvent(I)}},[i,t,e,n,r,s,p,T]),N=m.useCallback(async()=>{y.current.length!==0&&(T("Analytics disabled - clearing batch without sending"),y.current=[],g.current&&(clearTimeout(g.current),g.current=null))},[T]),E=m.useCallback(Ke(()=>{if(!s.current)return;const v=lt(s.current),F=Date.now(),w=new Date(p.timeMetrics.loadedAt).getTime();h(I=>{const S={...I};v>0&&k.current.push(v);const R=I.isVisible,M=v>0;if(M&&!R)u.current=F,S.engagementMetrics.viewportEnterCount++,S.timeMetrics.timeToFirstVisible||(S.timeMetrics.timeToFirstVisible=F-w,S.engagementMetrics.scrollDepthAtFirstVisible=Ve(),x("ad_visible"));else if(!M&&R){if(u.current){const D=F-u.current;S.timeMetrics.totalVisibleDuration+=D,u.current=null}S.engagementMetrics.viewportExitCount++,x("ad_hidden")}else if(M&&R&&u.current){const D=F-u.current;S.timeMetrics.totalVisibleDuration+=D,u.current=F}if(S.isVisible=M,S.visibilityPercentage=v,v>S.engagementMetrics.maxVisibilityPercentage&&(S.engagementMetrics.maxVisibilityPercentage=v),k.current.length>0&&(S.engagementMetrics.averageVisibilityPercentage=gt(k.current)),c.current){const D=I.isViewable,A=ht(v,S.timeMetrics.totalVisibleDuration,c.current);if(A&&!D)S.isViewable=!0,S.timeMetrics.timeToViewable=F-w,_.current=F,x("ad_viewable");else if(A&&D&&_.current){const j=F-_.current;S.timeMetrics.totalViewableDuration+=j,_.current=F}}return S.engagementMetrics.currentScrollDepth=Ve(),S})},100),[s,p.timeMetrics.loadedAt,x]);return m.useEffect(()=>{if(!s.current)return;const v=s.current.getBoundingClientRect();c.current=dt(v.width,v.height,i.mrcStandards),T("Initialized MRC standards"),x("ad_loaded")},[s,i.mrcStandards,T,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=new IntersectionObserver(F=>{F.forEach(()=>{E()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return v.observe(s.current),()=>{v.disconnect()}},[i.enabled,s,E]),m.useEffect(()=>{if(!i.enabled)return;const v=Ke(()=>{E()},100);return window.addEventListener("scroll",v,{passive:!0}),()=>window.removeEventListener("scroll",v)},[i.enabled,E]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,F=()=>{f.current=Date.now(),h(I=>({...I,engagementMetrics:{...I.engagementMetrics,hoverCount:I.engagementMetrics.hoverCount+1}})),x("ad_hover_start")},w=()=>{if(f.current){const I=Date.now()-f.current;h(S=>({...S,timeMetrics:{...S.timeMetrics,totalHoverDuration:S.timeMetrics.totalHoverDuration+I}})),f.current=null,x("ad_hover_end",{hoverDuration:I})}};return v.addEventListener("mouseenter",F),v.addEventListener("mouseleave",w),()=>{v.removeEventListener("mouseenter",F),v.removeEventListener("mouseleave",w)}},[i.enabled,s,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,F=()=>{b.current=Date.now(),x("ad_focus")},w=()=>{if(b.current){const I=Date.now()-b.current;h(S=>({...S,timeMetrics:{...S.timeMetrics,totalFocusDuration:S.timeMetrics.totalFocusDuration+I}})),b.current=null,x("ad_blur",{focusDuration:I})}};return v.addEventListener("focus",F),v.addEventListener("blur",w),()=>{v.removeEventListener("focus",F),v.removeEventListener("blur",w)}},[i.enabled,s,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,F=()=>{h(w=>({...w,engagementMetrics:{...w.engagementMetrics,wasClicked:!0}})),x("ad_click")};return v.addEventListener("click",F),()=>{v.removeEventListener("click",F)}},[i.enabled,s,x]),m.useEffect(()=>()=>{const v=Date.now(),F=new Date(p.timeMetrics.loadedAt).getTime(),w=v-F;h(I=>({...I,timeMetrics:{...I.timeMetrics,sessionDuration:w}})),x("ad_unloaded",{sessionDuration:w}),N()},[]),p}const ke=({productId:t,offerId:e,agentId:n,recommendationId:r,exposureUrl:s,sessionId:a,children:i,config:l,className:p,style:h,onViewabilityChange:c,onVisible:u,onViewable:_,onClick:f})=>{const b=m.useRef(null),k=m.useRef(!1),y=Ye({productId:t,offerId:e,agentId:n,recommendationId:r,elementRef:b,config:l}),g=m.useRef(y.isViewable);m.useEffect(()=>{y.isViewable!==g.current&&(g.current=y.isViewable,c&&c(y.isViewable),y.isViewable&&_&&_(),y.isViewable&&!k.current&&(o.log("[AdMeshViewabilityTracker] ๐ŸŽฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:s?"present":"MISSING",sessionId:a?"present":"MISSING",recommendationId:r}),s&&a?(k.current=!0,o.log("[AdMeshViewabilityTracker] ๐Ÿ”ฅ Firing exposure pixel:",s),fetch(s,{method:"GET",keepalive:!0}).then(()=>{o.log("[AdMesh] โœ… Exposure pixel fired successfully")}).catch(N=>{o.warn("[AdMesh] โš ๏ธ Failed to fire exposure pixel:",N),k.current=!1})):o.warn("[AdMeshViewabilityTracker] โš ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!s,hasSessionId:!!a})))},[y.isViewable,c,_,s,a,r]);const T=m.useRef(y.isVisible);m.useEffect(()=>{y.isVisible!==T.current&&(T.current=y.isVisible,y.isVisible&&u&&u())},[y.isVisible,u]);const x=()=>{f&&f()};return d.jsx("div",{ref:b,className:p,style:h,onClick:x,"data-admesh-viewability-tracker":!0,"data-recommendation-id":r,"data-is-viewable":y.isViewable,"data-is-visible":y.isVisible,"data-visibility-percentage":y.visibilityPercentage.toFixed(2),children:i})};ke.displayName="AdMeshViewabilityTracker";const Ee=m.createContext(void 0);function Ze(){const t=m.useContext(Ee);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}const xt=t=>{try{return new URL(t),!0}catch{return!1}},vt=t=>t&&t.trim()?t.trim():"",Pe=({recommendations:t,theme:e,className:n="",style:r={},sessionId:s})=>{var Q,ie,se,de,oe,U,pe,xe,ce,me,ve;const a=m.useContext(Ee),i=a==null?void 0:a.userId,l=a==null?void 0:a.model,p=a==null?void 0:a.sessionId,h=(a==null?void 0:a.sdk)||null,c=s||p,[u,_]=m.useState(!1),[f,b]=m.useState(!1),[k,y]=m.useState(!1);if(!t||t.length===0)return o.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;if(u)return null;const g=t[0],T=g==null?void 0:g.product_id,x=g==null?void 0:g.exposure_url,N=(g==null?void 0:g.recommendation_id)||"",E=(g==null?void 0:g.creative_input)||{},v=E.short_description||"",F=E.offer_summary||"",w=E.brand_name||(g==null?void 0:g.title)||"",I=E.product_name||"",R=(E.assets||{}).logo_url||"",M=(g==null?void 0:g.click_url)||(g==null?void 0:g.admesh_link)||E.cta_url||(g==null?void 0:g.url),D=vt(E.cta_label);if(!w)return o.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brandName is missing",brandName:w,hasFirstRecommendation:!!g,hasCreativeInput:!!E,creativeInputBrandName:E.brand_name,recommendationTitle:g==null?void 0:g.title,recommendationId:N,recommendationKeys:g?Object.keys(g):[]}),null;let A=w,j="";F?j=F:I&&(j=I),j&&(A=`${w} โ€” ${j}`),o.debug("[AdMeshTailAd] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:N,productId:T,exposureUrl:x?"present":"MISSING",sessionId:s?"present":"MISSING",recommendationsCount:t.length,clickUrl:M||"MISSING",clickUrlSource:g!=null&&g.click_url?"click_url":g!=null&&g.admesh_link?"admesh_link":E.cta_url?"cta_url":g!=null&&g.url?"url":"none",shortDescription:v?"present":"MISSING",offerSummary:F||"MISSING",brandName:w,productName:I,headlineText:A});const G=(L,J)=>{o.log(`AdMesh tail ad ${L} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:g.recommendation_id,productId:g.product_id,clickUrl:M,source:L}).catch(()=>{o.error(`[AdMesh] Failed to track ${L} click`)})},Y=L=>{L.stopPropagation(),G("tail_ad_brand_name")},X=L=>{L.stopPropagation(),G("tail_ad_cta")},re=L=>{L.stopPropagation(),G("tail_ad_logo")},q=()=>h&&typeof h.getApiBaseUrl=="function"?h.getApiBaseUrl():h&&h.apiBaseUrl?h.apiBaseUrl:typeof window<"u"&&window.__ADMESH_API_BASE_URL__?window.__ADMESH_API_BASE_URL__:"https://api.useadmesh.com",ne=async L=>{if(!(f||k)){y(!0);try{const J=q(),he=(g==null?void 0:g.agent_id)||"",ge={message_index:0,feedback:L,session_id:c||null,user_id:i||null,agent_id:he||null,model_used:l||null,recommendationId:N||null},we=`${J}/user/feedback/submit`;o.log(`[AdMesh Tail Ad] Submitting feedback: ${L}`,{endpoint:we,payload:ge});const ee=await fetch(we,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ge)});if(o.log(`[AdMesh Tail Ad] Feedback response status: ${ee.status} ${ee.statusText}`),!ee.ok){let Ae=`Feedback submission failed: ${ee.status} ${ee.statusText}`;try{const ue=await ee.json().catch(()=>null);ue!=null&&ue.detail&&(Ae=`Feedback submission failed: ${ue.detail}`),o.error("[AdMesh Tail Ad] Error response body:",ue)}catch{}throw new Error(Ae)}const ye=await ee.json();o.log(`[AdMesh Tail Ad] โœ… Feedback submitted successfully: ${L}`,ye),b(!0),L==="dislike"&&_(!0)}catch(J){const he=J instanceof Error?{message:J.message,name:J.name,stack:J.stack}:String(J);o.error(`[AdMesh Tail Ad] โŒ Failed to submit feedback: ${L}`,{error:he,apiBaseUrl:q(),endpoint:`${q()}/user/feedback/submit`}),y(!1)}}},C=L=>{L.stopPropagation(),L.preventDefault(),ne("like")},B=L=>{L.stopPropagation(),L.preventDefault(),ne("dislike")},[ae,le]=m.useState(!1),$=w?w.charAt(0).toUpperCase():"B",z=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,P=(e==null?void 0:e.surfaceColor)||((ie=(Q=e==null?void 0:e.components)==null?void 0:Q.card)==null?void 0:ie.backgroundColor)||(z?"#1f2937":"#ffffff"),W=(e==null?void 0:e.borderColor)||((de=(se=e==null?void 0:e.components)==null?void 0:se.card)==null?void 0:de.borderColor)||(z?"rgba(255, 255, 255, 0.1)":"rgba(0, 0, 0, 0.05)"),K=(e==null?void 0:e.borderRadius)||((U=(oe=e==null?void 0:e.components)==null?void 0:oe.card)==null?void 0:U.borderRadius)||"8px",Z=z?"0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2)":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",O=z?"0 10px 15px -3px rgba(0, 0, 0, 0.4), 0 4px 6px -2px rgba(0, 0, 0, 0.3)":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",V=((pe=e==null?void 0:e.shadows)==null?void 0:pe.medium)||((ce=(xe=e==null?void 0:e.components)==null?void 0:xe.card)==null?void 0:ce.boxShadow)||Z,H=((me=e==null?void 0:e.shadows)==null?void 0:me.large)||O;return d.jsx(ke,{productId:T,recommendationId:N,exposureUrl:x,sessionId:s,className:`admesh-tail-ad ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...r},children:d.jsxs("div",{className:"tail-ad-container flex flex-row gap-3",style:{backgroundColor:P,borderRadius:K,padding:"16px",boxShadow:V,border:`1px solid ${W}`,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",...(ve=e==null?void 0:e.components)==null?void 0:ve.card},onMouseEnter:L=>{L.currentTarget.style.boxShadow=H,L.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:L=>{L.currentTarget.style.boxShadow=V,L.currentTarget.style.transform="translateY(0)"},children:[R&&d.jsx("div",{className:"flex-shrink-0 flex items-center justify-center pr-2",style:{width:"10%",minWidth:"48px"},children:!ae&&xt(R)?d.jsx("a",{href:M||"#",target:M?"_blank":void 0,rel:M?"noopener noreferrer":void 0,onClick:M?re:void 0,className:"block",style:{cursor:M?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:d.jsx("img",{src:R,alt:`${w} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{le(!0),o.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):d.jsx("div",{className:"flex items-center justify-center text-lg font-semibold text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-800",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px"},children:$})}),d.jsxs("div",{className:"flex-1",style:{width:R?"90%":"100%",minWidth:0},children:[A&&d.jsx("div",{className:"mb-2",children:d.jsx("h3",{className:"text-black dark:text-white font-semibold text-base",style:{fontSize:"0.7rem"},children:M&&w?d.jsxs(d.Fragment,{children:[d.jsx("a",{href:M,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-semibold",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:Y,children:w}),j&&` โ€” ${j}`]}):A})}),v&&d.jsx("p",{className:"text-gray-700 dark:text-gray-300 text-sm mb-3 leading-relaxed",style:{fontSize:"0.7rem"},children:v}),d.jsxs("div",{className:"flex items-center justify-between mt-2",children:[d.jsx("div",{className:"flex items-center gap-2",children:D&&M&&d.jsx("a",{href:M,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium text-sm",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:X,children:D})}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:C,disabled:f||k,"aria-label":"Mark as helpful",className:"flex items-center justify-center px-2 py-1 rounded transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",style:{color:f&&!u?"#10b981":z?"#9ca3af":"#6b7280",backgroundColor:"transparent",border:"none",cursor:f||k?"not-allowed":"pointer",fontSize:"0.75rem",fontWeight:"500",minHeight:"24px"},onMouseEnter:L=>{!f&&!k&&(L.currentTarget.style.color="#10b981",L.currentTarget.style.backgroundColor="rgba(16, 185, 129, 0.1)")},onMouseLeave:L=>{f||(L.currentTarget.style.color=f?"#10b981":z?"#9ca3af":"#6b7280",L.currentTarget.style.backgroundColor="transparent")},children:"Helpful"}),d.jsx("button",{onClick:B,disabled:f||k,"aria-label":"Mark as not helpful",className:"flex items-center justify-center px-2 py-1 rounded transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",style:{color:u?"#ef4444":z?"#9ca3af":"#6b7280",backgroundColor:"transparent",border:"none",cursor:f||k?"not-allowed":"pointer",fontSize:"0.75rem",fontWeight:"500",minHeight:"24px"},onMouseEnter:L=>{!f&&!k&&(L.currentTarget.style.color="#ef4444",L.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)")},onMouseLeave:L=>{u||(L.currentTarget.style.color=z?"#9ca3af":"#6b7280",L.currentTarget.style.backgroundColor="transparent")},children:"Not Helpful"}),d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})]})]})]})]})})};function be(){const t=Ze();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,language:t.language,geo_country:t.geo_country,userId:t.userId,model:t.model,messages:t.messages,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const wt=(t,e)=>{if(!t)return"Get Started";let n="";const r=[/(?:set up|setup|integrate|add|install|use)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,| by)/i,/(?:by|from)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,)/];for(const i of r){const l=t.match(i);if(l&&l[1]){n=l[1].trim();break}}const s=e||n;if(s)return`Integrate ${s.split(/\s+/).slice(0,2).join(" ")}`;const a=t.match(/to\s+set\s+up\s+([a-zA-Z0-9\s]+?)(?:\s+by|\s*[.,]|$)/i);return a&&a[1]?`Integrate ${a[1].trim().split(/\s+/).slice(0,2).join(" ")}`:"Integrate"},je=({recommendation:t,theme:e,className:n="",style:r={},sessionId:s,onLinkClick:a,onPasteToInput:i})=>{var E,v,F,w,I,S,R;const l=t.creative_input||{},p=l.bridge_headline||"",h=l.bridge_description||"",c=l.bridge_prompt||l.bridge_content||"",u=l.product_name||"",_=l.cta_label||"";if(!h&&!c)return null;const f=t.product_id||"",b=t.recommendation_id||"",{sdk:k,sessionId:y}=be(),g=s||y,T=async M=>{if(M.preventDefault(),!!c){if(b&&g)try{const D=(k==null?void 0:k.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",A=await fetch(`${D}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:b,session_id:g,agent_id:t.agent_id,user_id:t.user_id||void 0,is_test:!1})});A.ok?o.log("[AdMesh Bridge] โœ… Engagement tracked successfully"):o.warn("[AdMesh Bridge] โš ๏ธ Failed to track engagement:",A.statusText)}catch(D){o.error("[AdMesh Bridge] โŒ Error tracking engagement:",D)}a&&a(t),i?i(c):typeof window<"u"&&window.__admesh_setMessage&&window.__admesh_setMessage(c)}},x=_||wt(c,u),N=!!x;return d.jsx(ke,{productId:f,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:s,className:`admesh-bridge-format ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',padding:"1rem",border:"none",borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",backgroundColor:"transparent",color:(e==null?void 0:e.textColor)||"inherit",...r},children:d.jsxs("div",{"data-admesh-theme":(e==null?void 0:e.mode)||"light",children:[p&&d.jsx("div",{className:"admesh-bridge-headline",style:{marginBottom:h?"0.75rem":N?"1rem":"0",fontSize:((E=e==null?void 0:e.fontSize)==null?void 0:E.large)||"1rem",fontWeight:600,color:(e==null?void 0:e.textColor)||"inherit",lineHeight:"1.4"},children:p}),h&&d.jsx("div",{className:"admesh-bridge-description",style:{marginBottom:N||(v=t.creative_input)!=null&&v.offer_summary?"1rem":"0",lineHeight:"1.6",fontSize:((F=e==null?void 0:e.fontSize)==null?void 0:F.base)||"0.875rem",color:(e==null?void 0:e.textColor)||"inherit"},children:h}),((w=t.creative_input)==null?void 0:w.offer_summary)&&d.jsx("div",{className:"admesh-bridge-offer-summary",style:{marginBottom:N?"1rem":"0",lineHeight:"1.5",fontSize:((I=e==null?void 0:e.fontSize)==null?void 0:I.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:t.creative_input.offer_summary}),N&&d.jsx("div",{style:{marginBottom:"0.75rem"},children:d.jsx("button",{onClick:T,className:"admesh-bridge-cta-button",style:{padding:"0.5rem 1rem",backgroundColor:"#000000",color:"#ffffff",fontSize:((S=e==null?void 0:e.fontSize)==null?void 0:S.small)||"0.875rem",fontWeight:500,borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",border:"none",cursor:"pointer",transition:"background-color 0.2s, opacity 0.2s"},onMouseEnter:M=>{M.currentTarget.style.backgroundColor="#1a1a1a",M.currentTarget.style.opacity="0.9"},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="#000000",M.currentTarget.style.opacity="1"},children:x})}),d.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"0.5rem"},children:d.jsx("div",{className:"admesh-bridge-label",style:{fontSize:((R=e==null?void 0:e.fontSize)==null?void 0:R.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:"Sponsored"})})]})})};function yt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fe={exports:{}};/*!
2
2
  Copyright (c) 2018 Jed Watson.
3
3
  Licensed under the MIT License (MIT), see
4
4
  http://jedwatson.github.io/classnames
5
- */var Oe;function _t(){return Oe||(Oe=1,(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var a="",i=0;i<arguments.length;i++){var l=arguments[i];l&&(a=s(a,r(l)))}return a}function r(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return n.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var i="";for(var l in a)e.call(a,l)&&a[l]&&(i=s(i,l));return i}function s(a,i){return i?a?a+" "+i:a+i:a}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Fe)),Fe.exports}var kt=_t();const _e=yt(kt),Ne=({recommendationId:t,admeshLink:e,productId:n,children:r,trackingData:s,className:a,style:i})=>{const l=m.useRef(null);m.useEffect(()=>{if(!l.current)return;l.current.querySelectorAll("a").forEach(c=>{(!c.hasAttribute("target")||c.getAttribute("target")!=="_blank")&&(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer"))})},[r]);const p=m.useCallback(h=>{const u=h.target.closest("a");u?((!u.href||u.href==="#"||u.href==="")&&e&&(u.href=e),(!u.hasAttribute("target")||u.getAttribute("target")!=="_blank")&&(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):o.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return d.jsx("div",{ref:l,className:a,onClick:p,style:{cursor:"pointer",...i},children:r})};Ne.displayName="AdMeshLinkTracker";const De=({brand:t,title:e="Product Recommendations",showTitle:n=!1,className:r="",cardClassName:s="",onProductClick:a,maxCards:i=10,cardWidth:l="md",theme:p="auto",borderRadius:h="md",shadow:c="sm",sessionId:u,onFeedback:_})=>{const[f,b]=m.useState(null);if(!t)return o.log("[AdMesh Ecommerce Cards] Brand object is required but was not provided"),null;if(!t.products||t.products.length===0)return o.log("[AdMesh Ecommerce Cards] Products array is required but was empty or missing. Both brand info and products are required for ecommerce cards."),null;const k=t.products.slice(0,i),y=()=>{var F;return t.brand_name||((F=t.creative_input)==null?void 0:F.brand_name)||""},g=()=>{var F,U;return((U=(F=t.creative_input)==null?void 0:F.assets)==null?void 0:U.logo_url)||""},C=()=>{var F;return((F=t.creative_input)==null?void 0:F.short_description)||t.description||""},x=F=>F.product_link||F.product_click_url||"",N=F=>F.product_cta_label||"Shop",E=F=>{const U=F.product_price;if(U!=null){if(typeof U=="string")return U;if(typeof U=="number")return`$${U.toFixed(2)}`}return""},v=F=>F.product_name||"",T=F=>F.product_description||"",w=F=>F.product_image_url||null,I=F=>{const U=F.product_discount;if(U!=null){if(typeof U=="string")return U;if(typeof U=="number")return`${U}%`}return null},S=()=>{switch(l){case"sm":return"w-[305px] min-w-[305px] max-w-[305px]";case"md":return"w-[345px] min-w-[345px] max-w-[345px]";case"lg":return"w-[385px] min-w-[385px] max-w-[385px]";default:return"w-[345px] min-w-[345px] max-w-[345px]"}},R=()=>{switch(h){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},M=()=>{switch(c){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},D=()=>p==="dark"?"bg-gray-900 text-white":p==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",A=F=>{if(a)a(F);else{const U=F.product_link||F.product_click_url;U&&window.open(U,"_blank","noopener,noreferrer")}},j=y(),Q=g(),G=C(),{sessionId:X,userId:re}=be(),q=u||X,ne=t.exposure_url;return d.jsxs("div",{className:_e("w-full",r),children:[d.jsxs("div",{className:_e("bg-white dark:bg-gray-900","border border-gray-200 dark:border-gray-700","rounded-xl","shadow-[0_4px_6px_-1px_rgba(0,0,0,0.1),0_2px_4px_-1px_rgba(0,0,0,0.06)]","dark:shadow-[0_4px_6px_-1px_rgba(0,0,0,0.3),0_2px_4px_-1px_rgba(0,0,0,0.2)]","p-6","transition-shadow duration-200","hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.1),0_4px_6px_-2px_rgba(0,0,0,0.05)]","dark:hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.4),0_4px_6px_-2px_rgba(0,0,0,0.3)]"),children:[(j||Q||G)&&d.jsx("div",{className:"mb-4",children:d.jsxs("div",{className:"flex items-start gap-3",children:[Q&&d.jsx("div",{className:"flex-shrink-0",children:d.jsx("div",{className:"rounded-full overflow-hidden bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center",style:{aspectRatio:"1",width:"48px",height:"48px"},children:d.jsx("img",{src:Q,alt:`${j} logo`,className:"w-full h-full object-contain",style:{aspectRatio:"1"},onError:F=>{F.target.style.display="none"}})})}),d.jsxs("div",{className:"flex-1",children:[j&&d.jsx("div",{className:"font-bold text-gray-900 dark:text-white text-base mb-1",children:j}),G&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:G})]})]})}),d.jsxs("div",{className:"relative",children:[k.length===0?d.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):d.jsx("div",{className:"flex gap-3 sm:gap-4 overflow-x-auto pb-4 scrollbar-hide",children:k.map(F=>{const U=F.product_id,ce=U,ue=x(F),z=N(F),V=E(F),P=v(F);T(F);const W=I(F),H=w(F),Z=F.product_link||F.product_click_url||"",K=t.recommendation_id;return d.jsx(Ne,{recommendationId:K,admeshLink:Z,productId:U,trackingData:{sessionId:q,userId:re},children:d.jsx(ke,{recommendationId:K,productId:U,exposureUrl:ne,sessionId:q,className:_e(S(),R(),M(),D(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02] overflow-hidden box-border",s),style:{width:l==="sm"?"305px":l==="lg"?"385px":"345px",minWidth:l==="sm"?"305px":l==="lg"?"385px":"345px",maxWidth:l==="sm"?"305px":l==="lg"?"385px":"345px"},onClick:()=>A(F),children:d.jsxs("div",{className:"p-3 w-full overflow-hidden box-border",children:[d.jsxs("div",{className:"flex items-start gap-3 mb-3 w-full",children:[d.jsx("div",{className:"flex-shrink-0",children:d.jsx("div",{className:"rounded-full overflow-hidden bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center",style:{aspectRatio:"1",width:"48px",height:"48px"},children:H?d.jsx("img",{src:H,alt:P,className:"w-full h-full object-cover",style:{aspectRatio:"1"},onError:$=>{$.target.style.display="none";const O=$.target.parentElement;O&&(O.innerHTML=`
5
+ */var Oe;function _t(){return Oe||(Oe=1,(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var a="",i=0;i<arguments.length;i++){var l=arguments[i];l&&(a=s(a,r(l)))}return a}function r(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return n.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var i="";for(var l in a)e.call(a,l)&&a[l]&&(i=s(i,l));return i}function s(a,i){return i?a?a+" "+i:a+i:a}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Fe)),Fe.exports}var kt=_t();const _e=yt(kt),Ne=({recommendationId:t,admeshLink:e,productId:n,children:r,trackingData:s,className:a,style:i})=>{const l=m.useRef(null);m.useEffect(()=>{if(!l.current)return;l.current.querySelectorAll("a").forEach(c=>{(!c.hasAttribute("target")||c.getAttribute("target")!=="_blank")&&(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer"))})},[r]);const p=m.useCallback(h=>{const u=h.target.closest("a");u?((!u.href||u.href==="#"||u.href==="")&&e&&(u.href=e),(!u.hasAttribute("target")||u.getAttribute("target")!=="_blank")&&(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):o.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return d.jsx("div",{ref:l,className:a,onClick:p,style:{cursor:"pointer",...i},children:r})};Ne.displayName="AdMeshLinkTracker";const De=({brand:t,title:e="Product Recommendations",showTitle:n=!1,className:r="",cardClassName:s="",onProductClick:a,maxCards:i=10,cardWidth:l="md",theme:p="auto",borderRadius:h="md",shadow:c="sm",sessionId:u,onFeedback:_})=>{const[f,b]=m.useState(null);if(!t)return o.log("[AdMesh Ecommerce Cards] Brand object is required but was not provided"),null;if(!t.products||t.products.length===0)return o.log("[AdMesh Ecommerce Cards] Products array is required but was empty or missing. Both brand info and products are required for ecommerce cards."),null;const k=t.products.slice(0,i),y=()=>{var C;return t.brand_name||((C=t.creative_input)==null?void 0:C.brand_name)||""},g=()=>{var C,B;return((B=(C=t.creative_input)==null?void 0:C.assets)==null?void 0:B.logo_url)||""},T=()=>{var C;return((C=t.creative_input)==null?void 0:C.short_description)||t.description||""},x=C=>C.product_link||C.product_click_url||"",N=C=>C.product_cta_label||"Shop",E=C=>{const B=C.product_price;if(B!=null){if(typeof B=="string")return B;if(typeof B=="number")return`$${B.toFixed(2)}`}return""},v=C=>C.product_name||"",F=C=>{if(C.product_features&&C.product_features.length>0){let B=0;const ae=C.product_id||"";for(let $=0;$<ae.length;$++)B=(B<<5)-B+ae.charCodeAt($),B|=0;const le=Math.abs(B)%C.product_features.length;return C.product_features[le]}return C.product_description||""},w=C=>C.product_image_url||null,I=C=>{const B=C.product_discount;if(B!=null){if(typeof B=="string")return B;if(typeof B=="number")return`${B}%`}return null},S=()=>{switch(l){case"sm":return"w-[305px] min-w-[305px] max-w-[305px]";case"md":return"w-[345px] min-w-[345px] max-w-[345px]";case"lg":return"w-[385px] min-w-[385px] max-w-[385px]";default:return"w-[345px] min-w-[345px] max-w-[345px]"}},R=()=>{switch(h){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},M=()=>{switch(c){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},D=()=>p==="dark"?"bg-gray-900 text-white":p==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",A=C=>{if(a)a(C);else{const B=C.product_link||C.product_click_url;B&&window.open(B,"_blank","noopener,noreferrer")}},j=y(),G=g(),Y=T(),{sessionId:X,userId:re}=be(),q=u||X,ne=t.exposure_url;return d.jsxs(ke,{recommendationId:t.recommendation_id,exposureUrl:ne,sessionId:q,className:_e("w-full",r),children:[d.jsxs("div",{className:_e("bg-white dark:bg-gray-900","border border-gray-200 dark:border-gray-700","rounded-xl","shadow-[0_4px_6px_-1px_rgba(0,0,0,0.1),0_2px_4px_-1px_rgba(0,0,0,0.06)]","dark:shadow-[0_4px_6px_-1px_rgba(0,0,0,0.3),0_2px_4px_-1px_rgba(0,0,0,0.2)]","p-6","transition-shadow duration-200","hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.1),0_4px_6px_-2px_rgba(0,0,0,0.05)]","dark:hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.4),0_4px_6px_-2px_rgba(0,0,0,0.3)]"),children:[(j||G||Y)&&d.jsx("div",{className:"mb-4",children:d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("div",{className:"flex-shrink-0",children:d.jsx("div",{className:"rounded-full overflow-hidden bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center",style:{aspectRatio:"1",width:"48px",height:"48px"},children:d.jsx("img",{src:G,alt:`${j} logo`,className:"w-full h-full object-contain",style:{aspectRatio:"1"},onError:C=>{C.target.style.display="none"}})})}),d.jsxs("div",{className:"flex-1",children:[j&&d.jsx("div",{className:"font-bold text-gray-900 dark:text-white text-base mb-1",children:j}),Y&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:Y})]})]})}),d.jsxs("div",{className:"relative",children:[k.length===0?d.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):d.jsx("div",{className:"flex gap-3 sm:gap-4 overflow-x-auto pb-4 scrollbar-hide",children:k.map(C=>{const B=C.product_id,ae=B,le=x(C),$=N(C),z=E(C),P=v(C),W=F(C),K=I(C),Z=w(C),O=C.product_link||C.product_click_url||"",V=t.recommendation_id;return d.jsx(Ne,{recommendationId:V,admeshLink:O,productId:B,trackingData:{sessionId:q,userId:re},children:d.jsx("div",{className:_e(S(),R(),M(),D(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02] overflow-hidden box-border",s),style:{width:l==="sm"?"305px":l==="lg"?"385px":"345px",minWidth:l==="sm"?"305px":l==="lg"?"385px":"345px",maxWidth:l==="sm"?"305px":l==="lg"?"385px":"345px"},onClick:()=>A(C),children:d.jsxs("div",{className:"p-3 w-full overflow-hidden box-border",children:[d.jsxs("div",{className:"flex items-start gap-3 mb-3 w-full",children:[d.jsx("div",{className:"flex-shrink-0",children:d.jsx("div",{className:"rounded-full overflow-hidden bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center",style:{aspectRatio:"1",width:"48px",height:"48px"},children:Z?d.jsx("img",{src:Z,alt:P,className:"w-full h-full object-cover",style:{aspectRatio:"1"},onError:H=>{H.target.style.display="none";const Q=H.target.parentElement;Q&&(Q.innerHTML=`
6
6
  <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
7
7
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
8
8
  </svg>
9
- `)}}):d.jsx("svg",{className:"w-6 h-6 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),d.jsx("div",{className:"flex-1 min-w-0 max-w-full overflow-hidden",children:P&&d.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white mb-1 leading-tight break-words overflow-wrap-anywhere",children:P})})]}),d.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[V&&d.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:V}),W&&d.jsxs("span",{className:"text-xs text-red-600 dark:text-red-400 font-medium",children:[W," OFF"]})]}),ue&&d.jsx("button",{onClick:$=>{$.stopPropagation(),A(F)},className:"px-3 py-1.5 text-xs font-medium text-gray-100 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 rounded-md transition-colors duration-200 whitespace-nowrap",children:z})]})]})})},ce)})}),k.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),d.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),d.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),_&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 mr-1",children:"Was this helpful?"}),d.jsx("button",{onClick:()=>{f===null&&(b("helpful"),_(!0,t.recommendation_id||""))},disabled:f!==null,className:_e("px-2 py-1 text-xs font-medium rounded transition-colors duration-200",f==="helpful"?"bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 cursor-default":"bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer",f!==null&&f!=="helpful"&&"opacity-50 cursor-not-allowed"),title:"Helpful",children:d.jsxs("span",{className:"flex items-center gap-1",children:[d.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"})}),"Helpful"]})}),d.jsx("button",{onClick:()=>{f===null&&(b("not-helpful"),_(!1,t.recommendation_id||""))},disabled:f!==null,className:_e("px-2 py-1 text-xs font-medium rounded transition-colors duration-200",f==="not-helpful"?"bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 cursor-default":"bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer",f!==null&&f!=="not-helpful"&&"opacity-50 cursor-not-allowed"),title:"Not helpful",children:d.jsxs("span",{className:"flex items-center gap-1",children:[d.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4a2 2 0 00-2-2h-1.528c-.163 0-.326.02-.485.06L9 4m7 10H9m0 0H5m4 0v5a2 2 0 002 2h2M9 9h.01"})}),"Not helpful"]})})]})]})]}),d.jsx("style",{dangerouslySetInnerHTML:{__html:`
9
+ `)}}):d.jsx("svg",{className:"w-6 h-6 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),d.jsxs("div",{className:"flex-1 min-w-0 max-w-full overflow-hidden",children:[P&&d.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white mb-1 leading-tight break-words overflow-wrap-anywhere",children:P}),W&&d.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 break-words overflow-wrap-anywhere line-clamp-2",title:W,children:W})]})]}),d.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[z&&d.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:z}),K&&d.jsxs("span",{className:"text-xs text-red-600 dark:text-red-400 font-medium",children:[K," OFF"]})]}),le&&d.jsx("button",{onClick:H=>{H.stopPropagation(),A(C)},className:"px-3 py-1.5 text-xs font-medium text-gray-100 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 rounded-md transition-colors duration-200 whitespace-nowrap",children:$})]})]})})},ae)})}),k.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),d.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),d.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),_&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 mr-1",children:"Was this helpful?"}),d.jsx("button",{onClick:()=>{f===null&&(b("helpful"),_(!0,t.recommendation_id||""))},disabled:f!==null,className:_e("px-2 py-1 text-xs font-medium rounded transition-colors duration-200",f==="helpful"?"bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 cursor-default":"bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer",f!==null&&f!=="helpful"&&"opacity-50 cursor-not-allowed"),title:"Helpful",children:d.jsxs("span",{className:"flex items-center gap-1",children:[d.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"})}),"Helpful"]})}),d.jsx("button",{onClick:()=>{f===null&&(b("not-helpful"),_(!1,t.recommendation_id||""))},disabled:f!==null,className:_e("px-2 py-1 text-xs font-medium rounded transition-colors duration-200",f==="not-helpful"?"bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 cursor-default":"bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer",f!==null&&f!=="not-helpful"&&"opacity-50 cursor-not-allowed"),title:"Not helpful",children:d.jsxs("span",{className:"flex items-center gap-1",children:[d.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4a2 2 0 00-2-2h-1.528c-.163 0-.326.02-.485.06L9 4m7 10H9m0 0H5m4 0v5a2 2 0 002 2h2M9 9h.01"})}),"Not helpful"]})})]})]})]}),d.jsx("style",{dangerouslySetInnerHTML:{__html:`
10
10
  .scrollbar-hide {
11
11
  -ms-overflow-style: none;
12
12
  scrollbar-width: none;
@@ -20,7 +20,7 @@
20
20
  -webkit-box-orient: vertical;
21
21
  overflow: hidden;
22
22
  }
23
- `}})]})},Xe=({recommendations:t,summaryText:e,theme:n,className:r,style:s,onLinkClick:a,onPasteToInput:i,sessionId:l,response:p})=>{var f;const h=t||(p==null?void 0:p.recommendations)||[];let c=e||(p==null?void 0:p.tail_summary);const u=h.filter(b=>b&&typeof b=="object"&&b.recommendation_id);if(!u||u.length===0)return o.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;if(!c&&u.length>0&&((f=u[0])!=null&&f.creative_input)){const b=u[0].creative_input;c=b.long_description||b.context_snippet||b.short_description||void 0}o.log(`[AdMeshLayout] Rendering with ${u.length} valid recommendations`);const _=()=>{if(u.length>0){const b=u[0],k=(b==null?void 0:b.creative_input)||{},y=(b==null?void 0:b.preferred_format)||(k==null?void 0:k.preferred_format);if(o.log("[AdMeshLayout] ๐Ÿ” Checking format:",{preferredFormat:y,creativeInputKeys:Object.keys(k),recommendationKeys:Object.keys(b||{})}),y==="product_card"){const x=(b==null?void 0:b.products)||(k==null?void 0:k.products)||[];if(x&&x.length>0)return o.log(`[AdMeshLayout] ๐Ÿ›๏ธ Rendering product_card format with ${x.length} products`),d.jsx(De,{brand:b,theme:n,sessionId:l});o.warn("[AdMeshLayout] product_card format detected but no products array, falling back to tail")}if(!!k.bridge_prompt||!!k.bridge_content||y==="bridge")return o.log("[AdMeshLayout] ๐ŸŽฏ โœ… Rendering bridge format"),d.jsx(je,{recommendation:b,theme:n,sessionId:l,onLinkClick:a,onPasteToInput:i});o.log("[AdMeshLayout] โš ๏ธ Bridge format NOT detected, falling back to other formats")}return c?d.jsx(Pe,{summaryText:c,recommendations:u,theme:n,onLinkClick:a,sessionId:l}):null};return d.jsx("div",{className:`admesh-layout ${r}`,style:{fontFamily:(n==null?void 0:n.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:_()})},At=({className:t,size:e=20})=>d.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:[d.jsx("path",{d:"M5 12h14"}),d.jsx("path",{d:"M12 5v14"})]}),Ce=({recommendation:t,theme:e,sdk:n,sessionId:r,onExecuteQuery:s})=>{const a=t.followup_query,i=t.followup_engagement_url,l=t.followup_exposure_url,p=t.recommendation_id;if(!a||!i||!l)return o.log("[AdMeshFollowup] Missing followup_query, followup_engagement_url, or followup_exposure_url - not rendering"),null;const h=async()=>{try{i&&p&&(o.log("[AdMeshFollowup] ๐ŸŽฏ Firing follow-up engagement tracking"),await n.fireFollowupEngagement(i,p,r)),s&&a?(o.log(`[AdMeshFollowup] ๐Ÿ” Executing query: ${a}`),await s(a)):o.warn("[AdMeshFollowup] โš ๏ธ onExecuteQuery not provided - cannot execute query")}catch(c){o.error("[AdMeshFollowup] โŒ Error handling follow-up click:",c)}};return e!=null&&e.mode,d.jsx(ke,{productId:t.product_id||"",recommendationId:p||"",exposureUrl:l,sessionId:r,className:"admesh-followup-container",style:{width:"100%"},children:d.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[d.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),d.jsxs("div",{onClick:h,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&h()},"aria-label":`Sponsored follow-up: ${a}`,children:[d.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:a}),d.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),d.jsx(At,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})};class Je{constructor(e){te(this,"firedExposures",new Set);te(this,"debug",!1);te(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,n,r){const s=`${r}_${n}`;if(this.firedExposures.has(s)){this.debug&&o.log("[Tracker] Exposure already fired");return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&o.warn("[Tracker] Failed to fire exposure")}),this.debug&&o.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&o.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,n,r,s){const a=`${r}_${n}`;if(this.firedExposures.has(a)){this.debug&&o.log("[Tracker] MRC exposure already fired");return}return new Promise(i=>{let l=null,p=null;const h=new IntersectionObserver(_=>{_.forEach(f=>{f.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?l===null&&(l=Date.now(),this.debug&&o.log("[Tracker] Ad reached MRC visibility threshold"),p=setTimeout(()=>{this.fireExposure(e,n,r),h.disconnect(),i()},this.mrcThreshold.minimumDurationMs)):l!==null&&(p&&(clearTimeout(p),p=null),l=null,this.debug&&o.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});h.observe(s);const u=setTimeout(()=>{h.disconnect(),p&&clearTimeout(p),i()},3e4);s.__admeshTrackerCleanup=()=>{h.disconnect(),p&&clearTimeout(p),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,n,r){this.fireExposure(e,n,r)}fireFollowupEngagement(e,n,r){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:r})}).catch(s=>{this.debug&&o.warn("[Tracker] Failed to fire followup engagement (non-critical):",s)}).then(()=>{})}}const Le=({apiKey:t,sessionId:e,theme:n,apiBaseUrl:r,language:s,geo_country:a,userId:i,model:l,messages:p,children:h})=>{const c=m.useRef(null),[u,_]=m.useState(new Set);m.useEffect(()=>{if(!e||e.trim()===""){o.error("[AdMeshProvider] โŒ sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");return}},[e]),m.useEffect(()=>{if(!t){o.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){o.error("[AdMeshProvider] โŒ Cannot initialize SDK: sessionId is required and must be provided by the platform");return}try{c.current=new tt({apiKey:t,theme:n,apiBaseUrl:r}),o.log("[AdMeshProvider] โœ… AdMesh SDK initialized"),r&&o.log("[AdMeshProvider] ๐Ÿ“ Using custom API base URL")}catch{o.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK")}return()=>{o.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,n,r]);const f={sdk:c.current,apiKey:t,sessionId:e,theme:n,language:s,geo_country:a,userId:i,model:l,messages:p,processedMessageIds:u,markMessageAsProcessed:b=>{_(k=>{const y=new Set(k);return y.add(b),y})},isMessageProcessed:b=>u.has(b)};return d.jsx(Ee.Provider,{value:f,children:h})};class et{constructor(){te(this,"roots",new Map)}async render(e){var n;try{o.log("[AdMeshRenderer] ๐ŸŽจ Attempting to render recommendations");const r=e.response.recommendations||[];if(r.length===0){o.log("[AdMeshRenderer] โš ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw o.error("[AdMeshRenderer] โŒ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);o.log("[AdMeshRenderer] โœ… Container ready");const a=this.roots.get(e.containerId);a&&(o.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing root"),a.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const i=ze.createRoot(s),l=((n=r[0])==null?void 0:n.tail_summary)||"";o.log("[AdMeshRenderer] ๐Ÿ“Š Rendering recommendations");const p=e.onPasteToInput||(typeof window<"u"?window.__admesh_onPasteToInput:void 0);if(i.render(d.jsx(Le,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,geo_country:e.geo_country,userId:e.userId,model:e.model,messages:e.messages,children:d.jsx(Xe,{recommendations:r,summaryText:l,theme:e.theme,sessionId:e.sessionId,onPasteToInput:p})})),s.style.display="block",o.log("[AdMeshRenderer] โœ… Recommendations rendered successfully"),this.roots.set(e.containerId,i),e.followups_container_id){const h=r[0];h!=null&&h.followup_query&&(h!=null&&h.followup_engagement_url)&&await this.renderFollowup({containerId:e.followups_container_id,recommendation:h,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,apiKey:e.apiKey,apiBaseUrl:e.apiBaseUrl,onExecuteQuery:e.onExecuteQuery})}}catch(r){throw o.error("[AdMeshRenderer] โŒ Error rendering recommendations"),r}}async renderFollowup(e){try{o.log(`[AdMeshRenderer] ๐ŸŽฏ Rendering follow-up in container: ${e.containerId}`);const n=document.getElementById(e.containerId);if(!n){o.warn(`[AdMeshRenderer] โš ๏ธ Followups container not found: ${e.containerId}`);return}const r=this.roots.get(e.containerId);r&&(o.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing followup root"),r.unmount(),this.roots.delete(e.containerId)),n.innerHTML="";const s=ze.createRoot(n);s.render(d.jsx(Le,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,children:d.jsx(Ce,{recommendation:e.recommendation,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,onExecuteQuery:e.onExecuteQuery})})),n.style.display="block",o.log("[AdMeshRenderer] โœ… Follow-up rendered successfully"),this.roots.set(e.containerId,s)}catch{o.error("[AdMeshRenderer] โŒ Error rendering follow-up")}}unmount(e){const n=this.roots.get(e);if(n){n.unmount(),this.roots.delete(e);const r=document.getElementById(e);r&&(r.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class tt{constructor(e){te(this,"config");te(this,"apiBaseUrl");te(this,"renderer",null);te(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static createSession(){const e=Date.now(),n=Math.random().toString(36).substring(2,15);return`session_${e}_${n}`}static createMessageId(e){const n=Date.now(),r=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${n}_${r}`:`msg_${n}_${r}`}getRenderer(){return this.renderer||(this.renderer=new et),this.renderer}getTracker(){return this.tracker||(this.tracker=new Je({apiKey:this.config.apiKey})),this.tracker}async showRecommendations(e){try{if(!e.session_id||e.session_id.trim()==="")throw new Error("session_id 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 n=await this.fetchRecommendationFromAIPContext({query:e.query,sessionId:e.session_id,messageId:e.messageId,platformSurface:e.platformSurface,model:e.model,messages:e.messages,language:e.locale,geo_country:e.geo,userId:e.userId}),r=this.convertAIPResponseToRecommendation(n),s={session_id:n.session_id,message_id:`msg_${n.recommendation_id}`,recommendations:[r]},a=this.getRenderer(),i=this.getTracker();await a.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:i,sessionId:e.session_id,apiKey:this.config.apiKey,apiBaseUrl:this.apiBaseUrl,language:e.locale,geo_country:e.geo,userId:e.userId,model:e.model,messages:e.messages,onPasteToInput:e.onPasteToInput,onExecuteQuery:e.onExecuteQuery})}catch(n){throw o.error("[AdMeshSDK] Error showing recommendations"),n}}async fetchRecommendationFromAIPContext(e){var u,_,f;const n=`${this.apiBaseUrl}/aip/context`;if(o.log("[AdMeshSDK] ๐Ÿ“ฅ fetchRecommendationFromAIPContext called"),!e.sessionId||e.sessionId.trim()===""){const b=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw o.error("[AdMeshSDK] โŒ sessionId not provided by platform - cannot process request"),b}const r=e.messageId;if(!r||r.trim()===""){const b=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw o.error("[AdMeshSDK] โŒ messageId not provided by platform - cannot process request"),b}const s=e.messages?e.messages.length:0,a=(typeof window<"u"&&window.navigator,"web"),i=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",l={spec_version:"1.0.0",message_id:r,timestamp:new Date().toISOString(),producer:{agent_id:"placeholder",agent_role:"publisher",software:"admesh_ui_sdk",software_version:e.model||"1.0.0"},context:{language:e.language||"en-US",publisher:"placeholder",placement:{ad_unit:e.platformSurface||"web"},device:{platform:a,form_factor:i},geography:{country:e.geo_country||"US"}},identity:{namespace:"platform_user",value_hash:e.userId||"",confidence:1},extensions:{aip:{session_id:e.sessionId,turn_index:s,query_text:e.query,messages:e.messages||[],cpx_floor:0}}};(!l.extensions.aip.query_text||!l.extensions.aip.query_text.trim())&&o.warn("[AdMeshSDK] โš ๏ธ Warning: Sending request with empty query_text");const p=JSON.stringify(l);o.log("[AdMeshSDK] ๐Ÿ“ค Sending request to /aip/context");const h=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:p});if(!h.ok){const k=(await h.json().catch(()=>({}))).detail||`HTTP ${h.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${k}`)}const c=await h.json();return o.log("[AdMeshSDK] ๐Ÿ“ฅ Raw response from /aip/context:",{hasCreative:!!c.creative,creativeFormat:(u=c.creative)==null?void 0:u.format,creativeBridgeContent:(_=c.creative)!=null&&_.bridge_content?c.creative.bridge_content.substring(0,50)+"...":void 0,hasWinningBid:!!c.winning_bid,winningBidPreferredFormat:(f=c.winning_bid)==null?void 0:f.preferred_format,topLevelKeys:Object.keys(c)}),c}convertAIPResponseToRecommendation(e){var T,w,I,S,R,M,D;const n=e;let r=e.creative_input||{};const s=n.creative||{},a=s.format||n.format||((T=n.winning_bid)==null?void 0:T.preferred_format),i=s.headline,l=s.bridge_headline,p=s.bridge_description,h=s.bridge_prompt||s.bridge_content,c=h||r.bridge_prompt||r.bridge_content,u=s.cta_label,_=u||r.cta_label,f=l||r.bridge_headline,b=p||r.bridge_description;o.log("[AdMeshSDK] ๐Ÿ” Extracting from response:",{creativeObject:s,creativeFormat:s.format,creativeBridgeHeadline:l,creativeBridgeDescription:p?String(p).substring(0,50)+"...":void 0,creativeBridgePrompt:h?String(h).substring(0,50)+"...":void 0,creativeCtaLabel:u,extractedFormat:a,extractedBridgeHeadline:f,extractedBridgeDescription:b?String(b).substring(0,50)+"...":void 0,extractedBridgePrompt:c?String(c).substring(0,50)+"...":void 0,extractedCtaLabel:_,creativeInputHasBridgeHeadline:!!r.bridge_headline,creativeInputHasBridgeDescription:!!r.bridge_description,creativeInputHasBridgePrompt:!!r.bridge_prompt,creativeInputHasBridgeContent:!!r.bridge_content,creativeInputHasCtaLabel:!!r.cta_label});const k=r.assets||{};r={...r,assets:k,...i&&{headline:i},...f&&{bridge_headline:f},...b&&{bridge_description:b},...c&&{bridge_prompt:c},...c&&{bridge_content:c},..._&&{cta_label:_},...a&&{format:a}};const y=e.recommendation_id||n.recommendation_id||n.bid_id||"",g=e.click_url||e.admesh_link||"",C={...e,recommendation_id:y,admesh_link:g||e.click_url||"",ad_id:void 0,bid_id:void 0,creative_input:r,product_title:e.title,tail_summary:r.long_description||"",product_summary:r.short_description||"",weave_summary:r.context_snippet||"",product_logo:(w=r.assets)!=null&&w.logo_url?{url:r.assets.logo_url}:void 0,categories:r.categories||[]};delete C.ad_id,delete C.bid_id;const x=(e==null?void 0:e.products)||[],N=(r==null?void 0:r.products)||[],E=x.length>0?x:N;E&&E.length>0&&(C.products=E,o.log(`[AdMeshSDK] โœ… Preserved ${E.length} products for product_card format`));const v=(e==null?void 0:e.preferred_format)||(r==null?void 0:r.preferred_format);return v&&(C.preferred_format=v,o.log(`[AdMeshSDK] โœ… Preserved preferred_format: ${v}`)),o.log("[AdMeshSDK] ๐Ÿ”„ Converted recommendation:",{preferredFormat:v,hasProducts:!!(E&&E.length>0),productsCount:(E==null?void 0:E.length)||0,hasBridgeHeadline:!!f,bridgeHeadline:f,hasBridgeDescription:!!b,bridgeDescriptionPreview:b?String(b).substring(0,50)+"...":void 0,hasBridgePrompt:!!c,hasCtaLabel:!!_,ctaLabel:_,bridgeHeadlineInCreativeInput:!!((I=C.creative_input)!=null&&I.bridge_headline),bridgeDescriptionInCreativeInput:!!((S=C.creative_input)!=null&&S.bridge_description),bridgePromptInCreativeInput:!!((R=C.creative_input)!=null&&R.bridge_prompt),bridgeContentInCreativeInput:!!((M=C.creative_input)!=null&&M.bridge_content),ctaLabelInCreativeInput:!!((D=C.creative_input)!=null&&D.cta_label),bridgePromptPreview:c?String(c).substring(0,50)+"...":void 0,creativeInputKeys:Object.keys(C.creative_input||{})}),C}fireFollowupExposure(e,n,r){this.getTracker().fireFollowupExposure(e,n,r)}async fireFollowupEngagement(e,n,r){return this.getTracker().fireFollowupEngagement(e,n,r)}}class Be{constructor(e={}){te(this,"autoAddLabels");te(this,"fireExposurePixels");te(this,"labelStyle");te(this,"processedLinks",new Set);te(this,"mutationObserver",null);var n,r,s,a;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((n=e.labelStyle)==null?void 0:n.fontSize)||"0.75em",fontWeight:((r=e.labelStyle)==null?void 0:r.fontWeight)||"bold",color:((s=e.labelStyle)==null?void 0:s.color)||"#666",marginLeft:((a=e.labelStyle)==null?void 0:a.marginLeft)||"2px"}}getLinksToProcess(e){const r=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return r.length>0?Array.from(r):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,n,r){if(!e)return[];const s=[];if(n.length>0){const a=this.getLinksToProcess(e),i=new Map(n.filter(p=>p.click_url).map(p=>[p.click_url,p])),l=new Map;n.forEach(p=>{var c;const h=p.redirect_url||p.url||((c=p.creative_input)==null?void 0:c.cta_url);if(h&&typeof h=="string"){const u=h.trim().replace(/\/$/,"");l.set(u,p),l.set(`${u}/`,p)}}),a.forEach(p=>{const h=p.getAttribute("href")||"",c=`${h}`;if(this.processedLinks.has(c))return;let u=i.get(h),_=h;if(!u){const f=h.trim().replace(/\/$/,"");u=l.get(f)||l.get(`${f}/`),u&&u.click_url&&(o.log("[WeaveResponseProcessor] ๐Ÿ”„ Found brand URL match, replacing with click_url:",h),p.setAttribute("href",u.click_url),_=u.click_url)}if(u){this.processedLinks.add(c),p.setAttribute("target","_blank"),p.setAttribute("rel","noopener noreferrer");const f={element:p,href:_,text:p.textContent||"",hasAdLabel:this.hasAdLabel(p),matchedRecommendation:{recommendation_id:u.recommendation_id||"",click_url:u.click_url,exposure_url:u.exposure_url}};this.autoAddLabels&&!f.hasAdLabel?(o.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to matched recommendation link:",_),this.addAdLabel(p),f.hasAdLabel=!0):this.autoAddLabels?f.hasAdLabel&&o.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):o.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&u.exposure_url&&r&&f.matchedRecommendation&&r({exposureUrl:u.exposure_url,recommendationId:f.matchedRecommendation.recommendation_id,linkElement:p}),s.push(f)}})}else Array.from(e.querySelectorAll("a")).forEach(i=>{const l=i.getAttribute("href")||"",p=`${l}`;if(this.processedLinks.has(p))return;if(this.isAdMeshLink(l)){this.processedLinks.add(p);const c={element:i,href:l,text:i.textContent||"",hasAdLabel:this.hasAdLabel(i),matchedRecommendation:void 0};if(i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(o.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to pattern-matched AdMesh link:",l),this.addAdLabel(i),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&o.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):o.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&r){const u=this.convertClickUrlToExposureUrl(l);r({exposureUrl:u,recommendationId:this.extractRecommendationIdFromUrl(l),linkElement:i})}s.push(c)}});return s}hasAdLabel(e){var i,l,p;if((e.textContent||"").includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Link text contains [Ad] label"),!0;const r=e.querySelectorAll("sub, span");for(const h of Array.from(r))if((i=h.textContent)!=null&&i.includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Link has [Ad] label as child element"),!0;let s=e.previousSibling;for(;s&&s.nodeType===Node.TEXT_NODE;){const h=s.textContent||"";if(h.trim()===""){s=s.previousSibling;continue}if(h.includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous text sibling"),!0;break}if(s&&s.nodeType===Node.ELEMENT_NODE){const h=s,c=h.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((l=h.textContent)!=null&&l.includes("[Ad]")))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous element sibling:",c),!0}let a=e.nextSibling;for(;a&&a.nodeType===Node.TEXT_NODE;){const h=a.textContent||"";if(h.trim()===""){a=a.nextSibling;continue}if(h.includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next text sibling"),!0;break}if(a&&a.nodeType===Node.ELEMENT_NODE){const h=a,c=h.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((p=h.textContent)!=null&&p.includes("[Ad]")))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next element sibling:",c),!0}return o.log("[WeaveResponseProcessor] โ„น๏ธ No existing [Ad] label found"),!1}addAdLabel(e){if(o.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Attempting to add [Ad] label to link:",e.href),!e.isConnected){o.warn("[WeaveResponseProcessor] โš ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){o.log("[WeaveResponseProcessor] โ„น๏ธ Link already has [Ad] label, skipping");return}const n=e.parentNode;if(!n){o.error("[WeaveResponseProcessor] โŒ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const r=document.createElement("sub");r.textContent="[Ad]",r.style.fontSize=this.labelStyle.fontSize,r.style.fontWeight=this.labelStyle.fontWeight,r.style.color=this.labelStyle.color,r.style.marginLeft=this.labelStyle.marginLeft,r.style.cursor="pointer",r.style.borderBottom=`1px dotted ${this.labelStyle.color}`,r.style.whiteSpace="nowrap",r.title="Why this ad? This is a sponsored recommendation based on your search query.";let s=!1;r.addEventListener("mouseenter",()=>{r.style.opacity="0.7"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1",s&&(s=!1)}),r.addEventListener("click",i=>{i.stopPropagation(),s=!s,s?(r.style.textDecoration="underline",r.style.opacity="0.7"):(r.style.textDecoration="none",r.style.opacity="1")});const a=i=>{s&&i.target!==r&&(s=!1,r.style.textDecoration="none",r.style.opacity="1")};document.addEventListener("click",a);try{const i=e.nextSibling;i?(n.insertBefore(r,i),o.log("[WeaveResponseProcessor] โœ… [Ad] label inserted before next sibling")):(n.appendChild(r),o.log("[WeaveResponseProcessor] โœ… [Ad] label appended to parent (no next sibling)")),r.isConnected&&r.parentNode===n?o.log("[WeaveResponseProcessor] โœ… [Ad] label successfully added to link:",e.href):o.error("[WeaveResponseProcessor] โŒ [Ad] label insertion failed - label not in DOM")}catch(i){o.error("[WeaveResponseProcessor] โŒ Error inserting [Ad] label:",i)}}removeLeftAdLabel(e){var r,s,a;let n=e.previousSibling;for(;n&&n.nodeType===Node.TEXT_NODE;){const i=n.textContent||"";if(i.trim()===""){n=n.previousSibling;continue}if(i.includes("[Ad]")){(r=n.parentNode)==null||r.removeChild(n);return}break}if(n&&n.nodeType===Node.ELEMENT_NODE){const i=n;(i.tagName==="SUB"||i.tagName==="SPAN")&&((s=i.textContent)!=null&&s.includes("[Ad]"))&&((a=i.parentNode)==null||a.removeChild(i))}}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(s=>e.includes(s)))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 n=e.match(/\/click\/([^/?]+)/);return n&&n[1]?n[1]:""}catch{return e}}convertClickUrlToExposureUrl(e){try{const n=new URL(e),s=`${`${n.protocol}//${n.host}`}/exposure`,a=new URLSearchParams(n.search);return a.has("cpx")||a.set("cpx","0"),`${s}?${a.toString()}`}catch{return o.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,n,r){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,n,r)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}const St=({onRecommendationsShown:t,onError:e,messageId:n,query:r,onPasteToInput:s,followups_container_id:a,onExecuteQuery:i,onFollowupDetected:l,isContainerReady:p,userId:h})=>{const{sdk:c,sessionId:u,language:_,geo_country:f,userId:b,model:k,messages:y,theme:g}=be(),C=h||b,[x,N]=m.useState(null),[E,v]=m.useState(null),[T,w]=m.useState(!0),[I,S]=m.useState(null),R=m.useRef(null),M=m.useRef(!1),D=m.useRef(t),A=m.useRef(e),j=m.useRef(l);m.useEffect(()=>{D.current=t,A.current=e,j.current=l},[t,e,l]);const Q=z=>{var Ae,me,Ue,$e,We;const V=z;let P=z.creative_input||{};const W=V.creative||{},H=W.format||V.format||((Ae=V.winning_bid)==null?void 0:Ae.preferred_format)||((me=z.creative_input)==null?void 0:me.preferred_format),Z=W.headline,K=W.bridge_headline,$=W.bridge_description,Y=W.bridge_prompt||W.bridge_content||P.bridge_prompt||P.bridge_content,ae=W.cta_label||P.cta_label,ie=K||P.bridge_headline,oe=$||P.bridge_description,B=P.assets||{};P={...P,assets:B,...Z&&{headline:Z},...ie&&{bridge_headline:ie},...oe&&{bridge_description:oe},...Y&&{bridge_prompt:Y},...Y&&{bridge_content:Y},...ae&&{cta_label:ae},...H&&{format:H}};const pe=z.recommendation_id||z.bid_id||"",xe=z.click_url||z.admesh_link||"",de={...z,recommendation_id:pe,admesh_link:xe||z.click_url||"",creative_input:P,ad_id:void 0,bid_id:void 0,...H&&{format:H}};delete de.ad_id,delete de.bid_id;const le=z.followup_query,ve=((Ue=z.creative_input)==null?void 0:Ue.followup_query)||(P==null?void 0:P.followup_query),L=le||ve,J=z.followup_engagement_url,he=(($e=z.creative_input)==null?void 0:$e.followup_engagement_url)||(P==null?void 0:P.followup_engagement_url),ge=J||he,we=z.followup_exposure_url,ee=((We=z.creative_input)==null?void 0:We.followup_exposure_url)||(P==null?void 0:P.followup_exposure_url),ye=we||ee;return L&&(de.followup_query=L,o.debug("[AdMeshRecommendations] โœ… Extracted followup_query:",L.substring(0,50)+"...")),ge&&(de.followup_engagement_url=ge,o.debug("[AdMeshRecommendations] โœ… Extracted followup_engagement_url")),ye&&(de.followup_exposure_url=ye,o.debug("[AdMeshRecommendations] โœ… Extracted followup_exposure_url")),de};m.useEffect(()=>{R.current!==n&&(R.current=null,N(null),v(null))},[n]);const[G,X]=m.useState(null);m.useEffect(()=>{if(!(x!=null&&x.followup_query)||!a){X(null);return}if(p===!1){o.debug("[AdMeshRecommendations] โณ Waiting for container signal...");return}let z=0;const V=5,P=()=>{const H=document.getElementById(a);return H?(o.debug(`[AdMeshRecommendations] โœ… Found followup container: ${a} `),X(H),!0):!1};if(P())return;const W=setInterval(()=>{z++,(P()||z>=V)&&(clearInterval(W),z>=V&&o.warn(`[AdMeshRecommendations] โš ๏ธ Followup container not found after signal: ${a} `))},100);return()=>clearInterval(W)},[x,a,p]),m.useEffect(()=>{if(!n||!r||r.trim()===""){o.log("[AdMeshRecommendations] โŒ Validation failed - missing required parameters"),w(!1);return}if(!(c!=null&&c.fetchRecommendationFromAIPContext)){o.log("[AdMeshRecommendations] SDK fetchRecommendationFromAIPContext not available"),w(!1);return}if(R.current===n){o.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(M.current){o.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}o.log("[AdMeshRecommendations] ๐Ÿ“ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var V,P,W,H,Z;try{M.current=!0,w(!0),S(null);const K=await c.fetchRecommendationFromAIPContext({query:r.trim(),sessionId:u,messageId:n,language:_,geo_country:f,userId:C,model:k,...y&&y.length>0&&{messages:y}}),$=Q(K),O=K.followup_query||$.followup_query,Y=K.followup_engagement_url||$.followup_engagement_url,se=$.recommendation_id||"";O&&(o.debug("[AdMeshRecommendations] โœ… Followup query detected:",O),o.debug("[AdMeshRecommendations] โœ… Followup engagement URL:",Y?"present":"missing"),o.debug("[AdMeshRecommendations] โœ… Recommendation ID:",se||"missing"),Y||o.debug("[AdMeshRecommendations] โš ๏ธ Followup engagement URL is missing (optional)"),se||o.debug("[AdMeshRecommendations] โš ๏ธ Recommendation ID is missing (optional)"),a?o.debug("[AdMeshRecommendations] โœ… Using SDK-managed portal rendering (followups_container_id provided)"):j.current?(o.debug("[AdMeshRecommendations] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),j.current(O,Y||"",se||"")):o.debug("[AdMeshRecommendations] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)")),N($);const ae=K,ie=ae.preferred_format||((V=ae.creative)==null?void 0:V.preferred_format)||((P=ae.winning_bid)==null?void 0:P.preferred_format)||((W=K.creative_input)==null?void 0:W.preferred_format);let oe=ie||"tail";oe==="weave"&&(oe="tail"),v(oe),R.current=n,o.log("[AdMeshRecommendations] ๐Ÿ“Š Format detection:",{preferred_format:ie,selected_format:oe}),w(!1),M.current=!1,(H=D.current)==null||H.call(D,n)}catch(K){const $=K instanceof Error?K:new Error(String(K));$.message.includes("Failed to fetch")||$.message.includes("NetworkError")?o.warn(`[AdMeshRecommendations] โš ๏ธ Network error fetching recommendations(non - critical): ${$.message} `):o.error(`[AdMeshRecommendations] โŒ Error fetching recommendations: ${$.message} `),S($),w(!1),M.current=!1,(Z=A.current)==null||Z.call(A,$)}})()},[c,u,n,r,_,f,C,k]);const re=()=>G&&(x!=null&&x.followup_query)&&c?(o.debug(`[AdMeshRecommendations] ๐ŸŒ€ Rendering followup portal into: ${a} `),Ge.createPortal(d.jsx(Ce,{recommendation:x,theme:g,sdk:c,sessionId:u,onExecuteQuery:i}),G)):(o.debug(`[AdMeshRecommendations] โŒ Skipping followup portal.Container: ${!!G}, Query: ${!!(x!=null&&x.followup_query)}, SDK: ${!!c} `),null);if(!n||!r||r.trim()===""||T||I||!x||!E)return null;const q=x.creative_input||{},ne=!!q.bridge_prompt||!!q.bridge_content,F=(x==null?void 0:x.format)||(q==null?void 0:q.format),U=x==null?void 0:x.preferred_format;if(ne||(F==="bridge"||U==="bridge"||E==="bridge"))return d.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[d.jsx(je,{recommendation:x,theme:g,sessionId:u,onPasteToInput:s}),re()]});if(E==="product_card"){if(x.products&&x.products.length>0)return d.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[d.jsx(De,{brand:x,theme:(g==null?void 0:g.mode)==="dark"?"dark":(g==null?void 0:g.mode)==="light"?"light":"auto",sessionId:u}),re()]});o.warn("[AdMeshRecommendations] product_card format detected but no products array, falling back to tail format")}const ue=q.long_description||q.context_snippet||q.short_description||"";return d.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[d.jsx(Pe,{summaryText:ue,recommendations:[x],theme:g,sessionId:u}),re()]})},rt=({format:t="tail",onError:e,messageId:n,query:r,fallback:s,previousRecommendations:a})=>{const{sdk:i,sessionId:l,theme:p,apiKey:h,language:c,geo_country:u,userId:_,model:f,messages:b}=be(),k=m.useRef(null),[y,g]=m.useState("");return m.useEffect(()=>{n&&g(`admesh-weave-fallback-${n}`)},[n]),o.log("[WeaveFallbackRecommendations] ๐ŸŽจ Component render"),m.useEffect(()=>{if(o.log("[WeaveFallbackRecommendations] ๐Ÿ”„ useEffect triggered",{fallback:s,hasPreviousRecommendations:a&&a.length>0,previousRecommendationsCount:(a==null?void 0:a.length)||0}),!s){o.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(o.log("[WeaveFallbackRecommendations] โœ… fallback is TRUE, proceeding with recommendations"),!n||!r||r.trim()===""){o.log("[WeaveFallbackRecommendations] โŒ Validation failed - returning early");return}if(o.log("[WeaveFallbackRecommendations] โœ… Validation passed"),!i||!y){o.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const C=a&&a.length>0;o.log("[WeaveFallbackRecommendations] ๐Ÿ“Š Checking previous recommendations:",{hasPreviousRecs:C,count:(a==null?void 0:a.length)||0,fallback:s,messageId:n}),C?(o.log(`[WeaveFallbackRecommendations] โ™ป๏ธ Reusing ${a.length} previous recommendation(s), skipping API call`),(async()=>{var N,E,v,T,w,I,S,R,M,D;try{const A=a[0];if(o.log("[WeaveFallbackRecommendations] ๐Ÿ“ฆ Processing AIP response:",{hasAipResponse:!!A,recommendationId:A==null?void 0:A.recommendation_id,hasCreativeInput:!!(A!=null&&A.creative_input)}),A&&process.env.NODE_ENV==="development"&&o.log("[WeaveFallbackRecommendations] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:A.recommendation_id,product_id:A.product_id,brand_id:A.brand_id,title:A.title,click_url:A.click_url,contextual_relevance_score:A.contextual_relevance_score,preferred_format:(N=A.creative_input)==null?void 0:N.preferred_format,resolved_format:(E=A.format_resolution)==null?void 0:E.resolved_format,creative_input:{product_name:(v=A.creative_input)==null?void 0:v.product_name,brand_name:(T=A.creative_input)==null?void 0:T.brand_name,cta_url:(w=A.creative_input)==null?void 0:w.cta_url,short_description:(I=A.creative_input)==null?void 0:I.short_description,allowed_formats:(S=A.creative_input)==null?void 0:S.allowed_formats,fallback_formats:(R=A.creative_input)==null?void 0:R.fallback_formats},format_resolution:A.format_resolution,full_response:A}),!A){o.warn("[WeaveFallbackRecommendations] โš ๏ธ Previous recommendation is empty, falling back to API call"),await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n});return}const j=i,Q=j.convertAIPResponseToRecommendation,G=j.getRenderer,X=j.getTracker,re=(M=j.config)==null?void 0:M.theme;if(Q&&G&&X){const q=Q.call(i,A);if(!q){o.warn("[WeaveFallbackRecommendations] โš ๏ธ Conversion returned empty, falling back to API call"),await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n});return}const ne={session_id:A.session_id||l,message_id:`msg_${A.recommendation_id||n}`,recommendations:[q]},F=G.call(i),U=X.call(i),ce=(i==null?void 0:i.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await F.render({containerId:y,response:ne,theme:p||re,tracker:U,sessionId:l,apiKey:h||((D=i==null?void 0:i.config)==null?void 0:D.apiKey),apiBaseUrl:ce,language:c,geo_country:u,userId:_,model:f,messages:b}),o.log("[WeaveFallbackRecommendations] โœ… Recommendations rendered from previous response (no API call)")}else o.warn("[WeaveFallbackRecommendations] โš ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n})}catch(A){const j=A instanceof Error?A:new Error(String(A));o.error(`[WeaveFallbackRecommendations] โŒ Error rendering previous recommendations: ${j.message}`);try{await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n})}catch{e==null||e(j)}}})()):(o.log("[WeaveFallbackRecommendations] ๐Ÿ“ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(i!=null&&i.showRecommendations)){o.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n}),o.log("[WeaveFallbackRecommendations] โœ… Recommendations displayed successfully")}catch(N){const E=N instanceof Error?N:new Error(String(N));o.log(`[WeaveFallbackRecommendations] โŒ Error: ${E.message}`),e==null||e(E)}})())},[i,l,y,t,n,r,s,e,a,p]),!s||!n||!r||r.trim()===""?null:d.jsx("div",{ref:k,id:y,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},ot=m.createContext(void 0),Mt=({children:t,shouldRenderFallback:e,messageId:n,sessionId:r,query:s})=>d.jsx(ot.Provider,{value:{shouldRenderFallback:e,messageId:n,sessionId:r,query:s},children:t}),Et=()=>m.useContext(ot),Ct={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Tt={"Top Match":"โ˜…","Free Tier":"โ—†","AI Powered":"โ—‰",Popular:"โ–ฒ",New:"โ—","Trial Available":"โ—ˆ"},nt=({type:t,variant:e,size:n="md",className:r,style:s})=>{const a=e||Ct[t]||"secondary",i=Tt[t],l=_e("admesh-component","admesh-badge",`admesh-badge--${a}`,`admesh-badge--${n}`,r);return d.jsxs("span",{className:l,style:s,children:[i&&d.jsx("span",{className:"admesh-badge__icon",children:i}),d.jsx("span",{className:"admesh-badge__text",children:t})]})};nt.displayName="AdMeshBadge";const Se="admesh:streamingStart",Me="admesh:streamingComplete";function Ft(t,e){const n={messageId:t,sessionId:e,timestamp:Date.now()},r=new CustomEvent(Se,{detail:n});window.dispatchEvent(r),o.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function It(t,e,n){const r={messageId:t,sessionId:e,timestamp:Date.now(),metadata:n},s=new CustomEvent(Me,{detail:r});window.dispatchEvent(s),o.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:n})}function Rt(t,e,n){const r=s=>{const a=s;a.detail.messageId===t&&a.detail.sessionId===e&&(o.log("[StreamingEvents] ๐Ÿ“จ Received streamingStart event"),n(a.detail))};return window.addEventListener(Se,r),()=>{window.removeEventListener(Se,r)}}function at(t,e,n){o.log("[StreamingEvents] ๐Ÿ‘‚ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const r=s=>{const a=s;o.log("[StreamingEvents] ๐Ÿ“จ Received streamingComplete event (checking match)",{receivedMessageId:a.detail.messageId,receivedSessionId:a.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:a.detail.messageId===t,sessionIdMatch:a.detail.sessionId===e}),a.detail.messageId===t&&a.detail.sessionId===e?(o.log("[StreamingEvents] โœ… Event matched! Calling callback"),n(a.detail)):o.log("[StreamingEvents] โš ๏ธ Event did not match - ignoring")};return window.addEventListener(Me,r),()=>{o.log("[StreamingEvents] ๐Ÿงน Removing streamingComplete listener"),window.removeEventListener(Me,r)}}const Te=()=>{const t=new Set,e=new Map,n=a=>{const i=e.get(a);i&&(i.observer.disconnect(),i.timeoutId&&clearTimeout(i.timeoutId),e.delete(a))};return{startTracking:({exposureUrl:a,recommendationId:i,linkElement:l,sessionId:p,logPrefix:h="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!a||!l){h&&o.warn(`${h} โš ๏ธ Missing exposure tracking data`);return}const c=`${p||"anonymous"}::${i||a}`;if(t.has(c)||e.has(c))return;const u={observer:void 0,timeoutId:null,viewableStart:null},_=()=>{n(c),t.add(c),fetch(a,{method:"GET",keepalive:!0}).then(()=>{h&&o.log(`${h} โœ… Exposure pixel fired`)}).catch(()=>{h&&o.warn(`${h} โš ๏ธ Failed to fire exposure pixel`),t.delete(c)})},f=new IntersectionObserver(b=>{b.forEach(k=>{k.intersectionRatio>=.5?u.viewableStart===null&&(u.viewableStart=performance.now(),u.timeoutId=setTimeout(_,1e3)):(u.viewableStart=null,u.timeoutId&&(clearTimeout(u.timeoutId),u.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});u.observer=f,f.observe(l),e.set(c,u)},cleanup:()=>{Array.from(e.keys()).forEach(n)}}},Lt=({containerId:t,messageId:e,sessionId:n,sdk:r,query:s,recommendations:a=[],onLinksFound:i,onNoLinksFound:l,children:p})=>{const[h,c]=m.useState(!1),[u,_]=m.useState(!0),[f,b]=m.useState(!1),k=m.useRef(Te()),y=m.useRef(i),g=m.useRef(l),C=m.useRef(t),x=m.useRef(r),N=m.useRef(n),E=m.useRef(s);m.useEffect(()=>{y.current=i,g.current=l,C.current=t,x.current=r,N.current=n,E.current=s},[i,l,t,r,n,s]),m.useEffect(()=>()=>{k.current.cleanup()},[]);const v=m.useCallback(({exposureUrl:w,recommendationId:I,linkElement:S})=>{k.current.startTracking({exposureUrl:w,recommendationId:I,linkElement:S,sessionId:N.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),T=m.useCallback(()=>{o.log("[FinalLinkDetectionCheck] ๐Ÿ” Performing final link detection...");try{const w=document.getElementById(C.current);if(!w){o.warn("[FinalLinkDetectionCheck] โŒ Container not found"),c(!0),l();return}const I=new Be({autoAddLabels:!0,fireExposurePixels:!0}),S=a.length>0?a:[];o.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Using ${S.length} recommendations for link detection`),S.length>0&&process.env.NODE_ENV==="development"&&S.forEach((M,D)=>{var A,j,Q,G,X;o.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Recommendation ${D+1} (DEV):`,{recommendation_id:M.recommendation_id,product_id:M.product_id,title:M.title,click_url:M.click_url,preferred_format:(A=M.creative_input)==null?void 0:A.preferred_format,resolved_format:(j=M.format_resolution)==null?void 0:j.resolved_format,creative_input:{product_name:(Q=M.creative_input)==null?void 0:Q.product_name,brand_name:(G=M.creative_input)==null?void 0:G.brand_name,cta_url:(X=M.creative_input)==null?void 0:X.cta_url}})});const R=I.scanAndProcessLinks(w,S,({exposureUrl:M,recommendationId:D,linkElement:A})=>v({exposureUrl:M,recommendationId:D,linkElement:A}));o.log(`[FinalLinkDetectionCheck] ๐Ÿ“Š Final check result: ${R.length} links`),R.length>0?(o.log("[FinalLinkDetectionCheck] โœ… Links detected - canceling fallback (no API call)"),b(!0),y.current(R.length)):(o.log(`[FinalLinkDetectionCheck] โš ๏ธ No links found - rendering fallback (will use ${S.length} previous recommendation(s) if available)`),b(!1),g.current()),c(!0)}catch{o.error("[FinalLinkDetectionCheck] โŒ Error during final check"),c(!0),g.current()}},[v,a]);return m.useEffect(()=>{o.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:n,recommendationsCount:a.length});let w=null,I=!1;const S=at(e,n,R=>{o.log("[FinalLinkDetectionCheck] ๐ŸŽฏ Received streamingComplete event",{messageId:R.messageId,sessionId:R.sessionId,timestamp:R.timestamp}),I=!0,w&&(clearTimeout(w),w=null),_(!1),setTimeout(()=>{T()},100)});return w=setTimeout(()=>{I||(o.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),_(!1),setTimeout(()=>{T()},100))},5e3),()=>{o.log("[FinalLinkDetectionCheck] ๐Ÿงน Cleaning up listener"),w&&clearTimeout(w),S()}},[e,n]),u?d.jsx(d.Fragment,{}):h?f?(o.log("[FinalLinkDetectionCheck] ๐Ÿšซ Links found - NOT rendering fallback"),d.jsx(d.Fragment,{})):(o.log("[FinalLinkDetectionCheck] โœ… No links found - rendering fallback"),d.jsx(d.Fragment,{children:p})):d.jsx(d.Fragment,{})},Pt=({messageId:t,children:e,fallbackFormat:n="tail",onLinksDetected:r,onNoLinksDetected:s,onError:a,className:i,query:l,onFallbackChange:p,onWeaveAttempt:h,onWeaveOutcome:c,followups_container_id:u,onExecuteQuery:_,onFollowupDetected:f,isContainerReady:b})=>{var ce,ue,z,V;const{sessionId:k,sdk:y,language:g,geo_country:C,userId:x,model:N,messages:E,theme:v}=be(),T=m.useRef(null),w=`weave-ad-container-${t}`,I=m.useRef(Te()),S=m.useRef(!1),R=m.useRef(null),[M,D]=m.useState([]),A=m.useRef([]),[j,Q]=m.useState(null),[G,X]=m.useState(null),re=m.useRef(f);m.useEffect(()=>{re.current=f},[f]),m.useEffect(()=>(R.current||(R.current=new Be({autoAddLabels:!0,fireExposurePixels:!0})),()=>{R.current&&(R.current.stopWatching(),R.current.clearCache())}),[]),m.useEffect(()=>()=>{I.current.cleanup()},[]),m.useEffect(()=>{(async()=>{var W,H,Z,K,$,O,Y,se,ae,ie,oe;if(!y||!(l!=null&&l.trim())||!t){o.log("[WeaveAdFormatContainer] โš ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{o.log("[WeaveAdFormatContainer] ๐Ÿ“ค Fetching recommendations from SDK for brand URL matching");const B=await y.fetchRecommendationFromAIPContext({query:l.trim(),sessionId:k,messageId:t,language:g,geo_country:C,userId:x,model:N,messages:E}),pe=B?[B]:[];if(D(pe),A.current=pe,o.log("[WeaveAdFormatContainer] โœ… Fetched recommendations:",pe.length),B){const xe=B.followup_query,de=(W=B.creative_input)==null?void 0:W.followup_query,le=xe||de,ve=B.followup_engagement_url,L=(H=B.creative_input)==null?void 0:H.followup_engagement_url,J=ve||L,he=B.followup_exposure_url,ge=(Z=B.creative_input)==null?void 0:Z.followup_exposure_url,we=he||ge,ee=B.recommendation_id||"";if(le)if(o.debug("[WeaveAdFormatContainer] โœ… Followup query detected:",le),o.debug("[WeaveAdFormatContainer] โœ… Followup engagement URL:",J?"present":"missing"),o.debug("[WeaveAdFormatContainer] โœ… Recommendation ID:",ee||"missing"),u){o.debug("[WeaveAdFormatContainer] โœ… Using SDK-managed portal rendering (followups_container_id provided)");const ye={...B,followup_query:le,followup_engagement_url:J,followup_exposure_url:we,recommendation_id:ee||B.recommendation_id};Q(ye)}else re.current?(o.debug("[WeaveAdFormatContainer] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),re.current(le,J||"",ee||"")):o.debug("[WeaveAdFormatContainer] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)");else Q(null)}B&&process.env.NODE_ENV==="development"&&o.log("[WeaveAdFormatContainer] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:B.recommendation_id,product_id:B.product_id,brand_id:B.brand_id,title:B.title,click_url:B.click_url,contextual_relevance_score:B.contextual_relevance_score,preferred_format:(K=B.creative_input)==null?void 0:K.preferred_format,resolved_format:($=B.format_resolution)==null?void 0:$.resolved_format,creative_input:{product_name:(O=B.creative_input)==null?void 0:O.product_name,brand_name:(Y=B.creative_input)==null?void 0:Y.brand_name,cta_url:(se=B.creative_input)==null?void 0:se.cta_url,short_description:(ae=B.creative_input)==null?void 0:ae.short_description,allowed_formats:(ie=B.creative_input)==null?void 0:ie.allowed_formats,fallback_formats:(oe=B.creative_input)==null?void 0:oe.fallback_formats},format_resolution:B.format_resolution,full_response:B})}catch(B){o.warn("[WeaveAdFormatContainer] โš ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",B),D([])}})()},[y,k,t,l,u]),m.useEffect(()=>{if(!(j!=null&&j.followup_query)||!u){X(null);return}if(b===!1){o.debug("[WeaveAdFormatContainer] โณ Waiting for container signal...");return}let P=0;const W=5,H=()=>{const K=document.getElementById(u);return K?(o.debug(`[WeaveAdFormatContainer] โœ… Found followup container: ${u} `),X(K),!0):!1};if(H())return;const Z=setInterval(()=>{P++,(H()||P>=W)&&(clearInterval(Z),P>=W&&o.warn(`[WeaveAdFormatContainer] โš ๏ธ Followup container not found after signal: ${u} `))},100);return()=>clearInterval(Z)},[j,u,b]),m.useEffect(()=>{const P=T.current;if(!P||!R.current)return;const W=R.current,H=({exposureUrl:$,recommendationId:O,linkElement:Y})=>{I.current.startTracking({exposureUrl:$,recommendationId:O,linkElement:Y,sessionId:k,logPrefix:"[WeaveAdFormatContainer]"})},K=setTimeout(()=>{o.log("[WeaveAdFormatContainer] ๐Ÿ” Weave injection attempt started"),h==null||h(t);const $=A.current.length>0?A.current:[];o.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Using ${$.length} recommendations for link detection`);try{const O=W.scanAndProcessLinks(P,$,H);O.length>0&&!S.current?(S.current=!0,o.log(`[WeaveAdFormatContainer] โœ… Weave injection succeeded: ${O.length} links detected`),c==null||c(t,!0,`Found ${O.length} links`),r==null||r(O.length),p==null||p(!1)):S.current||o.log("[WeaveAdFormatContainer] โš ๏ธ Weave injection: no links found on initial scan")}catch(O){const Y=O instanceof Error?O.message:String(O);o.error(`[WeaveAdFormatContainer] โŒ Weave injection failed: ${Y}`),c==null||c(t,!1,Y),s==null||s(),p==null||p(!0)}},100);return W.watchForNewLinks(P,A.current,H),()=>{clearTimeout(K),W.stopWatching()}},[e,k,t,r,p,h,c]);const q=(ue=(ce=M[0])==null?void 0:ce.format_resolution)==null?void 0:ue.resolved_format,ne=(V=(z=M[0])==null?void 0:z.creative_input)==null?void 0:V.preferred_format,F=q==="weave"||ne==="weave";m.useEffect(()=>{l&&F&&o.log(`[WeaveAdFormatContainer] ๐ŸŽฏ Format is "weave" (resolved: ${q}, preferred: ${ne}) - skipping fallback recommendations`)},[l,F,q,ne]);const U=()=>G&&(j!=null&&j.followup_query)&&y?(o.debug(`[WeaveAdFormatContainer] ๐ŸŒ€ Rendering followup portal into: ${u} `),Ge.createPortal(d.jsx(Ce,{recommendation:j,theme:v,sdk:y,sessionId:k,onExecuteQuery:_}),G)):(o.debug(`[WeaveAdFormatContainer] โŒ Skipping followup portal. Container: ${!!G}, Query: ${!!(j!=null&&j.followup_query)}, SDK: ${!!y} `),null);return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:T,id:w,className:i,"data-weave-ad-format":"true","data-message-id":t,children:e}),l&&!F&&d.jsx(Lt,{containerId:w,messageId:t,sessionId:k,sdk:y,query:l,recommendations:M,onLinksFound:P=>{o.log(`[WeaveAdFormatContainer] โœ… Links found (${P}) - no fallback needed`),c==null||c(t,!0,`Found ${P} links in final check`),r==null||r(P),p==null||p(!1)},onNoLinksFound:()=>{o.log("[WeaveAdFormatContainer] โš ๏ธ No links found - rendering fallback"),o.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Passing ${M.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),s==null||s(),p==null||p(!0)},children:d.jsx(rt,{format:n,messageId:t,query:l,fallback:!0,onError:a,previousRecommendations:M.length>0?M:void 0})}),U()]})},Ie="admesh-ui-sdk-styles",Re="admesh-ui-sdk-reset",jt=`
23
+ `}})]})},Xe=({recommendations:t,summaryText:e,theme:n,className:r,style:s,onLinkClick:a,onPasteToInput:i,sessionId:l,response:p})=>{var f;const h=t||(p==null?void 0:p.recommendations)||[];let c=e||(p==null?void 0:p.tail_summary);const u=h.filter(b=>b&&typeof b=="object"&&b.recommendation_id);if(!u||u.length===0)return o.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;if(!c&&u.length>0&&((f=u[0])!=null&&f.creative_input)){const b=u[0].creative_input;c=b.long_description||b.context_snippet||b.short_description||void 0}o.log(`[AdMeshLayout] Rendering with ${u.length} valid recommendations`);const _=()=>{if(u.length>0){const b=u[0],k=(b==null?void 0:b.creative_input)||{},y=(b==null?void 0:b.preferred_format)||(k==null?void 0:k.preferred_format);if(o.log("[AdMeshLayout] ๐Ÿ” Checking format:",{preferredFormat:y,creativeInputKeys:Object.keys(k),recommendationKeys:Object.keys(b||{})}),y==="product_card"){const x=(b==null?void 0:b.products)||(k==null?void 0:k.products)||[];if(x&&x.length>0)return o.log(`[AdMeshLayout] ๐Ÿ›๏ธ Rendering product_card format with ${x.length} products`),d.jsx(De,{brand:b,theme:n,sessionId:l});o.warn("[AdMeshLayout] product_card format detected but no products array, falling back to tail")}if(!!k.bridge_prompt||!!k.bridge_content||y==="bridge")return o.log("[AdMeshLayout] ๐ŸŽฏ โœ… Rendering bridge format"),d.jsx(je,{recommendation:b,theme:n,sessionId:l,onLinkClick:a,onPasteToInput:i});o.log("[AdMeshLayout] โš ๏ธ Bridge format NOT detected, falling back to other formats")}return c?d.jsx(Pe,{summaryText:c,recommendations:u,theme:n,onLinkClick:a,sessionId:l}):null};return d.jsx("div",{className:`admesh-layout ${r}`,style:{fontFamily:(n==null?void 0:n.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:_()})},At=({className:t,size:e=20})=>d.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:[d.jsx("path",{d:"M5 12h14"}),d.jsx("path",{d:"M12 5v14"})]}),Ce=({recommendation:t,theme:e,sdk:n,sessionId:r,onExecuteQuery:s})=>{const a=t.followup_query,i=t.followup_engagement_url,l=t.followup_exposure_url,p=t.recommendation_id;if(!a||!i||!l)return o.log("[AdMeshFollowup] Missing followup_query, followup_engagement_url, or followup_exposure_url - not rendering"),null;const h=async()=>{try{i&&p&&(o.log("[AdMeshFollowup] ๐ŸŽฏ Firing follow-up engagement tracking"),await n.fireFollowupEngagement(i,p,r)),s&&a?(o.log(`[AdMeshFollowup] ๐Ÿ” Executing query: ${a}`),await s(a)):o.warn("[AdMeshFollowup] โš ๏ธ onExecuteQuery not provided - cannot execute query")}catch(c){o.error("[AdMeshFollowup] โŒ Error handling follow-up click:",c)}};return e!=null&&e.mode,d.jsx(ke,{productId:t.product_id||"",recommendationId:p||"",exposureUrl:l,sessionId:r,className:"admesh-followup-container",style:{width:"100%"},children:d.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[d.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),d.jsxs("div",{onClick:h,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&h()},"aria-label":`Sponsored follow-up: ${a}`,children:[d.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:a}),d.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),d.jsx(At,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})};class Je{constructor(e){te(this,"firedExposures",new Set);te(this,"debug",!1);te(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,n,r){const s=`${r}_${n}`;if(this.firedExposures.has(s)){this.debug&&o.log("[Tracker] Exposure already fired");return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&o.warn("[Tracker] Failed to fire exposure")}),this.debug&&o.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&o.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,n,r,s){const a=`${r}_${n}`;if(this.firedExposures.has(a)){this.debug&&o.log("[Tracker] MRC exposure already fired");return}return new Promise(i=>{let l=null,p=null;const h=new IntersectionObserver(_=>{_.forEach(f=>{f.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?l===null&&(l=Date.now(),this.debug&&o.log("[Tracker] Ad reached MRC visibility threshold"),p=setTimeout(()=>{this.fireExposure(e,n,r),h.disconnect(),i()},this.mrcThreshold.minimumDurationMs)):l!==null&&(p&&(clearTimeout(p),p=null),l=null,this.debug&&o.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});h.observe(s);const u=setTimeout(()=>{h.disconnect(),p&&clearTimeout(p),i()},3e4);s.__admeshTrackerCleanup=()=>{h.disconnect(),p&&clearTimeout(p),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,n,r){this.fireExposure(e,n,r)}fireFollowupEngagement(e,n,r){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:r})}).catch(s=>{this.debug&&o.warn("[Tracker] Failed to fire followup engagement (non-critical):",s)}).then(()=>{})}}const Le=({apiKey:t,sessionId:e,theme:n,apiBaseUrl:r,language:s,geo_country:a,userId:i,model:l,messages:p,children:h})=>{const c=m.useRef(null),[u,_]=m.useState(new Set);m.useEffect(()=>{if(!e||e.trim()===""){o.error("[AdMeshProvider] โŒ sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");return}},[e]),m.useEffect(()=>{if(!t){o.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){o.error("[AdMeshProvider] โŒ Cannot initialize SDK: sessionId is required and must be provided by the platform");return}try{c.current=new tt({apiKey:t,theme:n,apiBaseUrl:r}),o.log("[AdMeshProvider] โœ… AdMesh SDK initialized"),r&&o.log("[AdMeshProvider] ๐Ÿ“ Using custom API base URL")}catch{o.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK")}return()=>{o.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,n,r]);const f={sdk:c.current,apiKey:t,sessionId:e,theme:n,language:s,geo_country:a,userId:i,model:l,messages:p,processedMessageIds:u,markMessageAsProcessed:b=>{_(k=>{const y=new Set(k);return y.add(b),y})},isMessageProcessed:b=>u.has(b)};return d.jsx(Ee.Provider,{value:f,children:h})};class et{constructor(){te(this,"roots",new Map)}async render(e){var n;try{o.log("[AdMeshRenderer] ๐ŸŽจ Attempting to render recommendations");const r=e.response.recommendations||[];if(r.length===0){o.log("[AdMeshRenderer] โš ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw o.error("[AdMeshRenderer] โŒ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);o.log("[AdMeshRenderer] โœ… Container ready");const a=this.roots.get(e.containerId);a&&(o.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing root"),a.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const i=ze.createRoot(s),l=((n=r[0])==null?void 0:n.tail_summary)||"";o.log("[AdMeshRenderer] ๐Ÿ“Š Rendering recommendations");const p=e.onPasteToInput||(typeof window<"u"?window.__admesh_onPasteToInput:void 0);if(i.render(d.jsx(Le,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,geo_country:e.geo_country,userId:e.userId,model:e.model,messages:e.messages,children:d.jsx(Xe,{recommendations:r,summaryText:l,theme:e.theme,sessionId:e.sessionId,onPasteToInput:p})})),s.style.display="block",o.log("[AdMeshRenderer] โœ… Recommendations rendered successfully"),this.roots.set(e.containerId,i),e.followups_container_id){const h=r[0];h!=null&&h.followup_query&&(h!=null&&h.followup_engagement_url)&&await this.renderFollowup({containerId:e.followups_container_id,recommendation:h,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,apiKey:e.apiKey,apiBaseUrl:e.apiBaseUrl,onExecuteQuery:e.onExecuteQuery})}}catch(r){throw o.error("[AdMeshRenderer] โŒ Error rendering recommendations"),r}}async renderFollowup(e){try{o.log(`[AdMeshRenderer] ๐ŸŽฏ Rendering follow-up in container: ${e.containerId}`);const n=document.getElementById(e.containerId);if(!n){o.warn(`[AdMeshRenderer] โš ๏ธ Followups container not found: ${e.containerId}`);return}const r=this.roots.get(e.containerId);r&&(o.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing followup root"),r.unmount(),this.roots.delete(e.containerId)),n.innerHTML="";const s=ze.createRoot(n);s.render(d.jsx(Le,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,children:d.jsx(Ce,{recommendation:e.recommendation,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,onExecuteQuery:e.onExecuteQuery})})),n.style.display="block",o.log("[AdMeshRenderer] โœ… Follow-up rendered successfully"),this.roots.set(e.containerId,s)}catch{o.error("[AdMeshRenderer] โŒ Error rendering follow-up")}}unmount(e){const n=this.roots.get(e);if(n){n.unmount(),this.roots.delete(e);const r=document.getElementById(e);r&&(r.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class tt{constructor(e){te(this,"config");te(this,"apiBaseUrl");te(this,"renderer",null);te(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static createSession(){const e=Date.now(),n=Math.random().toString(36).substring(2,15);return`session_${e}_${n}`}static createMessageId(e){const n=Date.now(),r=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${n}_${r}`:`msg_${n}_${r}`}getRenderer(){return this.renderer||(this.renderer=new et),this.renderer}getTracker(){return this.tracker||(this.tracker=new Je({apiKey:this.config.apiKey})),this.tracker}async showRecommendations(e){try{if(!e.session_id||e.session_id.trim()==="")throw new Error("session_id 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 n=await this.fetchRecommendationFromAIPContext({query:e.query,sessionId:e.session_id,messageId:e.messageId,platformSurface:e.platformSurface,model:e.model,messages:e.messages,language:e.locale,geo_country:e.geo,userId:e.userId}),r=this.convertAIPResponseToRecommendation(n),s={session_id:n.session_id,message_id:`msg_${n.recommendation_id}`,recommendations:[r]},a=this.getRenderer(),i=this.getTracker();await a.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:i,sessionId:e.session_id,apiKey:this.config.apiKey,apiBaseUrl:this.apiBaseUrl,language:e.locale,geo_country:e.geo,userId:e.userId,model:e.model,messages:e.messages,onPasteToInput:e.onPasteToInput,onExecuteQuery:e.onExecuteQuery})}catch(n){throw o.error("[AdMeshSDK] Error showing recommendations"),n}}async fetchRecommendationFromAIPContext(e){var u,_,f;const n=`${this.apiBaseUrl}/aip/context`;if(o.log("[AdMeshSDK] ๐Ÿ“ฅ fetchRecommendationFromAIPContext called"),!e.sessionId||e.sessionId.trim()===""){const b=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw o.error("[AdMeshSDK] โŒ sessionId not provided by platform - cannot process request"),b}const r=e.messageId;if(!r||r.trim()===""){const b=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw o.error("[AdMeshSDK] โŒ messageId not provided by platform - cannot process request"),b}const s=e.messages?e.messages.length:0,a=(typeof window<"u"&&window.navigator,"web"),i=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",l={spec_version:"1.0.0",message_id:r,timestamp:new Date().toISOString(),producer:{agent_id:"placeholder",agent_role:"publisher",software:"admesh_ui_sdk",software_version:e.model||"1.0.0"},context:{language:e.language||"en-US",publisher:"placeholder",placement:{ad_unit:e.platformSurface||"web"},device:{platform:a,form_factor:i},geography:{country:e.geo_country||"US"}},identity:{namespace:"platform_user",value_hash:e.userId||"",confidence:1},extensions:{aip:{session_id:e.sessionId,turn_index:s,query_text:e.query,messages:e.messages||[],cpx_floor:0}}};(!l.extensions.aip.query_text||!l.extensions.aip.query_text.trim())&&o.warn("[AdMeshSDK] โš ๏ธ Warning: Sending request with empty query_text");const p=JSON.stringify(l);o.log("[AdMeshSDK] ๐Ÿ“ค Sending request to /aip/context");const h=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:p});if(!h.ok){const k=(await h.json().catch(()=>({}))).detail||`HTTP ${h.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${k}`)}const c=await h.json();return o.log("[AdMeshSDK] ๐Ÿ“ฅ Raw response from /aip/context:",{hasCreative:!!c.creative,creativeFormat:(u=c.creative)==null?void 0:u.format,creativeBridgeContent:(_=c.creative)!=null&&_.bridge_content?c.creative.bridge_content.substring(0,50)+"...":void 0,hasWinningBid:!!c.winning_bid,winningBidPreferredFormat:(f=c.winning_bid)==null?void 0:f.preferred_format,topLevelKeys:Object.keys(c)}),c}convertAIPResponseToRecommendation(e){var F,w,I,S,R,M,D;const n=e;let r=e.creative_input||{};const s=n.creative||{},a=s.format||n.format||((F=n.winning_bid)==null?void 0:F.preferred_format),i=s.headline,l=s.bridge_headline,p=s.bridge_description,h=s.bridge_prompt||s.bridge_content,c=h||r.bridge_prompt||r.bridge_content,u=s.cta_label,_=u||r.cta_label,f=l||r.bridge_headline,b=p||r.bridge_description;o.log("[AdMeshSDK] ๐Ÿ” Extracting from response:",{creativeObject:s,creativeFormat:s.format,creativeBridgeHeadline:l,creativeBridgeDescription:p?String(p).substring(0,50)+"...":void 0,creativeBridgePrompt:h?String(h).substring(0,50)+"...":void 0,creativeCtaLabel:u,extractedFormat:a,extractedBridgeHeadline:f,extractedBridgeDescription:b?String(b).substring(0,50)+"...":void 0,extractedBridgePrompt:c?String(c).substring(0,50)+"...":void 0,extractedCtaLabel:_,creativeInputHasBridgeHeadline:!!r.bridge_headline,creativeInputHasBridgeDescription:!!r.bridge_description,creativeInputHasBridgePrompt:!!r.bridge_prompt,creativeInputHasBridgeContent:!!r.bridge_content,creativeInputHasCtaLabel:!!r.cta_label});const k=r.assets||{};r={...r,assets:k,...i&&{headline:i},...f&&{bridge_headline:f},...b&&{bridge_description:b},...c&&{bridge_prompt:c},...c&&{bridge_content:c},..._&&{cta_label:_},...a&&{format:a}};const y=e.recommendation_id||n.recommendation_id||n.bid_id||"",g=e.click_url||e.admesh_link||"",T={...e,recommendation_id:y,admesh_link:g||e.click_url||"",ad_id:void 0,bid_id:void 0,creative_input:r,product_title:e.title,tail_summary:r.long_description||"",product_summary:r.short_description||"",weave_summary:r.context_snippet||"",product_logo:(w=r.assets)!=null&&w.logo_url?{url:r.assets.logo_url}:void 0,categories:r.categories||[]};delete T.ad_id,delete T.bid_id;const x=(e==null?void 0:e.products)||[],N=(r==null?void 0:r.products)||[],E=x.length>0?x:N;E&&E.length>0&&(T.products=E,o.log(`[AdMeshSDK] โœ… Preserved ${E.length} products for product_card format`));const v=(e==null?void 0:e.preferred_format)||(r==null?void 0:r.preferred_format);return v&&(T.preferred_format=v,o.log(`[AdMeshSDK] โœ… Preserved preferred_format: ${v}`)),o.log("[AdMeshSDK] ๐Ÿ”„ Converted recommendation:",{preferredFormat:v,hasProducts:!!(E&&E.length>0),productsCount:(E==null?void 0:E.length)||0,hasBridgeHeadline:!!f,bridgeHeadline:f,hasBridgeDescription:!!b,bridgeDescriptionPreview:b?String(b).substring(0,50)+"...":void 0,hasBridgePrompt:!!c,hasCtaLabel:!!_,ctaLabel:_,bridgeHeadlineInCreativeInput:!!((I=T.creative_input)!=null&&I.bridge_headline),bridgeDescriptionInCreativeInput:!!((S=T.creative_input)!=null&&S.bridge_description),bridgePromptInCreativeInput:!!((R=T.creative_input)!=null&&R.bridge_prompt),bridgeContentInCreativeInput:!!((M=T.creative_input)!=null&&M.bridge_content),ctaLabelInCreativeInput:!!((D=T.creative_input)!=null&&D.cta_label),bridgePromptPreview:c?String(c).substring(0,50)+"...":void 0,creativeInputKeys:Object.keys(T.creative_input||{})}),T}fireFollowupExposure(e,n,r){this.getTracker().fireFollowupExposure(e,n,r)}async fireFollowupEngagement(e,n,r){return this.getTracker().fireFollowupEngagement(e,n,r)}}class Be{constructor(e={}){te(this,"autoAddLabels");te(this,"fireExposurePixels");te(this,"labelStyle");te(this,"processedLinks",new Set);te(this,"mutationObserver",null);var n,r,s,a;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((n=e.labelStyle)==null?void 0:n.fontSize)||"0.75em",fontWeight:((r=e.labelStyle)==null?void 0:r.fontWeight)||"bold",color:((s=e.labelStyle)==null?void 0:s.color)||"#666",marginLeft:((a=e.labelStyle)==null?void 0:a.marginLeft)||"2px"}}getLinksToProcess(e){const r=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return r.length>0?Array.from(r):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,n,r){if(!e)return[];const s=[];if(n.length>0){const a=this.getLinksToProcess(e),i=new Map(n.filter(p=>p.click_url).map(p=>[p.click_url,p])),l=new Map;n.forEach(p=>{var c;const h=p.redirect_url||p.url||((c=p.creative_input)==null?void 0:c.cta_url);if(h&&typeof h=="string"){const u=h.trim().replace(/\/$/,"");l.set(u,p),l.set(`${u}/`,p)}}),a.forEach(p=>{const h=p.getAttribute("href")||"",c=`${h}`;if(this.processedLinks.has(c))return;let u=i.get(h),_=h;if(!u){const f=h.trim().replace(/\/$/,"");u=l.get(f)||l.get(`${f}/`),u&&u.click_url&&(o.log("[WeaveResponseProcessor] ๐Ÿ”„ Found brand URL match, replacing with click_url:",h),p.setAttribute("href",u.click_url),_=u.click_url)}if(u){this.processedLinks.add(c),p.setAttribute("target","_blank"),p.setAttribute("rel","noopener noreferrer");const f={element:p,href:_,text:p.textContent||"",hasAdLabel:this.hasAdLabel(p),matchedRecommendation:{recommendation_id:u.recommendation_id||"",click_url:u.click_url,exposure_url:u.exposure_url}};this.autoAddLabels&&!f.hasAdLabel?(o.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to matched recommendation link:",_),this.addAdLabel(p),f.hasAdLabel=!0):this.autoAddLabels?f.hasAdLabel&&o.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):o.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&u.exposure_url&&r&&f.matchedRecommendation&&r({exposureUrl:u.exposure_url,recommendationId:f.matchedRecommendation.recommendation_id,linkElement:p}),s.push(f)}})}else Array.from(e.querySelectorAll("a")).forEach(i=>{const l=i.getAttribute("href")||"",p=`${l}`;if(this.processedLinks.has(p))return;if(this.isAdMeshLink(l)){this.processedLinks.add(p);const c={element:i,href:l,text:i.textContent||"",hasAdLabel:this.hasAdLabel(i),matchedRecommendation:void 0};if(i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(o.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to pattern-matched AdMesh link:",l),this.addAdLabel(i),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&o.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):o.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&r){const u=this.convertClickUrlToExposureUrl(l);r({exposureUrl:u,recommendationId:this.extractRecommendationIdFromUrl(l),linkElement:i})}s.push(c)}});return s}hasAdLabel(e){var i,l,p;if((e.textContent||"").includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Link text contains [Ad] label"),!0;const r=e.querySelectorAll("sub, span");for(const h of Array.from(r))if((i=h.textContent)!=null&&i.includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Link has [Ad] label as child element"),!0;let s=e.previousSibling;for(;s&&s.nodeType===Node.TEXT_NODE;){const h=s.textContent||"";if(h.trim()===""){s=s.previousSibling;continue}if(h.includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous text sibling"),!0;break}if(s&&s.nodeType===Node.ELEMENT_NODE){const h=s,c=h.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((l=h.textContent)!=null&&l.includes("[Ad]")))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous element sibling:",c),!0}let a=e.nextSibling;for(;a&&a.nodeType===Node.TEXT_NODE;){const h=a.textContent||"";if(h.trim()===""){a=a.nextSibling;continue}if(h.includes("[Ad]"))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next text sibling"),!0;break}if(a&&a.nodeType===Node.ELEMENT_NODE){const h=a,c=h.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((p=h.textContent)!=null&&p.includes("[Ad]")))return o.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next element sibling:",c),!0}return o.log("[WeaveResponseProcessor] โ„น๏ธ No existing [Ad] label found"),!1}addAdLabel(e){if(o.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Attempting to add [Ad] label to link:",e.href),!e.isConnected){o.warn("[WeaveResponseProcessor] โš ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){o.log("[WeaveResponseProcessor] โ„น๏ธ Link already has [Ad] label, skipping");return}const n=e.parentNode;if(!n){o.error("[WeaveResponseProcessor] โŒ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const r=document.createElement("sub");r.textContent="[Ad]",r.style.fontSize=this.labelStyle.fontSize,r.style.fontWeight=this.labelStyle.fontWeight,r.style.color=this.labelStyle.color,r.style.marginLeft=this.labelStyle.marginLeft,r.style.cursor="pointer",r.style.borderBottom=`1px dotted ${this.labelStyle.color}`,r.style.whiteSpace="nowrap",r.title="Why this ad? This is a sponsored recommendation based on your search query.";let s=!1;r.addEventListener("mouseenter",()=>{r.style.opacity="0.7"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1",s&&(s=!1)}),r.addEventListener("click",i=>{i.stopPropagation(),s=!s,s?(r.style.textDecoration="underline",r.style.opacity="0.7"):(r.style.textDecoration="none",r.style.opacity="1")});const a=i=>{s&&i.target!==r&&(s=!1,r.style.textDecoration="none",r.style.opacity="1")};document.addEventListener("click",a);try{const i=e.nextSibling;i?(n.insertBefore(r,i),o.log("[WeaveResponseProcessor] โœ… [Ad] label inserted before next sibling")):(n.appendChild(r),o.log("[WeaveResponseProcessor] โœ… [Ad] label appended to parent (no next sibling)")),r.isConnected&&r.parentNode===n?o.log("[WeaveResponseProcessor] โœ… [Ad] label successfully added to link:",e.href):o.error("[WeaveResponseProcessor] โŒ [Ad] label insertion failed - label not in DOM")}catch(i){o.error("[WeaveResponseProcessor] โŒ Error inserting [Ad] label:",i)}}removeLeftAdLabel(e){var r,s,a;let n=e.previousSibling;for(;n&&n.nodeType===Node.TEXT_NODE;){const i=n.textContent||"";if(i.trim()===""){n=n.previousSibling;continue}if(i.includes("[Ad]")){(r=n.parentNode)==null||r.removeChild(n);return}break}if(n&&n.nodeType===Node.ELEMENT_NODE){const i=n;(i.tagName==="SUB"||i.tagName==="SPAN")&&((s=i.textContent)!=null&&s.includes("[Ad]"))&&((a=i.parentNode)==null||a.removeChild(i))}}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(s=>e.includes(s)))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 n=e.match(/\/click\/([^/?]+)/);return n&&n[1]?n[1]:""}catch{return e}}convertClickUrlToExposureUrl(e){try{const n=new URL(e),s=`${`${n.protocol}//${n.host}`}/exposure`,a=new URLSearchParams(n.search);return a.has("cpx")||a.set("cpx","0"),`${s}?${a.toString()}`}catch{return o.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,n,r){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,n,r)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}const St=({onRecommendationsShown:t,onError:e,messageId:n,query:r,onPasteToInput:s,followups_container_id:a,onExecuteQuery:i,onFollowupDetected:l,isContainerReady:p,userId:h})=>{const{sdk:c,sessionId:u,language:_,geo_country:f,userId:b,model:k,messages:y,theme:g}=be(),T=h||b,[x,N]=m.useState(null),[E,v]=m.useState(null),[F,w]=m.useState(!0),[I,S]=m.useState(null),R=m.useRef(null),M=m.useRef(!1),D=m.useRef(t),A=m.useRef(e),j=m.useRef(l);m.useEffect(()=>{D.current=t,A.current=e,j.current=l},[t,e,l]);const G=$=>{var Ae,ue,Ue,$e,We;const z=$;let P=$.creative_input||{};const W=z.creative||{},K=W.format||z.format||((Ae=z.winning_bid)==null?void 0:Ae.preferred_format)||((ue=$.creative_input)==null?void 0:ue.preferred_format),Z=W.headline,O=W.bridge_headline,V=W.bridge_description,Q=W.bridge_prompt||W.bridge_content||P.bridge_prompt||P.bridge_content,se=W.cta_label||P.cta_label,de=O||P.bridge_headline,oe=V||P.bridge_description,U=P.assets||{};P={...P,assets:U,...Z&&{headline:Z},...de&&{bridge_headline:de},...oe&&{bridge_description:oe},...Q&&{bridge_prompt:Q},...Q&&{bridge_content:Q},...se&&{cta_label:se},...K&&{format:K}};const pe=$.recommendation_id||$.bid_id||"",xe=$.click_url||$.admesh_link||"",ce={...$,recommendation_id:pe,admesh_link:xe||$.click_url||"",creative_input:P,ad_id:void 0,bid_id:void 0,...K&&{format:K}};delete ce.ad_id,delete ce.bid_id;const me=$.followup_query,ve=((Ue=$.creative_input)==null?void 0:Ue.followup_query)||(P==null?void 0:P.followup_query),L=me||ve,J=$.followup_engagement_url,he=(($e=$.creative_input)==null?void 0:$e.followup_engagement_url)||(P==null?void 0:P.followup_engagement_url),ge=J||he,we=$.followup_exposure_url,ee=((We=$.creative_input)==null?void 0:We.followup_exposure_url)||(P==null?void 0:P.followup_exposure_url),ye=we||ee;return L&&(ce.followup_query=L,o.debug("[AdMeshRecommendations] โœ… Extracted followup_query:",L.substring(0,50)+"...")),ge&&(ce.followup_engagement_url=ge,o.debug("[AdMeshRecommendations] โœ… Extracted followup_engagement_url")),ye&&(ce.followup_exposure_url=ye,o.debug("[AdMeshRecommendations] โœ… Extracted followup_exposure_url")),ce};m.useEffect(()=>{R.current!==n&&(R.current=null,N(null),v(null))},[n]);const[Y,X]=m.useState(null);m.useEffect(()=>{if(!(x!=null&&x.followup_query)||!a){X(null);return}if(p===!1){o.debug("[AdMeshRecommendations] โณ Waiting for container signal...");return}let $=0;const z=5,P=()=>{const K=document.getElementById(a);return K?(o.debug(`[AdMeshRecommendations] โœ… Found followup container: ${a} `),X(K),!0):!1};if(P())return;const W=setInterval(()=>{$++,(P()||$>=z)&&(clearInterval(W),$>=z&&o.warn(`[AdMeshRecommendations] โš ๏ธ Followup container not found after signal: ${a} `))},100);return()=>clearInterval(W)},[x,a,p]),m.useEffect(()=>{if(!n||!r||r.trim()===""){o.log("[AdMeshRecommendations] โŒ Validation failed - missing required parameters"),w(!1);return}if(!(c!=null&&c.fetchRecommendationFromAIPContext)){o.log("[AdMeshRecommendations] SDK fetchRecommendationFromAIPContext not available"),w(!1);return}if(R.current===n){o.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(M.current){o.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}o.log("[AdMeshRecommendations] ๐Ÿ“ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var z,P,W,K,Z;try{M.current=!0,w(!0),S(null);const O=await c.fetchRecommendationFromAIPContext({query:r.trim(),sessionId:u,messageId:n,language:_,geo_country:f,userId:T,model:k,...y&&y.length>0&&{messages:y}}),V=G(O),H=O.followup_query||V.followup_query,Q=O.followup_engagement_url||V.followup_engagement_url,ie=V.recommendation_id||"";H&&(o.debug("[AdMeshRecommendations] โœ… Followup query detected:",H),o.debug("[AdMeshRecommendations] โœ… Followup engagement URL:",Q?"present":"missing"),o.debug("[AdMeshRecommendations] โœ… Recommendation ID:",ie||"missing"),Q||o.debug("[AdMeshRecommendations] โš ๏ธ Followup engagement URL is missing (optional)"),ie||o.debug("[AdMeshRecommendations] โš ๏ธ Recommendation ID is missing (optional)"),a?o.debug("[AdMeshRecommendations] โœ… Using SDK-managed portal rendering (followups_container_id provided)"):j.current?(o.debug("[AdMeshRecommendations] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),j.current(H,Q||"",ie||"")):o.debug("[AdMeshRecommendations] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)")),N(V);const se=O,de=se.preferred_format||((z=se.creative)==null?void 0:z.preferred_format)||((P=se.winning_bid)==null?void 0:P.preferred_format)||((W=O.creative_input)==null?void 0:W.preferred_format);let oe=de||"tail";oe==="weave"&&(oe="tail"),v(oe),R.current=n,o.log("[AdMeshRecommendations] ๐Ÿ“Š Format detection:",{preferred_format:de,selected_format:oe}),w(!1),M.current=!1,(K=D.current)==null||K.call(D,n)}catch(O){const V=O instanceof Error?O:new Error(String(O));V.message.includes("Failed to fetch")||V.message.includes("NetworkError")?o.warn(`[AdMeshRecommendations] โš ๏ธ Network error fetching recommendations(non - critical): ${V.message} `):o.error(`[AdMeshRecommendations] โŒ Error fetching recommendations: ${V.message} `),S(V),w(!1),M.current=!1,(Z=A.current)==null||Z.call(A,V)}})()},[c,u,n,r,_,f,T,k]);const re=()=>Y&&(x!=null&&x.followup_query)&&c?(o.debug(`[AdMeshRecommendations] ๐ŸŒ€ Rendering followup portal into: ${a} `),Ge.createPortal(d.jsx(Ce,{recommendation:x,theme:g,sdk:c,sessionId:u,onExecuteQuery:i}),Y)):(o.debug(`[AdMeshRecommendations] โŒ Skipping followup portal.Container: ${!!Y}, Query: ${!!(x!=null&&x.followup_query)}, SDK: ${!!c} `),null);if(!n||!r||r.trim()===""||F||I||!x||!E)return null;const q=x.creative_input||{},ne=!!q.bridge_prompt||!!q.bridge_content,C=(x==null?void 0:x.format)||(q==null?void 0:q.format),B=x==null?void 0:x.preferred_format;if(ne||(C==="bridge"||B==="bridge"||E==="bridge"))return d.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[d.jsx(je,{recommendation:x,theme:g,sessionId:u,onPasteToInput:s}),re()]});if(E==="product_card"){if(x.products&&x.products.length>0)return d.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[d.jsx(De,{brand:x,theme:(g==null?void 0:g.mode)==="dark"?"dark":(g==null?void 0:g.mode)==="light"?"light":"auto",sessionId:u}),re()]});o.warn("[AdMeshRecommendations] product_card format detected but no products array, falling back to tail format")}const le=q.long_description||q.context_snippet||q.short_description||"";return d.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[d.jsx(Pe,{summaryText:le,recommendations:[x],theme:g,sessionId:u}),re()]})},rt=({format:t="tail",onError:e,messageId:n,query:r,fallback:s,previousRecommendations:a})=>{const{sdk:i,sessionId:l,theme:p,apiKey:h,language:c,geo_country:u,userId:_,model:f,messages:b}=be(),k=m.useRef(null),[y,g]=m.useState("");return m.useEffect(()=>{n&&g(`admesh-weave-fallback-${n}`)},[n]),o.log("[WeaveFallbackRecommendations] ๐ŸŽจ Component render"),m.useEffect(()=>{if(o.log("[WeaveFallbackRecommendations] ๐Ÿ”„ useEffect triggered",{fallback:s,hasPreviousRecommendations:a&&a.length>0,previousRecommendationsCount:(a==null?void 0:a.length)||0}),!s){o.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(o.log("[WeaveFallbackRecommendations] โœ… fallback is TRUE, proceeding with recommendations"),!n||!r||r.trim()===""){o.log("[WeaveFallbackRecommendations] โŒ Validation failed - returning early");return}if(o.log("[WeaveFallbackRecommendations] โœ… Validation passed"),!i||!y){o.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const T=a&&a.length>0;o.log("[WeaveFallbackRecommendations] ๐Ÿ“Š Checking previous recommendations:",{hasPreviousRecs:T,count:(a==null?void 0:a.length)||0,fallback:s,messageId:n}),T?(o.log(`[WeaveFallbackRecommendations] โ™ป๏ธ Reusing ${a.length} previous recommendation(s), skipping API call`),(async()=>{var N,E,v,F,w,I,S,R,M,D;try{const A=a[0];if(o.log("[WeaveFallbackRecommendations] ๐Ÿ“ฆ Processing AIP response:",{hasAipResponse:!!A,recommendationId:A==null?void 0:A.recommendation_id,hasCreativeInput:!!(A!=null&&A.creative_input)}),A&&process.env.NODE_ENV==="development"&&o.log("[WeaveFallbackRecommendations] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:A.recommendation_id,product_id:A.product_id,brand_id:A.brand_id,title:A.title,click_url:A.click_url,contextual_relevance_score:A.contextual_relevance_score,preferred_format:(N=A.creative_input)==null?void 0:N.preferred_format,resolved_format:(E=A.format_resolution)==null?void 0:E.resolved_format,creative_input:{product_name:(v=A.creative_input)==null?void 0:v.product_name,brand_name:(F=A.creative_input)==null?void 0:F.brand_name,cta_url:(w=A.creative_input)==null?void 0:w.cta_url,short_description:(I=A.creative_input)==null?void 0:I.short_description,allowed_formats:(S=A.creative_input)==null?void 0:S.allowed_formats,fallback_formats:(R=A.creative_input)==null?void 0:R.fallback_formats},format_resolution:A.format_resolution,full_response:A}),!A){o.warn("[WeaveFallbackRecommendations] โš ๏ธ Previous recommendation is empty, falling back to API call"),await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n});return}const j=i,G=j.convertAIPResponseToRecommendation,Y=j.getRenderer,X=j.getTracker,re=(M=j.config)==null?void 0:M.theme;if(G&&Y&&X){const q=G.call(i,A);if(!q){o.warn("[WeaveFallbackRecommendations] โš ๏ธ Conversion returned empty, falling back to API call"),await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n});return}const ne={session_id:A.session_id||l,message_id:`msg_${A.recommendation_id||n}`,recommendations:[q]},C=Y.call(i),B=X.call(i),ae=(i==null?void 0:i.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await C.render({containerId:y,response:ne,theme:p||re,tracker:B,sessionId:l,apiKey:h||((D=i==null?void 0:i.config)==null?void 0:D.apiKey),apiBaseUrl:ae,language:c,geo_country:u,userId:_,model:f,messages:b}),o.log("[WeaveFallbackRecommendations] โœ… Recommendations rendered from previous response (no API call)")}else o.warn("[WeaveFallbackRecommendations] โš ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n})}catch(A){const j=A instanceof Error?A:new Error(String(A));o.error(`[WeaveFallbackRecommendations] โŒ Error rendering previous recommendations: ${j.message}`);try{await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n})}catch{e==null||e(j)}}})()):(o.log("[WeaveFallbackRecommendations] ๐Ÿ“ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(i!=null&&i.showRecommendations)){o.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await i.showRecommendations({query:r.trim(),containerId:y,session_id:l,messageId:n}),o.log("[WeaveFallbackRecommendations] โœ… Recommendations displayed successfully")}catch(N){const E=N instanceof Error?N:new Error(String(N));o.log(`[WeaveFallbackRecommendations] โŒ Error: ${E.message}`),e==null||e(E)}})())},[i,l,y,t,n,r,s,e,a,p]),!s||!n||!r||r.trim()===""?null:d.jsx("div",{ref:k,id:y,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},ot=m.createContext(void 0),Mt=({children:t,shouldRenderFallback:e,messageId:n,sessionId:r,query:s})=>d.jsx(ot.Provider,{value:{shouldRenderFallback:e,messageId:n,sessionId:r,query:s},children:t}),Et=()=>m.useContext(ot),Ct={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Tt={"Top Match":"โ˜…","Free Tier":"โ—†","AI Powered":"โ—‰",Popular:"โ–ฒ",New:"โ—","Trial Available":"โ—ˆ"},nt=({type:t,variant:e,size:n="md",className:r,style:s})=>{const a=e||Ct[t]||"secondary",i=Tt[t],l=_e("admesh-component","admesh-badge",`admesh-badge--${a}`,`admesh-badge--${n}`,r);return d.jsxs("span",{className:l,style:s,children:[i&&d.jsx("span",{className:"admesh-badge__icon",children:i}),d.jsx("span",{className:"admesh-badge__text",children:t})]})};nt.displayName="AdMeshBadge";const Se="admesh:streamingStart",Me="admesh:streamingComplete";function Ft(t,e){const n={messageId:t,sessionId:e,timestamp:Date.now()},r=new CustomEvent(Se,{detail:n});window.dispatchEvent(r),o.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function It(t,e,n){const r={messageId:t,sessionId:e,timestamp:Date.now(),metadata:n},s=new CustomEvent(Me,{detail:r});window.dispatchEvent(s),o.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:n})}function Rt(t,e,n){const r=s=>{const a=s;a.detail.messageId===t&&a.detail.sessionId===e&&(o.log("[StreamingEvents] ๐Ÿ“จ Received streamingStart event"),n(a.detail))};return window.addEventListener(Se,r),()=>{window.removeEventListener(Se,r)}}function at(t,e,n){o.log("[StreamingEvents] ๐Ÿ‘‚ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const r=s=>{const a=s;o.log("[StreamingEvents] ๐Ÿ“จ Received streamingComplete event (checking match)",{receivedMessageId:a.detail.messageId,receivedSessionId:a.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:a.detail.messageId===t,sessionIdMatch:a.detail.sessionId===e}),a.detail.messageId===t&&a.detail.sessionId===e?(o.log("[StreamingEvents] โœ… Event matched! Calling callback"),n(a.detail)):o.log("[StreamingEvents] โš ๏ธ Event did not match - ignoring")};return window.addEventListener(Me,r),()=>{o.log("[StreamingEvents] ๐Ÿงน Removing streamingComplete listener"),window.removeEventListener(Me,r)}}const Te=()=>{const t=new Set,e=new Map,n=a=>{const i=e.get(a);i&&(i.observer.disconnect(),i.timeoutId&&clearTimeout(i.timeoutId),e.delete(a))};return{startTracking:({exposureUrl:a,recommendationId:i,linkElement:l,sessionId:p,logPrefix:h="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!a||!l){h&&o.warn(`${h} โš ๏ธ Missing exposure tracking data`);return}const c=`${p||"anonymous"}::${i||a}`;if(t.has(c)||e.has(c))return;const u={observer:void 0,timeoutId:null,viewableStart:null},_=()=>{n(c),t.add(c),fetch(a,{method:"GET",keepalive:!0}).then(()=>{h&&o.log(`${h} โœ… Exposure pixel fired`)}).catch(()=>{h&&o.warn(`${h} โš ๏ธ Failed to fire exposure pixel`),t.delete(c)})},f=new IntersectionObserver(b=>{b.forEach(k=>{k.intersectionRatio>=.5?u.viewableStart===null&&(u.viewableStart=performance.now(),u.timeoutId=setTimeout(_,1e3)):(u.viewableStart=null,u.timeoutId&&(clearTimeout(u.timeoutId),u.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});u.observer=f,f.observe(l),e.set(c,u)},cleanup:()=>{Array.from(e.keys()).forEach(n)}}},Lt=({containerId:t,messageId:e,sessionId:n,sdk:r,query:s,recommendations:a=[],onLinksFound:i,onNoLinksFound:l,children:p})=>{const[h,c]=m.useState(!1),[u,_]=m.useState(!0),[f,b]=m.useState(!1),k=m.useRef(Te()),y=m.useRef(i),g=m.useRef(l),T=m.useRef(t),x=m.useRef(r),N=m.useRef(n),E=m.useRef(s);m.useEffect(()=>{y.current=i,g.current=l,T.current=t,x.current=r,N.current=n,E.current=s},[i,l,t,r,n,s]),m.useEffect(()=>()=>{k.current.cleanup()},[]);const v=m.useCallback(({exposureUrl:w,recommendationId:I,linkElement:S})=>{k.current.startTracking({exposureUrl:w,recommendationId:I,linkElement:S,sessionId:N.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),F=m.useCallback(()=>{o.log("[FinalLinkDetectionCheck] ๐Ÿ” Performing final link detection...");try{const w=document.getElementById(T.current);if(!w){o.warn("[FinalLinkDetectionCheck] โŒ Container not found"),c(!0),l();return}const I=new Be({autoAddLabels:!0,fireExposurePixels:!0}),S=a.length>0?a:[];o.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Using ${S.length} recommendations for link detection`),S.length>0&&process.env.NODE_ENV==="development"&&S.forEach((M,D)=>{var A,j,G,Y,X;o.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Recommendation ${D+1} (DEV):`,{recommendation_id:M.recommendation_id,product_id:M.product_id,title:M.title,click_url:M.click_url,preferred_format:(A=M.creative_input)==null?void 0:A.preferred_format,resolved_format:(j=M.format_resolution)==null?void 0:j.resolved_format,creative_input:{product_name:(G=M.creative_input)==null?void 0:G.product_name,brand_name:(Y=M.creative_input)==null?void 0:Y.brand_name,cta_url:(X=M.creative_input)==null?void 0:X.cta_url}})});const R=I.scanAndProcessLinks(w,S,({exposureUrl:M,recommendationId:D,linkElement:A})=>v({exposureUrl:M,recommendationId:D,linkElement:A}));o.log(`[FinalLinkDetectionCheck] ๐Ÿ“Š Final check result: ${R.length} links`),R.length>0?(o.log("[FinalLinkDetectionCheck] โœ… Links detected - canceling fallback (no API call)"),b(!0),y.current(R.length)):(o.log(`[FinalLinkDetectionCheck] โš ๏ธ No links found - rendering fallback (will use ${S.length} previous recommendation(s) if available)`),b(!1),g.current()),c(!0)}catch{o.error("[FinalLinkDetectionCheck] โŒ Error during final check"),c(!0),g.current()}},[v,a]);return m.useEffect(()=>{o.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:n,recommendationsCount:a.length});let w=null,I=!1;const S=at(e,n,R=>{o.log("[FinalLinkDetectionCheck] ๐ŸŽฏ Received streamingComplete event",{messageId:R.messageId,sessionId:R.sessionId,timestamp:R.timestamp}),I=!0,w&&(clearTimeout(w),w=null),_(!1),setTimeout(()=>{F()},100)});return w=setTimeout(()=>{I||(o.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),_(!1),setTimeout(()=>{F()},100))},5e3),()=>{o.log("[FinalLinkDetectionCheck] ๐Ÿงน Cleaning up listener"),w&&clearTimeout(w),S()}},[e,n]),u?d.jsx(d.Fragment,{}):h?f?(o.log("[FinalLinkDetectionCheck] ๐Ÿšซ Links found - NOT rendering fallback"),d.jsx(d.Fragment,{})):(o.log("[FinalLinkDetectionCheck] โœ… No links found - rendering fallback"),d.jsx(d.Fragment,{children:p})):d.jsx(d.Fragment,{})},Pt=({messageId:t,children:e,fallbackFormat:n="tail",onLinksDetected:r,onNoLinksDetected:s,onError:a,className:i,query:l,onFallbackChange:p,onWeaveAttempt:h,onWeaveOutcome:c,followups_container_id:u,onExecuteQuery:_,onFollowupDetected:f,isContainerReady:b})=>{var ae,le,$,z;const{sessionId:k,sdk:y,language:g,geo_country:T,userId:x,model:N,messages:E,theme:v}=be(),F=m.useRef(null),w=`weave-ad-container-${t}`,I=m.useRef(Te()),S=m.useRef(!1),R=m.useRef(null),[M,D]=m.useState([]),A=m.useRef([]),[j,G]=m.useState(null),[Y,X]=m.useState(null),re=m.useRef(f);m.useEffect(()=>{re.current=f},[f]),m.useEffect(()=>(R.current||(R.current=new Be({autoAddLabels:!0,fireExposurePixels:!0})),()=>{R.current&&(R.current.stopWatching(),R.current.clearCache())}),[]),m.useEffect(()=>()=>{I.current.cleanup()},[]),m.useEffect(()=>{(async()=>{var W,K,Z,O,V,H,Q,ie,se,de,oe;if(!y||!(l!=null&&l.trim())||!t){o.log("[WeaveAdFormatContainer] โš ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{o.log("[WeaveAdFormatContainer] ๐Ÿ“ค Fetching recommendations from SDK for brand URL matching");const U=await y.fetchRecommendationFromAIPContext({query:l.trim(),sessionId:k,messageId:t,language:g,geo_country:T,userId:x,model:N,messages:E}),pe=U?[U]:[];if(D(pe),A.current=pe,o.log("[WeaveAdFormatContainer] โœ… Fetched recommendations:",pe.length),U){const xe=U.followup_query,ce=(W=U.creative_input)==null?void 0:W.followup_query,me=xe||ce,ve=U.followup_engagement_url,L=(K=U.creative_input)==null?void 0:K.followup_engagement_url,J=ve||L,he=U.followup_exposure_url,ge=(Z=U.creative_input)==null?void 0:Z.followup_exposure_url,we=he||ge,ee=U.recommendation_id||"";if(me)if(o.debug("[WeaveAdFormatContainer] โœ… Followup query detected:",me),o.debug("[WeaveAdFormatContainer] โœ… Followup engagement URL:",J?"present":"missing"),o.debug("[WeaveAdFormatContainer] โœ… Recommendation ID:",ee||"missing"),u){o.debug("[WeaveAdFormatContainer] โœ… Using SDK-managed portal rendering (followups_container_id provided)");const ye={...U,followup_query:me,followup_engagement_url:J,followup_exposure_url:we,recommendation_id:ee||U.recommendation_id};G(ye)}else re.current?(o.debug("[WeaveAdFormatContainer] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),re.current(me,J||"",ee||"")):o.debug("[WeaveAdFormatContainer] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)");else G(null)}U&&process.env.NODE_ENV==="development"&&o.log("[WeaveAdFormatContainer] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:U.recommendation_id,product_id:U.product_id,brand_id:U.brand_id,title:U.title,click_url:U.click_url,contextual_relevance_score:U.contextual_relevance_score,preferred_format:(O=U.creative_input)==null?void 0:O.preferred_format,resolved_format:(V=U.format_resolution)==null?void 0:V.resolved_format,creative_input:{product_name:(H=U.creative_input)==null?void 0:H.product_name,brand_name:(Q=U.creative_input)==null?void 0:Q.brand_name,cta_url:(ie=U.creative_input)==null?void 0:ie.cta_url,short_description:(se=U.creative_input)==null?void 0:se.short_description,allowed_formats:(de=U.creative_input)==null?void 0:de.allowed_formats,fallback_formats:(oe=U.creative_input)==null?void 0:oe.fallback_formats},format_resolution:U.format_resolution,full_response:U})}catch(U){o.warn("[WeaveAdFormatContainer] โš ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",U),D([])}})()},[y,k,t,l,u]),m.useEffect(()=>{if(!(j!=null&&j.followup_query)||!u){X(null);return}if(b===!1){o.debug("[WeaveAdFormatContainer] โณ Waiting for container signal...");return}let P=0;const W=5,K=()=>{const O=document.getElementById(u);return O?(o.debug(`[WeaveAdFormatContainer] โœ… Found followup container: ${u} `),X(O),!0):!1};if(K())return;const Z=setInterval(()=>{P++,(K()||P>=W)&&(clearInterval(Z),P>=W&&o.warn(`[WeaveAdFormatContainer] โš ๏ธ Followup container not found after signal: ${u} `))},100);return()=>clearInterval(Z)},[j,u,b]),m.useEffect(()=>{const P=F.current;if(!P||!R.current)return;const W=R.current,K=({exposureUrl:V,recommendationId:H,linkElement:Q})=>{I.current.startTracking({exposureUrl:V,recommendationId:H,linkElement:Q,sessionId:k,logPrefix:"[WeaveAdFormatContainer]"})},O=setTimeout(()=>{o.log("[WeaveAdFormatContainer] ๐Ÿ” Weave injection attempt started"),h==null||h(t);const V=A.current.length>0?A.current:[];o.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Using ${V.length} recommendations for link detection`);try{const H=W.scanAndProcessLinks(P,V,K);H.length>0&&!S.current?(S.current=!0,o.log(`[WeaveAdFormatContainer] โœ… Weave injection succeeded: ${H.length} links detected`),c==null||c(t,!0,`Found ${H.length} links`),r==null||r(H.length),p==null||p(!1)):S.current||o.log("[WeaveAdFormatContainer] โš ๏ธ Weave injection: no links found on initial scan")}catch(H){const Q=H instanceof Error?H.message:String(H);o.error(`[WeaveAdFormatContainer] โŒ Weave injection failed: ${Q}`),c==null||c(t,!1,Q),s==null||s(),p==null||p(!0)}},100);return W.watchForNewLinks(P,A.current,K),()=>{clearTimeout(O),W.stopWatching()}},[e,k,t,r,p,h,c]);const q=(le=(ae=M[0])==null?void 0:ae.format_resolution)==null?void 0:le.resolved_format,ne=(z=($=M[0])==null?void 0:$.creative_input)==null?void 0:z.preferred_format,C=q==="weave"||ne==="weave";m.useEffect(()=>{l&&C&&o.log(`[WeaveAdFormatContainer] ๐ŸŽฏ Format is "weave" (resolved: ${q}, preferred: ${ne}) - skipping fallback recommendations`)},[l,C,q,ne]);const B=()=>Y&&(j!=null&&j.followup_query)&&y?(o.debug(`[WeaveAdFormatContainer] ๐ŸŒ€ Rendering followup portal into: ${u} `),Ge.createPortal(d.jsx(Ce,{recommendation:j,theme:v,sdk:y,sessionId:k,onExecuteQuery:_}),Y)):(o.debug(`[WeaveAdFormatContainer] โŒ Skipping followup portal. Container: ${!!Y}, Query: ${!!(j!=null&&j.followup_query)}, SDK: ${!!y} `),null);return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:F,id:w,className:i,"data-weave-ad-format":"true","data-message-id":t,children:e}),l&&!C&&d.jsx(Lt,{containerId:w,messageId:t,sessionId:k,sdk:y,query:l,recommendations:M,onLinksFound:P=>{o.log(`[WeaveAdFormatContainer] โœ… Links found (${P}) - no fallback needed`),c==null||c(t,!0,`Found ${P} links in final check`),r==null||r(P),p==null||p(!1)},onNoLinksFound:()=>{o.log("[WeaveAdFormatContainer] โš ๏ธ No links found - rendering fallback"),o.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Passing ${M.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),s==null||s(),p==null||p(!0)},children:d.jsx(rt,{format:n,messageId:t,query:l,fallback:!0,onError:a,previousRecommendations:M.length>0?M:void 0})}),B()]})},Ie="admesh-ui-sdk-styles",Re="admesh-ui-sdk-reset",jt=`
24
24
  /* AdMesh UI SDK - CSS Reset & Normalization */
25
25
  .admesh-component,
26
26
  .admesh-component * {
@@ -988,5 +988,5 @@
988
988
  .admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
989
989
  .admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
990
990
  }
991
- `;let qe=!1;const Ut=()=>{m.useEffect(()=>{if(!qe){try{Dt();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Bt,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),qe=!0}catch{o.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])},$t=t=>{const{sdk:e,sessionId:n}=be(),r=m.useRef(!1),s=m.useRef(0),a=m.useRef(!1),i=m.useRef(!1),l=m.useRef(null),p=m.useRef(Te());m.useEffect(()=>()=>{p.current.cleanup()},[]);const h=m.useCallback(({exposureUrl:g,recommendationId:C,linkElement:x})=>{p.current.startTracking({exposureUrl:g,recommendationId:C,linkElement:x,sessionId:n,logPrefix:"[useWeaveAdFormat]"})},[n]),c=m.useRef(Date.now()),u=m.useRef(0),_=m.useRef(null),f=m.useRef([]),b=m.useRef(300),k=m.useCallback(async()=>{var g,C,x,N;if(!(!e||!n||r.current)){r.current=!0,s.current=0;try{const E=document.getElementById(t.llmOutputContainerId);if(!E)return;const v=(g=e.getWeaveProcessor)==null?void 0:g.call(e);if(!v)return;const T=v.scanAndProcessLinks(E,[],({exposureUrl:I,recommendationId:S,linkElement:R})=>h({exposureUrl:I,recommendationId:S,linkElement:R}));s.current=T.length;const w=T.length>0;if(w&&!a.current)a.current=!0,(C=t.onLinksDetected)==null||C.call(t,T.length),i.current=!0;else if(!w&&a.current)a.current=!1,i.current=!1;else if(!w&&!i.current){l.current&&clearTimeout(l.current),_.current&&clearInterval(_.current),u.current=0,c.current=Date.now();const I=Math.max(100,b.current/3);_.current=setInterval(()=>{var D;const R=Date.now()-c.current,M=b.current;R>=M?(u.current++,u.current>=2&&(_.current&&(clearInterval(_.current),_.current=null),!a.current&&!i.current&&((D=t.onNoLinksDetected)==null||D.call(t),i.current=!0))):u.current=0},I);const S=Math.max(1500,b.current*5);l.current=setTimeout(()=>{var R;_.current&&(clearInterval(_.current),_.current=null),!a.current&&!i.current&&((R=t.onNoLinksDetected)==null||R.call(t),i.current=!0)},S)}else w&&i.current&&!a.current&&(l.current&&(clearTimeout(l.current),l.current=null),a.current=!0,(x=t.onLinksDetected)==null||x.call(t,T.length),i.current=!0)}catch(E){const v=E instanceof Error?E:new Error(String(E));(N=t.onError)==null||N.call(t,v)}finally{r.current=!1}}},[e,n,t,h]),y=m.useCallback(()=>{const g=f.current;if(g.length<2){b.current=300;return}const C=[];for(let E=1;E<g.length;E++)C.push(g[E]-g[E-1]);const x=C.reduce((E,v)=>E+v,0)/C.length,N=Math.max(100,Math.min(x*3,1e3));b.current=N},[]);return m.useEffect(()=>{const g=document.getElementById(t.llmOutputContainerId);if(!g)return;k();const C=new MutationObserver(()=>{const x=Date.now();c.current=x,u.current=0,f.current.push(x),f.current.length>10&&f.current.shift(),y(),k()});return C.observe(g,{childList:!0,subtree:!0,characterData:!1}),()=>{C.disconnect(),l.current&&clearTimeout(l.current),_.current&&clearInterval(_.current)}},[t.llmOutputContainerId,k,y]),{isProcessing:r.current,detectedLinksCount:s.current,linksFound:a.current,shouldRenderFallback:!a.current&&i.current,processWeaveFormat:k}},Wt="1.0.10";exports.AdMeshBadge=nt;exports.AdMeshBridgeFormat=je;exports.AdMeshContext=Ee;exports.AdMeshEcommerceCards=De;exports.AdMeshFollowup=Ce;exports.AdMeshLayout=Xe;exports.AdMeshLinkTracker=Ne;exports.AdMeshProvider=Le;exports.AdMeshRecommendations=St;exports.AdMeshRenderer=et;exports.AdMeshSDK=tt;exports.AdMeshTailAd=Pe;exports.AdMeshTracker=Je;exports.AdMeshViewabilityTracker=ke;exports.STREAMING_COMPLETE_EVENT=Me;exports.STREAMING_START_EVENT=Se;exports.VERSION=Wt;exports.WeaveAdFormatContainer=Pt;exports.WeaveAdFormatProvider=Mt;exports.WeaveFallbackRecommendations=rt;exports.WeaveResponseProcessor=Be;exports.createInlineExposureTracker=Te;exports.dispatchStreamingCompleteEvent=It;exports.dispatchStreamingStartEvent=Ft;exports.onStreamingComplete=at;exports.onStreamingStart=Rt;exports.useAdMesh=be;exports.useAdMeshContext=Ze;exports.useAdMeshStyles=Ut;exports.useViewabilityTracker=Ye;exports.useWeaveAdFormat=$t;exports.useWeaveAdFormatContext=Et;
991
+ `;let qe=!1;const Ut=()=>{m.useEffect(()=>{if(!qe){try{Dt();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Bt,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),qe=!0}catch{o.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])},$t=t=>{const{sdk:e,sessionId:n}=be(),r=m.useRef(!1),s=m.useRef(0),a=m.useRef(!1),i=m.useRef(!1),l=m.useRef(null),p=m.useRef(Te());m.useEffect(()=>()=>{p.current.cleanup()},[]);const h=m.useCallback(({exposureUrl:g,recommendationId:T,linkElement:x})=>{p.current.startTracking({exposureUrl:g,recommendationId:T,linkElement:x,sessionId:n,logPrefix:"[useWeaveAdFormat]"})},[n]),c=m.useRef(Date.now()),u=m.useRef(0),_=m.useRef(null),f=m.useRef([]),b=m.useRef(300),k=m.useCallback(async()=>{var g,T,x,N;if(!(!e||!n||r.current)){r.current=!0,s.current=0;try{const E=document.getElementById(t.llmOutputContainerId);if(!E)return;const v=(g=e.getWeaveProcessor)==null?void 0:g.call(e);if(!v)return;const F=v.scanAndProcessLinks(E,[],({exposureUrl:I,recommendationId:S,linkElement:R})=>h({exposureUrl:I,recommendationId:S,linkElement:R}));s.current=F.length;const w=F.length>0;if(w&&!a.current)a.current=!0,(T=t.onLinksDetected)==null||T.call(t,F.length),i.current=!0;else if(!w&&a.current)a.current=!1,i.current=!1;else if(!w&&!i.current){l.current&&clearTimeout(l.current),_.current&&clearInterval(_.current),u.current=0,c.current=Date.now();const I=Math.max(100,b.current/3);_.current=setInterval(()=>{var D;const R=Date.now()-c.current,M=b.current;R>=M?(u.current++,u.current>=2&&(_.current&&(clearInterval(_.current),_.current=null),!a.current&&!i.current&&((D=t.onNoLinksDetected)==null||D.call(t),i.current=!0))):u.current=0},I);const S=Math.max(1500,b.current*5);l.current=setTimeout(()=>{var R;_.current&&(clearInterval(_.current),_.current=null),!a.current&&!i.current&&((R=t.onNoLinksDetected)==null||R.call(t),i.current=!0)},S)}else w&&i.current&&!a.current&&(l.current&&(clearTimeout(l.current),l.current=null),a.current=!0,(x=t.onLinksDetected)==null||x.call(t,F.length),i.current=!0)}catch(E){const v=E instanceof Error?E:new Error(String(E));(N=t.onError)==null||N.call(t,v)}finally{r.current=!1}}},[e,n,t,h]),y=m.useCallback(()=>{const g=f.current;if(g.length<2){b.current=300;return}const T=[];for(let E=1;E<g.length;E++)T.push(g[E]-g[E-1]);const x=T.reduce((E,v)=>E+v,0)/T.length,N=Math.max(100,Math.min(x*3,1e3));b.current=N},[]);return m.useEffect(()=>{const g=document.getElementById(t.llmOutputContainerId);if(!g)return;k();const T=new MutationObserver(()=>{const x=Date.now();c.current=x,u.current=0,f.current.push(x),f.current.length>10&&f.current.shift(),y(),k()});return T.observe(g,{childList:!0,subtree:!0,characterData:!1}),()=>{T.disconnect(),l.current&&clearTimeout(l.current),_.current&&clearInterval(_.current)}},[t.llmOutputContainerId,k,y]),{isProcessing:r.current,detectedLinksCount:s.current,linksFound:a.current,shouldRenderFallback:!a.current&&i.current,processWeaveFormat:k}},Wt="1.0.10";exports.AdMeshBadge=nt;exports.AdMeshBridgeFormat=je;exports.AdMeshContext=Ee;exports.AdMeshEcommerceCards=De;exports.AdMeshFollowup=Ce;exports.AdMeshLayout=Xe;exports.AdMeshLinkTracker=Ne;exports.AdMeshProvider=Le;exports.AdMeshRecommendations=St;exports.AdMeshRenderer=et;exports.AdMeshSDK=tt;exports.AdMeshTailAd=Pe;exports.AdMeshTracker=Je;exports.AdMeshViewabilityTracker=ke;exports.STREAMING_COMPLETE_EVENT=Me;exports.STREAMING_START_EVENT=Se;exports.VERSION=Wt;exports.WeaveAdFormatContainer=Pt;exports.WeaveAdFormatProvider=Mt;exports.WeaveFallbackRecommendations=rt;exports.WeaveResponseProcessor=Be;exports.createInlineExposureTracker=Te;exports.dispatchStreamingCompleteEvent=It;exports.dispatchStreamingStartEvent=Ft;exports.onStreamingComplete=at;exports.onStreamingStart=Rt;exports.useAdMesh=be;exports.useAdMeshContext=Ze;exports.useAdMeshStyles=Ut;exports.useViewabilityTracker=Ye;exports.useWeaveAdFormat=$t;exports.useWeaveAdFormatContext=Et;
992
992
  //# sourceMappingURL=index.js.map