admesh-ui-sdk 1.0.40 โ†’ 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,119 +1,149 @@
1
- "use strict";var Or=Object.defineProperty;var Vr=(t,e,o)=>e in t?Or(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var Be=(t,e,o)=>Vr(t,typeof e!="symbol"?e+"":e,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),Kr=require("react-dom/client"),l=require("react"),Gr=require("react-dom");let Dt=!1;var pr;try{typeof globalThis.importMeta<"u"&&((pr=globalThis.importMeta.env)!=null&&pr.PROD)&&(Dt=!0)}catch{}Dt||(Dt=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const a={log:(...t)=>{Dt||console.log(...t)},warn:(...t)=>{Dt||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{Dt||console.info(...t)},debug:(...t)=>{Dt||console.debug(...t)}};function Yr(t,e,o){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...o}}function Qr(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function Xr(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,i=e.height,c=e.width;if(i===0||c===0)return 0;const u=Math.max(0,e.top),b=Math.min(o,e.bottom),h=Math.max(0,e.left),_=Math.min(s,e.right),d=Math.max(0,b-u),m=Math.max(0,_-h),M=d*m,x=i*c;return x>0?M/x:0}function Xn(){const t=window.innerHeight,e=document.documentElement.scrollHeight,o=window.pageYOffset||document.documentElement.scrollTop,s=e-t;return s<=0?100:Math.min(100,o/s*100)}function Jr(t){const e=t.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+o,left:e.left+s}}function Zr(t){const e=t.getBoundingClientRect(),o=Jr(t),s=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,c=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Qr(s),viewportWidth:s,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:c,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function eo(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function to(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function Jn(t=new Date){return t.toISOString()}function no(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function Zn(t,e){let o;return function(...i){o||(t(...i),o=!0,setTimeout(()=>o=!1,e))}}const ro={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let oo=ro,so=!1;function hr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:i,config:c}){const u={...oo,...c},b=l.useRef(eo()),[h,_]=l.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:Jn(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:u.enabled}),d=l.useRef(null),m=l.useRef(null),M=l.useRef(null),x=l.useRef(null),w=l.useRef(null),g=l.useRef([]),p=l.useRef([]),y=l.useRef(null),j=l.useCallback(S=>{u.debug&&a.log(`[AdMesh Viewability] ${S}`)},[u.debug]),R=l.useCallback(async(S,L)=>{if(!(!u.enabled||so||!i.current||!d.current)&&(j(`Analytics disabled - skipping event: ${S}`),u.onEvent)){const W=Zr(i.current),N={eventType:S,timestamp:Jn(),sessionId:b.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:h.timeMetrics,engagementMetrics:h.engagementMetrics,contextMetrics:W,mrcStandards:d.current,isViewable:h.isViewable,metadata:L};u.onEvent(N)}},[u,t,e,o,s,i,h,j]),q=l.useCallback(async()=>{p.current.length!==0&&(j("Analytics disabled - clearing batch without sending"),p.current=[],y.current&&(clearTimeout(y.current),y.current=null))},[j]),A=l.useCallback(Zn(()=>{if(!i.current)return;const S=Xr(i.current),L=Date.now(),W=new Date(h.timeMetrics.loadedAt).getTime();_(N=>{const z={...N};S>0&&g.current.push(S);const P=N.isVisible,$=S>0;if($&&!P)m.current=L,z.engagementMetrics.viewportEnterCount++,z.timeMetrics.timeToFirstVisible||(z.timeMetrics.timeToFirstVisible=L-W,z.engagementMetrics.scrollDepthAtFirstVisible=Xn(),R("ad_visible"));else if(!$&&P){if(m.current){const Y=L-m.current;z.timeMetrics.totalVisibleDuration+=Y,m.current=null}z.engagementMetrics.viewportExitCount++,R("ad_hidden")}else if($&&P&&m.current){const Y=L-m.current;z.timeMetrics.totalVisibleDuration+=Y,m.current=L}if(z.isVisible=$,z.visibilityPercentage=S,S>z.engagementMetrics.maxVisibilityPercentage&&(z.engagementMetrics.maxVisibilityPercentage=S),g.current.length>0&&(z.engagementMetrics.averageVisibilityPercentage=no(g.current)),d.current){const Y=N.isViewable,Z=to(S,z.timeMetrics.totalVisibleDuration,d.current);if(Z&&!Y)z.isViewable=!0,z.timeMetrics.timeToViewable=L-W,M.current=L,R("ad_viewable");else if(Z&&Y&&M.current){const xe=L-M.current;z.timeMetrics.totalViewableDuration+=xe,M.current=L}}return z.engagementMetrics.currentScrollDepth=Xn(),z})},100),[i,h.timeMetrics.loadedAt,R]);return l.useEffect(()=>{if(!i.current)return;const S=i.current.getBoundingClientRect();d.current=Yr(S.width,S.height,u.mrcStandards),j("Initialized MRC standards"),R("ad_loaded")},[i,u.mrcStandards,j,R]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=new IntersectionObserver(L=>{L.forEach(()=>{A()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return S.observe(i.current),()=>{S.disconnect()}},[u.enabled,i,A]),l.useEffect(()=>{if(!u.enabled)return;const S=Zn(()=>{A()},100);return window.addEventListener("scroll",S,{passive:!0}),()=>window.removeEventListener("scroll",S)},[u.enabled,A]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{x.current=Date.now(),_(N=>({...N,engagementMetrics:{...N.engagementMetrics,hoverCount:N.engagementMetrics.hoverCount+1}})),R("ad_hover_start")},W=()=>{if(x.current){const N=Date.now()-x.current;_(z=>({...z,timeMetrics:{...z.timeMetrics,totalHoverDuration:z.timeMetrics.totalHoverDuration+N}})),x.current=null,R("ad_hover_end",{hoverDuration:N})}};return S.addEventListener("mouseenter",L),S.addEventListener("mouseleave",W),()=>{S.removeEventListener("mouseenter",L),S.removeEventListener("mouseleave",W)}},[u.enabled,i,R]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{w.current=Date.now(),R("ad_focus")},W=()=>{if(w.current){const N=Date.now()-w.current;_(z=>({...z,timeMetrics:{...z.timeMetrics,totalFocusDuration:z.timeMetrics.totalFocusDuration+N}})),w.current=null,R("ad_blur",{focusDuration:N})}};return S.addEventListener("focus",L),S.addEventListener("blur",W),()=>{S.removeEventListener("focus",L),S.removeEventListener("blur",W)}},[u.enabled,i,R]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{_(W=>({...W,engagementMetrics:{...W.engagementMetrics,wasClicked:!0}})),R("ad_click")};return S.addEventListener("click",L),()=>{S.removeEventListener("click",L)}},[u.enabled,i,R]),l.useEffect(()=>()=>{const S=Date.now(),L=new Date(h.timeMetrics.loadedAt).getTime(),W=S-L;_(N=>({...N,timeMetrics:{...N.timeMetrics,sessionDuration:W}})),R("ad_unloaded",{sessionDuration:W}),q()},[]),h}const Zt=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:i,sessionId:c,triggerExposureUrl:u=!0,children:b,config:h,className:_,style:d,onViewabilityChange:m,onVisible:M,onViewable:x,onClick:w})=>{const g=l.useRef(null),p=l.useRef(!1),y=hr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:g,config:h}),j=l.useRef(y.isViewable);l.useEffect(()=>{p.current=!1,j.current=!1},[i,s,c]),l.useEffect(()=>{y.isViewable!==j.current&&(j.current=y.isViewable,m&&m(y.isViewable),y.isViewable&&x&&x(),y.isViewable&&!p.current&&u&&(a.log("[AdMeshViewabilityTracker] ๐ŸŽฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:i?"present":"MISSING",sessionId:c?"present":"MISSING",recommendationId:s}),i&&c?(p.current=!0,a.log("[AdMeshViewabilityTracker] ๐Ÿ”ฅ Firing exposure pixel:",i),fetch(i,{method:"GET",keepalive:!0}).then(()=>{a.log("[AdMesh] โœ… Exposure pixel fired successfully")}).catch(A=>{a.warn("[AdMesh] โš ๏ธ Failed to fire exposure pixel:",A),p.current=!1})):a.warn("[AdMeshViewabilityTracker] โš ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!i,hasSessionId:!!c})))},[y.isViewable,m,x,i,c,s,u]);const R=l.useRef(y.isVisible);l.useEffect(()=>{y.isVisible!==R.current&&(R.current=y.isVisible,y.isVisible&&M&&M())},[y.isVisible,M]);const q=()=>{w&&w()};return r.jsx("div",{ref:g,className:_,style:d,onClick:q,"data-admesh-viewability-tracker":!0,"data-recommendation-id":s,"data-is-viewable":y.isViewable,"data-is-visible":y.isVisible,"data-visibility-percentage":y.visibilityPercentage.toFixed(2),children:b})};Zt.displayName="AdMeshViewabilityTracker";const er=t=>{try{return new URL(t),!0}catch{return!1}},Ft=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",st=t=>Ft(t)||void 0,io=t=>t&&t.trim()?t.trim():"",ao=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return Ft(t)},jn=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:c=!0,onDelegationConsent:u,onDelegationActivated:b,onStartDelegation:h})=>{var ye,Ie,I,Ue,tt,ht,kt,Ye,St;if(!t||t.length===0)return a.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const _=t[0],d=_==null?void 0:_.recommendation,m=d==null?void 0:d.creative,M=_==null?void 0:_.tracking,x=_==null?void 0:_.delegation,w=(_==null?void 0:_.recommendation_id)||"",g=(d==null?void 0:d.offerId)||"",p=(m==null?void 0:m.brand_name)||"",y=(m==null?void 0:m.headline)||"",j=(m==null?void 0:m.description)||"",R=(m==null?void 0:m.logo_url)||"",q=(M==null?void 0:M.click_url)||(m==null?void 0:m.landing_page_url)||"",A=(M==null?void 0:M.exposure_url)||"",S=(d==null?void 0:d.disclosure)||"Sponsored",L=(m==null?void 0:m.products)||[],W=L.slice(0,4),N=L.length>1,P=((d==null?void 0:d.format)||"tail")==="bridge",$=(x==null?void 0:x.available)===!0,Y=P&&$,Z=(x==null?void 0:x.brand_name)||p,xe="Talk to Agent",F=io(m==null?void 0:m.cta_text),me=!N&&!!F&&!!q;if(!p&&!y&&!j)return a.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:w}),null;const ge=y&&y!==p?y:p,de=j,Q=p.trim().toLowerCase(),G=ge.trim().toLowerCase(),Ne=!!p&&Q!==G,[we,Ce]=l.useState(!1),ie=l.useRef(null);l.useEffect(()=>()=>{ie.current&&(ie.current(!1),ie.current=null)},[]);const ve=te=>{var Re;(Re=ie.current)==null||Re.call(ie,te),ie.current=null,Ce(!1)},_e=async()=>u?await u(_):await new Promise(te=>{ie.current=te,Ce(!0)}),ze=(te,Re)=>{Re&&Re.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:w,productId:g,clickUrl:q,source:te}).catch(()=>{a.error(`[AdMesh] Failed to track ${te} click`)})},Ee=()=>{N||!q||(ze("compact_tail_ad_card"),typeof window<"u"&&window.open(q,"_blank","noopener,noreferrer"))},lt=te=>{N||!q||(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),Ee())},et=async()=>{if(w&&i)try{const te=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",Re=await fetch(`${te}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:w,session_id:i,is_test:!1})});Re.ok||a.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",Re.statusText)}catch(te){a.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",te)}},B=async te=>{if(te.preventDefault(),te.stopPropagation(),!_||!Y||(ze("compact_tail_ad_delegation_cta"),await et(),!await _e()))return;const Je=x!=null&&x.available?{recommendation_id:_.recommendation_id,brand_id:st(x.brand_id),brand_name:st(x.brand_name||(m==null?void 0:m.brand_name)),eligibility_reason:st(x.eligibility_reason),delegate_reason:st(x.delegate_reason),session_goal:st(x.session_goal),desired_outcome_type:x.desired_outcome_type,required_user_inputs:Array.isArray(x.required_user_inputs)?x.required_user_inputs.filter(Ke=>typeof Ke=="string"):[],required_consent_types:Array.isArray(x.required_consent_types)?x.required_consent_types.filter(Ke=>typeof Ke=="string"):[],success_outcome:st(x.success_outcome),fallback_message:st(x.fallback_message),session_mode:st(x.session_mode),status:st(x.status),capabilities:x.capabilities||[],allowed_data_types:x.allowed_data_types||[],consent_requirements:x.consent_requirements||[],auth_model:st(x.auth_model),handoff_protocol:x.handoff_protocol&&typeof x.handoff_protocol=="object"?x.handoff_protocol:void 0,supported_actions:x.supported_actions||[],metadata:x.metadata&&typeof x.metadata=="object"?x.metadata:void 0,platform_response:_}:null;if(b&&Je){await b(Je);return}if(h){await h(_);return}},[k,O]=l.useState(!1),v=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,C=(e==null?void 0:e.surfaceColor)||((Ie=(ye=e==null?void 0:e.components)==null?void 0:ye.card)==null?void 0:Ie.backgroundColor)||(v?"#111827":"#ffffff"),ee=(e==null?void 0:e.borderColor)||((Ue=(I=e==null?void 0:e.components)==null?void 0:I.card)==null?void 0:Ue.borderColor)||(v?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),T=((tt=e==null?void 0:e.shadows)==null?void 0:tt.medium)||((kt=(ht=e==null?void 0:e.components)==null?void 0:ht.card)==null?void 0:kt.boxShadow)||(v?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),ue="#2563eb",V=v?"#9ca3af":"#6b7280",se=v?"#e5e7eb":"#374151",pe=v?"#f9fafb":"#0f172a",oe=v?"rgba(255, 255, 255, 0.04)":"#f8fafc",K="50px",Me=Y||me?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[Y?r.jsx("button",{type:"button",onClick:B,style:{background:"none",border:"none",padding:0,color:ue,fontSize:"12px",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:xe}):null,me?r.jsx("a",{href:q,target:"_blank",rel:"noopener noreferrer",onClick:te=>ze("compact_tail_ad_cta",te),style:{color:ue,fontSize:"12px",fontWeight:600,textDecoration:"none"},children:F}):null]}):null;return r.jsxs(Zt,{productId:g,recommendationId:w,exposureUrl:A,sessionId:i,triggerExposureUrl:c,className:`admesh-compact-tail-ad ${o}`,style:{all:"initial",boxSizing:"border-box",display:"block",fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[r.jsx("style",{children:`
2
- .admesh-compact-tail-ad,
3
- .admesh-compact-tail-ad * {
4
- box-sizing: border-box;
5
- }
6
-
7
- .admesh-compact-line-clamp-1 {
8
- overflow: hidden;
9
- display: -webkit-box;
10
- -webkit-box-orient: vertical;
11
- -webkit-line-clamp: 1;
12
- }
13
-
14
- .admesh-compact-line-clamp-2 {
15
- overflow: hidden;
16
- display: -webkit-box;
17
- -webkit-box-orient: vertical;
18
- -webkit-line-clamp: 2;
19
- }
20
-
21
- .admesh-compact-tail-scroll {
22
- -ms-overflow-style: none;
23
- scrollbar-width: none;
24
- }
25
-
26
- .admesh-compact-tail-scroll::-webkit-scrollbar {
27
- display: none;
28
- }
29
- `}),r.jsxs("div",{role:!N&&q?"link":void 0,tabIndex:!N&&q?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((St=(Ye=e==null?void 0:e.components)==null?void 0:Ye.card)==null?void 0:St.borderRadius)||"14px",border:`1px solid ${ee}`,background:C,boxShadow:T,minWidth:0,cursor:!N&&q?"pointer":void 0},onClick:Ee,onKeyDown:lt,children:[r.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[r.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:v?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!k&&R&&er(R)?r.jsx("img",{src:R,alt:`${p} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>O(!0)}):r.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:V},children:(p||"A").charAt(0).toUpperCase()})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[r.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"11px",color:V},children:Ne?p:""}),r.jsx("div",{style:{flexShrink:0,fontSize:"10px",color:V,textTransform:"uppercase",letterSpacing:"0.08em"},children:S})]}),!N&&r.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",lineHeight:1.3,fontWeight:700,color:pe,marginBottom:"4px"},title:ge,children:ge}),de&&r.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"12px",lineHeight:1.35,color:se},title:de,children:de})]})]}),N&&r.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:W.map(te=>{const Re=Ft(te.product_name)||"Product",Je=Ft(te.product_link)||Ft(te.product_url)||q||"#",Ke=ao(te.product_price,te.product_currency),ft=Ft(te.product_image_url),nt=ft&&er(ft)?ft:"",He=Je!=="#";return r.jsx("a",{href:Je,target:He?"_blank":void 0,rel:He?"noopener noreferrer":void 0,onClick:$e=>ze(`compact_tail_ad_product_${te.product_id||"item"}`,$e),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${ee}`,borderRadius:"12px",background:oe,padding:"8px",flexShrink:0},children:r.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[r.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:v?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:V,fontSize:"12px",fontWeight:700},children:nt?r.jsx("img",{src:nt,alt:Re,style:{width:"100%",height:"100%",objectFit:"cover"}}):Re.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("div",{style:{fontSize:"12px",lineHeight:1.25,fontWeight:600,color:pe,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:Re,children:Re}),r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:Ke&&r.jsx("span",{style:{fontSize:"12px",fontWeight:700,color:pe},children:Ke})})]})]})},te.product_id||`${w}-${Re}`)})}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:N?0:K},children:[r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:Me}),N&&L.length>W.length?r.jsxs("span",{style:{fontSize:"10px",color:V},children:["+",L.length-W.length," more"]}):null]}),we?r.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${ee}`,borderRadius:"12px",background:oe,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:ue},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:pe,fontWeight:600},children:["Allow ",Z||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:se},children:"The agent will only use the details you choose to share for this request."})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[r.jsx("button",{type:"button",onClick:te=>{te.preventDefault(),te.stopPropagation(),ve(!1)},style:{borderRadius:"10px",border:`1px solid ${ee}`,background:C,color:pe,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:te=>{te.preventDefault(),te.stopPropagation(),ve(!0)},style:{borderRadius:"10px",border:"none",background:ue,color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})},fr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:c,onDelegationActivated:u,onStartDelegation:b})=>{const h=t.filter(d=>d&&typeof d=="object"&&typeof d.recommendation_id=="string"&&d.recommendation_id.length>0);if(!h||h.length===0)return a.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;a.log(`[AdMeshLayout] Rendering with ${h.length} valid recommendations`);const _=()=>{var d;if(h.length>0){const m=h[0],M=(d=m.recommendation)==null?void 0:d.format;a.log("[AdMeshLayout] ๐Ÿ” Checking format:",{preferredFormat:M,recommendationKeys:Object.keys(m||{})}),(M==="product_card"||M==="weave"||M==="bridge")&&a.warn(`[AdMeshLayout] ${M} format requested, falling back to tail for canonical render payload`)}return r.jsx(jn,{recommendations:h,theme:e,sessionId:i,onDelegationConsent:c,onDelegationActivated:u,onStartDelegation:b})};return r.jsx("div",{className:`admesh-layout ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:_()})};class gr{constructor(e){Be(this,"firedExposures",new Set);Be(this,"debug",!1);Be(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,o,s){const i=`${s}_${o}`;if(this.firedExposures.has(i)){this.debug&&a.log("[Tracker] Exposure already fired");return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&a.warn("[Tracker] Failed to fire exposure")}),this.debug&&a.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&a.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,i){const c=`${s}_${o}`;if(this.firedExposures.has(c)){this.debug&&a.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let b=null,h=null;const _=new IntersectionObserver(M=>{M.forEach(x=>{x.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?b===null&&(b=Date.now(),this.debug&&a.log("[Tracker] Ad reached MRC visibility threshold"),h=setTimeout(()=>{this.fireExposure(e,o,s),_.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):b!==null&&(h&&(clearTimeout(h),h=null),b=null,this.debug&&a.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});_.observe(i);const m=setTimeout(()=>{_.disconnect(),h&&clearTimeout(h),u()},3e4);i.__admeshTrackerCleanup=()=>{_.disconnect(),h&&clearTimeout(h),clearTimeout(m)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,o,s){this.fireExposure(e,o,s)}fireFollowupEngagement(e,o,s){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s})}).catch(i=>{this.debug&&a.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const En=l.createContext(void 0);function Rn(){const t=l.useContext(En);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function lo(t){const e=t.split("/").filter(Boolean),i=(e[e.length-1]||e[e.length-2]||"").replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i?i.replace(/\b\w/g,c=>c.toUpperCase()):"This page"}function xr(){var t;try{console.log("[AdMesh] Starting direct headings extraction...");const e=_=>_.replace(/\s+/g," ").trim(),o=()=>{var p;const _=["article","main article","main",'[role="main"]',"[data-admesh-article]",".article-content",".post-content",".entry-content",".content"],d=["script","style","noscript","svg","canvas","iframe","nav","header","footer","aside",'[aria-hidden="true"]',"[data-admesh-ignore]",".admesh-publisher-assistant-root",".admesh-publisher-assistant-reactMount",".admesh-publisher-assistant-floating",".admesh-publisher-assistant-inline"].join(","),x=(((p=_.map(y=>document.querySelector(y)).filter(y=>!!y).map(y=>{const j=y.cloneNode(!0);j.querySelectorAll(d).forEach(q=>q.remove());const R=e(j.textContent||"");return{element:y,text:R}}).filter(y=>y.text.length>=200).sort((y,j)=>j.text.length-y.text.length)[0])==null?void 0:p.element)||document.body).cloneNode(!0);x.querySelectorAll(d).forEach(y=>y.remove());const w=Array.from(x.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(y=>e(y.textContent||"")).filter(y=>y.length>=24);return(w.length>0?w.join(`
30
- `):e(x.textContent||"")).slice(0,6e3)},s=lo(window.location.pathname||"/"),i=e(document.title||"")||s,u=(()=>{const _=[],d=document.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(d).forEach(m=>{const M=e(m.textContent||"");M.length>0&&_.push(M)}),_})(),b=u.length>0?u:[i||s],h={title:i,headings:b,article_text:o(),url:window.location.href,domain:window.location.hostname,extracted_at:new Date().toISOString()};return console.log("[AdMesh] Extracted headings:",{title:h.title,headingsCount:h.headings.length,articleTextLength:((t=h.article_text)==null?void 0:t.length)||0,domain:h.domain}),h}catch(e){return console.error("[AdMesh] Error in direct headings extraction:",e),null}}function co(t){return!!(t&&typeof t=="object"&&"recommendation_id"in t&&"status"in t)}function uo(t){var s,i,c,u,b,h,_,d,m,M,x;if(!t||typeof t!="object")return;if(co(t))return t;const e=t;if(!e.recommendation_id)return;const o=(e.products||[]).map(w=>{var g,p;return{product_id:w.product_id||"",product_link:w.product_link||w.product_click_url||e.click_url||e.url||"",product_name:w.product_name||e.title||((g=e.creative_input)==null?void 0:g.product_name)||"",product_description:w.product_description||"",product_price:w.product_price??void 0,product_discount:w.product_discount??void 0,product_currency:w.product_currency,product_discount_type:w.product_discount_type,product_cta_label:w.product_cta_label||((p=e.creative_input)==null?void 0:p.cta_label),product_image_url:w.product_image_url,product_features:w.product_features}});return{spec_version:"1.0",recommendation_id:e.recommendation_id,timestamp:new Date().toISOString(),status:"generated",ttl_ms:3e5,recommendation:{format:e.preferred_format||"tail",disclosure:"Sponsored",creative:{brand_name:((s=e.creative_input)==null?void 0:s.brand_name)||"",headline:e.title||((i=e.creative_input)==null?void 0:i.product_name)||"",description:((c=e.creative_input)==null?void 0:c.short_description)||((u=e.creative_input)==null?void 0:u.long_description)||"",cta_text:((b=e.creative_input)==null?void 0:b.cta_label)||((h=o[0])==null?void 0:h.product_cta_label)||"Learn more",follow_up_suggestion:e.follow_up_suggestion,logo_url:(d=(_=e.creative_input)==null?void 0:_.assets)==null?void 0:d.logo_url,image_urls:((M=(m=e.creative_input)==null?void 0:m.assets)==null?void 0:M.image_urls)||[],landing_page_url:e.url||e.click_url||((x=e.creative_input)==null?void 0:x.cta_url)||"",products:o}},tracking:{exposure_url:e.exposure_url,click_url:e.click_url,followup_exposure_url:e.followup_exposure_url,followup_engagement_url:e.followup_engagement_url}}}function mo(t){return{...t,suggestions:(t.suggestions||[]).map(e=>({...e,recommendation:uo(e.recommendation)}))}}function tr(t){try{const o=new URL(t).pathname.split("/").filter(i=>i.length>0);return o[o.length-1]||void 0}catch{return}}async function br(t,e){var o,s,i,c,u;try{console.log("[AdMesh SDK] Starting ACIE analyze-intent call...",{url:t.url});const b=Array.isArray(t.headings)?t.headings:[],h=(o=tr(t.url))==null?void 0:o.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),_=h?h.replace(/\b\w/g,j=>j.toUpperCase()):void 0,d=e.apiKey.toLowerCase().startsWith("pub_")?tr(t.url):void 0,m=e.extension?"extension":"admesh_ui_sdk",M=(t.domain||(typeof window<"u"?window.location.hostname:"")).trim().toLowerCase(),x={url:t.url,title:t.title||void 0,headings:b.length>0?b:_?[_]:void 0,article_text:((s=t.article_text)==null?void 0:s.trim())||void 0,domain:M,article_slug:d,agent_id:void 0,cpx_floor:void 0,source:m,api_key:e.apiKey,user_id:e.userId||void 0};console.log("[AdMesh SDK] Payload prepared:",{url:x.url,titleLength:((i=x.title)==null?void 0:i.length)||0,headingsCount:((c=x.headings)==null?void 0:c.length)||0,articleTextLength:((u=x.article_text)==null?void 0:u.length)||0,domain:x.domain,article_slug:x.article_slug,source:x.source,has_user_id:!!x.user_id});const w=`${e.apiBaseUrl}/acie/analyze-intent`;console.log("[AdMesh SDK] Calling ACIE API:",w);const g=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(x)});if(console.log("[AdMesh SDK] ACIE API response received:",{status:g.status,statusText:g.statusText,ok:g.ok}),!g.ok){const j=await g.text();throw console.error("[AdMesh SDK] ACIE API error:",{status:g.status,statusText:g.statusText,errorText:j}),new Error(`ACIE API error: ${g.status} - ${j}`)}const p=await g.json(),y=mo(p);return console.log("[AdMesh SDK] ACIE analysis completed:",{url:t.url,suggestionsCount:y.suggestions.length}),y}catch(b){return console.error("[AdMesh SDK] Error calling ACIE analyze-intent endpoint:",b),null}}async function po(t,e){var c,u;const o=(e.apiBaseUrl||"https://api.useadmesh.com").replace(/\/$/,""),s=new URLSearchParams({url:t.trim()});(c=e.agentDisplayId)!=null&&c.trim()&&s.set("agent_display_id",e.agentDisplayId.trim()),(u=e.publisherId)!=null&&u.trim()&&s.set("publisher_id",e.publisherId.trim());const i=await fetch(`${o}/publisher-assistant/page-context?${s.toString()}`,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e.apiKey}`}});if(!i.ok){const b=await i.text().catch(()=>"");throw new Error(`Page context request failed (${i.status}): ${b||i.statusText}`)}return await i.json()}function ho(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function fo(){var t;if(typeof window>"u")return null;try{const e=(t=window.location.href)==null?void 0:t.trim();if(yr(e))return e}catch{return null}return null}function yr(t){const e=t==null?void 0:t.trim();if(!e||/%%[^%]+%%/.test(e))return!1;try{const o=new URL(e);return o.protocol==="http:"||o.protocol==="https:"}catch{return!1}}function go(t){try{const e=new URL(t),o=e.pathname.split("/").filter(Boolean),i=(o[o.length-1]||o[o.length-2]||e.hostname).replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i?i.replace(/\b\w/g,c=>c.toUpperCase()):e.hostname}catch{return"This page"}}function nr(t){const e=new URL(t),o=go(t);return{title:o,headings:[o],article_text:`Article URL: ${t}
31
- Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const xo=6e4,rr=3;function bo(t){const e=fo();if(e)return e;const o=t==null?void 0:t.trim();return yr(o)?o:null}const _r=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:c,location:u,userId:b,model:h,messages:_,pageContext:d,articleUrl:m,contextMode:M="auto",agentDisplayId:x,children:w})=>{const[g,p]=l.useState(null),[y,j]=l.useState(new Set),[R,q]=l.useState(new Map),[A,S]=l.useState(null),[L,W]=l.useState([]),[N,z]=l.useState(!1),[P,$]=l.useState(null),[Y,Z]=l.useState(!1),xe=l.useRef(!1),F=l.useRef(0),me=l.useRef(null),ge=l.useRef(null);ge.current=A;const de=!!d||M==="ad-slot"||M==="auto"&&(!!(m!=null&&m.trim())||ho()),Q=l.useCallback(async()=>{if(d)return d;if(!de)return xr();const B=bo(m);if(!B)return a.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),$("Article URL is required for ad-slot context"),null;if(!t||!i)return a.warn("[AdMeshProvider] Cannot fetch page context: missing API key or base URL"),nr(B);try{Z(!0);const k=await po(B,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:x});return a.log("[AdMeshProvider] Page context resolved",{source:k.source,cache_hit:k.cache_hit,domain:k.context.domain}),k.context}catch(k){return a.error("[AdMeshProvider] Failed to fetch page context:",k),a.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),nr(B)}finally{Z(!1)}},[x,i,t,m,d,de]),G=l.useCallback((B,k)=>{const O=B.filter(v=>!v.is_sponsored).slice(0,3);return[k,...O]},[]),Ne=l.useCallback((B,k)=>{const O=B.find(C=>C.is_sponsored),v=k.filter(C=>!C.is_sponsored).slice(0,3);return O?[O,...v]:v},[]);l.useEffect(()=>{if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}a.log("[AdMeshProvider] โœ… Session ID available:",e)},[e]),l.useEffect(()=>{if(!t){a.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const B=new Jt({apiKey:t,theme:s,apiBaseUrl:i,extension:o});p(B),a.log("[AdMeshProvider] โœ… AdMesh SDK initialized with session:",e),i&&a.log("[AdMeshProvider] ๐Ÿ“ Using custom API base URL")}catch(B){a.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK:",B)}return()=>{a.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,s,i,e,o]);const we=l.useCallback(async B=>{var k;if(!t||!i){a.warn("[AdMeshProvider] โš ๏ธ Cannot perform intent analysis: missing API key or base URL");return}if(o)a.log("[AdMeshProvider] โ„น๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){a.log('[AdMeshProvider] โ„น๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{z(!0),$(null),a.log("[AdMeshProvider] ๐Ÿ”„ Starting automatic intent analysis...");const O=B??await Q();if(!O){a.warn("[AdMeshProvider] โš ๏ธ Failed to extract headings for intent analysis"),$("Failed to extract page content");return}a.log("[AdMeshProvider] ๐Ÿ“„ Extracted headings:",{title:O.title,headingsCount:O.headings.length,articleTextLength:((k=O.article_text)==null?void 0:k.length)||0,domain:O.domain});const C=await br(O,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:b});C?(a.log("[AdMeshProvider] โœ… Intent analysis completed:",{suggestionsCount:C.suggestions.length,suggestions:(C.suggestions||[]).map(ee=>{var T;return{id:ee.id,text:ee.text,is_sponsored:ee.is_sponsored,recommendationId:((T=ee.recommendation)==null?void 0:T.recommendation_id)||null}})}),W(ee=>Ne(ee,C.suggestions||[]))):(a.warn("[AdMeshProvider] โš ๏ธ Intent analysis returned null"),$("Intent analysis failed"),W(ee=>ee.length>0?(a.log("[AdMeshProvider] โ„น๏ธ Preserving existing suggestions after null intent analysis result"),ee):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(O){a.error("[AdMeshProvider] โŒ Error in intent analysis:",O),$("Intent analysis error"),W(v=>v.length>0?(a.log("[AdMeshProvider] โ„น๏ธ Preserving existing suggestions after intent analysis error"),v):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{z(!1)}},[t,i,o,b,Ne,Q]),Ce=l.useCallback(async B=>{var v,C,ee,T,ue,V;if(!g||!t||!t.toLowerCase().startsWith("pub_"))return;const k=B??await Q();if(!k){a.warn("[AdMeshProvider] โš ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const O=((C=(v=k.headings)==null?void 0:v[0])==null?void 0:C.trim())||((ee=k.title)==null?void 0:ee.trim());if(!O){a.warn("[AdMeshProvider] โš ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{a.log("[AdMeshProvider] ๐Ÿ”„ Prefetching sponsored suggestion from /aip/context...");const se=await g.fetchPlatformResponse({query:O,sessionId:e,messageId:Jt.createMessageId(e),platformSurface:"embedded_assistant",model:h,messages:[],language:c,location:u,userId:b}),pe=(V=(ue=(T=se.recommendation)==null?void 0:T.creative)==null?void 0:ue.follow_up_suggestion)==null?void 0:V.trim(),oe=se.recommendation_id;if(!pe||!oe){a.log("[AdMeshProvider] โ„น๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const K={id:oe,text:pe,type:"action",is_sponsored:!0,recommendation:se,metadata:{source:"aip_context_prefetch",recommendation_id:oe}};W(Me=>G(Me,K)),a.log("[AdMeshProvider] โœ… Sponsored suggestion prefetched from /aip/context",{recommendationId:oe,suggestionText:pe})}catch(se){a.warn("[AdMeshProvider] โš ๏ธ Sponsored suggestion prefetch failed (non-blocking):",se)}},[t,c,u,h,g,e,b,G,Q]),ie=l.useCallback(async()=>{a.log("[AdMeshProvider] ๐Ÿ”„ Manual retry of intent analysis"),await we()},[we]);l.useEffect(()=>{!g||xe.current||(xe.current=!0,(async()=>{const B=await Q();await Promise.allSettled([Ce(B),we(B)])})())},[g,we,Ce,Q]);const ve=l.useCallback(B=>{if(!B||B.status!=="active")return!1;const k=Date.parse(B.expires_at);return Number.isNaN(k)?!1:k>Date.now()},[]),_e=l.useCallback(async(B,k,O,v)=>{const C=v??A;if(!C||!g){a.warn("[AdMeshProvider] โš ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:B,eventType:k,hasSession:!!C,hasSdk:!!g});return}const ee=new Date().toISOString();a.log("[AdMeshProvider] ๐Ÿ“ก Sending delegation event",{endpoint:B,eventType:k,recommendationId:C.recommendation_id,delegationSessionId:C.delegation_session_id,sessionId:C.session_id});const T=await fetch(`${g.getApiBaseUrl()}${B}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:C.delegation_session_id,recommendation_id:C.recommendation_id,session_id:C.session_id,event_type:k,timestamp:ee,metadata:O||{}})});if(!T.ok){const se=await T.text();throw a.error("[AdMeshProvider] โŒ Delegation event failed",{endpoint:B,eventType:k,status:T.status,errorBody:se,recommendationId:C.recommendation_id,delegationSessionId:C.delegation_session_id}),new Error(`Delegation event failed (${T.status}): ${se}`)}const ue=await T.json(),V=ue==null?void 0:ue.session;a.log("[AdMeshProvider] โœ… Delegation event acknowledged",{endpoint:B,eventType:k,recommendationId:C.recommendation_id,delegationSessionId:C.delegation_session_id,returnedStatus:(V==null?void 0:V.status)||(ue==null?void 0:ue.status)}),V&&S(V)},[A,t,g]),ze=l.useCallback(()=>{F.current=0},[]),Ee=l.useCallback(async(B="user_stopped",k)=>{const O=A;if(!O){a.warn("[AdMeshProvider] โš ๏ธ stopDelegationSession called without an active SDK delegation session");return}a.log("[AdMeshProvider] ๐Ÿ›‘ Stopping delegation session",{reason:B,recommendationId:O.recommendation_id,delegationSessionId:O.delegation_session_id}),await _e("/aip/delegation/stop","session_stopped",{reason:B,...k||{}},O),await(g==null?void 0:g.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:O.session_id,recommendation_id:O.recommendation_id,delegation_session_id:O.delegation_session_id,brand_name:O.brand_name,status:"stopped",metadata:{reason:B,...k||{}}}).catch(v=>{a.warn("[AdMeshProvider] โš ๏ธ Failed to track delegation_stopped event:",v)})),F.current=0,me.current=null,S(null),a.log("[AdMeshProvider] โœ… Delegation session cleared locally after stop")},[A,_e,g]),lt=l.useCallback(async(B="turn_completed",k)=>{B==="turn_started"&&ze(),await _e("/aip/delegation/activity",B,k)},[_e,ze]);l.useEffect(()=>{const B=(A==null?void 0:A.delegation_session_id)??null;B!==me.current&&(me.current=B,F.current=0)},[A==null?void 0:A.delegation_session_id]),l.useEffect(()=>{if(!((A==null?void 0:A.delegation_session_id)??null)||!g)return;const k=ge.current;if(!k||!ve(k)){S(v=>v?{...v,status:"expired"}:null);return}const O=window.setInterval(()=>{const v=ge.current;if(!(!v||!ve(v))){if(F.current+=1,F.current>=rr){a.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:v.delegation_session_id,heartbeatsSinceLastUserTurn:F.current,idleHeartbeatLimit:rr}),Ee("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:F.current}).catch(C=>{a.warn("[AdMeshProvider] โš ๏ธ Failed to stop idle delegation session:",C)});return}_e("/aip/delegation/heartbeat","heartbeat").catch(C=>{a.warn("[AdMeshProvider] โš ๏ธ Failed to send delegation heartbeat:",C)})}},xo);return()=>{window.clearInterval(O)}},[A==null?void 0:A.delegation_session_id,ve,_e,g,Ee]);const et={sdk:g,apiKey:t,sessionId:e,theme:s,language:c,location:u,userId:b,model:h,messages:_,processedMessageIds:y,recommendationResults:R,activeDelegationSession:A,suggestions:L,isAnalyzingIntent:N||Y,intentError:P,markMessageAsProcessed:B=>{j(k=>{const O=new Set(k);return O.add(B),O})},isMessageProcessed:B=>y.has(B),setRecommendationResult:(B,k)=>{q(O=>{const v=new Map(O);return v.set(B,k),v}),j(O=>{const v=new Set(O);return v.add(B),v})},getRecommendationResult:B=>R.get(B),hasRecommendationResult:B=>R.has(B),setActiveDelegationSession:B=>{S(B)},getActiveDelegationSession:()=>ve(A)?A:null,hasActiveDelegationSession:()=>ve(A),refreshDelegationActivity:lt,stopDelegationSession:Ee,retryIntentAnalysis:ie};return r.jsx(En.Provider,{value:et,children:w})};class wr{constructor(){Be(this,"roots",new Map)}async render(e){try{a.log("[AdMeshRenderer] ๐ŸŽจ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){a.log("[AdMeshRenderer] โš ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw a.error("[AdMeshRenderer] โŒ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);a.log("[AdMeshRenderer] โœ… Container ready");const i=this.roots.get(e.containerId);i&&(a.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const c=Kr.createRoot(s);a.log("[AdMeshRenderer] ๐Ÿ“Š Rendering recommendations"),c.render(r.jsx(_r,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:r.jsx(fr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",a.log("[AdMeshRenderer] โœ… Recommendations rendered successfully"),this.roots.set(e.containerId,c)}catch(o){throw a.error("[AdMeshRenderer] โŒ Error rendering recommendations"),o}}unmount(e){const o=this.roots.get(e);if(o){o.unmount(),this.roots.delete(e);const s=document.getElementById(e);s&&(s.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}const yo=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},at=class at{constructor(e){Be(this,"config");Be(this,"apiBaseUrl");Be(this,"renderer",null);Be(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl,extension:e.extension,extensionSourceDomain:e.extensionSourceDomain,userId:e.userId},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static buildPlatformResponseCacheKey(e,o){return`${e}::${o}`}getExtensionSourceDomain(){var o,s;const e=(o=this.config.extensionSourceDomain)==null?void 0:o.trim();if(e)return e.toLowerCase();if(typeof window<"u"&&((s=window.location)!=null&&s.hostname))return window.location.hostname.trim().toLowerCase()||void 0}static createSession(){const e=Date.now(),o=Math.random().toString(36).substring(2,15);return`session_${e}_${o}`}static generateSessionIdFromUrl(e){const o=e||(typeof window<"u"?window.location.href:"");if(!o)return at.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),c=i[i.length-1];return c?`session_${Date.now()}_${c}`:at.createSession()}catch{return at.createSession()}}static createMessageId(e){const o=Date.now(),s=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${o}_${s}`:`msg_${o}_${s}`}getRenderer(){return this.renderer||(this.renderer=new wr),this.renderer}getTracker(){return this.tracker||(this.tracker=new gr({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const c=await fetch(`${this.apiBaseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({delegation_session_id:o.delegation_session_id,recommendation_id:o.recommendation_id,session_id:o.session_id,event_type:s,timestamp:new Date().toISOString(),metadata:i||{}})});if(!c.ok){const b=await c.text();throw new Error(`Delegation event failed (${c.status}): ${b}`)}const u=await c.json();return(u==null?void 0:u.session)||null}async reportDelegationTurnStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_started",o)}async reportDelegationSessionStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"session_started",o)}async reportDelegationTurnCompleted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_completed",o)}async reportDelegationToolInvocation(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"tool_invoked",o)}async reportDelegationOutcome(e,o,s){return this.postDelegationEvent("/aip/delegation/complete",e,o,s)}async stopDelegationSession(e,o="user_stopped",s){return this.postDelegationEvent("/aip/delegation/stop",e,"session_stopped",{reason:o,...s||{}})}getActiveDelegationSession(e){if(!e||e.status!=="active")return null;const o=Date.parse(e.expires_at);return Number.isNaN(o)||o<=Date.now()?null:e}hasActiveDelegationSession(e){return!!this.getActiveDelegationSession(e)}async showRecommendations(e){try{if(!e.sessionId||e.sessionId.trim()==="")throw new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");if(!e.messageId||e.messageId.trim()==="")throw new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");const o=await this.fetchPlatformResponse({query:e.query,sessionId:e.sessionId,messageId:e.messageId,platformSurface:e.platformSurface,model:e.model,messages:e.messages,language:e.locale,location:e.location,userId:e.userId??this.config.userId}),s={sessionId:e.sessionId,messageId:e.messageId,recommendations:[o]},i=this.getRenderer(),c=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:c,sessionId:e.sessionId,apiKey:this.config.apiKey,apiBaseUrl:this.apiBaseUrl,language:e.locale,location:e.location,userId:e.userId,model:e.model,messages:e.messages,onPasteToInput:e.onPasteToInput,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation,onExecuteQuery:e.onExecuteQuery})}catch(o){throw a.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var p,y,j,R,q,A,S,L,W,N,z,P,$;const o=`${this.apiBaseUrl}/aip/context`;if(a.log("[AdMeshSDK] ๐Ÿ“ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const Y=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw a.error("[AdMeshSDK] โŒ sessionId not provided by platform - cannot process request"),Y}const s=e.messageId;if(!s||s.trim()===""){const Y=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw a.error("[AdMeshSDK] โŒ messageId not provided by platform - cannot process request"),Y}const i=at.buildPlatformResponseCacheKey(e.sessionId,s),c=at.inFlightPlatformResponses.get(i);if(c)return a.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),c;const u=e.messages?e.messages.length:0,b=(typeof window<"u"&&window.navigator,"web"),h=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",_=yo((p=e.location)==null?void 0:p.countryCode)||"US",d=typeof window<"u"&&window.location?{url:window.location.href,origin:window.location.origin,referrer:document.referrer||void 0,host:window.location.hostname}:void 0,m=e.userId??this.config.userId,M={spec_version:"1.0",message_id:s,timestamp:new Date().toISOString(),platform:{platform_id:"placeholder",role:"platform",software:{name:"admesh_ui_sdk",version:e.model||"1.0.0"}},identity:{namespace:"platform_user",value_hash:m||"",confidence:m?1:0},consent:{status:"granted",source:"admesh_ui_sdk",scope:{intent_based_monetization:!0,agent_participation:!0,measurement:!0},constraints:{allow_identity_downstream:!1}},classification_input:{type:"interaction",interaction:{session:{id:e.sessionId,turn_index:u},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:b,form_factor:h,locale:e.language||"en-US",country:_,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((y=e.location)==null?void 0:y.city)||void 0,state:((j=e.location)==null?void 0:j.state)||void 0,state_code:((R=e.location)==null?void 0:R.stateCode)||void 0,country:((q=e.location)==null?void 0:q.country)||void 0,country_code:_,zipcode:((A=e.location)==null?void 0:A.zipcode)||void 0,latitude:(S=e.location)==null?void 0:S.latitude,longitude:(L=e.location)==null?void 0:L.longitude},page:d}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(N=(W=M.classification_input.interaction)==null?void 0:W.input.query_text)!=null&&N.trim()||a.warn("[AdMeshSDK] โš ๏ธ Warning: Sending request with empty query_text");const x=JSON.stringify(M);a.log("[AdMeshSDK] ๐Ÿ“ค Sending canonical request to /aip/context",{messageId:M.message_id,specVersion:M.spec_version,classificationType:M.classification_input.type,platformId:M.platform.platform_id,surfaceChannel:(z=M.classification_input.interaction)==null?void 0:z.surface.channel,sessionId:($=(P=M.classification_input.interaction)==null?void 0:P.session)==null?void 0:$.id});const w={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){w["X-AdMesh-Source"]="extension";const Y=this.getExtensionSourceDomain();Y&&(w["X-AdMesh-Source-Domain"]=Y)}const g=(async()=>{const Y=await fetch(o,{method:"POST",headers:w,body:x});if(!Y.ok){const F=(await Y.json().catch(()=>({}))).detail||`HTTP ${Y.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${F}`)}const Z=await Y.json();return a.log("[AdMeshSDK] ๐Ÿ“ฅ Raw response from /aip/context:",{status:Z.status,recommendationId:Z.recommendation_id,hasRecommendation:!!Z.recommendation,hasTracking:!!Z.tracking,hasDelegation:!!Z.delegation,topLevelKeys:Object.keys(Z)}),a.log("[AdMeshSDK] ๐Ÿ“ฆ Full PlatformResponse received from /aip/context",Z),Z})();at.inFlightPlatformResponses.set(i,g);try{return await g}finally{at.inFlightPlatformResponses.delete(i)}}async trackPublisherAssistantEvent(e){const o=Array.isArray(e)?{events:e}:e,s=await fetch(`${this.apiBaseUrl}/analytics/publisher-assistant/events`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),keepalive:!0});if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Failed to track publisher assistant analytics (${s.status}): ${i}`)}}fireFollowupExposure(e,o,s){this.getTracker().fireFollowupExposure(e,o,s)}async fireFollowupEngagement(e,o,s){return this.getTracker().fireFollowupEngagement(e,o,s)}};Be(at,"inFlightPlatformResponses",new Map);let Jt=at;class Tn{constructor(e={}){Be(this,"autoAddLabels");Be(this,"fireExposurePixels");Be(this,"labelStyle");Be(this,"processedLinks",new Set);Be(this,"mutationObserver",null);var o,s,i,c;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((o=e.labelStyle)==null?void 0:o.fontSize)||"0.75em",fontWeight:((s=e.labelStyle)==null?void 0:s.fontWeight)||"bold",color:((i=e.labelStyle)==null?void 0:i.color)||"#666",marginLeft:((c=e.labelStyle)==null?void 0:c.marginLeft)||"2px"}}getLinksToProcess(e){const s=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return s.length>0?Array.from(s):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,o,s){if(!e)return[];const i=[];if(o.length>0){const c=this.getLinksToProcess(e),u=new Map(o.map(h=>{var _,d,m;return[((_=h==null?void 0:h.tracking)==null?void 0:_.click_url)||((m=(d=h==null?void 0:h.recommendation)==null?void 0:d.creative)==null?void 0:m.landing_page_url)||"",h]}).filter(([h])=>!!h)),b=new Map;o.forEach(h=>{var d,m;const _=(m=(d=h==null?void 0:h.recommendation)==null?void 0:d.creative)==null?void 0:m.landing_page_url;if(_&&typeof _=="string"){const M=_.trim().replace(/\/$/,"");b.set(M,h),b.set(`${M}/`,h)}}),c.forEach(h=>{var x,w,g,p,y,j,R,q;const _=h.getAttribute("href")||"",d=`${_}`;if(this.processedLinks.has(d))return;let m=u.get(_),M=_;if(!m){const A=_.trim().replace(/\/$/,"");m=b.get(A)||b.get(`${A}/`);const S=((x=m==null?void 0:m.tracking)==null?void 0:x.click_url)||((g=(w=m==null?void 0:m.recommendation)==null?void 0:w.creative)==null?void 0:g.landing_page_url);m&&S&&(a.log("[WeaveResponseProcessor] ๐Ÿ”„ Found brand URL match, replacing with click_url:",_),h.setAttribute("href",S),M=S)}if(m){this.processedLinks.add(d),h.setAttribute("target","_blank"),h.setAttribute("rel","noopener noreferrer");const A={element:h,href:M,text:h.textContent||"",hasAdLabel:this.hasAdLabel(h),matchedRecommendation:{recommendation_id:(m==null?void 0:m.recommendation_id)||"",click_url:((p=m==null?void 0:m.tracking)==null?void 0:p.click_url)||((j=(y=m==null?void 0:m.recommendation)==null?void 0:y.creative)==null?void 0:j.landing_page_url)||"",exposure_url:(R=m==null?void 0:m.tracking)==null?void 0:R.exposure_url}};this.autoAddLabels&&!A.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding Ad label to matched recommendation link:",M),this.addAdLabel(h),A.hasAdLabel=!0):this.autoAddLabels?A.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label");const S=(q=m==null?void 0:m.tracking)==null?void 0:q.exposure_url;this.fireExposurePixels&&S&&s&&A.matchedRecommendation&&s({exposureUrl:S,recommendationId:A.matchedRecommendation.recommendation_id,linkElement:h}),i.push(A)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const b=u.getAttribute("href")||"",h=`${b}`;if(this.processedLinks.has(h))return;if(this.isAdMeshLink(b)){this.processedLinks.add(h);const d={element:u,href:b,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:void 0};if(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!d.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding Ad label to pattern-matched AdMesh link:",b),this.addAdLabel(u),d.hasAdLabel=!0):this.autoAddLabels?d.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const m=this.convertClickUrlToExposureUrl(b);s({exposureUrl:m,recommendationId:this.extractRecommendationIdFromUrl(b),linkElement:u})}i.push(d)}});return i}hasAdLabel(e){var u,b,h;if((e.textContent||"").includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link text contains Ad label"),!0;const s=e.querySelectorAll("sub, span");for(const _ of Array.from(s))if((u=_.textContent)!=null&&u.includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link has Ad label as child element"),!0;let i=e.previousSibling;for(;i&&i.nodeType===Node.TEXT_NODE;){const _=i.textContent||"";if(_.trim()===""){i=i.previousSibling;continue}if(_.includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const _=i,d=_.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((b=_.textContent)!=null&&b.includes("Ad")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in previous element sibling:",d),!0}let c=e.nextSibling;for(;c&&c.nodeType===Node.TEXT_NODE;){const _=c.textContent||"";if(_.trim()===""){c=c.nextSibling;continue}if(_.includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in next text sibling"),!0;break}if(c&&c.nodeType===Node.ELEMENT_NODE){const _=c,d=_.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((h=_.textContent)!=null&&h.includes("Ad")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in next element sibling:",d),!0}return a.log("[WeaveResponseProcessor] โ„น๏ธ No existing Ad label found"),!1}addAdLabel(e){if(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){a.warn("[WeaveResponseProcessor] โš ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){a.error("[WeaveResponseProcessor] โŒ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const s=document.createElement("sub");s.textContent="Ad",s.style.fontSize=this.labelStyle.fontSize,s.style.fontWeight=this.labelStyle.fontWeight,s.style.color=this.labelStyle.color,s.style.marginLeft=this.labelStyle.marginLeft,s.style.cursor="pointer",s.style.borderBottom=`1px dotted ${this.labelStyle.color}`,s.style.whiteSpace="nowrap",s.title="Why this ad? This is a sponsored recommendation based on your search query.";let i=!1;s.addEventListener("mouseenter",()=>{s.style.opacity="0.7"}),s.addEventListener("mouseleave",()=>{s.style.opacity="1",i&&(i=!1)}),s.addEventListener("click",u=>{u.stopPropagation(),i=!i,i?(s.style.textDecoration="underline",s.style.opacity="0.7"):(s.style.textDecoration="none",s.style.opacity="1")});const c=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",c);try{const u=e.nextSibling;u?(o.insertBefore(s,u),a.log("[WeaveResponseProcessor] โœ… Ad label inserted before next sibling")):(o.appendChild(s),a.log("[WeaveResponseProcessor] โœ… Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?a.log("[WeaveResponseProcessor] โœ… Ad label successfully added to link:",e.href):a.error("[WeaveResponseProcessor] โŒ Ad label insertion failed - label not in DOM")}catch(u){a.error("[WeaveResponseProcessor] โŒ Error inserting Ad label:",u)}}removeLeftAdLabel(e){var s,i,c;let o=e.previousSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const u=o.textContent||"";if(u.trim()===""){o=o.previousSibling;continue}if(u.includes("Ad")){(s=o.parentNode)==null||s.removeChild(o);return}break}if(o&&o.nodeType===Node.ELEMENT_NODE){const u=o;(u.tagName==="SUB"||u.tagName==="SPAN")&&((i=u.textContent)!=null&&i.includes("Ad"))&&((c=u.parentNode)==null||c.removeChild(u))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(i=>e.includes(i)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractRecommendationIdFromUrl(e){try{const o=e.match(/\/click\/([^/?]+)/);return o&&o[1]?o[1]:""}catch{return e}}convertClickUrlToExposureUrl(e){try{const o=new URL(e),i=`${`${o.protocol}//${o.host}`}/exposure`,c=new URLSearchParams(o.search);return c.has("cpx")||c.set("cpx","0"),`${i}?${c.toString()}`}catch{return a.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,o,s){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,o,s)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}function Wt(){const t=Rn();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,language:t.language,location:t.location,userId:t.userId,model:t.model,messages:t.messages,processedMessageIds:t.processedMessageIds,recommendationResults:t.recommendationResults,activeDelegationSession:t.activeDelegationSession,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed,setRecommendationResult:t.setRecommendationResult,getRecommendationResult:t.getRecommendationResult,hasRecommendationResult:t.hasRecommendationResult,setActiveDelegationSession:t.setActiveDelegationSession,getActiveDelegationSession:t.getActiveDelegationSession,hasActiveDelegationSession:t.hasActiveDelegationSession,refreshDelegationActivity:t.refreshDelegationActivity,stopDelegationSession:t.stopDelegationSession}}const _o=({className:t,size:e=20})=>r.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[r.jsx("path",{d:"M5 12h14"}),r.jsx("path",{d:"M12 5v14"})]}),vr=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var M,x,w,g,p;const c=(x=(M=t.recommendation)==null?void 0:M.creative)!=null&&x.follow_up_suggestion&&((w=t.tracking)!=null&&w.followup_engagement_url)&&((g=t.tracking)!=null&&g.followup_exposure_url)?{query:t.recommendation.creative.follow_up_suggestion,engagement_url:t.tracking.followup_engagement_url,exposure_url:t.tracking.followup_exposure_url}:null,u=c==null?void 0:c.query,b=c==null?void 0:c.engagement_url,h=c==null?void 0:c.exposure_url,_=t.recommendation_id,d=((p=t.recommendation)==null?void 0:p.offerId)||_;if(!u||!b||!h)return a.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const m=async()=>{try{b&&_&&(a.log("[AdMeshFollowup] ๐ŸŽฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(b,_,s)),i&&u?(a.log(`[AdMeshFollowup] ๐Ÿ” Executing query: ${u}`),await i(u)):a.warn("[AdMeshFollowup] โš ๏ธ onExecuteQuery not provided - cannot execute query")}catch(y){a.error("[AdMeshFollowup] โŒ Error handling follow-up click:",y)}};return r.jsx(Zt,{productId:d,recommendationId:_||"",exposureUrl:h,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:r.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[r.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),r.jsxs("div",{onClick:m,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&m()},"aria-label":`Sponsored follow-up: ${u}`,children:[r.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),r.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[r.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),r.jsx(_o,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},Xt=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:c,triggerExposureUrl:u=!0,followups_container_id:b,onPasteToInput:h,onDelegationConsent:_,onDelegationActivated:d,onStartDelegation:m,onExecuteQuery:M,onFollowupDetected:x,isContainerReady:w})=>{var B,k,O,v;const{sdk:g,sessionId:p,apiKey:y,language:j,location:R,userId:q,model:A,messages:S,theme:L,getRecommendationResult:W,hasRecommendationResult:N,setRecommendationResult:z,activeDelegationSession:P,setActiveDelegationSession:$,hasActiveDelegationSession:Y}=Wt(),Z=C=>!!C&&C.status==="generated"&&!!C.recommendation,xe=i||q,[F,me]=l.useState(null),[ge,de]=l.useState(null),[Q,G]=l.useState(!0),[Ne,we]=l.useState(null),Ce=l.useRef(null),ie=l.useRef(!1),ve=l.useRef(!1),_e=l.useRef(t),ze=l.useRef(e);l.useEffect(()=>{_e.current=t,ze.current=e},[t,e]),l.useEffect(()=>{Ce.current!==o&&(Ce.current=null,ve.current=!1,me(null),de(null))},[o]);const Ee=Y()&&(P==null?void 0:P.session_id)===p;l.useEffect(()=>{var T,ue,V;if(!o||!N(o)||Ee)return;const C=W(o);if(!C){a.log("[AdMeshRecommendations] โ™ป๏ธ Reusing stored no_match result from provider state"),me(null),de(null),we(null),G(!1),Ce.current=o,ie.current=!1,ve.current=!0;return}let ee=((T=C.recommendation)==null?void 0:T.format)||"tail";(ee==="weave"||ee==="product_card")&&(ee="tail"),a.log("[AdMeshRecommendations] โ™ป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:C.recommendation_id,format:(ue=C.recommendation)==null?void 0:ue.format}),me(C),de(ee),we(null),G(!1),Ce.current=o,ie.current=!1,ve.current=!0,(V=_e.current)==null||V.call(_e,o,C)},[W,N,Ee,o]),l.useEffect(()=>{var C,ee,T,ue,V,se,pe;if(!(!c||!o)&&!Ee)try{const oe=c,K=c.status||"unknown";if(!Z(oe)){if(K==="no_match"){a.log("[AdMeshRecommendations] โ„น๏ธ Initial recommendation returned no_match - rendering nothing"),me(null),de(null),we(null),G(!1),Ce.current=o,ie.current=!1,ve.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${K})`)}let Me=((C=oe.recommendation)==null?void 0:C.format)||"tail";(Me==="weave"||Me==="product_card")&&(Me="tail"),me(oe),de(Me),we(null),G(!1),Ce.current=o,ie.current=!1,ve.current=!0,z(o,oe),(ee=_e.current)==null||ee.call(_e,o,oe),a.log("[AdMeshRecommendations] โ™ป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),a.log("[AdMeshRecommendations] โœ… Accepted initial generated recommendation payload",{messageId:o,recommendationId:oe.recommendation_id,format:(T=oe.recommendation)==null?void 0:T.format,brandName:(V=(ue=oe.recommendation)==null?void 0:ue.creative)==null?void 0:V.brand_name,headline:(pe=(se=oe.recommendation)==null?void 0:se.creative)==null?void 0:pe.headline,hasTracking:!!oe.tracking})}catch(oe){const K=oe instanceof Error?oe:new Error(String(oe));ve.current=!1,a.warn(`[AdMeshRecommendations] โš ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${K.message}`)}},[Ee,c,o,z]),l.useEffect(()=>{if(!o||!s||s.trim()===""){a.log("[AdMeshRecommendations] โŒ Validation failed - missing required parameters"),G(!1);return}if(Ee){a.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:p,delegationSessionId:P==null?void 0:P.delegation_session_id}),me(null),de(null),we(null),G(!1),ie.current=!1;return}if(!(g!=null&&g.fetchPlatformResponse)){a.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),G(!1);return}if(ve.current){a.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(Ce.current===o){a.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(ie.current){a.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}a.log("[AdMeshRecommendations] ๐Ÿ“ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var ee,T,ue,V,se,pe,oe,K,Me;try{ie.current=!0,G(!0),we(null);const ye=await g.fetchPlatformResponse({query:s.trim(),sessionId:p,messageId:o,language:j,location:R,userId:xe,model:A,...S&&S.length>0&&{messages:S}}),Ie=(ye==null?void 0:ye.status)||"unknown";if(!Z(ye)){if(Ie==="no_match"){a.log("[AdMeshRecommendations] โ„น๏ธ No recommendation returned from /aip/context"),me(null),de(null),we(null),G(!1),ie.current=!1,Ce.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${Ie})`)}me(ye),a.log("[AdMeshRecommendations] โœ… Accepted fetched generated recommendation payload",{messageId:o,recommendationId:ye.recommendation_id,format:(ee=ye.recommendation)==null?void 0:ee.format,brandName:(ue=(T=ye.recommendation)==null?void 0:T.creative)==null?void 0:ue.brand_name,headline:(se=(V=ye.recommendation)==null?void 0:V.creative)==null?void 0:se.headline,hasTracking:!!ye.tracking});let I=((pe=ye.recommendation)==null?void 0:pe.format)||"tail";(I==="weave"||I==="product_card")&&(I="tail"),de(I),Ce.current=o,z(o,ye),a.log("[AdMeshRecommendations] ๐Ÿ“Š Format detection:",{preferred_format:(oe=ye.recommendation)==null?void 0:oe.format,selected_format:I}),G(!1),ie.current=!1,(K=_e.current)==null||K.call(_e,o,ye)}catch(ye){const Ie=ye instanceof Error?ye:new Error(String(ye));Ie.message.includes("Failed to fetch")||Ie.message.includes("NetworkError")?a.warn(`[AdMeshRecommendations] โš ๏ธ Network error fetching recommendations(non - critical): ${Ie.message} `):a.error(`[AdMeshRecommendations] โŒ Error fetching recommendations: ${Ie.message} `),we(Ie),G(!1),ie.current=!1,(Me=ze.current)==null||Me.call(ze,Ie)}})()},[P==null?void 0:P.delegation_session_id,Ee,g,p,o,s,j,R,xe,A,c,z]),l.useEffect(()=>{var ee,T,ue,V;if(!F||!x)return;const C=(T=(ee=F.recommendation)==null?void 0:ee.creative)!=null&&T.follow_up_suggestion&&((ue=F.tracking)!=null&&ue.followup_engagement_url)&&((V=F.tracking)!=null&&V.followup_exposure_url)?{label:F.recommendation.creative.follow_up_suggestion,query:F.recommendation.creative.follow_up_suggestion,engagement_url:F.tracking.followup_engagement_url,exposure_url:F.tracking.followup_exposure_url}:null;C&&x(C,F.recommendation_id)},[F,x]);const lt=l.useCallback(async C=>{if(!g||!p)throw new Error("AdMesh SDK activation requires an initialized session");const ee=await fetch(`${g.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({session_id:p,recommendation_id:C.recommendation_id,metadata:C.metadata})});if(!ee.ok){const se=await ee.text();throw new Error(`Failed to activate delegation session: ${ee.status} ${se}`)}const T=await ee.json(),ue={...C,delegation_session_id:T.delegation_session_id||C.delegation_session_id,session_id:T.session_id||p,brand_id:T.brand_id||C.brand_id,brand_name:T.brand_name||C.brand_name,mcp_endpoint:T.mcp_endpoint,eligibility_reason:T.eligibility_reason||C.eligibility_reason,delegate_reason:T.delegate_reason||C.delegate_reason,session_goal:T.session_goal||C.session_goal,desired_outcome_type:T.desired_outcome_type||C.desired_outcome_type,required_user_inputs:T.required_user_inputs||C.required_user_inputs||[],required_consent_types:T.required_consent_types||C.required_consent_types||[],success_outcome:T.success_outcome||C.success_outcome,fallback_message:T.fallback_message||C.fallback_message,session_mode:"inline",status:T.status||"active",capabilities:T.capabilities||C.capabilities||[],allowed_data_types:T.allowed_data_types||C.allowed_data_types||[],auth_model:T.auth_model||C.auth_model,handoff_protocol:T.handoff_protocol||C.handoff_protocol,supported_actions:T.supported_actions||C.supported_actions||[],metadata:T.metadata||C.metadata},V={delegation_session_id:T.delegation_session_id,recommendation_id:C.recommendation_id,session_id:T.session_id||p,brand_agent_id:T.brand_agent_id,brand_id:T.brand_id||C.brand_id,brand_name:T.brand_name||C.brand_name||"Brand",mcp_endpoint:T.mcp_endpoint,status:T.status||"active",activated_at:T.created_at,last_activity_at:T.updated_at,expires_at:T.expires_at||T.updated_at,eligibility_reason:T.eligibility_reason||C.eligibility_reason,delegate_reason:T.delegate_reason||C.delegate_reason,session_goal:T.session_goal||C.session_goal,desired_outcome_type:T.desired_outcome_type||C.desired_outcome_type,required_user_inputs:T.required_user_inputs||C.required_user_inputs||[],required_consent_types:T.required_consent_types||C.required_consent_types||[],success_outcome:T.success_outcome||C.success_outcome,fallback_message:T.fallback_message||C.fallback_message,capabilities:T.capabilities||C.capabilities||[],allowed_data_types:T.allowed_data_types||C.allowed_data_types||[],consent_requirements:T.consent_requirements||C.consent_requirements||[],auth_model:T.auth_model||C.auth_model,handoff_protocol:T.handoff_protocol||C.handoff_protocol,supported_actions:T.supported_actions||C.supported_actions||[],metadata:T.metadata||C.metadata};if($(V),await g.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:p,recommendation_id:C.recommendation_id,delegation_session_id:T.delegation_session_id,brand_name:V.brand_name,status:T.status||"active",metadata:{brand_agent_id:T.brand_agent_id,source:"recommendation_card"}}).catch(se=>{a.warn("[AdMeshRecommendations] โš ๏ธ Failed to track delegation_started event:",se)}),await g.reportDelegationSessionStarted(V,{brand_agent_id:T.brand_agent_id,brand_name:V.brand_name}).then(se=>{se&&$(se)}).catch(se=>{a.warn("[AdMeshRecommendations] โš ๏ธ Failed to report delegation session_started event:",se)}),d){try{await d(ue)}catch(se){a.warn("[AdMeshRecommendations] โš ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",se)}return}if(m)try{await m({...C.platform_response,delegation:{...C.platform_response.delegation,...ue,delegation_session_id:T.delegation_session_id,available:!0,status:T.status||"active"}})}catch(se){a.warn("[AdMeshRecommendations] โš ๏ธ Host onStartDelegation callback failed after successful delegation activation:",se)}},[y,d,m,g,p,$]);if(!o||!s||s.trim()===""||Q||Ne)return null;if(!F||!ge)return a.log("[AdMeshRecommendations] ๐Ÿšซ Nothing to render",{messageId:o,hasPlatformResult:!!F,detectedFormat:ge,isLoading:Q,hasError:!!Ne}),null;a.log("[AdMeshRecommendations] ๐ŸŽจ Rendering recommendation component",{messageId:o,recommendationId:F.recommendation_id,detectedFormat:ge,brandName:(k=(B=F.recommendation)==null?void 0:B.creative)==null?void 0:k.brand_name,headline:(v=(O=F.recommendation)==null?void 0:O.creative)==null?void 0:v.headline});const et=typeof document<"u"&&b&&(w??!0)?document.getElementById(b):null;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:r.jsx(jn,{recommendations:[F],theme:L,sessionId:p,triggerExposureUrl:u,onPasteToInput:h,onDelegationConsent:_,onDelegationActivated:lt,onStartDelegation:m})}),et&&g&&p?Gr.createPortal(r.jsx(vr,{recommendation:F,theme:L,sdk:g,sessionId:p,onExecuteQuery:M}),et):null]})},kr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:c})=>{const{sdk:u,sessionId:b,theme:h,apiKey:_,language:d,location:m,userId:M,model:x,messages:w}=Wt(),g=l.useRef(null),[p,y]=l.useState("");return l.useEffect(()=>{o&&y(`admesh-weave-fallback-${o}`)},[o]),a.log("[WeaveFallbackRecommendations] ๐ŸŽจ Component render"),l.useEffect(()=>{if(a.log("[WeaveFallbackRecommendations] ๐Ÿ”„ useEffect triggered",{fallback:i,hasPreviousRecommendations:c&&c.length>0,previousRecommendationsCount:(c==null?void 0:c.length)||0}),!i){a.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(a.log("[WeaveFallbackRecommendations] โœ… fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){a.log("[WeaveFallbackRecommendations] โŒ Validation failed - returning early");return}if(a.log("[WeaveFallbackRecommendations] โœ… Validation passed"),!u||!p){a.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const j=c&&c.length>0;a.log("[WeaveFallbackRecommendations] ๐Ÿ“Š Checking previous recommendations:",{hasPreviousRecs:j,count:(c==null?void 0:c.length)||0,fallback:i,messageId:o}),j?(a.log(`[WeaveFallbackRecommendations] โ™ป๏ธ Reusing ${c.length} previous recommendation(s), skipping API call`),(async()=>{var q,A,S,L,W,N,z;try{const P=c[0];if(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ฆ Processing AIP response:",{hasAipResponse:!!P,recommendationId:(P==null?void 0:P.recommendation_id)||"",format:((q=P==null?void 0:P.recommendation)==null?void 0:q.format)||"unknown"}),P&&process.env.NODE_ENV==="development"&&a.log("[WeaveFallbackRecommendations] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:P==null?void 0:P.recommendation_id,click_url:((A=P==null?void 0:P.tracking)==null?void 0:A.click_url)||((L=(S=P==null?void 0:P.recommendation)==null?void 0:S.creative)==null?void 0:L.landing_page_url),format:(W=P==null?void 0:P.recommendation)==null?void 0:W.format,full_response:P}),!P){a.warn("[WeaveFallbackRecommendations] โš ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:p,sessionId:b,messageId:o});return}const $=u,Y=$.getRenderer,Z=$.getTracker,xe=(N=$.config)==null?void 0:N.theme;if(Y&&Z){const F={sessionId:b,messageId:o,recommendations:[P]},me=Y.call(u),ge=Z.call(u),de=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await me.render({containerId:p,response:F,theme:h||xe,tracker:ge,sessionId:b,apiKey:_||((z=u==null?void 0:u.config)==null?void 0:z.apiKey),apiBaseUrl:de,language:d,location:m,userId:M,model:x,messages:w}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations rendered from previous response (no API call)")}else a.warn("[WeaveFallbackRecommendations] โš ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:p,sessionId:b,messageId:o})}catch(P){const $=P instanceof Error?P:new Error(String(P));a.error(`[WeaveFallbackRecommendations] โŒ Error rendering previous recommendations: ${$.message}`);try{await u.showRecommendations({query:s.trim(),containerId:p,sessionId:b,messageId:o})}catch{e==null||e($)}}})()):(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){a.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:p,sessionId:b,messageId:o}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations displayed successfully")}catch(q){const A=q instanceof Error?q:new Error(String(q));a.log(`[WeaveFallbackRecommendations] โŒ Error: ${A.message}`),e==null||e(A)}})())},[u,b,p,t,o,s,i,e,c,h]),!i||!o||!s||s.trim()===""?null:r.jsx("div",{ref:g,id:p,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Sr=l.createContext(void 0),wo=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>r.jsx(Sr.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),vo=()=>l.useContext(Sr),wn=t=>{try{return new URL(t),!0}catch{return!1}},or=t=>t&&t.trim()?t.trim():"",vt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",it=t=>vt(t)||void 0,ko=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},So=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return vt(t)},Ao=(t,e,o)=>{if(t==null||t==="")return"";const s=(e||"percentage").trim().toLowerCase();if(typeof t=="number"){if(s==="amount"||s==="fixed"||s==="fixed_amount")try{return`${new Intl.NumberFormat("en-US",{style:"currency",currency:o||"USD",maximumFractionDigits:2}).format(t)} off`}catch{return`${t} off`}return`${t}% off`}const i=vt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},fe={surface:"#ffffff",surfaceMuted:"#f9fafb",surfaceSubtle:"#f8fafc",border:"rgba(17, 24, 39, 0.10)",text:"#111827",textSecondary:"#4b5563",textMuted:"#6b7280",link:"#2563eb",logoFallbackBg:"#f3f4f6",logoFallbackText:"#4b5563",productImageFallbackBg:"#e5e7eb",successText:"#065f46",successBg:"#d1fae5"},Co=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:c=!0,onDelegationConsent:u,onDelegationActivated:b,onStartDelegation:h,onPasteToInput:_})=>{var V,se,pe,oe,K,Me,ye,Ie,I,Ue,tt,ht,kt,Ye,St,te,Re,Je,Ke,ft,nt,He,$e,$t,gt,At,Ct,Mt,Lt,Ut,Ht,jt,zt;if(!t||t.length===0)return a.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const d=t[0],m=((V=d==null?void 0:d.recommendation)==null?void 0:V.offerId)||"",M=((se=d==null?void 0:d.tracking)==null?void 0:se.exposure_url)||"",x=(d==null?void 0:d.recommendation_id)||"",w=((oe=(pe=d==null?void 0:d.recommendation)==null?void 0:pe.creative)==null?void 0:oe.description)||"",g=((K=d==null?void 0:d.recommendation)==null?void 0:K.disclosure)||"Sponsored",p=((ye=(Me=d==null?void 0:d.recommendation)==null?void 0:Me.creative)==null?void 0:ye.brand_name)||"",y=((I=(Ie=d==null?void 0:d.recommendation)==null?void 0:Ie.creative)==null?void 0:I.headline)||((tt=(Ue=d==null?void 0:d.recommendation)==null?void 0:Ue.creative)==null?void 0:tt.brand_name)||"",j=((kt=(ht=d==null?void 0:d.recommendation)==null?void 0:ht.creative)==null?void 0:kt.logo_url)||"",R=((Ye=d==null?void 0:d.tracking)==null?void 0:Ye.click_url)||((te=(St=d==null?void 0:d.recommendation)==null?void 0:St.creative)==null?void 0:te.landing_page_url)||"",q=or((Je=(Re=d==null?void 0:d.recommendation)==null?void 0:Re.creative)==null?void 0:Je.cta_text),A=((ft=(Ke=d==null?void 0:d.recommendation)==null?void 0:Ke.creative)==null?void 0:ft.products)||[],S=A.length>1,L=S?A.slice(0,4):[],W=((nt=d==null?void 0:d.recommendation)==null?void 0:nt.format)||"tail",N=W==="bridge",z=((He=d==null?void 0:d.delegation)==null?void 0:He.brand_name)||p,P=(($e=d==null?void 0:d.delegation)==null?void 0:$e.available)===!0,$=N&&P,Y="Talk to Agent",Z=!S&&!!q&&!!R;if(!p&&!y&&!w)return a.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:p,hasFirstRecommendation:!!d,recommendationId:x,recommendationKeys:d?Object.keys(d):[]}),null;let xe=p,F="";y&&y!==p&&(F=y),F&&(xe=`${p} โ€” ${F}`),a.debug("[AdMeshTailAd] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:x,productId:m,exposureUrl:M?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:R||"MISSING",clickUrlSource:($t=d==null?void 0:d.tracking)!=null&&$t.click_url?"tracking.click_url":(At=(gt=d==null?void 0:d.recommendation)==null?void 0:gt.creative)!=null&&At.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:w?"present":"MISSING",brandName:p,productName:y,headlineText:xe,triggerExposureUrl:c}),a.log("[AdMeshTailAd] โœ… Rendering tail ad",{recommendationId:x,brandName:p,productName:y,hasDescription:!!w,hasClickUrl:!!R,hasLogoUrl:!!j,recommendationFormat:W});const me=(H,be)=>{be&&be.stopPropagation(),a.log(`AdMesh tail ad ${H} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:x,productId:m,clickUrl:R,source:H}).catch(()=>{a.error(`[AdMesh] Failed to track ${H} click`)})},ge=H=>{H.stopPropagation(),me("tail_ad_brand_name")},de=H=>{H.stopPropagation(),me("tail_ad_cta")},Q=H=>{H.stopPropagation(),me("tail_ad_logo")},G=()=>{S||!R||(me("tail_ad_card"),typeof window<"u"&&window.open(R,"_blank","noopener,noreferrer"))},Ne=H=>{S||!R||(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),G())},[we,Ce]=l.useState(!1),ie=l.useRef(null);l.useEffect(()=>()=>{ie.current&&(ie.current(!1),ie.current=null)},[]);const ve=H=>{var be;(be=ie.current)==null||be.call(ie,H),ie.current=null,Ce(!1)},_e=async()=>u?await u(d):await new Promise(H=>{ie.current=H,Ce(!0)}),ze=async()=>{if(x&&i)try{const H=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",be=await fetch(`${H}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:x,session_id:i,is_test:!1})});be.ok||a.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",be.statusText)}catch(H){a.error("[AdMesh Tail Ad] Error tracking delegation engagement:",H)}},Ee=async H=>{var xt,bt,De,ct;if(H.preventDefault(),H.stopPropagation(),!d||!$)return;if(me("tail_ad_delegation_cta"),await ze(),!await _e()){a.log("[AdMesh Tail Ad] Delegation consent declined");return}const le=d.delegation,Et=le!=null&&le.available?{recommendation_id:d.recommendation_id,brand_id:it(le.brand_id),brand_name:it(le.brand_name||((bt=(xt=d.recommendation)==null?void 0:xt.creative)==null?void 0:bt.brand_name)),eligibility_reason:it(le.eligibility_reason),delegate_reason:it(le.delegate_reason),session_goal:it(le.session_goal),desired_outcome_type:le.desired_outcome_type,required_user_inputs:Array.isArray(le.required_user_inputs)?le.required_user_inputs.filter(rt=>typeof rt=="string"):[],required_consent_types:Array.isArray(le.required_consent_types)?le.required_consent_types.filter(rt=>typeof rt=="string"):[],success_outcome:it(le.success_outcome),fallback_message:it(le.fallback_message),session_mode:it(le.session_mode),status:it(le.status),capabilities:le.capabilities||[],allowed_data_types:le.allowed_data_types||[],consent_requirements:le.consent_requirements||[],auth_model:it(le.auth_model),handoff_protocol:le.handoff_protocol&&typeof le.handoff_protocol=="object"?le.handoff_protocol:void 0,supported_actions:le.supported_actions||[],metadata:le.metadata&&typeof le.metadata=="object"?le.metadata:void 0,platform_response:d}:null;if(b&&Et){await b(Et);return}if(h){await h(d);return}const Qe=((ct=(De=d.recommendation)==null?void 0:De.creative)==null?void 0:ct.follow_up_suggestion)||"";if(Qe&&_){_(Qe);return}if(Qe&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(Qe);return}},[lt,et]=l.useState(!1),B=p?p.charAt(0).toUpperCase():"B",k=fe.surface,O=fe.border,v=(e==null?void 0:e.borderRadius)||((Mt=(Ct=e==null?void 0:e.components)==null?void 0:Ct.card)==null?void 0:Mt.borderRadius)||"8px",C="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",ee="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",T=((Lt=e==null?void 0:e.shadows)==null?void 0:Lt.medium)||((Ht=(Ut=e==null?void 0:e.components)==null?void 0:Ut.card)==null?void 0:Ht.boxShadow)||C,ue=((jt=e==null?void 0:e.shadows)==null?void 0:jt.large)||ee;return r.jsxs(Zt,{productId:m,recommendationId:x,exposureUrl:M,sessionId:i,triggerExposureUrl:c,className:`admesh-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[r.jsx("style",{children:`
32
- .admesh-tail-product-scroll {
33
- -ms-overflow-style: none;
34
- scrollbar-width: none;
35
- }
36
-
37
- .admesh-tail-product-scroll::-webkit-scrollbar {
38
- display: none;
39
- width: 0;
40
- height: 0;
41
- }
42
- `}),r.jsxs("div",{className:"tail-ad-container flex flex-col gap-3 sm:flex-row",role:!S&&R?"link":void 0,tabIndex:!S&&R?0:void 0,style:{...(zt=e==null?void 0:e.components)==null?void 0:zt.card,backgroundColor:k,borderRadius:v,padding:"16px",boxShadow:T,border:`1px solid ${O}`,color:fe.text,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",cursor:!S&&R?"pointer":void 0},onClick:G,onKeyDown:Ne,onMouseEnter:H=>{H.currentTarget.style.boxShadow=ue,H.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:H=>{H.currentTarget.style.boxShadow=T,H.currentTarget.style.transform="translateY(0)"},children:[j&&r.jsx("div",{className:"flex-shrink-0 flex items-center justify-start pr-0 sm:justify-center sm:pr-2",style:{width:"auto",minWidth:"48px"},children:!lt&&wn(j)?r.jsx("a",{href:R||"#",target:R?"_blank":void 0,rel:R?"noopener noreferrer":void 0,onClick:R?Q:void 0,className:"block",style:{cursor:R?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:r.jsx("img",{src:j,alt:`${p} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{et(!0),a.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):r.jsx("div",{className:"flex items-center justify-center text-lg font-semibold",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px",backgroundColor:fe.logoFallbackBg,color:fe.logoFallbackText,fontSize:"18px"},children:B})}),r.jsxs("div",{className:"flex-1",style:{width:"100%",minWidth:0},children:[xe&&!S&&r.jsx("div",{className:"mb-2",children:r.jsx("h3",{className:"font-semibold text-base",style:{fontSize:"14px",lineHeight:1.35,color:fe.text},children:R&&p?r.jsxs(r.Fragment,{children:[r.jsx("a",{href:R,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-semibold",style:{color:fe.link,textDecoration:"underline",textDecorationColor:fe.link,textUnderlineOffset:"2px"},onClick:ge,children:p}),F&&` โ€” ${F}`]}):xe})}),w&&!S&&r.jsx("p",{className:"text-sm mb-3 leading-relaxed",style:{fontSize:"13px",lineHeight:1.45,color:fe.textSecondary},children:w}),S&&L.length>0&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"admesh-tail-product-scroll",style:{marginBottom:"8px",overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch",overscrollBehaviorX:"contain",overscrollBehaviorY:"none",scrollBehavior:"smooth",paddingBottom:"2px"},children:r.jsx("div",{style:{display:"flex",gap:"10px",minWidth:"max-content",scrollSnapType:"x proximity",paddingRight:0},children:L.map(H=>{const be=vt(H.product_name)||"Product",le=vt(H.product_link)||vt(H.product_url)||R||"#",Et=ko(vt(H.product_description),10),Qe=So(H.product_price,H.product_currency),xt=Ao(H.product_discount,H.product_discount_type,H.product_currency),bt=vt(H.product_image_url),De=j&&wn(j)?j:"",ct=bt&&wn(bt)?bt:De,rt=or(H.product_cta_label),qt=le!=="#";return r.jsx("a",{href:le,target:qt?"_blank":void 0,rel:qt?"noopener noreferrer":void 0,onClick:Ot=>me(`tail_ad_product_${H.product_id||"item"}`,Ot),className:"block",style:{border:`1px solid ${O}`,borderRadius:"8px",padding:"10px",backgroundColor:fe.surfaceMuted,textDecoration:"none",color:fe.text,minWidth:"min(264px, 82vw)",width:"clamp(220px, 72vw, 312px)",flex:"0 0 clamp(220px, 72vw, 312px)",scrollSnapAlign:"start"},children:r.jsxs("div",{className:"flex items-start gap-2",children:[ct?r.jsx("img",{src:ct,alt:be,style:{width:"44px",height:"44px",objectFit:"cover",borderRadius:"6px",flexShrink:0}}):r.jsx("div",{className:"flex items-center justify-center text-xs font-semibold",style:{width:"44px",height:"44px",borderRadius:"6px",flexShrink:0,backgroundColor:fe.productImageFallbackBg,color:fe.textSecondary,fontSize:"12px"},children:be.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("p",{className:"font-medium text-sm",style:{fontSize:"13px",lineHeight:1.3,color:fe.text,marginBottom:"4px"},children:be}),Et&&r.jsx("p",{className:"text-xs",style:{fontSize:"12px",lineHeight:1.3,color:fe.textSecondary,marginBottom:"6px"},children:Et}),(Qe||xt)&&r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{marginBottom:rt?"6px":0},children:[Qe&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{style:{fontSize:"10px",color:fe.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Price"}),r.jsx("span",{className:"font-semibold",style:{fontSize:"13px",color:fe.text},children:Qe})]}),xt&&r.jsx("span",{className:"text-xs",style:{fontSize:"11px",color:fe.successText,backgroundColor:fe.successBg,borderRadius:"999px",padding:"2px 8px",fontWeight:600},children:xt})]}),rt&&r.jsx("span",{className:"font-medium",style:{fontSize:"12px",color:fe.link,textDecoration:"underline",textUnderlineOffset:"2px"},children:rt})]})]})},H.product_id||`${x}-${be}`)})})})}),r.jsxs("div",{className:"mt-2 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[S&&p&&r.jsx("span",{className:"text-sm",style:{fontSize:"13px",color:fe.textSecondary,fontWeight:400},children:p}),$?r.jsx("button",{type:"button",onClick:Ee,className:"underline transition-colors duration-200 font-medium text-sm",style:{color:fe.link,textDecoration:"underline",textDecorationColor:fe.link,textUnderlineOffset:"2px",fontSize:"13px",background:"none",border:"none",padding:0,cursor:"pointer"},children:Y}):null,Z&&r.jsx("a",{href:R,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-medium text-sm",style:{color:fe.link,textDecoration:"underline",textDecorationColor:fe.link,textUnderlineOffset:"2px",fontSize:"13px"},onClick:de,children:q}),S&&A.length>L.length&&r.jsxs("span",{className:"text-xs",style:{fontSize:"11px",color:fe.textMuted},children:["+",A.length-L.length," more"]})]}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsx("p",{className:"text-xs",style:{fontSize:"11px",color:fe.textMuted},children:g})})]}),we?r.jsxs("div",{style:{marginTop:"10px",border:`1px solid ${O}`,borderRadius:"12px",backgroundColor:fe.surfaceSubtle,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:fe.link},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"14px",lineHeight:1.4,color:fe.text,fontWeight:600},children:["Allow ",z||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:fe.textSecondary},children:"The agent will only use the details you choose to share for this request."})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[r.jsx("button",{type:"button",onClick:H=>{H.preventDefault(),H.stopPropagation(),ve(!1)},style:{borderRadius:"10px",border:`1px solid ${O}`,background:k,color:fe.text,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:H=>{H.preventDefault(),H.stopPropagation(),ve(!0)},style:{borderRadius:"10px",border:"none",background:"#2563eb",color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})]})},Ar=({recommendationId:t,admeshLink:e,productId:o,children:s,trackingData:i,className:c,style:u})=>{const b=l.useRef(null);l.useEffect(()=>{if(!b.current)return;b.current.querySelectorAll("a").forEach(d=>{(!d.hasAttribute("target")||d.getAttribute("target")!=="_blank")&&(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer"))})},[s]);const h=l.useCallback(_=>{const m=_.target.closest("a");m?((!m.href||m.href==="#"||m.href==="")&&e&&(m.href=e),(!m.hasAttribute("target")||m.getAttribute("target")!=="_blank")&&(m.setAttribute("target","_blank"),m.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):a.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return r.jsx("div",{ref:b,className:c,onClick:h,style:{cursor:"pointer",...u},children:s})};Ar.displayName="AdMeshLinkTracker";function Mo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var vn={exports:{}};/*!
43
- Copyright (c) 2018 Jed Watson.
44
- Licensed under the MIT License (MIT), see
45
- http://jedwatson.github.io/classnames
46
- */var sr;function jo(){return sr||(sr=1,(function(t){(function(){var e={}.hasOwnProperty;function o(){for(var c="",u=0;u<arguments.length;u++){var b=arguments[u];b&&(c=i(c,s(b)))}return c}function s(c){if(typeof c=="string"||typeof c=="number")return c;if(typeof c!="object")return"";if(Array.isArray(c))return o.apply(null,c);if(c.toString!==Object.prototype.toString&&!c.toString.toString().includes("[native code]"))return c.toString();var u="";for(var b in c)e.call(c,b)&&c[b]&&(u=i(u,b));return u}function i(c,u){return u?c?c+" "+u:c+u:c}t.exports?(o.default=o,t.exports=o):window.classNames=o})()})(vn)),vn.exports}var Eo=jo();const Ro=Mo(Eo),To={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Io={"Top Match":"โ˜…","Free Tier":"โ—†","AI Powered":"โ—‰",Popular:"โ–ฒ",New:"โ—","Trial Available":"โ—ˆ"},Cr=({type:t,variant:e,size:o="md",className:s,style:i})=>{const c=e||To[t]||"secondary",u=Io[t],b=Ro("admesh-component","admesh-badge",`admesh-badge--${c}`,`admesh-badge--${o}`,s);return r.jsxs("span",{className:b,style:i,children:[u&&r.jsx("span",{className:"admesh-badge__icon",children:u}),r.jsx("span",{className:"admesh-badge__text",children:t})]})};Cr.displayName="AdMeshBadge";/**
1
+ "use strict";var Or=Object.defineProperty;var Vr=(t,e,o)=>e in t?Or(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var Oe=(t,e,o)=>Vr(t,typeof e!="symbol"?e+"":e,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),Kr=require("react-dom/client"),l=require("react"),Gr=require("react-dom");let Lt=!1;var pr;try{typeof globalThis.importMeta<"u"&&((pr=globalThis.importMeta.env)!=null&&pr.PROD)&&(Lt=!0)}catch{}Lt||(Lt=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const a={log:(...t)=>{Lt||console.log(...t)},warn:(...t)=>{Lt||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{Lt||console.info(...t)},debug:(...t)=>{Lt||console.debug(...t)}};/**
2
+ * @license lucide-react v0.563.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const hr=(...t)=>t.filter((e,o,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===o).join(" ").trim();/**
47
7
  * @license lucide-react v0.563.0 - ISC
48
8
  *
49
9
  * This source code is licensed under the ISC license.
50
10
  * See the LICENSE file in the root directory of this source tree.
51
- */const Mr=(...t)=>t.filter((e,o,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===o).join(" ").trim();/**
11
+ */const Yr=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
52
12
  * @license lucide-react v0.563.0 - ISC
53
13
  *
54
14
  * This source code is licensed under the ISC license.
55
15
  * See the LICENSE file in the root directory of this source tree.
56
- */const Do=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
16
+ */const Qr=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,o,s)=>s?s.toUpperCase():o.toLowerCase());/**
57
17
  * @license lucide-react v0.563.0 - ISC
58
18
  *
59
19
  * This source code is licensed under the ISC license.
60
20
  * See the LICENSE file in the root directory of this source tree.
61
- */const Po=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,o,s)=>s?s.toUpperCase():o.toLowerCase());/**
21
+ */const Xn=t=>{const e=Qr(t);return e.charAt(0).toUpperCase()+e.slice(1)};/**
62
22
  * @license lucide-react v0.563.0 - ISC
63
23
  *
64
24
  * This source code is licensed under the ISC license.
65
25
  * See the LICENSE file in the root directory of this source tree.
66
- */const ir=t=>{const e=Po(t);return e.charAt(0).toUpperCase()+e.slice(1)};/**
26
+ */var Xr={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
67
27
  * @license lucide-react v0.563.0 - ISC
68
28
  *
69
29
  * This source code is licensed under the ISC license.
70
30
  * See the LICENSE file in the root directory of this source tree.
71
- */var $o={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
31
+ */const Jr=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
72
32
  * @license lucide-react v0.563.0 - ISC
73
33
  *
74
34
  * This source code is licensed under the ISC license.
75
35
  * See the LICENSE file in the root directory of this source tree.
76
- */const Lo=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
36
+ */const Zr=l.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:o=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...y},g)=>l.createElement("svg",{ref:g,...Xr,width:e,height:e,stroke:t,strokeWidth:s?Number(o)*24/Number(e):o,className:hr("lucide",i),...!c&&!Jr(y)&&{"aria-hidden":"true"},...y},[...u.map(([v,d])=>l.createElement(v,d)),...Array.isArray(c)?c:[c]]));/**
77
37
  * @license lucide-react v0.563.0 - ISC
78
38
  *
79
39
  * This source code is licensed under the ISC license.
80
40
  * See the LICENSE file in the root directory of this source tree.
81
- */const zo=l.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:o=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...b},h)=>l.createElement("svg",{ref:h,...$o,width:e,height:e,stroke:t,strokeWidth:s?Number(o)*24/Number(e):o,className:Mr("lucide",i),...!c&&!Lo(b)&&{"aria-hidden":"true"},...b},[...u.map(([_,d])=>l.createElement(_,d)),...Array.isArray(c)?c:[c]]));/**
41
+ */const Ft=(t,e)=>{const o=l.forwardRef(({className:s,...i},c)=>l.createElement(Zr,{ref:c,iconNode:e,className:hr(`lucide-${Yr(Xn(t))}`,`lucide-${t}`,s),...i}));return o.displayName=Xn(t),o};/**
82
42
  * @license lucide-react v0.563.0 - ISC
83
43
  *
84
44
  * This source code is licensed under the ISC license.
85
45
  * See the LICENSE file in the root directory of this source tree.
86
- */const Bt=(t,e)=>{const o=l.forwardRef(({className:s,...i},c)=>l.createElement(zo,{ref:c,iconNode:e,className:Mr(`lucide-${Do(ir(t))}`,`lucide-${t}`,s),...i}));return o.displayName=ir(t),o};/**
46
+ */const eo=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],to=Ft("flag",eo);/**
87
47
  * @license lucide-react v0.563.0 - ISC
88
48
  *
89
49
  * This source code is licensed under the ISC license.
90
50
  * See the LICENSE file in the root directory of this source tree.
91
- */const No=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],Fo=Bt("maximize-2",No);/**
51
+ */const no=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],ro=Ft("maximize-2",no);/**
92
52
  * @license lucide-react v0.563.0 - ISC
93
53
  *
94
54
  * This source code is licensed under the ISC license.
95
55
  * See the LICENSE file in the root directory of this source tree.
96
- */const Wo=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Bo=Bt("minimize-2",Wo);/**
56
+ */const oo=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],so=Ft("minimize-2",oo);/**
97
57
  * @license lucide-react v0.563.0 - ISC
98
58
  *
99
59
  * This source code is licensed under the ISC license.
100
60
  * See the LICENSE file in the root directory of this source tree.
101
- */const Uo=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],ar=Bt("send",Uo);/**
61
+ */const io=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Jn=Ft("send",io);/**
102
62
  * @license lucide-react v0.563.0 - ISC
103
63
  *
104
64
  * This source code is licensed under the ISC license.
105
65
  * See the LICENSE file in the root directory of this source tree.
106
- */const Ho=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}],["path",{d:"M17 14V2",key:"8ymqnk"}]],lr=Bt("thumbs-down",Ho);/**
66
+ */const ao=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}],["path",{d:"M17 14V2",key:"8ymqnk"}]],Zn=Ft("thumbs-down",ao);/**
107
67
  * @license lucide-react v0.563.0 - ISC
108
68
  *
109
69
  * This source code is licensed under the ISC license.
110
70
  * See the LICENSE file in the root directory of this source tree.
111
- */const qo=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}],["path",{d:"M7 10v12",key:"1qc93n"}]],cr=Bt("thumbs-up",qo);/**
71
+ */const lo=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}],["path",{d:"M7 10v12",key:"1qc93n"}]],er=Ft("thumbs-up",lo);/**
112
72
  * @license lucide-react v0.563.0 - ISC
113
73
  *
114
74
  * This source code is licensed under the ISC license.
115
75
  * See the LICENSE file in the root directory of this source tree.
116
- */const Oo=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],kn=Bt("x",Oo),Sn="admesh-ui-sdk-styles",An="admesh-ui-sdk-reset",Vo=`
76
+ */const co=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],wn=Ft("x",co);function uo(t,e,o){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...o}}function mo(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function po(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,i=e.height,c=e.width;if(i===0||c===0)return 0;const u=Math.max(0,e.top),y=Math.min(o,e.bottom),g=Math.max(0,e.left),v=Math.min(s,e.right),d=Math.max(0,y-u),h=Math.max(0,v-g),w=d*h,C=i*c;return C>0?w/C:0}function tr(){const t=window.innerHeight,e=document.documentElement.scrollHeight,o=window.pageYOffset||document.documentElement.scrollTop,s=e-t;return s<=0?100:Math.min(100,o/s*100)}function ho(t){const e=t.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+o,left:e.left+s}}function fo(t){const e=t.getBoundingClientRect(),o=ho(t),s=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,c=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:mo(s),viewportWidth:s,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:c,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function go(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function xo(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function nr(t=new Date){return t.toISOString()}function bo(t){return t.length===0?0:t.reduce((o,s)=>o+s,0)/t.length}function rr(t,e){let o;return function(...i){o||(t(...i),o=!0,setTimeout(()=>o=!1,e))}}const yo={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let _o=yo,wo=!1;function fr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:i,config:c}){const u={..._o,...c},y=l.useRef(go()),[g,v]=l.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:nr(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:u.enabled}),d=l.useRef(null),h=l.useRef(null),w=l.useRef(null),C=l.useRef(null),m=l.useRef(null),b=l.useRef([]),f=l.useRef([]),p=l.useRef(null),E=l.useCallback(S=>{u.debug&&a.log(`[AdMesh Viewability] ${S}`)},[u.debug]),I=l.useCallback(async(S,L)=>{if(!(!u.enabled||wo||!i.current||!d.current)&&(E(`Analytics disabled - skipping event: ${S}`),u.onEvent)){const N=fo(i.current),B={eventType:S,timestamp:nr(),sessionId:y.current,productId:t,offerId:e,agentId:o,recommendationId:s,timeMetrics:g.timeMetrics,engagementMetrics:g.engagementMetrics,contextMetrics:N,mrcStandards:d.current,isViewable:g.isViewable,metadata:L};u.onEvent(B)}},[u,t,e,o,s,i,g,E]),G=l.useCallback(async()=>{f.current.length!==0&&(E("Analytics disabled - clearing batch without sending"),f.current=[],p.current&&(clearTimeout(p.current),p.current=null))},[E]),k=l.useCallback(rr(()=>{if(!i.current)return;const S=po(i.current),L=Date.now(),N=new Date(g.timeMetrics.loadedAt).getTime();v(B=>{const $={...B};S>0&&b.current.push(S);const z=B.isVisible,D=S>0;if(D&&!z)h.current=L,$.engagementMetrics.viewportEnterCount++,$.timeMetrics.timeToFirstVisible||($.timeMetrics.timeToFirstVisible=L-N,$.engagementMetrics.scrollDepthAtFirstVisible=tr(),I("ad_visible"));else if(!D&&z){if(h.current){const Q=L-h.current;$.timeMetrics.totalVisibleDuration+=Q,h.current=null}$.engagementMetrics.viewportExitCount++,I("ad_hidden")}else if(D&&z&&h.current){const Q=L-h.current;$.timeMetrics.totalVisibleDuration+=Q,h.current=L}if($.isVisible=D,$.visibilityPercentage=S,S>$.engagementMetrics.maxVisibilityPercentage&&($.engagementMetrics.maxVisibilityPercentage=S),b.current.length>0&&($.engagementMetrics.averageVisibilityPercentage=bo(b.current)),d.current){const Q=B.isViewable,J=xo(S,$.timeMetrics.totalVisibleDuration,d.current);if(J&&!Q)$.isViewable=!0,$.timeMetrics.timeToViewable=L-N,w.current=L,I("ad_viewable");else if(J&&Q&&w.current){const ge=L-w.current;$.timeMetrics.totalViewableDuration+=ge,w.current=L}}return $.engagementMetrics.currentScrollDepth=tr(),$})},100),[i,g.timeMetrics.loadedAt,I]);return l.useEffect(()=>{if(!i.current)return;const S=i.current.getBoundingClientRect();d.current=uo(S.width,S.height,u.mrcStandards),E("Initialized MRC standards"),I("ad_loaded")},[i,u.mrcStandards,E,I]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=new IntersectionObserver(L=>{L.forEach(()=>{k()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return S.observe(i.current),()=>{S.disconnect()}},[u.enabled,i,k]),l.useEffect(()=>{if(!u.enabled)return;const S=rr(()=>{k()},100);return window.addEventListener("scroll",S,{passive:!0}),()=>window.removeEventListener("scroll",S)},[u.enabled,k]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{C.current=Date.now(),v(B=>({...B,engagementMetrics:{...B.engagementMetrics,hoverCount:B.engagementMetrics.hoverCount+1}})),I("ad_hover_start")},N=()=>{if(C.current){const B=Date.now()-C.current;v($=>({...$,timeMetrics:{...$.timeMetrics,totalHoverDuration:$.timeMetrics.totalHoverDuration+B}})),C.current=null,I("ad_hover_end",{hoverDuration:B})}};return S.addEventListener("mouseenter",L),S.addEventListener("mouseleave",N),()=>{S.removeEventListener("mouseenter",L),S.removeEventListener("mouseleave",N)}},[u.enabled,i,I]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{m.current=Date.now(),I("ad_focus")},N=()=>{if(m.current){const B=Date.now()-m.current;v($=>({...$,timeMetrics:{...$.timeMetrics,totalFocusDuration:$.timeMetrics.totalFocusDuration+B}})),m.current=null,I("ad_blur",{focusDuration:B})}};return S.addEventListener("focus",L),S.addEventListener("blur",N),()=>{S.removeEventListener("focus",L),S.removeEventListener("blur",N)}},[u.enabled,i,I]),l.useEffect(()=>{if(!u.enabled||!i.current)return;const S=i.current,L=()=>{v(N=>({...N,engagementMetrics:{...N.engagementMetrics,wasClicked:!0}})),I("ad_click")};return S.addEventListener("click",L),()=>{S.removeEventListener("click",L)}},[u.enabled,i,I]),l.useEffect(()=>()=>{const S=Date.now(),L=new Date(g.timeMetrics.loadedAt).getTime(),N=S-L;v(B=>({...B,timeMetrics:{...B.timeMetrics,sessionDuration:N}})),I("ad_unloaded",{sessionDuration:N}),G()},[]),g}const Zt=({productId:t,offerId:e,agentId:o,recommendationId:s,exposureUrl:i,sessionId:c,triggerExposureUrl:u=!0,children:y,config:g,className:v,style:d,onViewabilityChange:h,onVisible:w,onViewable:C,onClick:m})=>{const b=l.useRef(null),f=l.useRef(!1),p=fr({productId:t,offerId:e,agentId:o,recommendationId:s,elementRef:b,config:g}),E=l.useRef(p.isViewable);l.useEffect(()=>{f.current=!1,E.current=!1},[i,s,c]),l.useEffect(()=>{p.isViewable!==E.current&&(E.current=p.isViewable,h&&h(p.isViewable),p.isViewable&&C&&C(),p.isViewable&&!f.current&&u&&(a.log("[AdMeshViewabilityTracker] ๐ŸŽฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:i?"present":"MISSING",sessionId:c?"present":"MISSING",recommendationId:s}),i&&c?(f.current=!0,a.log("[AdMeshViewabilityTracker] ๐Ÿ”ฅ Firing exposure pixel:",i),fetch(i,{method:"GET",keepalive:!0}).then(()=>{a.log("[AdMesh] โœ… Exposure pixel fired successfully")}).catch(k=>{a.warn("[AdMesh] โš ๏ธ Failed to fire exposure pixel:",k),f.current=!1})):a.warn("[AdMeshViewabilityTracker] โš ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!i,hasSessionId:!!c})))},[p.isViewable,h,C,i,c,s,u]);const I=l.useRef(p.isVisible);l.useEffect(()=>{p.isVisible!==I.current&&(I.current=p.isVisible,p.isVisible&&w&&w())},[p.isVisible,w]);const G=()=>{m&&m()};return r.jsx("div",{ref:b,className:v,style:d,onClick:G,"data-admesh-viewability-tracker":!0,"data-recommendation-id":s,"data-is-viewable":p.isViewable,"data-is-visible":p.isVisible,"data-visibility-percentage":p.visibilityPercentage.toFixed(2),children:y})};Zt.displayName="AdMeshViewabilityTracker";const or=t=>{try{return new URL(t),!0}catch{return!1}},Ut=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",lt=t=>Ut(t)||void 0,vo=t=>t&&t.trim()?t.trim():"",ko=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return Ut(t)},jn=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:c=!0,onDelegationConsent:u,onDelegationActivated:y,onStartDelegation:g,onRecommendationReport:v})=>{var jt,ut,Et,_t,mt,Rt,st,Ve,ze;if(!t||t.length===0)return a.log("[AdMesh Compact Tail Ad] No recommendations provided - not rendering"),null;const d=t[0],h=d==null?void 0:d.recommendation,w=h==null?void 0:h.creative,C=d==null?void 0:d.tracking,m=d==null?void 0:d.delegation,b=(d==null?void 0:d.recommendation_id)||"",f=(h==null?void 0:h.offerId)||"",p=(w==null?void 0:w.brand_name)||"",E=(w==null?void 0:w.headline)||"",I=(w==null?void 0:w.description)||"",G=(w==null?void 0:w.logo_url)||"",k=(C==null?void 0:C.click_url)||(w==null?void 0:w.landing_page_url)||"",S=(C==null?void 0:C.exposure_url)||"",L=(h==null?void 0:h.disclosure)||"Sponsored",N=(w==null?void 0:w.products)||[],B=N.slice(0,4),$=N.length>1,D=((h==null?void 0:h.format)||"tail")==="bridge",Q=(m==null?void 0:m.available)===!0,J=D&&Q,ge=(m==null?void 0:m.brand_name)||p,V="Talk to Agent",ee=vo(w==null?void 0:w.cta_text),me=!$&&!!ee&&!!k;if(!p&&!E&&!I)return a.log("[AdMesh Compact Tail Ad] No valid recommendation data provided - not rendering",{recommendationId:b}),null;const xe=E&&E!==p?E:p,q=I,oe=p.trim().toLowerCase(),ve=xe.trim().toLowerCase(),Ne=!!p&&oe!==ve,[Pe,be]=l.useState(!1),[we,Se]=l.useState(!1),[_e,Fe]=l.useState(null),Ee=l.useRef(null);l.useEffect(()=>()=>{Ee.current&&(Ee.current(!1),Ee.current=null)},[]);const rt=O=>{var fe;(fe=Ee.current)==null||fe.call(Ee,O),Ee.current=null,be(!1)},F=async()=>u?await u(d):await new Promise(O=>{Ee.current=O,be(!0)}),_=(O,fe)=>{fe&&fe.stopPropagation(),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:b,productId:f,clickUrl:k,source:O}).catch(()=>{a.error(`[AdMesh] Failed to track ${O} click`)})},H=[{value:"irrelevant",label:"Not relevant"},{value:"misleading",label:"Misleading"},{value:"inappropriate",label:"Inappropriate"},{value:"broken_link",label:"Broken link"},{value:"other",label:"Other"}],A=O=>{O.preventDefault(),O.stopPropagation(),!_e&&Se(fe=>!fe)},ie=async(O,fe)=>{if(O.preventDefault(),O.stopPropagation(),Se(!1),Fe(fe),!!v)try{await v({recommendation:d,recommendation_id:b,reason:fe,session_id:i})}catch(Ue){a.warn("[AdMesh Compact Tail Ad] Failed to submit recommendation report:",Ue)}},ke=()=>{$||!k||(_("compact_tail_ad_card"),typeof window<"u"&&window.open(k,"_blank","noopener,noreferrer"))},T=O=>{$||!k||(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),ke())},se=async()=>{if(b&&i)try{const O=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",fe=await fetch(`${O}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:b,session_id:i,is_test:!1})});fe.ok||a.warn("[AdMesh Compact Tail Ad] Delegation engagement tracking failed:",fe.statusText)}catch(O){a.error("[AdMesh Compact Tail Ad] Error tracking delegation engagement:",O)}},j=async O=>{if(O.preventDefault(),O.stopPropagation(),!d||!J||(_("compact_tail_ad_delegation_cta"),await se(),!await F()))return;const Ue=m!=null&&m.available?{recommendation_id:d.recommendation_id,brand_id:lt(m.brand_id),brand_name:lt(m.brand_name||(w==null?void 0:w.brand_name)),eligibility_reason:lt(m.eligibility_reason),delegate_reason:lt(m.delegate_reason),session_goal:lt(m.session_goal),desired_outcome_type:m.desired_outcome_type,required_user_inputs:Array.isArray(m.required_user_inputs)?m.required_user_inputs.filter(Ke=>typeof Ke=="string"):[],required_consent_types:Array.isArray(m.required_consent_types)?m.required_consent_types.filter(Ke=>typeof Ke=="string"):[],success_outcome:lt(m.success_outcome),fallback_message:lt(m.fallback_message),session_mode:lt(m.session_mode),status:lt(m.status),capabilities:m.capabilities||[],allowed_data_types:m.allowed_data_types||[],consent_requirements:m.consent_requirements||[],auth_model:lt(m.auth_model),handoff_protocol:m.handoff_protocol&&typeof m.handoff_protocol=="object"?m.handoff_protocol:void 0,supported_actions:m.supported_actions||[],metadata:m.metadata&&typeof m.metadata=="object"?m.metadata:void 0,platform_response:d}:null;if(y&&Ue){await y(Ue);return}if(g){await g(d);return}},[ce,re]=l.useState(!1),Y=(e==null?void 0:e.mode)==="dark"||typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,K=(e==null?void 0:e.surfaceColor)||((ut=(jt=e==null?void 0:e.components)==null?void 0:jt.card)==null?void 0:ut.backgroundColor)||(Y?"#111827":"#ffffff"),ae=(e==null?void 0:e.borderColor)||((_t=(Et=e==null?void 0:e.components)==null?void 0:Et.card)==null?void 0:_t.borderColor)||(Y?"rgba(255, 255, 255, 0.10)":"rgba(15, 23, 42, 0.08)"),Be=((mt=e==null?void 0:e.shadows)==null?void 0:mt.medium)||((st=(Rt=e==null?void 0:e.components)==null?void 0:Rt.card)==null?void 0:st.boxShadow)||(Y?"0 8px 18px rgba(0, 0, 0, 0.28)":"0 8px 18px rgba(15, 23, 42, 0.08)"),Te="#2563eb",M=Y?"#9ca3af":"#6b7280",Ce=Y?"#e5e7eb":"#374151",Ie=Y?"#f9fafb":"#0f172a",ot=Y?"rgba(255, 255, 255, 0.04)":"#f8fafc",yt="50px",et=J||me?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flexWrap:"wrap"},children:[J?r.jsx("button",{type:"button",onClick:j,style:{background:"none",border:"none",padding:0,color:Te,fontSize:"12px",fontWeight:500,cursor:"pointer",textDecoration:"none"},children:V}):null,me?r.jsx("a",{href:k,target:"_blank",rel:"noopener noreferrer",onClick:O=>_("compact_tail_ad_cta",O),style:{color:Te,fontSize:"12px",fontWeight:600,textDecoration:"none"},children:ee}):null]}):null;return r.jsxs(Zt,{productId:f,recommendationId:b,exposureUrl:S,sessionId:i,triggerExposureUrl:c,className:`admesh-compact-tail-ad ${o}`,style:{all:"initial",boxSizing:"border-box",display:"block",fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[r.jsx("style",{children:`
77
+ .admesh-compact-tail-ad,
78
+ .admesh-compact-tail-ad * {
79
+ box-sizing: border-box;
80
+ }
81
+
82
+ .admesh-compact-line-clamp-1 {
83
+ overflow: hidden;
84
+ display: -webkit-box;
85
+ -webkit-box-orient: vertical;
86
+ -webkit-line-clamp: 1;
87
+ }
88
+
89
+ .admesh-compact-line-clamp-2 {
90
+ overflow: hidden;
91
+ display: -webkit-box;
92
+ -webkit-box-orient: vertical;
93
+ -webkit-line-clamp: 2;
94
+ }
95
+
96
+ .admesh-compact-tail-scroll {
97
+ -ms-overflow-style: none;
98
+ scrollbar-width: none;
99
+ }
100
+
101
+ .admesh-compact-tail-scroll::-webkit-scrollbar {
102
+ display: none;
103
+ }
104
+
105
+ @media (max-width: 420px) {
106
+ .admesh-compact-meta-row {
107
+ align-items: flex-start !important;
108
+ }
109
+
110
+ .admesh-compact-disclosure-actions {
111
+ gap: 4px !important;
112
+ }
113
+
114
+ .admesh-compact-footer-row,
115
+ .admesh-compact-report-panel,
116
+ .admesh-compact-report-status {
117
+ margin-left: 0 !important;
118
+ }
119
+
120
+ .admesh-compact-report-panel {
121
+ width: 100%;
122
+ }
123
+
124
+ .admesh-compact-report-option {
125
+ flex: 1 1 calc(50% - 6px);
126
+ min-height: 34px;
127
+ }
128
+ }
129
+ `}),r.jsxs("div",{role:!$&&k?"link":void 0,tabIndex:!$&&k?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((ze=(Ve=e==null?void 0:e.components)==null?void 0:Ve.card)==null?void 0:ze.borderRadius)||"14px",border:`1px solid ${ae}`,background:K,boxShadow:Be,minWidth:0,cursor:!$&&k?"pointer":void 0},onClick:ke,onKeyDown:T,children:[r.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[r.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:Y?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!ce&&G&&or(G)?r.jsx("img",{src:G,alt:`${p} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>re(!0)}):r.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:M},children:(p||"A").charAt(0).toUpperCase()})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsxs("div",{className:"admesh-compact-meta-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[r.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"11px",color:M},children:Ne?p:""}),r.jsx("span",{style:{flexShrink:0,fontSize:"10px",color:M,textTransform:"uppercase",letterSpacing:"0.08em"},children:L})]}),!$&&r.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",lineHeight:1.3,fontWeight:700,color:Ie,marginBottom:"4px"},title:xe,children:xe}),q&&r.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"12px",lineHeight:1.35,color:Ce},title:q,children:q})]})]}),$&&r.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:B.map(O=>{const fe=Ut(O.product_name)||"Product",Ue=Ut(O.product_link)||Ut(O.product_url)||k||"#",Ke=ko(O.product_price,O.product_currency),tt=Ut(O.product_image_url),pt=tt&&or(tt)?tt:"",wt=Ue!=="#";return r.jsx("a",{href:Ue,target:wt?"_blank":void 0,rel:wt?"noopener noreferrer":void 0,onClick:Tt=>_(`compact_tail_ad_product_${O.product_id||"item"}`,Tt),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${ae}`,borderRadius:"12px",background:ot,padding:"8px",flexShrink:0},children:r.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[r.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:Y?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:M,fontSize:"12px",fontWeight:700},children:pt?r.jsx("img",{src:pt,alt:fe,style:{width:"100%",height:"100%",objectFit:"cover"}}):fe.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("div",{style:{fontSize:"12px",lineHeight:1.25,fontWeight:600,color:Ie,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:fe,children:fe}),r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:Ke&&r.jsx("span",{style:{fontSize:"12px",fontWeight:700,color:Ie},children:Ke})})]})]})},O.product_id||`${b}-${fe}`)})}),r.jsxs("div",{className:"admesh-compact-footer-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:$?0:yt},children:[r.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:et}),r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",marginLeft:"auto",flexShrink:0},children:[$&&N.length>B.length?r.jsxs("span",{style:{fontSize:"10px",color:M},children:["+",N.length-B.length," more"]}):null,r.jsx("button",{type:"button","aria-label":_e?"Recommendation reported":"Report recommendation",title:_e?"Reported":"Report recommendation",disabled:!!_e,onClick:A,style:{width:"28px",height:"28px",borderRadius:"999px",border:`1px solid ${ae}`,background:_e?ot:K,color:_e?Te:M,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,cursor:_e?"default":"pointer",flexShrink:0},children:r.jsx(to,{size:13})})]})]}),we?r.jsx("div",{className:"admesh-compact-report-panel",onClick:O=>O.stopPropagation(),style:{marginLeft:$?0:yt,border:`1px solid ${ae}`,borderRadius:"12px",background:ot,padding:"8px",display:"flex",flexWrap:"wrap",gap:"6px"},children:H.map(O=>r.jsx("button",{className:"admesh-compact-report-option",type:"button",onClick:fe=>ie(fe,O.value),style:{borderRadius:"999px",border:`1px solid ${ae}`,background:K,color:Ie,fontSize:"11px",fontWeight:600,padding:"6px 9px",cursor:"pointer"},children:O.label},O.value))}):null,_e?r.jsx("div",{className:"admesh-compact-report-status",style:{marginLeft:$?0:yt,fontSize:"11px",color:M},children:"Thanks for reporting this recommendation."}):null,Pe?r.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${ae}`,borderRadius:"12px",background:ot,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:Te},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:Ie,fontWeight:600},children:["Allow ",ge||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:Ce},children:"The agent will only use the details you choose to share for this request."})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[r.jsx("button",{type:"button",onClick:O=>{O.preventDefault(),O.stopPropagation(),rt(!1)},style:{borderRadius:"10px",border:`1px solid ${ae}`,background:K,color:Ie,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:O=>{O.preventDefault(),O.stopPropagation(),rt(!0)},style:{borderRadius:"10px",border:"none",background:Te,color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})},gr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:c,onDelegationActivated:u,onStartDelegation:y})=>{const g=t.filter(d=>d&&typeof d=="object"&&typeof d.recommendation_id=="string"&&d.recommendation_id.length>0);if(!g||g.length===0)return a.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;a.log(`[AdMeshLayout] Rendering with ${g.length} valid recommendations`);const v=()=>{var d;if(g.length>0){const h=g[0],w=(d=h.recommendation)==null?void 0:d.format;a.log("[AdMeshLayout] ๐Ÿ” Checking format:",{preferredFormat:w,recommendationKeys:Object.keys(h||{})}),(w==="product_card"||w==="weave"||w==="bridge")&&a.warn(`[AdMeshLayout] ${w} format requested, falling back to tail for canonical render payload`)}return r.jsx(jn,{recommendations:g,theme:e,sessionId:i,onDelegationConsent:c,onDelegationActivated:u,onStartDelegation:y})};return r.jsx("div",{className:`admesh-layout ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:v()})};class xr{constructor(e){Oe(this,"firedExposures",new Set);Oe(this,"debug",!1);Oe(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,o,s){const i=`${s}_${o}`;if(this.firedExposures.has(i)){this.debug&&a.log("[Tracker] Exposure already fired");return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&a.warn("[Tracker] Failed to fire exposure")}),this.debug&&a.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&a.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,i){const c=`${s}_${o}`;if(this.firedExposures.has(c)){this.debug&&a.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let y=null,g=null;const v=new IntersectionObserver(w=>{w.forEach(C=>{C.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?y===null&&(y=Date.now(),this.debug&&a.log("[Tracker] Ad reached MRC visibility threshold"),g=setTimeout(()=>{this.fireExposure(e,o,s),v.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):y!==null&&(g&&(clearTimeout(g),g=null),y=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"});v.observe(i);const h=setTimeout(()=>{v.disconnect(),g&&clearTimeout(g),u()},3e4);i.__admeshTrackerCleanup=()=>{v.disconnect(),g&&clearTimeout(g),clearTimeout(h)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}fireFollowupExposure(e,o,s){this.fireExposure(e,o,s)}fireFollowupEngagement(e,o,s){return fetch(e,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s})}).catch(i=>{this.debug&&a.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const En=l.createContext(void 0);function Rn(){const t=l.useContext(En);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function So(t){const e=t.split("/").filter(Boolean),i=(e[e.length-1]||e[e.length-2]||"").replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i?i.replace(/\b\w/g,c=>c.toUpperCase()):"This page"}function br(){var t;try{console.log("[AdMesh] Starting direct headings extraction...");const e=v=>v.replace(/\s+/g," ").trim(),o=()=>{var f;const v=["article","main article","main",'[role="main"]',"[data-admesh-article]",".article-content",".post-content",".entry-content",".content"],d=["script","style","noscript","svg","canvas","iframe","nav","header","footer","aside",'[aria-hidden="true"]',"[data-admesh-ignore]",".admesh-publisher-assistant-root",".admesh-publisher-assistant-reactMount",".admesh-publisher-assistant-floating",".admesh-publisher-assistant-inline"].join(","),C=(((f=v.map(p=>document.querySelector(p)).filter(p=>!!p).map(p=>{const E=p.cloneNode(!0);E.querySelectorAll(d).forEach(G=>G.remove());const I=e(E.textContent||"");return{element:p,text:I}}).filter(p=>p.text.length>=200).sort((p,E)=>E.text.length-p.text.length)[0])==null?void 0:f.element)||document.body).cloneNode(!0);C.querySelectorAll(d).forEach(p=>p.remove());const m=Array.from(C.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(p=>e(p.textContent||"")).filter(p=>p.length>=24);return(m.length>0?m.join(`
130
+ `):e(C.textContent||"")).slice(0,6e3)},s=So(window.location.pathname||"/"),i=e(document.title||"")||s,u=(()=>{const v=[],d=document.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(d).forEach(h=>{const w=e(h.textContent||"");w.length>0&&v.push(w)}),v})(),y=u.length>0?u:[i||s],g={title:i,headings:y,article_text:o(),url:window.location.href,domain:window.location.hostname,extracted_at:new Date().toISOString()};return console.log("[AdMesh] Extracted headings:",{title:g.title,headingsCount:g.headings.length,articleTextLength:((t=g.article_text)==null?void 0:t.length)||0,domain:g.domain}),g}catch(e){return console.error("[AdMesh] Error in direct headings extraction:",e),null}}function Ao(t){return!!(t&&typeof t=="object"&&"recommendation_id"in t&&"status"in t)}function Co(t){var s,i,c,u,y,g,v,d,h,w,C;if(!t||typeof t!="object")return;if(Ao(t))return t;const e=t;if(!e.recommendation_id)return;const o=(e.products||[]).map(m=>{var b,f;return{product_id:m.product_id||"",product_link:m.product_link||m.product_click_url||e.click_url||e.url||"",product_name:m.product_name||e.title||((b=e.creative_input)==null?void 0:b.product_name)||"",product_description:m.product_description||"",product_price:m.product_price??void 0,product_discount:m.product_discount??void 0,product_currency:m.product_currency,product_discount_type:m.product_discount_type,product_cta_label:m.product_cta_label||((f=e.creative_input)==null?void 0:f.cta_label),product_image_url:m.product_image_url,product_features:m.product_features}});return{spec_version:"1.0",recommendation_id:e.recommendation_id,timestamp:new Date().toISOString(),status:"generated",ttl_ms:3e5,recommendation:{format:e.preferred_format||"tail",disclosure:"Sponsored",creative:{brand_name:((s=e.creative_input)==null?void 0:s.brand_name)||"",headline:e.title||((i=e.creative_input)==null?void 0:i.product_name)||"",description:((c=e.creative_input)==null?void 0:c.short_description)||((u=e.creative_input)==null?void 0:u.long_description)||"",cta_text:((y=e.creative_input)==null?void 0:y.cta_label)||((g=o[0])==null?void 0:g.product_cta_label)||"Learn more",follow_up_suggestion:e.follow_up_suggestion,logo_url:(d=(v=e.creative_input)==null?void 0:v.assets)==null?void 0:d.logo_url,image_urls:((w=(h=e.creative_input)==null?void 0:h.assets)==null?void 0:w.image_urls)||[],landing_page_url:e.url||e.click_url||((C=e.creative_input)==null?void 0:C.cta_url)||"",products:o}},tracking:{exposure_url:e.exposure_url,click_url:e.click_url,followup_exposure_url:e.followup_exposure_url,followup_engagement_url:e.followup_engagement_url}}}function Mo(t){return{...t,suggestions:(t.suggestions||[]).map(e=>({...e,recommendation:Co(e.recommendation)}))}}function sr(t){try{const o=new URL(t).pathname.split("/").filter(i=>i.length>0);return o[o.length-1]||void 0}catch{return}}async function yr(t,e){var o,s,i,c,u;try{console.log("[AdMesh SDK] Starting ACIE analyze-intent call...",{url:t.url});const y=Array.isArray(t.headings)?t.headings:[],g=(o=sr(t.url))==null?void 0:o.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),v=g?g.replace(/\b\w/g,E=>E.toUpperCase()):void 0,d=e.apiKey.toLowerCase().startsWith("pub_")?sr(t.url):void 0,h=e.extension?"extension":"admesh_ui_sdk",w=(t.domain||(typeof window<"u"?window.location.hostname:"")).trim().toLowerCase(),C={url:t.url,title:t.title||void 0,headings:y.length>0?y:v?[v]:void 0,article_text:((s=t.article_text)==null?void 0:s.trim())||void 0,domain:w,article_slug:d,agent_id:void 0,cpx_floor:void 0,source:h,api_key:e.apiKey,user_id:e.userId||void 0};console.log("[AdMesh SDK] Payload prepared:",{url:C.url,titleLength:((i=C.title)==null?void 0:i.length)||0,headingsCount:((c=C.headings)==null?void 0:c.length)||0,articleTextLength:((u=C.article_text)==null?void 0:u.length)||0,domain:C.domain,article_slug:C.article_slug,source:C.source,has_user_id:!!C.user_id});const m=`${e.apiBaseUrl}/acie/analyze-intent`;console.log("[AdMesh SDK] Calling ACIE API:",m);const b=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(C)});if(console.log("[AdMesh SDK] ACIE API response received:",{status:b.status,statusText:b.statusText,ok:b.ok}),!b.ok){const E=await b.text();throw console.error("[AdMesh SDK] ACIE API error:",{status:b.status,statusText:b.statusText,errorText:E}),new Error(`ACIE API error: ${b.status} - ${E}`)}const f=await b.json(),p=Mo(f);return console.log("[AdMesh SDK] ACIE analysis completed:",{url:t.url,suggestionsCount:p.suggestions.length}),p}catch(y){return console.error("[AdMesh SDK] Error calling ACIE analyze-intent endpoint:",y),null}}async function jo(t,e){var c,u;const o=(e.apiBaseUrl||"https://api.useadmesh.com").replace(/\/$/,""),s=new URLSearchParams({url:t.trim()});(c=e.agentDisplayId)!=null&&c.trim()&&s.set("agent_display_id",e.agentDisplayId.trim()),(u=e.publisherId)!=null&&u.trim()&&s.set("publisher_id",e.publisherId.trim());const i=await fetch(`${o}/publisher-assistant/page-context?${s.toString()}`,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e.apiKey}`}});if(!i.ok){const y=await i.text().catch(()=>"");throw new Error(`Page context request failed (${i.status}): ${y||i.statusText}`)}return await i.json()}function Eo(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function Ro(){var t;if(typeof window>"u")return null;try{const e=(t=window.location.href)==null?void 0:t.trim();if(_r(e))return e}catch{return null}return null}function _r(t){const e=t==null?void 0:t.trim();if(!e||/%%[^%]+%%/.test(e))return!1;try{const o=new URL(e);return o.protocol==="http:"||o.protocol==="https:"}catch{return!1}}function To(t){try{const e=new URL(t),o=e.pathname.split("/").filter(Boolean),i=(o[o.length-1]||o[o.length-2]||e.hostname).replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i?i.replace(/\b\w/g,c=>c.toUpperCase()):e.hostname}catch{return"This page"}}function ir(t){const e=new URL(t),o=To(t);return{title:o,headings:[o],article_text:`Article URL: ${t}
131
+ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const Io=6e4,ar=3;function Do(t){const e=Ro();if(e)return e;const o=t==null?void 0:t.trim();return _r(o)?o:null}const wr=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:c,location:u,userId:y,model:g,messages:v,pageContext:d,articleUrl:h,contextMode:w="auto",agentDisplayId:C,children:m})=>{const[b,f]=l.useState(null),[p,E]=l.useState(new Set),[I,G]=l.useState(new Map),[k,S]=l.useState(null),[L,N]=l.useState([]),[B,$]=l.useState(!1),[z,D]=l.useState(null),[Q,J]=l.useState(!1),ge=l.useRef(!1),V=l.useRef(0),ee=l.useRef(null),me=l.useRef(null);me.current=k;const xe=!!d||w==="ad-slot"||w==="auto"&&(!!(h!=null&&h.trim())||Eo()),q=l.useCallback(async()=>{if(d)return d;if(!xe)return br();const F=Do(h);if(!F)return a.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),D("Article URL is required for ad-slot context"),null;if(!t||!i)return a.warn("[AdMeshProvider] Cannot fetch page context: missing API key or base URL"),ir(F);try{J(!0);const _=await jo(F,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:C});return a.log("[AdMeshProvider] Page context resolved",{source:_.source,cache_hit:_.cache_hit,domain:_.context.domain}),_.context}catch(_){return a.error("[AdMeshProvider] Failed to fetch page context:",_),a.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),ir(F)}finally{J(!1)}},[C,i,t,h,d,xe]),oe=l.useCallback((F,_)=>{const H=F.filter(A=>!A.is_sponsored).slice(0,3);return[_,...H]},[]),ve=l.useCallback((F,_)=>{const H=F.find(ie=>ie.is_sponsored),A=_.filter(ie=>!ie.is_sponsored).slice(0,3);return H?[H,...A]:A},[]);l.useEffect(()=>{if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}a.log("[AdMeshProvider] โœ… Session ID available:",e)},[e]),l.useEffect(()=>{if(!t){a.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){a.error("[AdMeshProvider] โŒ Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const F=new Jt({apiKey:t,theme:s,apiBaseUrl:i,extension:o});f(F),a.log("[AdMeshProvider] โœ… AdMesh SDK initialized with session:",e),i&&a.log("[AdMeshProvider] ๐Ÿ“ Using custom API base URL")}catch(F){a.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK:",F)}return()=>{a.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,s,i,e,o]);const Ne=l.useCallback(async F=>{var _;if(!t||!i){a.warn("[AdMeshProvider] โš ๏ธ Cannot perform intent analysis: missing API key or base URL");return}if(o)a.log("[AdMeshProvider] โ„น๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){a.log('[AdMeshProvider] โ„น๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{$(!0),D(null),a.log("[AdMeshProvider] ๐Ÿ”„ Starting automatic intent analysis...");const H=F??await q();if(!H){a.warn("[AdMeshProvider] โš ๏ธ Failed to extract headings for intent analysis"),D("Failed to extract page content");return}a.log("[AdMeshProvider] ๐Ÿ“„ Extracted headings:",{title:H.title,headingsCount:H.headings.length,articleTextLength:((_=H.article_text)==null?void 0:_.length)||0,domain:H.domain});const ie=await yr(H,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:y});ie?(a.log("[AdMeshProvider] โœ… Intent analysis completed:",{suggestionsCount:ie.suggestions.length,suggestions:(ie.suggestions||[]).map(ke=>{var T;return{id:ke.id,text:ke.text,is_sponsored:ke.is_sponsored,recommendationId:((T=ke.recommendation)==null?void 0:T.recommendation_id)||null}})}),N(ke=>ve(ke,ie.suggestions||[]))):(a.warn("[AdMeshProvider] โš ๏ธ Intent analysis returned null"),D("Intent analysis failed"),N(ke=>ke.length>0?(a.log("[AdMeshProvider] โ„น๏ธ Preserving existing suggestions after null intent analysis result"),ke):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(H){a.error("[AdMeshProvider] โŒ Error in intent analysis:",H),D("Intent analysis error"),N(A=>A.length>0?(a.log("[AdMeshProvider] โ„น๏ธ Preserving existing suggestions after intent analysis error"),A):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{$(!1)}},[t,i,o,y,ve,q]),Pe=l.useCallback(async F=>{var A,ie,ke,T,se,j;if(!b||!t||!t.toLowerCase().startsWith("pub_"))return;const _=F??await q();if(!_){a.warn("[AdMeshProvider] โš ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const H=((ie=(A=_.headings)==null?void 0:A[0])==null?void 0:ie.trim())||((ke=_.title)==null?void 0:ke.trim());if(!H){a.warn("[AdMeshProvider] โš ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{a.log("[AdMeshProvider] ๐Ÿ”„ Prefetching sponsored suggestion from /aip/context...");const ce=await b.fetchPlatformResponse({query:H,sessionId:e,messageId:Jt.createMessageId(e),platformSurface:"embedded_assistant",model:g,messages:[],language:c,location:u,userId:y}),re=(j=(se=(T=ce.recommendation)==null?void 0:T.creative)==null?void 0:se.follow_up_suggestion)==null?void 0:j.trim(),Y=ce.recommendation_id;if(!re||!Y){a.log("[AdMeshProvider] โ„น๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const K={id:Y,text:re,type:"action",is_sponsored:!0,recommendation:ce,metadata:{source:"aip_context_prefetch",recommendation_id:Y}};N(ae=>oe(ae,K)),a.log("[AdMeshProvider] โœ… Sponsored suggestion prefetched from /aip/context",{recommendationId:Y,suggestionText:re})}catch(ce){a.warn("[AdMeshProvider] โš ๏ธ Sponsored suggestion prefetch failed (non-blocking):",ce)}},[t,c,u,g,b,e,y,oe,q]),be=l.useCallback(async()=>{a.log("[AdMeshProvider] ๐Ÿ”„ Manual retry of intent analysis"),await Ne()},[Ne]);l.useEffect(()=>{!b||ge.current||(ge.current=!0,(async()=>{const F=await q();await Promise.allSettled([Pe(F),Ne(F)])})())},[b,Ne,Pe,q]);const we=l.useCallback(F=>{if(!F||F.status!=="active")return!1;const _=Date.parse(F.expires_at);return Number.isNaN(_)?!1:_>Date.now()},[]),Se=l.useCallback(async(F,_,H,A)=>{const ie=A??k;if(!ie||!b){a.warn("[AdMeshProvider] โš ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:F,eventType:_,hasSession:!!ie,hasSdk:!!b});return}const ke=new Date().toISOString();a.log("[AdMeshProvider] ๐Ÿ“ก Sending delegation event",{endpoint:F,eventType:_,recommendationId:ie.recommendation_id,delegationSessionId:ie.delegation_session_id,sessionId:ie.session_id});const T=await fetch(`${b.getApiBaseUrl()}${F}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:ie.delegation_session_id,recommendation_id:ie.recommendation_id,session_id:ie.session_id,event_type:_,timestamp:ke,metadata:H||{}})});if(!T.ok){const ce=await T.text();throw a.error("[AdMeshProvider] โŒ Delegation event failed",{endpoint:F,eventType:_,status:T.status,errorBody:ce,recommendationId:ie.recommendation_id,delegationSessionId:ie.delegation_session_id}),new Error(`Delegation event failed (${T.status}): ${ce}`)}const se=await T.json(),j=se==null?void 0:se.session;a.log("[AdMeshProvider] โœ… Delegation event acknowledged",{endpoint:F,eventType:_,recommendationId:ie.recommendation_id,delegationSessionId:ie.delegation_session_id,returnedStatus:(j==null?void 0:j.status)||(se==null?void 0:se.status)}),j&&S(j)},[k,t,b]),_e=l.useCallback(()=>{V.current=0},[]),Fe=l.useCallback(async(F="user_stopped",_)=>{const H=k;if(!H){a.warn("[AdMeshProvider] โš ๏ธ stopDelegationSession called without an active SDK delegation session");return}a.log("[AdMeshProvider] ๐Ÿ›‘ Stopping delegation session",{reason:F,recommendationId:H.recommendation_id,delegationSessionId:H.delegation_session_id}),await Se("/aip/delegation/stop","session_stopped",{reason:F,..._||{}},H),await(b==null?void 0:b.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:H.session_id,recommendation_id:H.recommendation_id,delegation_session_id:H.delegation_session_id,brand_name:H.brand_name,status:"stopped",metadata:{reason:F,..._||{}}}).catch(A=>{a.warn("[AdMeshProvider] โš ๏ธ Failed to track delegation_stopped event:",A)})),V.current=0,ee.current=null,S(null),a.log("[AdMeshProvider] โœ… Delegation session cleared locally after stop")},[k,Se,b]),Ee=l.useCallback(async(F="turn_completed",_)=>{F==="turn_started"&&_e(),await Se("/aip/delegation/activity",F,_)},[Se,_e]);l.useEffect(()=>{const F=(k==null?void 0:k.delegation_session_id)??null;F!==ee.current&&(ee.current=F,V.current=0)},[k==null?void 0:k.delegation_session_id]),l.useEffect(()=>{if(!((k==null?void 0:k.delegation_session_id)??null)||!b)return;const _=me.current;if(!_||!we(_)){S(A=>A?{...A,status:"expired"}:null);return}const H=window.setInterval(()=>{const A=me.current;if(!(!A||!we(A))){if(V.current+=1,V.current>=ar){a.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:A.delegation_session_id,heartbeatsSinceLastUserTurn:V.current,idleHeartbeatLimit:ar}),Fe("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:V.current}).catch(ie=>{a.warn("[AdMeshProvider] โš ๏ธ Failed to stop idle delegation session:",ie)});return}Se("/aip/delegation/heartbeat","heartbeat").catch(ie=>{a.warn("[AdMeshProvider] โš ๏ธ Failed to send delegation heartbeat:",ie)})}},Io);return()=>{window.clearInterval(H)}},[k==null?void 0:k.delegation_session_id,we,Se,b,Fe]);const rt={sdk:b,apiKey:t,sessionId:e,theme:s,language:c,location:u,userId:y,model:g,messages:v,processedMessageIds:p,recommendationResults:I,activeDelegationSession:k,suggestions:L,isAnalyzingIntent:B||Q,intentError:z,markMessageAsProcessed:F=>{E(_=>{const H=new Set(_);return H.add(F),H})},isMessageProcessed:F=>p.has(F),setRecommendationResult:(F,_)=>{G(H=>{const A=new Map(H);return A.set(F,_),A}),E(H=>{const A=new Set(H);return A.add(F),A})},getRecommendationResult:F=>I.get(F),hasRecommendationResult:F=>I.has(F),setActiveDelegationSession:F=>{S(F)},getActiveDelegationSession:()=>we(k)?k:null,hasActiveDelegationSession:()=>we(k),refreshDelegationActivity:Ee,stopDelegationSession:Fe,retryIntentAnalysis:be};return r.jsx(En.Provider,{value:rt,children:m})};class vr{constructor(){Oe(this,"roots",new Map)}async render(e){try{a.log("[AdMeshRenderer] ๐ŸŽจ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){a.log("[AdMeshRenderer] โš ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw a.error("[AdMeshRenderer] โŒ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);a.log("[AdMeshRenderer] โœ… Container ready");const i=this.roots.get(e.containerId);i&&(a.log("[AdMeshRenderer] ๐Ÿงน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const c=Kr.createRoot(s);a.log("[AdMeshRenderer] ๐Ÿ“Š Rendering recommendations"),c.render(r.jsx(wr,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:r.jsx(gr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",a.log("[AdMeshRenderer] โœ… Recommendations rendered successfully"),this.roots.set(e.containerId,c)}catch(o){throw a.error("[AdMeshRenderer] โŒ Error rendering recommendations"),o}}unmount(e){const o=this.roots.get(e);if(o){o.unmount(),this.roots.delete(e);const s=document.getElementById(e);s&&(s.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}const Po=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},dt=class dt{constructor(e){Oe(this,"config");Oe(this,"apiBaseUrl");Oe(this,"renderer",null);Oe(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl,extension:e.extension,extensionSourceDomain:e.extensionSourceDomain,userId:e.userId},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}getApiBaseUrl(){return this.apiBaseUrl}static buildPlatformResponseCacheKey(e,o){return`${e}::${o}`}getExtensionSourceDomain(){var o,s;const e=(o=this.config.extensionSourceDomain)==null?void 0:o.trim();if(e)return e.toLowerCase();if(typeof window<"u"&&((s=window.location)!=null&&s.hostname))return window.location.hostname.trim().toLowerCase()||void 0}static createSession(){const e=Date.now(),o=Math.random().toString(36).substring(2,15);return`session_${e}_${o}`}static generateSessionIdFromUrl(e){const o=e||(typeof window<"u"?window.location.href:"");if(!o)return dt.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),c=i[i.length-1];return c?`session_${Date.now()}_${c}`:dt.createSession()}catch{return dt.createSession()}}static createMessageId(e){const o=Date.now(),s=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${o}_${s}`:`msg_${o}_${s}`}getRenderer(){return this.renderer||(this.renderer=new vr),this.renderer}getTracker(){return this.tracker||(this.tracker=new xr({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const c=await fetch(`${this.apiBaseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({delegation_session_id:o.delegation_session_id,recommendation_id:o.recommendation_id,session_id:o.session_id,event_type:s,timestamp:new Date().toISOString(),metadata:i||{}})});if(!c.ok){const y=await c.text();throw new Error(`Delegation event failed (${c.status}): ${y}`)}const u=await c.json();return(u==null?void 0:u.session)||null}async reportDelegationTurnStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_started",o)}async reportDelegationSessionStarted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"session_started",o)}async reportDelegationTurnCompleted(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"turn_completed",o)}async reportDelegationToolInvocation(e,o){return this.postDelegationEvent("/aip/delegation/activity",e,"tool_invoked",o)}async reportDelegationOutcome(e,o,s){return this.postDelegationEvent("/aip/delegation/complete",e,o,s)}async stopDelegationSession(e,o="user_stopped",s){return this.postDelegationEvent("/aip/delegation/stop",e,"session_stopped",{reason:o,...s||{}})}getActiveDelegationSession(e){if(!e||e.status!=="active")return null;const o=Date.parse(e.expires_at);return Number.isNaN(o)||o<=Date.now()?null:e}hasActiveDelegationSession(e){return!!this.getActiveDelegationSession(e)}async showRecommendations(e){try{if(!e.sessionId||e.sessionId.trim()==="")throw new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");if(!e.messageId||e.messageId.trim()==="")throw new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");const o=await this.fetchPlatformResponse({query:e.query,sessionId:e.sessionId,messageId:e.messageId,platformSurface:e.platformSurface,model:e.model,messages:e.messages,language:e.locale,location:e.location,userId:e.userId??this.config.userId}),s={sessionId:e.sessionId,messageId:e.messageId,recommendations:[o]},i=this.getRenderer(),c=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:c,sessionId:e.sessionId,apiKey:this.config.apiKey,apiBaseUrl:this.apiBaseUrl,language:e.locale,location:e.location,userId:e.userId,model:e.model,messages:e.messages,onPasteToInput:e.onPasteToInput,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation,onExecuteQuery:e.onExecuteQuery})}catch(o){throw a.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var f,p,E,I,G,k,S,L,N,B,$,z,D;const o=`${this.apiBaseUrl}/aip/context`;if(a.log("[AdMeshSDK] ๐Ÿ“ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const Q=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"),Q}const s=e.messageId;if(!s||s.trim()===""){const Q=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"),Q}const i=dt.buildPlatformResponseCacheKey(e.sessionId,s),c=dt.inFlightPlatformResponses.get(i);if(c)return a.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),c;const u=e.messages?e.messages.length:0,y=(typeof window<"u"&&window.navigator,"web"),g=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",v=Po((f=e.location)==null?void 0:f.countryCode)||"US",d=typeof window<"u"&&window.location?{url:window.location.href,origin:window.location.origin,referrer:document.referrer||void 0,host:window.location.hostname}:void 0,h=e.userId??this.config.userId,w={spec_version:"1.0",message_id:s,timestamp:new Date().toISOString(),platform:{platform_id:"placeholder",role:"platform",software:{name:"admesh_ui_sdk",version:e.model||"1.0.0"}},identity:{namespace:"platform_user",value_hash:h||"",confidence:h?1:0},consent:{status:"granted",source:"admesh_ui_sdk",scope:{intent_based_monetization:!0,agent_participation:!0,measurement:!0},constraints:{allow_identity_downstream:!1}},classification_input:{type:"interaction",interaction:{session:{id:e.sessionId,turn_index:u},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:y,form_factor:g,locale:e.language||"en-US",country:v,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((p=e.location)==null?void 0:p.city)||void 0,state:((E=e.location)==null?void 0:E.state)||void 0,state_code:((I=e.location)==null?void 0:I.stateCode)||void 0,country:((G=e.location)==null?void 0:G.country)||void 0,country_code:v,zipcode:((k=e.location)==null?void 0:k.zipcode)||void 0,latitude:(S=e.location)==null?void 0:S.latitude,longitude:(L=e.location)==null?void 0:L.longitude},page:d}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(B=(N=w.classification_input.interaction)==null?void 0:N.input.query_text)!=null&&B.trim()||a.warn("[AdMeshSDK] โš ๏ธ Warning: Sending request with empty query_text");const C=JSON.stringify(w);a.log("[AdMeshSDK] ๐Ÿ“ค Sending canonical request to /aip/context",{messageId:w.message_id,specVersion:w.spec_version,classificationType:w.classification_input.type,platformId:w.platform.platform_id,surfaceChannel:($=w.classification_input.interaction)==null?void 0:$.surface.channel,sessionId:(D=(z=w.classification_input.interaction)==null?void 0:z.session)==null?void 0:D.id});const m={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){m["X-AdMesh-Source"]="extension";const Q=this.getExtensionSourceDomain();Q&&(m["X-AdMesh-Source-Domain"]=Q)}const b=(async()=>{const Q=await fetch(o,{method:"POST",headers:m,body:C});if(!Q.ok){const V=(await Q.json().catch(()=>({}))).detail||`HTTP ${Q.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${V}`)}const J=await Q.json();return a.log("[AdMeshSDK] ๐Ÿ“ฅ Raw response from /aip/context:",{status:J.status,recommendationId:J.recommendation_id,hasRecommendation:!!J.recommendation,hasTracking:!!J.tracking,hasDelegation:!!J.delegation,topLevelKeys:Object.keys(J)}),a.log("[AdMeshSDK] ๐Ÿ“ฆ Full PlatformResponse received from /aip/context",J),J})();dt.inFlightPlatformResponses.set(i,b);try{return await b}finally{dt.inFlightPlatformResponses.delete(i)}}async trackPublisherAssistantEvent(e){const o=Array.isArray(e)?{events:e}:e,s=await fetch(`${this.apiBaseUrl}/analytics/publisher-assistant/events`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),keepalive:!0});if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Failed to track publisher assistant analytics (${s.status}): ${i}`)}}async reportSponsoredRecommendation(e){const o=await fetch(`${this.apiBaseUrl}/analytics/recommendation-reports`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(e),keepalive:!0});if(!o.ok){const s=await o.text().catch(()=>"");throw new Error(`Failed to report sponsored recommendation (${o.status}): ${s}`)}}fireFollowupExposure(e,o,s){this.getTracker().fireFollowupExposure(e,o,s)}async fireFollowupEngagement(e,o,s){return this.getTracker().fireFollowupEngagement(e,o,s)}};Oe(dt,"inFlightPlatformResponses",new Map);let Jt=dt;class Tn{constructor(e={}){Oe(this,"autoAddLabels");Oe(this,"fireExposurePixels");Oe(this,"labelStyle");Oe(this,"processedLinks",new Set);Oe(this,"mutationObserver",null);var o,s,i,c;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((o=e.labelStyle)==null?void 0:o.fontSize)||"0.75em",fontWeight:((s=e.labelStyle)==null?void 0:s.fontWeight)||"bold",color:((i=e.labelStyle)==null?void 0:i.color)||"#666",marginLeft:((c=e.labelStyle)==null?void 0:c.marginLeft)||"2px"}}getLinksToProcess(e){const s=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return s.length>0?Array.from(s):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,o,s){if(!e)return[];const i=[];if(o.length>0){const c=this.getLinksToProcess(e),u=new Map(o.map(g=>{var v,d,h;return[((v=g==null?void 0:g.tracking)==null?void 0:v.click_url)||((h=(d=g==null?void 0:g.recommendation)==null?void 0:d.creative)==null?void 0:h.landing_page_url)||"",g]}).filter(([g])=>!!g)),y=new Map;o.forEach(g=>{var d,h;const v=(h=(d=g==null?void 0:g.recommendation)==null?void 0:d.creative)==null?void 0:h.landing_page_url;if(v&&typeof v=="string"){const w=v.trim().replace(/\/$/,"");y.set(w,g),y.set(`${w}/`,g)}}),c.forEach(g=>{var C,m,b,f,p,E,I,G;const v=g.getAttribute("href")||"",d=`${v}`;if(this.processedLinks.has(d))return;let h=u.get(v),w=v;if(!h){const k=v.trim().replace(/\/$/,"");h=y.get(k)||y.get(`${k}/`);const S=((C=h==null?void 0:h.tracking)==null?void 0:C.click_url)||((b=(m=h==null?void 0:h.recommendation)==null?void 0:m.creative)==null?void 0:b.landing_page_url);h&&S&&(a.log("[WeaveResponseProcessor] ๐Ÿ”„ Found brand URL match, replacing with click_url:",v),g.setAttribute("href",S),w=S)}if(h){this.processedLinks.add(d),g.setAttribute("target","_blank"),g.setAttribute("rel","noopener noreferrer");const k={element:g,href:w,text:g.textContent||"",hasAdLabel:this.hasAdLabel(g),matchedRecommendation:{recommendation_id:(h==null?void 0:h.recommendation_id)||"",click_url:((f=h==null?void 0:h.tracking)==null?void 0:f.click_url)||((E=(p=h==null?void 0:h.recommendation)==null?void 0:p.creative)==null?void 0:E.landing_page_url)||"",exposure_url:(I=h==null?void 0:h.tracking)==null?void 0:I.exposure_url}};this.autoAddLabels&&!k.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding Ad label to matched recommendation link:",w),this.addAdLabel(g),k.hasAdLabel=!0):this.autoAddLabels?k.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label");const S=(G=h==null?void 0:h.tracking)==null?void 0:G.exposure_url;this.fireExposurePixels&&S&&s&&k.matchedRecommendation&&s({exposureUrl:S,recommendationId:k.matchedRecommendation.recommendation_id,linkElement:g}),i.push(k)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const y=u.getAttribute("href")||"",g=`${y}`;if(this.processedLinks.has(g))return;if(this.isAdMeshLink(y)){this.processedLinks.add(g);const d={element:u,href:y,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:void 0};if(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!d.hasAdLabel?(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding Ad label to pattern-matched AdMesh link:",y),this.addAdLabel(u),d.hasAdLabel=!0):this.autoAddLabels?d.hasAdLabel&&a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has label, skipping"):a.log("[WeaveResponseProcessor] โ„น๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const h=this.convertClickUrlToExposureUrl(y);s({exposureUrl:h,recommendationId:this.extractRecommendationIdFromUrl(y),linkElement:u})}i.push(d)}});return i}hasAdLabel(e){var u,y,g;if((e.textContent||"").includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link text contains Ad label"),!0;const s=e.querySelectorAll("sub, span");for(const v of Array.from(s))if((u=v.textContent)!=null&&u.includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Link has Ad label as child element"),!0;let i=e.previousSibling;for(;i&&i.nodeType===Node.TEXT_NODE;){const v=i.textContent||"";if(v.trim()===""){i=i.previousSibling;continue}if(v.includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const v=i,d=v.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((y=v.textContent)!=null&&y.includes("Ad")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in previous element sibling:",d),!0}let c=e.nextSibling;for(;c&&c.nodeType===Node.TEXT_NODE;){const v=c.textContent||"";if(v.trim()===""){c=c.nextSibling;continue}if(v.includes("Ad"))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in next text sibling"),!0;break}if(c&&c.nodeType===Node.ELEMENT_NODE){const v=c,d=v.tagName.toUpperCase();if((d==="SUB"||d==="SPAN")&&((g=v.textContent)!=null&&g.includes("Ad")))return a.log("[WeaveResponseProcessor] โ„น๏ธ Found Ad label in next element sibling:",d),!0}return a.log("[WeaveResponseProcessor] โ„น๏ธ No existing Ad label found"),!1}addAdLabel(e){if(a.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){a.warn("[WeaveResponseProcessor] โš ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){a.log("[WeaveResponseProcessor] โ„น๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){a.error("[WeaveResponseProcessor] โŒ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const s=document.createElement("sub");s.textContent="Ad",s.style.fontSize=this.labelStyle.fontSize,s.style.fontWeight=this.labelStyle.fontWeight,s.style.color=this.labelStyle.color,s.style.marginLeft=this.labelStyle.marginLeft,s.style.cursor="pointer",s.style.borderBottom=`1px dotted ${this.labelStyle.color}`,s.style.whiteSpace="nowrap",s.title="Why this ad? This is a sponsored recommendation based on your search query.";let i=!1;s.addEventListener("mouseenter",()=>{s.style.opacity="0.7"}),s.addEventListener("mouseleave",()=>{s.style.opacity="1",i&&(i=!1)}),s.addEventListener("click",u=>{u.stopPropagation(),i=!i,i?(s.style.textDecoration="underline",s.style.opacity="0.7"):(s.style.textDecoration="none",s.style.opacity="1")});const c=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",c);try{const u=e.nextSibling;u?(o.insertBefore(s,u),a.log("[WeaveResponseProcessor] โœ… Ad label inserted before next sibling")):(o.appendChild(s),a.log("[WeaveResponseProcessor] โœ… Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?a.log("[WeaveResponseProcessor] โœ… Ad label successfully added to link:",e.href):a.error("[WeaveResponseProcessor] โŒ Ad label insertion failed - label not in DOM")}catch(u){a.error("[WeaveResponseProcessor] โŒ Error inserting Ad label:",u)}}removeLeftAdLabel(e){var s,i,c;let o=e.previousSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const u=o.textContent||"";if(u.trim()===""){o=o.previousSibling;continue}if(u.includes("Ad")){(s=o.parentNode)==null||s.removeChild(o);return}break}if(o&&o.nodeType===Node.ELEMENT_NODE){const u=o;(u.tagName==="SUB"||u.tagName==="SPAN")&&((i=u.textContent)!=null&&i.includes("Ad"))&&((c=u.parentNode)==null||c.removeChild(u))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(i=>e.includes(i)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractRecommendationIdFromUrl(e){try{const o=e.match(/\/click\/([^/?]+)/);return o&&o[1]?o[1]:""}catch{return e}}convertClickUrlToExposureUrl(e){try{const o=new URL(e),i=`${`${o.protocol}//${o.host}`}/exposure`,c=new URLSearchParams(o.search);return c.has("cpx")||c.set("cpx","0"),`${i}?${c.toString()}`}catch{return a.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,o,s){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,o,s)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}function Ht(){const t=Rn();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,language:t.language,location:t.location,userId:t.userId,model:t.model,messages:t.messages,processedMessageIds:t.processedMessageIds,recommendationResults:t.recommendationResults,activeDelegationSession:t.activeDelegationSession,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed,setRecommendationResult:t.setRecommendationResult,getRecommendationResult:t.getRecommendationResult,hasRecommendationResult:t.hasRecommendationResult,setActiveDelegationSession:t.setActiveDelegationSession,getActiveDelegationSession:t.getActiveDelegationSession,hasActiveDelegationSession:t.hasActiveDelegationSession,refreshDelegationActivity:t.refreshDelegationActivity,stopDelegationSession:t.stopDelegationSession}}const $o=({className:t,size:e=20})=>r.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[r.jsx("path",{d:"M5 12h14"}),r.jsx("path",{d:"M12 5v14"})]}),kr=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var w,C,m,b,f;const c=(C=(w=t.recommendation)==null?void 0:w.creative)!=null&&C.follow_up_suggestion&&((m=t.tracking)!=null&&m.followup_engagement_url)&&((b=t.tracking)!=null&&b.followup_exposure_url)?{query:t.recommendation.creative.follow_up_suggestion,engagement_url:t.tracking.followup_engagement_url,exposure_url:t.tracking.followup_exposure_url}:null,u=c==null?void 0:c.query,y=c==null?void 0:c.engagement_url,g=c==null?void 0:c.exposure_url,v=t.recommendation_id,d=((f=t.recommendation)==null?void 0:f.offerId)||v;if(!u||!y||!g)return a.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const h=async()=>{try{y&&v&&(a.log("[AdMeshFollowup] ๐ŸŽฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(y,v,s)),i&&u?(a.log(`[AdMeshFollowup] ๐Ÿ” Executing query: ${u}`),await i(u)):a.warn("[AdMeshFollowup] โš ๏ธ onExecuteQuery not provided - cannot execute query")}catch(p){a.error("[AdMeshFollowup] โŒ Error handling follow-up click:",p)}};return r.jsx(Zt,{productId:d,recommendationId:v||"",exposureUrl:g,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:r.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[r.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),r.jsxs("div",{onClick:h,className:"cursor-pointer flex flex-row justify-between font-medium space-x-2 items-center group",role:"button",tabIndex:0,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&h()},"aria-label":`Sponsored follow-up: ${u}`,children:[r.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),r.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[r.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),r.jsx($o,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},Xt=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:c,triggerExposureUrl:u=!0,followups_container_id:y,onPasteToInput:g,onDelegationConsent:v,onDelegationActivated:d,onStartDelegation:h,onRecommendationReport:w,onExecuteQuery:C,onFollowupDetected:m,isContainerReady:b})=>{var H,A,ie,ke;const{sdk:f,sessionId:p,apiKey:E,language:I,location:G,userId:k,model:S,messages:L,theme:N,getRecommendationResult:B,hasRecommendationResult:$,setRecommendationResult:z,activeDelegationSession:D,setActiveDelegationSession:Q,hasActiveDelegationSession:J}=Ht(),ge=T=>!!T&&T.status==="generated"&&!!T.recommendation,V=i||k,[ee,me]=l.useState(null),[xe,q]=l.useState(null),[oe,ve]=l.useState(!0),[Ne,Pe]=l.useState(null),be=l.useRef(null),we=l.useRef(!1),Se=l.useRef(!1),_e=l.useRef(t),Fe=l.useRef(e);l.useEffect(()=>{_e.current=t,Fe.current=e},[t,e]),l.useEffect(()=>{be.current!==o&&(be.current=null,Se.current=!1,me(null),q(null))},[o]);const Ee=J()&&(D==null?void 0:D.session_id)===p;l.useEffect(()=>{var j,ce,re;if(!o||!$(o)||Ee)return;const T=B(o);if(!T){a.log("[AdMeshRecommendations] โ™ป๏ธ Reusing stored no_match result from provider state"),me(null),q(null),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0;return}let se=((j=T.recommendation)==null?void 0:j.format)||"tail";(se==="weave"||se==="product_card")&&(se="tail"),a.log("[AdMeshRecommendations] โ™ป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:T.recommendation_id,format:(ce=T.recommendation)==null?void 0:ce.format}),me(T),q(se),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0,(re=_e.current)==null||re.call(_e,o,T)},[B,$,Ee,o]),l.useEffect(()=>{var T,se,j,ce,re,Y,K;if(!(!c||!o)&&!Ee)try{const ae=c,Be=c.status||"unknown";if(!ge(ae)){if(Be==="no_match"){a.log("[AdMeshRecommendations] โ„น๏ธ Initial recommendation returned no_match - rendering nothing"),me(null),q(null),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${Be})`)}let Te=((T=ae.recommendation)==null?void 0:T.format)||"tail";(Te==="weave"||Te==="product_card")&&(Te="tail"),me(ae),q(Te),Pe(null),ve(!1),be.current=o,we.current=!1,Se.current=!0,z(o,ae),(se=_e.current)==null||se.call(_e,o,ae),a.log("[AdMeshRecommendations] โ™ป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),a.log("[AdMeshRecommendations] โœ… Accepted initial generated recommendation payload",{messageId:o,recommendationId:ae.recommendation_id,format:(j=ae.recommendation)==null?void 0:j.format,brandName:(re=(ce=ae.recommendation)==null?void 0:ce.creative)==null?void 0:re.brand_name,headline:(K=(Y=ae.recommendation)==null?void 0:Y.creative)==null?void 0:K.headline,hasTracking:!!ae.tracking})}catch(ae){const Be=ae instanceof Error?ae:new Error(String(ae));Se.current=!1,a.warn(`[AdMeshRecommendations] โš ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${Be.message}`)}},[Ee,c,o,z]),l.useEffect(()=>{if(!o||!s||s.trim()===""){a.log("[AdMeshRecommendations] โŒ Validation failed - missing required parameters"),ve(!1);return}if(Ee){a.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:p,delegationSessionId:D==null?void 0:D.delegation_session_id}),me(null),q(null),Pe(null),ve(!1),we.current=!1;return}if(!(f!=null&&f.fetchPlatformResponse)){a.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),ve(!1);return}if(Se.current){a.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(be.current===o){a.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(we.current){a.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}a.log("[AdMeshRecommendations] ๐Ÿ“ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var se,j,ce,re,Y,K,ae,Be,Te;try{we.current=!0,ve(!0),Pe(null);const M=await f.fetchPlatformResponse({query:s.trim(),sessionId:p,messageId:o,language:I,location:G,userId:V,model:S,...L&&L.length>0&&{messages:L}}),Ce=(M==null?void 0:M.status)||"unknown";if(!ge(M)){if(Ce==="no_match"){a.log("[AdMeshRecommendations] โ„น๏ธ No recommendation returned from /aip/context"),me(null),q(null),Pe(null),ve(!1),we.current=!1,be.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${Ce})`)}me(M),a.log("[AdMeshRecommendations] โœ… Accepted fetched generated recommendation payload",{messageId:o,recommendationId:M.recommendation_id,format:(se=M.recommendation)==null?void 0:se.format,brandName:(ce=(j=M.recommendation)==null?void 0:j.creative)==null?void 0:ce.brand_name,headline:(Y=(re=M.recommendation)==null?void 0:re.creative)==null?void 0:Y.headline,hasTracking:!!M.tracking});let Ie=((K=M.recommendation)==null?void 0:K.format)||"tail";(Ie==="weave"||Ie==="product_card")&&(Ie="tail"),q(Ie),be.current=o,z(o,M),a.log("[AdMeshRecommendations] ๐Ÿ“Š Format detection:",{preferred_format:(ae=M.recommendation)==null?void 0:ae.format,selected_format:Ie}),ve(!1),we.current=!1,(Be=_e.current)==null||Be.call(_e,o,M)}catch(M){const Ce=M instanceof Error?M:new Error(String(M));Ce.message.includes("Failed to fetch")||Ce.message.includes("NetworkError")?a.warn(`[AdMeshRecommendations] โš ๏ธ Network error fetching recommendations(non - critical): ${Ce.message} `):a.error(`[AdMeshRecommendations] โŒ Error fetching recommendations: ${Ce.message} `),Pe(Ce),ve(!1),we.current=!1,(Te=Fe.current)==null||Te.call(Fe,Ce)}})()},[D==null?void 0:D.delegation_session_id,Ee,f,p,o,s,I,G,V,S,c,z]),l.useEffect(()=>{var se,j,ce,re;if(!ee||!m)return;const T=(j=(se=ee.recommendation)==null?void 0:se.creative)!=null&&j.follow_up_suggestion&&((ce=ee.tracking)!=null&&ce.followup_engagement_url)&&((re=ee.tracking)!=null&&re.followup_exposure_url)?{label:ee.recommendation.creative.follow_up_suggestion,query:ee.recommendation.creative.follow_up_suggestion,engagement_url:ee.tracking.followup_engagement_url,exposure_url:ee.tracking.followup_exposure_url}:null;T&&m(T,ee.recommendation_id)},[ee,m]);const rt=l.useCallback(async T=>{if(!f||!p)throw new Error("AdMesh SDK activation requires an initialized session");const se=await fetch(`${f.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${E}`},body:JSON.stringify({session_id:p,recommendation_id:T.recommendation_id,metadata:T.metadata})});if(!se.ok){const Y=await se.text();throw new Error(`Failed to activate delegation session: ${se.status} ${Y}`)}const j=await se.json(),ce={...T,delegation_session_id:j.delegation_session_id||T.delegation_session_id,session_id:j.session_id||p,brand_id:j.brand_id||T.brand_id,brand_name:j.brand_name||T.brand_name,mcp_endpoint:j.mcp_endpoint,eligibility_reason:j.eligibility_reason||T.eligibility_reason,delegate_reason:j.delegate_reason||T.delegate_reason,session_goal:j.session_goal||T.session_goal,desired_outcome_type:j.desired_outcome_type||T.desired_outcome_type,required_user_inputs:j.required_user_inputs||T.required_user_inputs||[],required_consent_types:j.required_consent_types||T.required_consent_types||[],success_outcome:j.success_outcome||T.success_outcome,fallback_message:j.fallback_message||T.fallback_message,session_mode:"inline",status:j.status||"active",capabilities:j.capabilities||T.capabilities||[],allowed_data_types:j.allowed_data_types||T.allowed_data_types||[],auth_model:j.auth_model||T.auth_model,handoff_protocol:j.handoff_protocol||T.handoff_protocol,supported_actions:j.supported_actions||T.supported_actions||[],metadata:j.metadata||T.metadata},re={delegation_session_id:j.delegation_session_id,recommendation_id:T.recommendation_id,session_id:j.session_id||p,brand_agent_id:j.brand_agent_id,brand_id:j.brand_id||T.brand_id,brand_name:j.brand_name||T.brand_name||"Brand",mcp_endpoint:j.mcp_endpoint,status:j.status||"active",activated_at:j.created_at,last_activity_at:j.updated_at,expires_at:j.expires_at||j.updated_at,eligibility_reason:j.eligibility_reason||T.eligibility_reason,delegate_reason:j.delegate_reason||T.delegate_reason,session_goal:j.session_goal||T.session_goal,desired_outcome_type:j.desired_outcome_type||T.desired_outcome_type,required_user_inputs:j.required_user_inputs||T.required_user_inputs||[],required_consent_types:j.required_consent_types||T.required_consent_types||[],success_outcome:j.success_outcome||T.success_outcome,fallback_message:j.fallback_message||T.fallback_message,capabilities:j.capabilities||T.capabilities||[],allowed_data_types:j.allowed_data_types||T.allowed_data_types||[],consent_requirements:j.consent_requirements||T.consent_requirements||[],auth_model:j.auth_model||T.auth_model,handoff_protocol:j.handoff_protocol||T.handoff_protocol,supported_actions:j.supported_actions||T.supported_actions||[],metadata:j.metadata||T.metadata};if(Q(re),await f.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:p,recommendation_id:T.recommendation_id,delegation_session_id:j.delegation_session_id,brand_name:re.brand_name,status:j.status||"active",metadata:{brand_agent_id:j.brand_agent_id,source:"recommendation_card"}}).catch(Y=>{a.warn("[AdMeshRecommendations] โš ๏ธ Failed to track delegation_started event:",Y)}),await f.reportDelegationSessionStarted(re,{brand_agent_id:j.brand_agent_id,brand_name:re.brand_name}).then(Y=>{Y&&Q(Y)}).catch(Y=>{a.warn("[AdMeshRecommendations] โš ๏ธ Failed to report delegation session_started event:",Y)}),d){try{await d(ce)}catch(Y){a.warn("[AdMeshRecommendations] โš ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",Y)}return}if(h)try{await h({...T.platform_response,delegation:{...T.platform_response.delegation,...ce,delegation_session_id:j.delegation_session_id,available:!0,status:j.status||"active"}})}catch(Y){a.warn("[AdMeshRecommendations] โš ๏ธ Host onStartDelegation callback failed after successful delegation activation:",Y)}},[E,d,h,f,p,Q]),F=l.useCallback(async T=>{var se,j;if(w){await w(T);return}!f||!p||await f.reportSponsoredRecommendation({session_id:p,message_id:o,recommendation_id:T.recommendation_id,reason:T.reason,brand_name:(j=(se=T.recommendation.recommendation)==null?void 0:se.creative)==null?void 0:j.brand_name,metadata:{reason:T.reason,source:"recommendation_card"}}).catch(ce=>{a.warn("[AdMeshRecommendations] โš ๏ธ Failed to report sponsored recommendation:",ce)})},[o,w,f,p]);if(!o||!s||s.trim()===""||oe||Ne)return null;if(!ee||!xe)return a.log("[AdMeshRecommendations] ๐Ÿšซ Nothing to render",{messageId:o,hasPlatformResult:!!ee,detectedFormat:xe,isLoading:oe,hasError:!!Ne}),null;a.log("[AdMeshRecommendations] ๐ŸŽจ Rendering recommendation component",{messageId:o,recommendationId:ee.recommendation_id,detectedFormat:xe,brandName:(A=(H=ee.recommendation)==null?void 0:H.creative)==null?void 0:A.brand_name,headline:(ke=(ie=ee.recommendation)==null?void 0:ie.creative)==null?void 0:ke.headline});const _=typeof document<"u"&&y&&(b??!0)?document.getElementById(y):null;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:r.jsx(jn,{recommendations:[ee],theme:N,sessionId:p,triggerExposureUrl:u,onPasteToInput:g,onDelegationConsent:v,onDelegationActivated:rt,onStartDelegation:h,onRecommendationReport:F})}),_&&f&&p?Gr.createPortal(r.jsx(kr,{recommendation:ee,theme:N,sdk:f,sessionId:p,onExecuteQuery:C}),_):null]})},Sr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:c})=>{const{sdk:u,sessionId:y,theme:g,apiKey:v,language:d,location:h,userId:w,model:C,messages:m}=Ht(),b=l.useRef(null),[f,p]=l.useState("");return l.useEffect(()=>{o&&p(`admesh-weave-fallback-${o}`)},[o]),a.log("[WeaveFallbackRecommendations] ๐ŸŽจ Component render"),l.useEffect(()=>{if(a.log("[WeaveFallbackRecommendations] ๐Ÿ”„ useEffect triggered",{fallback:i,hasPreviousRecommendations:c&&c.length>0,previousRecommendationsCount:(c==null?void 0:c.length)||0}),!i){a.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(a.log("[WeaveFallbackRecommendations] โœ… fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){a.log("[WeaveFallbackRecommendations] โŒ Validation failed - returning early");return}if(a.log("[WeaveFallbackRecommendations] โœ… Validation passed"),!u||!f){a.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const E=c&&c.length>0;a.log("[WeaveFallbackRecommendations] ๐Ÿ“Š Checking previous recommendations:",{hasPreviousRecs:E,count:(c==null?void 0:c.length)||0,fallback:i,messageId:o}),E?(a.log(`[WeaveFallbackRecommendations] โ™ป๏ธ Reusing ${c.length} previous recommendation(s), skipping API call`),(async()=>{var G,k,S,L,N,B,$;try{const z=c[0];if(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ฆ Processing AIP response:",{hasAipResponse:!!z,recommendationId:(z==null?void 0:z.recommendation_id)||"",format:((G=z==null?void 0:z.recommendation)==null?void 0:G.format)||"unknown"}),z&&process.env.NODE_ENV==="development"&&a.log("[WeaveFallbackRecommendations] ๐Ÿ“‹ Recommendation received (DEV):",{recommendation_id:z==null?void 0:z.recommendation_id,click_url:((k=z==null?void 0:z.tracking)==null?void 0:k.click_url)||((L=(S=z==null?void 0:z.recommendation)==null?void 0:S.creative)==null?void 0:L.landing_page_url),format:(N=z==null?void 0:z.recommendation)==null?void 0:N.format,full_response:z}),!z){a.warn("[WeaveFallbackRecommendations] โš ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o});return}const D=u,Q=D.getRenderer,J=D.getTracker,ge=(B=D.config)==null?void 0:B.theme;if(Q&&J){const V={sessionId:y,messageId:o,recommendations:[z]},ee=Q.call(u),me=J.call(u),xe=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await ee.render({containerId:f,response:V,theme:g||ge,tracker:me,sessionId:y,apiKey:v||(($=u==null?void 0:u.config)==null?void 0:$.apiKey),apiBaseUrl:xe,language:d,location:h,userId:w,model:C,messages:m}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations rendered from previous response (no API call)")}else a.warn("[WeaveFallbackRecommendations] โš ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o})}catch(z){const D=z instanceof Error?z:new Error(String(z));a.error(`[WeaveFallbackRecommendations] โŒ Error rendering previous recommendations: ${D.message}`);try{await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o})}catch{e==null||e(D)}}})()):(a.log("[WeaveFallbackRecommendations] ๐Ÿ“ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){a.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:f,sessionId:y,messageId:o}),a.log("[WeaveFallbackRecommendations] โœ… Recommendations displayed successfully")}catch(G){const k=G instanceof Error?G:new Error(String(G));a.log(`[WeaveFallbackRecommendations] โŒ Error: ${k.message}`),e==null||e(k)}})())},[u,y,f,t,o,s,i,e,c,g]),!i||!o||!s||s.trim()===""?null:r.jsx("div",{ref:b,id:f,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Ar=l.createContext(void 0),zo=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>r.jsx(Ar.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),Lo=()=>l.useContext(Ar),vn=t=>{try{return new URL(t),!0}catch{return!1}},lr=t=>t&&t.trim()?t.trim():"",Mt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",ct=t=>Mt(t)||void 0,No=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},Fo=(t,e)=>{if(t==null||t==="")return"";if(typeof t=="number")try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e||"USD",maximumFractionDigits:2}).format(t)}catch{return String(t)}return Mt(t)},Wo=(t,e,o)=>{if(t==null||t==="")return"";const s=(e||"percentage").trim().toLowerCase();if(typeof t=="number"){if(s==="amount"||s==="fixed"||s==="fixed_amount")try{return`${new Intl.NumberFormat("en-US",{style:"currency",currency:o||"USD",maximumFractionDigits:2}).format(t)} off`}catch{return`${t} off`}return`${t}% off`}const i=Mt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},he={surface:"#ffffff",surfaceMuted:"#f9fafb",surfaceSubtle:"#f8fafc",border:"rgba(17, 24, 39, 0.10)",text:"#111827",textSecondary:"#4b5563",textMuted:"#6b7280",link:"#2563eb",logoFallbackBg:"#f3f4f6",logoFallbackText:"#4b5563",productImageFallbackBg:"#e5e7eb",successText:"#065f46",successBg:"#d1fae5"},Bo=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:c=!0,onDelegationConsent:u,onDelegationActivated:y,onStartDelegation:g,onPasteToInput:v})=>{var j,ce,re,Y,K,ae,Be,Te,M,Ce,Ie,ot,yt,et,jt,ut,Et,_t,mt,Rt,st,Ve,ze,O,fe,Ue,Ke,tt,pt,wt,Tt,It,Wt;if(!t||t.length===0)return a.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const d=t[0],h=((j=d==null?void 0:d.recommendation)==null?void 0:j.offerId)||"",w=((ce=d==null?void 0:d.tracking)==null?void 0:ce.exposure_url)||"",C=(d==null?void 0:d.recommendation_id)||"",m=((Y=(re=d==null?void 0:d.recommendation)==null?void 0:re.creative)==null?void 0:Y.description)||"",b=((K=d==null?void 0:d.recommendation)==null?void 0:K.disclosure)||"Sponsored",f=((Be=(ae=d==null?void 0:d.recommendation)==null?void 0:ae.creative)==null?void 0:Be.brand_name)||"",p=((M=(Te=d==null?void 0:d.recommendation)==null?void 0:Te.creative)==null?void 0:M.headline)||((Ie=(Ce=d==null?void 0:d.recommendation)==null?void 0:Ce.creative)==null?void 0:Ie.brand_name)||"",E=((yt=(ot=d==null?void 0:d.recommendation)==null?void 0:ot.creative)==null?void 0:yt.logo_url)||"",I=((et=d==null?void 0:d.tracking)==null?void 0:et.click_url)||((ut=(jt=d==null?void 0:d.recommendation)==null?void 0:jt.creative)==null?void 0:ut.landing_page_url)||"",G=lr((_t=(Et=d==null?void 0:d.recommendation)==null?void 0:Et.creative)==null?void 0:_t.cta_text),k=((Rt=(mt=d==null?void 0:d.recommendation)==null?void 0:mt.creative)==null?void 0:Rt.products)||[],S=k.length>1,L=S?k.slice(0,4):[],N=((st=d==null?void 0:d.recommendation)==null?void 0:st.format)||"tail",B=N==="bridge",$=((Ve=d==null?void 0:d.delegation)==null?void 0:Ve.brand_name)||f,z=((ze=d==null?void 0:d.delegation)==null?void 0:ze.available)===!0,D=B&&z,Q="Talk to Agent",J=!S&&!!G&&!!I;if(!f&&!p&&!m)return a.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:f,hasFirstRecommendation:!!d,recommendationId:C,recommendationKeys:d?Object.keys(d):[]}),null;let ge=f,V="";p&&p!==f&&(V=p),V&&(ge=`${f} โ€” ${V}`),a.debug("[AdMeshTailAd] ๐Ÿ“Š Rendering with tracking data:",{recommendationId:C,productId:h,exposureUrl:w?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:I||"MISSING",clickUrlSource:(O=d==null?void 0:d.tracking)!=null&&O.click_url?"tracking.click_url":(Ue=(fe=d==null?void 0:d.recommendation)==null?void 0:fe.creative)!=null&&Ue.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:m?"present":"MISSING",brandName:f,productName:p,headlineText:ge,triggerExposureUrl:c}),a.log("[AdMeshTailAd] โœ… Rendering tail ad",{recommendationId:C,brandName:f,productName:p,hasDescription:!!m,hasClickUrl:!!I,hasLogoUrl:!!E,recommendationFormat:N});const ee=(U,ye)=>{ye&&ye.stopPropagation(),a.log(`AdMesh tail ad ${U} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:C,productId:h,clickUrl:I,source:U}).catch(()=>{a.error(`[AdMesh] Failed to track ${U} click`)})},me=U=>{U.stopPropagation(),ee("tail_ad_brand_name")},xe=U=>{U.stopPropagation(),ee("tail_ad_cta")},q=U=>{U.stopPropagation(),ee("tail_ad_logo")},oe=()=>{S||!I||(ee("tail_ad_card"),typeof window<"u"&&window.open(I,"_blank","noopener,noreferrer"))},ve=U=>{S||!I||(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),oe())},[Ne,Pe]=l.useState(!1),be=l.useRef(null);l.useEffect(()=>()=>{be.current&&(be.current(!1),be.current=null)},[]);const we=U=>{var ye;(ye=be.current)==null||ye.call(be,U),be.current=null,Pe(!1)},Se=async()=>u?await u(d):await new Promise(U=>{be.current=U,Pe(!0)}),_e=async()=>{if(C&&i)try{const U=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",ye=await fetch(`${U}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:C,session_id:i,is_test:!1})});ye.ok||a.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",ye.statusText)}catch(U){a.error("[AdMesh Tail Ad] Error tracking delegation engagement:",U)}},Fe=async U=>{var vt,kt,$e,ht;if(U.preventDefault(),U.stopPropagation(),!d||!D)return;if(ee("tail_ad_delegation_cta"),await _e(),!await Se()){a.log("[AdMesh Tail Ad] Delegation consent declined");return}const de=d.delegation,Dt=de!=null&&de.available?{recommendation_id:d.recommendation_id,brand_id:ct(de.brand_id),brand_name:ct(de.brand_name||((kt=(vt=d.recommendation)==null?void 0:vt.creative)==null?void 0:kt.brand_name)),eligibility_reason:ct(de.eligibility_reason),delegate_reason:ct(de.delegate_reason),session_goal:ct(de.session_goal),desired_outcome_type:de.desired_outcome_type,required_user_inputs:Array.isArray(de.required_user_inputs)?de.required_user_inputs.filter(it=>typeof it=="string"):[],required_consent_types:Array.isArray(de.required_consent_types)?de.required_consent_types.filter(it=>typeof it=="string"):[],success_outcome:ct(de.success_outcome),fallback_message:ct(de.fallback_message),session_mode:ct(de.session_mode),status:ct(de.status),capabilities:de.capabilities||[],allowed_data_types:de.allowed_data_types||[],consent_requirements:de.consent_requirements||[],auth_model:ct(de.auth_model),handoff_protocol:de.handoff_protocol&&typeof de.handoff_protocol=="object"?de.handoff_protocol:void 0,supported_actions:de.supported_actions||[],metadata:de.metadata&&typeof de.metadata=="object"?de.metadata:void 0,platform_response:d}:null;if(y&&Dt){await y(Dt);return}if(g){await g(d);return}const Je=((ht=($e=d.recommendation)==null?void 0:$e.creative)==null?void 0:ht.follow_up_suggestion)||"";if(Je&&v){v(Je);return}if(Je&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(Je);return}},[Ee,rt]=l.useState(!1),F=f?f.charAt(0).toUpperCase():"B",_=he.surface,H=he.border,A=(e==null?void 0:e.borderRadius)||((tt=(Ke=e==null?void 0:e.components)==null?void 0:Ke.card)==null?void 0:tt.borderRadius)||"8px",ie="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",ke="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",T=((pt=e==null?void 0:e.shadows)==null?void 0:pt.medium)||((Tt=(wt=e==null?void 0:e.components)==null?void 0:wt.card)==null?void 0:Tt.boxShadow)||ie,se=((It=e==null?void 0:e.shadows)==null?void 0:It.large)||ke;return r.jsxs(Zt,{productId:h,recommendationId:C,exposureUrl:w,sessionId:i,triggerExposureUrl:c,className:`admesh-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",lineHeight:1.4,...s},children:[r.jsx("style",{children:`
132
+ .admesh-tail-product-scroll {
133
+ -ms-overflow-style: none;
134
+ scrollbar-width: none;
135
+ }
136
+
137
+ .admesh-tail-product-scroll::-webkit-scrollbar {
138
+ display: none;
139
+ width: 0;
140
+ height: 0;
141
+ }
142
+ `}),r.jsxs("div",{className:"tail-ad-container flex flex-col gap-3 sm:flex-row",role:!S&&I?"link":void 0,tabIndex:!S&&I?0:void 0,style:{...(Wt=e==null?void 0:e.components)==null?void 0:Wt.card,backgroundColor:_,borderRadius:A,padding:"16px",boxShadow:T,border:`1px solid ${H}`,color:he.text,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",transform:"translateY(0)",cursor:!S&&I?"pointer":void 0},onClick:oe,onKeyDown:ve,onMouseEnter:U=>{U.currentTarget.style.boxShadow=se,U.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:U=>{U.currentTarget.style.boxShadow=T,U.currentTarget.style.transform="translateY(0)"},children:[E&&r.jsx("div",{className:"flex-shrink-0 flex items-center justify-start pr-0 sm:justify-center sm:pr-2",style:{width:"auto",minWidth:"48px"},children:!Ee&&vn(E)?r.jsx("a",{href:I||"#",target:I?"_blank":void 0,rel:I?"noopener noreferrer":void 0,onClick:I?q:void 0,className:"block",style:{cursor:I?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",maxWidth:"64px"},children:r.jsx("img",{src:E,alt:`${f} logo`,className:"object-cover",style:{width:"100%",height:"auto",maxWidth:"64px",maxHeight:"64px",objectFit:"contain",borderRadius:"8px"},onError:()=>{rt(!0),a.debug("[AdMesh Tail Ad] Logo failed to load, showing fallback")}})}):r.jsx("div",{className:"flex items-center justify-center text-lg font-semibold",style:{width:"100%",maxWidth:"64px",aspectRatio:"1",borderRadius:"8px",minHeight:"48px",backgroundColor:he.logoFallbackBg,color:he.logoFallbackText,fontSize:"18px"},children:F})}),r.jsxs("div",{className:"flex-1",style:{width:"100%",minWidth:0},children:[ge&&!S&&r.jsx("div",{className:"mb-2",children:r.jsx("h3",{className:"font-semibold text-base",style:{fontSize:"14px",lineHeight:1.35,color:he.text},children:I&&f?r.jsxs(r.Fragment,{children:[r.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-semibold",style:{color:he.link,textDecoration:"underline",textDecorationColor:he.link,textUnderlineOffset:"2px"},onClick:me,children:f}),V&&` โ€” ${V}`]}):ge})}),m&&!S&&r.jsx("p",{className:"text-sm mb-3 leading-relaxed",style:{fontSize:"13px",lineHeight:1.45,color:he.textSecondary},children:m}),S&&L.length>0&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"admesh-tail-product-scroll",style:{marginBottom:"8px",overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch",overscrollBehaviorX:"contain",overscrollBehaviorY:"none",scrollBehavior:"smooth",paddingBottom:"2px"},children:r.jsx("div",{style:{display:"flex",gap:"10px",minWidth:"max-content",scrollSnapType:"x proximity",paddingRight:0},children:L.map(U=>{const ye=Mt(U.product_name)||"Product",de=Mt(U.product_link)||Mt(U.product_url)||I||"#",Dt=No(Mt(U.product_description),10),Je=Fo(U.product_price,U.product_currency),vt=Wo(U.product_discount,U.product_discount_type,U.product_currency),kt=Mt(U.product_image_url),$e=E&&vn(E)?E:"",ht=kt&&vn(kt)?kt:$e,it=lr(U.product_cta_label),qt=de!=="#";return r.jsx("a",{href:de,target:qt?"_blank":void 0,rel:qt?"noopener noreferrer":void 0,onClick:Ot=>ee(`tail_ad_product_${U.product_id||"item"}`,Ot),className:"block",style:{border:`1px solid ${H}`,borderRadius:"8px",padding:"10px",backgroundColor:he.surfaceMuted,textDecoration:"none",color:he.text,minWidth:"min(264px, 82vw)",width:"clamp(220px, 72vw, 312px)",flex:"0 0 clamp(220px, 72vw, 312px)",scrollSnapAlign:"start"},children:r.jsxs("div",{className:"flex items-start gap-2",children:[ht?r.jsx("img",{src:ht,alt:ye,style:{width:"44px",height:"44px",objectFit:"cover",borderRadius:"6px",flexShrink:0}}):r.jsx("div",{className:"flex items-center justify-center text-xs font-semibold",style:{width:"44px",height:"44px",borderRadius:"6px",flexShrink:0,backgroundColor:he.productImageFallbackBg,color:he.textSecondary,fontSize:"12px"},children:ye.charAt(0).toUpperCase()}),r.jsxs("div",{style:{minWidth:0,flex:1},children:[r.jsx("p",{className:"font-medium text-sm",style:{fontSize:"13px",lineHeight:1.3,color:he.text,marginBottom:"4px"},children:ye}),Dt&&r.jsx("p",{className:"text-xs",style:{fontSize:"12px",lineHeight:1.3,color:he.textSecondary,marginBottom:"6px"},children:Dt}),(Je||vt)&&r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{marginBottom:it?"6px":0},children:[Je&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{style:{fontSize:"10px",color:he.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Price"}),r.jsx("span",{className:"font-semibold",style:{fontSize:"13px",color:he.text},children:Je})]}),vt&&r.jsx("span",{className:"text-xs",style:{fontSize:"11px",color:he.successText,backgroundColor:he.successBg,borderRadius:"999px",padding:"2px 8px",fontWeight:600},children:vt})]}),it&&r.jsx("span",{className:"font-medium",style:{fontSize:"12px",color:he.link,textDecoration:"underline",textUnderlineOffset:"2px"},children:it})]})]})},U.product_id||`${C}-${ye}`)})})})}),r.jsxs("div",{className:"mt-2 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[S&&f&&r.jsx("span",{className:"text-sm",style:{fontSize:"13px",color:he.textSecondary,fontWeight:400},children:f}),D?r.jsx("button",{type:"button",onClick:Fe,className:"underline transition-colors duration-200 font-medium text-sm",style:{color:he.link,textDecoration:"underline",textDecorationColor:he.link,textUnderlineOffset:"2px",fontSize:"13px",background:"none",border:"none",padding:0,cursor:"pointer"},children:Q}):null,J&&r.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",className:"underline transition-colors duration-200 font-medium text-sm",style:{color:he.link,textDecoration:"underline",textDecorationColor:he.link,textUnderlineOffset:"2px",fontSize:"13px"},onClick:xe,children:G}),S&&k.length>L.length&&r.jsxs("span",{className:"text-xs",style:{fontSize:"11px",color:he.textMuted},children:["+",k.length-L.length," more"]})]}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsx("p",{className:"text-xs",style:{fontSize:"11px",color:he.textMuted},children:b})})]}),Ne?r.jsxs("div",{style:{marginTop:"10px",border:`1px solid ${H}`,borderRadius:"12px",backgroundColor:he.surfaceSubtle,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:he.link},children:"Confirm Agent Access"}),r.jsxs("div",{style:{fontSize:"14px",lineHeight:1.4,color:he.text,fontWeight:600},children:["Allow ",$||"this brand"," to start a delegated session?"]}),r.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:he.textSecondary},children:"The agent will only use the details you choose to share for this request."})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[r.jsx("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),we(!1)},style:{borderRadius:"10px",border:`1px solid ${H}`,background:_,color:he.text,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:"pointer"},children:"Not now"}),r.jsx("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),we(!0)},style:{borderRadius:"10px",border:"none",background:"#2563eb",color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:"pointer"},children:"Allow agent"})]})]}):null]})]})]})},Cr=({recommendationId:t,admeshLink:e,productId:o,children:s,trackingData:i,className:c,style:u})=>{const y=l.useRef(null);l.useEffect(()=>{if(!y.current)return;y.current.querySelectorAll("a").forEach(d=>{(!d.hasAttribute("target")||d.getAttribute("target")!=="_blank")&&(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer"))})},[s]);const g=l.useCallback(v=>{const h=v.target.closest("a");h?((!h.href||h.href==="#"||h.href==="")&&e&&(h.href=e),(!h.hasAttribute("target")||h.getAttribute("target")!=="_blank")&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener noreferrer"))):e?window.open(e,"_blank","noopener,noreferrer"):a.warn("[AdMeshLinkTracker] No admeshLink provided for click tracking")},[e]);return r.jsx("div",{ref:y,className:c,onClick:g,style:{cursor:"pointer",...u},children:s})};Cr.displayName="AdMeshLinkTracker";function Uo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var kn={exports:{}};/*!
143
+ Copyright (c) 2018 Jed Watson.
144
+ Licensed under the MIT License (MIT), see
145
+ http://jedwatson.github.io/classnames
146
+ */var cr;function Ho(){return cr||(cr=1,(function(t){(function(){var e={}.hasOwnProperty;function o(){for(var c="",u=0;u<arguments.length;u++){var y=arguments[u];y&&(c=i(c,s(y)))}return c}function s(c){if(typeof c=="string"||typeof c=="number")return c;if(typeof c!="object")return"";if(Array.isArray(c))return o.apply(null,c);if(c.toString!==Object.prototype.toString&&!c.toString.toString().includes("[native code]"))return c.toString();var u="";for(var y in c)e.call(c,y)&&c[y]&&(u=i(u,y));return u}function i(c,u){return u?c?c+" "+u:c+u:c}t.exports?(o.default=o,t.exports=o):window.classNames=o})()})(kn)),kn.exports}var qo=Ho();const Oo=Uo(qo),Vo={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Ko={"Top Match":"โ˜…","Free Tier":"โ—†","AI Powered":"โ—‰",Popular:"โ–ฒ",New:"โ—","Trial Available":"โ—ˆ"},Mr=({type:t,variant:e,size:o="md",className:s,style:i})=>{const c=e||Vo[t]||"secondary",u=Ko[t],y=Oo("admesh-component","admesh-badge",`admesh-badge--${c}`,`admesh-badge--${o}`,s);return r.jsxs("span",{className:y,style:i,children:[u&&r.jsx("span",{className:"admesh-badge__icon",children:u}),r.jsx("span",{className:"admesh-badge__text",children:t})]})};Mr.displayName="AdMeshBadge";const Sn="admesh-ui-sdk-styles",An="admesh-ui-sdk-reset",Go=`
117
147
  /* AdMesh UI SDK - CSS Reset & Normalization */
118
148
  .admesh-component,
119
149
  .admesh-component * {
@@ -202,7 +232,7 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
202
232
  .admesh-component[data-admesh-theme="light"] {
203
233
  color-scheme: light;
204
234
  }
205
- `,Ko=`
235
+ `,Yo=`
206
236
  /* AdMesh Core Component Styles */
207
237
 
208
238
  .admesh-component {
@@ -413,7 +443,7 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
413
443
  font-size: 0.875rem;
414
444
  }
415
445
  }
416
- `,Go=()=>{if(!(typeof document>"u")&&!(document.getElementById(An)&&document.getElementById(Sn))){if(!document.getElementById(An)){const t=document.createElement("style");t.id=An,t.textContent=Vo,document.head.appendChild(t)}if(!document.getElementById(Sn)){const t=document.createElement("style");t.id=Sn,t.textContent=Ko,document.head.appendChild(t)}}},Yo=`
446
+ `,Qo=()=>{if(!(typeof document>"u")&&!(document.getElementById(An)&&document.getElementById(Sn))){if(!document.getElementById(An)){const t=document.createElement("style");t.id=An,t.textContent=Go,document.head.appendChild(t)}if(!document.getElementById(Sn)){const t=document.createElement("style");t.id=Sn,t.textContent=Yo,document.head.appendChild(t)}}},Xo=`
417
447
  /* AdMesh UI SDK - Complete Self-Contained Styles */
418
448
 
419
449
  /* CSS Reset for AdMesh components */
@@ -1081,15 +1111,15 @@ Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at
1081
1111
  .admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
1082
1112
  .admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
1083
1113
  }
1084
- `;let dr=!1;const jr=()=>{l.useEffect(()=>{if(!dr){try{Go();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Yo,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),dr=!0}catch{a.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])};function Qo(t){const e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;const o=Math.floor(e/60),s=e%60;return s>0?`${o}m ${s}s`:`${o}m`}function Xo(t){return Qo(t/1e3)}const Cn=({content:t,theme:e,fontSize:o})=>{const s=w=>w.split(/(\*\*[^*]+\*\*|\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g).map((p,y)=>{if(p.startsWith("**")&&p.endsWith("**")&&p.length>4)return r.jsx("strong",{style:{fontWeight:"600",color:e.textColor},children:p.slice(2,-2)},y);const j=p.match(/^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/);return j?r.jsx("a",{href:j[2],target:"_blank",rel:"noopener noreferrer",style:{color:e.primaryColor,textDecoration:"underline",textUnderlineOffset:"2px"},children:j[1]},y):r.jsx(l.Fragment,{children:p},y)}),i=w=>w.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(p=>p.trim()).filter((p,y,j)=>p.length>0||y<j.length-1),c=w=>{const g=i(w);return g.length>1&&g.every(p=>/^:?-{3,}:?$/.test(p))},u=w=>{const g=w.indexOf("|");if(g<=0)return{heading:null,headerLine:w};const p=w.slice(0,g).trim();return!p||/^[-|:\s]+$/.test(p)?{heading:null,headerLine:w}:{heading:p,headerLine:w.slice(g).trim()}},b=(w,g)=>{const p=i(w).length,y=i(g).length;return p<=1||p===y?g:`| ${Array.from({length:p},()=>"---").join(" | ")} |`},h=w=>{if(w.length<2||!w[0].includes("|"))return{heading:null,lines:w};const{heading:g,headerLine:p}=u(w[0]),y=p.startsWith("|")?p:`| ${p}`,j=b(y,w[1]);return{heading:g,lines:[y,j,...w.slice(2)]}},_=w=>{if(w.length<2||!w[0].includes("|"))return!1;const{lines:g}=h(w);return c(g[1])&&i(g[0]).length>=2},d=w=>{if(!w.includes("|"))return[w];let g=w.trim();const p=[],y=g.indexOf("|");if(y>0){const j=g.slice(0,y).trim();j&&!/^[-|:\s]+$/.test(j)&&(p.push(j),g=g.slice(y).trim())}return g=g.replace(/\|\s*(\|(?:\s*:?-{3,}:?\s*\|)+)/g,(j,R)=>`
1085
- ${R}`),g=g.replace(/\|\s*\|\s*(?=[A-Za-z0-9*])/g,`|
1086
- | `),g=g.replace(/\|\s+(?=\|(?!\s*:?-{3,}:?\s*\|)[^|\n])/g,`|
1087
- `),p.push(...g.split(`
1088
- `).map(j=>j.trim()).filter(Boolean)),p},m=w=>{const g=w.split(`
1089
- `),p=[];for(const y of g){if(!y.includes("|")){p.push(y);continue}p.push(...d(y))}return p.join(`
1090
- `)},x=(w=>{const g=m(w).split(`
1091
- `),p=[];let y=0;for(;y<g.length;){const j=g[y],R=g[y+1]||"";if(j.includes("|")&&c(R)){p.length>0&&p[p.length-1].trim()&&p.push("");const{heading:q,headerLine:A}=u(j);for(q&&p.push(q),p.push(A,b(A,R)),y+=2;y<g.length&&g[y].includes("|")&&g[y].trim();)p.push(g[y]),y+=1;y<g.length&&g[y].trim()&&p.push("");continue}p.push(j),y+=1}return p.join(`
1092
- `)})(t).split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);return r.jsx("div",{style:{margin:0,color:e.textColor,fontSize:o},children:x.map((w,g)=>{const p=w.split(`
1093
- `).map(A=>A.trim()).filter(Boolean),y=p.every(A=>/^[-*]\s+/.test(A)),j=p.every(A=>/^\d+\.\s+/.test(A)),R=p.length===1&&/^#{1,3}\s+/.test(p[0]),q=_(p);if(R){const A=p[0].replace(/^#{1,3}\s+/,"");return r.jsx("h3",{style:{marginTop:g===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(A)},g)}if(q){const{heading:A,lines:S}=h(p),L=i(S[0]),W=S.slice(2).map(i).filter(N=>N.length===L.length);return r.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[A?r.jsx("p",{style:{marginTop:g===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(A)}):null,r.jsx("div",{style:{border:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,borderRadius:8,overflowX:"auto"},children:r.jsxs("table",{style:{width:"100%",minWidth:L.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[r.jsx("thead",{children:r.jsx("tr",{children:L.map((N,z)=>r.jsx("th",{style:{textAlign:"left",padding:"9px 10px",fontWeight:600,background:e.surfaceColor||"rgba(148, 163, 184, 0.12)",borderBottom:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,whiteSpace:"normal"},children:s(N)},z))})}),r.jsx("tbody",{children:W.map((N,z)=>r.jsx("tr",{children:N.map((P,$)=>r.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:z===W.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(P)},$))},z))})]})})]},g)}if(y||j){const A=j?"ol":"ul";return r.jsx(A,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:p.map((S,L)=>r.jsx("li",{style:{marginBottom:"0.45rem"},children:s(S.replace(/^([-*]|\d+\.)\s+/,""))},L))},g)}return r.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:p.map((A,S)=>r.jsxs(l.Fragment,{children:[S>0&&r.jsx("br",{}),s(A)]},S))},g)})})};function Qt(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function Pt(t){return t.replace(/\s+/g," ").trim()}function Jo(t,e){const o=t.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),s=e.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),i=e.find(u=>u==null?void 0:u.is_sponsored);if(!i)return s.length?s:o;const c=s.length?s:o;return[i,...c].slice(0,4)}function Zo(t,e,o,s){const i=new Set,c=[],u=(x,w="information")=>{const g=Pt(x);if(!g)return;const p=g.toLowerCase();i.has(p)||(i.add(p),c.push({id:`followup_${c.length}_${p.replace(/[^a-z0-9]+/g,"_")}`,text:g,type:w,is_sponsored:!1}))},b=new Set,h=x=>{const w=Pt(x||"");if(!w)return;const g=w.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();g&&b.add(g)};(s||[]).forEach(x=>h(x==null?void 0:x.title)),(o||[]).forEach(x=>h(x==null?void 0:x.title)),e.split(/\n+/).map(x=>Pt(x.replace(/^[-*]\s+/,""))).filter(Boolean).filter(x=>x.length>=24&&x.length<=90).forEach(x=>{b.size>=6||h(x)});const d=Pt(t.replace(/[?.!]+$/g,"")),m=Array.from(b).slice(0,3);return[m[0]?`Tell me more about ${m[0]}`:"",m[1]?`Show me examples related to ${m[1]}`:"",m[2]?`Compare the main options for ${m[2]}`:"","Break this down more simply",`What should I look at next about ${d}`,"Give me the practical takeaway here"].forEach((x,w)=>{c.length>=3||u(x,w===0?"comparison":"information")}),c.slice(0,3)}function es(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function Er(t){const e=t==null?void 0:t.trim();if(!e||/%%[^%]+%%/.test(e))return!1;try{const o=new URL(e);return!!(o.protocol&&o.hostname)}catch{return!1}}function ur(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Er(e))return e}catch{return}}function mr(t){if(typeof window>"u")return{page_url:void 0,page_path:void 0,article_slug:void 0,page_title:void 0,referrer:void 0,device_type:"unknown"};const e=ur()||(Er(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=ur()?window.location.pathname||"/":void 0}const s=(o||"").split("/").filter(Boolean);return{page_url:e,page_path:o,article_slug:s[s.length-1],page_title:document.title||void 0,referrer:document.referrer||void 0,device_type:es()}}function ts(t){var s,i;const e=(i=(s=t==null?void 0:t.recommendation)==null?void 0:s.creative)==null?void 0:i.follow_up_suggestion,o=t==null?void 0:t.recommendation_id;return!e||!o?null:{id:o,text:Pt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Mn(t){return[...t].sort((e,o)=>{const s=!!e.is_sponsored,i=!!o.is_sponsored;return s===i?0:s?-1:1})}const ns={mode:"light",primaryColor:"#3b82f6",secondaryColor:"#64748b",backgroundColor:"#ffffff",surfaceColor:"#f8fafc",borderColor:"#e2e8f0",textColor:"#1e293b",textSecondaryColor:"#64748b",borderRadius:"0.5rem",spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},shadows:{small:"0 1px 2px 0 rgb(0 0 0 / 0.05)",medium:"0 4px 6px -1px rgb(0 0 0 / 0.1)",large:"0 10px 15px -3px rgb(0 0 0 / 0.1)"}},rs={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},os={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},ss=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:c,showHeaderTitle:u=!0,showSubtitle:b=!0,layout:h="floating",surface:_="page",panelWidth:d,panelHeight:m,analyticsPageUrl:M,fontScale:x=1,position:w="bottom-right",size:g="md",defaultOpen:p,open:y,onOpenChange:j,autoOpen:R=!1,showWelcomeMessage:q=!1,welcomeMessage:A="Hi, Iโ€™m Ava. Iโ€™ll help you find the best options.",placeholder:S="Ask me anything about products...",adsEnabled:L=!0,suggestions:W,maxSuggestions:N=6,suggestionStyle:z="carousel",onlyShowWhenSponsored:P=!1,variant:$="default",queryHandler:Y,suggestionsLoader:Z,disclaimerText:xe,poweredByLabel:F="Powered by AdMesh",subtitle:me="Publisher Assistant",onOpen:ge,onClose:de})=>{const{sdk:Q,sessionId:G,theme:Ne,apiKey:we,userId:Ce}=Wt(),{suggestions:ie,isAnalyzingIntent:ve,intentError:_e,retryIntentAnalysis:ze,activeDelegationSession:Ee,hasActiveDelegationSession:lt,stopDelegationSession:et,refreshDelegationActivity:B}=Rn();jr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:Q,sessionId:G,hasContextTheme:!!Ne});const k=t||Ne||ns,O=(k==null?void 0:k.mode)||"light",v=_==="ad-slot",[C,ee]=l.useState(p||R),T=y!==void 0,ue=T?y:C,[V,se]=l.useState(""),[pe,oe]=l.useState([]),[K,Me]=l.useState(!1),[ye,Ie]=l.useState(null),[I,Ue]=l.useState(!1),[tt,ht]=l.useState(new Set),[kt,Ye]=l.useState(W||ie||[]),[St,te]=l.useState(0),[Re,Je]=l.useState(0),[Ke,ft]=l.useState({}),nt=l.useRef(null),He=l.useRef(!1),$e=l.useRef(null),$t=l.useRef(new Map),gt=l.useRef([]),At=l.useRef(null),Ct=l.useRef(null),Mt=l.useRef(null),Lt=l.useRef(!1),Ut=l.useRef(!1),Ht=l.useRef(null),jt=l.useRef(null),zt=l.useRef(null),H=l.useRef(null),be=l.useRef(null),[le,Et]=l.useState(!1),[Qe,xt]=l.useState(!1),bt=!!(we!=null&&we.toLowerCase().startsWith("pub_")),De=lt()&&(Ee==null?void 0:Ee.session_id)===G?Ee:null,ct=l.useRef(new Set),rt=l.useRef(new Set),qt=l.useRef(!1),Ot=v&&(I||pe.length>0||K),dt=Qt(d)??"100%",Nt=Qt(m)??"100%",en=l.useCallback(n=>f=>{f?$t.current.set(n,f):$t.current.delete(n)},[]),Se=l.useCallback(async(n,f={})=>{if(!(!Q||!G))try{await Q.trackPublisherAssistantEvent({event_name:n,timestamp:new Date().toISOString(),session_id:G,...mr(M),...f})}catch(E){console.warn(`[AdMeshIntentAssistant] Failed to track ${n}`,E)}},[M,Q,G]),tn=l.useCallback((n,f,E)=>{var ne,Ae;const D=f==null?void 0:f.recommendation_id;if(!D)return;const U=`${n}:${D}`;rt.current.has(U)||(rt.current.add(U),Se("recommendation_shown",{message_id:n,query:E,recommendation_id:D,brand_name:(Ae=(ne=f.recommendation)==null?void 0:ne.creative)==null?void 0:Ae.brand_name,is_sponsored:!0}))},[Se]),un=l.useCallback((n,f,E,D,U,ne)=>{const Ae=Array.isArray(ne)&&ne.length?ne.map((je,ke)=>{const Pe=Pt(je.text||"");return Pe?{id:`followup_llm_${ke}_${Pe.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:Pe,type:je.type||"information",is_sponsored:!1}:null}).filter(je=>!!je).slice(0,3):Zo(n,f,E,D),Fe=ts(U),We=Fe?[Fe,...Ae.slice(0,2)]:Ae.slice(0,3);We.length&&Ye(Mn(We))},[]),nn=l.useCallback((n,f)=>{const E=Pt(n.query||n.label||"");if(!E||!f)return;const D={id:f,text:E,type:"action",is_sponsored:!0,recommendation:{recommendation_id:f,recommendation:{creative:{follow_up_suggestion:E}},tracking:{followup_engagement_url:n.engagement_url,followup_exposure_url:n.exposure_url}}};Ye(U=>{const ne=U.filter(Ae=>!Ae.is_sponsored).slice(0,3);return Mn([D,...ne].slice(0,4))})},[]),In=l.useCallback(()=>{const n=At.current,f=Ct.current;if(!n||!f)return!1;const E=n.getBoundingClientRect(),D=f.getBoundingClientRect(),U=Math.max(0,n.scrollTop+D.top-E.top);return n.scrollTop=U,!0},[]);l.useLayoutEffect(()=>{var n;if(Lt.current){In()&&(Lt.current=!1);return}Ut.current||(n=jt.current)==null||n.scrollIntoView({behavior:"smooth"})},[pe,In]),l.useLayoutEffect(()=>{if(!v)return;const n=Ht.current;if(!n)return;const f=n.closest(".admesh-publisher-assistant-reactMount"),E=Nt;[n,f].forEach(U=>{U&&(U.style.width=dt,U.style.maxWidth=dt,U.style.height=E,U.style.maxHeight=E,U.style.overflow="hidden",U.style.boxSizing="border-box",U.dataset.admeshAdSlotExpanded=Ot?"true":"false")});const D=f==null?void 0:f.parentElement;D&&D!==document.body&&D!==document.documentElement&&(D.style.width=dt,D.style.maxWidth=dt,D.style.height=E,D.style.maxHeight=E,D.style.overflow="hidden",D.style.boxSizing="border-box")},[Nt,dt,v,Ot]),l.useEffect(()=>{if(W&&W.length){Ye(W);return}ie&&ie.length&&Ye(n=>Jo(n,ie))},[W,ie]),l.useEffect(()=>{if($!=="default"||!Z)return;let n=!1;return Z().then(f=>{!n&&Array.isArray(f)&&f.length&&Ye(f)}).catch(f=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",f)}),()=>{n=!0}},[Z,$]),l.useEffect(()=>{if(!K){Je(0),nt.current=null;return}nt.current==null&&(nt.current=typeof performance<"u"?performance.now():Date.now());const n=()=>{const E=nt.current;if(E==null)return;const D=typeof performance<"u"?performance.now():Date.now();Je(Math.floor((D-E)/1e3))};n();const f=window.setInterval(n,1e3);return()=>window.clearInterval(f)},[K]),l.useEffect(()=>{if(!K||$!=="default"){te(0);return}const n=window.setInterval(()=>{te(f=>Math.min(f+1,7))},3e3);return()=>window.clearInterval(n)},[K,$]),l.useEffect(()=>{qt.current||!Q||!G||(qt.current=!0,Se("assistant_loaded",{metadata:{layout:h,surface:_,variant:$,default_open:p||R}}))},[R,p,h,Q,G,_,Se,$]);const yt=l.useCallback(n=>{T?j==null||j(n):ee(n),n?(Se("assistant_opened",{metadata:{layout:h,surface:_,variant:$,expanded:I}}),ge==null||ge()):de==null||de()},[T,I,h,j,ge,de,_,Se,$]),Dn=l.useCallback(()=>{yt(!0)},[yt]),Tr=l.useCallback(()=>{yt(!1)},[yt]),Ir=l.useCallback(()=>{Ue(n=>!n)},[]),Pn=l.useCallback(async(n,f,E,D,U,ne,Ae)=>{var Fe,We,je;if(!Q)return console.warn("[AdMeshIntentAssistant] SDK not available - using fallback response"),{text:"I'm a demo assistant. The SDK is not properly configured, but I can still help with suggestions! Try clicking on one of the suggested questions above."};try{De&&await B("turn_started",{source:"publisher_assistant",recommendation_id:De.recommendation_id}).catch(ce=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",ce)});const ke=await fetch(`${Q.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:ne,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${we}`},body:JSON.stringify({message:n,session_id:G||"default-session",message_id:f,user_id:Ce,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:mr(M),conversation_history:Ae,sponsored_recommendation:U!=null&&U.recommendation_id?{recommendation_id:U.recommendation_id,brand_name:(We=(Fe=U.recommendation)==null?void 0:Fe.creative)==null?void 0:We.brand_name}:void 0,active_delegation_session:De?{delegation_session_id:De.delegation_session_id,recommendation_id:De.recommendation_id,session_id:De.session_id,brand_name:De.brand_name,mcp_endpoint:De.mcp_endpoint,status:De.status}:void 0}})});if(!ke.ok)throw new Error(`API request failed: ${ke.status} ${ke.statusText}`);const Pe=(je=ke.body)==null?void 0:je.getReader(),Rt=new TextDecoder;if(!Pe)throw new Error("Response body is not readable");let Oe="",Xe,Tt,pt,X,re;return await(async()=>{try{for(;;){const{done:ce,value:Ze}=await Pe.read();if(ce)break;const Ge=Rt.decode(Ze,{stream:!0}).split(`
1094
- `);for(const It of Ge)if(It.startsWith("data: ")){const _n=It.slice(6);if(_n.trim()==="[DONE]")return De&&B("turn_completed",{source:"publisher_assistant",recommendation_id:De.recommendation_id}).catch(Te=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",Te)}),{text:Oe,source_links:Xe,related_items:Tt,followup_suggestions:pt,used_capability:X,response_time_ms:re};try{const Te=JSON.parse(_n);switch(Te.type){case"content":{const Qn=Te.content||"";Oe+=Qn,E==null||E(Qn);break}case"final":{Oe=Te.reply||Oe,Xe=Array.isArray(Te.source_links)?Te.source_links:void 0,Tt=Array.isArray(Te.related_items)?Te.related_items:void 0,pt=Array.isArray(Te.followup_suggestions)?Te.followup_suggestions:void 0,X=typeof Te.used_capability=="string"?Te.used_capability:X,re=typeof Te.response_time_ms=="number"?Te.response_time_ms:re;break}case"followup_suggestions":{pt=Array.isArray(Te.followup_suggestions)?Te.followup_suggestions:pt;break}case"error":throw new Error(Te.message||"Unknown streaming error");case"session_start":D==null||D(),console.log("Session started:",Te.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",_n);continue}}}}catch(ce){if(ne!=null&&ne.aborted)return{text:Oe,source_links:Xe,related_items:Tt,followup_suggestions:pt,used_capability:X,response_time_ms:re,error:"aborted"};throw console.error("Stream processing error:",ce),ce}finally{Pe.releaseLock()}return{text:Oe,source_links:Xe,related_items:Tt,followup_suggestions:pt,used_capability:X,response_time_ms:re}})()}catch(ke){return ne!=null&&ne.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",ke),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:ke instanceof Error?ke.message:"request_failed"})}},[Q,G,we,Ce,De,B]),mn=l.useCallback(()=>{const n=H.current;if(!n||n.signal.aborted)return;n.abort(),Me(!1),$e.current=null,He.current=!1;const f=be.current;f&&oe(E=>E.map(D=>D.id===f&&!D.content.trim()?{...D,content:"Generation stopped."}:D))},[]),_t=l.useCallback(async n=>{var je,ke,Pe,Rt,Oe,Xe,Tt,pt;if(!n.trim()||K)return;const f=typeof performance<"u"?performance.now():Date.now(),E=n.trim(),D=Date.now().toString(),U=new AbortController,ne=$e.current,Ae=(ne==null?void 0:ne.recommendation)||null,Fe=pe.filter(X=>(X.role==="user"||X.role==="assistant")&&X.content.trim()).slice(-6).map(X=>({role:X.role,content:X.content.trim().slice(0,1200)}));H.current=U,be.current=null,Mt.current=D,Lt.current=!0,Ut.current=!0,$e.current=null,Ye(X=>X.some(re=>re.is_sponsored)?X.filter(re=>!re.is_sponsored):X),Ie(null);const We={id:D,role:"user",content:E,timestamp:new Date};if(Se("query_submitted",{message_id:D,query:E}),oe(X=>[...X,We]),se(""),Me(!0),$==="default"&&Y){try{const X=(Date.now()+1).toString(),re={id:X,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:null};He.current&&(ht(Ze=>new Set([...Ze,X])),He.current=!1),oe(Ze=>[...Ze,re]),be.current=X;const Le=await Y(E,{sponsoredSuggestion:ne});if(U.signal.aborted){$e.current=null;return}const ce=Le.recommendation||Ae||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:n,hasResponseRecommendation:!!Le.recommendation,hasSponsoredSuggestionRecommendation:!!Ae,finalRecommendationId:ce==null?void 0:ce.recommendation_id}),oe(Ze=>Ze.map(Ve=>Ve.id===X?{...Ve,content:Le.answer,sourceLinks:Le.source_links,relatedItems:Le.related_items,initialRecommendation:ce,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-f}:Ve)),un(E,Le.answer,Le.source_links,Le.related_items,Le.recommendation||null,Le.followup_suggestions),Se("answer_completed",{message_id:X,query:E,recommendation_id:ce==null?void 0:ce.recommendation_id,brand_name:(ke=(je=ce==null?void 0:ce.recommendation)==null?void 0:je.creative)==null?void 0:ke.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:"completed",metadata:{variant:$,source:"query_handler"}}),$e.current=null}catch(X){console.error("Error sending message:",X);const re=X instanceof Error?X.message:"Unknown error occurred";Ie(re);const Le={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};oe(ce=>[...ce,Le]),Se("answer_failed",{query:E,status:re,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,metadata:{variant:$,source:"query_handler"}}),$e.current=null}finally{H.current===U&&(H.current=null,be.current=null,Me(!1))}return}if(!Q){setTimeout(()=>{if(U.signal.aborted){H.current===U&&(H.current=null,be.current=null);return}const X={id:(Date.now()+1).toString(),role:"assistant",content:"I'm a demo assistant. The SDK is not properly configured, but I can still help! Try clicking on the suggested questions above, or check your AdMesh API key configuration.",timestamp:new Date,recommendations:[],userQuery:n};oe(re=>[...re,X]),H.current===U&&(H.current=null,be.current=null,Me(!1))},1e3);return}try{const X=(Date.now()+1).toString(),re=Ae,Le={id:X,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:re};He.current&&(ht(Ve=>new Set([...Ve,X])),He.current=!1),oe(Ve=>[...Ve,Le]),be.current=X;const ce=await Pn(E,D,Ve=>{oe(Ge=>Ge.map(It=>It.id===X?{...It,content:It.content+Ve}:It))},()=>{Me(!0),te(0)},re,U.signal,Fe);if(U.signal.aborted){ce.text.trim()||oe(Ve=>Ve.map(Ge=>Ge.id===X&&!Ge.content.trim()?{...Ge,content:"Generation stopped."}:Ge)),Se("answer_failed",{message_id:X,query:E,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(Rt=(Pe=re==null?void 0:re.recommendation)==null?void 0:Pe.creative)==null?void 0:Rt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:"aborted",metadata:{variant:$,source:"api_chat_assistant"}}),$e.current=null;return}const Ze=typeof ce.response_time_ms=="number"?ce.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-f;oe(Ve=>Ve.map(Ge=>Ge.id===X?{...Ge,content:ce.text,sourceLinks:ce.source_links,relatedItems:ce.related_items,initialRecommendation:Ge.initialRecommendation||re,responseTimeMs:Ze}:Ge)),un(E,ce.text,ce.source_links,ce.related_items,null,ce.followup_suggestions),ce.error?Se("answer_failed",{message_id:X,query:E,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(Xe=(Oe=re==null?void 0:re.recommendation)==null?void 0:Oe.creative)==null?void 0:Xe.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:ce.error,metadata:{variant:$,source:"api_chat_assistant"}}):Se("answer_completed",{message_id:X,query:E,recommendation_id:re==null?void 0:re.recommendation_id,brand_name:(pt=(Tt=re==null?void 0:re.recommendation)==null?void 0:Tt.creative)==null?void 0:pt.brand_name,used_capability:ce.used_capability,latency_ms:Ze,status:"completed",metadata:{variant:$,source:"api_chat_assistant",response_time_ms:Ze}}),$e.current=null}catch(X){console.error("Error sending message:",X);const re=X instanceof Error?X.message:"Unknown error occurred";Ie(re);const Le={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};oe(ce=>[...ce,Le]),Se("answer_failed",{query:E,latency_ms:(typeof performance<"u"?performance.now():Date.now())-f,status:re,metadata:{variant:$,source:"api_chat_assistant"}}),$e.current=null}finally{H.current===U&&(H.current=null,be.current=null,Me(!1))}},[K,Pn,Y,un,Q,Se,$]),wt=kt,rn=l.useMemo(()=>wt.some(n=>n==null?void 0:n.is_sponsored),[wt]),on=l.useMemo(()=>wt.filter(n=>!(n&&typeof n.id=="string")?!1:P?rn:!0),[rn,P,wt]),qe=l.useMemo(()=>Mn(on),[on]),sn=l.useCallback(async n=>{var E,D,U,ne,Ae,Fe,We;console.log("[AdMeshIntentAssistant] ๐Ÿ–ฑ๏ธ Suggestion clicked:",{text:n.text,is_sponsored:n.is_sponsored,hasRecommendation:!!n.recommendation,recommendationId:((E=n.recommendation)==null?void 0:E.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((U=(D=n.recommendation)==null?void 0:D.tracking)!=null&&U.followup_engagement_url),sessionId:G}),He.current=n.is_sponsored||!1,$e.current=n.is_sponsored?n:null;const f=qe.findIndex(je=>je.id===n.id);Se("suggestion_clicked",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:f>=0?f:void 0,is_sponsored:n.is_sponsored,recommendation_id:(ne=n.recommendation)==null?void 0:ne.recommendation_id,brand_name:(We=(Fe=(Ae=n.recommendation)==null?void 0:Ae.recommendation)==null?void 0:Fe.creative)==null?void 0:We.brand_name,query:n.text}),_t(n.text),n.is_sponsored&&n.recommendation&&Q?setTimeout(async()=>{var je;try{const ke=(je=n.recommendation.tracking)==null?void 0:je.followup_engagement_url,Pe=n.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ŸŽฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:ke,recommendationId:Pe,sessionId:G}),ke&&Pe&&G?(console.log("[AdMeshIntentAssistant] ๐ŸŽฏ Firing sponsored suggestion engagement tracking"),await Q.fireFollowupEngagement(ke,Pe,G),console.log("[AdMeshIntentAssistant] โœ… Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โš ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!ke,hasRecommendationId:!!Pe,hasSessionId:!!G})}catch(ke){console.error("[AdMeshIntentAssistant] โŒ Error firing sponsored suggestion engagement:",ke)}},0):console.log("[AdMeshIntentAssistant] โ„น๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[_t,qe,Q,G,Se]),an=os[w],$n=rs[g];l.useEffect(()=>{if(gt.current.forEach(n=>n()),gt.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return qe.forEach((n,f)=>{const E=$t.current.get(n.id);if(!E)return;const D=`${G||"anonymous"}:${n.id}:${n.is_sponsored?"s":"o"}`;if(ct.current.has(D))return;let U=null,ne=null;const Ae=()=>{U&&(clearTimeout(U),U=null),ne==null||ne.disconnect(),ne=null},Fe=()=>{var We,je,ke,Pe,Rt;if(ct.current.has(D)){Ae();return}if(ct.current.add(D),Ae(),Se("suggestion_exposure",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:f,is_sponsored:n.is_sponsored,recommendation_id:(We=n.recommendation)==null?void 0:We.recommendation_id,brand_name:(Pe=(ke=(je=n.recommendation)==null?void 0:je.recommendation)==null?void 0:ke.creative)==null?void 0:Pe.brand_name}),Q&&G&&n.is_sponsored&&n.recommendation){const Oe=(Rt=n.recommendation.tracking)==null?void 0:Rt.followup_exposure_url,Xe=n.recommendation.recommendation_id;Oe&&Xe?(console.log("[AdMeshIntentAssistant] ๐ŸŽฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Oe,recommendationId:Xe,suggestionText:n.text,sessionId:G}),Q.fireFollowupExposure(Oe,Xe,G)):console.warn("[AdMeshIntentAssistant] โš ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Oe,hasRecommendationId:!!Xe,suggestionText:n.text})}};ne=new IntersectionObserver(We=>{const je=We[0];if(je){if(je.intersectionRatio>=.5){U||(U=setTimeout(Fe,1e3));return}U&&(clearTimeout(U),U=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),ne.observe(E),gt.current.push(Ae)}),()=>{gt.current.forEach(n=>n()),gt.current=[]}},[qe,Q,G,Se]),console.log("[AdMeshIntentAssistant] ๐Ÿ“ฅ Received suggestions:",{totalSuggestions:wt.length,safeSuggestions:on.length,isAnalyzingIntent:ve,hasIntentError:!!_e,onlyShowWhenSponsored:P,hasSponsoredSuggestions:rn,sponsoredCount:wt.filter(n=>n==null?void 0:n.is_sponsored).length,nonSponsoredCount:wt.filter(n=>n&&!(n!=null&&n.is_sponsored)).length,modalShouldAppear:P?rn:!0,suggestions:wt.map(n=>{var f,E,D;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((f=n==null?void 0:n.recommendation)==null?void 0:f.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((D=(E=n==null?void 0:n.recommendation)==null?void 0:E.tracking)!=null&&D.followup_engagement_url)}}),renderedSuggestions:qe.map(n=>{var f,E,D;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((f=n==null?void 0:n.recommendation)==null?void 0:f.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((D=(E=n==null?void 0:n.recommendation)==null?void 0:E.tracking)!=null&&D.followup_engagement_url)}})});const he={base:`${16*x}px`,sm:`${14*x}px`,xs:`${12*x}px`},pn=xe||"AI-generated responses may contain errors. Please verify important information independently.",Dr=["Searching trusted sources...","Reviewing publisher coverage...","Checking relevant context...","Comparing supporting signals...","Identifying the strongest examples...","Organizing the most useful details...","Shaping the response for clarity...","Preparing the clearest answer...","Finishing the response..."],Vt=n=>{const f=(n==null?void 0:n.accentColor)||ot,E=(n==null?void 0:n.metaColor)||Gt,D=(n==null?void 0:n.includeSteps)??$==="default",U=`${Re}s`,ne=D?`${Dr[St]} (${U})`:`Generating answer... ${U}`;return r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:n!=null&&n.compact?"8px":"10px",color:E,fontSize:n!=null&&n.compact?he.xs:he.sm},children:[r.jsx("span",{style:{width:n!=null&&n.compact?8:9,height:n!=null&&n.compact?8:9,borderRadius:999,background:f,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${J(ae,.28)}`,flexShrink:0}}),r.jsx("span",{children:ne})]})},Ln=l.useCallback((n,f)=>{if(Ke[n.id])return;const E=f?"helpful":"not_helpful";ft(D=>({...D,[n.id]:E})),Se("answer_feedback",{message_id:n.id,query:n.userQuery,status:E,latency_ms:n.responseTimeMs,metadata:{helpful:f}})},[Ke,Se]);function hn(n,f){if(n.role!=="assistant"||!n.content.trim()||K&&n.id===be.current)return null;const E=(f==null?void 0:f.accentColor)||ot,D=(f==null?void 0:f.metaColor)||Gt,U=Ke[n.id],ne=typeof n.responseTimeMs=="number";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${J(ae,.08)}`,flexWrap:"nowrap"},children:[r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto"},children:[r.jsx("span",{style:{fontSize:he.xs,color:D,whiteSpace:"nowrap"},children:U?"Thanks for your feedback":"Is this helpful?"}),U?r.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,background:J(E,.12),color:E,flexShrink:0},children:U==="helpful"?r.jsx(cr,{size:14}):r.jsx(lr,{size:14})}):r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[r.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>Ln(n,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${J(ae,.12)}`,background:"#ffffff",color:D,cursor:"pointer"},children:r.jsx(cr,{size:14})}),r.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>Ln(n,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${J(ae,.12)}`,background:"#ffffff",color:D,cursor:"pointer"},children:r.jsx(lr,{size:14})})]})]}),ne?r.jsxs("span",{style:{fontSize:he.xs,color:D,whiteSpace:"nowrap",flexShrink:0,marginLeft:"auto"},children:["Answer Completed in ",Xo(n.responseTimeMs)]}):null]})}const Kt=l.useCallback(()=>{const n=zt.current;if(!n)return;const f=Math.max(0,n.scrollWidth-n.clientWidth);Et(n.scrollLeft>4),xt(n.scrollLeft<f-4)},[]);l.useEffect(()=>(Kt(),window.addEventListener("resize",Kt),()=>window.removeEventListener("resize",Kt)),[Kt,qe.length]);const zn=l.useCallback(n=>{const f=zt.current;f&&f.scrollBy({left:n==="left"?-Math.max(160,Math.floor(f.clientWidth*.75)):Math.max(160,Math.floor(f.clientWidth*.75)),behavior:"smooth"})},[]),J=(n,f)=>{if(!n||!n.startsWith("#"))return`rgba(15, 23, 42, ${f})`;const E=n.slice(1),D=E.length===3?E.split("").map(Fe=>`${Fe}${Fe}`).join(""):E;if(D.length!==6)return n;const U=parseInt(D.slice(0,2),16),ne=parseInt(D.slice(2,4),16),Ae=parseInt(D.slice(4,6),16);return`rgba(${U}, ${ne}, ${Ae}, ${f})`},ae=k.primaryColor||"#3F037F";k.surfaceColor,k.backgroundColor;const Nn=k.borderColor||"#e5e7eb",ut=k.textColor||"#111827",Pr=k.textSecondaryColor||"#6b7280";J(ae,.12);const fn=J(ae,.24);J(ae,.38);const $r=J(ae,.12),Lr=v?dt:I?"min(960px, calc(100vw - 24px))":h==="inline"?"100%":"min(420px, calc(100vw - 32px))",Fn=v?Nt:I?"min(78vh, 760px)":"auto",zr=v?dt:"100%",Nr=v?Nt:void 0,Wn=v?"13px":"16.25px",Fr=`linear-gradient(180deg, ${J(ae,.04)} 0%, ${J(ae,.08)} 100%)`,ot=ae,Gt=Pr,Bn=me||"Publisher Assistant",Yt=ve&&qe.length===0&&pe.length===0,gn="#f7f8fc",xn="linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(248,250,252,0.98) 100%)",mt="rgba(15, 23, 42, 0.08)",Un="rgba(15, 23, 42, 0.12)",Hn="0 24px 60px rgba(15, 23, 42, 0.16)",bn="#667085",qn="#98a2b3",Wr=ot,On="#ffffff",Vn="0 8px 24px rgba(15, 23, 42, 0.08)",Kn="rgba(15, 23, 42, 0.18)";function Gn(n){return De?r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:n==="default"?"10px 12px":"8px 10px",borderRadius:n==="default"?"14px":"12px",border:`1px solid ${fn}`,background:J("#ffffff",.9),marginBottom:"4px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{color:ot,fontSize:he.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),r.jsxs("div",{style:{color:ut,fontSize:he.sm,fontWeight:600,lineHeight:1.3},children:[De.brand_name," agent is active"]})]}),r.jsx("button",{type:"button",onClick:()=>{et("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${fn}`,borderRadius:999,background:J("#ffffff",.92),color:ot,padding:"7px 12px",fontSize:he.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function Yn(n){const f=v;return r.jsxs("div",{style:{display:"flex",flexDirection:f?"column":"row",alignItems:f||n==="default"?"center":"flex-start",justifyContent:f?"center":"space-between",gap:f?"2px":"12px",flexWrap:"wrap",paddingTop:f||n==="default"?"2px":"8px",borderTop:n==="default"?`1px solid ${mt}`:"none",marginTop:f?"0":n==="default"?"4px":0,flexShrink:0},children:[r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:f?"4px":"8px",color:qn,fontSize:f?"9.5px":"11px",fontWeight:700,letterSpacing:"0.01em"},children:r.jsxs("span",{children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]})}),r.jsx("div",{style:{color:qn,fontSize:f?"9px":"11px",lineHeight:f?1.25:1.45,maxWidth:f?"100%":n==="default"?"68%":"100%",textAlign:f?"center":n==="default"?"right":"left"},children:pn})]})}function yn(n){const f=n==="publisher"?[180,220,196]:["100%","82%","68%"];return n==="publisher"?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:J(ae,.1),flexShrink:0}}),r.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:f.map((E,D)=>r.jsx("div",{style:{width:E,maxWidth:"100%",height:40,borderRadius:999,background:`linear-gradient(90deg, ${J(ae,.08)} 0%, ${J(ae,.18)} 50%, ${J(ae,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:`0 8px 22px ${J(ae,.08)}`,flexShrink:0}},`suggestion-skeleton-${D}`))}),r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:J(ae,.1),flexShrink:0}})]}):r.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:n==="publisher"?"10px":"12px"},children:f.map((E,D)=>r.jsx("div",{style:{width:E,maxWidth:"100%",height:n==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${J(ae,.08)} 0%, ${J(ae,.18)} 50%, ${J(ae,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:n==="publisher"?`0 8px 22px ${J(ae,.08)}`:"none"}},`suggestion-skeleton-${D}`))})}function Br(){if(K)return null;if(Yt)return yn("publisher");if(!qe.length)return null;const n=qe.slice(0,N);return z==="stacked"?r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:v?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:v?"240px":void 0,paddingRight:v?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:n.map(f=>r.jsxs("button",{ref:en(f.id),onClick:()=>{$==="default"&&(Ue(!0),h==="floating"&&yt(!0)),sn(f)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:v?"12px":"14px",border:f.is_sponsored?`1px solid ${J(ae,.32)}`:`1px solid ${J(ae,.42)}`,background:f.is_sponsored?ae:J("#ffffff",.94),color:f.is_sponsored?"#ffffff":ut,padding:v?"8px 10px":"10px 14px",fontSize:v?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:f.is_sponsored?`0 8px 18px ${J(ae,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{style:{minWidth:0},children:f.text}),L&&f.is_sponsored&&r.jsx("span",{style:{flexShrink:0,borderRadius:999,background:J("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},f.id))}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:v?"6px":"10px",flexShrink:0},children:[r.jsx("button",{type:"button",onClick:()=>zn("left"),disabled:!le,"aria-label":"Scroll suggestions left",style:{width:v?24:28,height:v?24:28,borderRadius:999,border:`1px solid ${J(Nn,.8)}`,background:J("#ffffff",.9),color:"#6b7280",cursor:le?"pointer":"default",opacity:le?1:.55},children:"โ€น"}),r.jsx("div",{ref:zt,onScroll:Kt,style:{display:"flex",gap:v?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:n.map(f=>r.jsxs("button",{ref:en(f.id),onClick:()=>{$==="default"&&(Ue(!0),h==="floating"&&yt(!0)),sn(f)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:"8px",whiteSpace:"nowrap",borderRadius:999,border:f.is_sponsored?`1px solid ${J(ae,.32)}`:`1px solid ${J(ae,.42)}`,background:f.is_sponsored?ae:J("#ffffff",.94),color:f.is_sponsored?"#ffffff":ut,padding:v?"7px 10px":"8px 14px",fontSize:v?"12px":"13px",fontWeight:500,boxShadow:f.is_sponsored?`0 8px 18px ${J(ae,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{children:f.text}),L&&f.is_sponsored&&r.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},f.id))}),r.jsx("button",{type:"button",onClick:()=>zn("right"),disabled:!Qe,"aria-label":"Scroll suggestions right",style:{width:v?24:28,height:v?24:28,borderRadius:999,border:`1px solid ${J(Nn,.8)}`,background:J("#ffffff",.9),color:"#6b7280",cursor:Qe?"pointer":"default",opacity:Qe?1:.55},children:"โ€บ"})]})}function Ur(n){var f,E;return(f=n.relatedItems)!=null&&f.length||!((E=n.sourceLinks)!=null&&E.length)?null:r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:n.sourceLinks.map(D=>r.jsx("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Se("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:D.title,source_url:D.url}})},style:{color:ot,fontSize:he.xs,textDecoration:"none",borderBottom:`1px solid ${J(ae,.18)}`},children:D.title||D.url},`${n.id}-${D.url}`))})}function Hr(n){var f;return(f=n.relatedItems)!=null&&f.length?r.jsxs("div",{style:{marginTop:"14px"},children:[r.jsx("div",{style:{fontSize:he.xs,fontWeight:700,color:"#4b5563",marginBottom:"8px"},children:"Related"}),r.jsx("div",{style:{display:"flex",gap:v?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:n.relatedItems.slice(0,4).map(E=>r.jsxs("a",{href:E.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Se("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:E.title,source_url:E.url,source_publisher:E.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:v?"6px":"10px",padding:v?"10px":"14px",borderRadius:v?"12px":"14px",textDecoration:"none",color:ut,border:`1px solid ${J(ae,.18)}`,background:"#ffffff",boxShadow:"0 10px 24px rgba(15, 23, 42, 0.08)",flex:v?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:v?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[r.jsx("div",{style:{fontSize:v?"13px":"18px",fontWeight:650,lineHeight:1.35,color:ae,overflowWrap:"anywhere"},children:E.title||E.url}),E.publisher&&r.jsx("div",{style:{fontSize:v?"11px":"15px",color:"#6b7280",lineHeight:1.4,overflowWrap:"anywhere"},children:E.publisher})]},`${n.id}-${E.url}`))})]}):null}function qr(){return r.jsxs("div",{ref:At,style:{flex:v?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:v?"contain":void 0,WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none",padding:v?"0 2px 4px":I?"16px 16px 8px":0},children:[pe.map(n=>{const f=n.role==="user"&&n.id===Mt.current;return r.jsx("div",{ref:f?Ct:void 0,style:{marginBottom:"12px",textAlign:n.role==="user"?"right":"left"},children:(()=>{const D=!!n.content.trim()||!K;return r.jsx(r.Fragment,{children:r.jsxs("div",{style:{display:n.role==="assistant"?"block":"inline-block",width:n.role==="assistant"?"100%":void 0,maxWidth:n.role==="assistant"?"100%":"76%",padding:n.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:n.role==="assistant"?0:"18px",background:n.role==="user"?ot:"transparent",color:n.role==="user"?"#ffffff":ut,boxShadow:"none",border:"none",fontSize:n.role==="assistant"?Wn:v?"12px":"13px",lineHeight:n.role==="assistant"?1.62:1.4},children:[n.role==="assistant"?n.content.trim()?r.jsx(Cn,{content:n.content,theme:{...k,textColor:ut},fontSize:Wn}):K&&n.id===be.current?Vt({includeSteps:!0}):null:r.jsx("p",{style:{margin:0},children:n.content}),n.role==="assistant"&&Ur(n),n.role==="assistant"&&Hr(n),n.role==="assistant"&&hn(n),n.role==="assistant"&&D&&tt.has(n.id)&&n.initialRecommendation&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:nn,onRecommendationsShown:(U,ne)=>{tn(U,ne,n.userQuery)},onError:U=>{console.error("[AdMeshIntentAssistant] Recommendation error:",U)}})}),n.role==="assistant"&&D&&!tt.has(n.id)&&(n.initialRecommendation||bt)&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation||void 0,onFollowupDetected:nn,onRecommendationsShown:(U,ne)=>{tn(U,ne,n.userQuery)},onError:U=>{console.error("[AdMeshIntentAssistant] Recommendation error:",U)}})})]})})})()},n.id)}),ye&&r.jsx("div",{style:{color:Gt,fontSize:he.sm},children:"Connection issue. Please try again."}),r.jsx("div",{ref:jt})]})}if($==="default"){const n=r.jsxs("div",{style:{width:Lr,maxWidth:zr,height:Fn,maxHeight:Nr,boxSizing:"border-box",display:"flex",flexDirection:"column",background:I?gn:Fr,borderRadius:v?"12px":I?"18px":"20px",padding:I?0:v?"8px":"12px",boxShadow:I?Hn:"none",border:I?`1px solid ${Un}`:"none",overflow:"hidden",minHeight:v?0:void 0},children:[(I||v)&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:v?"10px 12px":"16px 18px",background:I?xn:"#ffffff29",color:ut,borderBottom:`1px solid ${mt}`,flexShrink:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("div",{style:{width:v?30:40,height:v?30:40,borderRadius:v?"10px":"14px",background:J(ae,.08),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:ot,overflow:"hidden"},children:c?r.jsx("img",{src:c,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||b)&&r.jsxs("div",{children:[u&&r.jsx("div",{style:{fontSize:v?"14px":"20px",fontWeight:700,lineHeight:1.1,letterSpacing:0},children:i}),b&&r.jsx("div",{style:{fontSize:v?"10px":"12px",color:bn,marginTop:"2px"},children:Bn})]})]}),!v&&r.jsx("button",{type:"button",onClick:()=>Ue(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"12px",border:`1px solid ${mt}`,background:"#ffffff",color:bn,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx("span",{style:{fontSize:"18px",lineHeight:1,fontWeight:700,transform:"translateY(-1px)"},children:"-"})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:v?"6px":"16px",minHeight:0,flex:v?"1 1 0":void 0,overflow:v?"hidden":void 0,padding:v?"8px 10px 6px":I?"18px":"14px",background:I?gn:J("#ffffff",.16),height:v?void 0:I?Fn:"auto"},children:[Gn("default"),I&&qr(),v&&!I&&r.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),v&&!I&&q&&pe.length===0&&r.jsx("div",{style:{color:ut,fontSize:"15px",lineHeight:1.3,fontWeight:700,letterSpacing:0,padding:"2px 2px 0",textAlign:"center"},children:A}),Br(),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",borderRadius:v?"12px":"16px",background:On,padding:v?"6px 6px 6px 10px":"8px 8px 8px 14px",boxShadow:I?Vn:`0 8px 22px ${$r}`,border:`1px solid ${I?mt:fn}`,flexShrink:0},children:[r.jsx("input",{type:"text",value:V,onChange:f=>se(f.target.value),onKeyPress:f=>{if(f.key==="Enter"){if(f.preventDefault(),K)return;$e.current=null,He.current=!1,Ue(!0),h==="floating"&&yt(!0),_t(V)}},placeholder:S,style:{flex:1,border:"none",outline:"none",borderRadius:"12px",padding:v?"8px 2px":"10px 4px",color:ut,fontSize:v?"13px":"15px",background:"transparent"}}),r.jsx("button",{type:"button",onClick:()=>{if(K){mn();return}$e.current=null,He.current=!1,Ue(!0),h==="floating"&&yt(!0),_t(V)},disabled:!K&&!V.trim(),style:{border:"none",borderRadius:"12px",background:K?"#dc2626":ot,color:"#ffffff",minWidth:v?"40px":"48px",height:v?"36px":"44px",padding:v?"0 10px":"0 16px",fontSize:v?"12px":"14px",fontWeight:700,cursor:!K&&!V.trim()?"default":"pointer",opacity:!K&&!V.trim()?.6:1,boxShadow:`0 10px 20px ${K?"rgba(220, 38, 38, 0.18)":J(ae,.18)}`},children:K?"Stop":"Send"})]}),I&&Yn("default"),!I&&r.jsxs("div",{style:{textAlign:"center",paddingTop:"2px"},children:[r.jsxs("div",{style:{color:Gt,fontSize:v?"9.5px":he.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),r.jsx("div",{style:{color:Gt,fontSize:v?"9px":he.xs,lineHeight:v?1.25:1.5},children:pn})]})]})]});return h==="inline"?v?r.jsx("div",{ref:Ht,className:"admesh-component","data-admesh-theme":O,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-expanded":Ot?"true":"false",style:{width:dt,height:Nt,maxWidth:dt,maxHeight:Nt,position:"relative",overflow:"hidden"},children:n}):r.jsxs("div",{className:"admesh-component","data-admesh-theme":O,style:{width:"100%",position:"relative"},children:[n,I&&r.jsx("div",{onClick:()=>Ue(!1),style:{position:"fixed",inset:0,background:Kn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),I&&r.jsx("div",{style:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",zIndex:2147483001},children:n})]}):ue?r.jsxs("div",{className:"admesh-component","data-admesh-theme":O,children:[I&&r.jsx("div",{onClick:()=>Ue(!1),style:{position:"fixed",inset:0,background:Kn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),r.jsx("div",{style:{position:"fixed",...I?{left:"50%",bottom:"12px",transform:"translateX(-50%)"}:an,zIndex:2147483001},children:n})]}):r.jsx("div",{className:"admesh-component","data-admesh-theme":O,children:r.jsx("button",{type:"button",onClick:Dn,style:{position:"fixed",...an,zIndex:2147483e3,border:"none",borderRadius:999,background:k.primaryColor,color:"#ffffff",padding:"14px 18px",boxShadow:"0 18px 40px rgba(15, 23, 42, 0.18)",cursor:"pointer"},children:s})})}return qe.length===0&&!Yt?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):h==="inline"?r.jsx("div",{className:"admesh-component","data-admesh-theme":O,children:r.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:Qt(d)??"100%",backgroundColor:"#eef2ff",fontSize:he.base,...o},children:r.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[Yt?yn("legacy"):qe.length>0&&r.jsx("div",{className:"flex flex-col gap-3",children:qe.slice(0,N).map((n,f)=>r.jsxs("button",{ref:en(n.id),onClick:()=>sn(n),className:"rounded-full px-5 py-4 text-left shadow-sm transition-transform duration-200 hover:scale-[1.01] active:scale-[0.99]",style:{width:f===0?"100%":f===1?"82%":"68%",backgroundColor:k.surfaceColor||"#ffffff",color:k.textColor||"#1e293b",border:`1px solid ${k.borderColor||"#e2e8f0"}`,fontSize:he.sm},children:[r.jsx("span",{className:"leading-tight",children:n.text}),L&&n.is_sponsored&&r.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:k.backgroundColor||"#ffffff",color:k.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},n.id))}),pe.length>0&&r.jsxs("div",{ref:At,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:k.textColor},children:[pe.map(n=>{const f=n.role==="user"&&n.id===Mt.current;return r.jsx("div",{ref:f?Ct:void 0,className:n.role==="user"?"text-right":"text-left",children:r.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:n.role==="user"?k.primaryColor:"#ffffff",color:n.role==="user"?"#ffffff":k.textColor,fontSize:he.sm},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx(Cn,{content:n.content,theme:k,fontSize:he.sm}),hn(n,{accentColor:k.primaryColor,metaColor:k.textSecondaryColor})]}):K&&n.id===be.current?Vt({compact:!0,accentColor:k.primaryColor,metaColor:k.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:n.content})})},n.id)}),K&&!pe.some(n=>n.role==="assistant"&&n.id===be.current&&!n.content.trim())&&r.jsx("div",{className:"text-sm",style:{color:k.textSecondaryColor},children:Vt({compact:!0,accentColor:k.primaryColor,metaColor:k.textSecondaryColor,includeSteps:!1})}),ye&&r.jsx("div",{className:"text-sm",style:{color:k.textSecondaryColor},children:"Connection issue. Please try again."}),r.jsx("div",{ref:jt})]}),r.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{type:"text",value:V,onChange:n=>se(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(K){n.preventDefault();return}_t(V)}},placeholder:S,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:k.backgroundColor||"#ffffff",color:k.textColor,fontSize:he.sm}}),r.jsx("button",{onClick:()=>{if(K){mn();return}_t(V)},disabled:!K&&!V.trim(),className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50",style:{backgroundColor:K?"#dc2626":k.primaryColor,color:"#ffffff"},children:K?r.jsx(kn,{size:18}):r.jsx(ar,{size:18})})]})}),r.jsxs("div",{className:"space-y-2 text-center",children:[r.jsxs("p",{style:{color:k.textSecondaryColor,fontSize:he.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),r.jsx("p",{style:{color:k.textSecondaryColor,fontSize:he.xs,lineHeight:1.5},children:pn})]})]})})}):ue?r.jsx("div",{className:"admesh-component","data-admesh-theme":O,children:r.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...I?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...an,width:Qt(d)??$n.width,height:Qt(m)??$n.height},backgroundColor:I?gn:k.backgroundColor,zIndex:9999,fontSize:he.base,borderRadius:I?"20px":"16px",border:I?`1px solid ${Un}`:"1px solid transparent",boxShadow:I?Hn:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[r.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between p-4 border-b",style:{position:"sticky",top:0,zIndex:10,borderColor:I?mt:"transparent",background:I?xn:k.backgroundColor,padding:I?"18px 20px":"16px"},children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{style:{width:I?40:32,height:I?40:32,borderRadius:I?"14px":"10px",background:J(ae,.08),color:ot,display:"flex",alignItems:"center",justifyContent:"center",fontSize:I?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:c?r.jsx("img",{src:c,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||b&&I)&&r.jsxs("div",{children:[u&&r.jsx("div",{className:"font-medium",style:{color:k.textColor,fontSize:I?"20px":he.base,fontWeight:700,letterSpacing:I?"-0.02em":0},children:i}),b&&I&&r.jsx("div",{style:{color:bn,fontSize:"12px",marginTop:"2px"},children:Bn})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[!v&&r.jsx("button",{onClick:Ir,className:"transition-colors",title:I?"Minimize":"Expand",style:{width:I?36:28,height:I?36:28,borderRadius:I?"12px":"10px",border:`1px solid ${I?mt:"transparent"}`,background:I?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:I?r.jsx(Bo,{size:16,style:{color:k.textSecondaryColor}}):r.jsx(Fo,{size:16,style:{color:k.textSecondaryColor}})}),r.jsx("button",{onClick:Tr,className:"transition-colors",style:{width:I?36:28,height:I?36:28,borderRadius:I?"12px":"10px",border:`1px solid ${I?mt:"transparent"}`,background:I?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx(kn,{size:16,style:{color:k.textSecondaryColor}})})]})]}),r.jsxs("div",{ref:At,className:"flex-1 min-h-0 overflow-y-auto p-4",style:{flex:"1 1 0%",minHeight:0,overflowY:"auto",padding:I?"20px":"16px"},children:[Gn("legacy"),q&&pe.length===0&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",children:r.jsx("p",{style:{color:k.textColor,margin:0,fontSize:he.sm},children:A})})}),pe.map(n=>{const f=n.role==="user"&&n.id===Mt.current;return r.jsxs("div",{ref:f?Ct:void 0,className:"mb-3",children:[r.jsx("div",{className:n.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:n.role==="user"?Wr:"transparent",color:n.role==="user"?"#ffffff":k.textColor,border:"none",borderRadius:n.role==="user"?I?"14px":"12px":0,padding:n.role==="user"?I?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{fontSize:`calc(${he.sm} * 1.3)`,lineHeight:1.65},children:r.jsx(Cn,{content:n.content,theme:k,fontSize:`calc(${he.sm} * 1.3)`})}),hn(n,{accentColor:k.primaryColor,metaColor:k.textSecondaryColor})]}):K&&n.id===be.current?Vt({compact:!0,accentColor:k.primaryColor,metaColor:k.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,fontSize:he.sm,lineHeight:"1.4"},children:n.content})}),n.role==="assistant"&&!tt.has(n.id)&&r.jsx(Xt,{messageId:n.id,query:n.userQuery,onFollowupDetected:nn,onRecommendationsShown:(E,D)=>{tn(E,D,n.userQuery)},onError:E=>{console.error("[AdMeshIntentAssistant] Recommendations error:",E)}}),n.role==="assistant"&&tt.has(n.id)&&n.initialRecommendation&&!K&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:nn,onRecommendationsShown:(E,D)=>{tn(E,D,n.userQuery)},onError:E=>{console.error("[AdMeshIntentAssistant] Recommendations error:",E)}})]})]},n.id)}),K&&!pe.some(n=>n.role==="assistant"&&n.id===be.current&&!n.content.trim())&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:Vt({compact:!0,accentColor:k.primaryColor,metaColor:k.textSecondaryColor,includeSteps:!1})})}),ye&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:k.textSecondaryColor},children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{style:{fontSize:he.xs},children:"โš ๏ธ"}),r.jsx("span",{style:{fontSize:he.sm},children:"Connection issue. Please try again."})]})})}),r.jsx("div",{ref:jt})]}),pe.length===0&&Yt&&r.jsx("div",{className:"px-4 pb-2",children:yn("legacy")}),qe.length>0&&pe.length===0&&!Yt&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:qe.slice(0,N).map(n=>r.jsxs("button",{ref:en(n.id),onClick:()=>sn(n),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:k.surfaceColor||"#f8fafc",color:k.textColor||"#1e293b",border:`1px solid ${k.borderColor||"#e2e8f0"}`,fontSize:he.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[r.jsx("span",{className:"leading-tight",children:n.text}),L&&n.is_sponsored&&r.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:k.backgroundColor||"#ffffff",color:k.textSecondaryColor||"#64748b"},children:"Ad"})]},n.id))})}),_e&&!ve&&on.length===0&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:r.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:k.surfaceColor,borderColor:k.borderColor,color:k.textSecondaryColor},children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{style:{fontSize:he.sm},children:"Intent analysis failed"}),r.jsx("button",{onClick:ze,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:k.primaryColor,color:"#ffffff"},children:"Retry"})]}),r.jsx("span",{style:{fontSize:he.xs},children:_e})]})})}),r.jsxs("div",{className:"p-3 border-t",style:{borderColor:I?mt:"transparent",padding:I?"18px 20px":void 0,background:I?xn:void 0},children:[r.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${mt}`,borderRadius:I?"16px":"12px",background:On,boxShadow:I?Vn:"none",padding:I?"8px 8px 8px 14px":void 0},children:[r.jsx("input",{type:"text",value:V,onChange:n=>se(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(K){n.preventDefault();return}_t(V)}},placeholder:S,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:k.textColor,fontSize:I?"15px":he.sm,"--tw-ring-color":k.primaryColor}}),r.jsx("button",{onClick:()=>{if(K){mn();return}_t(V)},disabled:!K&&!V.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:K?"#dc2626":k.primaryColor,color:"#ffffff",borderRadius:I?"12px":"10px",width:I?"46px":void 0,height:I?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:I?`0 10px 20px ${J(ae,.18)}`:"none"},children:K?r.jsx(kn,{size:14}):r.jsx(ar,{size:14})})]}),Yn("legacy")]})]})}):r.jsx("div",{className:"admesh-component","data-admesh-theme":O,children:r.jsx("button",{onClick:Dn,className:"flex items-center gap-2 px-4 py-3 rounded-full shadow-lg transition-all duration-200 hover:scale-105 active:scale-95",style:{position:"fixed",...an,backgroundColor:k.primaryColor,color:"#ffffff",zIndex:9999,fontSize:he.base,...o},children:r.jsx("span",{className:"font-medium",children:s})})})},ln="admesh:streamingStart",cn="admesh:streamingComplete";function is(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(ln,{detail:o});window.dispatchEvent(s),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function as(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(cn,{detail:s});window.dispatchEvent(i),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function ls(t,e,o){const s=i=>{const c=i;c.detail.messageId===t&&c.detail.sessionId===e&&(a.log("[StreamingEvents] ๐Ÿ“จ Received streamingStart event"),o(c.detail))};return window.addEventListener(ln,s),()=>{window.removeEventListener(ln,s)}}function Rr(t,e,o){a.log("[StreamingEvents] ๐Ÿ‘‚ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const c=i;a.log("[StreamingEvents] ๐Ÿ“จ Received streamingComplete event (checking match)",{receivedMessageId:c.detail.messageId,receivedSessionId:c.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:c.detail.messageId===t,sessionIdMatch:c.detail.sessionId===e}),c.detail.messageId===t&&c.detail.sessionId===e?(a.log("[StreamingEvents] โœ… Event matched! Calling callback"),o(c.detail)):a.log("[StreamingEvents] โš ๏ธ Event did not match - ignoring")};return window.addEventListener(cn,s),()=>{a.log("[StreamingEvents] ๐Ÿงน Removing streamingComplete listener"),window.removeEventListener(cn,s)}}const dn=()=>{const t=new Set,e=new Map,o=c=>{const u=e.get(c);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(c))};return{startTracking:({exposureUrl:c,recommendationId:u,linkElement:b,sessionId:h,logPrefix:_="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!c||!b){_&&a.warn(`${_} โš ๏ธ Missing exposure tracking data`);return}const d=`${h||"anonymous"}::${u||c}`;if(t.has(d)||e.has(d))return;const m={observer:void 0,timeoutId:null,viewableStart:null},M=()=>{o(d),t.add(d),fetch(c,{method:"GET",keepalive:!0}).then(()=>{_&&a.log(`${_} โœ… Exposure pixel fired`)}).catch(()=>{_&&a.warn(`${_} โš ๏ธ Failed to fire exposure pixel`),t.delete(d)})},x=new IntersectionObserver(w=>{w.forEach(g=>{g.intersectionRatio>=.5?m.viewableStart===null&&(m.viewableStart=performance.now(),m.timeoutId=setTimeout(M,1e3)):(m.viewableStart=null,m.timeoutId&&(clearTimeout(m.timeoutId),m.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});m.observer=x,x.observe(b),e.set(d,m)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},cs=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:c=[],onLinksFound:u,onNoLinksFound:b,children:h})=>{const[_,d]=l.useState(!1),[m,M]=l.useState(!0),[x,w]=l.useState(!1),g=l.useRef(dn()),p=l.useRef(u),y=l.useRef(b),j=l.useRef(t),R=l.useRef(s),q=l.useRef(o),A=l.useRef(i);l.useEffect(()=>{p.current=u,y.current=b,j.current=t,R.current=s,q.current=o,A.current=i},[u,b,t,s,o,i]),l.useEffect(()=>()=>{g.current.cleanup()},[]);const S=l.useCallback(({exposureUrl:W,recommendationId:N,linkElement:z})=>{g.current.startTracking({exposureUrl:W,recommendationId:N,linkElement:z,sessionId:q.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),L=l.useCallback(()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿ” Performing final link detection...");try{const W=document.getElementById(j.current);if(!W){a.warn("[FinalLinkDetectionCheck] โŒ Container not found"),d(!0),b();return}const N=new Tn({autoAddLabels:!0,fireExposurePixels:!0}),z=c.length>0?c:[];a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Using ${z.length} recommendations for link detection`),z.length>0&&process.env.NODE_ENV==="development"&&z.forEach(($,Y)=>{var Z,xe,F,me,ge,de,Q,G,Ne;a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Recommendation ${Y+1} (DEV):`,{recommendation_id:$==null?void 0:$.recommendation_id,click_url:((Z=$==null?void 0:$.tracking)==null?void 0:Z.click_url)||((F=(xe=$==null?void 0:$.recommendation)==null?void 0:xe.creative)==null?void 0:F.landing_page_url),format:(me=$==null?void 0:$.recommendation)==null?void 0:me.format,brand_name:(Q=(de=(ge=$.render)==null?void 0:ge.creative)==null?void 0:de.advertiser)==null?void 0:Q.brand_name,cta_url:(Ne=(G=$.render)==null?void 0:G.creative)==null?void 0:Ne.landing_page_url})});const P=N.scanAndProcessLinks(W,z,({exposureUrl:$,recommendationId:Y,linkElement:Z})=>S({exposureUrl:$,recommendationId:Y,linkElement:Z}));a.log(`[FinalLinkDetectionCheck] ๐Ÿ“Š Final check result: ${P.length} links`),P.length>0?(a.log("[FinalLinkDetectionCheck] โœ… Links detected - canceling fallback (no API call)"),w(!0),p.current(P.length)):(a.log(`[FinalLinkDetectionCheck] โš ๏ธ No links found - rendering fallback (will use ${z.length} previous recommendation(s) if available)`),w(!1),y.current()),d(!0)}catch{a.error("[FinalLinkDetectionCheck] โŒ Error during final check"),d(!0),y.current()}},[S,c]);return l.useEffect(()=>{a.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:c.length});let W=null,N=!1;const z=Rr(e,o,P=>{a.log("[FinalLinkDetectionCheck] ๐ŸŽฏ Received streamingComplete event",{messageId:P.messageId,sessionId:P.sessionId,timestamp:P.timestamp}),N=!0,W&&(clearTimeout(W),W=null),M(!1),setTimeout(()=>{L()},100)});return W=setTimeout(()=>{N||(a.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),M(!1),setTimeout(()=>{L()},100))},5e3),()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿงน Cleaning up listener"),W&&clearTimeout(W),z()}},[e,o]),m?r.jsx(r.Fragment,{}):_?x?(a.log("[FinalLinkDetectionCheck] ๐Ÿšซ Links found - NOT rendering fallback"),r.jsx(r.Fragment,{})):(a.log("[FinalLinkDetectionCheck] โœ… No links found - rendering fallback"),r.jsx(r.Fragment,{children:h})):r.jsx(r.Fragment,{})},ds=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:c,className:u,query:b,onFallbackChange:h,onWeaveAttempt:_,onWeaveOutcome:d})=>{var $,Y;const{sessionId:m,sdk:M,language:x,location:w,userId:g,model:p,messages:y}=Wt(),j=l.useRef(null),R=`weave-ad-container-${t}`,q=l.useRef(dn()),A=l.useRef(!1),S=l.useRef(null),[L,W]=l.useState([]),N=l.useRef([]);l.useEffect(()=>(S.current||(S.current=new Tn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{S.current&&(S.current.stopWatching(),S.current.clearCache())}),[]),l.useEffect(()=>()=>{q.current.cleanup()},[]),l.useEffect(()=>{(async()=>{var xe;if(!M||!(b!=null&&b.trim())||!t){a.log("[WeaveAdFormatContainer] โš ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{a.log("[WeaveAdFormatContainer] ๐Ÿ“ค Fetching recommendations from SDK for brand URL matching");const F=await M.fetchPlatformResponse({query:b.trim(),sessionId:m,messageId:t,language:x,location:w,userId:g,model:p,messages:y}),me=(F==null?void 0:F.status)==="generated"?[F]:[];if(W(me),N.current=me,a.log("[WeaveAdFormatContainer] ๐Ÿ“ฅ Got platform response:",{status:F==null?void 0:F.status,recommendationId:F==null?void 0:F.recommendation_id,hasRecommendation:!!(F!=null&&F.recommendation),format:(xe=F==null?void 0:F.recommendation)==null?void 0:xe.format}),F!=null&&F.recommendation){const ge=F.recommendation.creative,de=ge.landing_page_url;a.log("[WeaveAdFormatContainer] ๐ŸŽฏ Found creative in platform response:",{brandName:ge.brand_name,headline:ge.headline,description:ge.description,brandUrl:de})}else a.log("[WeaveAdFormatContainer] โš ๏ธ No recommendation found in platform response")}catch(F){a.warn("[WeaveAdFormatContainer] โš ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",F),W([])}})()},[M,m,t,b]),l.useEffect(()=>{const Z=j.current;if(!Z||!S.current)return;const xe=S.current,F=({exposureUrl:de,recommendationId:Q,linkElement:G})=>{q.current.startTracking({exposureUrl:de,recommendationId:Q,linkElement:G,sessionId:m,logPrefix:"[WeaveAdFormatContainer]"})},ge=setTimeout(()=>{a.log("[WeaveAdFormatContainer] ๐Ÿ” Weave injection attempt started"),_==null||_(t);const de=N.current.length>0?N.current:[];a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Using ${de.length} recommendations for link detection`);try{const Q=xe.scanAndProcessLinks(Z,de,F);Q.length>0&&!A.current?(A.current=!0,a.log(`[WeaveAdFormatContainer] โœ… Weave injection succeeded: ${Q.length} links detected`),d==null||d(t,!0,`Found ${Q.length} links`),s==null||s(Q.length),h==null||h(!1)):A.current||a.log("[WeaveAdFormatContainer] โš ๏ธ Weave injection: no links found on initial scan")}catch(Q){const G=Q instanceof Error?Q.message:String(Q);a.error(`[WeaveAdFormatContainer] โŒ Weave injection failed: ${G}`),d==null||d(t,!1,G),i==null||i(),h==null||h(!0)}},100);return xe.watchForNewLinks(Z,N.current,F),()=>{clearTimeout(ge),xe.stopWatching()}},[e,m,t,s,h,_,d]);const z=(Y=($=L[0])==null?void 0:$.recommendation)==null?void 0:Y.format,P=z==="weave";return l.useEffect(()=>{b&&P&&a.log(`[WeaveAdFormatContainer] ๐ŸŽฏ Format is "weave" (preferred: ${z}) - skipping fallback recommendations`)},[b,P,z]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:j,id:R,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),b&&!P&&r.jsx(cs,{containerId:R,messageId:t,sessionId:m,sdk:M,query:b,recommendations:L,onLinksFound:Z=>{a.log(`[WeaveAdFormatContainer] โœ… Links found (${Z}) - no fallback needed`),d==null||d(t,!0,`Found ${Z} links in final check`),s==null||s(Z),h==null||h(!1)},onNoLinksFound:()=>{a.log("[WeaveAdFormatContainer] โš ๏ธ No links found - rendering fallback"),a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Passing ${L.length} recommendation(s) to fallback component`),d==null||d(t,!1,"No links detected in final check"),i==null||i(),h==null||h(!0)},children:r.jsx(kr,{format:o,messageId:t,query:b,fallback:!0,onError:c,previousRecommendations:L.length>0?L:void 0})})]})},us=t=>{const{sdk:e,sessionId:o}=Wt(),s=l.useRef(!1),i=l.useRef(0),c=l.useRef(!1),u=l.useRef(!1),b=l.useRef(null),h=l.useRef(dn());l.useEffect(()=>()=>{h.current.cleanup()},[]);const _=l.useCallback(({exposureUrl:y,recommendationId:j,linkElement:R})=>{h.current.startTracking({exposureUrl:y,recommendationId:j,linkElement:R,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),d=l.useRef(Date.now()),m=l.useRef(0),M=l.useRef(null),x=l.useRef([]),w=l.useRef(300),g=l.useCallback(async()=>{var y,j,R,q;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const A=document.getElementById(t.llmOutputContainerId);if(!A)return;const S=(y=e.getWeaveProcessor)==null?void 0:y.call(e);if(!S)return;const L=S.scanAndProcessLinks(A,[],({exposureUrl:N,recommendationId:z,linkElement:P})=>_({exposureUrl:N,recommendationId:z,linkElement:P}));i.current=L.length;const W=L.length>0;if(W&&!c.current)c.current=!0,(j=t.onLinksDetected)==null||j.call(t,L.length),u.current=!0;else if(!W&&c.current)c.current=!1,u.current=!1;else if(!W&&!u.current){b.current&&clearTimeout(b.current),M.current&&clearInterval(M.current),m.current=0,d.current=Date.now();const N=Math.max(100,w.current/3);M.current=setInterval(()=>{var Y;const P=Date.now()-d.current,$=w.current;P>=$?(m.current++,m.current>=2&&(M.current&&(clearInterval(M.current),M.current=null),!c.current&&!u.current&&((Y=t.onNoLinksDetected)==null||Y.call(t),u.current=!0))):m.current=0},N);const z=Math.max(1500,w.current*5);b.current=setTimeout(()=>{var P;M.current&&(clearInterval(M.current),M.current=null),!c.current&&!u.current&&((P=t.onNoLinksDetected)==null||P.call(t),u.current=!0)},z)}else W&&u.current&&!c.current&&(b.current&&(clearTimeout(b.current),b.current=null),c.current=!0,(R=t.onLinksDetected)==null||R.call(t,L.length),u.current=!0)}catch(A){const S=A instanceof Error?A:new Error(String(A));(q=t.onError)==null||q.call(t,S)}finally{s.current=!1}}},[e,o,t,_]),p=l.useCallback(()=>{const y=x.current;if(y.length<2){w.current=300;return}const j=[];for(let A=1;A<y.length;A++)j.push(y[A]-y[A-1]);const R=j.reduce((A,S)=>A+S,0)/j.length,q=Math.max(100,Math.min(R*3,1e3));w.current=q},[]);return l.useEffect(()=>{const y=document.getElementById(t.llmOutputContainerId);if(!y)return;g();const j=new MutationObserver(()=>{const R=Date.now();d.current=R,m.current=0,x.current.push(R),x.current.length>10&&x.current.shift(),p(),g()});return j.observe(y,{childList:!0,subtree:!0,characterData:!1}),()=>{j.disconnect(),b.current&&clearTimeout(b.current),M.current&&clearInterval(M.current)}},[t.llmOutputContainerId,g,p]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:c.current,shouldRenderFallback:!c.current&&u.current,processWeaveFormat:g}},ms="1.0.31";exports.AdMeshBadge=Cr;exports.AdMeshCompactCard=jn;exports.AdMeshContext=En;exports.AdMeshFollowup=vr;exports.AdMeshIntentAssistant=ss;exports.AdMeshLayout=fr;exports.AdMeshLinkTracker=Ar;exports.AdMeshProvider=_r;exports.AdMeshRecommendations=Xt;exports.AdMeshRenderer=wr;exports.AdMeshSDK=Jt;exports.AdMeshTailAd=Co;exports.AdMeshTracker=gr;exports.AdMeshViewabilityTracker=Zt;exports.STREAMING_COMPLETE_EVENT=cn;exports.STREAMING_START_EVENT=ln;exports.VERSION=ms;exports.WeaveAdFormatContainer=ds;exports.WeaveAdFormatProvider=wo;exports.WeaveFallbackRecommendations=kr;exports.WeaveResponseProcessor=Tn;exports.callAnalyzeIntentEndpoint=br;exports.createInlineExposureTracker=dn;exports.dispatchStreamingCompleteEvent=as;exports.dispatchStreamingStartEvent=is;exports.extractHeadingsDirectly=xr;exports.onStreamingComplete=Rr;exports.onStreamingStart=ls;exports.useAdMesh=Wt;exports.useAdMeshContext=Rn;exports.useAdMeshStyles=jr;exports.useViewabilityTracker=hr;exports.useWeaveAdFormat=us;exports.useWeaveAdFormatContext=vo;
1114
+ `;let dr=!1;const jr=()=>{l.useEffect(()=>{if(!dr){try{Qo();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Xo,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),dr=!0}catch{a.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])};function Jo(t){const e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;const o=Math.floor(e/60),s=e%60;return s>0?`${o}m ${s}s`:`${o}m`}function Zo(t){return Jo(t/1e3)}const Cn=({content:t,theme:e,fontSize:o})=>{const s=m=>m.split(/(\*\*[^*]+\*\*|\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g).map((f,p)=>{if(f.startsWith("**")&&f.endsWith("**")&&f.length>4)return r.jsx("strong",{style:{fontWeight:"600",color:e.textColor},children:f.slice(2,-2)},p);const E=f.match(/^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/);return E?r.jsx("a",{href:E[2],target:"_blank",rel:"noopener noreferrer",style:{color:e.primaryColor,textDecoration:"underline",textUnderlineOffset:"2px"},children:E[1]},p):r.jsx(l.Fragment,{children:f},p)}),i=m=>m.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(f=>f.trim()).filter((f,p,E)=>f.length>0||p<E.length-1),c=m=>{const b=i(m);return b.length>1&&b.every(f=>/^:?-{3,}:?$/.test(f))},u=m=>{const b=m.indexOf("|");if(b<=0)return{heading:null,headerLine:m};const f=m.slice(0,b).trim();return!f||/^[-|:\s]+$/.test(f)?{heading:null,headerLine:m}:{heading:f,headerLine:m.slice(b).trim()}},y=(m,b)=>{const f=i(m).length,p=i(b).length;return f<=1||f===p?b:`| ${Array.from({length:f},()=>"---").join(" | ")} |`},g=m=>{if(m.length<2||!m[0].includes("|"))return{heading:null,lines:m};const{heading:b,headerLine:f}=u(m[0]),p=f.startsWith("|")?f:`| ${f}`,E=y(p,m[1]);return{heading:b,lines:[p,E,...m.slice(2)]}},v=m=>{if(m.length<2||!m[0].includes("|"))return!1;const{lines:b}=g(m);return c(b[1])&&i(b[0]).length>=2},d=m=>{if(!m.includes("|"))return[m];let b=m.trim();const f=[],p=b.indexOf("|");if(p>0){const E=b.slice(0,p).trim();E&&!/^[-|:\s]+$/.test(E)&&(f.push(E),b=b.slice(p).trim())}return b=b.replace(/\|\s*(\|(?:\s*:?-{3,}:?\s*\|)+)/g,(E,I)=>`
1115
+ ${I}`),b=b.replace(/\|\s*\|\s*(?=[A-Za-z0-9*])/g,`|
1116
+ | `),b=b.replace(/\|\s+(?=\|(?!\s*:?-{3,}:?\s*\|)[^|\n])/g,`|
1117
+ `),f.push(...b.split(`
1118
+ `).map(E=>E.trim()).filter(Boolean)),f},h=m=>{const b=m.split(`
1119
+ `),f=[];for(const p of b){if(!p.includes("|")){f.push(p);continue}f.push(...d(p))}return f.join(`
1120
+ `)},C=(m=>{const b=h(m).split(`
1121
+ `),f=[];let p=0;for(;p<b.length;){const E=b[p],I=b[p+1]||"";if(E.includes("|")&&c(I)){f.length>0&&f[f.length-1].trim()&&f.push("");const{heading:G,headerLine:k}=u(E);for(G&&f.push(G),f.push(k,y(k,I)),p+=2;p<b.length&&b[p].includes("|")&&b[p].trim();)f.push(b[p]),p+=1;p<b.length&&b[p].trim()&&f.push("");continue}f.push(E),p+=1}return f.join(`
1122
+ `)})(t).split(/\n\s*\n/).map(m=>m.trim()).filter(Boolean);return r.jsx("div",{style:{margin:0,color:e.textColor,fontSize:o},children:C.map((m,b)=>{const f=m.split(`
1123
+ `).map(k=>k.trim()).filter(Boolean),p=f.every(k=>/^[-*]\s+/.test(k)),E=f.every(k=>/^\d+\.\s+/.test(k)),I=f.length===1&&/^#{1,3}\s+/.test(f[0]),G=v(f);if(I){const k=f[0].replace(/^#{1,3}\s+/,"");return r.jsx("h3",{style:{marginTop:b===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(k)},b)}if(G){const{heading:k,lines:S}=g(f),L=i(S[0]),N=S.slice(2).map(i).filter(B=>B.length===L.length);return r.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[k?r.jsx("p",{style:{marginTop:b===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(k)}):null,r.jsx("div",{style:{border:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,borderRadius:8,overflowX:"auto"},children:r.jsxs("table",{style:{width:"100%",minWidth:L.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[r.jsx("thead",{children:r.jsx("tr",{children:L.map((B,$)=>r.jsx("th",{style:{textAlign:"left",padding:"9px 10px",fontWeight:600,background:e.surfaceColor||"rgba(148, 163, 184, 0.12)",borderBottom:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,whiteSpace:"normal"},children:s(B)},$))})}),r.jsx("tbody",{children:N.map((B,$)=>r.jsx("tr",{children:B.map((z,D)=>r.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:$===N.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(z)},D))},$))})]})})]},b)}if(p||E){const k=E?"ol":"ul";return r.jsx(k,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:f.map((S,L)=>r.jsx("li",{style:{marginBottom:"0.45rem"},children:s(S.replace(/^([-*]|\d+\.)\s+/,""))},L))},b)}return r.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:f.map((k,S)=>r.jsxs(l.Fragment,{children:[S>0&&r.jsx("br",{}),s(k)]},S))},b)})})};function Qt(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function Nt(t){return t.replace(/\s+/g," ").trim()}function es(t,e){const o=t.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),s=e.filter(u=>!(u!=null&&u.is_sponsored)).slice(0,3),i=e.find(u=>u==null?void 0:u.is_sponsored);if(!i)return s.length?s:o;const c=s.length?s:o;return[i,...c].slice(0,4)}function ts(t,e,o,s){const i=new Set,c=[],u=(C,m="information")=>{const b=Nt(C);if(!b)return;const f=b.toLowerCase();i.has(f)||(i.add(f),c.push({id:`followup_${c.length}_${f.replace(/[^a-z0-9]+/g,"_")}`,text:b,type:m,is_sponsored:!1}))},y=new Set,g=C=>{const m=Nt(C||"");if(!m)return;const b=m.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();b&&y.add(b)};(s||[]).forEach(C=>g(C==null?void 0:C.title)),(o||[]).forEach(C=>g(C==null?void 0:C.title)),e.split(/\n+/).map(C=>Nt(C.replace(/^[-*]\s+/,""))).filter(Boolean).filter(C=>C.length>=24&&C.length<=90).forEach(C=>{y.size>=6||g(C)});const d=Nt(t.replace(/[?.!]+$/g,"")),h=Array.from(y).slice(0,3);return[h[0]?`Tell me more about ${h[0]}`:"",h[1]?`Show me examples related to ${h[1]}`:"",h[2]?`Compare the main options for ${h[2]}`:"","Break this down more simply",`What should I look at next about ${d}`,"Give me the practical takeaway here"].forEach((C,m)=>{c.length>=3||u(C,m===0?"comparison":"information")}),c.slice(0,3)}function ns(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function Er(t){const e=t==null?void 0:t.trim();if(!e||/%%[^%]+%%/.test(e))return!1;try{const o=new URL(e);return!!(o.protocol&&o.hostname)}catch{return!1}}function ur(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Er(e))return e}catch{return}}function mr(t){if(typeof window>"u")return{page_url:void 0,page_path:void 0,article_slug:void 0,page_title:void 0,referrer:void 0,device_type:"unknown"};const e=ur()||(Er(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=ur()?window.location.pathname||"/":void 0}const s=(o||"").split("/").filter(Boolean);return{page_url:e,page_path:o,article_slug:s[s.length-1],page_title:document.title||void 0,referrer:document.referrer||void 0,device_type:ns()}}function rs(t){var s,i;const e=(i=(s=t==null?void 0:t.recommendation)==null?void 0:s.creative)==null?void 0:i.follow_up_suggestion,o=t==null?void 0:t.recommendation_id;return!e||!o?null:{id:o,text:Nt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Mn(t){return[...t].sort((e,o)=>{const s=!!e.is_sponsored,i=!!o.is_sponsored;return s===i?0:s?-1:1})}const os={mode:"light",primaryColor:"#3b82f6",secondaryColor:"#64748b",backgroundColor:"#ffffff",surfaceColor:"#f8fafc",borderColor:"#e2e8f0",textColor:"#1e293b",textSecondaryColor:"#64748b",borderRadius:"0.5rem",spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},shadows:{small:"0 1px 2px 0 rgb(0 0 0 / 0.05)",medium:"0 4px 6px -1px rgb(0 0 0 / 0.1)",large:"0 10px 15px -3px rgb(0 0 0 / 0.1)"}},ss={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},is={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},as=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:c,showHeaderTitle:u=!0,showSubtitle:y=!0,layout:g="floating",surface:v="page",panelWidth:d,panelHeight:h,analyticsPageUrl:w,fontScale:C=1,position:m="bottom-right",size:b="md",defaultOpen:f,open:p,onOpenChange:E,autoOpen:I=!1,showWelcomeMessage:G=!1,welcomeMessage:k="Hi, Iโ€™m Ava. Iโ€™ll help you find the best options.",placeholder:S="Ask me anything about products...",adsEnabled:L=!0,suggestions:N,maxSuggestions:B=6,suggestionStyle:$="carousel",onlyShowWhenSponsored:z=!1,variant:D="default",queryHandler:Q,suggestionsLoader:J,disclaimerText:ge,poweredByLabel:V="Powered by AdMesh",subtitle:ee="Publisher Assistant",onOpen:me,onClose:xe})=>{const{sdk:q,sessionId:oe,theme:ve,apiKey:Ne,userId:Pe}=Ht(),{suggestions:be,isAnalyzingIntent:we,intentError:Se,retryIntentAnalysis:_e,activeDelegationSession:Fe,hasActiveDelegationSession:Ee,stopDelegationSession:rt,refreshDelegationActivity:F}=Rn();jr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:q,sessionId:oe,hasContextTheme:!!ve});const _=t||ve||os,H=(_==null?void 0:_.mode)||"light",A=v==="ad-slot",[ie,ke]=l.useState(f||I),T=p!==void 0,se=T?p:ie,[j,ce]=l.useState(""),[re,Y]=l.useState([]),[K,ae]=l.useState(!1),[Be,Te]=l.useState(null),[M,Ce]=l.useState(!1),[Ie,ot]=l.useState(new Set),[yt,et]=l.useState(N||be||[]),[jt,ut]=l.useState(0),[Et,_t]=l.useState(0),[mt,Rt]=l.useState({}),st=l.useRef(null),Ve=l.useRef(!1),ze=l.useRef(null),O=l.useRef(new Map),fe=l.useRef([]),Ue=l.useRef(null),Ke=l.useRef(null),tt=l.useRef(null),pt=l.useRef(!1),wt=l.useRef(!1),Tt=l.useRef(null),It=l.useRef(null),Wt=l.useRef(null),U=l.useRef(null),ye=l.useRef(null),[de,Dt]=l.useState(!1),[Je,vt]=l.useState(!1),kt=!!(Ne!=null&&Ne.toLowerCase().startsWith("pub_")),$e=Ee()&&(Fe==null?void 0:Fe.session_id)===oe?Fe:null,ht=l.useRef(new Set),it=l.useRef(new Set),qt=l.useRef(!1),Ot=A&&(M||re.length>0||K),ft=Qt(d)??"100%",Bt=Qt(h)??"100%",en=l.useCallback(n=>x=>{x?O.current.set(n,x):O.current.delete(n)},[]),Me=l.useCallback(async(n,x={})=>{if(!(!q||!oe))try{await q.trackPublisherAssistantEvent({event_name:n,timestamp:new Date().toISOString(),session_id:oe,...mr(w),...x})}catch(R){console.warn(`[AdMeshIntentAssistant] Failed to track ${n}`,R)}},[w,q,oe]),tn=l.useCallback((n,x,R)=>{var te,je;const P=x==null?void 0:x.recommendation_id;if(!P)return;const W=`${n}:${P}`;it.current.has(W)||(it.current.add(W),Me("recommendation_shown",{message_id:n,query:R,recommendation_id:P,brand_name:(je=(te=x.recommendation)==null?void 0:te.creative)==null?void 0:je.brand_name,is_sponsored:!0}))},[Me]),un=l.useCallback((n,x,R,P,W,te)=>{const je=Array.isArray(te)&&te.length?te.map((Re,Ae)=>{const Le=Nt(Re.text||"");return Le?{id:`followup_llm_${Ae}_${Le.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:Le,type:Re.type||"information",is_sponsored:!1}:null}).filter(Re=>!!Re).slice(0,3):ts(n,x,R,P),He=rs(W),qe=He?[He,...je.slice(0,2)]:je.slice(0,3);qe.length&&et(Mn(qe))},[]),nn=l.useCallback((n,x)=>{const R=Nt(n.query||n.label||"");if(!R||!x)return;const P={id:x,text:R,type:"action",is_sponsored:!0,recommendation:{recommendation_id:x,recommendation:{creative:{follow_up_suggestion:R}},tracking:{followup_engagement_url:n.engagement_url,followup_exposure_url:n.exposure_url}}};et(W=>{const te=W.filter(je=>!je.is_sponsored).slice(0,3);return Mn([P,...te].slice(0,4))})},[]),In=l.useCallback(()=>{const n=Ue.current,x=Ke.current;if(!n||!x)return!1;const R=n.getBoundingClientRect(),P=x.getBoundingClientRect(),W=Math.max(0,n.scrollTop+P.top-R.top);return n.scrollTop=W,!0},[]);l.useLayoutEffect(()=>{var n;if(pt.current){In()&&(pt.current=!1);return}wt.current||(n=It.current)==null||n.scrollIntoView({behavior:"smooth"})},[re,In]),l.useLayoutEffect(()=>{if(!A)return;const n=Tt.current;if(!n)return;const x=n.closest(".admesh-publisher-assistant-reactMount"),R=Bt;[n,x].forEach(W=>{W&&(W.style.width=ft,W.style.maxWidth=ft,W.style.height=R,W.style.maxHeight=R,W.style.overflow="hidden",W.style.boxSizing="border-box",W.dataset.admeshAdSlotExpanded=Ot?"true":"false")});const P=x==null?void 0:x.parentElement;P&&P!==document.body&&P!==document.documentElement&&(P.style.width=ft,P.style.maxWidth=ft,P.style.height=R,P.style.maxHeight=R,P.style.overflow="hidden",P.style.boxSizing="border-box")},[Bt,ft,A,Ot]),l.useEffect(()=>{if(N&&N.length){et(N);return}be&&be.length&&et(n=>es(n,be))},[N,be]),l.useEffect(()=>{if(D!=="default"||!J)return;let n=!1;return J().then(x=>{!n&&Array.isArray(x)&&x.length&&et(x)}).catch(x=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",x)}),()=>{n=!0}},[J,D]),l.useEffect(()=>{if(!K){_t(0),st.current=null;return}st.current==null&&(st.current=typeof performance<"u"?performance.now():Date.now());const n=()=>{const R=st.current;if(R==null)return;const P=typeof performance<"u"?performance.now():Date.now();_t(Math.floor((P-R)/1e3))};n();const x=window.setInterval(n,1e3);return()=>window.clearInterval(x)},[K]),l.useEffect(()=>{if(!K||D!=="default"){ut(0);return}const n=window.setInterval(()=>{ut(x=>Math.min(x+1,7))},3e3);return()=>window.clearInterval(n)},[K,D]),l.useEffect(()=>{qt.current||!q||!oe||(qt.current=!0,Me("assistant_loaded",{metadata:{layout:g,surface:v,variant:D,default_open:f||I}}))},[I,f,g,q,oe,v,Me,D]);const St=l.useCallback(n=>{T?E==null||E(n):ke(n),n?(Me("assistant_opened",{metadata:{layout:g,surface:v,variant:D,expanded:M}}),me==null||me()):xe==null||xe()},[T,M,g,E,me,xe,v,Me,D]),Dn=l.useCallback(()=>{St(!0)},[St]),Tr=l.useCallback(()=>{St(!1)},[St]),Ir=l.useCallback(()=>{Ce(n=>!n)},[]),Pn=l.useCallback(async(n,x,R,P,W,te,je)=>{var He,qe,Re;if(!q)return console.warn("[AdMeshIntentAssistant] SDK not available - using fallback response"),{text:"I'm a demo assistant. The SDK is not properly configured, but I can still help with suggestions! Try clicking on one of the suggested questions above."};try{$e&&await F("turn_started",{source:"publisher_assistant",recommendation_id:$e.recommendation_id}).catch(ue=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",ue)});const Ae=await fetch(`${q.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:te,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${Ne}`},body:JSON.stringify({message:n,session_id:oe||"default-session",message_id:x,user_id:Pe,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:mr(w),conversation_history:je,sponsored_recommendation:W!=null&&W.recommendation_id?{recommendation_id:W.recommendation_id,brand_name:(qe=(He=W.recommendation)==null?void 0:He.creative)==null?void 0:qe.brand_name}:void 0,active_delegation_session:$e?{delegation_session_id:$e.delegation_session_id,recommendation_id:$e.recommendation_id,session_id:$e.session_id,brand_name:$e.brand_name,mcp_endpoint:$e.mcp_endpoint,status:$e.status}:void 0}})});if(!Ae.ok)throw new Error(`API request failed: ${Ae.status} ${Ae.statusText}`);const Le=(Re=Ae.body)==null?void 0:Re.getReader(),Pt=new TextDecoder;if(!Le)throw new Error("Response body is not readable");let Ye="",Ze,$t,bt,X,ne;return await(async()=>{try{for(;;){const{done:ue,value:nt}=await Le.read();if(ue)break;const Xe=Pt.decode(nt,{stream:!0}).split(`
1124
+ `);for(const zt of Xe)if(zt.startsWith("data: ")){const _n=zt.slice(6);if(_n.trim()==="[DONE]")return $e&&F("turn_completed",{source:"publisher_assistant",recommendation_id:$e.recommendation_id}).catch(De=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",De)}),{text:Ye,source_links:Ze,related_items:$t,followup_suggestions:bt,used_capability:X,response_time_ms:ne};try{const De=JSON.parse(_n);switch(De.type){case"content":{const Qn=De.content||"";Ye+=Qn,R==null||R(Qn);break}case"final":{Ye=De.reply||Ye,Ze=Array.isArray(De.source_links)?De.source_links:void 0,$t=Array.isArray(De.related_items)?De.related_items:void 0,bt=Array.isArray(De.followup_suggestions)?De.followup_suggestions:void 0,X=typeof De.used_capability=="string"?De.used_capability:X,ne=typeof De.response_time_ms=="number"?De.response_time_ms:ne;break}case"followup_suggestions":{bt=Array.isArray(De.followup_suggestions)?De.followup_suggestions:bt;break}case"error":throw new Error(De.message||"Unknown streaming error");case"session_start":P==null||P(),console.log("Session started:",De.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",_n);continue}}}}catch(ue){if(te!=null&&te.aborted)return{text:Ye,source_links:Ze,related_items:$t,followup_suggestions:bt,used_capability:X,response_time_ms:ne,error:"aborted"};throw console.error("Stream processing error:",ue),ue}finally{Le.releaseLock()}return{text:Ye,source_links:Ze,related_items:$t,followup_suggestions:bt,used_capability:X,response_time_ms:ne}})()}catch(Ae){return te!=null&&te.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",Ae),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:Ae instanceof Error?Ae.message:"request_failed"})}},[q,oe,Ne,Pe,$e,F]),mn=l.useCallback(()=>{const n=U.current;if(!n||n.signal.aborted)return;n.abort(),ae(!1),ze.current=null,Ve.current=!1;const x=ye.current;x&&Y(R=>R.map(P=>P.id===x&&!P.content.trim()?{...P,content:"Generation stopped."}:P))},[]),At=l.useCallback(async n=>{var Re,Ae,Le,Pt,Ye,Ze,$t,bt;if(!n.trim()||K)return;const x=typeof performance<"u"?performance.now():Date.now(),R=n.trim(),P=Date.now().toString(),W=new AbortController,te=ze.current,je=(te==null?void 0:te.recommendation)||null,He=re.filter(X=>(X.role==="user"||X.role==="assistant")&&X.content.trim()).slice(-6).map(X=>({role:X.role,content:X.content.trim().slice(0,1200)}));U.current=W,ye.current=null,tt.current=P,pt.current=!0,wt.current=!0,ze.current=null,et(X=>X.some(ne=>ne.is_sponsored)?X.filter(ne=>!ne.is_sponsored):X),Te(null);const qe={id:P,role:"user",content:R,timestamp:new Date};if(Me("query_submitted",{message_id:P,query:R}),Y(X=>[...X,qe]),ce(""),ae(!0),D==="default"&&Q){try{const X=(Date.now()+1).toString(),ne={id:X,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:null};Ve.current&&(ot(nt=>new Set([...nt,X])),Ve.current=!1),Y(nt=>[...nt,ne]),ye.current=X;const We=await Q(R,{sponsoredSuggestion:te});if(W.signal.aborted){ze.current=null;return}const ue=We.recommendation||je||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:n,hasResponseRecommendation:!!We.recommendation,hasSponsoredSuggestionRecommendation:!!je,finalRecommendationId:ue==null?void 0:ue.recommendation_id}),Y(nt=>nt.map(Qe=>Qe.id===X?{...Qe,content:We.answer,sourceLinks:We.source_links,relatedItems:We.related_items,initialRecommendation:ue,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-x}:Qe)),un(R,We.answer,We.source_links,We.related_items,We.recommendation||null,We.followup_suggestions),Me("answer_completed",{message_id:X,query:R,recommendation_id:ue==null?void 0:ue.recommendation_id,brand_name:(Ae=(Re=ue==null?void 0:ue.recommendation)==null?void 0:Re.creative)==null?void 0:Ae.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:"completed",metadata:{variant:D,source:"query_handler"}}),ze.current=null}catch(X){console.error("Error sending message:",X);const ne=X instanceof Error?X.message:"Unknown error occurred";Te(ne);const We={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Y(ue=>[...ue,We]),Me("answer_failed",{query:R,status:ne,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,metadata:{variant:D,source:"query_handler"}}),ze.current=null}finally{U.current===W&&(U.current=null,ye.current=null,ae(!1))}return}if(!q){setTimeout(()=>{if(W.signal.aborted){U.current===W&&(U.current=null,ye.current=null);return}const X={id:(Date.now()+1).toString(),role:"assistant",content:"I'm a demo assistant. The SDK is not properly configured, but I can still help! Try clicking on the suggested questions above, or check your AdMesh API key configuration.",timestamp:new Date,recommendations:[],userQuery:n};Y(ne=>[...ne,X]),U.current===W&&(U.current=null,ye.current=null,ae(!1))},1e3);return}try{const X=(Date.now()+1).toString(),ne=je,We={id:X,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:n,initialRecommendation:ne};Ve.current&&(ot(Qe=>new Set([...Qe,X])),Ve.current=!1),Y(Qe=>[...Qe,We]),ye.current=X;const ue=await Pn(R,P,Qe=>{Y(Xe=>Xe.map(zt=>zt.id===X?{...zt,content:zt.content+Qe}:zt))},()=>{ae(!0),ut(0)},ne,W.signal,He);if(W.signal.aborted){ue.text.trim()||Y(Qe=>Qe.map(Xe=>Xe.id===X&&!Xe.content.trim()?{...Xe,content:"Generation stopped."}:Xe)),Me("answer_failed",{message_id:X,query:R,recommendation_id:ne==null?void 0:ne.recommendation_id,brand_name:(Pt=(Le=ne==null?void 0:ne.recommendation)==null?void 0:Le.creative)==null?void 0:Pt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:"aborted",metadata:{variant:D,source:"api_chat_assistant"}}),ze.current=null;return}const nt=typeof ue.response_time_ms=="number"?ue.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-x;Y(Qe=>Qe.map(Xe=>Xe.id===X?{...Xe,content:ue.text,sourceLinks:ue.source_links,relatedItems:ue.related_items,initialRecommendation:Xe.initialRecommendation||ne,responseTimeMs:nt}:Xe)),un(R,ue.text,ue.source_links,ue.related_items,null,ue.followup_suggestions),ue.error?Me("answer_failed",{message_id:X,query:R,recommendation_id:ne==null?void 0:ne.recommendation_id,brand_name:(Ze=(Ye=ne==null?void 0:ne.recommendation)==null?void 0:Ye.creative)==null?void 0:Ze.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:ue.error,metadata:{variant:D,source:"api_chat_assistant"}}):Me("answer_completed",{message_id:X,query:R,recommendation_id:ne==null?void 0:ne.recommendation_id,brand_name:(bt=($t=ne==null?void 0:ne.recommendation)==null?void 0:$t.creative)==null?void 0:bt.brand_name,used_capability:ue.used_capability,latency_ms:nt,status:"completed",metadata:{variant:D,source:"api_chat_assistant",response_time_ms:nt}}),ze.current=null}catch(X){console.error("Error sending message:",X);const ne=X instanceof Error?X.message:"Unknown error occurred";Te(ne);const We={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Y(ue=>[...ue,We]),Me("answer_failed",{query:R,latency_ms:(typeof performance<"u"?performance.now():Date.now())-x,status:ne,metadata:{variant:D,source:"api_chat_assistant"}}),ze.current=null}finally{U.current===W&&(U.current=null,ye.current=null,ae(!1))}},[K,Pn,Q,un,q,Me,D]),Ct=yt,rn=l.useMemo(()=>Ct.some(n=>n==null?void 0:n.is_sponsored),[Ct]),on=l.useMemo(()=>Ct.filter(n=>!(n&&typeof n.id=="string")?!1:z?rn:!0),[rn,z,Ct]),Ge=l.useMemo(()=>Mn(on),[on]),sn=l.useCallback(async n=>{var R,P,W,te,je,He,qe;console.log("[AdMeshIntentAssistant] ๐Ÿ–ฑ๏ธ Suggestion clicked:",{text:n.text,is_sponsored:n.is_sponsored,hasRecommendation:!!n.recommendation,recommendationId:((R=n.recommendation)==null?void 0:R.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((W=(P=n.recommendation)==null?void 0:P.tracking)!=null&&W.followup_engagement_url),sessionId:oe}),Ve.current=n.is_sponsored||!1,ze.current=n.is_sponsored?n:null;const x=Ge.findIndex(Re=>Re.id===n.id);Me("suggestion_clicked",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:x>=0?x:void 0,is_sponsored:n.is_sponsored,recommendation_id:(te=n.recommendation)==null?void 0:te.recommendation_id,brand_name:(qe=(He=(je=n.recommendation)==null?void 0:je.recommendation)==null?void 0:He.creative)==null?void 0:qe.brand_name,query:n.text}),At(n.text),n.is_sponsored&&n.recommendation&&q?setTimeout(async()=>{var Re;try{const Ae=(Re=n.recommendation.tracking)==null?void 0:Re.followup_engagement_url,Le=n.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ŸŽฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:Ae,recommendationId:Le,sessionId:oe}),Ae&&Le&&oe?(console.log("[AdMeshIntentAssistant] ๐ŸŽฏ Firing sponsored suggestion engagement tracking"),await q.fireFollowupEngagement(Ae,Le,oe),console.log("[AdMeshIntentAssistant] โœ… Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โš ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!Ae,hasRecommendationId:!!Le,hasSessionId:!!oe})}catch(Ae){console.error("[AdMeshIntentAssistant] โŒ Error firing sponsored suggestion engagement:",Ae)}},0):console.log("[AdMeshIntentAssistant] โ„น๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[At,Ge,q,oe,Me]),an=is[m],$n=ss[b];l.useEffect(()=>{if(fe.current.forEach(n=>n()),fe.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return Ge.forEach((n,x)=>{const R=O.current.get(n.id);if(!R)return;const P=`${oe||"anonymous"}:${n.id}:${n.is_sponsored?"s":"o"}`;if(ht.current.has(P))return;let W=null,te=null;const je=()=>{W&&(clearTimeout(W),W=null),te==null||te.disconnect(),te=null},He=()=>{var qe,Re,Ae,Le,Pt;if(ht.current.has(P)){je();return}if(ht.current.add(P),je(),Me("suggestion_exposure",{suggestion_id:n.id,suggestion_text:n.text,suggestion_type:n.type,suggestion_position:x,is_sponsored:n.is_sponsored,recommendation_id:(qe=n.recommendation)==null?void 0:qe.recommendation_id,brand_name:(Le=(Ae=(Re=n.recommendation)==null?void 0:Re.recommendation)==null?void 0:Ae.creative)==null?void 0:Le.brand_name}),q&&oe&&n.is_sponsored&&n.recommendation){const Ye=(Pt=n.recommendation.tracking)==null?void 0:Pt.followup_exposure_url,Ze=n.recommendation.recommendation_id;Ye&&Ze?(console.log("[AdMeshIntentAssistant] ๐ŸŽฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Ye,recommendationId:Ze,suggestionText:n.text,sessionId:oe}),q.fireFollowupExposure(Ye,Ze,oe)):console.warn("[AdMeshIntentAssistant] โš ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Ye,hasRecommendationId:!!Ze,suggestionText:n.text})}};te=new IntersectionObserver(qe=>{const Re=qe[0];if(Re){if(Re.intersectionRatio>=.5){W||(W=setTimeout(He,1e3));return}W&&(clearTimeout(W),W=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),te.observe(R),fe.current.push(je)}),()=>{fe.current.forEach(n=>n()),fe.current=[]}},[Ge,q,oe,Me]),console.log("[AdMeshIntentAssistant] ๐Ÿ“ฅ Received suggestions:",{totalSuggestions:Ct.length,safeSuggestions:on.length,isAnalyzingIntent:we,hasIntentError:!!Se,onlyShowWhenSponsored:z,hasSponsoredSuggestions:rn,sponsoredCount:Ct.filter(n=>n==null?void 0:n.is_sponsored).length,nonSponsoredCount:Ct.filter(n=>n&&!(n!=null&&n.is_sponsored)).length,modalShouldAppear:z?rn:!0,suggestions:Ct.map(n=>{var x,R,P;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((x=n==null?void 0:n.recommendation)==null?void 0:x.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((P=(R=n==null?void 0:n.recommendation)==null?void 0:R.tracking)!=null&&P.followup_engagement_url)}}),renderedSuggestions:Ge.map(n=>{var x,R,P;return{id:n==null?void 0:n.id,text:n==null?void 0:n.text,type:n==null?void 0:n.type,is_sponsored:n==null?void 0:n.is_sponsored,hasRecommendation:!!(n!=null&&n.recommendation),recommendationId:((x=n==null?void 0:n.recommendation)==null?void 0:x.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((P=(R=n==null?void 0:n.recommendation)==null?void 0:R.tracking)!=null&&P.followup_engagement_url)}})});const pe={base:`${16*C}px`,sm:`${14*C}px`,xs:`${12*C}px`},pn=ge||"AI-generated responses may contain errors. Please verify important information independently.",Dr=["Searching trusted sources...","Reviewing publisher coverage...","Checking relevant context...","Comparing supporting signals...","Identifying the strongest examples...","Organizing the most useful details...","Shaping the response for clarity...","Preparing the clearest answer...","Finishing the response..."],Vt=n=>{const x=(n==null?void 0:n.accentColor)||at,R=(n==null?void 0:n.metaColor)||Gt,P=(n==null?void 0:n.includeSteps)??D==="default",W=`${Et}s`,te=P?`${Dr[jt]} (${W})`:`Generating answer... ${W}`;return r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:n!=null&&n.compact?"8px":"10px",color:R,fontSize:n!=null&&n.compact?pe.xs:pe.sm},children:[r.jsx("span",{style:{width:n!=null&&n.compact?8:9,height:n!=null&&n.compact?8:9,borderRadius:999,background:x,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${Z(le,.28)}`,flexShrink:0}}),r.jsx("span",{children:te})]})},zn=l.useCallback((n,x)=>{if(mt[n.id])return;const R=x?"helpful":"not_helpful";Rt(P=>({...P,[n.id]:R})),Me("answer_feedback",{message_id:n.id,query:n.userQuery,status:R,latency_ms:n.responseTimeMs,metadata:{helpful:x}})},[mt,Me]);function hn(n,x){if(n.role!=="assistant"||!n.content.trim()||K&&n.id===ye.current)return null;const R=(x==null?void 0:x.accentColor)||at,P=(x==null?void 0:x.metaColor)||Gt,W=mt[n.id],te=typeof n.responseTimeMs=="number";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${Z(le,.08)}`,flexWrap:"wrap"},children:[r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto",flexWrap:"wrap"},children:[r.jsx("span",{style:{fontSize:pe.xs,color:P,whiteSpace:"nowrap"},children:W?"Thanks for your feedback":"Is this helpful?"}),W?r.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,background:Z(R,.12),color:R,flexShrink:0},children:W==="helpful"?r.jsx(er,{size:14}):r.jsx(Zn,{size:14})}):r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[r.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>zn(n,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${Z(le,.12)}`,background:"#ffffff",color:P,cursor:"pointer"},children:r.jsx(er,{size:14})}),r.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>zn(n,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:999,border:`1px solid ${Z(le,.12)}`,background:"#ffffff",color:P,cursor:"pointer"},children:r.jsx(Zn,{size:14})})]})]}),te?r.jsxs("span",{style:{fontSize:pe.xs,color:P,whiteSpace:"nowrap",flex:"0 1 auto",marginLeft:"auto"},children:["Answer Completed in ",Zo(n.responseTimeMs)]}):null]})}const Kt=l.useCallback(()=>{const n=Wt.current;if(!n)return;const x=Math.max(0,n.scrollWidth-n.clientWidth);Dt(n.scrollLeft>4),vt(n.scrollLeft<x-4)},[]);l.useEffect(()=>(Kt(),window.addEventListener("resize",Kt),()=>window.removeEventListener("resize",Kt)),[Kt,Ge.length]);const Ln=l.useCallback(n=>{const x=Wt.current;x&&x.scrollBy({left:n==="left"?-Math.max(160,Math.floor(x.clientWidth*.75)):Math.max(160,Math.floor(x.clientWidth*.75)),behavior:"smooth"})},[]),Z=(n,x)=>{if(!n||!n.startsWith("#"))return`rgba(15, 23, 42, ${x})`;const R=n.slice(1),P=R.length===3?R.split("").map(He=>`${He}${He}`).join(""):R;if(P.length!==6)return n;const W=parseInt(P.slice(0,2),16),te=parseInt(P.slice(2,4),16),je=parseInt(P.slice(4,6),16);return`rgba(${W}, ${te}, ${je}, ${x})`},le=_.primaryColor||"#3F037F";_.surfaceColor,_.backgroundColor;const Nn=_.borderColor||"#e5e7eb",gt=_.textColor||"#111827",Pr=_.textSecondaryColor||"#6b7280";Z(le,.12);const fn=Z(le,.24);Z(le,.38);const $r=Z(le,.12),zr=A?ft:M?"min(960px, calc(100vw - 24px))":g==="inline"?"100%":"min(420px, calc(100vw - 32px))",Fn=A?Bt:M?"min(78vh, 760px)":"auto",Lr=A?ft:"100%",Nr=A?Bt:void 0,Wn=A?"13px":"16.25px",Fr=`linear-gradient(180deg, ${Z(le,.04)} 0%, ${Z(le,.08)} 100%)`,at=le,Gt=Pr,Bn=ee||"Publisher Assistant",Yt=we&&Ge.length===0&&re.length===0,gn="#f7f8fc",xn="linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(248,250,252,0.98) 100%)",xt="rgba(15, 23, 42, 0.08)",Un="rgba(15, 23, 42, 0.12)",Hn="0 24px 60px rgba(15, 23, 42, 0.16)",bn="#667085",qn="#98a2b3",Wr=at,On="#ffffff",Vn="0 8px 24px rgba(15, 23, 42, 0.08)",Kn="rgba(15, 23, 42, 0.18)";function Gn(n){return $e?r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:n==="default"?"10px 12px":"8px 10px",borderRadius:n==="default"?"14px":"12px",border:`1px solid ${fn}`,background:Z("#ffffff",.9),marginBottom:"4px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{color:at,fontSize:pe.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),r.jsxs("div",{style:{color:gt,fontSize:pe.sm,fontWeight:600,lineHeight:1.3},children:[$e.brand_name," agent is active"]})]}),r.jsx("button",{type:"button",onClick:()=>{rt("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${fn}`,borderRadius:999,background:Z("#ffffff",.92),color:at,padding:"7px 12px",fontSize:pe.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function Yn(n){const x=A;return r.jsxs("div",{style:{display:"flex",flexDirection:x?"column":"row",alignItems:x||n==="default"?"center":"flex-start",justifyContent:x?"center":"space-between",gap:x?"2px":"12px",flexWrap:"wrap",paddingTop:x||n==="default"?"2px":"8px",borderTop:n==="default"?`1px solid ${xt}`:"none",marginTop:x?"0":n==="default"?"4px":0,flexShrink:0},children:[r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:x?"4px":"8px",color:qn,fontSize:x?"9.5px":"11px",fontWeight:700,letterSpacing:"0.01em"},children:r.jsxs("span",{children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]})}),r.jsx("div",{style:{color:qn,fontSize:x?"9px":"11px",lineHeight:x?1.25:1.45,maxWidth:x?"100%":n==="default"?"68%":"100%",textAlign:x?"center":n==="default"?"right":"left"},children:pn})]})}function yn(n){const x=n==="publisher"?[180,220,196]:["100%","82%","68%"];return n==="publisher"?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Z(le,.1),flexShrink:0}}),r.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:x.map((R,P)=>r.jsx("div",{style:{width:R,maxWidth:"100%",height:40,borderRadius:999,background:`linear-gradient(90deg, ${Z(le,.08)} 0%, ${Z(le,.18)} 50%, ${Z(le,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:`0 8px 22px ${Z(le,.08)}`,flexShrink:0}},`suggestion-skeleton-${P}`))}),r.jsx("div",{style:{width:28,height:28,borderRadius:999,background:Z(le,.1),flexShrink:0}})]}):r.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:n==="publisher"?"10px":"12px"},children:x.map((R,P)=>r.jsx("div",{style:{width:R,maxWidth:"100%",height:n==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${Z(le,.08)} 0%, ${Z(le,.18)} 50%, ${Z(le,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:n==="publisher"?`0 8px 22px ${Z(le,.08)}`:"none"}},`suggestion-skeleton-${P}`))})}function Br(){if(K)return null;if(Yt)return yn("publisher");if(!Ge.length)return null;const n=Ge.slice(0,B);return $==="stacked"?r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:A?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:A?"240px":void 0,paddingRight:A?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:n.map(x=>r.jsxs("button",{ref:en(x.id),onClick:()=>{D==="default"&&(Ce(!0),g==="floating"&&St(!0)),sn(x)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:A?"12px":"14px",border:x.is_sponsored?`1px solid ${Z(le,.32)}`:`1px solid ${Z(le,.42)}`,background:x.is_sponsored?le:Z("#ffffff",.94),color:x.is_sponsored?"#ffffff":gt,padding:A?"8px 10px":"10px 14px",fontSize:A?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:x.is_sponsored?`0 8px 18px ${Z(le,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{style:{minWidth:0},children:x.text}),L&&x.is_sponsored&&r.jsx("span",{style:{flexShrink:0,borderRadius:999,background:Z("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},x.id))}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:A?"6px":"10px",flexShrink:0},children:[r.jsx("button",{type:"button",onClick:()=>Ln("left"),disabled:!de,"aria-label":"Scroll suggestions left",style:{width:A?24:28,height:A?24:28,borderRadius:999,border:`1px solid ${Z(Nn,.8)}`,background:Z("#ffffff",.9),color:"#6b7280",cursor:de?"pointer":"default",opacity:de?1:.55},children:"โ€น"}),r.jsx("div",{ref:Wt,onScroll:Kt,style:{display:"flex",gap:A?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:n.map(x=>r.jsxs("button",{ref:en(x.id),onClick:()=>{D==="default"&&(Ce(!0),g==="floating"&&St(!0)),sn(x)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:"8px",whiteSpace:"nowrap",borderRadius:999,border:x.is_sponsored?`1px solid ${Z(le,.32)}`:`1px solid ${Z(le,.42)}`,background:x.is_sponsored?le:Z("#ffffff",.94),color:x.is_sponsored?"#ffffff":gt,padding:A?"7px 10px":"8px 14px",fontSize:A?"12px":"13px",fontWeight:500,boxShadow:x.is_sponsored?`0 8px 18px ${Z(le,.14)}`:"0 4px 12px rgba(15, 23, 42, 0.05)",cursor:"pointer"},children:[r.jsx("span",{children:x.text}),L&&x.is_sponsored&&r.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},x.id))}),r.jsx("button",{type:"button",onClick:()=>Ln("right"),disabled:!Je,"aria-label":"Scroll suggestions right",style:{width:A?24:28,height:A?24:28,borderRadius:999,border:`1px solid ${Z(Nn,.8)}`,background:Z("#ffffff",.9),color:"#6b7280",cursor:Je?"pointer":"default",opacity:Je?1:.55},children:"โ€บ"})]})}function Ur(n){var x,R;return(x=n.relatedItems)!=null&&x.length||!((R=n.sourceLinks)!=null&&R.length)?null:r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:n.sourceLinks.map(P=>r.jsx("a",{href:P.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Me("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:P.title,source_url:P.url}})},style:{color:at,fontSize:pe.xs,textDecoration:"none",borderBottom:`1px solid ${Z(le,.18)}`},children:P.title||P.url},`${n.id}-${P.url}`))})}function Hr(n){var x;return(x=n.relatedItems)!=null&&x.length?r.jsxs("div",{style:{marginTop:"14px"},children:[r.jsx("div",{style:{fontSize:pe.xs,fontWeight:700,color:"#4b5563",marginBottom:"8px"},children:"Related"}),r.jsx("div",{style:{display:"flex",gap:A?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:n.relatedItems.slice(0,4).map(R=>r.jsxs("a",{href:R.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Me("source_link_clicked",{message_id:n.id,query:n.userQuery,metadata:{source_title:R.title,source_url:R.url,source_publisher:R.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:A?"6px":"10px",padding:A?"10px":"14px",borderRadius:A?"12px":"14px",textDecoration:"none",color:gt,border:`1px solid ${Z(le,.18)}`,background:"#ffffff",boxShadow:"0 10px 24px rgba(15, 23, 42, 0.08)",flex:A?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:A?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[r.jsx("div",{style:{fontSize:A?"13px":"18px",fontWeight:650,lineHeight:1.35,color:le,overflowWrap:"anywhere"},children:R.title||R.url}),R.publisher&&r.jsx("div",{style:{fontSize:A?"11px":"15px",color:"#6b7280",lineHeight:1.4,overflowWrap:"anywhere"},children:R.publisher})]},`${n.id}-${R.url}`))})]}):null}function qr(){return r.jsxs("div",{ref:Ue,style:{flex:A?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none",padding:A?"0 2px 4px":M?"16px 16px 8px":0},children:[re.map(n=>{const x=n.role==="user"&&n.id===tt.current;return r.jsx("div",{ref:x?Ke:void 0,style:{marginBottom:"12px",textAlign:n.role==="user"?"right":"left"},children:(()=>{const P=!!n.content.trim()||!K;return r.jsx(r.Fragment,{children:r.jsxs("div",{style:{display:n.role==="assistant"?"block":"inline-block",width:n.role==="assistant"?"100%":void 0,maxWidth:n.role==="assistant"?"100%":"76%",padding:n.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:n.role==="assistant"?0:"18px",background:n.role==="user"?at:"transparent",color:n.role==="user"?"#ffffff":gt,boxShadow:"none",border:"none",fontSize:n.role==="assistant"?Wn:A?"12px":"13px",lineHeight:n.role==="assistant"?1.62:1.4},children:[n.role==="assistant"?n.content.trim()?r.jsx(Cn,{content:n.content,theme:{..._,textColor:gt},fontSize:Wn}):K&&n.id===ye.current?Vt({includeSteps:!0}):null:r.jsx("p",{style:{margin:0},children:n.content}),n.role==="assistant"&&Ur(n),n.role==="assistant"&&Hr(n),n.role==="assistant"&&hn(n),n.role==="assistant"&&P&&Ie.has(n.id)&&n.initialRecommendation&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:nn,onRecommendationsShown:(W,te)=>{tn(W,te,n.userQuery)},onError:W=>{console.error("[AdMeshIntentAssistant] Recommendation error:",W)}})}),n.role==="assistant"&&P&&!Ie.has(n.id)&&(n.initialRecommendation||kt)&&r.jsx("div",{style:{marginTop:"14px"},children:r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation||void 0,onFollowupDetected:nn,onRecommendationsShown:(W,te)=>{tn(W,te,n.userQuery)},onError:W=>{console.error("[AdMeshIntentAssistant] Recommendation error:",W)}})})]})})})()},n.id)}),Be&&r.jsx("div",{style:{color:Gt,fontSize:pe.sm},children:"Connection issue. Please try again."}),r.jsx("div",{ref:It})]})}if(D==="default"){const n=r.jsxs("div",{style:{width:zr,maxWidth:Lr,height:Fn,maxHeight:Nr,boxSizing:"border-box",display:"flex",flexDirection:"column",background:M?gn:Fr,borderRadius:A?"12px":M?"18px":"20px",padding:M?0:A?"8px":"12px",boxShadow:M?Hn:"none",border:M?`1px solid ${Un}`:"none",overflow:"hidden",minHeight:A?0:void 0},children:[(M||A)&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:A?"10px 12px":"16px 18px",background:M?xn:"#ffffff29",color:gt,borderBottom:`1px solid ${xt}`,flexShrink:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("div",{style:{width:A?30:40,height:A?30:40,borderRadius:A?"10px":"14px",background:Z(le,.08),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:at,overflow:"hidden"},children:c?r.jsx("img",{src:c,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||y)&&r.jsxs("div",{children:[u&&r.jsx("div",{style:{fontSize:A?"14px":"20px",fontWeight:700,lineHeight:1.1,letterSpacing:0},children:i}),y&&r.jsx("div",{style:{fontSize:A?"10px":"12px",color:bn,marginTop:"2px"},children:Bn})]})]}),!A&&r.jsx("button",{type:"button",onClick:()=>Ce(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"12px",border:`1px solid ${xt}`,background:"#ffffff",color:bn,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx("span",{style:{fontSize:"18px",lineHeight:1,fontWeight:700,transform:"translateY(-1px)"},children:"-"})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:A?"6px":"16px",minHeight:0,flex:A?"1 1 0":void 0,overflow:A?"hidden":void 0,overscrollBehavior:"contain",padding:A?"8px 10px 6px":M?"18px":"14px",background:M?gn:Z("#ffffff",.16),height:A?void 0:M?Fn:"auto"},children:[Gn("default"),M&&qr(),A&&!M&&r.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),A&&!M&&G&&re.length===0&&r.jsx("div",{style:{color:gt,fontSize:"15px",lineHeight:1.3,fontWeight:700,letterSpacing:0,padding:"2px 2px 0",textAlign:"center"},children:k}),Br(),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",borderRadius:A?"12px":"16px",background:On,padding:A?"6px 6px 6px 10px":"8px 8px 8px 14px",boxShadow:M?Vn:`0 8px 22px ${$r}`,border:`1px solid ${M?xt:fn}`,flexShrink:0},children:[r.jsx("input",{type:"text",value:j,onChange:x=>ce(x.target.value),onKeyPress:x=>{if(x.key==="Enter"){if(x.preventDefault(),K)return;ze.current=null,Ve.current=!1,Ce(!0),g==="floating"&&St(!0),At(j)}},placeholder:S,style:{flex:1,border:"none",outline:"none",borderRadius:"12px",padding:A?"8px 2px":"10px 4px",color:gt,fontSize:A?"13px":"15px",background:"transparent"}}),r.jsx("button",{type:"button",onClick:()=>{if(K){mn();return}ze.current=null,Ve.current=!1,Ce(!0),g==="floating"&&St(!0),At(j)},disabled:!K&&!j.trim(),style:{border:"none",borderRadius:"12px",background:K?"#dc2626":at,color:"#ffffff",minWidth:A?"40px":"48px",height:A?"36px":"44px",padding:A?"0 10px":"0 16px",fontSize:A?"12px":"14px",fontWeight:700,cursor:!K&&!j.trim()?"default":"pointer",opacity:!K&&!j.trim()?.6:1,boxShadow:`0 10px 20px ${K?"rgba(220, 38, 38, 0.18)":Z(le,.18)}`},children:K?"Stop":"Send"})]}),M&&Yn("default"),!M&&r.jsxs("div",{style:{textAlign:"center",paddingTop:"2px"},children:[r.jsxs("div",{style:{color:Gt,fontSize:A?"9.5px":pe.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),r.jsx("div",{style:{color:Gt,fontSize:A?"9px":pe.xs,lineHeight:A?1.25:1.5},children:pn})]})]})]});return g==="inline"?A?r.jsx("div",{ref:Tt,className:"admesh-component","data-admesh-theme":H,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-expanded":Ot?"true":"false",style:{width:ft,height:Bt,maxWidth:ft,maxHeight:Bt,position:"relative",overflow:"hidden"},children:n}):r.jsxs("div",{className:"admesh-component","data-admesh-theme":H,style:{width:"100%",position:"relative"},children:[n,M&&r.jsx("div",{style:{position:"fixed",inset:0,background:Kn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),M&&r.jsx("div",{style:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",zIndex:2147483001},children:n})]}):se?r.jsxs("div",{className:"admesh-component","data-admesh-theme":H,children:[M&&r.jsx("div",{style:{position:"fixed",inset:0,background:Kn,backdropFilter:"blur(6px)",zIndex:2147483e3}}),r.jsx("div",{style:{position:"fixed",...M?{left:"50%",bottom:"12px",transform:"translateX(-50%)"}:an,zIndex:2147483001},children:n})]}):r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsx("button",{type:"button",onClick:Dn,style:{position:"fixed",...an,zIndex:2147483e3,border:"none",borderRadius:999,background:_.primaryColor,color:"#ffffff",padding:"14px 18px",boxShadow:"0 18px 40px rgba(15, 23, 42, 0.18)",cursor:"pointer"},children:s})})}return Ge.length===0&&!Yt?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):g==="inline"?r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:Qt(d)??"100%",backgroundColor:"#eef2ff",fontSize:pe.base,...o},children:r.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[Yt?yn("legacy"):Ge.length>0&&r.jsx("div",{className:"flex flex-col gap-3",children:Ge.slice(0,B).map((n,x)=>r.jsxs("button",{ref:en(n.id),onClick:()=>sn(n),className:"rounded-full px-5 py-4 text-left shadow-sm transition-transform duration-200 hover:scale-[1.01] active:scale-[0.99]",style:{width:x===0?"100%":x===1?"82%":"68%",backgroundColor:_.surfaceColor||"#ffffff",color:_.textColor||"#1e293b",border:`1px solid ${_.borderColor||"#e2e8f0"}`,fontSize:pe.sm},children:[r.jsx("span",{className:"leading-tight",children:n.text}),L&&n.is_sponsored&&r.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:_.backgroundColor||"#ffffff",color:_.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},n.id))}),re.length>0&&r.jsxs("div",{ref:Ue,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:_.textColor,overscrollBehavior:"contain",WebkitOverflowScrolling:"touch"},children:[re.map(n=>{const x=n.role==="user"&&n.id===tt.current;return r.jsx("div",{ref:x?Ke:void 0,className:n.role==="user"?"text-right":"text-left",children:r.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:n.role==="user"?_.primaryColor:"#ffffff",color:n.role==="user"?"#ffffff":_.textColor,fontSize:pe.sm},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx(Cn,{content:n.content,theme:_,fontSize:pe.sm}),hn(n,{accentColor:_.primaryColor,metaColor:_.textSecondaryColor})]}):K&&n.id===ye.current?Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:n.content})})},n.id)}),K&&!re.some(n=>n.role==="assistant"&&n.id===ye.current&&!n.content.trim())&&r.jsx("div",{className:"text-sm",style:{color:_.textSecondaryColor},children:Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1})}),Be&&r.jsx("div",{className:"text-sm",style:{color:_.textSecondaryColor},children:"Connection issue. Please try again."}),r.jsx("div",{ref:It})]}),r.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{type:"text",value:j,onChange:n=>ce(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(K){n.preventDefault();return}At(j)}},placeholder:S,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:_.backgroundColor||"#ffffff",color:_.textColor,fontSize:pe.sm}}),r.jsx("button",{onClick:()=>{if(K){mn();return}At(j)},disabled:!K&&!j.trim(),className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50",style:{backgroundColor:K?"#dc2626":_.primaryColor,color:"#ffffff"},children:K?r.jsx(wn,{size:18}):r.jsx(Jn,{size:18})})]})}),r.jsxs("div",{className:"space-y-2 text-center",children:[r.jsxs("p",{style:{color:_.textSecondaryColor,fontSize:pe.xs,fontWeight:600},children:["Powered by"," ",r.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),r.jsx("p",{style:{color:_.textSecondaryColor,fontSize:pe.xs,lineHeight:1.5},children:pn})]})]})})}):se?r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...M?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...an,width:Qt(d)??$n.width,height:Qt(h)??$n.height},backgroundColor:M?gn:_.backgroundColor,zIndex:9999,fontSize:pe.base,borderRadius:M?"20px":"16px",border:M?`1px solid ${Un}`:"1px solid transparent",boxShadow:M?Hn:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[r.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between p-4 border-b",style:{position:"sticky",top:0,zIndex:10,borderColor:M?xt:"transparent",background:M?xn:_.backgroundColor,padding:M?"18px 20px":"16px"},children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{style:{width:M?40:32,height:M?40:32,borderRadius:M?"14px":"10px",background:Z(le,.08),color:at,display:"flex",alignItems:"center",justifyContent:"center",fontSize:M?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:c?r.jsx("img",{src:c,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(u||y&&M)&&r.jsxs("div",{children:[u&&r.jsx("div",{className:"font-medium",style:{color:_.textColor,fontSize:M?"20px":pe.base,fontWeight:700,letterSpacing:M?"-0.02em":0},children:i}),y&&M&&r.jsx("div",{style:{color:bn,fontSize:"12px",marginTop:"2px"},children:Bn})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[!A&&r.jsx("button",{onClick:Ir,className:"transition-colors",title:M?"Minimize":"Expand",style:{width:M?36:28,height:M?36:28,borderRadius:M?"12px":"10px",border:`1px solid ${M?xt:"transparent"}`,background:M?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:M?r.jsx(so,{size:16,style:{color:_.textSecondaryColor}}):r.jsx(ro,{size:16,style:{color:_.textSecondaryColor}})}),r.jsx("button",{onClick:Tr,className:"transition-colors",style:{width:M?36:28,height:M?36:28,borderRadius:M?"12px":"10px",border:`1px solid ${M?xt:"transparent"}`,background:M?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:r.jsx(wn,{size:16,style:{color:_.textSecondaryColor}})})]})]}),r.jsxs("div",{ref:Ue,className:"flex-1 min-h-0 overflow-y-auto p-4",style:{flex:"1 1 0%",minHeight:0,overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",padding:M?"20px":"16px"},children:[Gn("legacy"),G&&re.length===0&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",children:r.jsx("p",{style:{color:_.textColor,margin:0,fontSize:pe.sm},children:k})})}),re.map(n=>{const x=n.role==="user"&&n.id===tt.current;return r.jsxs("div",{ref:x?Ke:void 0,className:"mb-3",children:[r.jsx("div",{className:n.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:n.role==="user"?Wr:"transparent",color:n.role==="user"?"#ffffff":_.textColor,border:"none",borderRadius:n.role==="user"?M?"14px":"12px":0,padding:n.role==="user"?M?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:n.role==="assistant"?n.content.trim()?r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{fontSize:`calc(${pe.sm} * 1.3)`,lineHeight:1.65},children:r.jsx(Cn,{content:n.content,theme:_,fontSize:`calc(${pe.sm} * 1.3)`})}),hn(n,{accentColor:_.primaryColor,metaColor:_.textSecondaryColor})]}):K&&n.id===ye.current?Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1}):null:r.jsx("p",{style:{margin:0,fontSize:pe.sm,lineHeight:"1.4"},children:n.content})}),n.role==="assistant"&&!Ie.has(n.id)&&r.jsx(Xt,{messageId:n.id,query:n.userQuery,onFollowupDetected:nn,onRecommendationsShown:(R,P)=>{tn(R,P,n.userQuery)},onError:R=>{console.error("[AdMeshIntentAssistant] Recommendations error:",R)}}),n.role==="assistant"&&Ie.has(n.id)&&n.initialRecommendation&&!K&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),r.jsx(Xt,{messageId:n.id,query:n.userQuery,initialRecommendation:n.initialRecommendation,onFollowupDetected:nn,onRecommendationsShown:(R,P)=>{tn(R,P,n.userQuery)},onError:R=>{console.error("[AdMeshIntentAssistant] Recommendations error:",R)}})]})]},n.id)}),K&&!re.some(n=>n.role==="assistant"&&n.id===ye.current&&!n.content.trim())&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:Vt({compact:!0,accentColor:_.primaryColor,metaColor:_.textSecondaryColor,includeSteps:!1})})}),Be&&r.jsx("div",{className:"mb-3",children:r.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:_.textSecondaryColor},children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{style:{fontSize:pe.xs},children:"โš ๏ธ"}),r.jsx("span",{style:{fontSize:pe.sm},children:"Connection issue. Please try again."})]})})}),r.jsx("div",{ref:It})]}),re.length===0&&Yt&&r.jsx("div",{className:"px-4 pb-2",children:yn("legacy")}),Ge.length>0&&re.length===0&&!Yt&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:Ge.slice(0,B).map(n=>r.jsxs("button",{ref:en(n.id),onClick:()=>sn(n),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:_.surfaceColor||"#f8fafc",color:_.textColor||"#1e293b",border:`1px solid ${_.borderColor||"#e2e8f0"}`,fontSize:pe.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[r.jsx("span",{className:"leading-tight",children:n.text}),L&&n.is_sponsored&&r.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:_.backgroundColor||"#ffffff",color:_.textSecondaryColor||"#64748b"},children:"Ad"})]},n.id))})}),Se&&!we&&on.length===0&&r.jsx("div",{className:"px-4 pb-2",children:r.jsx("div",{className:"flex flex-col gap-2",children:r.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:_.surfaceColor,borderColor:_.borderColor,color:_.textSecondaryColor},children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{style:{fontSize:pe.sm},children:"Intent analysis failed"}),r.jsx("button",{onClick:_e,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:_.primaryColor,color:"#ffffff"},children:"Retry"})]}),r.jsx("span",{style:{fontSize:pe.xs},children:Se})]})})}),r.jsxs("div",{className:"p-3 border-t",style:{borderColor:M?xt:"transparent",padding:M?"18px 20px":void 0,background:M?xn:void 0},children:[r.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${xt}`,borderRadius:M?"16px":"12px",background:On,boxShadow:M?Vn:"none",padding:M?"8px 8px 8px 14px":void 0},children:[r.jsx("input",{type:"text",value:j,onChange:n=>ce(n.target.value),onKeyPress:n=>{if(n.key==="Enter"){if(K){n.preventDefault();return}At(j)}},placeholder:S,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:_.textColor,fontSize:M?"15px":pe.sm,"--tw-ring-color":_.primaryColor}}),r.jsx("button",{onClick:()=>{if(K){mn();return}At(j)},disabled:!K&&!j.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:K?"#dc2626":_.primaryColor,color:"#ffffff",borderRadius:M?"12px":"10px",width:M?"46px":void 0,height:M?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:M?`0 10px 20px ${Z(le,.18)}`:"none"},children:K?r.jsx(wn,{size:14}):r.jsx(Jn,{size:14})})]}),Yn("legacy")]})]})}):r.jsx("div",{className:"admesh-component","data-admesh-theme":H,children:r.jsx("button",{onClick:Dn,className:"flex items-center gap-2 px-4 py-3 rounded-full shadow-lg transition-all duration-200 hover:scale-105 active:scale-95",style:{position:"fixed",...an,backgroundColor:_.primaryColor,color:"#ffffff",zIndex:9999,fontSize:pe.base,...o},children:r.jsx("span",{className:"font-medium",children:s})})})},ln="admesh:streamingStart",cn="admesh:streamingComplete";function ls(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(ln,{detail:o});window.dispatchEvent(s),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function cs(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(cn,{detail:s});window.dispatchEvent(i),a.log("[StreamingEvents] ๐Ÿ“ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function ds(t,e,o){const s=i=>{const c=i;c.detail.messageId===t&&c.detail.sessionId===e&&(a.log("[StreamingEvents] ๐Ÿ“จ Received streamingStart event"),o(c.detail))};return window.addEventListener(ln,s),()=>{window.removeEventListener(ln,s)}}function Rr(t,e,o){a.log("[StreamingEvents] ๐Ÿ‘‚ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const c=i;a.log("[StreamingEvents] ๐Ÿ“จ Received streamingComplete event (checking match)",{receivedMessageId:c.detail.messageId,receivedSessionId:c.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:c.detail.messageId===t,sessionIdMatch:c.detail.sessionId===e}),c.detail.messageId===t&&c.detail.sessionId===e?(a.log("[StreamingEvents] โœ… Event matched! Calling callback"),o(c.detail)):a.log("[StreamingEvents] โš ๏ธ Event did not match - ignoring")};return window.addEventListener(cn,s),()=>{a.log("[StreamingEvents] ๐Ÿงน Removing streamingComplete listener"),window.removeEventListener(cn,s)}}const dn=()=>{const t=new Set,e=new Map,o=c=>{const u=e.get(c);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(c))};return{startTracking:({exposureUrl:c,recommendationId:u,linkElement:y,sessionId:g,logPrefix:v="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!c||!y){v&&a.warn(`${v} โš ๏ธ Missing exposure tracking data`);return}const d=`${g||"anonymous"}::${u||c}`;if(t.has(d)||e.has(d))return;const h={observer:void 0,timeoutId:null,viewableStart:null},w=()=>{o(d),t.add(d),fetch(c,{method:"GET",keepalive:!0}).then(()=>{v&&a.log(`${v} โœ… Exposure pixel fired`)}).catch(()=>{v&&a.warn(`${v} โš ๏ธ Failed to fire exposure pixel`),t.delete(d)})},C=new IntersectionObserver(m=>{m.forEach(b=>{b.intersectionRatio>=.5?h.viewableStart===null&&(h.viewableStart=performance.now(),h.timeoutId=setTimeout(w,1e3)):(h.viewableStart=null,h.timeoutId&&(clearTimeout(h.timeoutId),h.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});h.observer=C,C.observe(y),e.set(d,h)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},us=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:c=[],onLinksFound:u,onNoLinksFound:y,children:g})=>{const[v,d]=l.useState(!1),[h,w]=l.useState(!0),[C,m]=l.useState(!1),b=l.useRef(dn()),f=l.useRef(u),p=l.useRef(y),E=l.useRef(t),I=l.useRef(s),G=l.useRef(o),k=l.useRef(i);l.useEffect(()=>{f.current=u,p.current=y,E.current=t,I.current=s,G.current=o,k.current=i},[u,y,t,s,o,i]),l.useEffect(()=>()=>{b.current.cleanup()},[]);const S=l.useCallback(({exposureUrl:N,recommendationId:B,linkElement:$})=>{b.current.startTracking({exposureUrl:N,recommendationId:B,linkElement:$,sessionId:G.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),L=l.useCallback(()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿ” Performing final link detection...");try{const N=document.getElementById(E.current);if(!N){a.warn("[FinalLinkDetectionCheck] โŒ Container not found"),d(!0),y();return}const B=new Tn({autoAddLabels:!0,fireExposurePixels:!0}),$=c.length>0?c:[];a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Using ${$.length} recommendations for link detection`),$.length>0&&process.env.NODE_ENV==="development"&&$.forEach((D,Q)=>{var J,ge,V,ee,me,xe,q,oe,ve;a.log(`[FinalLinkDetectionCheck] ๐Ÿ“‹ Recommendation ${Q+1} (DEV):`,{recommendation_id:D==null?void 0:D.recommendation_id,click_url:((J=D==null?void 0:D.tracking)==null?void 0:J.click_url)||((V=(ge=D==null?void 0:D.recommendation)==null?void 0:ge.creative)==null?void 0:V.landing_page_url),format:(ee=D==null?void 0:D.recommendation)==null?void 0:ee.format,brand_name:(q=(xe=(me=D.render)==null?void 0:me.creative)==null?void 0:xe.advertiser)==null?void 0:q.brand_name,cta_url:(ve=(oe=D.render)==null?void 0:oe.creative)==null?void 0:ve.landing_page_url})});const z=B.scanAndProcessLinks(N,$,({exposureUrl:D,recommendationId:Q,linkElement:J})=>S({exposureUrl:D,recommendationId:Q,linkElement:J}));a.log(`[FinalLinkDetectionCheck] ๐Ÿ“Š Final check result: ${z.length} links`),z.length>0?(a.log("[FinalLinkDetectionCheck] โœ… Links detected - canceling fallback (no API call)"),m(!0),f.current(z.length)):(a.log(`[FinalLinkDetectionCheck] โš ๏ธ No links found - rendering fallback (will use ${$.length} previous recommendation(s) if available)`),m(!1),p.current()),d(!0)}catch{a.error("[FinalLinkDetectionCheck] โŒ Error during final check"),d(!0),p.current()}},[S,c]);return l.useEffect(()=>{a.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:c.length});let N=null,B=!1;const $=Rr(e,o,z=>{a.log("[FinalLinkDetectionCheck] ๐ŸŽฏ Received streamingComplete event",{messageId:z.messageId,sessionId:z.sessionId,timestamp:z.timestamp}),B=!0,N&&(clearTimeout(N),N=null),w(!1),setTimeout(()=>{L()},100)});return N=setTimeout(()=>{B||(a.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),w(!1),setTimeout(()=>{L()},100))},5e3),()=>{a.log("[FinalLinkDetectionCheck] ๐Ÿงน Cleaning up listener"),N&&clearTimeout(N),$()}},[e,o]),h?r.jsx(r.Fragment,{}):v?C?(a.log("[FinalLinkDetectionCheck] ๐Ÿšซ Links found - NOT rendering fallback"),r.jsx(r.Fragment,{})):(a.log("[FinalLinkDetectionCheck] โœ… No links found - rendering fallback"),r.jsx(r.Fragment,{children:g})):r.jsx(r.Fragment,{})},ms=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:c,className:u,query:y,onFallbackChange:g,onWeaveAttempt:v,onWeaveOutcome:d})=>{var D,Q;const{sessionId:h,sdk:w,language:C,location:m,userId:b,model:f,messages:p}=Ht(),E=l.useRef(null),I=`weave-ad-container-${t}`,G=l.useRef(dn()),k=l.useRef(!1),S=l.useRef(null),[L,N]=l.useState([]),B=l.useRef([]);l.useEffect(()=>(S.current||(S.current=new Tn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{S.current&&(S.current.stopWatching(),S.current.clearCache())}),[]),l.useEffect(()=>()=>{G.current.cleanup()},[]),l.useEffect(()=>{(async()=>{var ge;if(!w||!(y!=null&&y.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 V=await w.fetchPlatformResponse({query:y.trim(),sessionId:h,messageId:t,language:C,location:m,userId:b,model:f,messages:p}),ee=(V==null?void 0:V.status)==="generated"?[V]:[];if(N(ee),B.current=ee,a.log("[WeaveAdFormatContainer] ๐Ÿ“ฅ Got platform response:",{status:V==null?void 0:V.status,recommendationId:V==null?void 0:V.recommendation_id,hasRecommendation:!!(V!=null&&V.recommendation),format:(ge=V==null?void 0:V.recommendation)==null?void 0:ge.format}),V!=null&&V.recommendation){const me=V.recommendation.creative,xe=me.landing_page_url;a.log("[WeaveAdFormatContainer] ๐ŸŽฏ Found creative in platform response:",{brandName:me.brand_name,headline:me.headline,description:me.description,brandUrl:xe})}else a.log("[WeaveAdFormatContainer] โš ๏ธ No recommendation found in platform response")}catch(V){a.warn("[WeaveAdFormatContainer] โš ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",V),N([])}})()},[w,h,t,y]),l.useEffect(()=>{const J=E.current;if(!J||!S.current)return;const ge=S.current,V=({exposureUrl:xe,recommendationId:q,linkElement:oe})=>{G.current.startTracking({exposureUrl:xe,recommendationId:q,linkElement:oe,sessionId:h,logPrefix:"[WeaveAdFormatContainer]"})},me=setTimeout(()=>{a.log("[WeaveAdFormatContainer] ๐Ÿ” Weave injection attempt started"),v==null||v(t);const xe=B.current.length>0?B.current:[];a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Using ${xe.length} recommendations for link detection`);try{const q=ge.scanAndProcessLinks(J,xe,V);q.length>0&&!k.current?(k.current=!0,a.log(`[WeaveAdFormatContainer] โœ… Weave injection succeeded: ${q.length} links detected`),d==null||d(t,!0,`Found ${q.length} links`),s==null||s(q.length),g==null||g(!1)):k.current||a.log("[WeaveAdFormatContainer] โš ๏ธ Weave injection: no links found on initial scan")}catch(q){const oe=q instanceof Error?q.message:String(q);a.error(`[WeaveAdFormatContainer] โŒ Weave injection failed: ${oe}`),d==null||d(t,!1,oe),i==null||i(),g==null||g(!0)}},100);return ge.watchForNewLinks(J,B.current,V),()=>{clearTimeout(me),ge.stopWatching()}},[e,h,t,s,g,v,d]);const $=(Q=(D=L[0])==null?void 0:D.recommendation)==null?void 0:Q.format,z=$==="weave";return l.useEffect(()=>{y&&z&&a.log(`[WeaveAdFormatContainer] ๐ŸŽฏ Format is "weave" (preferred: ${$}) - skipping fallback recommendations`)},[y,z,$]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:E,id:I,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),y&&!z&&r.jsx(us,{containerId:I,messageId:t,sessionId:h,sdk:w,query:y,recommendations:L,onLinksFound:J=>{a.log(`[WeaveAdFormatContainer] โœ… Links found (${J}) - no fallback needed`),d==null||d(t,!0,`Found ${J} links in final check`),s==null||s(J),g==null||g(!1)},onNoLinksFound:()=>{a.log("[WeaveAdFormatContainer] โš ๏ธ No links found - rendering fallback"),a.log(`[WeaveAdFormatContainer] ๐Ÿ“‹ Passing ${L.length} recommendation(s) to fallback component`),d==null||d(t,!1,"No links detected in final check"),i==null||i(),g==null||g(!0)},children:r.jsx(Sr,{format:o,messageId:t,query:y,fallback:!0,onError:c,previousRecommendations:L.length>0?L:void 0})})]})},ps=t=>{const{sdk:e,sessionId:o}=Ht(),s=l.useRef(!1),i=l.useRef(0),c=l.useRef(!1),u=l.useRef(!1),y=l.useRef(null),g=l.useRef(dn());l.useEffect(()=>()=>{g.current.cleanup()},[]);const v=l.useCallback(({exposureUrl:p,recommendationId:E,linkElement:I})=>{g.current.startTracking({exposureUrl:p,recommendationId:E,linkElement:I,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),d=l.useRef(Date.now()),h=l.useRef(0),w=l.useRef(null),C=l.useRef([]),m=l.useRef(300),b=l.useCallback(async()=>{var p,E,I,G;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const k=document.getElementById(t.llmOutputContainerId);if(!k)return;const S=(p=e.getWeaveProcessor)==null?void 0:p.call(e);if(!S)return;const L=S.scanAndProcessLinks(k,[],({exposureUrl:B,recommendationId:$,linkElement:z})=>v({exposureUrl:B,recommendationId:$,linkElement:z}));i.current=L.length;const N=L.length>0;if(N&&!c.current)c.current=!0,(E=t.onLinksDetected)==null||E.call(t,L.length),u.current=!0;else if(!N&&c.current)c.current=!1,u.current=!1;else if(!N&&!u.current){y.current&&clearTimeout(y.current),w.current&&clearInterval(w.current),h.current=0,d.current=Date.now();const B=Math.max(100,m.current/3);w.current=setInterval(()=>{var Q;const z=Date.now()-d.current,D=m.current;z>=D?(h.current++,h.current>=2&&(w.current&&(clearInterval(w.current),w.current=null),!c.current&&!u.current&&((Q=t.onNoLinksDetected)==null||Q.call(t),u.current=!0))):h.current=0},B);const $=Math.max(1500,m.current*5);y.current=setTimeout(()=>{var z;w.current&&(clearInterval(w.current),w.current=null),!c.current&&!u.current&&((z=t.onNoLinksDetected)==null||z.call(t),u.current=!0)},$)}else N&&u.current&&!c.current&&(y.current&&(clearTimeout(y.current),y.current=null),c.current=!0,(I=t.onLinksDetected)==null||I.call(t,L.length),u.current=!0)}catch(k){const S=k instanceof Error?k:new Error(String(k));(G=t.onError)==null||G.call(t,S)}finally{s.current=!1}}},[e,o,t,v]),f=l.useCallback(()=>{const p=C.current;if(p.length<2){m.current=300;return}const E=[];for(let k=1;k<p.length;k++)E.push(p[k]-p[k-1]);const I=E.reduce((k,S)=>k+S,0)/E.length,G=Math.max(100,Math.min(I*3,1e3));m.current=G},[]);return l.useEffect(()=>{const p=document.getElementById(t.llmOutputContainerId);if(!p)return;b();const E=new MutationObserver(()=>{const I=Date.now();d.current=I,h.current=0,C.current.push(I),C.current.length>10&&C.current.shift(),f(),b()});return E.observe(p,{childList:!0,subtree:!0,characterData:!1}),()=>{E.disconnect(),y.current&&clearTimeout(y.current),w.current&&clearInterval(w.current)}},[t.llmOutputContainerId,b,f]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:c.current,shouldRenderFallback:!c.current&&u.current,processWeaveFormat:b}},hs="1.0.31";exports.AdMeshBadge=Mr;exports.AdMeshCompactCard=jn;exports.AdMeshContext=En;exports.AdMeshFollowup=kr;exports.AdMeshIntentAssistant=as;exports.AdMeshLayout=gr;exports.AdMeshLinkTracker=Cr;exports.AdMeshProvider=wr;exports.AdMeshRecommendations=Xt;exports.AdMeshRenderer=vr;exports.AdMeshSDK=Jt;exports.AdMeshTailAd=Bo;exports.AdMeshTracker=xr;exports.AdMeshViewabilityTracker=Zt;exports.STREAMING_COMPLETE_EVENT=cn;exports.STREAMING_START_EVENT=ln;exports.VERSION=hs;exports.WeaveAdFormatContainer=ms;exports.WeaveAdFormatProvider=zo;exports.WeaveFallbackRecommendations=Sr;exports.WeaveResponseProcessor=Tn;exports.callAnalyzeIntentEndpoint=yr;exports.createInlineExposureTracker=dn;exports.dispatchStreamingCompleteEvent=cs;exports.dispatchStreamingStartEvent=ls;exports.extractHeadingsDirectly=br;exports.onStreamingComplete=Rr;exports.onStreamingStart=ds;exports.useAdMesh=Ht;exports.useAdMeshContext=Rn;exports.useAdMeshStyles=jr;exports.useViewabilityTracker=fr;exports.useWeaveAdFormat=ps;exports.useWeaveAdFormatContext=Lo;
1095
1125
  //# sourceMappingURL=index.js.map