admesh-ui-sdk
Version:
Beautiful, modern React components for displaying AI-powered product recommendations with citation-based conversation ads, auto-triggered widgets, floating chat, conversational interfaces, persistent sidebar, and built-in tracking. Includes zero-code SDK
23 lines โข 118 kB
JavaScript
"use strict";var st=Object.defineProperty;var it=(t,e,n)=>e in t?st(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var te=(t,e,n)=>it(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),m=require("react"),ze=require("react-dom/client"),Ge=require("react-dom");let fe=!1;var Qe;try{typeof globalThis.importMeta<"u"&&((Qe=globalThis.importMeta.env)!=null&&Qe.PROD)&&(fe=!0)}catch{}fe||(fe=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const o={log:(...t)=>{fe||console.log(...t)},warn:(...t)=>{fe||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{fe||console.info(...t)},debug:(...t)=>{fe||console.debug(...t)}};function dt(t,e,n){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...n}}function ct(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function lt(t){const e=t.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth,s=e.height,a=e.width;if(s===0||a===0)return 0;const i=Math.max(0,e.top),l=Math.min(n,e.bottom),p=Math.max(0,e.left),h=Math.min(r,e.right),c=Math.max(0,l-i),u=Math.max(0,h-p),_=c*u,f=s*a;return f>0?_/f:0}function Ve(){const t=window.innerHeight,e=document.documentElement.scrollHeight,n=window.pageYOffset||document.documentElement.scrollTop,r=e-t;return r<=0?100:Math.min(100,n/r*100)}function mt(t){const e=t.getBoundingClientRect(),n=window.pageYOffset||document.documentElement.scrollTop,r=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+n,left:e.left+r}}function ut(t){const e=t.getBoundingClientRect(),n=mt(t),r=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,a=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ct(r),viewportWidth:r,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:n.top,adPositionLeft:n.left,isDarkMode:a,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function pt(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function ht(t,e,n){return t>=n.visibilityThreshold&&e>=n.minimumDuration}function He(t=new Date){return t.toISOString()}function gt(t){return t.length===0?0:t.reduce((n,r)=>n+r,0)/t.length}function Ke(t,e){let n;return function(...s){n||(t(...s),n=!0,setTimeout(()=>n=!1,e))}}const ft={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let bt=ft;function Ye({productId:t,offerId:e,agentId:n,recommendationId:r,elementRef:s,config:a}){const i={...bt,...a},l=m.useRef(pt()),[p,h]=m.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:He(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:i.enabled}),c=m.useRef(null),u=m.useRef(null),_=m.useRef(null),f=m.useRef(null),b=m.useRef(null),k=m.useRef([]),y=m.useRef([]),g=m.useRef(null),T=m.useCallback(v=>{i.debug&&o.log(`[AdMesh Viewability] ${v}`)},[i.debug]),x=m.useCallback(async(v,F)=>{if(!(!i.enabled||!s.current||!c.current)&&(T(`Analytics disabled - skipping event: ${v}`),i.onEvent)){const w=ut(s.current),I={eventType:v,timestamp:He(),sessionId:l.current,productId:t,offerId:e,agentId:n,recommendationId:r,timeMetrics:p.timeMetrics,engagementMetrics:p.engagementMetrics,contextMetrics:w,mrcStandards:c.current,isViewable:p.isViewable,metadata:F};i.onEvent(I)}},[i,t,e,n,r,s,p,T]),N=m.useCallback(async()=>{y.current.length!==0&&(T("Analytics disabled - clearing batch without sending"),y.current=[],g.current&&(clearTimeout(g.current),g.current=null))},[T]),E=m.useCallback(Ke(()=>{if(!s.current)return;const v=lt(s.current),F=Date.now(),w=new Date(p.timeMetrics.loadedAt).getTime();h(I=>{const S={...I};v>0&&k.current.push(v);const R=I.isVisible,M=v>0;if(M&&!R)u.current=F,S.engagementMetrics.viewportEnterCount++,S.timeMetrics.timeToFirstVisible||(S.timeMetrics.timeToFirstVisible=F-w,S.engagementMetrics.scrollDepthAtFirstVisible=Ve(),x("ad_visible"));else if(!M&&R){if(u.current){const D=F-u.current;S.timeMetrics.totalVisibleDuration+=D,u.current=null}S.engagementMetrics.viewportExitCount++,x("ad_hidden")}else if(M&&R&&u.current){const D=F-u.current;S.timeMetrics.totalVisibleDuration+=D,u.current=F}if(S.isVisible=M,S.visibilityPercentage=v,v>S.engagementMetrics.maxVisibilityPercentage&&(S.engagementMetrics.maxVisibilityPercentage=v),k.current.length>0&&(S.engagementMetrics.averageVisibilityPercentage=gt(k.current)),c.current){const D=I.isViewable,A=ht(v,S.timeMetrics.totalVisibleDuration,c.current);if(A&&!D)S.isViewable=!0,S.timeMetrics.timeToViewable=F-w,_.current=F,x("ad_viewable");else if(A&&D&&_.current){const j=F-_.current;S.timeMetrics.totalViewableDuration+=j,_.current=F}}return S.engagementMetrics.currentScrollDepth=Ve(),S})},100),[s,p.timeMetrics.loadedAt,x]);return m.useEffect(()=>{if(!s.current)return;const v=s.current.getBoundingClientRect();c.current=dt(v.width,v.height,i.mrcStandards),T("Initialized MRC standards"),x("ad_loaded")},[s,i.mrcStandards,T,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=new IntersectionObserver(F=>{F.forEach(()=>{E()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return v.observe(s.current),()=>{v.disconnect()}},[i.enabled,s,E]),m.useEffect(()=>{if(!i.enabled)return;const v=Ke(()=>{E()},100);return window.addEventListener("scroll",v,{passive:!0}),()=>window.removeEventListener("scroll",v)},[i.enabled,E]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,F=()=>{f.current=Date.now(),h(I=>({...I,engagementMetrics:{...I.engagementMetrics,hoverCount:I.engagementMetrics.hoverCount+1}})),x("ad_hover_start")},w=()=>{if(f.current){const I=Date.now()-f.current;h(S=>({...S,timeMetrics:{...S.timeMetrics,totalHoverDuration:S.timeMetrics.totalHoverDuration+I}})),f.current=null,x("ad_hover_end",{hoverDuration:I})}};return v.addEventListener("mouseenter",F),v.addEventListener("mouseleave",w),()=>{v.removeEventListener("mouseenter",F),v.removeEventListener("mouseleave",w)}},[i.enabled,s,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,F=()=>{b.current=Date.now(),x("ad_focus")},w=()=>{if(b.current){const I=Date.now()-b.current;h(S=>({...S,timeMetrics:{...S.timeMetrics,totalFocusDuration:S.timeMetrics.totalFocusDuration+I}})),b.current=null,x("ad_blur",{focusDuration:I})}};return v.addEventListener("focus",F),v.addEventListener("blur",w),()=>{v.removeEventListener("focus",F),v.removeEventListener("blur",w)}},[i.enabled,s,x]),m.useEffect(()=>{if(!i.enabled||!s.current)return;const v=s.current,F=()=>{h(w=>({...w,engagementMetrics:{...w.engagementMetrics,wasClicked:!0}})),x("ad_click")};return v.addEventListener("click",F),()=>{v.removeEventListener("click",F)}},[i.enabled,s,x]),m.useEffect(()=>()=>{const v=Date.now(),F=new Date(p.timeMetrics.loadedAt).getTime(),w=v-F;h(I=>({...I,timeMetrics:{...I.timeMetrics,sessionDuration:w}})),x("ad_unloaded",{sessionDuration:w}),N()},[]),p}const ke=({productId:t,offerId:e,agentId:n,recommendationId:r,exposureUrl:s,sessionId:a,children:i,config:l,className:p,style:h,onViewabilityChange:c,onVisible:u,onViewable:_,onClick:f})=>{const b=m.useRef(null),k=m.useRef(!1),y=Ye({productId:t,offerId:e,agentId:n,recommendationId:r,elementRef:b,config:l}),g=m.useRef(y.isViewable);m.useEffect(()=>{y.isViewable!==g.current&&(g.current=y.isViewable,c&&c(y.isViewable),y.isViewable&&_&&_(),y.isViewable&&!k.current&&(o.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:s?"present":"MISSING",sessionId:a?"present":"MISSING",recommendationId:r}),s&&a?(k.current=!0,o.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",s),fetch(s,{method:"GET",keepalive:!0}).then(()=>{o.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(N=>{o.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",N),k.current=!1})):o.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!s,hasSessionId:!!a})))},[y.isViewable,c,_,s,a,r]);const T=m.useRef(y.isVisible);m.useEffect(()=>{y.isVisible!==T.current&&(T.current=y.isVisible,y.isVisible&&u&&u())},[y.isVisible,u]);const x=()=>{f&&f()};return d.jsx("div",{ref:b,className:p,style:h,onClick:x,"data-admesh-viewability-tracker":!0,"data-recommendation-id":r,"data-is-viewable":y.isViewable,"data-is-visible":y.isVisible,"data-visibility-percentage":y.visibilityPercentage.toFixed(2),children:i})};ke.displayName="AdMeshViewabilityTracker";const Ee=m.createContext(void 0);function Ze(){const t=m.useContext(Ee);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}const xt=t=>{try{return new URL(t),!0}catch{return!1}},vt=t=>t&&t.trim()?t.trim():"",Pe=({recommendations:t,theme:e,className:n="",style:r={},sessionId:s})=>{var Q,ie,se,de,oe,U,pe,xe,ce,me,ve;const a=m.useContext(Ee),i=a==null?void 0:a.userId,l=a==null?void 0:a.model,p=a==null?void 0:a.sessionId,h=(a==null?void 0:a.sdk)||null,c=s||p,[u,_]=m.useState(!1),[f,b]=m.useState(!1),[k,y]=m.useState(!1);if(!t||t.length===0)return o.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;if(u)return null;const g=t[0],T=g==null?void 0:g.product_id,x=g==null?void 0:g.exposure_url,N=(g==null?void 0:g.recommendation_id)||"",E=(g==null?void 0:g.creative_input)||{},v=E.short_description||"",F=E.offer_summary||"",w=E.brand_name||(g==null?void 0:g.title)||"",I=E.product_name||"",R=(E.assets||{}).logo_url||"",M=(g==null?void 0:g.click_url)||(g==null?void 0:g.admesh_link)||E.cta_url||(g==null?void 0:g.url),D=vt(E.cta_label);if(!w)return o.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brandName is missing",brandName:w,hasFirstRecommendation:!!g,hasCreativeInput:!!E,creativeInputBrandName:E.brand_name,recommendationTitle:g==null?void 0:g.title,recommendationId:N,recommendationKeys:g?Object.keys(g):[]}),null;let A=w,j="";F?j=F:I&&(j=I),j&&(A=`${w} โ ${j}`),o.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:N,productId:T,exposureUrl:x?"present":"MISSING",sessionId:s?"present":"MISSING",recommendationsCount:t.length,clickUrl:M||"MISSING",clickUrlSource:g!=null&&g.click_url?"click_url":g!=null&&g.admesh_link?"admesh_link":E.cta_url?"cta_url":g!=null&&g.url?"url":"none",shortDescription:v?"present":"MISSING",offerSummary:F||"MISSING",brandName:w,productName:I,headlineText:A});const G=(L,J)=>{o.log(`AdMesh tail ad ${L} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:g.recommendation_id,productId:g.product_id,clickUrl:M,source:L}).catch(()=>{o.error(`[AdMesh] Failed to track ${L} click`)})},Y=L=>{L.stopPropagation(),G("tail_ad_brand_name")},X=L=>{L.stopPropagation(),G("tail_ad_cta")},re=L=>{L.stopPropagation(),G("tail_ad_logo")},q=()=>h&&typeof h.getApiBaseUrl=="function"?h.getApiBaseUrl():h&&h.apiBaseUrl?h.apiBaseUrl:typeof window<"u"&&window.__ADMESH_API_BASE_URL__?window.__ADMESH_API_BASE_URL__:"https://api.useadmesh.com",ne=async L=>{if(!(f||k)){y(!0);try{const J=q(),he=(g==null?void 0:g.agent_id)||"",ge={message_index:0,feedback:L,session_id:c||null,user_id:i||null,agent_id:he||null,model_used:l||null,recommendationId:N||null},we=`${J}/user/feedback/submit`;o.log(`[AdMesh Tail Ad] Submitting feedback: ${L}`,{endpoint:we,payload:ge});const ee=await fetch(we,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ge)});if(o.log(`[AdMesh Tail Ad] Feedback response status: ${ee.status} ${ee.statusText}`),!ee.ok){let Ae=`Feedback submission failed: ${ee.status} ${ee.statusText}`;try{const ue=await ee.json().catch(()=>null);ue!=null&&ue.detail&&(Ae=`Feedback submission failed: ${ue.detail}`),o.error("[AdMesh Tail Ad] Error response body:",ue)}catch{}throw new Error(Ae)}const ye=await ee.json();o.log(`[AdMesh Tail Ad] โ
Feedback submitted successfully: ${L}`,ye),b(!0),L==="dislike"&&_(!0)}catch(J){const he=J instanceof Error?{message:J.message,name:J.name,stack:J.stack}:String(J);o.error(`[AdMesh Tail Ad] โ Failed to submit feedback: ${L}`,{error:he,apiBaseUrl:q(),endpoint:`${q()}/user/feedback/submit`}),y(!1)}}},C=L=>{L.stopPropagation(),L.preventDefault(),ne("like")},B=L=>{L.stopPropagation(),L.preventDefault(),ne("dislike")},[ae,le]=m.useState(!1),$=w?w.charAt(0).toUpperCase():"B",z=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,P=(e==null?void 0:e.surfaceColor)||((ie=(Q=e==null?void 0:e.components)==null?void 0:Q.card)==null?void 0:ie.backgroundColor)||(z?"#1f2937":"#ffffff"),W=(e==null?void 0:e.borderColor)||((de=(se=e==null?void 0:e.components)==null?void 0:se.card)==null?void 0:de.borderColor)||(z?"rgba(255, 255, 255, 0.1)":"rgba(0, 0, 0, 0.05)"),K=(e==null?void 0:e.borderRadius)||((U=(oe=e==null?void 0:e.components)==null?void 0:oe.card)==null?void 0:U.borderRadius)||"8px",Z=z?"0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2)":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",O=z?"0 10px 15px -3px rgba(0, 0, 0, 0.4), 0 4px 6px -2px rgba(0, 0, 0, 0.3)":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",V=((pe=e==null?void 0:e.shadows)==null?void 0:pe.medium)||((ce=(xe=e==null?void 0:e.components)==null?void 0:xe.card)==null?void 0:ce.boxShadow)||Z,H=((me=e==null?void 0:e.shadows)==null?void 0:me.large)||O;return d.jsx(ke,{productId:T,recommendationId:N,exposureUrl:x,sessionId:s,className:`admesh-tail-ad ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...r},children:d.jsxs("div",{className:"tail-ad-container flex flex-row gap-3",style:{backgroundColor:P,borderRadius:K,padding:"16px",boxShadow:V,border:`1px solid ${W}`,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",...(ve=e==null?void 0:e.components)==null?void 0:ve.card},onMouseEnter:L=>{L.currentTarget.style.boxShadow=H,L.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:L=>{L.currentTarget.style.boxShadow=V,L.currentTarget.style.transform="translateY(0)"},children:[R&&d.jsx("div",{className:"flex-shrink-0 flex items-center justify-center pr-2",style:{width:"10%",minWidth:"48px"},children:!ae&&xt(R)?d.jsx("a",{href:M||"#",target:M?"_blank":void 0,rel:M?"noopener noreferrer":void 0,onClick:M?re:void 0,className:"block",style:{cursor:M?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:d.jsx("img",{src:R,alt:`${w} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{le(!0),o.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):d.jsx("div",{className:"flex items-center justify-center text-lg font-semibold text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-800",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px"},children:$})}),d.jsxs("div",{className:"flex-1",style:{width:R?"90%":"100%",minWidth:0},children:[A&&d.jsx("div",{className:"mb-2",children:d.jsx("h3",{className:"text-black dark:text-white font-semibold text-base",style:{fontSize:"0.7rem"},children:M&&w?d.jsxs(d.Fragment,{children:[d.jsx("a",{href:M,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-semibold",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:Y,children:w}),j&&` โ ${j}`]}):A})}),v&&d.jsx("p",{className:"text-gray-700 dark:text-gray-300 text-sm mb-3 leading-relaxed",style:{fontSize:"0.7rem"},children:v}),d.jsxs("div",{className:"flex items-center justify-between mt-2",children:[d.jsx("div",{className:"flex items-center gap-2",children:D&&M&&d.jsx("a",{href:M,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium text-sm",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:X,children:D})}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:C,disabled:f||k,"aria-label":"Mark as helpful",className:"flex items-center justify-center px-2 py-1 rounded transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",style:{color:f&&!u?"#10b981":z?"#9ca3af":"#6b7280",backgroundColor:"transparent",border:"none",cursor:f||k?"not-allowed":"pointer",fontSize:"0.75rem",fontWeight:"500",minHeight:"24px"},onMouseEnter:L=>{!f&&!k&&(L.currentTarget.style.color="#10b981",L.currentTarget.style.backgroundColor="rgba(16, 185, 129, 0.1)")},onMouseLeave:L=>{f||(L.currentTarget.style.color=f?"#10b981":z?"#9ca3af":"#6b7280",L.currentTarget.style.backgroundColor="transparent")},children:"Helpful"}),d.jsx("button",{onClick:B,disabled:f||k,"aria-label":"Mark as not helpful",className:"flex items-center justify-center px-2 py-1 rounded transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",style:{color:u?"#ef4444":z?"#9ca3af":"#6b7280",backgroundColor:"transparent",border:"none",cursor:f||k?"not-allowed":"pointer",fontSize:"0.75rem",fontWeight:"500",minHeight:"24px"},onMouseEnter:L=>{!f&&!k&&(L.currentTarget.style.color="#ef4444",L.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)")},onMouseLeave:L=>{u||(L.currentTarget.style.color=z?"#9ca3af":"#6b7280",L.currentTarget.style.backgroundColor="transparent")},children:"Not Helpful"}),d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})]})]})]})]})})};function be(){const t=Ze();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,language:t.language,geo_country:t.geo_country,userId:t.userId,model:t.model,messages:t.messages,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const wt=(t,e)=>{if(!t)return"Get Started";let n="";const r=[/(?:set up|setup|integrate|add|install|use)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,| by)/i,/(?:by|from)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,)/];for(const i of r){const l=t.match(i);if(l&&l[1]){n=l[1].trim();break}}const s=e||n;if(s)return`Integrate ${s.split(/\s+/).slice(0,2).join(" ")}`;const a=t.match(/to\s+set\s+up\s+([a-zA-Z0-9\s]+?)(?:\s+by|\s*[.,]|$)/i);return a&&a[1]?`Integrate ${a[1].trim().split(/\s+/).slice(0,2).join(" ")}`:"Integrate"},je=({recommendation:t,theme:e,className:n="",style:r={},sessionId:s,onLinkClick:a,onPasteToInput:i})=>{var E,v,F,w,I,S,R;const l=t.creative_input||{},p=l.bridge_headline||"",h=l.bridge_description||"",c=l.bridge_prompt||l.bridge_content||"",u=l.product_name||"",_=l.cta_label||"";if(!h&&!c)return null;const f=t.product_id||"",b=t.recommendation_id||"",{sdk:k,sessionId:y}=be(),g=s||y,T=async M=>{if(M.preventDefault(),!!c){if(b&&g)try{const D=(k==null?void 0:k.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",A=await fetch(`${D}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:b,session_id:g,agent_id:t.agent_id,user_id:t.user_id||void 0,is_test:!1})});A.ok?o.log("[AdMesh Bridge] โ
Engagement tracked successfully"):o.warn("[AdMesh Bridge] โ ๏ธ Failed to track engagement:",A.statusText)}catch(D){o.error("[AdMesh Bridge] โ Error tracking engagement:",D)}a&&a(t),i?i(c):typeof window<"u"&&window.__admesh_setMessage&&window.__admesh_setMessage(c)}},x=_||wt(c,u),N=!!x;return d.jsx(ke,{productId:f,recommendationId:t.recommendation_id||"",exposureUrl:t.exposure_url,sessionId:s,className:`admesh-bridge-format ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',padding:"1rem",border:"none",borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",backgroundColor:"transparent",color:(e==null?void 0:e.textColor)||"inherit",...r},children:d.jsxs("div",{"data-admesh-theme":(e==null?void 0:e.mode)||"light",children:[p&&d.jsx("div",{className:"admesh-bridge-headline",style:{marginBottom:h?"0.75rem":N?"1rem":"0",fontSize:((E=e==null?void 0:e.fontSize)==null?void 0:E.large)||"1rem",fontWeight:600,color:(e==null?void 0:e.textColor)||"inherit",lineHeight:"1.4"},children:p}),h&&d.jsx("div",{className:"admesh-bridge-description",style:{marginBottom:N||(v=t.creative_input)!=null&&v.offer_summary?"1rem":"0",lineHeight:"1.6",fontSize:((F=e==null?void 0:e.fontSize)==null?void 0:F.base)||"0.875rem",color:(e==null?void 0:e.textColor)||"inherit"},children:h}),((w=t.creative_input)==null?void 0:w.offer_summary)&&d.jsx("div",{className:"admesh-bridge-offer-summary",style:{marginBottom:N?"1rem":"0",lineHeight:"1.5",fontSize:((I=e==null?void 0:e.fontSize)==null?void 0:I.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:t.creative_input.offer_summary}),N&&d.jsx("div",{style:{marginBottom:"0.75rem"},children:d.jsx("button",{onClick:T,className:"admesh-bridge-cta-button",style:{padding:"0.5rem 1rem",backgroundColor:"#000000",color:"#ffffff",fontSize:((S=e==null?void 0:e.fontSize)==null?void 0:S.small)||"0.875rem",fontWeight:500,borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",border:"none",cursor:"pointer",transition:"background-color 0.2s, opacity 0.2s"},onMouseEnter:M=>{M.currentTarget.style.backgroundColor="#1a1a1a",M.currentTarget.style.opacity="0.9"},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="#000000",M.currentTarget.style.opacity="1"},children:x})}),d.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"0.5rem"},children:d.jsx("div",{className:"admesh-bridge-label",style:{fontSize:((R=e==null?void 0:e.fontSize)==null?void 0:R.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:"Sponsored"})})]})})};function yt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fe={exports:{}};/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/var Oe;function _t(){return Oe||(Oe=1,(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var a="",i=0;i<arguments.length;i++){var l=arguments[i];l&&(a=s(a,r(l)))}return a}function r(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return n.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var i="";for(var l in a)e.call(a,l)&&a[l]&&(i=s(i,l));return i}function s(a,i){return i?a?a+" "+i:a+i:a}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Fe)),Fe.exports}var kt=_t();const _e=yt(kt),Ne=({recommendationId:t,admeshLink:e,productId:n,children:r,trackingData:s,className:a,style:i})=>{const l=m.useRef(null);m.useEffect(()=>{if(!l.current)return;l.current.querySelectorAll("a").forEach(c=>{(!c.hasAttribute("target")||c.getAttribute("target")!=="_blank")&&(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer"))})},[r]);const p=m.useCallback(h=>{const u=h.target.closest("a");u?((!u.href||u.href==="#"||u.href==="")&&e&&(u.href=e),(!u.hasAttribute("target")||u.getAttribute("target")!=="_blank")&&(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):o.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return d.jsx("div",{ref:l,className:a,onClick:p,style:{cursor:"pointer",...i},children:r})};Ne.displayName="AdMeshLinkTracker";const De=({brand:t,title:e="Product Recommendations",showTitle:n=!1,className:r="",cardClassName:s="",onProductClick:a,maxCards:i=10,cardWidth:l="md",theme:p="auto",borderRadius:h="md",shadow:c="sm",sessionId:u,onFeedback:_})=>{const[f,b]=m.useState(null);if(!t)return o.log("[AdMesh Ecommerce Cards] Brand object is required but was not provided"),null;if(!t.products||t.products.length===0)return o.log("[AdMesh Ecommerce Cards] Products array is required but was empty or missing. Both brand info and products are required for ecommerce cards."),null;const k=t.products.slice(0,i),y=()=>{var C;return t.brand_name||((C=t.creative_input)==null?void 0:C.brand_name)||""},g=()=>{var C,B;return((B=(C=t.creative_input)==null?void 0:C.assets)==null?void 0:B.logo_url)||""},T=()=>{var C;return((C=t.creative_input)==null?void 0:C.short_description)||t.description||""},x=C=>C.product_link||C.product_click_url||"",N=C=>C.product_cta_label||"Shop",E=C=>{const B=C.product_price;if(B!=null){if(typeof B=="string")return B;if(typeof B=="number")return`$${B.toFixed(2)}`}return""},v=C=>C.product_name||"",F=C=>{if(C.product_features&&C.product_features.length>0){let B=0;const ae=C.product_id||"";for(let $=0;$<ae.length;$++)B=(B<<5)-B+ae.charCodeAt($),B|=0;const le=Math.abs(B)%C.product_features.length;return C.product_features[le]}return C.product_description||""},w=C=>C.product_image_url||null,I=C=>{const B=C.product_discount;if(B!=null){if(typeof B=="string")return B;if(typeof B=="number")return`${B}%`}return null},S=()=>{switch(l){case"sm":return"w-[305px] min-w-[305px] max-w-[305px]";case"md":return"w-[345px] min-w-[345px] max-w-[345px]";case"lg":return"w-[385px] min-w-[385px] max-w-[385px]";default:return"w-[345px] min-w-[345px] max-w-[345px]"}},R=()=>{switch(h){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},M=()=>{switch(c){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},D=()=>p==="dark"?"bg-gray-900 text-white":p==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",A=C=>{if(a)a(C);else{const B=C.product_link||C.product_click_url;B&&window.open(B,"_blank","noopener,noreferrer")}},j=y(),G=g(),Y=T(),{sessionId:X,userId:re}=be(),q=u||X,ne=t.exposure_url;return d.jsxs(ke,{recommendationId:t.recommendation_id,exposureUrl:ne,sessionId:q,className:_e("w-full",r),children:[d.jsxs("div",{className:_e("bg-white dark:bg-gray-900","border border-gray-200 dark:border-gray-700","rounded-xl","shadow-[0_4px_6px_-1px_rgba(0,0,0,0.1),0_2px_4px_-1px_rgba(0,0,0,0.06)]","dark:shadow-[0_4px_6px_-1px_rgba(0,0,0,0.3),0_2px_4px_-1px_rgba(0,0,0,0.2)]","p-6","transition-shadow duration-200","hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.1),0_4px_6px_-2px_rgba(0,0,0,0.05)]","dark:hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.4),0_4px_6px_-2px_rgba(0,0,0,0.3)]"),children:[(j||G||Y)&&d.jsx("div",{className:"mb-4",children:d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("div",{className:"flex-shrink-0",children:d.jsx("div",{className:"rounded-full overflow-hidden bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center",style:{aspectRatio:"1",width:"48px",height:"48px"},children:d.jsx("img",{src:G,alt:`${j} logo`,className:"w-full h-full object-contain",style:{aspectRatio:"1"},onError:C=>{C.target.style.display="none"}})})}),d.jsxs("div",{className:"flex-1",children:[j&&d.jsx("div",{className:"font-bold text-gray-900 dark:text-white text-base mb-1",children:j}),Y&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:Y})]})]})}),d.jsxs("div",{className:"relative",children:[k.length===0?d.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):d.jsx("div",{className:"flex gap-3 sm:gap-4 overflow-x-auto pb-4 scrollbar-hide",children:k.map(C=>{const B=C.product_id,ae=B,le=x(C),$=N(C),z=E(C),P=v(C),W=F(C),K=I(C),Z=w(C),O=C.product_link||C.product_click_url||"",V=t.recommendation_id;return d.jsx(Ne,{recommendationId:V,admeshLink:O,productId:B,trackingData:{sessionId:q,userId:re},children:d.jsx("div",{className:_e(S(),R(),M(),D(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02] overflow-hidden box-border",s),style:{width:l==="sm"?"305px":l==="lg"?"385px":"345px",minWidth:l==="sm"?"305px":l==="lg"?"385px":"345px",maxWidth:l==="sm"?"305px":l==="lg"?"385px":"345px"},onClick:()=>A(C),children:d.jsxs("div",{className:"p-3 w-full overflow-hidden box-border",children:[d.jsxs("div",{className:"flex items-start gap-3 mb-3 w-full",children:[d.jsx("div",{className:"flex-shrink-0",children:d.jsx("div",{className:"rounded-full overflow-hidden bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center",style:{aspectRatio:"1",width:"48px",height:"48px"},children:Z?d.jsx("img",{src:Z,alt:P,className:"w-full h-full object-cover",style:{aspectRatio:"1"},onError:H=>{H.target.style.display="none";const Q=H.target.parentElement;Q&&(Q.innerHTML=`
<svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
`)}}):d.jsx("svg",{className:"w-6 h-6 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),d.jsxs("div",{className:"flex-1 min-w-0 max-w-full overflow-hidden",children:[P&&d.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white mb-1 leading-tight break-words overflow-wrap-anywhere",children:P}),W&&d.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 break-words overflow-wrap-anywhere line-clamp-2",title:W,children:W})]})]}),d.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[z&&d.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:z}),K&&d.jsxs("span",{className:"text-xs text-red-600 dark:text-red-400 font-medium",children:[K," OFF"]})]}),le&&d.jsx("button",{onClick:H=>{H.stopPropagation(),A(C)},className:"px-3 py-1.5 text-xs font-medium text-gray-100 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 rounded-md transition-colors duration-200 whitespace-nowrap",children:$})]})]})})},ae)})}),k.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),d.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),d.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),_&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 mr-1",children:"Was this helpful?"}),d.jsx("button",{onClick:()=>{f===null&&(b("helpful"),_(!0,t.recommendation_id||""))},disabled:f!==null,className:_e("px-2 py-1 text-xs font-medium rounded transition-colors duration-200",f==="helpful"?"bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 cursor-default":"bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer",f!==null&&f!=="helpful"&&"opacity-50 cursor-not-allowed"),title:"Helpful",children:d.jsxs("span",{className:"flex items-center gap-1",children:[d.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"})}),"Helpful"]})}),d.jsx("button",{onClick:()=>{f===null&&(b("not-helpful"),_(!1,t.recommendation_id||""))},disabled:f!==null,className:_e("px-2 py-1 text-xs font-medium rounded transition-colors duration-200",f==="not-helpful"?"bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 cursor-default":"bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer",f!==null&&f!=="not-helpful"&&"opacity-50 cursor-not-allowed"),title:"Not helpful",children:d.jsxs("span",{className:"flex items-center gap-1",children:[d.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4a2 2 0 00-2-2h-1.528c-.163 0-.326.02-.485.06L9 4m7 10H9m0 0H5m4 0v5a2 2 0 002 2h2M9 9h.01"})}),"Not helpful"]})})]})]})]}),d.jsx("style",{dangerouslySetInnerHTML:{__html:`
.scrollbar-hide {
-ms-overflow-style: none;
scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
`}})]})},Xe=({recommendations:t,summaryText:e,theme:n,className:r,style:s,onLinkClick:a,onPasteToInput:i,sessionId:l,response:p})=>{var f;const h=t||(p==null?void 0:p.recommendations)||[];let c=e||(p==null?void 0:p.tail_summary);const u=h.filter(b=>b&&typeof b=="object"&&b.recommendation_id);if(!u||u.length===0)return o.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;if(!c&&u.length>0&&((f=u[0])!=null&&f.creative_input)){const b=u[0].creative_input;c=b.long_description||b.context_snippet||b.short_description||void 0}o.log(`[AdMeshLayout] Rendering with ${u.length} valid recommendations`);const _=()=>{if(u.length>0){const b=u[0],k=(b==null?void 0:b.creative_input)||{},y=(b==null?void 0:b.preferred_format)||(k==null?void 0:k.preferred_format);if(o.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:y,creativeInputKeys:Object.keys(k),recommendationKeys:Object.keys(b||{})}),y==="product_card"){const x=(b==null?void 0:b.products)||(k==null?void 0:k.products)||[];if(x&&x.length>0)return o.log(`[AdMeshLayout] ๐๏ธ Rendering product_card format with ${x.length} products`),d.jsx(De,{brand:b,theme:n,sessionId:l});o.warn("[AdMeshLayout] product_card format detected but no products array, falling back to tail")}if(!!k.bridge_prompt||!!k.bridge_content||y==="bridge")return o.log("[AdMeshLayout] ๐ฏ โ
Rendering bridge format"),d.jsx(je,{recommendation:b,theme:n,sessionId:l,onLinkClick:a,onPasteToInput:i});o.log("[AdMeshLayout] โ ๏ธ Bridge format NOT detected, falling back to other formats")}return c?d.jsx(Pe,{summaryText:c,recommendations:u,theme:n,onLinkClick:a,sessionId:l}):null};return d.jsx("div",{className:`admesh-layout ${r}`,style:{fontFamily:(n==null?void 0:n.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:_()})},At=({className:t,size:e=20})=>d.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[d.jsx("path",{d:"M5 12h14"}),d.jsx("path",{d:"M12 5v14"})]}),Ce=({recommendation:t,theme:e,sdk:n,sessionId:r,onExecuteQuery:s})=>{const a=t.followup_query,i=t.followup_engagement_url,l=t.followup_exposure_url,p=t.recommendation_id;if(!a||!i||!l)return o.log("[AdMeshFollowup] Missing followup_query, followup_engagement_url, or followup_exposure_url - not rendering"),null;const h=async()=>{try{i&&p&&(o.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await n.fireFollowupEngagement(i,p,r)),s&&a?(o.log(`[AdMeshFollowup] ๐ Executing query: ${a}`),await s(a)):o.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(c){o.error("[AdMeshFollowup] โ Error handling follow-up click:",c)}};return e!=null&&e.mode,d.jsx(ke,{productId:t.product_id||"",recommendationId:p||"",exposureUrl:l,sessionId:r,className:"admesh-followup-container",style:{width:"100%"},children:d.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[d.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),d.jsxs("div",{onClick:h,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&h()},"aria-label":`Sponsored follow-up: ${a}`,children:[d.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:a}),d.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),d.jsx(At,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})};class Je{constructor(e){te(this,"firedExposures",new Set);te(this,"debug",!1);te(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,n,r){const s=`${r}_${n}`;if(this.firedExposures.has(s)){this.debug&&o.log("[Tracker] Exposure already fired");return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&o.warn("[Tracker] Failed to fire exposure")}),this.debug&&o.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&o.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,n,r,s){const a=`${r}_${n}`;if(this.firedExposures.has(a)){this.debug&&o.log("[Tracker] MRC exposure already fired");return}return new Promise(i=>{let l=null,p=null;const h=new IntersectionObserver(_=>{_.forEach(f=>{f.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?l===null&&(l=Date.now(),this.debug&&o.log("[Tracker] Ad reached MRC visibility threshold"),p=setTimeout(()=>{this.fireExposure(e,n,r),h.disconnect(),i()},this.mrcThreshold.minimumDurationMs)):l!==null&&(p&&(clearTimeout(p),p=null),l=null,this.debug&&o.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});h.observe(s);const u=setTimeout(()=>{h.disconnect(),p&&clearTimeout(p),i()},3e4);s.__admeshTrackerCleanup=()=>{h.disconnect(),p&&clearTimeout(p),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,n,r){this.fireExposure(e,n,r)}fireFollowupEngagement(e,n,r){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:r})}).catch(s=>{this.debug&&o.warn("[Tracker] Failed to fire followup engagement (non-critical):",s)}).then(()=>{})}}const Le=({apiKey:t,sessionId:e,theme:n,apiBaseUrl:r,language:s,geo_country:a,userId:i,model:l,messages:p,children:h})=>{const c=m.useRef(null),[u,_]=m.useState(new Set);m.useEffect(()=>{if(!e||e.trim()===""){o.error("[AdMeshProvider] โ sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");return}},[e]),m.useEffect(()=>{if(!t){o.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){o.error("[AdMeshProvider] โ Cannot initialize SDK: sessionId is required and must be provided by the platform");return}try{c.current=new tt({apiKey:t,theme:n,apiBaseUrl:r}),o.log("[AdMeshProvider] โ
AdMesh SDK initialized"),r&&o.log("[AdMeshProvider] ๐ Using custom API base URL")}catch{o.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK")}return()=>{o.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,n,r]);const f={sdk:c.current,apiKey:t,sessionId:e,theme:n,language:s,geo_country:a,userId:i,model:l,messages:p,processedMessageIds:u,markMessageAsProcessed:b=>{_(k=>{const y=new Set(k);return y.add(b),y})},isMessageProcessed:b=>u.has(b)};return d.jsx(Ee.Provider,{value:f,children:h})};class et{constructor(){te(this,"roots",new Map)}async render(e){var n;try{o.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const r=e.response.recommendations||[];if(r.length===0){o.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw o.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);o.log("[AdMeshRenderer] โ
Container ready");const a=this.roots.get(e.containerId);a&&(o.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),a.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const i=ze.createRoot(s),l=((n=r[0])==null?void 0:n.tail_summary)||"";o.log("[AdMeshRenderer] ๐ Rendering recommendations");const p=e.onPasteToInput||(typeof window<"u"?window.__admesh_onPasteToInput:void 0);if(i.render(d.jsx(Le,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,geo_country:e.geo_country,userId:e.userId,model:e.model,messages:e.messages,children:d.jsx(Xe,{recommendations:r,summaryText:l,theme:e.theme,sessionId:e.sessionId,onPasteToInput:p})})),s.style.display="block",o.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,i),e.followups_container_id){const h=r[0];h!=null&&h.followup_query&&(h!=null&&h.followup_engagement_url)&&await this.renderFollowup({containerId:e.followups_container_id,recommendation:h,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,apiKey:e.apiKey,apiBaseUrl:e.apiBaseUrl,onExecuteQuery:e.onExecuteQuery})}}catch(r){throw o.error("[AdMeshRenderer] โ Error rendering recommendations"),r}}async renderFollowup(e){try{o.log(`[AdMeshRenderer] ๐ฏ Rendering follow-up in container: ${e.containerId}`);const n=document.getElementById(e.containerId);if(!n){o.warn(`[AdMeshRenderer] โ ๏ธ Followups container not found: ${e.containerId}`);return}const r=this.roots.get(e.containerId);r&&(o.log("[AdMeshRenderer] ๐งน Cleaning up existing followup root"),r.unmount(),this.roots.delete(e.containerId)),n.innerHTML="";const s=ze.createRoot(n);s.render(d.jsx(Le,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,children:d.jsx(Ce,{recommendation:e.recommendation,theme:e.theme,tracker:e.tracker,sessionId:e.sessionId,onExecuteQuery:e.onExecuteQuery})})),n.style.display="block",o.log("[AdMeshRenderer] โ
Follow-up rendered successfully"),this.roots.set(e.containerId,s)}catch{o.error("[AdMeshRenderer] โ Error rendering follow-up")}}unmount(e){const n=this.roots.get(e);if(n){n.unmount(),this.roots.delete(e);const r=document.getElementById(e);r&&(r.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class tt{constructor(e){te(this,"config");te(this,"apiBaseUrl");te(this,"renderer",null);te(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static createSession(){const e=Date.now(),n=Math.random().toString(36).substring(2,15);return`session_${e}_${n}`}static createMessageId(e){const n=Date.now(),r=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${n}_${r}`:`msg_${n}_${r}`}getRenderer(){return this.renderer||(this.renderer=new et),this.renderer}getTracker(){return this.tracker||(this.tracker=new Je({apiKey:this.config.apiKey})),this.tracker}async showRecommendations(e){try{if(!e.session_id||e.session_id.trim()==="")throw new Error("session_id is required and must be provided by the platform. The SDK never generates sessionId automatically.");if(!e.messageId||e.messageId.trim()==="")throw new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");const n=await this.fetchRecommendationFromAIPContext({query:e.query,sessionId:e.session_id,messageId:e.messageId,platformSurface:e.platformSurface,model:e.model,messages:e.messages,language:e.locale,geo_country:e.geo,userId:e.userId}),r=this.convertAIPResponseToRecommendation(n),s={session_id:n.session_id,message_id:`msg_${n.recommendation_id}`,recommendations:[r]},a=this.getRenderer(),i=this.getTracker();await a.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:i,sessionId:e.session_id,apiKey:this.config.apiKey,apiBaseUrl:this.apiBaseUrl,language:e.locale,geo_country:e.geo,userId:e.userId,model:e.model,messages:e.messages,onPasteToInput:e.onPasteToInput,onExecuteQuery:e.onExecuteQuery})}catch(n){throw o.error("[AdMeshSDK] Error showing recommendations"),n}}async fetchRecommendationFromAIPContext(e){var u,_,f;const n=`${this.apiBaseUrl}/aip/context`;if(o.log("[AdMeshSDK] ๐ฅ fetchRecommendationFromAIPContext called"),!e.sessionId||e.sessionId.trim()===""){const b=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw o.error("[AdMeshSDK] โ sessionId not provided by platform - cannot process request"),b}const r=e.messageId;if(!r||r.trim()===""){const b=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw o.error("[AdMeshSDK] โ messageId not provided by platform - cannot process request"),b}const s=e.messages?e.messages.length:0,a=(typeof window<"u"&&window.navigator,"web"),i=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",l={spec_version:"1.0.0",message_id:r,timestamp:new Date().toISOString(),producer:{agent_id:"placeholder",agent_role:"publisher",software:"admesh_ui_sdk",software_version:e.model||"1.0.0"},context:{language:e.language||"en-US",publisher:"placeholder",placement:{ad_unit:e.platformSurface||"web"},device:{platform:a,form_factor:i},geography:{country:e.geo_country||"US"}},identity:{namespace:"platform_user",value_hash:e.userId||"",confidence:1},extensions:{aip:{session_id:e.sessionId,turn_index:s,query_text:e.query,messages:e.messages||[],cpx_floor:0}}};(!l.extensions.aip.query_text||!l.extensions.aip.query_text.trim())&&o.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const p=JSON.stringify(l);o.log("[AdMeshSDK] ๐ค Sending request to /aip/context");const h=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:p});if(!h.ok){const k=(await h.json().catch(()=>({}))).detail||`HTTP ${h.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${k}`)}const c=await h.json();return o.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{hasCreative:!!c.creative,creativeFormat:(u=c.creative)==null?void 0:u.format,creativeBridgeContent:(_=c.creative)!=null&&_.bridge_content?c.creative.bridge_content.substring(0,50)+"...":void 0,hasWinningBid:!!c.winning_bid,winningBidPreferredFormat:(f=c.winning_bid)==null?void 0:f.preferred_format,topLevelKeys:Object.keys(c)}),c}convertAIPResponseToRecommendation(e){var F,w,I,S,R,M,D;const n=e;let r=e.creative_input||{};const s=n.creative||{},a=s.format||n.format||((F=n.winning_bid)==null?void 0:F.preferred_format),i=s.headline,l=s.bridge_headline,p=s.bridge_description,h=s.bridge_prompt||s.bridge_content,c=h||r.bridge_prompt||r.bridge_content,u=s.cta_label,_=u||r.cta_label,f=l||r.bridge_headline,b=p||r.bridge_description;o.log("[AdMeshSDK] ๐ Extracting from response:",