admesh-ui-sdk 1.0.23 โ†’ 1.0.24

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":"AdMeshRecommendations.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshRecommendations.tsx"],"names":[],"mappings":"AAYA,MAAM,WAAW,0BAA0B;IACzC,uDAAuD;IACvD,sBAAsB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IAErD,iCAAiC;IACjC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;;;;;;OASG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAE3C;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAEhC;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IAEH,kBAAkB,CAAC,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,qBAAqB,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,KAAK,IAAI,CAAC;IAE9G;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,eAAO,MAAM,qBAAqB,GAAI,gMAWnC,0BAA0B,mDAkZ5B,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
1
+ {"version":3,"file":"AdMeshRecommendations.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshRecommendations.tsx"],"names":[],"mappings":"AAYA,MAAM,WAAW,0BAA0B;IACzC,uDAAuD;IACvD,sBAAsB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IAErD,iCAAiC;IACjC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;;;;;;OASG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAE3C;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAEhC;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IAEH,kBAAkB,CAAC,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,qBAAqB,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,KAAK,IAAI,CAAC;IAE9G;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,eAAO,MAAM,qBAAqB,GAAI,gMAWnC,0BAA0B,mDAsZ5B,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"AdMeshTailAd.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshTailAd.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAGxE,MAAM,WAAW,iBAAiB;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC5B,WAAW,CAAC,EAAE,CAAC,cAAc,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AA+BD,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CA4LpD,CAAC;AAEF,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"AdMeshTailAd.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshTailAd.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAGxE,MAAM,WAAW,iBAAiB;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC5B,WAAW,CAAC,EAAE,CAAC,cAAc,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AA+BD,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CA0RpD,CAAC;AAEF,eAAe,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var dt=Object.defineProperty;var ct=(t,e,r)=>e in t?dt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Z=(t,e,r)=>ct(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),$e=require("react-dom/client"),h=require("react"),qe=require("react-dom");let ie=!1;var Ke;try{typeof globalThis.importMeta<"u"&&((Ke=globalThis.importMeta.env)!=null&&Ke.PROD)&&(ie=!0)}catch{}ie||(ie=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const a={log:(...t)=>{ie||console.log(...t)},warn:(...t)=>{ie||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{ie||console.info(...t)},debug:(...t)=>{ie||console.debug(...t)}};function lt(t,e,r){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...r}}function mt(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function ut(t){const e=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth,s=e.height,n=e.width;if(s===0||n===0)return 0;const d=Math.max(0,e.top),l=Math.min(r,e.bottom),u=Math.max(0,e.left),p=Math.min(o,e.right),c=Math.max(0,l-d),g=Math.max(0,p-u),b=c*g,x=s*n;return x>0?b/x:0}function ze(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,o=e-t;return o<=0?100:Math.min(100,r/o*100)}function pt(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+o}}function ht(t){const e=t.getBoundingClientRect(),r=pt(t),o=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,n=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:mt(o),viewportWidth:o,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:r.top,adPositionLeft:r.left,isDarkMode:n,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function gt(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function ft(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function Be(t=new Date){return t.toISOString()}function bt(t){return t.length===0?0:t.reduce((r,o)=>r+o,0)/t.length}function Ue(t,e){let r;return function(...s){r||(t(...s),r=!0,setTimeout(()=>r=!1,e))}}const xt={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let vt=xt;function Ge({productId:t,offerId:e,agentId:r,recommendationId:o,elementRef:s,config:n}){const d={...vt,...n},l=h.useRef(gt()),[u,p]=h.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:Be(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:d.enabled}),c=h.useRef(null),g=h.useRef(null),b=h.useRef(null),x=h.useRef(null),f=h.useRef(null),y=h.useRef([]),_=h.useRef([]),m=h.useRef(null),M=h.useCallback(w=>{d.debug&&a.log(`[AdMesh Viewability] ${w}`)},[d.debug]),S=h.useCallback(async(w,v)=>{if(!(!d.enabled||!s.current||!c.current)&&(M(`Analytics disabled - skipping event: ${w}`),d.onEvent)){const A=ht(s.current),C={eventType:w,timestamp:Be(),sessionId:l.current,productId:t,offerId:e,agentId:r,recommendationId:o,timeMetrics:u.timeMetrics,engagementMetrics:u.engagementMetrics,contextMetrics:A,mrcStandards:c.current,isViewable:u.isViewable,metadata:v};d.onEvent(C)}},[d,t,e,r,o,s,u,M]),I=h.useCallback(async()=>{_.current.length!==0&&(M("Analytics disabled - clearing batch without sending"),_.current=[],m.current&&(clearTimeout(m.current),m.current=null))},[M]),E=h.useCallback(Ue(()=>{if(!s.current)return;const w=ut(s.current),v=Date.now(),A=new Date(u.timeMetrics.loadedAt).getTime();p(C=>{const k={...C};w>0&&y.current.push(w);const R=C.isVisible,T=w>0;if(T&&!R)g.current=v,k.engagementMetrics.viewportEnterCount++,k.timeMetrics.timeToFirstVisible||(k.timeMetrics.timeToFirstVisible=v-A,k.engagementMetrics.scrollDepthAtFirstVisible=ze(),S("ad_visible"));else if(!T&&R){if(g.current){const j=v-g.current;k.timeMetrics.totalVisibleDuration+=j,g.current=null}k.engagementMetrics.viewportExitCount++,S("ad_hidden")}else if(T&&R&&g.current){const j=v-g.current;k.timeMetrics.totalVisibleDuration+=j,g.current=v}if(k.isVisible=T,k.visibilityPercentage=w,w>k.engagementMetrics.maxVisibilityPercentage&&(k.engagementMetrics.maxVisibilityPercentage=w),y.current.length>0&&(k.engagementMetrics.averageVisibilityPercentage=bt(y.current)),c.current){const j=C.isViewable,D=ft(w,k.timeMetrics.totalVisibleDuration,c.current);if(D&&!j)k.isViewable=!0,k.timeMetrics.timeToViewable=v-A,b.current=v,S("ad_viewable");else if(D&&j&&b.current){const P=v-b.current;k.timeMetrics.totalViewableDuration+=P,b.current=v}}return k.engagementMetrics.currentScrollDepth=ze(),k})},100),[s,u.timeMetrics.loadedAt,S]);return h.useEffect(()=>{if(!s.current)return;const w=s.current.getBoundingClientRect();c.current=lt(w.width,w.height,d.mrcStandards),M("Initialized MRC standards"),S("ad_loaded")},[s,d.mrcStandards,M,S]),h.useEffect(()=>{if(!d.enabled||!s.current)return;const w=new IntersectionObserver(v=>{v.forEach(()=>{E()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return w.observe(s.current),()=>{w.disconnect()}},[d.enabled,s,E]),h.useEffect(()=>{if(!d.enabled)return;const w=Ue(()=>{E()},100);return window.addEventListener("scroll",w,{passive:!0}),()=>window.removeEventListener("scroll",w)},[d.enabled,E]),h.useEffect(()=>{if(!d.enabled||!s.current)return;const w=s.current,v=()=>{x.current=Date.now(),p(C=>({...C,engagementMetrics:{...C.engagementMetrics,hoverCount:C.engagementMetrics.hoverCount+1}})),S("ad_hover_start")},A=()=>{if(x.current){const C=Date.now()-x.current;p(k=>({...k,timeMetrics:{...k.timeMetrics,totalHoverDuration:k.timeMetrics.totalHoverDuration+C}})),x.current=null,S("ad_hover_end",{hoverDuration:C})}};return w.addEventListener("mouseenter",v),w.addEventListener("mouseleave",A),()=>{w.removeEventListener("mouseenter",v),w.removeEventListener("mouseleave",A)}},[d.enabled,s,S]),h.useEffect(()=>{if(!d.enabled||!s.current)return;const w=s.current,v=()=>{f.current=Date.now(),S("ad_focus")},A=()=>{if(f.current){const C=Date.now()-f.current;p(k=>({...k,timeMetrics:{...k.timeMetrics,totalFocusDuration:k.timeMetrics.totalFocusDuration+C}})),f.current=null,S("ad_blur",{focusDuration:C})}};return w.addEventListener("focus",v),w.addEventListener("blur",A),()=>{w.removeEventListener("focus",v),w.removeEventListener("blur",A)}},[d.enabled,s,S]),h.useEffect(()=>{if(!d.enabled||!s.current)return;const w=s.current,v=()=>{p(A=>({...A,engagementMetrics:{...A.engagementMetrics,wasClicked:!0}})),S("ad_click")};return w.addEventListener("click",v),()=>{w.removeEventListener("click",v)}},[d.enabled,s,S]),h.useEffect(()=>()=>{const w=Date.now(),v=new Date(u.timeMetrics.loadedAt).getTime(),A=w-v;p(C=>({...C,timeMetrics:{...C.timeMetrics,sessionDuration:A}})),S("ad_unloaded",{sessionDuration:A}),I()},[]),u}const ae=({productId:t,offerId:e,agentId:r,recommendationId:o,exposureUrl:s,sessionId:n,children:d,config:l,className:u,style:p,onViewabilityChange:c,onVisible:g,onViewable:b,onClick:x})=>{const f=h.useRef(null),y=h.useRef(!1),_=Ge({productId:t,offerId:e,agentId:r,recommendationId:o,elementRef:f,config:l}),m=h.useRef(_.isViewable);h.useEffect(()=>{_.isViewable!==m.current&&(m.current=_.isViewable,c&&c(_.isViewable),_.isViewable&&b&&b(),_.isViewable&&!y.current&&(a.log("[AdMeshViewabilityTracker] ๐ŸŽฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:s?"present":"MISSING",sessionId:n?"present":"MISSING",recommendationId:o}),s&&n?(y.current=!0,a.log("[AdMeshViewabilityTracker] ๐Ÿ”ฅ Firing exposure pixel:",s),fetch(s,{method:"GET",keepalive:!0}).then(()=>{a.log("[AdMesh] โœ… Exposure pixel fired successfully")}).catch(I=>{a.warn("[AdMesh] โš ๏ธ Failed to fire exposure pixel:",I),y.current=!1})):a.warn("[AdMeshViewabilityTracker] โš ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!s,hasSessionId:!!n})))},[_.isViewable,c,b,s,n,o]);const M=h.useRef(_.isVisible);h.useEffect(()=>{_.isVisible!==M.current&&(M.current=_.isVisible,_.isVisible&&g&&g())},[_.isVisible,g]);const S=()=>{x&&x()};return i.jsx("div",{ref:f,className:u,style:p,onClick:S,"data-admesh-viewability-tracker":!0,"data-recommendation-id":o,"data-is-viewable":_.isViewable,"data-is-visible":_.isVisible,"data-visibility-percentage":_.visibilityPercentage.toFixed(2),children:d})};ae.displayName="AdMeshViewabilityTracker";const yt=t=>t&&t.trim()?t.trim():"",Ae=({recommendations:t,theme:e,className:r="",style:o={},sessionId:s})=>{if(!t||t.length===0)return a.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const n=t[0],d=n==null?void 0:n.product_id,l=n==null?void 0:n.exposure_url,u=(n==null?void 0:n.recommendation_id)||"",p=(n==null?void 0:n.creative_input)||{},c=p.short_description||"",g=p.offer_summary||"",b=p.brand_name||(n==null?void 0:n.title)||"",x=p.product_name||"",f=(n==null?void 0:n.click_url)||(n==null?void 0:n.admesh_link)||p.cta_url||(n==null?void 0:n.url),y=yt(p.cta_label);if(!b)return a.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering"),null;let _=b,m="";g?m=g:x&&(m=x),m&&(_=`${b} โ€” ${m}`),a.debug("[AdMeshTailAd] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:u,productId:d,exposureUrl:l?"present":"MISSING",sessionId:s?"present":"MISSING",recommendationsCount:t.length,clickUrl:f||"MISSING",clickUrlSource:n!=null&&n.click_url?"click_url":n!=null&&n.admesh_link?"admesh_link":p.cta_url?"cta_url":n!=null&&n.url?"url":"none",shortDescription:c?"present":"MISSING",offerSummary:g||"MISSING",brandName:b,productName:x,headlineText:_});const M=(E,w)=>{a.log(`AdMesh tail ad ${E} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:n.recommendation_id,productId:n.product_id,clickUrl:f,source:E}).catch(()=>{a.error(`[AdMesh] Failed to track ${E} click`)})},S=E=>{E.stopPropagation(),M("tail_ad_brand_name")},I=E=>{E.stopPropagation(),M("tail_ad_cta")};return i.jsx(ae,{productId:d,recommendationId:u,exposureUrl:l,sessionId:s,className:`admesh-tail-ad ${r}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...o},children:i.jsxs("div",{className:"tail-ad-container",children:[_&&i.jsx("div",{className:"mb-2",children:i.jsx("h3",{className:"text-black dark:text-white font-semibold text-base",children:f&&b?i.jsxs(i.Fragment,{children:[i.jsx("a",{href:f,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:S,children:b}),m&&` โ€” ${m}`]}):_})}),c&&i.jsx("p",{className:"text-gray-700 dark:text-gray-300 text-sm mb-3 leading-relaxed",children:c}),i.jsxs("div",{className:"flex items-center justify-between mt-2",children:[y&&f&&i.jsx("a",{href:f,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:I,children:y}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})]})]})})};function wt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fe={exports:{}};/*!
1
+ "use strict";var ct=Object.defineProperty;var lt=(t,e,n)=>e in t?ct(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Z=(t,e,n)=>lt(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),Be=require("react-dom/client"),p=require("react"),Ge=require("react-dom");let ce=!1;var qe;try{typeof globalThis.importMeta<"u"&&((qe=globalThis.importMeta.env)!=null&&qe.PROD)&&(ce=!0)}catch{}ce||(ce=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const a={log:(...t)=>{ce||console.log(...t)},warn:(...t)=>{ce||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{ce||console.info(...t)},debug:(...t)=>{ce||console.debug(...t)}};function mt(t,e,n){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...n}}function ut(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function pt(t){const e=t.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth,s=e.height,r=e.width;if(s===0||r===0)return 0;const d=Math.max(0,e.top),l=Math.min(n,e.bottom),u=Math.max(0,e.left),m=Math.min(o,e.right),c=Math.max(0,l-d),h=Math.max(0,m-u),b=c*h,v=s*r;return v>0?b/v:0}function ze(){const t=window.innerHeight,e=document.documentElement.scrollHeight,n=window.pageYOffset||document.documentElement.scrollTop,o=e-t;return o<=0?100:Math.min(100,n/o*100)}function ht(t){const e=t.getBoundingClientRect(),n=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+n,left:e.left+o}}function gt(t){const e=t.getBoundingClientRect(),n=ht(t),o=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,r=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ut(o),viewportWidth:o,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:n.top,adPositionLeft:n.left,isDarkMode:r,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function ft(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function bt(t,e,n){return t>=n.visibilityThreshold&&e>=n.minimumDuration}function Ue(t=new Date){return t.toISOString()}function xt(t){return t.length===0?0:t.reduce((n,o)=>n+o,0)/t.length}function Ve(t,e){let n;return function(...s){n||(t(...s),n=!0,setTimeout(()=>n=!1,e))}}const vt={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let yt=vt;function Qe({productId:t,offerId:e,agentId:n,recommendationId:o,elementRef:s,config:r}){const d={...yt,...r},l=p.useRef(ft()),[u,m]=p.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:Ue(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:d.enabled}),c=p.useRef(null),h=p.useRef(null),b=p.useRef(null),v=p.useRef(null),f=p.useRef(null),w=p.useRef([]),y=p.useRef([]),g=p.useRef(null),S=p.useCallback(_=>{d.debug&&a.log(`[AdMesh Viewability] ${_}`)},[d.debug]),k=p.useCallback(async(_,x)=>{if(!(!d.enabled||!s.current||!c.current)&&(S(`Analytics disabled - skipping event: ${_}`),d.onEvent)){const M=gt(s.current),C={eventType:_,timestamp:Ue(),sessionId:l.current,productId:t,offerId:e,agentId:n,recommendationId:o,timeMetrics:u.timeMetrics,engagementMetrics:u.engagementMetrics,contextMetrics:M,mrcStandards:c.current,isViewable:u.isViewable,metadata:x};d.onEvent(C)}},[d,t,e,n,o,s,u,S]),F=p.useCallback(async()=>{y.current.length!==0&&(S("Analytics disabled - clearing batch without sending"),y.current=[],g.current&&(clearTimeout(g.current),g.current=null))},[S]),R=p.useCallback(Ve(()=>{if(!s.current)return;const _=pt(s.current),x=Date.now(),M=new Date(u.timeMetrics.loadedAt).getTime();m(C=>{const A={...C};_>0&&w.current.push(_);const E=C.isVisible,T=_>0;if(T&&!E)h.current=x,A.engagementMetrics.viewportEnterCount++,A.timeMetrics.timeToFirstVisible||(A.timeMetrics.timeToFirstVisible=x-M,A.engagementMetrics.scrollDepthAtFirstVisible=ze(),k("ad_visible"));else if(!T&&E){if(h.current){const I=x-h.current;A.timeMetrics.totalVisibleDuration+=I,h.current=null}A.engagementMetrics.viewportExitCount++,k("ad_hidden")}else if(T&&E&&h.current){const I=x-h.current;A.timeMetrics.totalVisibleDuration+=I,h.current=x}if(A.isVisible=T,A.visibilityPercentage=_,_>A.engagementMetrics.maxVisibilityPercentage&&(A.engagementMetrics.maxVisibilityPercentage=_),w.current.length>0&&(A.engagementMetrics.averageVisibilityPercentage=xt(w.current)),c.current){const I=C.isViewable,D=bt(_,A.timeMetrics.totalVisibleDuration,c.current);if(D&&!I)A.isViewable=!0,A.timeMetrics.timeToViewable=x-M,b.current=x,k("ad_viewable");else if(D&&I&&b.current){const P=x-b.current;A.timeMetrics.totalViewableDuration+=P,b.current=x}}return A.engagementMetrics.currentScrollDepth=ze(),A})},100),[s,u.timeMetrics.loadedAt,k]);return p.useEffect(()=>{if(!s.current)return;const _=s.current.getBoundingClientRect();c.current=mt(_.width,_.height,d.mrcStandards),S("Initialized MRC standards"),k("ad_loaded")},[s,d.mrcStandards,S,k]),p.useEffect(()=>{if(!d.enabled||!s.current)return;const _=new IntersectionObserver(x=>{x.forEach(()=>{R()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return _.observe(s.current),()=>{_.disconnect()}},[d.enabled,s,R]),p.useEffect(()=>{if(!d.enabled)return;const _=Ve(()=>{R()},100);return window.addEventListener("scroll",_,{passive:!0}),()=>window.removeEventListener("scroll",_)},[d.enabled,R]),p.useEffect(()=>{if(!d.enabled||!s.current)return;const _=s.current,x=()=>{v.current=Date.now(),m(C=>({...C,engagementMetrics:{...C.engagementMetrics,hoverCount:C.engagementMetrics.hoverCount+1}})),k("ad_hover_start")},M=()=>{if(v.current){const C=Date.now()-v.current;m(A=>({...A,timeMetrics:{...A.timeMetrics,totalHoverDuration:A.timeMetrics.totalHoverDuration+C}})),v.current=null,k("ad_hover_end",{hoverDuration:C})}};return _.addEventListener("mouseenter",x),_.addEventListener("mouseleave",M),()=>{_.removeEventListener("mouseenter",x),_.removeEventListener("mouseleave",M)}},[d.enabled,s,k]),p.useEffect(()=>{if(!d.enabled||!s.current)return;const _=s.current,x=()=>{f.current=Date.now(),k("ad_focus")},M=()=>{if(f.current){const C=Date.now()-f.current;m(A=>({...A,timeMetrics:{...A.timeMetrics,totalFocusDuration:A.timeMetrics.totalFocusDuration+C}})),f.current=null,k("ad_blur",{focusDuration:C})}};return _.addEventListener("focus",x),_.addEventListener("blur",M),()=>{_.removeEventListener("focus",x),_.removeEventListener("blur",M)}},[d.enabled,s,k]),p.useEffect(()=>{if(!d.enabled||!s.current)return;const _=s.current,x=()=>{m(M=>({...M,engagementMetrics:{...M.engagementMetrics,wasClicked:!0}})),k("ad_click")};return _.addEventListener("click",x),()=>{_.removeEventListener("click",x)}},[d.enabled,s,k]),p.useEffect(()=>()=>{const _=Date.now(),x=new Date(u.timeMetrics.loadedAt).getTime(),M=_-x;m(C=>({...C,timeMetrics:{...C.timeMetrics,sessionDuration:M}})),k("ad_unloaded",{sessionDuration:M}),F()},[]),u}const ie=({productId:t,offerId:e,agentId:n,recommendationId:o,exposureUrl:s,sessionId:r,children:d,config:l,className:u,style:m,onViewabilityChange:c,onVisible:h,onViewable:b,onClick:v})=>{const f=p.useRef(null),w=p.useRef(!1),y=Qe({productId:t,offerId:e,agentId:n,recommendationId:o,elementRef:f,config:l}),g=p.useRef(y.isViewable);p.useEffect(()=>{y.isViewable!==g.current&&(g.current=y.isViewable,c&&c(y.isViewable),y.isViewable&&b&&b(),y.isViewable&&!w.current&&(a.log("[AdMeshViewabilityTracker] ๐ŸŽฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:s?"present":"MISSING",sessionId:r?"present":"MISSING",recommendationId:o}),s&&r?(w.current=!0,a.log("[AdMeshViewabilityTracker] ๐Ÿ”ฅ Firing exposure pixel:",s),fetch(s,{method:"GET",keepalive:!0}).then(()=>{a.log("[AdMesh] โœ… Exposure pixel fired successfully")}).catch(F=>{a.warn("[AdMesh] โš ๏ธ Failed to fire exposure pixel:",F),w.current=!1})):a.warn("[AdMeshViewabilityTracker] โš ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!s,hasSessionId:!!r})))},[y.isViewable,c,b,s,r,o]);const S=p.useRef(y.isVisible);p.useEffect(()=>{y.isVisible!==S.current&&(S.current=y.isVisible,y.isVisible&&h&&h())},[y.isVisible,h]);const k=()=>{v&&v()};return i.jsx("div",{ref:f,className:u,style:m,onClick:k,"data-admesh-viewability-tracker":!0,"data-recommendation-id":o,"data-is-viewable":y.isViewable,"data-is-visible":y.isVisible,"data-visibility-percentage":y.visibilityPercentage.toFixed(2),children:d})};ie.displayName="AdMeshViewabilityTracker";const wt=t=>{try{return new URL(t),!0}catch{return!1}},_t=t=>t&&t.trim()?t.trim():"",we=({recommendations:t,theme:e,className:n="",style:o={},sessionId:s})=>{if(!t||t.length===0)return a.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const r=t[0],d=r==null?void 0:r.product_id,l=r==null?void 0:r.exposure_url,u=(r==null?void 0:r.recommendation_id)||"",m=(r==null?void 0:r.creative_input)||{},c=m.short_description||"",h=m.offer_summary||"",b=m.brand_name||(r==null?void 0:r.title)||"",v=m.product_name||"",w=(m.assets||{}).logo_url||"",y=(r==null?void 0:r.click_url)||(r==null?void 0:r.admesh_link)||m.cta_url||(r==null?void 0:r.url),g=_t(m.cta_label);if(!b)return a.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brandName is missing",brandName:b,hasFirstRecommendation:!!r,hasCreativeInput:!!m,creativeInputBrandName:m.brand_name,recommendationTitle:r==null?void 0:r.title,recommendationId:u,recommendationKeys:r?Object.keys(r):[]}),null;let S=b,k="";h?k=h:v&&(k=v),k&&(S=`${b} โ€” ${k}`),a.debug("[AdMeshTailAd] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:u,productId:d,exposureUrl:l?"present":"MISSING",sessionId:s?"present":"MISSING",recommendationsCount:t.length,clickUrl:y||"MISSING",clickUrlSource:r!=null&&r.click_url?"click_url":r!=null&&r.admesh_link?"admesh_link":m.cta_url?"cta_url":r!=null&&r.url?"url":"none",shortDescription:c?"present":"MISSING",offerSummary:h||"MISSING",brandName:b,productName:v,headlineText:S});const F=(E,T)=>{a.log(`AdMesh tail ad ${E} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:r.recommendation_id,productId:r.product_id,clickUrl:y,source:E}).catch(()=>{a.error(`[AdMesh] Failed to track ${E} click`)})},R=E=>{E.stopPropagation(),F("tail_ad_brand_name")},_=E=>{E.stopPropagation(),F("tail_ad_cta")},x=E=>{E.stopPropagation(),F("tail_ad_logo")},[M,C]=p.useState(!1),A=b?b.charAt(0).toUpperCase():"B";return i.jsx(ie,{productId:d,recommendationId:u,exposureUrl:l,sessionId:s,className:`admesh-tail-ad ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...o},children:i.jsxs("div",{className:"tail-ad-container flex flex-row gap-3",children:[w&&i.jsx("div",{className:"flex-shrink-0 flex items-center justify-center pr-2",style:{width:"10%",minWidth:"48px"},children:!M&&wt(w)?i.jsx("a",{href:y||"#",target:y?"_blank":void 0,rel:y?"noopener noreferrer":void 0,onClick:y?x:void 0,className:"block",style:{cursor:y?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:i.jsx("img",{src:w,alt:`${b} logo`,className:"object-cover border border-gray-200 dark:border-gray-700",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{C(!0),a.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):i.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 border border-gray-200 dark:border-gray-700",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px"},children:A})}),i.jsxs("div",{className:"flex-1",style:{width:w?"90%":"100%",minWidth:0},children:[S&&i.jsx("div",{className:"mb-2",children:i.jsx("h3",{className:"text-black dark:text-white font-semibold text-base",children:y&&b?i.jsxs(i.Fragment,{children:[i.jsx("a",{href:y,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:R,children:b}),k&&` โ€” ${k}`]}):S})}),c&&i.jsx("p",{className:"text-gray-700 dark:text-gray-300 text-sm mb-3 leading-relaxed",children:c}),i.jsxs("div",{className:"flex items-center justify-between mt-2",children:[g&&y&&i.jsx("a",{href:y,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:_,children:g}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})]})]})]})})};function kt(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 Ve;function _t(){return Ve||(Ve=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var n="",d=0;d<arguments.length;d++){var l=arguments[d];l&&(n=s(n,o(l)))}return n}function o(n){if(typeof n=="string"||typeof n=="number")return n;if(typeof n!="object")return"";if(Array.isArray(n))return r.apply(null,n);if(n.toString!==Object.prototype.toString&&!n.toString.toString().includes("[native code]"))return n.toString();var d="";for(var l in n)e.call(n,l)&&n[l]&&(d=s(d,l));return d}function s(n,d){return d?n?n+" "+d:n+d:n}t.exports?(r.default=r,t.exports=r):window.classNames=r})()})(Fe)),Fe.exports}var kt=_t();const ce=wt(kt),At="https://api.useadmesh.com/track";let St={enabled:!0,retryAttempts:3,retryDelay:1e3};const Qe=t=>{const[e,r]=h.useState(!1),[o,s]=h.useState(null),n=h.useMemo(()=>({...St,...t}),[t]),d=h.useCallback(async(c,g)=>{if(!n.enabled)return;if(!g.recommendationId||!g.admeshLink){s("Missing required tracking data: recommendationId and admeshLink are required");return}r(!0),s(null);const b={event_type:c,recommendation_id:g.recommendationId,admesh_link:g.admeshLink,product_id:g.productId,user_id:g.userId,session_id:g.sessionId,revenue:g.revenue,conversion_type:g.conversionType,metadata:g.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};let x=null;for(let y=1;y<=(n.retryAttempts||3);y++)try{const _=await fetch(`${At}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!_.ok)throw new Error(`HTTP ${_.status}: ${_.statusText}`);await _.json(),r(!1);return}catch(_){x=_,y<(n.retryAttempts||3)&&await new Promise(m=>setTimeout(m,(n.retryDelay||1e3)*y))}const f=`Failed to track ${c} event after ${n.retryAttempts} attempts: ${x==null?void 0:x.message}`;s(f),r(!1)},[n]),l=h.useCallback(async c=>d("click",c),[d]),u=h.useCallback(async c=>d("view",c),[d]),p=h.useCallback(async c=>d("conversion",c),[d]);return{trackClick:l,trackView:u,trackConversion:p,isTracking:e,error:o}},he=({recommendationId:t,admeshLink:e,productId:r,children:o,trackingData:s,className:n,style:d})=>{const{trackClick:l,trackView:u}=Qe(),p=h.useRef(null),c=h.useRef(!1);h.useEffect(()=>{if(!p.current)return;p.current.querySelectorAll("a").forEach(x=>{(!x.hasAttribute("target")||x.getAttribute("target")!=="_blank")&&(x.setAttribute("target","_blank"),x.setAttribute("rel","noopener noreferrer"))})},[o]),h.useEffect(()=>{if(!p.current||c.current)return;const b=new IntersectionObserver(x=>{x.forEach(f=>{f.isIntersecting&&!c.current&&(c.current=!0,u({recommendationId:t,admeshLink:e,productId:r,...s}).catch(a.error))})},{threshold:.5,rootMargin:"0px"});return b.observe(p.current),()=>{b.disconnect()}},[t,e,r,s,u]);const g=h.useCallback(b=>{l({recommendationId:t,admeshLink:e,productId:r,...s}).catch(()=>{a.error("[AdMesh] Failed to track click")});const f=b.target.closest("a");f?(!f.hasAttribute("target")||f.getAttribute("target")!=="_blank")&&(f.setAttribute("target","_blank"),f.setAttribute("rel","noopener noreferrer")):window.open(e,"_blank","noopener,noreferrer")},[t,e,r,s,l]);return i.jsx("div",{ref:p,className:n,onClick:g,style:{cursor:"pointer",...d},children:o})};he.displayName="AdMeshLinkTracker";const Ie="admesh-ui-sdk-styles",je="admesh-ui-sdk-reset",Mt=`
5
+ */var He;function At(){return He||(He=1,(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var r="",d=0;d<arguments.length;d++){var l=arguments[d];l&&(r=s(r,o(l)))}return r}function o(r){if(typeof r=="string"||typeof r=="number")return r;if(typeof r!="object")return"";if(Array.isArray(r))return n.apply(null,r);if(r.toString!==Object.prototype.toString&&!r.toString.toString().includes("[native code]"))return r.toString();var d="";for(var l in r)e.call(r,l)&&r[l]&&(d=s(d,l));return d}function s(r,d){return d?r?r+" "+d:r+d:r}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Fe)),Fe.exports}var St=At();const me=kt(St),Mt="https://api.useadmesh.com/track";let Ct={enabled:!0,retryAttempts:3,retryDelay:1e3};const Ye=t=>{const[e,n]=p.useState(!1),[o,s]=p.useState(null),r=p.useMemo(()=>({...Ct,...t}),[t]),d=p.useCallback(async(c,h)=>{if(!r.enabled)return;if(!h.recommendationId||!h.admeshLink){s("Missing required tracking data: recommendationId and admeshLink are required");return}n(!0),s(null);const b={event_type:c,recommendation_id:h.recommendationId,admesh_link:h.admeshLink,product_id:h.productId,user_id:h.userId,session_id:h.sessionId,revenue:h.revenue,conversion_type:h.conversionType,metadata:h.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};let v=null;for(let w=1;w<=(r.retryAttempts||3);w++)try{const y=await fetch(`${Mt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!y.ok)throw new Error(`HTTP ${y.status}: ${y.statusText}`);await y.json(),n(!1);return}catch(y){v=y,w<(r.retryAttempts||3)&&await new Promise(g=>setTimeout(g,(r.retryDelay||1e3)*w))}const f=`Failed to track ${c} event after ${r.retryAttempts} attempts: ${v==null?void 0:v.message}`;s(f),n(!1)},[r]),l=p.useCallback(async c=>d("click",c),[d]),u=p.useCallback(async c=>d("view",c),[d]),m=p.useCallback(async c=>d("conversion",c),[d]);return{trackClick:l,trackView:u,trackConversion:m,isTracking:e,error:o}},pe=({recommendationId:t,admeshLink:e,productId:n,children:o,trackingData:s,className:r,style:d})=>{const{trackClick:l,trackView:u}=Ye(),m=p.useRef(null),c=p.useRef(!1);p.useEffect(()=>{if(!m.current)return;m.current.querySelectorAll("a").forEach(v=>{(!v.hasAttribute("target")||v.getAttribute("target")!=="_blank")&&(v.setAttribute("target","_blank"),v.setAttribute("rel","noopener noreferrer"))})},[o]),p.useEffect(()=>{if(!m.current||c.current)return;const b=new IntersectionObserver(v=>{v.forEach(f=>{f.isIntersecting&&!c.current&&(c.current=!0,u({recommendationId:t,admeshLink:e,productId:n,...s}).catch(a.error))})},{threshold:.5,rootMargin:"0px"});return b.observe(m.current),()=>{b.disconnect()}},[t,e,n,s,u]);const h=p.useCallback(b=>{l({recommendationId:t,admeshLink:e,productId:n,...s}).catch(()=>{a.error("[AdMesh] Failed to track click")});const f=b.target.closest("a");f?(!f.hasAttribute("target")||f.getAttribute("target")!=="_blank")&&(f.setAttribute("target","_blank"),f.setAttribute("rel","noopener noreferrer")):window.open(e,"_blank","noopener,noreferrer")},[t,e,n,s,l]);return i.jsx("div",{ref:m,className:r,onClick:h,style:{cursor:"pointer",...d},children:o})};pe.displayName="AdMeshLinkTracker";const Ie="admesh-ui-sdk-styles",je="admesh-ui-sdk-reset",Et=`
6
6
  /* AdMesh UI SDK - CSS Reset & Normalization */
7
7
  .admesh-component,
8
8
  .admesh-component * {
@@ -91,7 +91,7 @@
91
91
  .admesh-component[data-admesh-theme="light"] {
92
92
  color-scheme: light;
93
93
  }
94
- `,Ct=`
94
+ `,Tt=`
95
95
  /* AdMesh Core Component Styles */
96
96
 
97
97
  .admesh-component {
@@ -302,7 +302,7 @@
302
302
  font-size: 0.875rem;
303
303
  }
304
304
  }
305
- `,Et=()=>{if(!(typeof document>"u")&&!(document.getElementById(je)&&document.getElementById(Ie))){if(!document.getElementById(je)){const t=document.createElement("style");t.id=je,t.textContent=Mt,document.head.appendChild(t)}if(!document.getElementById(Ie)){const t=document.createElement("style");t.id=Ie,t.textContent=Ct,document.head.appendChild(t)}}},Tt=`
305
+ `,Rt=()=>{if(!(typeof document>"u")&&!(document.getElementById(je)&&document.getElementById(Ie))){if(!document.getElementById(je)){const t=document.createElement("style");t.id=je,t.textContent=Et,document.head.appendChild(t)}if(!document.getElementById(Ie)){const t=document.createElement("style");t.id=Ie,t.textContent=Tt,document.head.appendChild(t)}}},Ft=`
306
306
  /* AdMesh UI SDK - Complete Self-Contained Styles */
307
307
 
308
308
  /* CSS Reset for AdMesh components */
@@ -970,7 +970,7 @@
970
970
  .admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
971
971
  .admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
972
972
  }
973
- `;let He=!1;const Ye=()=>{h.useEffect(()=>{if(!He){try{Et();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Tt,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),He=!0}catch{a.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])},we=(t,e={})=>{const r=t.intent_match_score||0,o=e.customLabels||{};return r>=.8?o.partnerRecommendation||"Smart Pick":r>=.6?o.partnerMatch||"Partner Recommendation":r>=.3?o.promotedOption||"Promoted Match":o.relatedOption||"Related"},Oe=(t,e)=>{const r=t.intent_match_score||0;return r>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":r>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":r>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},Se=({recommendation:t,theme:e,variation:r="default",className:o,style:s,sessionId:n})=>{var g,b,x,f,y,_,m,M,S,I,E,w,v,A,C,k,R,T,j,D,P,O,K,z,ee,te;if(!t||typeof t!="object")return a.log("[AdMesh Product Card] No recommendation provided - not rendering"),null;if(!t.recommendation_id&&!t.title)return a.log("[AdMesh Product Card] Invalid recommendation object (missing required fields) - not rendering"),null;Ye();const l=(()=>{const $=t.creative_input||{},X=$.product_name||t.title||t.product_title||"";let re="";r==="simple"?re=$.short_description||$.context_snippet||t.product_summary||t.weave_summary||t.reason||"":re=$.long_description||$.short_description||t.product_summary||t.weave_summary||t.reason||"";const N=$.cta_label||X;return r==="simple"?{title:X,description:re,ctaText:N,isSimple:!0}:{title:X,description:re,ctaText:N}})(),u=ce("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",o),p=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(g=e.shadows)==null?void 0:g.small,"--admesh-shadow-md":(b=e.shadows)==null?void 0:b.medium,"--admesh-shadow-lg":(x=e.shadows)==null?void 0:x.large,"--admesh-spacing-sm":(f=e.spacing)==null?void 0:f.small,"--admesh-spacing-md":(y=e.spacing)==null?void 0:y.medium,"--admesh-spacing-lg":(_=e.spacing)==null?void 0:_.large,"--admesh-font-size-sm":(m=e.fontSize)==null?void 0:m.small,"--admesh-font-size-base":(M=e.fontSize)==null?void 0:M.base,"--admesh-font-size-lg":(S=e.fontSize)==null?void 0:S.large,"--admesh-font-size-title":(I=e.fontSize)==null?void 0:I.title,fontFamily:e.fontFamily,width:((w=(E=e.components)==null?void 0:E.productCard)==null?void 0:w.width)||"100%"}:{width:"100%"};if(r==="simple"){const $=t.product_id||"";return i.jsx(ae,{productId:$,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:n,className:ce("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",o),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(v=e==null?void 0:e.components)==null?void 0:v.productCard,...s},children:i.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:Oe(t,we(t)),children:we(t)}),i.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[l.description," "]}),i.jsx(he,{recommendationId:t.recommendation_id||"",admeshLink:t.click_url||t.admesh_link||((A=t.creative_input)==null?void 0:A.cta_url)||t.url,productId:t.product_id,trackingData:{title:l.title,matchScore:t.contextual_relevance_score,component:"simple_ad_cta"},children:i.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:l.ctaText})})]})})}const c=t.product_id||"";return a.debug("[AdMeshProductCard] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:t.recommendation_id,productId:c,exposureUrl:t.exposure_url?"present":"MISSING",sessionId:n?"present":"MISSING"}),i.jsx(ae,{productId:c,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:n,className:u,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(C=e==null?void 0:e.components)==null?void 0:C.productCard,...s},children:i.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(k=e==null?void 0:e.components)==null?void 0:k.productCard,...s},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",style:p,children:[i.jsx("div",{className:"mb-1.5",children:i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:Oe(t,we(t)),children:we(t)})}),i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(((T=(R=t.creative_input)==null?void 0:R.assets)==null?void 0:T.logo_url)||((j=t.product_logo)==null?void 0:j.url))&&i.jsx("img",{src:((P=(D=t.creative_input)==null?void 0:D.assets)==null?void 0:P.logo_url)||((O=t.product_logo)==null?void 0:O.url),alt:`${l.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:$=>{$.target.style.display="none"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:l.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(he,{recommendationId:t.recommendation_id||"",admeshLink:t.click_url||t.admesh_link||((K=t.creative_input)==null?void 0:K.cta_url)||t.url,productId:t.product_id,trackingData:{title:l.title,matchScore:t.contextual_relevance_score,component:"product_card_cta"},children:i.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:[((z=t.creative_input)==null?void 0:z.cta_label)||"Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),i.jsx("div",{className:"mb-3",children:i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:l.description})}),((ee=t.creative_input)==null?void 0:ee.offer_summary)&&i.jsx("div",{className:"mb-3",children:i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 leading-relaxed italic",children:t.creative_input.offer_summary})}),((te=t.creative_input)==null?void 0:te.value_props)&&t.creative_input.value_props.length>0&&i.jsx("div",{className:"mb-3",children:i.jsx("ul",{className:"space-y-1.5",children:t.creative_input.value_props.slice(0,3).map(($,X)=>i.jsxs("li",{className:"flex items-start gap-2 text-xs text-gray-600 dark:text-gray-400",children:[i.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),i.jsx("span",{children:$})]},X))})}),i.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};Se.displayName="AdMeshProductCard";const Le=h.createContext(void 0);function Ze(){const t=h.useContext(Le);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function le(){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 Rt=(t,e)=>{if(!t)return"Get Started";let r="";const o=[/(?: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 d of o){const l=t.match(d);if(l&&l[1]){r=l[1].trim();break}}const s=e||r;if(s)return`Integrate ${s.split(/\s+/).slice(0,2).join(" ")}`;const n=t.match(/to\s+set\s+up\s+([a-zA-Z0-9\s]+?)(?:\s+by|\s*[.,]|$)/i);return n&&n[1]?`Integrate ${n[1].trim().split(/\s+/).slice(0,2).join(" ")}`:"Integrate"},Ne=({recommendation:t,theme:e,className:r="",style:o={},sessionId:s,onLinkClick:n,onPasteToInput:d})=>{var E,w,v,A,C,k,R;const l=t.creative_input||{},u=l.bridge_headline||"",p=l.bridge_description||"",c=l.bridge_prompt||l.bridge_content||"",g=l.product_name||"",b=l.cta_label||"";if(!p&&!c)return null;const x=t.product_id||"",f=t.recommendation_id||"",{sdk:y,sessionId:_}=le(),m=s||_,M=async T=>{if(T.preventDefault(),!!c){if(f&&m)try{const j=(y==null?void 0:y.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",D=await fetch(`${j}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:f,session_id:m,agent_id:t.agent_id,user_id:t.user_id||void 0,is_test:!1})});D.ok?a.log("[AdMesh Bridge] โœ… Engagement tracked successfully"):a.warn("[AdMesh Bridge] โš ๏ธ Failed to track engagement:",D.statusText)}catch(j){a.error("[AdMesh Bridge] โŒ Error tracking engagement:",j)}n&&n(t),d?d(c):typeof window<"u"&&window.__admesh_setMessage&&window.__admesh_setMessage(c)}},S=b||Rt(c,g),I=!!S;return i.jsx(ae,{productId:x,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:s,className:`admesh-bridge-format ${r}`,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",...o},children:i.jsxs("div",{"data-admesh-theme":(e==null?void 0:e.mode)||"light",children:[u&&i.jsx("div",{className:"admesh-bridge-headline",style:{marginBottom:p?"0.75rem":I?"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:u}),p&&i.jsx("div",{className:"admesh-bridge-description",style:{marginBottom:I||(w=t.creative_input)!=null&&w.offer_summary?"1rem":"0",lineHeight:"1.6",fontSize:((v=e==null?void 0:e.fontSize)==null?void 0:v.base)||"0.875rem",color:(e==null?void 0:e.textColor)||"inherit"},children:p}),((A=t.creative_input)==null?void 0:A.offer_summary)&&i.jsx("div",{className:"admesh-bridge-offer-summary",style:{marginBottom:I?"1rem":"0",lineHeight:"1.5",fontSize:((C=e==null?void 0:e.fontSize)==null?void 0:C.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}),I&&i.jsx("div",{style:{marginBottom:"0.75rem"},children:i.jsx("button",{onClick:M,className:"admesh-bridge-cta-button",style:{padding:"0.5rem 1rem",backgroundColor:"#000000",color:"#ffffff",fontSize:((k=e==null?void 0:e.fontSize)==null?void 0:k.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:T=>{T.currentTarget.style.backgroundColor="#1a1a1a",T.currentTarget.style.opacity="0.9"},onMouseLeave:T=>{T.currentTarget.style.backgroundColor="#000000",T.currentTarget.style.opacity="1"},children:S})}),i.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"0.5rem"},children:i.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"})})]})})},Xe=({recommendations:t,summaryText:e,theme:r,className:o="",style:s={},onLinkClick:n,onPasteToInput:d,sessionId:l,response:u})=>{var x;const c=(t||(u==null?void 0:u.recommendations)||[]).filter(f=>f&&typeof f=="object"&&f.recommendation_id);if(!c||c.length===0)return a.log("[AdMesh Summary Layout] Empty or invalid recommendations array - not rendering anything"),null;let g=e||(u==null?void 0:u.tail_summary);if(!g&&c.length>0&&((x=c[0])!=null&&x.creative_input)){const f=c[0].creative_input;g=f.long_description||f.context_snippet||f.short_description||void 0}a.log(`[AdMesh Summary Layout] Rendering with ${c.length} valid recommendations`);const b=()=>{if(c.length>0){const f=c[0],y=(f==null?void 0:f.creative_input)||{},_=!!y.bridge_prompt||!!y.bridge_content,m=(f==null?void 0:f.format)||(y==null?void 0:y.format),M=f==null?void 0:f.preferred_format,S=m==="bridge"||M==="bridge";if(a.log("[AdMesh Summary Layout] ๐Ÿ” Checking format:",{hasBridgePrompt:_,bridgePrompt:y.bridge_prompt||y.bridge_content?(y.bridge_prompt||y.bridge_content||"").substring(0,50)+"...":void 0,format:m,preferredFormat:M,creativeInputKeys:Object.keys(y),recommendationKeys:Object.keys(f||{})}),_||S)return a.log("[AdMesh Summary Layout] ๐ŸŽฏ โœ… Rendering bridge format"),i.jsx(Ne,{recommendation:f,theme:r,sessionId:l,onLinkClick:n,onPasteToInput:d});a.log("[AdMesh Summary Layout] โš ๏ธ Bridge format NOT detected, falling back to other formats")}return g?i.jsx(Ae,{summaryText:g,recommendations:c,theme:r,onLinkClick:n,sessionId:l}):c.length>0&&c[0]?i.jsx("div",{className:"fallback-citation",children:i.jsx(Se,{recommendation:c[0],theme:r,sessionId:l})}):null};return i.jsx("div",{className:`admesh-summary-layout ${o}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:b()})},Je=({recommendations:t,summaryText:e,theme:r,className:o,style:s,onLinkClick:n,onPasteToInput:d,sessionId:l,response:u})=>{const p=t||(u==null?void 0:u.recommendations)||[],c=e||(u==null?void 0:u.tail_summary),g=p.filter(b=>b&&typeof b=="object"&&b.recommendation_id);return!g||g.length===0?(a.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null):i.jsx(Xe,{recommendations:g,summaryText:c,theme:r,className:o,style:s,onLinkClick:n,onPasteToInput:d,sessionId:l})},Ft=({className:t,size:e=20})=>i.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:[i.jsx("path",{d:"M5 12h14"}),i.jsx("path",{d:"M12 5v14"})]}),Me=({recommendation:t,theme:e,sdk:r,sessionId:o,onExecuteQuery:s})=>{const n=t.followup_query,d=t.followup_engagement_url,l=t.followup_exposure_url,u=t.recommendation_id;if(!n||!d||!l)return a.log("[AdMeshFollowup] Missing followup_query, followup_engagement_url, or followup_exposure_url - not rendering"),null;const p=async()=>{try{d&&u&&(a.log("[AdMeshFollowup] ๐ŸŽฏ Firing follow-up engagement tracking"),await r.fireFollowupEngagement(d,u,o)),s&&n?(a.log(`[AdMeshFollowup] ๐Ÿ” Executing query: ${n}`),await s(n)):a.warn("[AdMeshFollowup] โš ๏ธ onExecuteQuery not provided - cannot execute query")}catch(c){a.error("[AdMeshFollowup] โŒ Error handling follow-up click:",c)}};return e!=null&&e.mode,i.jsx(ae,{productId:t.product_id||"",recommendationId:u||"",exposureUrl:l,sessionId:o,className:"admesh-followup-container",style:{width:"100%"},children:i.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[i.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),i.jsxs("div",{onClick:p,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===" ")&&p()},"aria-label":`Sponsored follow-up: ${n}`,children:[i.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:n}),i.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),i.jsx(Ft,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})};class et{constructor(e){Z(this,"firedExposures",new Set);Z(this,"debug",!1);Z(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,r,o){const s=`${o}_${r}`;if(this.firedExposures.has(s)){this.debug&&a.log("[Tracker] Exposure already fired");return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&a.warn("[Tracker] Failed to fire exposure")}),this.debug&&a.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&a.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,r,o,s){const n=`${o}_${r}`;if(this.firedExposures.has(n)){this.debug&&a.log("[Tracker] MRC exposure already fired");return}return new Promise(d=>{let l=null,u=null;const p=new IntersectionObserver(b=>{b.forEach(x=>{x.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?l===null&&(l=Date.now(),this.debug&&a.log("[Tracker] Ad reached MRC visibility threshold"),u=setTimeout(()=>{this.fireExposure(e,r,o),p.disconnect(),d()},this.mrcThreshold.minimumDurationMs)):l!==null&&(u&&(clearTimeout(u),u=null),l=null,this.debug&&a.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});p.observe(s);const g=setTimeout(()=>{p.disconnect(),u&&clearTimeout(u),d()},3e4);s.__admeshTrackerCleanup=()=>{p.disconnect(),u&&clearTimeout(u),clearTimeout(g)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,r,o){this.fireExposure(e,r,o)}fireFollowupEngagement(e,r,o){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:o})}).catch(s=>{this.debug&&a.warn("[Tracker] Failed to fire followup engagement (non-critical):",s)}).then(()=>{})}}class tt{constructor(){Z(this,"roots",new Map)}async render(e){var r;try{a.log("[AdMeshRenderer] ๐ŸŽจ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){a.log("[AdMeshRenderer] โš ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw a.error("[AdMeshRenderer] โŒ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);a.log("[AdMeshRenderer] โœ… Container ready");const n=this.roots.get(e.containerId);n&&(a.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing root"),n.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const d=$e.createRoot(s),l=((r=o[0])==null?void 0:r.tail_summary)||"";a.log("[AdMeshRenderer] ๐Ÿ“Š Rendering recommendations");const u=e.onPasteToInput||(typeof window<"u"?window.__admesh_onPasteToInput:void 0);if(d.render(i.jsx(Je,{recommendations:o,summaryText:l,theme:e.theme,sessionId:e.sessionId,onPasteToInput:u})),s.style.display="block",a.log("[AdMeshRenderer] โœ… Recommendations rendered successfully"),this.roots.set(e.containerId,d),e.followups_container_id){const p=o[0];p!=null&&p.followup_query&&(p!=null&&p.followup_engagement_url)&&await this.renderFollowup({containerId:e.followups_container_id,recommendation:p,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,onExecuteQuery:e.onExecuteQuery})}}catch(o){throw a.error("[AdMeshRenderer] โŒ Error rendering recommendations"),o}}async renderFollowup(e){try{a.log(`[AdMeshRenderer] ๐ŸŽฏ Rendering follow-up in container: ${e.containerId}`);const r=document.getElementById(e.containerId);if(!r){a.warn(`[AdMeshRenderer] โš ๏ธ Followups container not found: ${e.containerId}`);return}const o=this.roots.get(e.containerId);o&&(a.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing followup root"),o.unmount(),this.roots.delete(e.containerId)),r.innerHTML="";const s=$e.createRoot(r);s.render(i.jsx(Me,{recommendation:e.recommendation,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,onExecuteQuery:e.onExecuteQuery})),r.style.display="block",a.log("[AdMeshRenderer] โœ… Follow-up rendered successfully"),this.roots.set(e.containerId,s)}catch{a.error("[AdMeshRenderer] โŒ Error rendering follow-up")}}unmount(e){const r=this.roots.get(e);if(r){r.unmount(),this.roots.delete(e);const o=document.getElementById(e);o&&(o.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class rt{constructor(e){Z(this,"config");Z(this,"apiBaseUrl");Z(this,"renderer",null);Z(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"}static createSession(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}static createMessageId(e){const r=Date.now(),o=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${r}_${o}`:`msg_${r}_${o}`}getRenderer(){return this.renderer||(this.renderer=new tt),this.renderer}getTracker(){return this.tracker||(this.tracker=new et({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 r=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}),o=this.convertAIPResponseToRecommendation(r),s={session_id:r.session_id,message_id:`msg_${r.recommendation_id}`,recommendations:[o]},n=this.getRenderer(),d=this.getTracker();await n.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:d,sessionId:e.session_id,onPasteToInput:e.onPasteToInput,onExecuteQuery:e.onExecuteQuery})}catch(r){throw a.error("[AdMeshSDK] Error showing recommendations"),r}}async fetchRecommendationFromAIPContext(e){var g,b,x;const r=`${this.apiBaseUrl}/aip/context`;if(a.log("[AdMeshSDK] ๐Ÿ“ฅ fetchRecommendationFromAIPContext called"),!e.sessionId||e.sessionId.trim()===""){const f=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw a.error("[AdMeshSDK] โŒ sessionId not provided by platform - cannot process request"),f}const o=e.messageId;if(!o||o.trim()===""){const f=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw a.error("[AdMeshSDK] โŒ messageId not provided by platform - cannot process request"),f}const s=e.messages?e.messages.length:0,n=(typeof window<"u"&&window.navigator,"web"),d=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",l={spec_version:"1.0.0",message_id:o,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:n,form_factor:d},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())&&a.warn("[AdMeshSDK] โš ๏ธ Warning: Sending request with empty query_text");const u=JSON.stringify(l);a.log("[AdMeshSDK] ๐Ÿ“ค Sending request to /aip/context");const p=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:u});if(!p.ok){const y=(await p.json().catch(()=>({}))).detail||`HTTP ${p.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${y}`)}const c=await p.json();return a.log("[AdMeshSDK] ๐Ÿ“ฅ Raw response from /aip/context:",{hasCreative:!!c.creative,creativeFormat:(g=c.creative)==null?void 0:g.format,creativeBridgeContent:(b=c.creative)!=null&&b.bridge_content?c.creative.bridge_content.substring(0,50)+"...":void 0,hasWinningBid:!!c.winning_bid,winningBidPreferredFormat:(x=c.winning_bid)==null?void 0:x.preferred_format,topLevelKeys:Object.keys(c)}),c}convertAIPResponseToRecommendation(e){var M,S,I,E,w,v,A;const r=e;let o=e.creative_input||{};const s=r.creative||{},n=s.format||r.format||((M=r.winning_bid)==null?void 0:M.preferred_format),d=s.headline,l=s.bridge_headline,u=s.bridge_description,p=s.bridge_prompt||s.bridge_content,c=p||o.bridge_prompt||o.bridge_content,g=s.cta_label,b=g||o.cta_label,x=l||o.bridge_headline,f=u||o.bridge_description;a.log("[AdMeshSDK] ๐Ÿ” Extracting from response:",{creativeObject:s,creativeFormat:s.format,creativeBridgeHeadline:l,creativeBridgeDescription:u?String(u).substring(0,50)+"...":void 0,creativeBridgePrompt:p?String(p).substring(0,50)+"...":void 0,creativeCtaLabel:g,extractedFormat:n,extractedBridgeHeadline:x,extractedBridgeDescription:f?String(f).substring(0,50)+"...":void 0,extractedBridgePrompt:c?String(c).substring(0,50)+"...":void 0,extractedCtaLabel:b,creativeInputHasBridgeHeadline:!!o.bridge_headline,creativeInputHasBridgeDescription:!!o.bridge_description,creativeInputHasBridgePrompt:!!o.bridge_prompt,creativeInputHasBridgeContent:!!o.bridge_content,creativeInputHasCtaLabel:!!o.cta_label}),o={...o,...d&&{headline:d},...x&&{bridge_headline:x},...f&&{bridge_description:f},...c&&{bridge_prompt:c},...c&&{bridge_content:c},...b&&{cta_label:b},...n&&{format:n}};const y=e.recommendation_id||r.recommendation_id||r.bid_id||"",_=e.click_url||e.admesh_link||"",m={...e,recommendation_id:y,admesh_link:_||e.click_url||"",ad_id:void 0,bid_id:void 0,creative_input:o,product_title:e.title,tail_summary:o.long_description||"",product_summary:o.short_description||"",weave_summary:o.context_snippet||"",product_logo:(S=o.assets)!=null&&S.logo_url?{url:o.assets.logo_url}:void 0,categories:o.categories||[]};return delete m.ad_id,delete m.bid_id,n&&(m.format=n),a.log("[AdMeshSDK] ๐Ÿ”„ Converted recommendation:",{hasFormat:!!n,format:n,hasBridgeHeadline:!!x,bridgeHeadline:x,hasBridgeDescription:!!f,bridgeDescriptionPreview:f?String(f).substring(0,50)+"...":void 0,hasBridgePrompt:!!c,hasCtaLabel:!!b,ctaLabel:b,bridgeHeadlineInCreativeInput:!!((I=m.creative_input)!=null&&I.bridge_headline),bridgeDescriptionInCreativeInput:!!((E=m.creative_input)!=null&&E.bridge_description),bridgePromptInCreativeInput:!!((w=m.creative_input)!=null&&w.bridge_prompt),bridgeContentInCreativeInput:!!((v=m.creative_input)!=null&&v.bridge_content),ctaLabelInCreativeInput:!!((A=m.creative_input)!=null&&A.cta_label),bridgePromptPreview:c?String(c).substring(0,50)+"...":void 0,creativeInputKeys:Object.keys(m.creative_input||{}),recommendationFormat:m.format}),m}fireFollowupExposure(e,r,o){this.getTracker().fireFollowupExposure(e,r,o)}async fireFollowupEngagement(e,r,o){return this.getTracker().fireFollowupEngagement(e,r,o)}}class Pe{constructor(e={}){Z(this,"autoAddLabels");Z(this,"fireExposurePixels");Z(this,"labelStyle");Z(this,"processedLinks",new Set);Z(this,"mutationObserver",null);var r,o,s,n;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((r=e.labelStyle)==null?void 0:r.fontSize)||"0.75em",fontWeight:((o=e.labelStyle)==null?void 0:o.fontWeight)||"bold",color:((s=e.labelStyle)==null?void 0:s.color)||"#666",marginLeft:((n=e.labelStyle)==null?void 0:n.marginLeft)||"2px"}}getLinksToProcess(e){const o=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return o.length>0?Array.from(o):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,r,o){if(!e)return[];const s=[];if(r.length>0){const n=this.getLinksToProcess(e),d=new Map(r.filter(u=>u.click_url).map(u=>[u.click_url,u])),l=new Map;r.forEach(u=>{var c;const p=u.redirect_url||u.url||((c=u.creative_input)==null?void 0:c.cta_url);if(p&&typeof p=="string"){const g=p.trim().replace(/\/$/,"");l.set(g,u),l.set(`${g}/`,u)}}),n.forEach(u=>{const p=u.getAttribute("href")||"",c=`${p}`;if(this.processedLinks.has(c))return;let g=d.get(p),b=p;if(!g){const x=p.trim().replace(/\/$/,"");g=l.get(x)||l.get(`${x}/`),g&&g.click_url&&(a.log("[WeaveResponseProcessor] ๐Ÿ”„ Found brand URL match, replacing with click_url:",p),u.setAttribute("href",g.click_url),b=g.click_url)}if(g){this.processedLinks.add(c),u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer");const x={element:u,href:b,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:{recommendation_id:g.recommendation_id||"",click_url:g.click_url,exposure_url:g.exposure_url}};this.autoAddLabels&&!x.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to matched recommendation link:",b),this.addAdLabel(u),x.hasAdLabel=!0):this.autoAddLabels?x.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&g.exposure_url&&o&&x.matchedRecommendation&&o({exposureUrl:g.exposure_url,recommendationId:x.matchedRecommendation.recommendation_id,linkElement:u}),s.push(x)}})}else Array.from(e.querySelectorAll("a")).forEach(d=>{const l=d.getAttribute("href")||"",u=`${l}`;if(this.processedLinks.has(u))return;if(this.isAdMeshLink(l)){this.processedLinks.add(u);const c={element:d,href:l,text:d.textContent||"",hasAdLabel:this.hasAdLabel(d),matchedRecommendation:void 0};if(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to pattern-matched AdMesh link:",l),this.addAdLabel(d),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&o){const g=this.convertClickUrlToExposureUrl(l);o({exposureUrl:g,recommendationId:this.extractRecommendationIdFromUrl(l),linkElement:d})}s.push(c)}});return s}hasAdLabel(e){var d,l,u;if((e.textContent||"").includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link text contains [Ad] label"),!0;const o=e.querySelectorAll("sub, span");for(const p of Array.from(o))if((d=p.textContent)!=null&&d.includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link has [Ad] label as child element"),!0;let s=e.previousSibling;for(;s&&s.nodeType===Node.TEXT_NODE;){const p=s.textContent||"";if(p.trim()===""){s=s.previousSibling;continue}if(p.includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous text sibling"),!0;break}if(s&&s.nodeType===Node.ELEMENT_NODE){const p=s,c=p.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((l=p.textContent)!=null&&l.includes("[Ad]")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous element sibling:",c),!0}let n=e.nextSibling;for(;n&&n.nodeType===Node.TEXT_NODE;){const p=n.textContent||"";if(p.trim()===""){n=n.nextSibling;continue}if(p.includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next text sibling"),!0;break}if(n&&n.nodeType===Node.ELEMENT_NODE){const p=n,c=p.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((u=p.textContent)!=null&&u.includes("[Ad]")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next element sibling:",c),!0}return a.log("[WeaveResponseProcessor] โ„น๏ธ No existing [Ad] label found"),!1}addAdLabel(e){if(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Attempting to add [Ad] label to link:",e.href),!e.isConnected){a.warn("[WeaveResponseProcessor] โš ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has [Ad] label, skipping");return}const r=e.parentNode;if(!r){a.error("[WeaveResponseProcessor] โŒ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const o=document.createElement("sub");o.textContent="[Ad]",o.style.fontSize=this.labelStyle.fontSize,o.style.fontWeight=this.labelStyle.fontWeight,o.style.color=this.labelStyle.color,o.style.marginLeft=this.labelStyle.marginLeft,o.style.cursor="pointer",o.style.borderBottom=`1px dotted ${this.labelStyle.color}`,o.style.whiteSpace="nowrap",o.title="Why this ad? This is a sponsored recommendation based on your search query.";let s=!1;o.addEventListener("mouseenter",()=>{o.style.opacity="0.7"}),o.addEventListener("mouseleave",()=>{o.style.opacity="1",s&&(s=!1)}),o.addEventListener("click",d=>{d.stopPropagation(),s=!s,s?(o.style.textDecoration="underline",o.style.opacity="0.7"):(o.style.textDecoration="none",o.style.opacity="1")});const n=d=>{s&&d.target!==o&&(s=!1,o.style.textDecoration="none",o.style.opacity="1")};document.addEventListener("click",n);try{const d=e.nextSibling;d?(r.insertBefore(o,d),a.log("[WeaveResponseProcessor] โœ… [Ad] label inserted before next sibling")):(r.appendChild(o),a.log("[WeaveResponseProcessor] โœ… [Ad] label appended to parent (no next sibling)")),o.isConnected&&o.parentNode===r?a.log("[WeaveResponseProcessor] โœ… [Ad] label successfully added to link:",e.href):a.error("[WeaveResponseProcessor] โŒ [Ad] label insertion failed - label not in DOM")}catch(d){a.error("[WeaveResponseProcessor] โŒ Error inserting [Ad] label:",d)}}removeLeftAdLabel(e){var o,s,n;let r=e.previousSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const d=r.textContent||"";if(d.trim()===""){r=r.previousSibling;continue}if(d.includes("[Ad]")){(o=r.parentNode)==null||o.removeChild(r);return}break}if(r&&r.nodeType===Node.ELEMENT_NODE){const d=r;(d.tagName==="SUB"||d.tagName==="SPAN")&&((s=d.textContent)!=null&&s.includes("[Ad]"))&&((n=d.parentNode)==null||n.removeChild(d))}}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 r=e.match(/\/click\/([^/?]+)/);return r&&r[1]?r[1]:""}catch{return e}}convertClickUrlToExposureUrl(e){try{const r=new URL(e),s=`${`${r.protocol}//${r.host}`}/exposure`,n=new URLSearchParams(r.search);return n.has("cpx")||n.set("cpx","0"),`${s}?${n.toString()}`}catch{return a.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,r,o){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,r,o)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}const It=({apiKey:t,sessionId:e,theme:r,apiBaseUrl:o,language:s,geo_country:n,userId:d,model:l,messages:u,children:p})=>{const c=h.useRef(null),[g,b]=h.useState(new Set);h.useEffect(()=>{if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");return}},[e]),h.useEffect(()=>{if(!t){a.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ Cannot initialize SDK: sessionId is required and must be provided by the platform");return}try{c.current=new rt({apiKey:t,theme:r,apiBaseUrl:o}),a.log("[AdMeshProvider] โœ… AdMesh SDK initialized"),o&&a.log("[AdMeshProvider] ๐Ÿ“ Using custom API base URL")}catch{a.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK")}return()=>{a.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,r,o]);const x={sdk:c.current,apiKey:t,sessionId:e,theme:r,language:s,geo_country:n,userId:d,model:l,messages:u,processedMessageIds:g,markMessageAsProcessed:f=>{b(y=>{const _=new Set(y);return _.add(f),_})},isMessageProcessed:f=>g.has(f)};return i.jsx(Le.Provider,{value:x,children:p})},jt=({onRecommendationsShown:t,onError:e,messageId:r,query:o,onPasteToInput:s,followups_container_id:n,onExecuteQuery:d,onFollowupDetected:l,isContainerReady:u})=>{const{sdk:p,sessionId:c,language:g,geo_country:b,userId:x,model:f,messages:y,theme:_}=le(),[m,M]=h.useState(null),[S,I]=h.useState(null),[E,w]=h.useState(!0),[v,A]=h.useState(null),C=h.useRef(null),k=h.useRef(!1),R=h.useRef(t),T=h.useRef(e),j=h.useRef(l);h.useEffect(()=>{R.current=t,T.current=e,j.current=l},[t,e,l]);const D=N=>{var ve,se,ye,De,We;const G=N;let L=N.creative_input||{};const B=G.creative||{},W=B.format||G.format||((ve=G.winning_bid)==null?void 0:ve.preferred_format)||((se=N.creative_input)==null?void 0:se.preferred_format),Q=B.headline,U=B.bridge_headline,V=B.bridge_description,q=B.bridge_prompt||B.bridge_content||L.bridge_prompt||L.bridge_content,Y=B.cta_label||L.cta_label,oe=U||L.bridge_headline,ne=V||L.bridge_description;L={...L,...Q&&{headline:Q},...oe&&{bridge_headline:oe},...ne&&{bridge_description:ne},...q&&{bridge_prompt:q},...q&&{bridge_content:q},...Y&&{cta_label:Y},...W&&{format:W}};const ge=N.recommendation_id||N.bid_id||"",fe=N.click_url||N.admesh_link||"",F={...N,recommendation_id:ge,admesh_link:fe||N.click_url||"",creative_input:L,ad_id:void 0,bid_id:void 0,...W&&{format:W}};delete F.ad_id,delete F.bid_id;const me=N.followup_query,Ee=((ye=N.creative_input)==null?void 0:ye.followup_query)||(L==null?void 0:L.followup_query),ue=me||Ee,de=N.followup_engagement_url,Te=((De=N.creative_input)==null?void 0:De.followup_engagement_url)||(L==null?void 0:L.followup_engagement_url),be=de||Te,pe=N.followup_exposure_url,Re=((We=N.creative_input)==null?void 0:We.followup_exposure_url)||(L==null?void 0:L.followup_exposure_url),xe=pe||Re;return ue&&(F.followup_query=ue,a.debug("[AdMeshRecommendations] โœ… Extracted followup_query:",ue.substring(0,50)+"...")),be&&(F.followup_engagement_url=be,a.debug("[AdMeshRecommendations] โœ… Extracted followup_engagement_url")),xe&&(F.followup_exposure_url=xe,a.debug("[AdMeshRecommendations] โœ… Extracted followup_exposure_url")),F};h.useEffect(()=>{C.current!==r&&(C.current=null,M(null),I(null))},[r]);const[P,O]=h.useState(null);h.useEffect(()=>{if(!(m!=null&&m.followup_query)||!n){O(null);return}if(u===!1){a.debug("[AdMeshRecommendations] โณ Waiting for container signal...");return}let N=0;const G=5,L=()=>{const W=document.getElementById(n);return W?(a.debug(`[AdMeshRecommendations] โœ… Found followup container: ${n} `),O(W),!0):!1};if(L())return;const B=setInterval(()=>{N++,(L()||N>=G)&&(clearInterval(B),N>=G&&a.warn(`[AdMeshRecommendations] โš ๏ธ Followup container not found after signal: ${n} `))},100);return()=>clearInterval(B)},[m,n,u]),h.useEffect(()=>{if(!r||!o||o.trim()===""){a.log("[AdMeshRecommendations] โŒ Validation failed - missing required parameters"),w(!1);return}if(!(p!=null&&p.fetchRecommendationFromAIPContext)){a.log("[AdMeshRecommendations] SDK fetchRecommendationFromAIPContext not available"),w(!1);return}if(C.current===r){a.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(k.current){a.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}a.log("[AdMeshRecommendations] ๐Ÿ“ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var G,L,B,W,Q;try{k.current=!0,w(!0),A(null);const U=await p.fetchRecommendationFromAIPContext({query:o.trim(),sessionId:c,messageId:r,language:g,geo_country:b,userId:x,model:f,...y&&y.length>0&&{messages:y}}),V=D(U),J=U.followup_query||V.followup_query,q=U.followup_engagement_url||V.followup_engagement_url,H=V.recommendation_id||"";J&&(a.debug("[AdMeshRecommendations] โœ… Followup query detected:",J),a.debug("[AdMeshRecommendations] โœ… Followup engagement URL:",q?"present":"missing"),a.debug("[AdMeshRecommendations] โœ… Recommendation ID:",H||"missing"),q||a.debug("[AdMeshRecommendations] โš ๏ธ Followup engagement URL is missing (optional)"),H||a.debug("[AdMeshRecommendations] โš ๏ธ Recommendation ID is missing (optional)"),n?a.debug("[AdMeshRecommendations] โœ… Using SDK-managed portal rendering (followups_container_id provided)"):j.current?(a.debug("[AdMeshRecommendations] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),j.current(J,q||"",H||"")):a.debug("[AdMeshRecommendations] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)")),M(V);const Y=U,oe=((G=Y.creative)==null?void 0:G.preferred_format)||((L=Y.winning_bid)==null?void 0:L.preferred_format)||Y.preferred_format||((B=U.creative_input)==null?void 0:B.preferred_format);let ne;oe?ne=oe==="weave"?"tail":oe:ne="tail",I(ne),C.current=r,a.log("[AdMeshRecommendations] ๐Ÿ“Š Format detected:",ne),w(!1),k.current=!1,(W=R.current)==null||W.call(R,r)}catch(U){const V=U instanceof Error?U:new Error(String(U));V.message.includes("Failed to fetch")||V.message.includes("NetworkError")?a.warn(`[AdMeshRecommendations] โš ๏ธ Network error fetching recommendations(non - critical): ${V.message} `):a.error(`[AdMeshRecommendations] โŒ Error fetching recommendations: ${V.message} `),A(V),w(!1),k.current=!1,(Q=T.current)==null||Q.call(T,V)}})()},[p,c,r,o,g,b,x,f]);const K=()=>P&&(m!=null&&m.followup_query)&&p?(a.debug(`[AdMeshRecommendations] ๐ŸŒ€ Rendering followup portal into: ${n} `),qe.createPortal(i.jsx(Me,{recommendation:m,theme:_,sdk:p,sessionId:c,onExecuteQuery:d}),P)):(a.debug(`[AdMeshRecommendations] โŒ Skipping followup portal.Container: ${!!P}, Query: ${!!(m!=null&&m.followup_query)}, SDK: ${!!p} `),null);if(!r||!o||o.trim()===""||E||v||!m||!S)return null;const z=m.creative_input||{},ee=!!z.bridge_prompt||!!z.bridge_content,te=(m==null?void 0:m.format)||(z==null?void 0:z.format),$=m==null?void 0:m.preferred_format;if(ee||(te==="bridge"||$==="bridge"||S==="bridge"))return i.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[i.jsx(Ne,{recommendation:m,theme:_,sessionId:c,onPasteToInput:s}),K()]});if(S==="product"||S==="product_card")return i.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[i.jsx(Se,{recommendation:m,theme:_,sessionId:c}),K()]});const re=z.long_description||z.context_snippet||z.short_description||"";return i.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[i.jsx(Ae,{summaryText:re,recommendations:[m],theme:_,sessionId:c}),K()]})},nt=({format:t="tail",onError:e,messageId:r,query:o,fallback:s,previousRecommendations:n})=>{const{sdk:d,sessionId:l,theme:u}=le(),p=h.useRef(null),[c,g]=h.useState("");return h.useEffect(()=>{r&&g(`admesh-weave-fallback-${r}`)},[r]),a.log("[WeaveFallbackRecommendations] ๐ŸŽจ Component render"),h.useEffect(()=>{if(a.log("[WeaveFallbackRecommendations] ๐Ÿ”„ useEffect triggered",{fallback:s,hasPreviousRecommendations:n&&n.length>0,previousRecommendationsCount:(n==null?void 0:n.length)||0}),!s){a.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(a.log("[WeaveFallbackRecommendations] โœ… fallback is TRUE, proceeding with recommendations"),!r||!o||o.trim()===""){a.log("[WeaveFallbackRecommendations] โŒ Validation failed - returning early");return}if(a.log("[WeaveFallbackRecommendations] โœ… Validation passed"),!d||!c){a.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const b=n&&n.length>0;a.log("[WeaveFallbackRecommendations] ๐Ÿ“Š Checking previous recommendations:",{hasPreviousRecs:b,count:(n==null?void 0:n.length)||0,fallback:s,messageId:r}),b?(a.log(`[WeaveFallbackRecommendations] โ™ป๏ธ Reusing ${n.length} previous recommendation(s), skipping API call`),(async()=>{var f,y,_,m,M,S,I,E,w;try{const v=n[0];if(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ฆ Processing AIP response:",{hasAipResponse:!!v,recommendationId:v==null?void 0:v.recommendation_id,hasCreativeInput:!!(v!=null&&v.creative_input)}),v&&process.env.NODE_ENV==="development"&&a.log("[WeaveFallbackRecommendations] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:v.recommendation_id,product_id:v.product_id,brand_id:v.brand_id,title:v.title,click_url:v.click_url,contextual_relevance_score:v.contextual_relevance_score,preferred_format:(f=v.creative_input)==null?void 0:f.preferred_format,resolved_format:(y=v.format_resolution)==null?void 0:y.resolved_format,creative_input:{product_name:(_=v.creative_input)==null?void 0:_.product_name,brand_name:(m=v.creative_input)==null?void 0:m.brand_name,cta_url:(M=v.creative_input)==null?void 0:M.cta_url,short_description:(S=v.creative_input)==null?void 0:S.short_description,allowed_formats:(I=v.creative_input)==null?void 0:I.allowed_formats,fallback_formats:(E=v.creative_input)==null?void 0:E.fallback_formats},format_resolution:v.format_resolution,full_response:v}),!v){a.warn("[WeaveFallbackRecommendations] โš ๏ธ Previous recommendation is empty, falling back to API call"),await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:r});return}const A=d,C=A.convertAIPResponseToRecommendation,k=A.getRenderer,R=A.getTracker,T=(w=A.config)==null?void 0:w.theme;if(C&&k&&R){const j=C.call(d,v);if(!j){a.warn("[WeaveFallbackRecommendations] โš ๏ธ Conversion returned empty, falling back to API call"),await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:r});return}const D={session_id:v.session_id||l,message_id:`msg_${v.recommendation_id||r}`,recommendations:[j]},P=k.call(d),O=R.call(d);await P.render({containerId:c,response:D,theme:u||T,tracker:O,sessionId:l}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations rendered from previous response (no API call)")}else a.warn("[WeaveFallbackRecommendations] โš ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:r})}catch(v){const A=v instanceof Error?v:new Error(String(v));a.error(`[WeaveFallbackRecommendations] โŒ Error rendering previous recommendations: ${A.message}`);try{await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:r})}catch{e==null||e(A)}}})()):(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(d!=null&&d.showRecommendations)){a.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:r}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations displayed successfully")}catch(f){const y=f instanceof Error?f:new Error(String(f));a.log(`[WeaveFallbackRecommendations] โŒ Error: ${y.message}`),e==null||e(y)}})())},[d,l,c,t,r,o,s,e,n,u]),!s||!r||!o||o.trim()===""?null:i.jsx("div",{ref:p,id:c,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},ot=h.createContext(void 0),Lt=({children:t,shouldRenderFallback:e,messageId:r,sessionId:o,query:s})=>i.jsx(ot.Provider,{value:{shouldRenderFallback:e,messageId:r,sessionId:o,query:s},children:t}),Nt=()=>h.useContext(ot),Pt=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:o="",cardClassName:s="",onProductClick:n,maxCards:d=10,cardWidth:l="md",theme:u="auto",borderRadius:p="md",shadow:c="sm"})=>{if(!t||t.length===0)return a.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const g=t.slice(0,d),b=()=>{switch(l){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},x=()=>{switch(p){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},f=()=>{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"}},y=()=>u==="dark"?"bg-gray-900 text-white":u==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",_=m=>{var M;if(n)n(m);else{const S=m.click_url||m.admesh_link||m.url||((M=m.creative_input)==null?void 0:M.cta_url);S&&window.open(S,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:i.jsxs("div",{className:ce("w-full",o),children:[r&&i.jsxs("div",{className:"mb-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),i.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),i.jsxs("div",{className:"relative",children:[g.length===0?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):i.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:g.map(m=>{var E,w,v,A,C,k,R,T,j,D,P,O,K,z,ee,te,$,X,re,N,G;const M=m.recommendation_id||m.product_id||m.id||"",S=m.recommendation_id||m.product_id||"",I=m.product_id||"";return i.jsx(ae,{recommendationId:S,productId:I,className:ce(b(),x(),f(),y(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",s),onClick:()=>_(m),children:i.jsxs("div",{children:[i.jsx("div",{className:"relative aspect-square w-full overflow-hidden",children:(w=(E=m.creative_input)==null?void 0:E.assets)!=null&&w.logo_url||(C=(A=(v=m.creative_input)==null?void 0:v.assets)==null?void 0:A.image_urls)!=null&&C[0]||(k=m.product_logo)!=null&&k.url?i.jsx("img",{src:((j=(T=(R=m.creative_input)==null?void 0:R.assets)==null?void 0:T.image_urls)==null?void 0:j[0])||((P=(D=m.creative_input)==null?void 0:D.assets)==null?void 0:P.logo_url)||((O=m.product_logo)==null?void 0:O.url),alt:((K=m.creative_input)==null?void 0:K.product_name)||m.title||m.product_title||"Product",className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy",onError:L=>{L.target.style.display="none"}}):i.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:i.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.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"})})})}),i.jsxs("div",{className:"p-3",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:((z=m.creative_input)==null?void 0:z.product_name)||m.title||m.product_title||""}),(((ee=m.creative_input)==null?void 0:ee.short_description)||((te=m.creative_input)==null?void 0:te.context_snippet)||m.weave_summary)&&i.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 line-clamp-2 mb-2",children:(($=m.creative_input)==null?void 0:$.short_description)||((X=m.creative_input)==null?void 0:X.context_snippet)||m.weave_summary}),((re=m.creative_input)==null?void 0:re.offer_summary)&&i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-500 line-clamp-2 mb-2 italic",children:m.creative_input.offer_summary}),((N=m.creative_input)==null?void 0:N.value_props)&&m.creative_input.value_props.length>0&&i.jsx("div",{className:"mb-2",children:i.jsx("ul",{className:"space-y-1",children:m.creative_input.value_props.slice(0,2).map((L,B)=>i.jsxs("li",{className:"flex items-start gap-1.5 text-xs text-gray-600 dark:text-gray-400",children:[i.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),i.jsx("span",{className:"line-clamp-1",children:L})]},B))})}),(!((G=m.creative_input)!=null&&G.value_props)||m.creative_input.value_props.length===0)&&m.categories&&m.categories.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:m.categories.slice(0,2).map((L,B)=>i.jsx("span",{className:"text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-1 rounded",children:L},B))}),m.trust_score!==void 0&&i.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Trust Score: ",(m.trust_score*100).toFixed(0),"%"]})]})]})},M)})}),g.length>0&&i.jsxs(i.Fragment,{children:[i.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:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),i.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:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),i.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),i.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),i.jsx("style",{dangerouslySetInnerHTML:{__html:`
973
+ `;let Oe=!1;const Ze=()=>{p.useEffect(()=>{if(!Oe){try{Rt();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Ft,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),Oe=!0}catch{a.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])},xe=(t,e={})=>{const n=t.intent_match_score||0,o=e.customLabels||{};return n>=.8?o.partnerRecommendation||"Smart Pick":n>=.6?o.partnerMatch||"Partner Recommendation":n>=.3?o.promotedOption||"Promoted Match":o.relatedOption||"Related"},Ke=(t,e)=>{const n=t.intent_match_score||0;return n>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":n>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":n>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},_e=({recommendation:t,theme:e,variation:n="default",className:o,style:s,sessionId:r})=>{var h,b,v,f,w,y,g,S,k,F,R,_,x,M,C,A,E,T,I,D,P,O,K,B,ee,te;if(!t||typeof t!="object")return a.log("[AdMesh Product Card] No recommendation provided - not rendering"),null;if(!t.recommendation_id&&!t.title)return a.log("[AdMesh Product Card] Invalid recommendation object (missing required fields) - not rendering"),null;Ze();const l=(()=>{const $=t.creative_input||{},X=$.product_name||t.title||t.product_title||"";let re="";n==="simple"?re=$.short_description||$.context_snippet||t.product_summary||t.weave_summary||t.reason||"":re=$.long_description||$.short_description||t.product_summary||t.weave_summary||t.reason||"";const N=$.cta_label||X;return n==="simple"?{title:X,description:re,ctaText:N,isSimple:!0}:{title:X,description:re,ctaText:N}})(),u=me("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",o),m=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(h=e.shadows)==null?void 0:h.small,"--admesh-shadow-md":(b=e.shadows)==null?void 0:b.medium,"--admesh-shadow-lg":(v=e.shadows)==null?void 0:v.large,"--admesh-spacing-sm":(f=e.spacing)==null?void 0:f.small,"--admesh-spacing-md":(w=e.spacing)==null?void 0:w.medium,"--admesh-spacing-lg":(y=e.spacing)==null?void 0:y.large,"--admesh-font-size-sm":(g=e.fontSize)==null?void 0:g.small,"--admesh-font-size-base":(S=e.fontSize)==null?void 0:S.base,"--admesh-font-size-lg":(k=e.fontSize)==null?void 0:k.large,"--admesh-font-size-title":(F=e.fontSize)==null?void 0:F.title,fontFamily:e.fontFamily,width:((_=(R=e.components)==null?void 0:R.productCard)==null?void 0:_.width)||"100%"}:{width:"100%"};if(n==="simple"){const $=t.product_id||"";return i.jsx(ie,{productId:$,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:r,className:me("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",o),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(x=e==null?void 0:e.components)==null?void 0:x.productCard,...s},children:i.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:Ke(t,xe(t)),children:xe(t)}),i.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[l.description," "]}),i.jsx(pe,{recommendationId:t.recommendation_id||"",admeshLink:t.click_url||t.admesh_link||((M=t.creative_input)==null?void 0:M.cta_url)||t.url,productId:t.product_id,trackingData:{title:l.title,matchScore:t.contextual_relevance_score,component:"simple_ad_cta"},children:i.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:l.ctaText})})]})})}const c=t.product_id||"";return a.debug("[AdMeshProductCard] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:t.recommendation_id,productId:c,exposureUrl:t.exposure_url?"present":"MISSING",sessionId:r?"present":"MISSING"}),i.jsx(ie,{productId:c,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:r,className:u,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(C=e==null?void 0:e.components)==null?void 0:C.productCard,...s},children:i.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(A=e==null?void 0:e.components)==null?void 0:A.productCard,...s},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",style:m,children:[i.jsx("div",{className:"mb-1.5",children:i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:Ke(t,xe(t)),children:xe(t)})}),i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(((T=(E=t.creative_input)==null?void 0:E.assets)==null?void 0:T.logo_url)||((I=t.product_logo)==null?void 0:I.url))&&i.jsx("img",{src:((P=(D=t.creative_input)==null?void 0:D.assets)==null?void 0:P.logo_url)||((O=t.product_logo)==null?void 0:O.url),alt:`${l.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:$=>{$.target.style.display="none"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:l.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(pe,{recommendationId:t.recommendation_id||"",admeshLink:t.click_url||t.admesh_link||((K=t.creative_input)==null?void 0:K.cta_url)||t.url,productId:t.product_id,trackingData:{title:l.title,matchScore:t.contextual_relevance_score,component:"product_card_cta"},children:i.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:[((B=t.creative_input)==null?void 0:B.cta_label)||"Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),i.jsx("div",{className:"mb-3",children:i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:l.description})}),((ee=t.creative_input)==null?void 0:ee.offer_summary)&&i.jsx("div",{className:"mb-3",children:i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 leading-relaxed italic",children:t.creative_input.offer_summary})}),((te=t.creative_input)==null?void 0:te.value_props)&&t.creative_input.value_props.length>0&&i.jsx("div",{className:"mb-3",children:i.jsx("ul",{className:"space-y-1.5",children:t.creative_input.value_props.slice(0,3).map(($,X)=>i.jsxs("li",{className:"flex items-start gap-2 text-xs text-gray-600 dark:text-gray-400",children:[i.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),i.jsx("span",{children:$})]},X))})}),i.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};_e.displayName="AdMeshProductCard";const Le=p.createContext(void 0);function Xe(){const t=p.useContext(Le);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function ue(){const t=Xe();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 It=(t,e)=>{if(!t)return"Get Started";let n="";const o=[/(?: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 d of o){const l=t.match(d);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 r=t.match(/to\s+set\s+up\s+([a-zA-Z0-9\s]+?)(?:\s+by|\s*[.,]|$)/i);return r&&r[1]?`Integrate ${r[1].trim().split(/\s+/).slice(0,2).join(" ")}`:"Integrate"},Ne=({recommendation:t,theme:e,className:n="",style:o={},sessionId:s,onLinkClick:r,onPasteToInput:d})=>{var R,_,x,M,C,A,E;const l=t.creative_input||{},u=l.bridge_headline||"",m=l.bridge_description||"",c=l.bridge_prompt||l.bridge_content||"",h=l.product_name||"",b=l.cta_label||"";if(!m&&!c)return null;const v=t.product_id||"",f=t.recommendation_id||"",{sdk:w,sessionId:y}=ue(),g=s||y,S=async T=>{if(T.preventDefault(),!!c){if(f&&g)try{const I=(w==null?void 0:w.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",D=await fetch(`${I}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:f,session_id:g,agent_id:t.agent_id,user_id:t.user_id||void 0,is_test:!1})});D.ok?a.log("[AdMesh Bridge] โœ… Engagement tracked successfully"):a.warn("[AdMesh Bridge] โš ๏ธ Failed to track engagement:",D.statusText)}catch(I){a.error("[AdMesh Bridge] โŒ Error tracking engagement:",I)}r&&r(t),d?d(c):typeof window<"u"&&window.__admesh_setMessage&&window.__admesh_setMessage(c)}},k=b||It(c,h),F=!!k;return i.jsx(ie,{productId:v,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",...o},children:i.jsxs("div",{"data-admesh-theme":(e==null?void 0:e.mode)||"light",children:[u&&i.jsx("div",{className:"admesh-bridge-headline",style:{marginBottom:m?"0.75rem":F?"1rem":"0",fontSize:((R=e==null?void 0:e.fontSize)==null?void 0:R.large)||"1rem",fontWeight:600,color:(e==null?void 0:e.textColor)||"inherit",lineHeight:"1.4"},children:u}),m&&i.jsx("div",{className:"admesh-bridge-description",style:{marginBottom:F||(_=t.creative_input)!=null&&_.offer_summary?"1rem":"0",lineHeight:"1.6",fontSize:((x=e==null?void 0:e.fontSize)==null?void 0:x.base)||"0.875rem",color:(e==null?void 0:e.textColor)||"inherit"},children:m}),((M=t.creative_input)==null?void 0:M.offer_summary)&&i.jsx("div",{className:"admesh-bridge-offer-summary",style:{marginBottom:F?"1rem":"0",lineHeight:"1.5",fontSize:((C=e==null?void 0:e.fontSize)==null?void 0:C.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}),F&&i.jsx("div",{style:{marginBottom:"0.75rem"},children:i.jsx("button",{onClick:S,className:"admesh-bridge-cta-button",style:{padding:"0.5rem 1rem",backgroundColor:"#000000",color:"#ffffff",fontSize:((A=e==null?void 0:e.fontSize)==null?void 0:A.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:T=>{T.currentTarget.style.backgroundColor="#1a1a1a",T.currentTarget.style.opacity="0.9"},onMouseLeave:T=>{T.currentTarget.style.backgroundColor="#000000",T.currentTarget.style.opacity="1"},children:k})}),i.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"0.5rem"},children:i.jsx("div",{className:"admesh-bridge-label",style:{fontSize:((E=e==null?void 0:e.fontSize)==null?void 0:E.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:"Sponsored"})})]})})},Je=({recommendations:t,summaryText:e,theme:n,className:o="",style:s={},onLinkClick:r,onPasteToInput:d,sessionId:l,response:u})=>{var v;const c=(t||(u==null?void 0:u.recommendations)||[]).filter(f=>f&&typeof f=="object"&&f.recommendation_id);if(!c||c.length===0)return a.log("[AdMesh Summary Layout] Empty or invalid recommendations array - not rendering anything"),null;let h=e||(u==null?void 0:u.tail_summary);if(!h&&c.length>0&&((v=c[0])!=null&&v.creative_input)){const f=c[0].creative_input;h=f.long_description||f.context_snippet||f.short_description||void 0}a.log(`[AdMesh Summary Layout] Rendering with ${c.length} valid recommendations`);const b=()=>{if(c.length>0){const f=c[0],w=(f==null?void 0:f.creative_input)||{},y=!!w.bridge_prompt||!!w.bridge_content,g=(f==null?void 0:f.format)||(w==null?void 0:w.format),S=f==null?void 0:f.preferred_format,k=g==="bridge"||S==="bridge";if(a.log("[AdMesh Summary Layout] ๐Ÿ” Checking format:",{hasBridgePrompt:y,bridgePrompt:w.bridge_prompt||w.bridge_content?(w.bridge_prompt||w.bridge_content||"").substring(0,50)+"...":void 0,format:g,preferredFormat:S,creativeInputKeys:Object.keys(w),recommendationKeys:Object.keys(f||{})}),y||k)return a.log("[AdMesh Summary Layout] ๐ŸŽฏ โœ… Rendering bridge format"),i.jsx(Ne,{recommendation:f,theme:n,sessionId:l,onLinkClick:r,onPasteToInput:d});a.log("[AdMesh Summary Layout] โš ๏ธ Bridge format NOT detected, falling back to other formats")}return h?i.jsx(we,{summaryText:h,recommendations:c,theme:n,onLinkClick:r,sessionId:l}):c.length>0&&c[0]?i.jsx("div",{className:"fallback-citation",children:i.jsx(_e,{recommendation:c[0],theme:n,sessionId:l})}):null};return i.jsx("div",{className:`admesh-summary-layout ${o}`,style:{fontFamily:(n==null?void 0:n.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:b()})},et=({recommendations:t,summaryText:e,theme:n,className:o,style:s,onLinkClick:r,onPasteToInput:d,sessionId:l,response:u})=>{const m=t||(u==null?void 0:u.recommendations)||[],c=e||(u==null?void 0:u.tail_summary),h=m.filter(b=>b&&typeof b=="object"&&b.recommendation_id);return!h||h.length===0?(a.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null):i.jsx(Je,{recommendations:h,summaryText:c,theme:n,className:o,style:s,onLinkClick:r,onPasteToInput:d,sessionId:l})},jt=({className:t,size:e=20})=>i.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:[i.jsx("path",{d:"M5 12h14"}),i.jsx("path",{d:"M12 5v14"})]}),ke=({recommendation:t,theme:e,sdk:n,sessionId:o,onExecuteQuery:s})=>{const r=t.followup_query,d=t.followup_engagement_url,l=t.followup_exposure_url,u=t.recommendation_id;if(!r||!d||!l)return a.log("[AdMeshFollowup] Missing followup_query, followup_engagement_url, or followup_exposure_url - not rendering"),null;const m=async()=>{try{d&&u&&(a.log("[AdMeshFollowup] ๐ŸŽฏ Firing follow-up engagement tracking"),await n.fireFollowupEngagement(d,u,o)),s&&r?(a.log(`[AdMeshFollowup] ๐Ÿ” Executing query: ${r}`),await s(r)):a.warn("[AdMeshFollowup] โš ๏ธ onExecuteQuery not provided - cannot execute query")}catch(c){a.error("[AdMeshFollowup] โŒ Error handling follow-up click:",c)}};return e!=null&&e.mode,i.jsx(ie,{productId:t.product_id||"",recommendationId:u||"",exposureUrl:l,sessionId:o,className:"admesh-followup-container",style:{width:"100%"},children:i.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[i.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),i.jsxs("div",{onClick:m,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&m()},"aria-label":`Sponsored follow-up: ${r}`,children:[i.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:r}),i.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),i.jsx(jt,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})};class tt{constructor(e){Z(this,"firedExposures",new Set);Z(this,"debug",!1);Z(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,n,o){const s=`${o}_${n}`;if(this.firedExposures.has(s)){this.debug&&a.log("[Tracker] Exposure already fired");return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&a.warn("[Tracker] Failed to fire exposure")}),this.debug&&a.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&a.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,n,o,s){const r=`${o}_${n}`;if(this.firedExposures.has(r)){this.debug&&a.log("[Tracker] MRC exposure already fired");return}return new Promise(d=>{let l=null,u=null;const m=new IntersectionObserver(b=>{b.forEach(v=>{v.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?l===null&&(l=Date.now(),this.debug&&a.log("[Tracker] Ad reached MRC visibility threshold"),u=setTimeout(()=>{this.fireExposure(e,n,o),m.disconnect(),d()},this.mrcThreshold.minimumDurationMs)):l!==null&&(u&&(clearTimeout(u),u=null),l=null,this.debug&&a.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});m.observe(s);const h=setTimeout(()=>{m.disconnect(),u&&clearTimeout(u),d()},3e4);s.__admeshTrackerCleanup=()=>{m.disconnect(),u&&clearTimeout(u),clearTimeout(h)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,n,o){this.fireExposure(e,n,o)}fireFollowupEngagement(e,n,o){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:o})}).catch(s=>{this.debug&&a.warn("[Tracker] Failed to fire followup engagement (non-critical):",s)}).then(()=>{})}}class rt{constructor(){Z(this,"roots",new Map)}async render(e){var n;try{a.log("[AdMeshRenderer] ๐ŸŽจ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){a.log("[AdMeshRenderer] โš ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw a.error("[AdMeshRenderer] โŒ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);a.log("[AdMeshRenderer] โœ… Container ready");const r=this.roots.get(e.containerId);r&&(a.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing root"),r.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const d=Be.createRoot(s),l=((n=o[0])==null?void 0:n.tail_summary)||"";a.log("[AdMeshRenderer] ๐Ÿ“Š Rendering recommendations");const u=e.onPasteToInput||(typeof window<"u"?window.__admesh_onPasteToInput:void 0);if(d.render(i.jsx(et,{recommendations:o,summaryText:l,theme:e.theme,sessionId:e.sessionId,onPasteToInput:u})),s.style.display="block",a.log("[AdMeshRenderer] โœ… Recommendations rendered successfully"),this.roots.set(e.containerId,d),e.followups_container_id){const m=o[0];m!=null&&m.followup_query&&(m!=null&&m.followup_engagement_url)&&await this.renderFollowup({containerId:e.followups_container_id,recommendation:m,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,onExecuteQuery:e.onExecuteQuery})}}catch(o){throw a.error("[AdMeshRenderer] โŒ Error rendering recommendations"),o}}async renderFollowup(e){try{a.log(`[AdMeshRenderer] ๐ŸŽฏ Rendering follow-up in container: ${e.containerId}`);const n=document.getElementById(e.containerId);if(!n){a.warn(`[AdMeshRenderer] โš ๏ธ Followups container not found: ${e.containerId}`);return}const o=this.roots.get(e.containerId);o&&(a.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing followup root"),o.unmount(),this.roots.delete(e.containerId)),n.innerHTML="";const s=Be.createRoot(n);s.render(i.jsx(ke,{recommendation:e.recommendation,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,onExecuteQuery:e.onExecuteQuery})),n.style.display="block",a.log("[AdMeshRenderer] โœ… Follow-up rendered successfully"),this.roots.set(e.containerId,s)}catch{a.error("[AdMeshRenderer] โŒ Error rendering follow-up")}}unmount(e){const n=this.roots.get(e);if(n){n.unmount(),this.roots.delete(e);const o=document.getElementById(e);o&&(o.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class nt{constructor(e){Z(this,"config");Z(this,"apiBaseUrl");Z(this,"renderer",null);Z(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"}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(),o=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${n}_${o}`:`msg_${n}_${o}`}getRenderer(){return this.renderer||(this.renderer=new rt),this.renderer}getTracker(){return this.tracker||(this.tracker=new tt({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}),o=this.convertAIPResponseToRecommendation(n),s={session_id:n.session_id,message_id:`msg_${n.recommendation_id}`,recommendations:[o]},r=this.getRenderer(),d=this.getTracker();await r.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:d,sessionId:e.session_id,onPasteToInput:e.onPasteToInput,onExecuteQuery:e.onExecuteQuery})}catch(n){throw a.error("[AdMeshSDK] Error showing recommendations"),n}}async fetchRecommendationFromAIPContext(e){var h,b,v;const n=`${this.apiBaseUrl}/aip/context`;if(a.log("[AdMeshSDK] ๐Ÿ“ฅ fetchRecommendationFromAIPContext called"),!e.sessionId||e.sessionId.trim()===""){const f=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw a.error("[AdMeshSDK] โŒ sessionId not provided by platform - cannot process request"),f}const o=e.messageId;if(!o||o.trim()===""){const f=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw a.error("[AdMeshSDK] โŒ messageId not provided by platform - cannot process request"),f}const s=e.messages?e.messages.length:0,r=(typeof window<"u"&&window.navigator,"web"),d=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",l={spec_version:"1.0.0",message_id:o,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:r,form_factor:d},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())&&a.warn("[AdMeshSDK] โš ๏ธ Warning: Sending request with empty query_text");const u=JSON.stringify(l);a.log("[AdMeshSDK] ๐Ÿ“ค Sending request to /aip/context");const m=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:u});if(!m.ok){const w=(await m.json().catch(()=>({}))).detail||`HTTP ${m.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${w}`)}const c=await m.json();return a.log("[AdMeshSDK] ๐Ÿ“ฅ Raw response from /aip/context:",{hasCreative:!!c.creative,creativeFormat:(h=c.creative)==null?void 0:h.format,creativeBridgeContent:(b=c.creative)!=null&&b.bridge_content?c.creative.bridge_content.substring(0,50)+"...":void 0,hasWinningBid:!!c.winning_bid,winningBidPreferredFormat:(v=c.winning_bid)==null?void 0:v.preferred_format,topLevelKeys:Object.keys(c)}),c}convertAIPResponseToRecommendation(e){var k,F,R,_,x,M,C;const n=e;let o=e.creative_input||{};const s=n.creative||{},r=s.format||n.format||((k=n.winning_bid)==null?void 0:k.preferred_format),d=s.headline,l=s.bridge_headline,u=s.bridge_description,m=s.bridge_prompt||s.bridge_content,c=m||o.bridge_prompt||o.bridge_content,h=s.cta_label,b=h||o.cta_label,v=l||o.bridge_headline,f=u||o.bridge_description;a.log("[AdMeshSDK] ๐Ÿ” Extracting from response:",{creativeObject:s,creativeFormat:s.format,creativeBridgeHeadline:l,creativeBridgeDescription:u?String(u).substring(0,50)+"...":void 0,creativeBridgePrompt:m?String(m).substring(0,50)+"...":void 0,creativeCtaLabel:h,extractedFormat:r,extractedBridgeHeadline:v,extractedBridgeDescription:f?String(f).substring(0,50)+"...":void 0,extractedBridgePrompt:c?String(c).substring(0,50)+"...":void 0,extractedCtaLabel:b,creativeInputHasBridgeHeadline:!!o.bridge_headline,creativeInputHasBridgeDescription:!!o.bridge_description,creativeInputHasBridgePrompt:!!o.bridge_prompt,creativeInputHasBridgeContent:!!o.bridge_content,creativeInputHasCtaLabel:!!o.cta_label});const w=o.assets||{};o={...o,assets:w,...d&&{headline:d},...v&&{bridge_headline:v},...f&&{bridge_description:f},...c&&{bridge_prompt:c},...c&&{bridge_content:c},...b&&{cta_label:b},...r&&{format:r}};const y=e.recommendation_id||n.recommendation_id||n.bid_id||"",g=e.click_url||e.admesh_link||"",S={...e,recommendation_id:y,admesh_link:g||e.click_url||"",ad_id:void 0,bid_id:void 0,creative_input:o,product_title:e.title,tail_summary:o.long_description||"",product_summary:o.short_description||"",weave_summary:o.context_snippet||"",product_logo:(F=o.assets)!=null&&F.logo_url?{url:o.assets.logo_url}:void 0,categories:o.categories||[]};return delete S.ad_id,delete S.bid_id,r&&(S.format=r),a.log("[AdMeshSDK] ๐Ÿ”„ Converted recommendation:",{hasFormat:!!r,format:r,hasBridgeHeadline:!!v,bridgeHeadline:v,hasBridgeDescription:!!f,bridgeDescriptionPreview:f?String(f).substring(0,50)+"...":void 0,hasBridgePrompt:!!c,hasCtaLabel:!!b,ctaLabel:b,bridgeHeadlineInCreativeInput:!!((R=S.creative_input)!=null&&R.bridge_headline),bridgeDescriptionInCreativeInput:!!((_=S.creative_input)!=null&&_.bridge_description),bridgePromptInCreativeInput:!!((x=S.creative_input)!=null&&x.bridge_prompt),bridgeContentInCreativeInput:!!((M=S.creative_input)!=null&&M.bridge_content),ctaLabelInCreativeInput:!!((C=S.creative_input)!=null&&C.cta_label),bridgePromptPreview:c?String(c).substring(0,50)+"...":void 0,creativeInputKeys:Object.keys(S.creative_input||{}),recommendationFormat:S.format}),S}fireFollowupExposure(e,n,o){this.getTracker().fireFollowupExposure(e,n,o)}async fireFollowupEngagement(e,n,o){return this.getTracker().fireFollowupEngagement(e,n,o)}}class Pe{constructor(e={}){Z(this,"autoAddLabels");Z(this,"fireExposurePixels");Z(this,"labelStyle");Z(this,"processedLinks",new Set);Z(this,"mutationObserver",null);var n,o,s,r;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((n=e.labelStyle)==null?void 0:n.fontSize)||"0.75em",fontWeight:((o=e.labelStyle)==null?void 0:o.fontWeight)||"bold",color:((s=e.labelStyle)==null?void 0:s.color)||"#666",marginLeft:((r=e.labelStyle)==null?void 0:r.marginLeft)||"2px"}}getLinksToProcess(e){const o=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return o.length>0?Array.from(o):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,n,o){if(!e)return[];const s=[];if(n.length>0){const r=this.getLinksToProcess(e),d=new Map(n.filter(u=>u.click_url).map(u=>[u.click_url,u])),l=new Map;n.forEach(u=>{var c;const m=u.redirect_url||u.url||((c=u.creative_input)==null?void 0:c.cta_url);if(m&&typeof m=="string"){const h=m.trim().replace(/\/$/,"");l.set(h,u),l.set(`${h}/`,u)}}),r.forEach(u=>{const m=u.getAttribute("href")||"",c=`${m}`;if(this.processedLinks.has(c))return;let h=d.get(m),b=m;if(!h){const v=m.trim().replace(/\/$/,"");h=l.get(v)||l.get(`${v}/`),h&&h.click_url&&(a.log("[WeaveResponseProcessor] ๐Ÿ”„ Found brand URL match, replacing with click_url:",m),u.setAttribute("href",h.click_url),b=h.click_url)}if(h){this.processedLinks.add(c),u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer");const v={element:u,href:b,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:{recommendation_id:h.recommendation_id||"",click_url:h.click_url,exposure_url:h.exposure_url}};this.autoAddLabels&&!v.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to matched recommendation link:",b),this.addAdLabel(u),v.hasAdLabel=!0):this.autoAddLabels?v.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&h.exposure_url&&o&&v.matchedRecommendation&&o({exposureUrl:h.exposure_url,recommendationId:v.matchedRecommendation.recommendation_id,linkElement:u}),s.push(v)}})}else Array.from(e.querySelectorAll("a")).forEach(d=>{const l=d.getAttribute("href")||"",u=`${l}`;if(this.processedLinks.has(u))return;if(this.isAdMeshLink(l)){this.processedLinks.add(u);const c={element:d,href:l,text:d.textContent||"",hasAdLabel:this.hasAdLabel(d),matchedRecommendation:void 0};if(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to pattern-matched AdMesh link:",l),this.addAdLabel(d),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&o){const h=this.convertClickUrlToExposureUrl(l);o({exposureUrl:h,recommendationId:this.extractRecommendationIdFromUrl(l),linkElement:d})}s.push(c)}});return s}hasAdLabel(e){var d,l,u;if((e.textContent||"").includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link text contains [Ad] label"),!0;const o=e.querySelectorAll("sub, span");for(const m of Array.from(o))if((d=m.textContent)!=null&&d.includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link has [Ad] label as child element"),!0;let s=e.previousSibling;for(;s&&s.nodeType===Node.TEXT_NODE;){const m=s.textContent||"";if(m.trim()===""){s=s.previousSibling;continue}if(m.includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous text sibling"),!0;break}if(s&&s.nodeType===Node.ELEMENT_NODE){const m=s,c=m.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((l=m.textContent)!=null&&l.includes("[Ad]")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in previous element sibling:",c),!0}let r=e.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const m=r.textContent||"";if(m.trim()===""){r=r.nextSibling;continue}if(m.includes("[Ad]"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next text sibling"),!0;break}if(r&&r.nodeType===Node.ELEMENT_NODE){const m=r,c=m.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((u=m.textContent)!=null&&u.includes("[Ad]")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label in next element sibling:",c),!0}return a.log("[WeaveResponseProcessor] โ„น๏ธ No existing [Ad] label found"),!1}addAdLabel(e){if(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Attempting to add [Ad] label to link:",e.href),!e.isConnected){a.warn("[WeaveResponseProcessor] โš ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has [Ad] label, skipping");return}const n=e.parentNode;if(!n){a.error("[WeaveResponseProcessor] โŒ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const o=document.createElement("sub");o.textContent="[Ad]",o.style.fontSize=this.labelStyle.fontSize,o.style.fontWeight=this.labelStyle.fontWeight,o.style.color=this.labelStyle.color,o.style.marginLeft=this.labelStyle.marginLeft,o.style.cursor="pointer",o.style.borderBottom=`1px dotted ${this.labelStyle.color}`,o.style.whiteSpace="nowrap",o.title="Why this ad? This is a sponsored recommendation based on your search query.";let s=!1;o.addEventListener("mouseenter",()=>{o.style.opacity="0.7"}),o.addEventListener("mouseleave",()=>{o.style.opacity="1",s&&(s=!1)}),o.addEventListener("click",d=>{d.stopPropagation(),s=!s,s?(o.style.textDecoration="underline",o.style.opacity="0.7"):(o.style.textDecoration="none",o.style.opacity="1")});const r=d=>{s&&d.target!==o&&(s=!1,o.style.textDecoration="none",o.style.opacity="1")};document.addEventListener("click",r);try{const d=e.nextSibling;d?(n.insertBefore(o,d),a.log("[WeaveResponseProcessor] โœ… [Ad] label inserted before next sibling")):(n.appendChild(o),a.log("[WeaveResponseProcessor] โœ… [Ad] label appended to parent (no next sibling)")),o.isConnected&&o.parentNode===n?a.log("[WeaveResponseProcessor] โœ… [Ad] label successfully added to link:",e.href):a.error("[WeaveResponseProcessor] โŒ [Ad] label insertion failed - label not in DOM")}catch(d){a.error("[WeaveResponseProcessor] โŒ Error inserting [Ad] label:",d)}}removeLeftAdLabel(e){var o,s,r;let n=e.previousSibling;for(;n&&n.nodeType===Node.TEXT_NODE;){const d=n.textContent||"";if(d.trim()===""){n=n.previousSibling;continue}if(d.includes("[Ad]")){(o=n.parentNode)==null||o.removeChild(n);return}break}if(n&&n.nodeType===Node.ELEMENT_NODE){const d=n;(d.tagName==="SUB"||d.tagName==="SPAN")&&((s=d.textContent)!=null&&s.includes("[Ad]"))&&((r=d.parentNode)==null||r.removeChild(d))}}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`,r=new URLSearchParams(n.search);return r.has("cpx")||r.set("cpx","0"),`${s}?${r.toString()}`}catch{return a.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,n,o){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,n,o)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}const Lt=({apiKey:t,sessionId:e,theme:n,apiBaseUrl:o,language:s,geo_country:r,userId:d,model:l,messages:u,children:m})=>{const c=p.useRef(null),[h,b]=p.useState(new Set);p.useEffect(()=>{if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");return}},[e]),p.useEffect(()=>{if(!t){a.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ Cannot initialize SDK: sessionId is required and must be provided by the platform");return}try{c.current=new nt({apiKey:t,theme:n,apiBaseUrl:o}),a.log("[AdMeshProvider] โœ… AdMesh SDK initialized"),o&&a.log("[AdMeshProvider] ๐Ÿ“ Using custom API base URL")}catch{a.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK")}return()=>{a.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,n,o]);const v={sdk:c.current,apiKey:t,sessionId:e,theme:n,language:s,geo_country:r,userId:d,model:l,messages:u,processedMessageIds:h,markMessageAsProcessed:f=>{b(w=>{const y=new Set(w);return y.add(f),y})},isMessageProcessed:f=>h.has(f)};return i.jsx(Le.Provider,{value:v,children:m})},Nt=({onRecommendationsShown:t,onError:e,messageId:n,query:o,onPasteToInput:s,followups_container_id:r,onExecuteQuery:d,onFollowupDetected:l,isContainerReady:u})=>{const{sdk:m,sessionId:c,language:h,geo_country:b,userId:v,model:f,messages:w,theme:y}=ue(),[g,S]=p.useState(null),[k,F]=p.useState(null),[R,_]=p.useState(!0),[x,M]=p.useState(null),C=p.useRef(null),A=p.useRef(!1),E=p.useRef(t),T=p.useRef(e),I=p.useRef(l);p.useEffect(()=>{E.current=t,T.current=e,I.current=l},[t,e,l]);const D=N=>{var de,be,De,We,$e;const G=N;let j=N.creative_input||{};const z=G.creative||{},W=z.format||G.format||((de=G.winning_bid)==null?void 0:de.preferred_format)||((be=N.creative_input)==null?void 0:be.preferred_format),Q=z.headline,U=z.bridge_headline,V=z.bridge_description,q=z.bridge_prompt||z.bridge_content||j.bridge_prompt||j.bridge_content,Y=z.cta_label||j.cta_label,ae=U||j.bridge_headline,ne=V||j.bridge_description,he=j.assets||{};j={...j,assets:he,...Q&&{headline:Q},...ae&&{bridge_headline:ae},...ne&&{bridge_description:ne},...q&&{bridge_prompt:q},...q&&{bridge_content:q},...Y&&{cta_label:Y},...W&&{format:W}};const ge=N.recommendation_id||N.bid_id||"",L=N.click_url||N.admesh_link||"",oe={...N,recommendation_id:ge,admesh_link:L||N.click_url||"",creative_input:j,ad_id:void 0,bid_id:void 0,...W&&{format:W}};delete oe.ad_id,delete oe.bid_id;const Se=N.followup_query,Me=((De=N.creative_input)==null?void 0:De.followup_query)||(j==null?void 0:j.followup_query),se=Se||Me,Ce=N.followup_engagement_url,Ee=((We=N.creative_input)==null?void 0:We.followup_engagement_url)||(j==null?void 0:j.followup_engagement_url),le=Ce||Ee,Te=N.followup_exposure_url,Re=(($e=N.creative_input)==null?void 0:$e.followup_exposure_url)||(j==null?void 0:j.followup_exposure_url),fe=Te||Re;return se&&(oe.followup_query=se,a.debug("[AdMeshRecommendations] โœ… Extracted followup_query:",se.substring(0,50)+"...")),le&&(oe.followup_engagement_url=le,a.debug("[AdMeshRecommendations] โœ… Extracted followup_engagement_url")),fe&&(oe.followup_exposure_url=fe,a.debug("[AdMeshRecommendations] โœ… Extracted followup_exposure_url")),oe};p.useEffect(()=>{C.current!==n&&(C.current=null,S(null),F(null))},[n]);const[P,O]=p.useState(null);p.useEffect(()=>{if(!(g!=null&&g.followup_query)||!r){O(null);return}if(u===!1){a.debug("[AdMeshRecommendations] โณ Waiting for container signal...");return}let N=0;const G=5,j=()=>{const W=document.getElementById(r);return W?(a.debug(`[AdMeshRecommendations] โœ… Found followup container: ${r} `),O(W),!0):!1};if(j())return;const z=setInterval(()=>{N++,(j()||N>=G)&&(clearInterval(z),N>=G&&a.warn(`[AdMeshRecommendations] โš ๏ธ Followup container not found after signal: ${r} `))},100);return()=>clearInterval(z)},[g,r,u]),p.useEffect(()=>{if(!n||!o||o.trim()===""){a.log("[AdMeshRecommendations] โŒ Validation failed - missing required parameters"),_(!1);return}if(!(m!=null&&m.fetchRecommendationFromAIPContext)){a.log("[AdMeshRecommendations] SDK fetchRecommendationFromAIPContext not available"),_(!1);return}if(C.current===n){a.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(A.current){a.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}a.log("[AdMeshRecommendations] ๐Ÿ“ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var G,j,z,W,Q;try{A.current=!0,_(!0),M(null);const U=await m.fetchRecommendationFromAIPContext({query:o.trim(),sessionId:c,messageId:n,language:h,geo_country:b,userId:v,model:f,...w&&w.length>0&&{messages:w}}),V=D(U),J=U.followup_query||V.followup_query,q=U.followup_engagement_url||V.followup_engagement_url,H=V.recommendation_id||"";J&&(a.debug("[AdMeshRecommendations] โœ… Followup query detected:",J),a.debug("[AdMeshRecommendations] โœ… Followup engagement URL:",q?"present":"missing"),a.debug("[AdMeshRecommendations] โœ… Recommendation ID:",H||"missing"),q||a.debug("[AdMeshRecommendations] โš ๏ธ Followup engagement URL is missing (optional)"),H||a.debug("[AdMeshRecommendations] โš ๏ธ Recommendation ID is missing (optional)"),r?a.debug("[AdMeshRecommendations] โœ… Using SDK-managed portal rendering (followups_container_id provided)"):I.current?(a.debug("[AdMeshRecommendations] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),I.current(J,q||"",H||"")):a.debug("[AdMeshRecommendations] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)")),S(V);const Y=U,ae=((G=Y.creative)==null?void 0:G.preferred_format)||((j=Y.winning_bid)==null?void 0:j.preferred_format)||Y.preferred_format||((z=U.creative_input)==null?void 0:z.preferred_format);let ne;ae?ne=ae==="weave"?"tail":ae:ne="tail",F(ne),C.current=n,a.log("[AdMeshRecommendations] ๐Ÿ“Š Format detected:",ne),_(!1),A.current=!1,(W=E.current)==null||W.call(E,n)}catch(U){const V=U instanceof Error?U:new Error(String(U));V.message.includes("Failed to fetch")||V.message.includes("NetworkError")?a.warn(`[AdMeshRecommendations] โš ๏ธ Network error fetching recommendations(non - critical): ${V.message} `):a.error(`[AdMeshRecommendations] โŒ Error fetching recommendations: ${V.message} `),M(V),_(!1),A.current=!1,(Q=T.current)==null||Q.call(T,V)}})()},[m,c,n,o,h,b,v,f]);const K=()=>P&&(g!=null&&g.followup_query)&&m?(a.debug(`[AdMeshRecommendations] ๐ŸŒ€ Rendering followup portal into: ${r} `),Ge.createPortal(i.jsx(ke,{recommendation:g,theme:y,sdk:m,sessionId:c,onExecuteQuery:d}),P)):(a.debug(`[AdMeshRecommendations] โŒ Skipping followup portal.Container: ${!!P}, Query: ${!!(g!=null&&g.followup_query)}, SDK: ${!!m} `),null);if(!n||!o||o.trim()===""||R||x||!g||!k)return null;const B=g.creative_input||{},ee=!!B.bridge_prompt||!!B.bridge_content,te=(g==null?void 0:g.format)||(B==null?void 0:B.format),$=g==null?void 0:g.preferred_format;if(ee||(te==="bridge"||$==="bridge"||k==="bridge"))return i.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[i.jsx(Ne,{recommendation:g,theme:y,sessionId:c,onPasteToInput:s}),K()]});if(k==="product"||k==="product_card")return i.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[i.jsx(_e,{recommendation:g,theme:y,sessionId:c}),K()]});const re=B.long_description||B.context_snippet||B.short_description||"";return i.jsxs("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:[i.jsx(we,{summaryText:re,recommendations:[g],theme:y,sessionId:c}),K()]})},ot=({format:t="tail",onError:e,messageId:n,query:o,fallback:s,previousRecommendations:r})=>{const{sdk:d,sessionId:l,theme:u}=ue(),m=p.useRef(null),[c,h]=p.useState("");return p.useEffect(()=>{n&&h(`admesh-weave-fallback-${n}`)},[n]),a.log("[WeaveFallbackRecommendations] ๐ŸŽจ Component render"),p.useEffect(()=>{if(a.log("[WeaveFallbackRecommendations] ๐Ÿ”„ useEffect triggered",{fallback:s,hasPreviousRecommendations:r&&r.length>0,previousRecommendationsCount:(r==null?void 0:r.length)||0}),!s){a.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(a.log("[WeaveFallbackRecommendations] โœ… fallback is TRUE, proceeding with recommendations"),!n||!o||o.trim()===""){a.log("[WeaveFallbackRecommendations] โŒ Validation failed - returning early");return}if(a.log("[WeaveFallbackRecommendations] โœ… Validation passed"),!d||!c){a.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const b=r&&r.length>0;a.log("[WeaveFallbackRecommendations] ๐Ÿ“Š Checking previous recommendations:",{hasPreviousRecs:b,count:(r==null?void 0:r.length)||0,fallback:s,messageId:n}),b?(a.log(`[WeaveFallbackRecommendations] โ™ป๏ธ Reusing ${r.length} previous recommendation(s), skipping API call`),(async()=>{var f,w,y,g,S,k,F,R,_;try{const x=r[0];if(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ฆ Processing AIP response:",{hasAipResponse:!!x,recommendationId:x==null?void 0:x.recommendation_id,hasCreativeInput:!!(x!=null&&x.creative_input)}),x&&process.env.NODE_ENV==="development"&&a.log("[WeaveFallbackRecommendations] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:x.recommendation_id,product_id:x.product_id,brand_id:x.brand_id,title:x.title,click_url:x.click_url,contextual_relevance_score:x.contextual_relevance_score,preferred_format:(f=x.creative_input)==null?void 0:f.preferred_format,resolved_format:(w=x.format_resolution)==null?void 0:w.resolved_format,creative_input:{product_name:(y=x.creative_input)==null?void 0:y.product_name,brand_name:(g=x.creative_input)==null?void 0:g.brand_name,cta_url:(S=x.creative_input)==null?void 0:S.cta_url,short_description:(k=x.creative_input)==null?void 0:k.short_description,allowed_formats:(F=x.creative_input)==null?void 0:F.allowed_formats,fallback_formats:(R=x.creative_input)==null?void 0:R.fallback_formats},format_resolution:x.format_resolution,full_response:x}),!x){a.warn("[WeaveFallbackRecommendations] โš ๏ธ Previous recommendation is empty, falling back to API call"),await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:n});return}const M=d,C=M.convertAIPResponseToRecommendation,A=M.getRenderer,E=M.getTracker,T=(_=M.config)==null?void 0:_.theme;if(C&&A&&E){const I=C.call(d,x);if(!I){a.warn("[WeaveFallbackRecommendations] โš ๏ธ Conversion returned empty, falling back to API call"),await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:n});return}const D={session_id:x.session_id||l,message_id:`msg_${x.recommendation_id||n}`,recommendations:[I]},P=A.call(d),O=E.call(d);await P.render({containerId:c,response:D,theme:u||T,tracker:O,sessionId:l}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations rendered from previous response (no API call)")}else a.warn("[WeaveFallbackRecommendations] โš ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:n})}catch(x){const M=x instanceof Error?x:new Error(String(x));a.error(`[WeaveFallbackRecommendations] โŒ Error rendering previous recommendations: ${M.message}`);try{await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:n})}catch{e==null||e(M)}}})()):(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(d!=null&&d.showRecommendations)){a.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await d.showRecommendations({query:o.trim(),containerId:c,session_id:l,messageId:n}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations displayed successfully")}catch(f){const w=f instanceof Error?f:new Error(String(f));a.log(`[WeaveFallbackRecommendations] โŒ Error: ${w.message}`),e==null||e(w)}})())},[d,l,c,t,n,o,s,e,r,u]),!s||!n||!o||o.trim()===""?null:i.jsx("div",{ref:m,id:c,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},at=p.createContext(void 0),Pt=({children:t,shouldRenderFallback:e,messageId:n,sessionId:o,query:s})=>i.jsx(at.Provider,{value:{shouldRenderFallback:e,messageId:n,sessionId:o,query:s},children:t}),Dt=()=>p.useContext(at),Wt=({recommendations:t,title:e="Product Recommendations",showTitle:n=!0,className:o="",cardClassName:s="",onProductClick:r,maxCards:d=10,cardWidth:l="md",theme:u="auto",borderRadius:m="md",shadow:c="sm"})=>{if(!t||t.length===0)return a.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const h=t.slice(0,d),b=()=>{switch(l){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},v=()=>{switch(m){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},f=()=>{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"}},w=()=>u==="dark"?"bg-gray-900 text-white":u==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",y=g=>{var S;if(r)r(g);else{const k=g.click_url||g.admesh_link||g.url||((S=g.creative_input)==null?void 0:S.cta_url);k&&window.open(k,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:i.jsxs("div",{className:me("w-full",o),children:[n&&i.jsxs("div",{className:"mb-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),i.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),i.jsxs("div",{className:"relative",children:[h.length===0?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):i.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:h.map(g=>{var R,_,x,M,C,A,E,T,I,D,P,O,K,B,ee,te,$,X,re,N,G;const S=g.recommendation_id||g.product_id||g.id||"",k=g.recommendation_id||g.product_id||"",F=g.product_id||"";return i.jsx(ie,{recommendationId:k,productId:F,className:me(b(),v(),f(),w(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",s),onClick:()=>y(g),children:i.jsxs("div",{children:[i.jsx("div",{className:"relative aspect-square w-full overflow-hidden",children:(_=(R=g.creative_input)==null?void 0:R.assets)!=null&&_.logo_url||(C=(M=(x=g.creative_input)==null?void 0:x.assets)==null?void 0:M.image_urls)!=null&&C[0]||(A=g.product_logo)!=null&&A.url?i.jsx("img",{src:((I=(T=(E=g.creative_input)==null?void 0:E.assets)==null?void 0:T.image_urls)==null?void 0:I[0])||((P=(D=g.creative_input)==null?void 0:D.assets)==null?void 0:P.logo_url)||((O=g.product_logo)==null?void 0:O.url),alt:((K=g.creative_input)==null?void 0:K.product_name)||g.title||g.product_title||"Product",className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy",onError:j=>{j.target.style.display="none"}}):i.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:i.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.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"})})})}),i.jsxs("div",{className:"p-3",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:((B=g.creative_input)==null?void 0:B.product_name)||g.title||g.product_title||""}),(((ee=g.creative_input)==null?void 0:ee.short_description)||((te=g.creative_input)==null?void 0:te.context_snippet)||g.weave_summary)&&i.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 line-clamp-2 mb-2",children:(($=g.creative_input)==null?void 0:$.short_description)||((X=g.creative_input)==null?void 0:X.context_snippet)||g.weave_summary}),((re=g.creative_input)==null?void 0:re.offer_summary)&&i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-500 line-clamp-2 mb-2 italic",children:g.creative_input.offer_summary}),((N=g.creative_input)==null?void 0:N.value_props)&&g.creative_input.value_props.length>0&&i.jsx("div",{className:"mb-2",children:i.jsx("ul",{className:"space-y-1",children:g.creative_input.value_props.slice(0,2).map((j,z)=>i.jsxs("li",{className:"flex items-start gap-1.5 text-xs text-gray-600 dark:text-gray-400",children:[i.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),i.jsx("span",{className:"line-clamp-1",children:j})]},z))})}),(!((G=g.creative_input)!=null&&G.value_props)||g.creative_input.value_props.length===0)&&g.categories&&g.categories.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:g.categories.slice(0,2).map((j,z)=>i.jsx("span",{className:"text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-1 rounded",children:j},z))}),g.trust_score!==void 0&&i.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Trust Score: ",(g.trust_score*100).toFixed(0),"%"]})]})]})},S)})}),h.length>0&&i.jsxs(i.Fragment,{children:[i.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:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),i.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:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),i.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),i.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),i.jsx("style",{dangerouslySetInnerHTML:{__html:`
974
974
  .scrollbar-hide {
975
975
  -ms-overflow-style: none;
976
976
  scrollbar-width: none;
@@ -984,5 +984,5 @@
984
984
  -webkit-box-orient: vertical;
985
985
  overflow: hidden;
986
986
  }
987
- `}})]})},at=({recommendation:t,theme:e,variation:r="default",expandable:o=!1,className:s,style:n})=>{var p,c,g,b,x,f;if(!t)return a.log("[AdMesh Inline Card] No recommendation provided - not rendering"),null;const l={title:t.product_title||t.title,description:t.weave_summary||t.reason||"",ctaText:t.product_title||t.title},u=ce("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":o&&(r==="question"||r==="statement")},s);return i.jsx("div",{className:u,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((c=(p=e==null?void 0:e.components)==null?void 0:p.inlineRecommendation)==null?void 0:c.width)||"100%",...(g=e==null?void 0:e.components)==null?void 0:g.productCard,...n},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",children:[i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((b=t.product_logo)==null?void 0:b.url)&&i.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:y=>{y.target.style.display="none"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:l.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(he,{recommendationId:t.recommendation_id||"",admeshLink:t.click_url||t.admesh_link||((x=t.creative_input)==null?void 0:x.cta_url)||t.url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"inline_card_cta"},children:i.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[r==="question"?"Try":"Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),l.description&&i.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:l.description}),((f=t.creative_input)==null?void 0:f.offer_summary)&&i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2 line-clamp-2 italic",children:t.creative_input.offer_summary}),i.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};at.displayName="AdMeshInlineCard";const Dt={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Wt={"Top Match":"โ˜…","Free Tier":"โ—†","AI Powered":"โ—‰",Popular:"โ–ฒ",New:"โ—","Trial Available":"โ—ˆ"},st=({type:t,variant:e,size:r="md",className:o,style:s})=>{const n=e||Dt[t]||"secondary",d=Wt[t],l=ce("admesh-component","admesh-badge",`admesh-badge--${n}`,`admesh-badge--${r}`,o);return i.jsxs("span",{className:l,style:s,children:[d&&i.jsx("span",{className:"admesh-badge__icon",children:d}),i.jsx("span",{className:"admesh-badge__text",children:t})]})};st.displayName="AdMeshBadge";const _e="admesh:streamingStart",ke="admesh:streamingComplete";function $t(t,e){const r={messageId:t,sessionId:e,timestamp:Date.now()},o=new CustomEvent(_e,{detail:r});window.dispatchEvent(o),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function zt(t,e,r){const o={messageId:t,sessionId:e,timestamp:Date.now(),metadata:r},s=new CustomEvent(ke,{detail:o});window.dispatchEvent(s),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:r})}function Bt(t,e,r){const o=s=>{const n=s;n.detail.messageId===t&&n.detail.sessionId===e&&(a.log("[StreamingEvents] ๐Ÿ“จ Received streamingStart event"),r(n.detail))};return window.addEventListener(_e,o),()=>{window.removeEventListener(_e,o)}}function it(t,e,r){a.log("[StreamingEvents] ๐Ÿ‘‚ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const o=s=>{const n=s;a.log("[StreamingEvents] ๐Ÿ“จ Received streamingComplete event (checking match)",{receivedMessageId:n.detail.messageId,receivedSessionId:n.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:n.detail.messageId===t,sessionIdMatch:n.detail.sessionId===e}),n.detail.messageId===t&&n.detail.sessionId===e?(a.log("[StreamingEvents] โœ… Event matched! Calling callback"),r(n.detail)):a.log("[StreamingEvents] โš ๏ธ Event did not match - ignoring")};return window.addEventListener(ke,o),()=>{a.log("[StreamingEvents] ๐Ÿงน Removing streamingComplete listener"),window.removeEventListener(ke,o)}}const Ce=()=>{const t=new Set,e=new Map,r=n=>{const d=e.get(n);d&&(d.observer.disconnect(),d.timeoutId&&clearTimeout(d.timeoutId),e.delete(n))};return{startTracking:({exposureUrl:n,recommendationId:d,linkElement:l,sessionId:u,logPrefix:p="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!n||!l){p&&a.warn(`${p} โš ๏ธ Missing exposure tracking data`);return}const c=`${u||"anonymous"}::${d||n}`;if(t.has(c)||e.has(c))return;const g={observer:void 0,timeoutId:null,viewableStart:null},b=()=>{r(c),t.add(c),fetch(n,{method:"GET",keepalive:!0}).then(()=>{p&&a.log(`${p} โœ… Exposure pixel fired`)}).catch(()=>{p&&a.warn(`${p} โš ๏ธ Failed to fire exposure pixel`),t.delete(c)})},x=new IntersectionObserver(f=>{f.forEach(y=>{y.intersectionRatio>=.5?g.viewableStart===null&&(g.viewableStart=performance.now(),g.timeoutId=setTimeout(b,1e3)):(g.viewableStart=null,g.timeoutId&&(clearTimeout(g.timeoutId),g.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});g.observer=x,x.observe(l),e.set(c,g)},cleanup:()=>{Array.from(e.keys()).forEach(r)}}},Ut=({containerId:t,messageId:e,sessionId:r,sdk:o,query:s,recommendations:n=[],onLinksFound:d,onNoLinksFound:l,children:u})=>{const[p,c]=h.useState(!1),[g,b]=h.useState(!0),[x,f]=h.useState(!1),y=h.useRef(Ce()),_=h.useRef(d),m=h.useRef(l),M=h.useRef(t),S=h.useRef(o),I=h.useRef(r),E=h.useRef(s);h.useEffect(()=>{_.current=d,m.current=l,M.current=t,S.current=o,I.current=r,E.current=s},[d,l,t,o,r,s]),h.useEffect(()=>()=>{y.current.cleanup()},[]);const w=h.useCallback(({exposureUrl:A,recommendationId:C,linkElement:k})=>{y.current.startTracking({exposureUrl:A,recommendationId:C,linkElement:k,sessionId:I.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),v=h.useCallback(()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿ” Performing final link detection...");try{const A=document.getElementById(M.current);if(!A){a.warn("[FinalLinkDetectionCheck] โŒ Container not found"),c(!0),l();return}const C=new Pe({autoAddLabels:!0,fireExposurePixels:!0}),k=n.length>0?n:[];a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Using ${k.length} recommendations for link detection`),k.length>0&&process.env.NODE_ENV==="development"&&k.forEach((T,j)=>{var D,P,O,K,z;a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Recommendation ${j+1} (DEV):`,{recommendation_id:T.recommendation_id,product_id:T.product_id,title:T.title,click_url:T.click_url,preferred_format:(D=T.creative_input)==null?void 0:D.preferred_format,resolved_format:(P=T.format_resolution)==null?void 0:P.resolved_format,creative_input:{product_name:(O=T.creative_input)==null?void 0:O.product_name,brand_name:(K=T.creative_input)==null?void 0:K.brand_name,cta_url:(z=T.creative_input)==null?void 0:z.cta_url}})});const R=C.scanAndProcessLinks(A,k,({exposureUrl:T,recommendationId:j,linkElement:D})=>w({exposureUrl:T,recommendationId:j,linkElement:D}));a.log(`[FinalLinkDetectionCheck] ๐Ÿ“Š Final check result: ${R.length} links`),R.length>0?(a.log("[FinalLinkDetectionCheck] โœ… Links detected - canceling fallback (no API call)"),f(!0),_.current(R.length)):(a.log(`[FinalLinkDetectionCheck] โš ๏ธ No links found - rendering fallback (will use ${k.length} previous recommendation(s) if available)`),f(!1),m.current()),c(!0)}catch{a.error("[FinalLinkDetectionCheck] โŒ Error during final check"),c(!0),m.current()}},[w,n]);return h.useEffect(()=>{a.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:r,recommendationsCount:n.length});let A=null,C=!1;const k=it(e,r,R=>{a.log("[FinalLinkDetectionCheck] ๐ŸŽฏ Received streamingComplete event",{messageId:R.messageId,sessionId:R.sessionId,timestamp:R.timestamp}),C=!0,A&&(clearTimeout(A),A=null),b(!1),setTimeout(()=>{v()},100)});return A=setTimeout(()=>{C||(a.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),b(!1),setTimeout(()=>{v()},100))},5e3),()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿงน Cleaning up listener"),A&&clearTimeout(A),k()}},[e,r]),g?i.jsx(i.Fragment,{}):p?x?(a.log("[FinalLinkDetectionCheck] ๐Ÿšซ Links found - NOT rendering fallback"),i.jsx(i.Fragment,{})):(a.log("[FinalLinkDetectionCheck] โœ… No links found - rendering fallback"),i.jsx(i.Fragment,{children:u})):i.jsx(i.Fragment,{})},Vt=({messageId:t,children:e,fallbackFormat:r="tail",onLinksDetected:o,onNoLinksDetected:s,onError:n,className:d,query:l,onFallbackChange:u,onWeaveAttempt:p,onWeaveOutcome:c,followups_container_id:g,onExecuteQuery:b,onFollowupDetected:x,isContainerReady:f})=>{var N,G,L,B;const{sessionId:y,sdk:_,language:m,geo_country:M,userId:S,model:I,messages:E,theme:w}=le(),v=h.useRef(null),A=`weave-ad-container-${t}`,C=h.useRef(Ce()),k=h.useRef(!1),R=h.useRef(null),[T,j]=h.useState([]),D=h.useRef([]),[P,O]=h.useState(null),[K,z]=h.useState(null),ee=h.useRef(x);h.useEffect(()=>{ee.current=x},[x]),h.useEffect(()=>(R.current||(R.current=new Pe({autoAddLabels:!0,fireExposurePixels:!0})),()=>{R.current&&(R.current.stopWatching(),R.current.clearCache())}),[]),h.useEffect(()=>()=>{C.current.cleanup()},[]),h.useEffect(()=>{(async()=>{var Q,U,V,J,q,H,Y,oe,ne,ge,fe;if(!_||!(l!=null&&l.trim())||!t){a.log("[WeaveAdFormatContainer] โš ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{a.log("[WeaveAdFormatContainer] ๐Ÿ“ค Fetching recommendations from SDK for brand URL matching");const F=await _.fetchRecommendationFromAIPContext({query:l.trim(),sessionId:y,messageId:t,language:m,geo_country:M,userId:S,model:I,messages:E}),me=F?[F]:[];if(j(me),D.current=me,a.log("[WeaveAdFormatContainer] โœ… Fetched recommendations:",me.length),F){const Ee=F.followup_query,ue=(Q=F.creative_input)==null?void 0:Q.followup_query,de=Ee||ue,Te=F.followup_engagement_url,be=(U=F.creative_input)==null?void 0:U.followup_engagement_url,pe=Te||be,Re=F.followup_exposure_url,xe=(V=F.creative_input)==null?void 0:V.followup_exposure_url,ve=Re||xe,se=F.recommendation_id||"";if(de)if(a.debug("[WeaveAdFormatContainer] โœ… Followup query detected:",de),a.debug("[WeaveAdFormatContainer] โœ… Followup engagement URL:",pe?"present":"missing"),a.debug("[WeaveAdFormatContainer] โœ… Recommendation ID:",se||"missing"),g){a.debug("[WeaveAdFormatContainer] โœ… Using SDK-managed portal rendering (followups_container_id provided)");const ye={...F,followup_query:de,followup_engagement_url:pe,followup_exposure_url:ve,recommendation_id:se||F.recommendation_id};O(ye)}else ee.current?(a.debug("[WeaveAdFormatContainer] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),ee.current(de,pe||"",se||"")):a.debug("[WeaveAdFormatContainer] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)");else O(null)}F&&process.env.NODE_ENV==="development"&&a.log("[WeaveAdFormatContainer] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:F.recommendation_id,product_id:F.product_id,brand_id:F.brand_id,title:F.title,click_url:F.click_url,contextual_relevance_score:F.contextual_relevance_score,preferred_format:(J=F.creative_input)==null?void 0:J.preferred_format,resolved_format:(q=F.format_resolution)==null?void 0:q.resolved_format,creative_input:{product_name:(H=F.creative_input)==null?void 0:H.product_name,brand_name:(Y=F.creative_input)==null?void 0:Y.brand_name,cta_url:(oe=F.creative_input)==null?void 0:oe.cta_url,short_description:(ne=F.creative_input)==null?void 0:ne.short_description,allowed_formats:(ge=F.creative_input)==null?void 0:ge.allowed_formats,fallback_formats:(fe=F.creative_input)==null?void 0:fe.fallback_formats},format_resolution:F.format_resolution,full_response:F})}catch(F){a.warn("[WeaveAdFormatContainer] โš ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",F),j([])}})()},[_,y,t,l,g]),h.useEffect(()=>{if(!(P!=null&&P.followup_query)||!g){z(null);return}if(f===!1){a.debug("[WeaveAdFormatContainer] โณ Waiting for container signal...");return}let W=0;const Q=5,U=()=>{const J=document.getElementById(g);return J?(a.debug(`[WeaveAdFormatContainer] โœ… Found followup container: ${g} `),z(J),!0):!1};if(U())return;const V=setInterval(()=>{W++,(U()||W>=Q)&&(clearInterval(V),W>=Q&&a.warn(`[WeaveAdFormatContainer] โš ๏ธ Followup container not found after signal: ${g} `))},100);return()=>clearInterval(V)},[P,g,f]),h.useEffect(()=>{const W=v.current;if(!W||!R.current)return;const Q=R.current,U=({exposureUrl:q,recommendationId:H,linkElement:Y})=>{C.current.startTracking({exposureUrl:q,recommendationId:H,linkElement:Y,sessionId:y,logPrefix:"[WeaveAdFormatContainer]"})},J=setTimeout(()=>{a.log("[WeaveAdFormatContainer] ๐Ÿ” Weave injection attempt started"),p==null||p(t);const q=D.current.length>0?D.current:[];a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Using ${q.length} recommendations for link detection`);try{const H=Q.scanAndProcessLinks(W,q,U);H.length>0&&!k.current?(k.current=!0,a.log(`[WeaveAdFormatContainer] โœ… Weave injection succeeded: ${H.length} links detected`),c==null||c(t,!0,`Found ${H.length} links`),o==null||o(H.length),u==null||u(!1)):k.current||a.log("[WeaveAdFormatContainer] โš ๏ธ Weave injection: no links found on initial scan")}catch(H){const Y=H instanceof Error?H.message:String(H);a.error(`[WeaveAdFormatContainer] โŒ Weave injection failed: ${Y}`),c==null||c(t,!1,Y),s==null||s(),u==null||u(!0)}},100);return Q.watchForNewLinks(W,D.current,U),()=>{clearTimeout(J),Q.stopWatching()}},[e,y,t,o,u,p,c]);const te=(G=(N=T[0])==null?void 0:N.format_resolution)==null?void 0:G.resolved_format,$=(B=(L=T[0])==null?void 0:L.creative_input)==null?void 0:B.preferred_format,X=te==="weave"||$==="weave";h.useEffect(()=>{l&&X&&a.log(`[WeaveAdFormatContainer] ๐ŸŽฏ Format is "weave" (resolved: ${te}, preferred: ${$}) - skipping fallback recommendations`)},[l,X,te,$]);const re=()=>K&&(P!=null&&P.followup_query)&&_?(a.debug(`[WeaveAdFormatContainer] ๐ŸŒ€ Rendering followup portal into: ${g} `),qe.createPortal(i.jsx(Me,{recommendation:P,theme:w,sdk:_,sessionId:y,onExecuteQuery:b}),K)):(a.debug(`[WeaveAdFormatContainer] โŒ Skipping followup portal. Container: ${!!K}, Query: ${!!(P!=null&&P.followup_query)}, SDK: ${!!_} `),null);return i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:v,id:A,className:d,"data-weave-ad-format":"true","data-message-id":t,children:e}),l&&!X&&i.jsx(Ut,{containerId:A,messageId:t,sessionId:y,sdk:_,query:l,recommendations:T,onLinksFound:W=>{a.log(`[WeaveAdFormatContainer] โœ… Links found (${W}) - no fallback needed`),c==null||c(t,!0,`Found ${W} links in final check`),o==null||o(W),u==null||u(!1)},onNoLinksFound:()=>{a.log("[WeaveAdFormatContainer] โš ๏ธ No links found - rendering fallback"),a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Passing ${T.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),s==null||s(),u==null||u(!0)},children:i.jsx(nt,{format:r,messageId:t,query:l,fallback:!0,onError:n,previousRecommendations:T.length>0?T:void 0})}),re()]})},Ht=t=>{const{sdk:e,sessionId:r}=le(),o=h.useRef(!1),s=h.useRef(0),n=h.useRef(!1),d=h.useRef(!1),l=h.useRef(null),u=h.useRef(Ce());h.useEffect(()=>()=>{u.current.cleanup()},[]);const p=h.useCallback(({exposureUrl:m,recommendationId:M,linkElement:S})=>{u.current.startTracking({exposureUrl:m,recommendationId:M,linkElement:S,sessionId:r,logPrefix:"[useWeaveAdFormat]"})},[r]),c=h.useRef(Date.now()),g=h.useRef(0),b=h.useRef(null),x=h.useRef([]),f=h.useRef(300),y=h.useCallback(async()=>{var m,M,S,I;if(!(!e||!r||o.current)){o.current=!0,s.current=0;try{const E=document.getElementById(t.llmOutputContainerId);if(!E)return;const w=(m=e.getWeaveProcessor)==null?void 0:m.call(e);if(!w)return;const v=w.scanAndProcessLinks(E,[],({exposureUrl:C,recommendationId:k,linkElement:R})=>p({exposureUrl:C,recommendationId:k,linkElement:R}));s.current=v.length;const A=v.length>0;if(A&&!n.current)n.current=!0,(M=t.onLinksDetected)==null||M.call(t,v.length),d.current=!0;else if(!A&&n.current)n.current=!1,d.current=!1;else if(!A&&!d.current){l.current&&clearTimeout(l.current),b.current&&clearInterval(b.current),g.current=0,c.current=Date.now();const C=Math.max(100,f.current/3);b.current=setInterval(()=>{var j;const R=Date.now()-c.current,T=f.current;R>=T?(g.current++,g.current>=2&&(b.current&&(clearInterval(b.current),b.current=null),!n.current&&!d.current&&((j=t.onNoLinksDetected)==null||j.call(t),d.current=!0))):g.current=0},C);const k=Math.max(1500,f.current*5);l.current=setTimeout(()=>{var R;b.current&&(clearInterval(b.current),b.current=null),!n.current&&!d.current&&((R=t.onNoLinksDetected)==null||R.call(t),d.current=!0)},k)}else A&&d.current&&!n.current&&(l.current&&(clearTimeout(l.current),l.current=null),n.current=!0,(S=t.onLinksDetected)==null||S.call(t,v.length),d.current=!0)}catch(E){const w=E instanceof Error?E:new Error(String(E));(I=t.onError)==null||I.call(t,w)}finally{o.current=!1}}},[e,r,t,p]),_=h.useCallback(()=>{const m=x.current;if(m.length<2){f.current=300;return}const M=[];for(let E=1;E<m.length;E++)M.push(m[E]-m[E-1]);const S=M.reduce((E,w)=>E+w,0)/M.length,I=Math.max(100,Math.min(S*3,1e3));f.current=I},[]);return h.useEffect(()=>{const m=document.getElementById(t.llmOutputContainerId);if(!m)return;y();const M=new MutationObserver(()=>{const S=Date.now();c.current=S,g.current=0,x.current.push(S),x.current.length>10&&x.current.shift(),_(),y()});return M.observe(m,{childList:!0,subtree:!0,characterData:!1}),()=>{M.disconnect(),l.current&&clearTimeout(l.current),b.current&&clearInterval(b.current)}},[t.llmOutputContainerId,y,_]),{isProcessing:o.current,detectedLinksCount:s.current,linksFound:n.current,shouldRenderFallback:!n.current&&d.current,processWeaveFormat:y}},Ot="1.0.10";exports.AdMeshBadge=st;exports.AdMeshBridgeFormat=Ne;exports.AdMeshContext=Le;exports.AdMeshEcommerceCards=Pt;exports.AdMeshFollowup=Me;exports.AdMeshInlineCard=at;exports.AdMeshLayout=Je;exports.AdMeshLinkTracker=he;exports.AdMeshProductCard=Se;exports.AdMeshProvider=It;exports.AdMeshRecommendations=jt;exports.AdMeshRenderer=tt;exports.AdMeshSDK=rt;exports.AdMeshSummaryLayout=Xe;exports.AdMeshSummaryUnit=Ae;exports.AdMeshTailAd=Ae;exports.AdMeshTracker=et;exports.AdMeshViewabilityTracker=ae;exports.STREAMING_COMPLETE_EVENT=ke;exports.STREAMING_START_EVENT=_e;exports.VERSION=Ot;exports.WeaveAdFormatContainer=Vt;exports.WeaveAdFormatProvider=Lt;exports.WeaveFallbackRecommendations=nt;exports.WeaveResponseProcessor=Pe;exports.createInlineExposureTracker=Ce;exports.dispatchStreamingCompleteEvent=zt;exports.dispatchStreamingStartEvent=$t;exports.onStreamingComplete=it;exports.onStreamingStart=Bt;exports.useAdMesh=le;exports.useAdMeshContext=Ze;exports.useAdMeshStyles=Ye;exports.useAdMeshTracker=Qe;exports.useViewabilityTracker=Ge;exports.useWeaveAdFormat=Ht;exports.useWeaveAdFormatContext=Nt;
987
+ `}})]})},st=({recommendation:t,theme:e,variation:n="default",expandable:o=!1,className:s,style:r})=>{var m,c,h,b,v,f;if(!t)return a.log("[AdMesh Inline Card] No recommendation provided - not rendering"),null;const l={title:t.product_title||t.title,description:t.weave_summary||t.reason||"",ctaText:t.product_title||t.title},u=me("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":o&&(n==="question"||n==="statement")},s);return i.jsx("div",{className:u,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((c=(m=e==null?void 0:e.components)==null?void 0:m.inlineRecommendation)==null?void 0:c.width)||"100%",...(h=e==null?void 0:e.components)==null?void 0:h.productCard,...r},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",children:[i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((b=t.product_logo)==null?void 0:b.url)&&i.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:w=>{w.target.style.display="none"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:l.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(pe,{recommendationId:t.recommendation_id||"",admeshLink:t.click_url||t.admesh_link||((v=t.creative_input)==null?void 0:v.cta_url)||t.url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"inline_card_cta"},children:i.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[n==="question"?"Try":"Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),l.description&&i.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:l.description}),((f=t.creative_input)==null?void 0:f.offer_summary)&&i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2 line-clamp-2 italic",children:t.creative_input.offer_summary}),i.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};st.displayName="AdMeshInlineCard";const $t={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Bt={"Top Match":"โ˜…","Free Tier":"โ—†","AI Powered":"โ—‰",Popular:"โ–ฒ",New:"โ—","Trial Available":"โ—ˆ"},it=({type:t,variant:e,size:n="md",className:o,style:s})=>{const r=e||$t[t]||"secondary",d=Bt[t],l=me("admesh-component","admesh-badge",`admesh-badge--${r}`,`admesh-badge--${n}`,o);return i.jsxs("span",{className:l,style:s,children:[d&&i.jsx("span",{className:"admesh-badge__icon",children:d}),i.jsx("span",{className:"admesh-badge__text",children:t})]})};it.displayName="AdMeshBadge";const ve="admesh:streamingStart",ye="admesh:streamingComplete";function zt(t,e){const n={messageId:t,sessionId:e,timestamp:Date.now()},o=new CustomEvent(ve,{detail:n});window.dispatchEvent(o),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function Ut(t,e,n){const o={messageId:t,sessionId:e,timestamp:Date.now(),metadata:n},s=new CustomEvent(ye,{detail:o});window.dispatchEvent(s),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:n})}function Vt(t,e,n){const o=s=>{const r=s;r.detail.messageId===t&&r.detail.sessionId===e&&(a.log("[StreamingEvents] ๐Ÿ“จ Received streamingStart event"),n(r.detail))};return window.addEventListener(ve,o),()=>{window.removeEventListener(ve,o)}}function dt(t,e,n){a.log("[StreamingEvents] ๐Ÿ‘‚ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const o=s=>{const r=s;a.log("[StreamingEvents] ๐Ÿ“จ Received streamingComplete event (checking match)",{receivedMessageId:r.detail.messageId,receivedSessionId:r.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:r.detail.messageId===t,sessionIdMatch:r.detail.sessionId===e}),r.detail.messageId===t&&r.detail.sessionId===e?(a.log("[StreamingEvents] โœ… Event matched! Calling callback"),n(r.detail)):a.log("[StreamingEvents] โš ๏ธ Event did not match - ignoring")};return window.addEventListener(ye,o),()=>{a.log("[StreamingEvents] ๐Ÿงน Removing streamingComplete listener"),window.removeEventListener(ye,o)}}const Ae=()=>{const t=new Set,e=new Map,n=r=>{const d=e.get(r);d&&(d.observer.disconnect(),d.timeoutId&&clearTimeout(d.timeoutId),e.delete(r))};return{startTracking:({exposureUrl:r,recommendationId:d,linkElement:l,sessionId:u,logPrefix:m="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!r||!l){m&&a.warn(`${m} โš ๏ธ Missing exposure tracking data`);return}const c=`${u||"anonymous"}::${d||r}`;if(t.has(c)||e.has(c))return;const h={observer:void 0,timeoutId:null,viewableStart:null},b=()=>{n(c),t.add(c),fetch(r,{method:"GET",keepalive:!0}).then(()=>{m&&a.log(`${m} โœ… Exposure pixel fired`)}).catch(()=>{m&&a.warn(`${m} โš ๏ธ Failed to fire exposure pixel`),t.delete(c)})},v=new IntersectionObserver(f=>{f.forEach(w=>{w.intersectionRatio>=.5?h.viewableStart===null&&(h.viewableStart=performance.now(),h.timeoutId=setTimeout(b,1e3)):(h.viewableStart=null,h.timeoutId&&(clearTimeout(h.timeoutId),h.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});h.observer=v,v.observe(l),e.set(c,h)},cleanup:()=>{Array.from(e.keys()).forEach(n)}}},Ht=({containerId:t,messageId:e,sessionId:n,sdk:o,query:s,recommendations:r=[],onLinksFound:d,onNoLinksFound:l,children:u})=>{const[m,c]=p.useState(!1),[h,b]=p.useState(!0),[v,f]=p.useState(!1),w=p.useRef(Ae()),y=p.useRef(d),g=p.useRef(l),S=p.useRef(t),k=p.useRef(o),F=p.useRef(n),R=p.useRef(s);p.useEffect(()=>{y.current=d,g.current=l,S.current=t,k.current=o,F.current=n,R.current=s},[d,l,t,o,n,s]),p.useEffect(()=>()=>{w.current.cleanup()},[]);const _=p.useCallback(({exposureUrl:M,recommendationId:C,linkElement:A})=>{w.current.startTracking({exposureUrl:M,recommendationId:C,linkElement:A,sessionId:F.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),x=p.useCallback(()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿ” Performing final link detection...");try{const M=document.getElementById(S.current);if(!M){a.warn("[FinalLinkDetectionCheck] โŒ Container not found"),c(!0),l();return}const C=new Pe({autoAddLabels:!0,fireExposurePixels:!0}),A=r.length>0?r:[];a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Using ${A.length} recommendations for link detection`),A.length>0&&process.env.NODE_ENV==="development"&&A.forEach((T,I)=>{var D,P,O,K,B;a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Recommendation ${I+1} (DEV):`,{recommendation_id:T.recommendation_id,product_id:T.product_id,title:T.title,click_url:T.click_url,preferred_format:(D=T.creative_input)==null?void 0:D.preferred_format,resolved_format:(P=T.format_resolution)==null?void 0:P.resolved_format,creative_input:{product_name:(O=T.creative_input)==null?void 0:O.product_name,brand_name:(K=T.creative_input)==null?void 0:K.brand_name,cta_url:(B=T.creative_input)==null?void 0:B.cta_url}})});const E=C.scanAndProcessLinks(M,A,({exposureUrl:T,recommendationId:I,linkElement:D})=>_({exposureUrl:T,recommendationId:I,linkElement:D}));a.log(`[FinalLinkDetectionCheck] ๐Ÿ“Š Final check result: ${E.length} links`),E.length>0?(a.log("[FinalLinkDetectionCheck] โœ… Links detected - canceling fallback (no API call)"),f(!0),y.current(E.length)):(a.log(`[FinalLinkDetectionCheck] โš ๏ธ No links found - rendering fallback (will use ${A.length} previous recommendation(s) if available)`),f(!1),g.current()),c(!0)}catch{a.error("[FinalLinkDetectionCheck] โŒ Error during final check"),c(!0),g.current()}},[_,r]);return p.useEffect(()=>{a.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:n,recommendationsCount:r.length});let M=null,C=!1;const A=dt(e,n,E=>{a.log("[FinalLinkDetectionCheck] ๐ŸŽฏ Received streamingComplete event",{messageId:E.messageId,sessionId:E.sessionId,timestamp:E.timestamp}),C=!0,M&&(clearTimeout(M),M=null),b(!1),setTimeout(()=>{x()},100)});return M=setTimeout(()=>{C||(a.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),b(!1),setTimeout(()=>{x()},100))},5e3),()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿงน Cleaning up listener"),M&&clearTimeout(M),A()}},[e,n]),h?i.jsx(i.Fragment,{}):m?v?(a.log("[FinalLinkDetectionCheck] ๐Ÿšซ Links found - NOT rendering fallback"),i.jsx(i.Fragment,{})):(a.log("[FinalLinkDetectionCheck] โœ… No links found - rendering fallback"),i.jsx(i.Fragment,{children:u})):i.jsx(i.Fragment,{})},Ot=({messageId:t,children:e,fallbackFormat:n="tail",onLinksDetected:o,onNoLinksDetected:s,onError:r,className:d,query:l,onFallbackChange:u,onWeaveAttempt:m,onWeaveOutcome:c,followups_container_id:h,onExecuteQuery:b,onFollowupDetected:v,isContainerReady:f})=>{var N,G,j,z;const{sessionId:w,sdk:y,language:g,geo_country:S,userId:k,model:F,messages:R,theme:_}=ue(),x=p.useRef(null),M=`weave-ad-container-${t}`,C=p.useRef(Ae()),A=p.useRef(!1),E=p.useRef(null),[T,I]=p.useState([]),D=p.useRef([]),[P,O]=p.useState(null),[K,B]=p.useState(null),ee=p.useRef(v);p.useEffect(()=>{ee.current=v},[v]),p.useEffect(()=>(E.current||(E.current=new Pe({autoAddLabels:!0,fireExposurePixels:!0})),()=>{E.current&&(E.current.stopWatching(),E.current.clearCache())}),[]),p.useEffect(()=>()=>{C.current.cleanup()},[]),p.useEffect(()=>{(async()=>{var Q,U,V,J,q,H,Y,ae,ne,he,ge;if(!y||!(l!=null&&l.trim())||!t){a.log("[WeaveAdFormatContainer] โš ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{a.log("[WeaveAdFormatContainer] ๐Ÿ“ค Fetching recommendations from SDK for brand URL matching");const L=await y.fetchRecommendationFromAIPContext({query:l.trim(),sessionId:w,messageId:t,language:g,geo_country:S,userId:k,model:F,messages:R}),oe=L?[L]:[];if(I(oe),D.current=oe,a.log("[WeaveAdFormatContainer] โœ… Fetched recommendations:",oe.length),L){const Se=L.followup_query,Me=(Q=L.creative_input)==null?void 0:Q.followup_query,se=Se||Me,Ce=L.followup_engagement_url,Ee=(U=L.creative_input)==null?void 0:U.followup_engagement_url,le=Ce||Ee,Te=L.followup_exposure_url,Re=(V=L.creative_input)==null?void 0:V.followup_exposure_url,fe=Te||Re,de=L.recommendation_id||"";if(se)if(a.debug("[WeaveAdFormatContainer] โœ… Followup query detected:",se),a.debug("[WeaveAdFormatContainer] โœ… Followup engagement URL:",le?"present":"missing"),a.debug("[WeaveAdFormatContainer] โœ… Recommendation ID:",de||"missing"),h){a.debug("[WeaveAdFormatContainer] โœ… Using SDK-managed portal rendering (followups_container_id provided)");const be={...L,followup_query:se,followup_engagement_url:le,followup_exposure_url:fe,recommendation_id:de||L.recommendation_id};O(be)}else ee.current?(a.debug("[WeaveAdFormatContainer] ๐Ÿ”” Using legacy callback mode (followups_container_id not provided)"),ee.current(se,le||"",de||"")):a.debug("[WeaveAdFormatContainer] โš ๏ธ Followup detected but no rendering method provided (neither followups_container_id nor onFollowupDetected callback)");else O(null)}L&&process.env.NODE_ENV==="development"&&a.log("[WeaveAdFormatContainer] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:L.recommendation_id,product_id:L.product_id,brand_id:L.brand_id,title:L.title,click_url:L.click_url,contextual_relevance_score:L.contextual_relevance_score,preferred_format:(J=L.creative_input)==null?void 0:J.preferred_format,resolved_format:(q=L.format_resolution)==null?void 0:q.resolved_format,creative_input:{product_name:(H=L.creative_input)==null?void 0:H.product_name,brand_name:(Y=L.creative_input)==null?void 0:Y.brand_name,cta_url:(ae=L.creative_input)==null?void 0:ae.cta_url,short_description:(ne=L.creative_input)==null?void 0:ne.short_description,allowed_formats:(he=L.creative_input)==null?void 0:he.allowed_formats,fallback_formats:(ge=L.creative_input)==null?void 0:ge.fallback_formats},format_resolution:L.format_resolution,full_response:L})}catch(L){a.warn("[WeaveAdFormatContainer] โš ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",L),I([])}})()},[y,w,t,l,h]),p.useEffect(()=>{if(!(P!=null&&P.followup_query)||!h){B(null);return}if(f===!1){a.debug("[WeaveAdFormatContainer] โณ Waiting for container signal...");return}let W=0;const Q=5,U=()=>{const J=document.getElementById(h);return J?(a.debug(`[WeaveAdFormatContainer] โœ… Found followup container: ${h} `),B(J),!0):!1};if(U())return;const V=setInterval(()=>{W++,(U()||W>=Q)&&(clearInterval(V),W>=Q&&a.warn(`[WeaveAdFormatContainer] โš ๏ธ Followup container not found after signal: ${h} `))},100);return()=>clearInterval(V)},[P,h,f]),p.useEffect(()=>{const W=x.current;if(!W||!E.current)return;const Q=E.current,U=({exposureUrl:q,recommendationId:H,linkElement:Y})=>{C.current.startTracking({exposureUrl:q,recommendationId:H,linkElement:Y,sessionId:w,logPrefix:"[WeaveAdFormatContainer]"})},J=setTimeout(()=>{a.log("[WeaveAdFormatContainer] ๐Ÿ” Weave injection attempt started"),m==null||m(t);const q=D.current.length>0?D.current:[];a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Using ${q.length} recommendations for link detection`);try{const H=Q.scanAndProcessLinks(W,q,U);H.length>0&&!A.current?(A.current=!0,a.log(`[WeaveAdFormatContainer] โœ… Weave injection succeeded: ${H.length} links detected`),c==null||c(t,!0,`Found ${H.length} links`),o==null||o(H.length),u==null||u(!1)):A.current||a.log("[WeaveAdFormatContainer] โš ๏ธ Weave injection: no links found on initial scan")}catch(H){const Y=H instanceof Error?H.message:String(H);a.error(`[WeaveAdFormatContainer] โŒ Weave injection failed: ${Y}`),c==null||c(t,!1,Y),s==null||s(),u==null||u(!0)}},100);return Q.watchForNewLinks(W,D.current,U),()=>{clearTimeout(J),Q.stopWatching()}},[e,w,t,o,u,m,c]);const te=(G=(N=T[0])==null?void 0:N.format_resolution)==null?void 0:G.resolved_format,$=(z=(j=T[0])==null?void 0:j.creative_input)==null?void 0:z.preferred_format,X=te==="weave"||$==="weave";p.useEffect(()=>{l&&X&&a.log(`[WeaveAdFormatContainer] ๐ŸŽฏ Format is "weave" (resolved: ${te}, preferred: ${$}) - skipping fallback recommendations`)},[l,X,te,$]);const re=()=>K&&(P!=null&&P.followup_query)&&y?(a.debug(`[WeaveAdFormatContainer] ๐ŸŒ€ Rendering followup portal into: ${h} `),Ge.createPortal(i.jsx(ke,{recommendation:P,theme:_,sdk:y,sessionId:w,onExecuteQuery:b}),K)):(a.debug(`[WeaveAdFormatContainer] โŒ Skipping followup portal. Container: ${!!K}, Query: ${!!(P!=null&&P.followup_query)}, SDK: ${!!y} `),null);return i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:x,id:M,className:d,"data-weave-ad-format":"true","data-message-id":t,children:e}),l&&!X&&i.jsx(Ht,{containerId:M,messageId:t,sessionId:w,sdk:y,query:l,recommendations:T,onLinksFound:W=>{a.log(`[WeaveAdFormatContainer] โœ… Links found (${W}) - no fallback needed`),c==null||c(t,!0,`Found ${W} links in final check`),o==null||o(W),u==null||u(!1)},onNoLinksFound:()=>{a.log("[WeaveAdFormatContainer] โš ๏ธ No links found - rendering fallback"),a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Passing ${T.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),s==null||s(),u==null||u(!0)},children:i.jsx(ot,{format:n,messageId:t,query:l,fallback:!0,onError:r,previousRecommendations:T.length>0?T:void 0})}),re()]})},Kt=t=>{const{sdk:e,sessionId:n}=ue(),o=p.useRef(!1),s=p.useRef(0),r=p.useRef(!1),d=p.useRef(!1),l=p.useRef(null),u=p.useRef(Ae());p.useEffect(()=>()=>{u.current.cleanup()},[]);const m=p.useCallback(({exposureUrl:g,recommendationId:S,linkElement:k})=>{u.current.startTracking({exposureUrl:g,recommendationId:S,linkElement:k,sessionId:n,logPrefix:"[useWeaveAdFormat]"})},[n]),c=p.useRef(Date.now()),h=p.useRef(0),b=p.useRef(null),v=p.useRef([]),f=p.useRef(300),w=p.useCallback(async()=>{var g,S,k,F;if(!(!e||!n||o.current)){o.current=!0,s.current=0;try{const R=document.getElementById(t.llmOutputContainerId);if(!R)return;const _=(g=e.getWeaveProcessor)==null?void 0:g.call(e);if(!_)return;const x=_.scanAndProcessLinks(R,[],({exposureUrl:C,recommendationId:A,linkElement:E})=>m({exposureUrl:C,recommendationId:A,linkElement:E}));s.current=x.length;const M=x.length>0;if(M&&!r.current)r.current=!0,(S=t.onLinksDetected)==null||S.call(t,x.length),d.current=!0;else if(!M&&r.current)r.current=!1,d.current=!1;else if(!M&&!d.current){l.current&&clearTimeout(l.current),b.current&&clearInterval(b.current),h.current=0,c.current=Date.now();const C=Math.max(100,f.current/3);b.current=setInterval(()=>{var I;const E=Date.now()-c.current,T=f.current;E>=T?(h.current++,h.current>=2&&(b.current&&(clearInterval(b.current),b.current=null),!r.current&&!d.current&&((I=t.onNoLinksDetected)==null||I.call(t),d.current=!0))):h.current=0},C);const A=Math.max(1500,f.current*5);l.current=setTimeout(()=>{var E;b.current&&(clearInterval(b.current),b.current=null),!r.current&&!d.current&&((E=t.onNoLinksDetected)==null||E.call(t),d.current=!0)},A)}else M&&d.current&&!r.current&&(l.current&&(clearTimeout(l.current),l.current=null),r.current=!0,(k=t.onLinksDetected)==null||k.call(t,x.length),d.current=!0)}catch(R){const _=R instanceof Error?R:new Error(String(R));(F=t.onError)==null||F.call(t,_)}finally{o.current=!1}}},[e,n,t,m]),y=p.useCallback(()=>{const g=v.current;if(g.length<2){f.current=300;return}const S=[];for(let R=1;R<g.length;R++)S.push(g[R]-g[R-1]);const k=S.reduce((R,_)=>R+_,0)/S.length,F=Math.max(100,Math.min(k*3,1e3));f.current=F},[]);return p.useEffect(()=>{const g=document.getElementById(t.llmOutputContainerId);if(!g)return;w();const S=new MutationObserver(()=>{const k=Date.now();c.current=k,h.current=0,v.current.push(k),v.current.length>10&&v.current.shift(),y(),w()});return S.observe(g,{childList:!0,subtree:!0,characterData:!1}),()=>{S.disconnect(),l.current&&clearTimeout(l.current),b.current&&clearInterval(b.current)}},[t.llmOutputContainerId,w,y]),{isProcessing:o.current,detectedLinksCount:s.current,linksFound:r.current,shouldRenderFallback:!r.current&&d.current,processWeaveFormat:w}},qt="1.0.10";exports.AdMeshBadge=it;exports.AdMeshBridgeFormat=Ne;exports.AdMeshContext=Le;exports.AdMeshEcommerceCards=Wt;exports.AdMeshFollowup=ke;exports.AdMeshInlineCard=st;exports.AdMeshLayout=et;exports.AdMeshLinkTracker=pe;exports.AdMeshProductCard=_e;exports.AdMeshProvider=Lt;exports.AdMeshRecommendations=Nt;exports.AdMeshRenderer=rt;exports.AdMeshSDK=nt;exports.AdMeshSummaryLayout=Je;exports.AdMeshSummaryUnit=we;exports.AdMeshTailAd=we;exports.AdMeshTracker=tt;exports.AdMeshViewabilityTracker=ie;exports.STREAMING_COMPLETE_EVENT=ye;exports.STREAMING_START_EVENT=ve;exports.VERSION=qt;exports.WeaveAdFormatContainer=Ot;exports.WeaveAdFormatProvider=Pt;exports.WeaveFallbackRecommendations=ot;exports.WeaveResponseProcessor=Pe;exports.createInlineExposureTracker=Ae;exports.dispatchStreamingCompleteEvent=Ut;exports.dispatchStreamingStartEvent=zt;exports.onStreamingComplete=dt;exports.onStreamingStart=Vt;exports.useAdMesh=ue;exports.useAdMeshContext=Xe;exports.useAdMeshStyles=Ze;exports.useAdMeshTracker=Ye;exports.useViewabilityTracker=Qe;exports.useWeaveAdFormat=Kt;exports.useWeaveAdFormatContext=Dt;
988
988
  //# sourceMappingURL=index.js.map