admesh-ui-sdk 1.0.47 โ 1.0.48
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/components/AdMeshIntentAssistant.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +11 -4
- package/dist/index.mjs.map +1 -1
- package/dist/publisher-assistant.js +26 -26
- package/dist/publisher-assistant.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -148,7 +148,7 @@
|
|
|
148
148
|
}
|
|
149
149
|
`}),n.jsxs("div",{role:!P&&A?"link":void 0,tabIndex:!P&&A?0:void 0,style:{display:"flex",flexDirection:"column",gap:"10px",padding:"12px",borderRadius:(e==null?void 0:e.borderRadius)||((Ut=(Lt=e==null?void 0:e.components)==null?void 0:Lt.card)==null?void 0:Ut.borderRadius)||"14px",border:`1px solid ${ze}`,background:We,boxShadow:Se,minWidth:0,cursor:!P&&A?"pointer":void 0},onClick:ie,onKeyDown:D,children:[n.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-start",minWidth:0},children:[n.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0,overflow:"hidden",background:he?"#1f2937":"#eff6ff",display:"flex",alignItems:"center",justifyContent:"center"},children:!ce&&K&&vr(K)?n.jsx("img",{src:K,alt:`${h} logo`,style:{width:"100%",height:"100%",objectFit:"contain",padding:"6px",background:"#ffffff"},onError:()=>ke(!0)}):n.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:Ae},children:(h||"A").charAt(0).toUpperCase()})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{className:"admesh-compact-meta-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[n.jsx("div",{className:"admesh-compact-line-clamp-1",style:{fontSize:"11px",color:Ae},children:Ge?h:""}),n.jsx("span",{style:{flexShrink:0,fontSize:"10px",color:Ae,textTransform:"uppercase",letterSpacing:"0.08em"},children:L})]}),!P&&n.jsx("div",{className:"admesh-compact-line-clamp-2",style:{fontSize:"14px",lineHeight:1.3,fontWeight:700,color:st,marginBottom:"4px"},title:xe,children:xe}),Z&&n.jsx("p",{className:"admesh-compact-line-clamp-2",style:{margin:0,fontSize:"12px",lineHeight:1.35,color:yt},title:Z,children:Z})]})]}),P&&n.jsx("div",{className:"admesh-compact-tail-scroll",style:{display:"flex",gap:"8px",overflowX:"auto",paddingBottom:"2px"},children:F.map(q=>{const Ce=rn(q.product_name)||"Product",Qe=rn(q.product_link)||rn(q.product_url)||A||"#",ut=Zo(q.product_price,q.product_currency),Tt=rn(q.product_image_url),It=Tt&&vr(Tt)?Tt:"",Ht=Qe!=="#";return n.jsx("a",{href:Qe,target:Ht?"_blank":void 0,rel:Ht?"noopener noreferrer":void 0,onClick:Dt=>ee(`compact_tail_ad_product_${q.product_id||"item"}`,Dt),style:{minWidth:"220px",maxWidth:"220px",display:"block",textDecoration:"none",color:"inherit",border:`1px solid ${ze}`,borderRadius:"12px",background:jt,padding:"8px",flexShrink:0},children:n.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"flex-start"},children:[n.jsx("div",{style:{width:"34px",height:"34px",borderRadius:"8px",overflow:"hidden",flexShrink:0,background:he?"#374151":"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",color:Ae,fontSize:"12px",fontWeight:700},children:It?n.jsx("img",{src:It,alt:Ce,style:{width:"100%",height:"100%",objectFit:"cover"}}):Ce.charAt(0).toUpperCase()}),n.jsxs("div",{style:{minWidth:0,flex:1},children:[n.jsx("div",{style:{fontSize:"12px",lineHeight:1.25,fontWeight:600,color:st,marginBottom:"4px",whiteSpace:"normal",wordBreak:"break-word"},title:Ce,children:Ce}),n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:ut&&n.jsx("span",{style:{fontSize:"12px",fontWeight:700,color:st},children:ut})})]})]})},q.product_id||`${x}-${Ce}`)})}),n.jsxs("div",{className:"admesh-compact-footer-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",flexWrap:"wrap",marginLeft:P?0:Pe},children:[n.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px",minWidth:0,flexWrap:"wrap"},children:Oe}),n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",marginLeft:"auto",flexShrink:0},children:[P&&$.length>F.length?n.jsxs("span",{style:{fontSize:"10px",color:Ae},children:["+",$.length-F.length," more"]}):null,n.jsx("button",{type:"button","aria-label":se?"Recommendation reported":"Report recommendation",title:se?"Reported":"Report recommendation",disabled:!!se,onClick:Re,style:{width:"28px",height:"28px",borderRadius:"999px",border:`1px solid ${ze}`,background:se?jt:We,color:se?De:Ae,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,cursor:se?"default":"pointer",flexShrink:0},children:n.jsx(Ro,{size:13})})]})]}),Ee?n.jsx("div",{className:"admesh-compact-report-panel",onClick:q=>q.stopPropagation(),style:{marginLeft:P?0:Pe,border:`1px solid ${ze}`,borderRadius:"12px",background:jt,padding:"8px",display:"flex",flexWrap:"wrap",gap:"6px"},children:re.map(q=>n.jsx("button",{className:"admesh-compact-report-option",type:"button",onClick:Ce=>I(Ce,q.value),style:{borderRadius:"999px",border:`1px solid ${ze}`,background:We,color:st,fontSize:"11px",fontWeight:600,padding:"6px 9px",cursor:"pointer"},children:q.label},q.value))}):null,se?n.jsx("div",{className:"admesh-compact-report-status",style:{marginLeft:P?0:Pe,fontSize:"11px",color:Ae},children:"Thanks for reporting this recommendation."}):null,je?n.jsxs("div",{style:{marginTop:"2px",border:`1px solid ${ze}`,borderRadius:"12px",background:jt,padding:"12px",display:"flex",flexDirection:"column",gap:"10px"},children:[n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:De},children:"Confirm Agent Access"}),n.jsxs("div",{style:{fontSize:"13px",lineHeight:1.4,color:st,fontWeight:600},children:["Allow ",Y||"this brand"," to start a delegated session?"]}),n.jsx("div",{style:{fontSize:"12px",lineHeight:1.45,color:yt},children:"The agent will only use the details you choose to share for this request."})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[n.jsx("button",{type:"button",disabled:de,onClick:q=>{q.preventDefault(),q.stopPropagation(),!de&&Q(!1)},style:{borderRadius:"10px",border:`1px solid ${ze}`,background:We,color:st,fontSize:"12px",fontWeight:600,padding:"8px 12px",cursor:de?"not-allowed":"pointer",opacity:de?.65:1},children:"Not now"}),n.jsx("button",{type:"button",disabled:de,onClick:q=>{q.preventDefault(),q.stopPropagation(),!de&&Q(!0)},style:{borderRadius:"10px",border:"none",background:De,color:"#ffffff",fontSize:"12px",fontWeight:700,padding:"8px 12px",cursor:de?"wait":"pointer",opacity:de?.86:1},children:de?"Connecting...":"Allow agent"})]})]}):null]})]})},Nr=({recommendations:t,theme:e,className:o,style:s,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})=>{const g=t.filter(c=>c&&typeof c=="object"&&typeof c.recommendation_id=="string"&&c.recommendation_id.length>0);if(!g||g.length===0)return l.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null;l.log(`[AdMeshLayout] Rendering with ${g.length} valid recommendations`);const _=()=>{var c;if(g.length>0){const m=g[0],k=(c=m.recommendation)==null?void 0:c.format;l.log("[AdMeshLayout] ๐ Checking format:",{preferredFormat:k,recommendationKeys:Object.keys(m||{})}),(k==="product_card"||k==="weave"||k==="bridge")&&l.warn(`[AdMeshLayout] ${k} format requested, falling back to tail for canonical render payload`)}return n.jsx(qn,{recommendations:g,theme:e,sessionId:i,onDelegationConsent:d,onDelegationActivated:u,onStartDelegation:w})};return n.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 $r{constructor(e){Ye(this,"firedExposures",new Set);Ye(this,"debug",!1);Ye(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&&l.log("[Tracker] Exposure already fired");return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&l.warn("[Tracker] Failed to fire exposure")}),this.debug&&l.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&l.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,s,i){const d=`${s}_${o}`;if(this.firedExposures.has(d)){this.debug&&l.log("[Tracker] MRC exposure already fired");return}return new Promise(u=>{let w=null,g=null;const _=new IntersectionObserver(k=>{k.forEach(j=>{j.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?w===null&&(w=Date.now(),this.debug&&l.log("[Tracker] Ad reached MRC visibility threshold"),g=setTimeout(()=>{this.fireExposure(e,o,s),_.disconnect(),u()},this.mrcThreshold.minimumDurationMs)):w!==null&&(g&&(clearTimeout(g),g=null),w=null,this.debug&&l.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(),g&&clearTimeout(g),u()},3e4);i.__admeshTrackerCleanup=()=>{_.disconnect(),g&&clearTimeout(g),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&&l.warn("[Tracker] Failed to fire followup engagement (non-critical):",i)}).then(()=>{})}}const On=a.createContext(void 0);function Vn(){const t=a.useContext(On);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function es(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,d=>d.toUpperCase()):"This page"}function Lr(){var t;try{console.log("[AdMesh] Starting direct headings extraction...");const e=_=>_.replace(/\s+/g," ").trim(),o=()=>{var f;const _=["article","main article","main",'[role="main"]',"[data-admesh-article]",".article-content",".post-content",".entry-content",".content"],c=["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(","),j=(((f=_.map(h=>document.querySelector(h)).filter(h=>!!h).map(h=>{const S=h.cloneNode(!0);S.querySelectorAll(c).forEach(K=>K.remove());const T=e(S.textContent||"");return{element:h,text:T}}).filter(h=>h.text.length>=200).sort((h,S)=>S.text.length-h.text.length)[0])==null?void 0:f.element)||document.body).cloneNode(!0);j.querySelectorAll(c).forEach(h=>h.remove());const p=Array.from(j.querySelectorAll("h1, h2, h3, p, li, blockquote")).map(h=>e(h.textContent||"")).filter(h=>h.length>=24);return(p.length>0?p.join(`
|
|
150
150
|
`):e(j.textContent||"")).slice(0,6e3)},s=es(window.location.pathname||"/"),i=e(document.title||"")||s,u=(()=>{const _=[],c=document.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(c).forEach(m=>{const k=e(m.textContent||"");k.length>0&&_.push(k)}),_})(),w=u.length>0?u:[i||s],g={title:i,headings:w,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 ts(t){return!!(t&&typeof t=="object"&&"recommendation_id"in t&&"status"in t)}function ns(t){var s,i,d,u,w,g,_,c,m,k,j;if(!t||typeof t!="object")return;if(ts(t))return t;const e=t;if(!e.recommendation_id)return;const o=(e.products||[]).map(p=>{var x,f;return{product_id:p.product_id||"",product_link:p.product_link||p.product_click_url||e.click_url||e.url||"",product_name:p.product_name||e.title||((x=e.creative_input)==null?void 0:x.product_name)||"",product_description:p.product_description||"",product_price:p.product_price??void 0,product_discount:p.product_discount??void 0,product_currency:p.product_currency,product_discount_type:p.product_discount_type,product_cta_label:p.product_cta_label||((f=e.creative_input)==null?void 0:f.cta_label),product_image_url:p.product_image_url,product_features:p.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:((d=e.creative_input)==null?void 0:d.short_description)||((u=e.creative_input)==null?void 0:u.long_description)||"",cta_text:((w=e.creative_input)==null?void 0:w.cta_label)||((g=o[0])==null?void 0:g.product_cta_label)||"Learn more",follow_up_suggestion:e.follow_up_suggestion,logo_url:(c=(_=e.creative_input)==null?void 0:_.assets)==null?void 0:c.logo_url,image_urls:((k=(m=e.creative_input)==null?void 0:m.assets)==null?void 0:k.image_urls)||[],landing_page_url:e.url||e.click_url||((j=e.creative_input)==null?void 0:j.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 rs(t){return{...t,suggestions:(t.suggestions||[]).map(e=>({...e,recommendation:ns(e.recommendation)}))}}function kr(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 Fr(t,e){var o,s,i,d,u;try{console.log("[AdMesh SDK] Starting ACIE analyze-intent call...",{url:t.url});const w=Array.isArray(t.headings)?t.headings:[],g=(o=kr(t.url))==null?void 0:o.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),_=g?g.replace(/\b\w/g,S=>S.toUpperCase()):void 0,c=e.apiKey.toLowerCase().startsWith("pub_")?kr(t.url):void 0,m=e.extension?"extension":"admesh_ui_sdk",k=(t.domain||(typeof window<"u"?window.location.hostname:"")).trim().toLowerCase(),j={url:t.url,title:t.title||void 0,headings:w.length>0?w:_?[_]:void 0,article_text:((s=t.article_text)==null?void 0:s.trim())||void 0,domain:k,article_slug:c,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:j.url,titleLength:((i=j.title)==null?void 0:i.length)||0,headingsCount:((d=j.headings)==null?void 0:d.length)||0,articleTextLength:((u=j.article_text)==null?void 0:u.length)||0,domain:j.domain,article_slug:j.article_slug,source:j.source,has_user_id:!!j.user_id});const p=`${e.apiBaseUrl}/acie/analyze-intent`;console.log("[AdMesh SDK] Calling ACIE API:",p);const x=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(j)});if(console.log("[AdMesh SDK] ACIE API response received:",{status:x.status,statusText:x.statusText,ok:x.ok}),!x.ok){const S=await x.text();throw console.error("[AdMesh SDK] ACIE API error:",{status:x.status,statusText:x.statusText,errorText:S}),new Error(`ACIE API error: ${x.status} - ${S}`)}const f=await x.json(),h=rs(f);return console.log("[AdMesh SDK] ACIE analysis completed:",{url:t.url,suggestionsCount:h.suggestions.length}),h}catch(w){return console.error("[AdMesh SDK] Error calling ACIE analyze-intent endpoint:",w),null}}async function os(t,e){var d,u;const o=(e.apiBaseUrl||"https://api.useadmesh.com").replace(/\/$/,""),s=new URLSearchParams({url:t.trim()});(d=e.agentDisplayId)!=null&&d.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 w=await i.text().catch(()=>"");throw new Error(`Page context request failed (${i.status}): ${w||i.statusText}`)}return await i.json()}function ss(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function is(){var t;if(typeof window>"u")return null;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Wr(e))return e}catch{return null}return null}function Wr(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 as(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,d=>d.toUpperCase()):e.hostname}catch{return"This page"}}function Sr(t){const e=new URL(t),o=as(t);return{title:o,headings:[o],article_text:`Article URL: ${t}
|
|
151
|
-
Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const ls=6e4,Ar=3;function ds(t){const e=is();if(e)return e;const o=t==null?void 0:t.trim();return Wr(o)?o:null}const Br=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:d,location:u,userId:w,model:g,messages:_,pageContext:c,articleUrl:m,contextMode:k="auto",agentDisplayId:j,children:p})=>{const[x,f]=a.useState(null),[h,S]=a.useState(new Set),[T,K]=a.useState(new Map),[A,C]=a.useState(null),[L,$]=a.useState([]),[F,P]=a.useState(!1),[z,M]=a.useState(null),[W,O]=a.useState(!1),Y=a.useRef(!1),B=a.useRef(0),G=a.useRef(null),te=a.useRef(null);te.current=A;const xe=!!c||k==="ad-slot"||k==="auto"&&(!!(m!=null&&m.trim())||ss()),Z=a.useCallback(async()=>{if(c)return c;if(!xe)return Lr();const N=ds(m);if(!N)return l.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),M("Article URL is required for ad-slot context"),null;if(!t)return l.warn("[AdMeshProvider] Cannot fetch page context: missing API key"),Sr(N);try{O(!0);const Q=await os(N,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:j});return l.log("[AdMeshProvider] Page context resolved",{source:Q.source,cache_hit:Q.cache_hit,domain:Q.context.domain}),Q.context}catch(Q){return l.error("[AdMeshProvider] Failed to fetch page context:",Q),l.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),Sr(N)}finally{O(!1)}},[j,i,t,m,c,xe]),ne=a.useCallback((N,Q)=>{const X=N.filter(ee=>!ee.is_sponsored).slice(0,3);return[Q,...X]},[]),_e=a.useCallback((N,Q)=>{const X=N.find(re=>re.is_sponsored),ee=Q.filter(re=>!re.is_sponsored).slice(0,3);return X?[X,...ee]:ee},[]);a.useEffect(()=>{if(!e||e.trim()===""){l.error("[AdMeshProvider] sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}l.log("[AdMeshProvider] โ
Session ID available:",e)},[e]),a.useEffect(()=>{if(!t){l.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){l.error("[AdMeshProvider] Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const N=new pn({apiKey:t,theme:s,apiBaseUrl:i,extension:o});f(N),l.log("[AdMeshProvider] โ
AdMesh SDK initialized with session:",e),i&&l.log("[AdMeshProvider] ๐ Using custom API base URL")}catch(N){l.error("[AdMeshProvider] Failed to initialize AdMesh SDK:",N)}return()=>{l.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,s,i,e,o]);const Ge=a.useCallback(async N=>{var Q;if(!t){l.warn("[AdMeshProvider] โ ๏ธ Cannot perform intent analysis: missing API key");return}if(o)l.log("[AdMeshProvider] โน๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){l.log('[AdMeshProvider] โน๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{P(!0),M(null),l.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const X=N??await Z();if(!X){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),M("Failed to extract page content");return}l.log("[AdMeshProvider] ๐ Extracted headings:",{title:X.title,headingsCount:X.headings.length,articleTextLength:((Q=X.article_text)==null?void 0:Q.length)||0,domain:X.domain});const re=await Fr(X,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:w});re?(l.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:re.suggestions.length,suggestions:(re.suggestions||[]).map(Re=>{var I;return{id:Re.id,text:Re.text,is_sponsored:Re.is_sponsored,recommendationId:((I=Re.recommendation)==null?void 0:I.recommendation_id)||null}})}),$(Re=>_e(Re,re.suggestions||[]))):(l.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),M("Intent analysis failed"),$(Re=>Re.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),Re):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(X){l.error("[AdMeshProvider] Error in intent analysis:",X),M("Intent analysis error"),$(ee=>ee.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),ee):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{P(!1)}},[t,i,o,w,_e,Z]),je=a.useCallback(async N=>{var ee,re,Re,I,ie,D;if(!x||!t||!t.toLowerCase().startsWith("pub_"))return;const Q=N??await Z();if(!Q){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const X=((re=(ee=Q.headings)==null?void 0:ee[0])==null?void 0:re.trim())||((Re=Q.title)==null?void 0:Re.trim());if(!X){l.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{l.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const ge=await x.fetchPlatformResponse({query:X,sessionId:e,messageId:pn.createMessageId(e),platformSurface:"embedded_assistant",model:g,messages:[],language:d,location:u,userId:w}),E=(D=(ie=(I=ge.recommendation)==null?void 0:I.creative)==null?void 0:ie.follow_up_suggestion)==null?void 0:D.trim(),ce=ge.recommendation_id;if(!E||!ce){l.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const ke={id:ce,text:E,type:"action",is_sponsored:!0,recommendation:ge,metadata:{source:"aip_context_prefetch",recommendation_id:ce}};$(he=>ne(he,ke)),l.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:ce,suggestionText:E})}catch(ge){l.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",ge)}},[t,d,u,g,x,e,w,ne,Z]),ve=a.useCallback(async()=>{l.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await Ge()},[Ge]);a.useEffect(()=>{!x||Y.current||(Y.current=!0,(async()=>{const N=await Z();await Promise.allSettled([je(N),Ge(N)])})())},[x,Ge,je,Z]);const de=a.useCallback(N=>{if(!N||N.status!=="active")return!1;const Q=Date.parse(N.expires_at);return Number.isNaN(Q)?!1:Q>Date.now()},[]),pe=a.useCallback(async(N,Q,X,ee)=>{const re=ee??A;if(!re||!x){l.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:N,eventType:Q,hasSession:!!re,hasSdk:!!x});return}const Re=new Date().toISOString();l.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:N,eventType:Q,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id,sessionId:re.session_id});const I=await fetch(`${x.getApiBaseUrl()}${N}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:re.delegation_session_id,recommendation_id:re.recommendation_id,session_id:re.session_id,event_type:Q,timestamp:Re,metadata:X||{}})});if(!I.ok){const ge=await I.text();throw l.error("[AdMeshProvider] Delegation event failed",{endpoint:N,eventType:Q,status:I.status,errorBody:ge,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id}),new Error(`Delegation event failed (${I.status}): ${ge}`)}const ie=await I.json(),D=ie==null?void 0:ie.session;l.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:N,eventType:Q,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id,returnedStatus:(D==null?void 0:D.status)||(ie==null?void 0:ie.status)}),D&&C(D)},[A,t,x]),Ee=a.useCallback(()=>{B.current=0},[]),ye=a.useCallback(async(N="user_stopped",Q)=>{const X=A;if(!X){l.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}l.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:N,recommendationId:X.recommendation_id,delegationSessionId:X.delegation_session_id}),await pe("/aip/delegation/stop","session_stopped",{reason:N,...Q||{}},X),await(x==null?void 0:x.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:X.session_id,recommendation_id:X.recommendation_id,delegation_session_id:X.delegation_session_id,brand_name:X.brand_name,status:"stopped",metadata:{reason:N,...Q||{}}}).catch(ee=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",ee)})),B.current=0,G.current=null,C(null),l.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},[A,pe,x]),se=a.useCallback(async(N="turn_completed",Q)=>{N==="turn_started"&&Ee(),await pe("/aip/delegation/activity",N,Q)},[pe,Ee]);a.useEffect(()=>{const N=(A==null?void 0:A.delegation_session_id)??null;N!==G.current&&(G.current=N,B.current=0)},[A==null?void 0:A.delegation_session_id]),a.useEffect(()=>{if(!((A==null?void 0:A.delegation_session_id)??null)||!x)return;const Q=te.current;if(!Q||!de(Q)){C(ee=>ee?{...ee,status:"expired"}:null);return}const X=window.setInterval(()=>{const ee=te.current;if(!(!ee||!de(ee))){if(B.current+=1,B.current>=Ar){l.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:ee.delegation_session_id,heartbeatsSinceLastUserTurn:B.current,idleHeartbeatLimit:Ar}),ye("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:B.current}).catch(re=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to stop idle delegation session:",re)});return}pe("/aip/delegation/heartbeat","heartbeat").catch(re=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",re)})}},ls);return()=>{window.clearInterval(X)}},[A==null?void 0:A.delegation_session_id,de,pe,x,ye]);const bt={sdk:x,apiKey:t,sessionId:e,theme:s,language:d,location:u,userId:w,model:g,messages:_,processedMessageIds:h,recommendationResults:T,activeDelegationSession:A,suggestions:L,isAnalyzingIntent:F||W,intentError:z,markMessageAsProcessed:N=>{S(Q=>{const X=new Set(Q);return X.add(N),X})},isMessageProcessed:N=>h.has(N),setRecommendationResult:(N,Q)=>{K(X=>{const ee=new Map(X);return ee.set(N,Q),ee}),S(X=>{const ee=new Set(X);return ee.add(N),ee})},getRecommendationResult:N=>T.get(N),hasRecommendationResult:N=>T.has(N),setActiveDelegationSession:N=>{C(N)},getActiveDelegationSession:()=>de(A)?A:null,hasActiveDelegationSession:()=>de(A),refreshDelegationActivity:se,stopDelegationSession:ye,retryIntentAnalysis:ve};return n.jsx(On.Provider,{value:bt,children:p})};class Ur{constructor(){Ye(this,"roots",new Map)}async render(e){try{l.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){l.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw l.error("[AdMeshRenderer] Container not found"),new Error(`Container with ID "${e.containerId}" not found`);l.log("[AdMeshRenderer] โ
Container ready");const i=this.roots.get(e.containerId);i&&(l.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const d=yo.createRoot(s);l.log("[AdMeshRenderer] ๐ Rendering recommendations"),d.render(n.jsx(Br,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:n.jsx(Nr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",l.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,d)}catch(o){throw l.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 cs=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},Mt=class Mt{constructor(e){Ye(this,"config");Ye(this,"apiBaseUrl");Ye(this,"renderer",null);Ye(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 Mt.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),d=i[i.length-1];return d?`session_${Date.now()}_${d}`:Mt.createSession()}catch{return Mt.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 Ur),this.renderer}getTracker(){return this.tracker||(this.tracker=new $r({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const d=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(!d.ok){const w=await d.text();throw new Error(`Delegation event failed (${d.status}): ${w}`)}const u=await d.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(),d=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:d,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 l.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var f,h,S,T,K,A,C,L,$,F,P,z,M;const o=`${this.apiBaseUrl}/aip/context`;if(l.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const W=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw l.error("[AdMeshSDK] sessionId not provided by platform - cannot process request"),W}const s=e.messageId;if(!s||s.trim()===""){const W=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw l.error("[AdMeshSDK] messageId not provided by platform - cannot process request"),W}const i=Mt.buildPlatformResponseCacheKey(e.sessionId,s),d=Mt.inFlightPlatformResponses.get(i);if(d)return l.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),d;const u=e.messages?e.messages.length:0,w=(typeof window<"u"&&window.navigator,"web"),g=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",_=cs((f=e.location)==null?void 0:f.countryCode)||"US",c=typeof window<"u"&&window.location?{url:window.location.href,origin:window.location.origin,referrer:document.referrer||void 0,host:window.location.hostname}:void 0,m=e.userId??this.config.userId,k={spec_version:"1.0",message_id:s,timestamp:new Date().toISOString(),platform:{platform_id:"placeholder",role:"platform",software:{name:"admesh_ui_sdk",version:e.model||"1.0.0"}},identity:{namespace:"platform_user",value_hash:m||"",confidence:m?1:0},consent:{status:"granted",source:"admesh_ui_sdk",scope:{intent_based_monetization:!0,agent_participation:!0,measurement:!0},constraints:{allow_identity_downstream:!1}},classification_input:{type:"interaction",interaction:{session:{id:e.sessionId,turn_index:u},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:w,form_factor:g,locale:e.language||"en-US",country:_,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((h=e.location)==null?void 0:h.city)||void 0,state:((S=e.location)==null?void 0:S.state)||void 0,state_code:((T=e.location)==null?void 0:T.stateCode)||void 0,country:((K=e.location)==null?void 0:K.country)||void 0,country_code:_,zipcode:((A=e.location)==null?void 0:A.zipcode)||void 0,latitude:(C=e.location)==null?void 0:C.latitude,longitude:(L=e.location)==null?void 0:L.longitude},page:c}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(F=($=k.classification_input.interaction)==null?void 0:$.input.query_text)!=null&&F.trim()||l.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const j=JSON.stringify(k);l.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:k.message_id,specVersion:k.spec_version,classificationType:k.classification_input.type,platformId:k.platform.platform_id,surfaceChannel:(P=k.classification_input.interaction)==null?void 0:P.surface.channel,sessionId:(M=(z=k.classification_input.interaction)==null?void 0:z.session)==null?void 0:M.id});const p={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){p["X-AdMesh-Source"]="extension";const W=this.getExtensionSourceDomain();W&&(p["X-AdMesh-Source-Domain"]=W)}const x=(async()=>{const W=await fetch(o,{method:"POST",headers:p,body:j});if(!W.ok){const B=(await W.json().catch(()=>({}))).detail||`HTTP ${W.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${B}`)}const O=await W.json();return l.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{status:O.status,recommendationId:O.recommendation_id,hasRecommendation:!!O.recommendation,hasTracking:!!O.tracking,hasDelegation:!!O.delegation,topLevelKeys:Object.keys(O)}),l.log("[AdMeshSDK] ๐ฆ Full PlatformResponse received from /aip/context",O),O})();Mt.inFlightPlatformResponses.set(i,x);try{return await x}finally{Mt.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)}};Ye(Mt,"inFlightPlatformResponses",new Map);let pn=Mt;class Kn{constructor(e={}){Ye(this,"autoAddLabels");Ye(this,"fireExposurePixels");Ye(this,"labelStyle");Ye(this,"processedLinks",new Set);Ye(this,"mutationObserver",null);var o,s,i,d;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:((d=e.labelStyle)==null?void 0:d.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 d=this.getLinksToProcess(e),u=new Map(o.map(g=>{var _,c,m;return[((_=g==null?void 0:g.tracking)==null?void 0:_.click_url)||((m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url)||"",g]}).filter(([g])=>!!g)),w=new Map;o.forEach(g=>{var c,m;const _=(m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url;if(_&&typeof _=="string"){const k=_.trim().replace(/\/$/,"");w.set(k,g),w.set(`${k}/`,g)}}),d.forEach(g=>{var j,p,x,f,h,S,T,K;const _=g.getAttribute("href")||"",c=`${_}`;if(this.processedLinks.has(c))return;let m=u.get(_),k=_;if(!m){const A=_.trim().replace(/\/$/,"");m=w.get(A)||w.get(`${A}/`);const C=((j=m==null?void 0:m.tracking)==null?void 0:j.click_url)||((x=(p=m==null?void 0:m.recommendation)==null?void 0:p.creative)==null?void 0:x.landing_page_url);m&&C&&(l.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",_),g.setAttribute("href",C),k=C)}if(m){this.processedLinks.add(c),g.setAttribute("target","_blank"),g.setAttribute("rel","noopener noreferrer");const A={element:g,href:k,text:g.textContent||"",hasAdLabel:this.hasAdLabel(g),matchedRecommendation:{recommendation_id:(m==null?void 0:m.recommendation_id)||"",click_url:((f=m==null?void 0:m.tracking)==null?void 0:f.click_url)||((S=(h=m==null?void 0:m.recommendation)==null?void 0:h.creative)==null?void 0:S.landing_page_url)||"",exposure_url:(T=m==null?void 0:m.tracking)==null?void 0:T.exposure_url}};this.autoAddLabels&&!A.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",k),this.addAdLabel(g),A.hasAdLabel=!0):this.autoAddLabels?A.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const C=(K=m==null?void 0:m.tracking)==null?void 0:K.exposure_url;this.fireExposurePixels&&C&&s&&A.matchedRecommendation&&s({exposureUrl:C,recommendationId:A.matchedRecommendation.recommendation_id,linkElement:g}),i.push(A)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const w=u.getAttribute("href")||"",g=`${w}`;if(this.processedLinks.has(g))return;if(this.isAdMeshLink(w)){this.processedLinks.add(g);const c={element:u,href:w,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:void 0};if(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to pattern-matched AdMesh link:",w),this.addAdLabel(u),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const m=this.convertClickUrlToExposureUrl(w);s({exposureUrl:m,recommendationId:this.extractRecommendationIdFromUrl(w),linkElement:u})}i.push(c)}});return i}hasAdLabel(e){var u,w,g;if((e.textContent||"").includes("Ad"))return l.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 l.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 l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const _=i,c=_.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((w=_.textContent)!=null&&w.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",c),!0}let d=e.nextSibling;for(;d&&d.nodeType===Node.TEXT_NODE;){const _=d.textContent||"";if(_.trim()===""){d=d.nextSibling;continue}if(_.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(d&&d.nodeType===Node.ELEMENT_NODE){const _=d,c=_.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((g=_.textContent)!=null&&g.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next element sibling:",c),!0}return l.log("[WeaveResponseProcessor] โน๏ธ No existing Ad label found"),!1}addAdLabel(e){if(l.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){l.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){l.log("[WeaveResponseProcessor] โน๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){l.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 d=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",d);try{const u=e.nextSibling;u?(o.insertBefore(s,u),l.log("[WeaveResponseProcessor] โ
Ad label inserted before next sibling")):(o.appendChild(s),l.log("[WeaveResponseProcessor] โ
Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?l.log("[WeaveResponseProcessor] โ
Ad label successfully added to link:",e.href):l.error("[WeaveResponseProcessor] Ad label insertion failed - label not in DOM")}catch(u){l.error("[WeaveResponseProcessor] Error inserting Ad label:",u)}}removeLeftAdLabel(e){var s,i,d;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"))&&((d=u.parentNode)==null||d.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`,d=new URLSearchParams(o.search);return d.has("cpx")||d.set("cpx","0"),`${i}?${d.toString()}`}catch{return l.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 on(){const t=Vn();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 us=({className:t,size:e=20})=>n.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:[n.jsx("path",{d:"M5 12h14"}),n.jsx("path",{d:"M12 5v14"})]}),Hr=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var k,j,p,x,f;const d=(j=(k=t.recommendation)==null?void 0:k.creative)!=null&&j.follow_up_suggestion&&((p=t.tracking)!=null&&p.followup_engagement_url)&&((x=t.tracking)!=null&&x.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=d==null?void 0:d.query,w=d==null?void 0:d.engagement_url,g=d==null?void 0:d.exposure_url,_=t.recommendation_id,c=((f=t.recommendation)==null?void 0:f.offerId)||_;if(!u||!w||!g)return l.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const m=async()=>{try{w&&_&&(l.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(w,_,s)),i&&u?(l.log(`[AdMeshFollowup] ๐ Executing query: ${u}`),await i(u)):l.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(h){l.error("[AdMeshFollowup] Error handling follow-up click:",h)}};return n.jsx(hn,{productId:c,recommendationId:_||"",exposureUrl:g,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:n.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[n.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),n.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:h=>{(h.key==="Enter"||h.key===" ")&&m()},"aria-label":`Sponsored follow-up: ${u}`,children:[n.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),n.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),n.jsx(us,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},nn=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:d,triggerExposureUrl:u=!0,followups_container_id:w,onPasteToInput:g,onDelegationConsent:_,onDelegationActivated:c,onStartDelegation:m,onRecommendationReport:k,onExecuteQuery:j,onFollowupDetected:p,isContainerReady:x})=>{var X,ee,re,Re;const{sdk:f,sessionId:h,apiKey:S,language:T,location:K,userId:A,model:C,messages:L,theme:$,getRecommendationResult:F,hasRecommendationResult:P,setRecommendationResult:z,activeDelegationSession:M,setActiveDelegationSession:W,hasActiveDelegationSession:O}=on(),Y=I=>!!I&&I.status==="generated"&&!!I.recommendation,B=i||A,[G,te]=a.useState(null),[xe,Z]=a.useState(null),[ne,_e]=a.useState(!0),[Ge,je]=a.useState(null),ve=a.useRef(null),de=a.useRef(!1),pe=a.useRef(!1),Ee=a.useRef(t),ye=a.useRef(e);a.useEffect(()=>{Ee.current=t,ye.current=e},[t,e]),a.useEffect(()=>{ve.current!==o&&(ve.current=null,pe.current=!1,te(null),Z(null))},[o]);const se=O()&&(M==null?void 0:M.session_id)===h;a.useEffect(()=>{var D,ge,E;if(!o||!P(o)||se)return;const I=F(o);if(!I){l.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),te(null),Z(null),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0;return}let ie=((D=I.recommendation)==null?void 0:D.format)||"tail";(ie==="weave"||ie==="product_card")&&(ie="tail"),l.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:I.recommendation_id,format:(ge=I.recommendation)==null?void 0:ge.format}),te(I),Z(ie),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0,(E=Ee.current)==null||E.call(Ee,o,I)},[F,P,se,o]),a.useEffect(()=>{var I,ie,D,ge,E,ce,ke;if(!(!d||!o)&&!se)try{const he=d,We=d.status||"unknown";if(!Y(he)){if(We==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),te(null),Z(null),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${We})`)}let ze=((I=he.recommendation)==null?void 0:I.format)||"tail";(ze==="weave"||ze==="product_card")&&(ze="tail"),te(he),Z(ze),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0,z(o,he),(ie=Ee.current)==null||ie.call(Ee,o,he),l.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),l.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:he.recommendation_id,format:(D=he.recommendation)==null?void 0:D.format,brandName:(E=(ge=he.recommendation)==null?void 0:ge.creative)==null?void 0:E.brand_name,headline:(ke=(ce=he.recommendation)==null?void 0:ce.creative)==null?void 0:ke.headline,hasTracking:!!he.tracking})}catch(he){const We=he instanceof Error?he:new Error(String(he));pe.current=!1,l.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${We.message}`)}},[se,d,o,z]),a.useEffect(()=>{if(!o||!s||s.trim()===""){l.log("[AdMeshRecommendations] Validation failed - missing required parameters"),_e(!1);return}if(se){l.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:h,delegationSessionId:M==null?void 0:M.delegation_session_id}),te(null),Z(null),je(null),_e(!1),de.current=!1;return}if(!(f!=null&&f.fetchPlatformResponse)){l.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),_e(!1);return}if(pe.current){l.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(ve.current===o){l.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(de.current){l.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}l.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var ie,D,ge,E,ce,ke,he,We,ze;try{de.current=!0,_e(!0),je(null);const Se=await f.fetchPlatformResponse({query:s.trim(),sessionId:h,messageId:o,language:T,location:K,userId:B,model:C,...L&&L.length>0&&{messages:L}}),De=(Se==null?void 0:Se.status)||"unknown";if(!Y(Se)){if(De==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),te(null),Z(null),je(null),_e(!1),de.current=!1,ve.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${De})`)}te(Se),l.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:Se.recommendation_id,format:(ie=Se.recommendation)==null?void 0:ie.format,brandName:(ge=(D=Se.recommendation)==null?void 0:D.creative)==null?void 0:ge.brand_name,headline:(ce=(E=Se.recommendation)==null?void 0:E.creative)==null?void 0:ce.headline,hasTracking:!!Se.tracking});let Ae=((ke=Se.recommendation)==null?void 0:ke.format)||"tail";(Ae==="weave"||Ae==="product_card")&&(Ae="tail"),Z(Ae),ve.current=o,z(o,Se),l.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(he=Se.recommendation)==null?void 0:he.format,selected_format:Ae}),_e(!1),de.current=!1,(We=Ee.current)==null||We.call(Ee,o,Se)}catch(Se){const De=Se instanceof Error?Se:new Error(String(Se));De.message.includes("Failed to fetch")||De.message.includes("NetworkError")?l.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${De.message} `):l.error(`[AdMeshRecommendations] Error fetching recommendations: ${De.message} `),je(De),_e(!1),de.current=!1,(ze=ye.current)==null||ze.call(ye,De)}})()},[M==null?void 0:M.delegation_session_id,se,f,h,o,s,T,K,B,C,d,z]),a.useEffect(()=>{var ie,D,ge,E;if(!G||!p)return;const I=(D=(ie=G.recommendation)==null?void 0:ie.creative)!=null&&D.follow_up_suggestion&&((ge=G.tracking)!=null&&ge.followup_engagement_url)&&((E=G.tracking)!=null&&E.followup_exposure_url)?{label:G.recommendation.creative.follow_up_suggestion,query:G.recommendation.creative.follow_up_suggestion,engagement_url:G.tracking.followup_engagement_url,exposure_url:G.tracking.followup_exposure_url}:null;I&&p(I,G.recommendation_id)},[G,p]);const bt=a.useCallback(async I=>{if(!f||!h)throw new Error("AdMesh SDK activation requires an initialized session");const ie=await fetch(`${f.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({session_id:h,recommendation_id:I.recommendation_id,metadata:I.metadata})});if(!ie.ok){const ce=await ie.text();throw new Error(`Failed to activate delegation session: ${ie.status} ${ce}`)}const D=await ie.json(),ge={...I,delegation_session_id:D.delegation_session_id||I.delegation_session_id,session_id:D.session_id||h,brand_id:D.brand_id||I.brand_id,brand_name:D.brand_name||I.brand_name,mcp_endpoint:D.mcp_endpoint,eligibility_reason:D.eligibility_reason||I.eligibility_reason,delegate_reason:D.delegate_reason||I.delegate_reason,session_goal:D.session_goal||I.session_goal,desired_outcome_type:D.desired_outcome_type||I.desired_outcome_type,required_user_inputs:D.required_user_inputs||I.required_user_inputs||[],required_consent_types:D.required_consent_types||I.required_consent_types||[],success_outcome:D.success_outcome||I.success_outcome,fallback_message:D.fallback_message||I.fallback_message,session_mode:"inline",status:D.status||"active",capabilities:D.capabilities||I.capabilities||[],allowed_data_types:D.allowed_data_types||I.allowed_data_types||[],auth_model:D.auth_model||I.auth_model,handoff_protocol:D.handoff_protocol||I.handoff_protocol,supported_actions:D.supported_actions||I.supported_actions||[],metadata:D.metadata||I.metadata},E={delegation_session_id:D.delegation_session_id,recommendation_id:I.recommendation_id,session_id:D.session_id||h,brand_agent_id:D.brand_agent_id,brand_id:D.brand_id||I.brand_id,brand_name:D.brand_name||I.brand_name||"Brand",mcp_endpoint:D.mcp_endpoint,status:D.status||"active",activated_at:D.created_at,last_activity_at:D.updated_at,expires_at:D.expires_at||D.updated_at,eligibility_reason:D.eligibility_reason||I.eligibility_reason,delegate_reason:D.delegate_reason||I.delegate_reason,session_goal:D.session_goal||I.session_goal,desired_outcome_type:D.desired_outcome_type||I.desired_outcome_type,required_user_inputs:D.required_user_inputs||I.required_user_inputs||[],required_consent_types:D.required_consent_types||I.required_consent_types||[],success_outcome:D.success_outcome||I.success_outcome,fallback_message:D.fallback_message||I.fallback_message,capabilities:D.capabilities||I.capabilities||[],allowed_data_types:D.allowed_data_types||I.allowed_data_types||[],consent_requirements:D.consent_requirements||I.consent_requirements||[],auth_model:D.auth_model||I.auth_model,handoff_protocol:D.handoff_protocol||I.handoff_protocol,supported_actions:D.supported_actions||I.supported_actions||[],metadata:D.metadata||I.metadata};if(W(E),await f.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:h,recommendation_id:I.recommendation_id,delegation_session_id:D.delegation_session_id,brand_name:E.brand_name,status:D.status||"active",metadata:{brand_agent_id:D.brand_agent_id,source:"recommendation_card"}}).catch(ce=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",ce)}),await f.reportDelegationSessionStarted(E,{brand_agent_id:D.brand_agent_id,brand_name:E.brand_name}).then(ce=>{ce&&W(ce)}).catch(ce=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",ce)}),c){try{await c(ge)}catch(ce){l.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",ce)}return}if(m)try{await m({...I.platform_response,delegation:{...I.platform_response.delegation,...ge,delegation_session_id:D.delegation_session_id,available:!0,status:D.status||"active"}})}catch(ce){l.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",ce)}},[S,c,m,f,h,W]),N=a.useCallback(async I=>{var ie,D;if(k){await k(I);return}!f||!h||await f.reportSponsoredRecommendation({session_id:h,message_id:o,recommendation_id:I.recommendation_id,reason:I.reason,brand_name:(D=(ie=I.recommendation.recommendation)==null?void 0:ie.creative)==null?void 0:D.brand_name,metadata:{reason:I.reason,source:"recommendation_card"}}).catch(ge=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report sponsored recommendation:",ge)})},[o,k,f,h]);if(!o||!s||s.trim()===""||ne||Ge)return null;if(!G||!xe)return l.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!G,detectedFormat:xe,isLoading:ne,hasError:!!Ge}),null;l.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:G.recommendation_id,detectedFormat:xe,brandName:(ee=(X=G.recommendation)==null?void 0:X.creative)==null?void 0:ee.brand_name,headline:(Re=(re=G.recommendation)==null?void 0:re.creative)==null?void 0:Re.headline});const Q=typeof document<"u"&&w&&(x??!0)?document.getElementById(w):null;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:n.jsx(qn,{recommendations:[G],theme:$,sessionId:h,triggerExposureUrl:u,onPasteToInput:g,onDelegationConsent:_,onDelegationActivated:bt,onStartDelegation:m,onRecommendationReport:N})}),Q&&f&&h?Hn.createPortal(n.jsx(Hr,{recommendation:G,theme:$,sdk:f,sessionId:h,onExecuteQuery:j}),Q):null]})},qr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:d})=>{const{sdk:u,sessionId:w,theme:g,apiKey:_,language:c,location:m,userId:k,model:j,messages:p}=on(),x=a.useRef(null),[f,h]=a.useState("");return a.useEffect(()=>{o&&h(`admesh-weave-fallback-${o}`)},[o]),l.log("[WeaveFallbackRecommendations] ๐จ Component render"),a.useEffect(()=>{if(l.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:i,hasPreviousRecommendations:d&&d.length>0,previousRecommendationsCount:(d==null?void 0:d.length)||0}),!i){l.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(l.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){l.log("[WeaveFallbackRecommendations] Validation failed - returning early");return}if(l.log("[WeaveFallbackRecommendations] โ
Validation passed"),!u||!f){l.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const S=d&&d.length>0;l.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:S,count:(d==null?void 0:d.length)||0,fallback:i,messageId:o}),S?(l.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${d.length} previous recommendation(s), skipping API call`),(async()=>{var K,A,C,L,$,F,P;try{const z=d[0];if(l.log("[WeaveFallbackRecommendations] ๐ฆ Processing AIP response:",{hasAipResponse:!!z,recommendationId:(z==null?void 0:z.recommendation_id)||"",format:((K=z==null?void 0:z.recommendation)==null?void 0:K.format)||"unknown"}),z&&process.env.NODE_ENV==="development"&&l.log("[WeaveFallbackRecommendations] ๐ Recommendation received (DEV):",{recommendation_id:z==null?void 0:z.recommendation_id,click_url:((A=z==null?void 0:z.tracking)==null?void 0:A.click_url)||((L=(C=z==null?void 0:z.recommendation)==null?void 0:C.creative)==null?void 0:L.landing_page_url),format:($=z==null?void 0:z.recommendation)==null?void 0:$.format,full_response:z}),!z){l.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o});return}const M=u,W=M.getRenderer,O=M.getTracker,Y=(F=M.config)==null?void 0:F.theme;if(W&&O){const B={sessionId:w,messageId:o,recommendations:[z]},G=W.call(u),te=O.call(u),xe=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await G.render({containerId:f,response:B,theme:g||Y,tracker:te,sessionId:w,apiKey:_||((P=u==null?void 0:u.config)==null?void 0:P.apiKey),apiBaseUrl:xe,language:c,location:m,userId:k,model:j,messages:p}),l.log("[WeaveFallbackRecommendations] โ
Recommendations rendered from previous response (no API call)")}else l.warn("[WeaveFallbackRecommendations] โ ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch(z){const M=z instanceof Error?z:new Error(String(z));l.error(`[WeaveFallbackRecommendations] Error rendering previous recommendations: ${M.message}`);try{await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch{e==null||e(M)}}})()):(l.log("[WeaveFallbackRecommendations] ๐ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){l.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o}),l.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(K){const A=K instanceof Error?K:new Error(String(K));l.log(`[WeaveFallbackRecommendations] Error: ${A.message}`),e==null||e(A)}})())},[u,w,f,t,o,s,i,e,d,g]),!i||!o||!s||s.trim()===""?null:n.jsx("div",{ref:x,id:f,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Or=a.createContext(void 0),ms=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>n.jsx(Or.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),ps=()=>a.useContext(Or),Nn=t=>{try{return new URL(t),!0}catch{return!1}},Cr=t=>t&&t.trim()?t.trim():"",Bt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",gt=t=>Bt(t)||void 0,hs=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},fs=(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 Bt(t)},gs=(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=Bt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},be={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"},xs=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:g,onPasteToInput:_})=>{var E,ce,ke,he,We,ze,Se,De,Ae,yt,st,jt,Pe,Oe,fe,it,Et,Rt,H,at,wt,Lt,Ut,q,Ce,Qe,ut,Tt,It,Ht,Dt,_t,Xe;if(!t||t.length===0)return l.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],m=((E=c==null?void 0:c.recommendation)==null?void 0:E.offerId)||"",k=((ce=c==null?void 0:c.tracking)==null?void 0:ce.exposure_url)||"",j=(c==null?void 0:c.recommendation_id)||"",p=((he=(ke=c==null?void 0:c.recommendation)==null?void 0:ke.creative)==null?void 0:he.description)||"",x=((We=c==null?void 0:c.recommendation)==null?void 0:We.disclosure)||"Sponsored",f=((Se=(ze=c==null?void 0:c.recommendation)==null?void 0:ze.creative)==null?void 0:Se.brand_name)||"",h=((Ae=(De=c==null?void 0:c.recommendation)==null?void 0:De.creative)==null?void 0:Ae.headline)||((st=(yt=c==null?void 0:c.recommendation)==null?void 0:yt.creative)==null?void 0:st.brand_name)||"",S=((Pe=(jt=c==null?void 0:c.recommendation)==null?void 0:jt.creative)==null?void 0:Pe.logo_url)||"",T=((Oe=c==null?void 0:c.tracking)==null?void 0:Oe.click_url)||((it=(fe=c==null?void 0:c.recommendation)==null?void 0:fe.creative)==null?void 0:it.landing_page_url)||"",K=Cr((Rt=(Et=c==null?void 0:c.recommendation)==null?void 0:Et.creative)==null?void 0:Rt.cta_text),A=((at=(H=c==null?void 0:c.recommendation)==null?void 0:H.creative)==null?void 0:at.products)||[],C=A.length>1,L=C?A.slice(0,4):[],$=((wt=c==null?void 0:c.recommendation)==null?void 0:wt.format)||"tail",F=$==="bridge",P=((Lt=c==null?void 0:c.delegation)==null?void 0:Lt.brand_name)||f,z=((Ut=c==null?void 0:c.delegation)==null?void 0:Ut.available)===!0,M=F&&z,W="Talk to Agent",O=!C&&!!K&&!!T;if(!f&&!h&&!p)return l.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:f,hasFirstRecommendation:!!c,recommendationId:j,recommendationKeys:c?Object.keys(c):[]}),null;let Y=f,B="";h&&h!==f&&(B=h),B&&(Y=`${f} โ ${B}`),l.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:j,productId:m,exposureUrl:k?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:T||"MISSING",clickUrlSource:(q=c==null?void 0:c.tracking)!=null&&q.click_url?"tracking.click_url":(Qe=(Ce=c==null?void 0:c.recommendation)==null?void 0:Ce.creative)!=null&&Qe.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:p?"present":"MISSING",brandName:f,productName:h,headlineText:Y,triggerExposureUrl:d}),l.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:j,brandName:f,productName:h,hasDescription:!!p,hasClickUrl:!!T,hasLogoUrl:!!S,recommendationFormat:$});const G=(V,Ne)=>{Ne&&Ne.stopPropagation(),l.log(`AdMesh tail ad ${V} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:j,productId:m,clickUrl:T,source:V}).catch(()=>{l.error(`[AdMesh] Failed to track ${V} click`)})},te=V=>{V.stopPropagation(),G("tail_ad_brand_name")},xe=V=>{V.stopPropagation(),G("tail_ad_cta")},Z=V=>{V.stopPropagation(),G("tail_ad_logo")},ne=()=>{C||!T||(G("tail_ad_card"),typeof window<"u"&&window.open(T,"_blank","noopener,noreferrer"))},_e=V=>{C||!T||(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),ne())},[Ge,je]=a.useState(!1),[ve,de]=a.useState(!1),pe=a.useRef(null);a.useEffect(()=>()=>{pe.current&&(pe.current(!1),pe.current=null)},[]);const Ee=V=>{var Ne;V&&de(!0),(Ne=pe.current)==null||Ne.call(pe,V),pe.current=null,V||(de(!1),je(!1))},ye=async()=>u?await u(c):await new Promise(V=>{pe.current=V,je(!0)}),se=async()=>{if(j&&i)try{const V=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",Ne=await fetch(`${V}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:j,session_id:i,is_test:!1})});Ne.ok||l.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",Ne.statusText)}catch(V){l.error("[AdMesh Tail Ad] Error tracking delegation engagement:",V)}},bt=async V=>{var kt,Pt,qt,St;if(V.preventDefault(),V.stopPropagation(),!c||!M)return;if(G("tail_ad_delegation_cta"),!await ye()){l.log("[AdMesh Tail Ad] Delegation consent declined");return}se();const ae=c.delegation,vt=ae!=null&&ae.available?{recommendation_id:c.recommendation_id,brand_id:gt(ae.brand_id),brand_name:gt(ae.brand_name||((Pt=(kt=c.recommendation)==null?void 0:kt.creative)==null?void 0:Pt.brand_name)),mcp_endpoint:gt(ae.mcp_endpoint),eligibility_reason:gt(ae.eligibility_reason),delegate_reason:gt(ae.delegate_reason),session_goal:gt(ae.session_goal),desired_outcome_type:ae.desired_outcome_type,required_user_inputs:Array.isArray(ae.required_user_inputs)?ae.required_user_inputs.filter(mt=>typeof mt=="string"):[],required_consent_types:Array.isArray(ae.required_consent_types)?ae.required_consent_types.filter(mt=>typeof mt=="string"):[],success_outcome:gt(ae.success_outcome),fallback_message:gt(ae.fallback_message),session_mode:gt(ae.session_mode),status:gt(ae.status),capabilities:ae.capabilities||[],allowed_data_types:ae.allowed_data_types||[],consent_requirements:ae.consent_requirements||[],auth_model:gt(ae.auth_model),handoff_protocol:ae.handoff_protocol&&typeof ae.handoff_protocol=="object"?ae.handoff_protocol:void 0,supported_actions:ae.supported_actions||[],metadata:ae.metadata&&typeof ae.metadata=="object"?ae.metadata:void 0,platform_response:c}:null;if(w&&vt){try{await w(vt)}finally{de(!1),je(!1)}return}if(g){try{await g(c)}finally{de(!1),je(!1)}return}const rt=((St=(qt=c.recommendation)==null?void 0:qt.creative)==null?void 0:St.follow_up_suggestion)||"";if(rt&&_){_(rt),de(!1),je(!1);return}if(rt&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(rt),de(!1),je(!1);return}de(!1),je(!1)},[N,Q]=a.useState(!1),X=f?f.charAt(0).toUpperCase():"B",ee=be.surface,re=be.border,Re=(e==null?void 0:e.borderRadius)||((Tt=(ut=e==null?void 0:e.components)==null?void 0:ut.card)==null?void 0:Tt.borderRadius)||"8px",I="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",ie="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",D=((It=e==null?void 0:e.shadows)==null?void 0:It.medium)||((Dt=(Ht=e==null?void 0:e.components)==null?void 0:Ht.card)==null?void 0:Dt.boxShadow)||I,ge=((_t=e==null?void 0:e.shadows)==null?void 0:_t.large)||ie;return n.jsxs(hn,{productId:m,recommendationId:j,exposureUrl:k,sessionId:i,triggerExposureUrl:d,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:[n.jsx("style",{children:`
|
|
151
|
+
Article topic inferred from URL path: ${o}`,url:t,domain:e.hostname,extracted_at:new Date().toISOString()}}const ls=6e4,Ar=3;function ds(t){const e=is();if(e)return e;const o=t==null?void 0:t.trim();return Wr(o)?o:null}const Br=({apiKey:t,sessionId:e,extension:o,theme:s,apiBaseUrl:i,language:d,location:u,userId:w,model:g,messages:_,pageContext:c,articleUrl:m,contextMode:k="auto",agentDisplayId:j,children:p})=>{const[x,f]=a.useState(null),[h,S]=a.useState(new Set),[T,K]=a.useState(new Map),[A,C]=a.useState(null),[L,$]=a.useState([]),[F,P]=a.useState(!1),[z,M]=a.useState(null),[W,O]=a.useState(!1),Y=a.useRef(!1),B=a.useRef(0),G=a.useRef(null),te=a.useRef(null);te.current=A;const xe=!!c||k==="ad-slot"||k==="auto"&&(!!(m!=null&&m.trim())||ss()),Z=a.useCallback(async()=>{if(c)return c;if(!xe)return Lr();const N=ds(m);if(!N)return l.warn("[AdMeshProvider] Ad-slot context mode requires a real article URL"),M("Article URL is required for ad-slot context"),null;if(!t)return l.warn("[AdMeshProvider] Cannot fetch page context: missing API key"),Sr(N);try{O(!0);const Q=await os(N,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",agentDisplayId:j});return l.log("[AdMeshProvider] Page context resolved",{source:Q.source,cache_hit:Q.cache_hit,domain:Q.context.domain}),Q.context}catch(Q){return l.error("[AdMeshProvider] Failed to fetch page context:",Q),l.warn("[AdMeshProvider] Falling back to URL-path context for suggestions"),Sr(N)}finally{O(!1)}},[j,i,t,m,c,xe]),ne=a.useCallback((N,Q)=>{const X=N.filter(ee=>!ee.is_sponsored).slice(0,3);return[Q,...X]},[]),_e=a.useCallback((N,Q)=>{const X=N.find(re=>re.is_sponsored),ee=Q.filter(re=>!re.is_sponsored).slice(0,3);return X?[X,...ee]:ee},[]);a.useEffect(()=>{if(!e||e.trim()===""){l.error("[AdMeshProvider] sessionId is required and must be provided by the platform. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}l.log("[AdMeshProvider] โ
Session ID available:",e)},[e]),a.useEffect(()=>{if(!t){l.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}if(!e||e.trim()===""){l.error("[AdMeshProvider] Cannot initialize SDK: sessionId is required. Use AdMeshSDK.generateSessionIdFromUrl() for URL-based detection.");return}try{const N=new pn({apiKey:t,theme:s,apiBaseUrl:i,extension:o});f(N),l.log("[AdMeshProvider] โ
AdMesh SDK initialized with session:",e),i&&l.log("[AdMeshProvider] ๐ Using custom API base URL")}catch(N){l.error("[AdMeshProvider] Failed to initialize AdMesh SDK:",N)}return()=>{l.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,s,i,e,o]);const Ge=a.useCallback(async N=>{var Q;if(!t){l.warn("[AdMeshProvider] โ ๏ธ Cannot perform intent analysis: missing API key");return}if(o)l.log("[AdMeshProvider] โน๏ธ Extension mode: allowing intent analysis for any API key");else if(!t.toLowerCase().startsWith("pub_")){l.log('[AdMeshProvider] โน๏ธ Skipping auto intent analysis: API key does not start with "pub_"');return}try{P(!0),M(null),l.log("[AdMeshProvider] ๐ Starting automatic intent analysis...");const X=N??await Z();if(!X){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract headings for intent analysis"),M("Failed to extract page content");return}l.log("[AdMeshProvider] ๐ Extracted headings:",{title:X.title,headingsCount:X.headings.length,articleTextLength:((Q=X.article_text)==null?void 0:Q.length)||0,domain:X.domain});const re=await Fr(X,{apiKey:t,apiBaseUrl:i||"https://api.useadmesh.com",extension:o,userId:w});re?(l.log("[AdMeshProvider] โ
Intent analysis completed:",{suggestionsCount:re.suggestions.length,suggestions:(re.suggestions||[]).map(Re=>{var I;return{id:Re.id,text:Re.text,is_sponsored:Re.is_sponsored,recommendationId:((I=Re.recommendation)==null?void 0:I.recommendation_id)||null}})}),$(Re=>_e(Re,re.suggestions||[]))):(l.warn("[AdMeshProvider] โ ๏ธ Intent analysis returned null"),M("Intent analysis failed"),$(Re=>Re.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after null intent analysis result"),Re):[{id:"fallback-1",text:"What are your questions about this content?",type:"information",is_sponsored:!1,recommendation:void 0}]))}catch(X){l.error("[AdMeshProvider] Error in intent analysis:",X),M("Intent analysis error"),$(ee=>ee.length>0?(l.log("[AdMeshProvider] โน๏ธ Preserving existing suggestions after intent analysis error"),ee):[{id:"error-fallback-1",text:"Ask me questions about this page",type:"information",is_sponsored:!1,recommendation:void 0}])}finally{P(!1)}},[t,i,o,w,_e,Z]),je=a.useCallback(async N=>{var ee,re,Re,I,ie,D;if(!x||!t||!t.toLowerCase().startsWith("pub_"))return;const Q=N??await Z();if(!Q){l.warn("[AdMeshProvider] โ ๏ธ Failed to extract page content for sponsored suggestion prefetch");return}const X=((re=(ee=Q.headings)==null?void 0:ee[0])==null?void 0:re.trim())||((Re=Q.title)==null?void 0:Re.trim());if(!X){l.warn("[AdMeshProvider] โ ๏ธ Skipping sponsored suggestion prefetch: no usable page query");return}try{l.log("[AdMeshProvider] ๐ Prefetching sponsored suggestion from /aip/context...");const ge=await x.fetchPlatformResponse({query:X,sessionId:e,messageId:pn.createMessageId(e),platformSurface:"copilot",model:g,messages:[],language:d,location:u,userId:w}),E=(D=(ie=(I=ge.recommendation)==null?void 0:I.creative)==null?void 0:ie.follow_up_suggestion)==null?void 0:D.trim(),ce=ge.recommendation_id;if(!E||!ce){l.log("[AdMeshProvider] โน๏ธ No sponsored follow-up suggestion returned from /aip/context");return}const ke={id:ce,text:E,type:"action",is_sponsored:!0,recommendation:ge,metadata:{source:"aip_context_prefetch",recommendation_id:ce}};$(he=>ne(he,ke)),l.log("[AdMeshProvider] โ
Sponsored suggestion prefetched from /aip/context",{recommendationId:ce,suggestionText:E})}catch(ge){l.warn("[AdMeshProvider] โ ๏ธ Sponsored suggestion prefetch failed (non-blocking):",ge)}},[t,d,u,g,x,e,w,ne,Z]),ve=a.useCallback(async()=>{l.log("[AdMeshProvider] ๐ Manual retry of intent analysis"),await Ge()},[Ge]);a.useEffect(()=>{!x||Y.current||(Y.current=!0,(async()=>{const N=await Z();await Promise.allSettled([je(N),Ge(N)])})())},[x,Ge,je,Z]);const de=a.useCallback(N=>{if(!N||N.status!=="active")return!1;const Q=Date.parse(N.expires_at);return Number.isNaN(Q)?!1:Q>Date.now()},[]),pe=a.useCallback(async(N,Q,X,ee)=>{const re=ee??A;if(!re||!x){l.warn("[AdMeshProvider] โ ๏ธ Skipping delegation event because session or SDK is missing",{endpoint:N,eventType:Q,hasSession:!!re,hasSdk:!!x});return}const Re=new Date().toISOString();l.log("[AdMeshProvider] ๐ก Sending delegation event",{endpoint:N,eventType:Q,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id,sessionId:re.session_id});const I=await fetch(`${x.getApiBaseUrl()}${N}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({delegation_session_id:re.delegation_session_id,recommendation_id:re.recommendation_id,session_id:re.session_id,event_type:Q,timestamp:Re,metadata:X||{}})});if(!I.ok){const ge=await I.text();throw l.error("[AdMeshProvider] Delegation event failed",{endpoint:N,eventType:Q,status:I.status,errorBody:ge,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id}),new Error(`Delegation event failed (${I.status}): ${ge}`)}const ie=await I.json(),D=ie==null?void 0:ie.session;l.log("[AdMeshProvider] โ
Delegation event acknowledged",{endpoint:N,eventType:Q,recommendationId:re.recommendation_id,delegationSessionId:re.delegation_session_id,returnedStatus:(D==null?void 0:D.status)||(ie==null?void 0:ie.status)}),D&&C(D)},[A,t,x]),Ee=a.useCallback(()=>{B.current=0},[]),ye=a.useCallback(async(N="user_stopped",Q)=>{const X=A;if(!X){l.warn("[AdMeshProvider] โ ๏ธ stopDelegationSession called without an active SDK delegation session");return}l.log("[AdMeshProvider] ๐ Stopping delegation session",{reason:N,recommendationId:X.recommendation_id,delegationSessionId:X.delegation_session_id}),await pe("/aip/delegation/stop","session_stopped",{reason:N,...Q||{}},X),await(x==null?void 0:x.trackPublisherAssistantEvent({event_name:"delegation_stopped",timestamp:new Date().toISOString(),session_id:X.session_id,recommendation_id:X.recommendation_id,delegation_session_id:X.delegation_session_id,brand_name:X.brand_name,status:"stopped",metadata:{reason:N,...Q||{}}}).catch(ee=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to track delegation_stopped event:",ee)})),B.current=0,G.current=null,C(null),l.log("[AdMeshProvider] โ
Delegation session cleared locally after stop")},[A,pe,x]),se=a.useCallback(async(N="turn_completed",Q)=>{N==="turn_started"&&Ee(),await pe("/aip/delegation/activity",N,Q)},[pe,Ee]);a.useEffect(()=>{const N=(A==null?void 0:A.delegation_session_id)??null;N!==G.current&&(G.current=N,B.current=0)},[A==null?void 0:A.delegation_session_id]),a.useEffect(()=>{if(!((A==null?void 0:A.delegation_session_id)??null)||!x)return;const Q=te.current;if(!Q||!de(Q)){C(ee=>ee?{...ee,status:"expired"}:null);return}const X=window.setInterval(()=>{const ee=te.current;if(!(!ee||!de(ee))){if(B.current+=1,B.current>=Ar){l.log("[AdMeshProvider] โฑ๏ธ Stopping delegation after idle heartbeats",{delegationSessionId:ee.delegation_session_id,heartbeatsSinceLastUserTurn:B.current,idleHeartbeatLimit:Ar}),ye("idle_timeout",{source:"heartbeat_idle",heartbeats_without_turn:B.current}).catch(re=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to stop idle delegation session:",re)});return}pe("/aip/delegation/heartbeat","heartbeat").catch(re=>{l.warn("[AdMeshProvider] โ ๏ธ Failed to send delegation heartbeat:",re)})}},ls);return()=>{window.clearInterval(X)}},[A==null?void 0:A.delegation_session_id,de,pe,x,ye]);const bt={sdk:x,apiKey:t,sessionId:e,theme:s,language:d,location:u,userId:w,model:g,messages:_,processedMessageIds:h,recommendationResults:T,activeDelegationSession:A,suggestions:L,isAnalyzingIntent:F||W,intentError:z,markMessageAsProcessed:N=>{S(Q=>{const X=new Set(Q);return X.add(N),X})},isMessageProcessed:N=>h.has(N),setRecommendationResult:(N,Q)=>{K(X=>{const ee=new Map(X);return ee.set(N,Q),ee}),S(X=>{const ee=new Set(X);return ee.add(N),ee})},getRecommendationResult:N=>T.get(N),hasRecommendationResult:N=>T.has(N),setActiveDelegationSession:N=>{C(N)},getActiveDelegationSession:()=>de(A)?A:null,hasActiveDelegationSession:()=>de(A),refreshDelegationActivity:se,stopDelegationSession:ye,retryIntentAnalysis:ve};return n.jsx(On.Provider,{value:bt,children:p})};class Ur{constructor(){Ye(this,"roots",new Map)}async render(e){try{l.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){l.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const s=document.getElementById(e.containerId);if(!s)throw l.error("[AdMeshRenderer] Container not found"),new Error(`Container with ID "${e.containerId}" not found`);l.log("[AdMeshRenderer] โ
Container ready");const i=this.roots.get(e.containerId);i&&(l.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),i.unmount(),this.roots.delete(e.containerId)),s.innerHTML="";const d=yo.createRoot(s);l.log("[AdMeshRenderer] ๐ Rendering recommendations"),d.render(n.jsx(Br,{apiKey:e.apiKey,sessionId:e.sessionId,theme:e.theme,apiBaseUrl:e.apiBaseUrl,language:e.language,location:e.location,userId:e.userId,model:e.model,messages:e.messages,children:n.jsx(Nr,{recommendations:o,theme:e.theme,sessionId:e.sessionId,onDelegationConsent:e.onDelegationConsent,onDelegationActivated:e.onDelegationActivated,onStartDelegation:e.onStartDelegation})})),s.style.display="block",l.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,d)}catch(o){throw l.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 cs=t=>{if(typeof t!="string")return;const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?e:void 0},Mt=class Mt{constructor(e){Ye(this,"config");Ye(this,"apiBaseUrl");Ye(this,"renderer",null);Ye(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 Mt.createSession();try{const i=new URL(o).pathname.split("/").filter(u=>u.length>0),d=i[i.length-1];return d?`session_${Date.now()}_${d}`:Mt.createSession()}catch{return Mt.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 Ur),this.renderer}getTracker(){return this.tracker||(this.tracker=new $r({apiKey:this.config.apiKey})),this.tracker}async postDelegationEvent(e,o,s,i){const d=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(!d.ok){const w=await d.text();throw new Error(`Delegation event failed (${d.status}): ${w}`)}const u=await d.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(),d=this.getTracker();await i.render({containerId:e.containerId,followups_container_id:e.followups_container_id,response:s,theme:e.theme||this.config.theme,tracker:d,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 l.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchPlatformResponse(e){var f,h,S,T,K,A,C,L,$,F,P,z,M;const o=`${this.apiBaseUrl}/aip/context`;if(l.log("[AdMeshSDK] ๐ฅ fetchPlatformResponse called"),!e.sessionId||e.sessionId.trim()===""){const W=new Error("sessionId is required and must be provided by the platform. The SDK never generates sessionId automatically.");throw l.error("[AdMeshSDK] sessionId not provided by platform - cannot process request"),W}const s=e.messageId;if(!s||s.trim()===""){const W=new Error("messageId is required and must be provided by the platform. The SDK never generates messageId automatically.");throw l.error("[AdMeshSDK] messageId not provided by platform - cannot process request"),W}const i=Mt.buildPlatformResponseCacheKey(e.sessionId,s),d=Mt.inFlightPlatformResponses.get(i);if(d)return l.log("[AdMeshSDK] โณ Reusing in-flight PlatformResponse request",{sessionId:e.sessionId,messageId:s}),d;const u=e.messages?e.messages.length:0,w=(typeof window<"u"&&window.navigator,"web"),g=typeof window<"u"&&window.innerWidth?window.innerWidth<768?"mobile":window.innerWidth<1024?"tablet":"desktop":"desktop",_=cs((f=e.location)==null?void 0:f.countryCode)||"US",c=typeof window<"u"&&window.location?{url:window.location.href,origin:window.location.origin,referrer:document.referrer||void 0,host:window.location.hostname}:void 0,m=e.userId??this.config.userId,k={spec_version:"1.0",message_id:s,timestamp:new Date().toISOString(),platform:{platform_id:"placeholder",role:"platform",software:{name:"admesh_ui_sdk",version:e.model||"1.0.0"}},identity:{namespace:"platform_user",value_hash:m||"",confidence:m?1:0},consent:{status:"granted",source:"admesh_ui_sdk",scope:{intent_based_monetization:!0,agent_participation:!0,measurement:!0},constraints:{allow_identity_downstream:!1}},classification_input:{type:"interaction",interaction:{session:{id:e.sessionId,turn_index:u},surface:{channel:e.platformSurface||"conversation",interaction_mode:"text",platform:w,form_factor:g,locale:e.language||"en-US",country:_,publisher:"placeholder"},input:{query_text:e.query,messages:e.messages||[]},context:{location:{city:((h=e.location)==null?void 0:h.city)||void 0,state:((S=e.location)==null?void 0:S.state)||void 0,state_code:((T=e.location)==null?void 0:T.stateCode)||void 0,country:((K=e.location)==null?void 0:K.country)||void 0,country_code:_,zipcode:((A=e.location)==null?void 0:A.zipcode)||void 0,latitude:(C=e.location)==null?void 0:C.latitude,longitude:(L=e.location)==null?void 0:L.longitude},page:c}}},monetization:{enabled:!0,pricing_model:"CPX",auction:{enabled:!0,floor:{amount:0,currency:"USD"}}}};(F=($=k.classification_input.interaction)==null?void 0:$.input.query_text)!=null&&F.trim()||l.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const j=JSON.stringify(k);l.log("[AdMeshSDK] ๐ค Sending canonical request to /aip/context",{messageId:k.message_id,specVersion:k.spec_version,classificationType:k.classification_input.type,platformId:k.platform.platform_id,surfaceChannel:(P=k.classification_input.interaction)==null?void 0:P.surface.channel,sessionId:(M=(z=k.classification_input.interaction)==null?void 0:z.session)==null?void 0:M.id});const p={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`};if(this.config.extension){p["X-AdMesh-Source"]="extension";const W=this.getExtensionSourceDomain();W&&(p["X-AdMesh-Source-Domain"]=W)}const x=(async()=>{const W=await fetch(o,{method:"POST",headers:p,body:j});if(!W.ok){const B=(await W.json().catch(()=>({}))).detail||`HTTP ${W.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${B}`)}const O=await W.json();return l.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{status:O.status,recommendationId:O.recommendation_id,hasRecommendation:!!O.recommendation,hasTracking:!!O.tracking,hasDelegation:!!O.delegation,topLevelKeys:Object.keys(O)}),l.log("[AdMeshSDK] ๐ฆ Full PlatformResponse received from /aip/context",O),O})();Mt.inFlightPlatformResponses.set(i,x);try{return await x}finally{Mt.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)}};Ye(Mt,"inFlightPlatformResponses",new Map);let pn=Mt;class Kn{constructor(e={}){Ye(this,"autoAddLabels");Ye(this,"fireExposurePixels");Ye(this,"labelStyle");Ye(this,"processedLinks",new Set);Ye(this,"mutationObserver",null);var o,s,i,d;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:((d=e.labelStyle)==null?void 0:d.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 d=this.getLinksToProcess(e),u=new Map(o.map(g=>{var _,c,m;return[((_=g==null?void 0:g.tracking)==null?void 0:_.click_url)||((m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url)||"",g]}).filter(([g])=>!!g)),w=new Map;o.forEach(g=>{var c,m;const _=(m=(c=g==null?void 0:g.recommendation)==null?void 0:c.creative)==null?void 0:m.landing_page_url;if(_&&typeof _=="string"){const k=_.trim().replace(/\/$/,"");w.set(k,g),w.set(`${k}/`,g)}}),d.forEach(g=>{var j,p,x,f,h,S,T,K;const _=g.getAttribute("href")||"",c=`${_}`;if(this.processedLinks.has(c))return;let m=u.get(_),k=_;if(!m){const A=_.trim().replace(/\/$/,"");m=w.get(A)||w.get(`${A}/`);const C=((j=m==null?void 0:m.tracking)==null?void 0:j.click_url)||((x=(p=m==null?void 0:m.recommendation)==null?void 0:p.creative)==null?void 0:x.landing_page_url);m&&C&&(l.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",_),g.setAttribute("href",C),k=C)}if(m){this.processedLinks.add(c),g.setAttribute("target","_blank"),g.setAttribute("rel","noopener noreferrer");const A={element:g,href:k,text:g.textContent||"",hasAdLabel:this.hasAdLabel(g),matchedRecommendation:{recommendation_id:(m==null?void 0:m.recommendation_id)||"",click_url:((f=m==null?void 0:m.tracking)==null?void 0:f.click_url)||((S=(h=m==null?void 0:m.recommendation)==null?void 0:h.creative)==null?void 0:S.landing_page_url)||"",exposure_url:(T=m==null?void 0:m.tracking)==null?void 0:T.exposure_url}};this.autoAddLabels&&!A.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to matched recommendation link:",k),this.addAdLabel(g),A.hasAdLabel=!0):this.autoAddLabels?A.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label");const C=(K=m==null?void 0:m.tracking)==null?void 0:K.exposure_url;this.fireExposurePixels&&C&&s&&A.matchedRecommendation&&s({exposureUrl:C,recommendationId:A.matchedRecommendation.recommendation_id,linkElement:g}),i.push(A)}})}else Array.from(e.querySelectorAll("a")).forEach(u=>{const w=u.getAttribute("href")||"",g=`${w}`;if(this.processedLinks.has(g))return;if(this.isAdMeshLink(w)){this.processedLinks.add(g);const c={element:u,href:w,text:u.textContent||"",hasAdLabel:this.hasAdLabel(u),matchedRecommendation:void 0};if(u.setAttribute("target","_blank"),u.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel?(l.log("[WeaveResponseProcessor] ๐ท๏ธ Adding Ad label to pattern-matched AdMesh link:",w),this.addAdLabel(u),c.hasAdLabel=!0):this.autoAddLabels?c.hasAdLabel&&l.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):l.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&s){const m=this.convertClickUrlToExposureUrl(w);s({exposureUrl:m,recommendationId:this.extractRecommendationIdFromUrl(w),linkElement:u})}i.push(c)}});return i}hasAdLabel(e){var u,w,g;if((e.textContent||"").includes("Ad"))return l.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 l.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 l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous text sibling"),!0;break}if(i&&i.nodeType===Node.ELEMENT_NODE){const _=i,c=_.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((w=_.textContent)!=null&&w.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in previous element sibling:",c),!0}let d=e.nextSibling;for(;d&&d.nodeType===Node.TEXT_NODE;){const _=d.textContent||"";if(_.trim()===""){d=d.nextSibling;continue}if(_.includes("Ad"))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next text sibling"),!0;break}if(d&&d.nodeType===Node.ELEMENT_NODE){const _=d,c=_.tagName.toUpperCase();if((c==="SUB"||c==="SPAN")&&((g=_.textContent)!=null&&g.includes("Ad")))return l.log("[WeaveResponseProcessor] โน๏ธ Found Ad label in next element sibling:",c),!0}return l.log("[WeaveResponseProcessor] โน๏ธ No existing Ad label found"),!1}addAdLabel(e){if(l.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add Ad label to link:",e.href),!e.isConnected){l.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){l.log("[WeaveResponseProcessor] โน๏ธ Link already has Ad label, skipping");return}const o=e.parentNode;if(!o){l.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 d=u=>{i&&u.target!==s&&(i=!1,s.style.textDecoration="none",s.style.opacity="1")};document.addEventListener("click",d);try{const u=e.nextSibling;u?(o.insertBefore(s,u),l.log("[WeaveResponseProcessor] โ
Ad label inserted before next sibling")):(o.appendChild(s),l.log("[WeaveResponseProcessor] โ
Ad label appended to parent (no next sibling)")),s.isConnected&&s.parentNode===o?l.log("[WeaveResponseProcessor] โ
Ad label successfully added to link:",e.href):l.error("[WeaveResponseProcessor] Ad label insertion failed - label not in DOM")}catch(u){l.error("[WeaveResponseProcessor] Error inserting Ad label:",u)}}removeLeftAdLabel(e){var s,i,d;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"))&&((d=u.parentNode)==null||d.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`,d=new URLSearchParams(o.search);return d.has("cpx")||d.set("cpx","0"),`${i}?${d.toString()}`}catch{return l.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 on(){const t=Vn();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 us=({className:t,size:e=20})=>n.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:[n.jsx("path",{d:"M5 12h14"}),n.jsx("path",{d:"M12 5v14"})]}),Hr=({recommendation:t,theme:e,sdk:o,sessionId:s,onExecuteQuery:i})=>{var k,j,p,x,f;const d=(j=(k=t.recommendation)==null?void 0:k.creative)!=null&&j.follow_up_suggestion&&((p=t.tracking)!=null&&p.followup_engagement_url)&&((x=t.tracking)!=null&&x.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=d==null?void 0:d.query,w=d==null?void 0:d.engagement_url,g=d==null?void 0:d.exposure_url,_=t.recommendation_id,c=((f=t.recommendation)==null?void 0:f.offerId)||_;if(!u||!w||!g)return l.log("[AdMeshFollowup] Missing followup_suggestion.query, engagement_url, or exposure_url - not rendering"),null;const m=async()=>{try{w&&_&&(l.log("[AdMeshFollowup] ๐ฏ Firing follow-up engagement tracking"),await o.fireFollowupEngagement(w,_,s)),i&&u?(l.log(`[AdMeshFollowup] ๐ Executing query: ${u}`),await i(u)):l.warn("[AdMeshFollowup] โ ๏ธ onExecuteQuery not provided - cannot execute query")}catch(h){l.error("[AdMeshFollowup] Error handling follow-up click:",h)}};return n.jsx(hn,{productId:c,recommendationId:_||"",exposureUrl:g,sessionId:s,className:"admesh-followup-container",style:{width:"100%"},children:n.jsxs("div",{className:"flex flex-col space-y-3 text-sm admesh-followup-wrapper",children:[n.jsx("div",{className:"h-px w-full bg-[#E5E5E5] dark:bg-[#262626] admesh-divider"}),n.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:h=>{(h.key==="Enter"||h.key===" ")&&m()},"aria-label":`Sponsored follow-up: ${u}`,children:[n.jsx("p",{className:"transition duration-200 text-[#000] dark:text-[#FFF] hover:text-[#24A0ED] admesh-followup-text",children:u}),n.jsxs("div",{className:"flex flex-row items-center space-x-2",children:[n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 italic admesh-ad-label",children:"Ad"}),n.jsx(us,{size:20,className:"text-[#24A0ED] flex-shrink-0 admesh-plus-icon"})]})]})]})})},nn=({onRecommendationsShown:t,onError:e,messageId:o,query:s,userId:i,initialRecommendation:d,triggerExposureUrl:u=!0,followups_container_id:w,onPasteToInput:g,onDelegationConsent:_,onDelegationActivated:c,onStartDelegation:m,onRecommendationReport:k,onExecuteQuery:j,onFollowupDetected:p,isContainerReady:x})=>{var X,ee,re,Re;const{sdk:f,sessionId:h,apiKey:S,language:T,location:K,userId:A,model:C,messages:L,theme:$,getRecommendationResult:F,hasRecommendationResult:P,setRecommendationResult:z,activeDelegationSession:M,setActiveDelegationSession:W,hasActiveDelegationSession:O}=on(),Y=I=>!!I&&I.status==="generated"&&!!I.recommendation,B=i||A,[G,te]=a.useState(null),[xe,Z]=a.useState(null),[ne,_e]=a.useState(!0),[Ge,je]=a.useState(null),ve=a.useRef(null),de=a.useRef(!1),pe=a.useRef(!1),Ee=a.useRef(t),ye=a.useRef(e);a.useEffect(()=>{Ee.current=t,ye.current=e},[t,e]),a.useEffect(()=>{ve.current!==o&&(ve.current=null,pe.current=!1,te(null),Z(null))},[o]);const se=O()&&(M==null?void 0:M.session_id)===h;a.useEffect(()=>{var D,ge,E;if(!o||!P(o)||se)return;const I=F(o);if(!I){l.log("[AdMeshRecommendations] โป๏ธ Reusing stored no_match result from provider state"),te(null),Z(null),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0;return}let ie=((D=I.recommendation)==null?void 0:D.format)||"tail";(ie==="weave"||ie==="product_card")&&(ie="tail"),l.log("[AdMeshRecommendations] โป๏ธ Reusing stored recommendation result from provider state",{messageId:o,recommendationId:I.recommendation_id,format:(ge=I.recommendation)==null?void 0:ge.format}),te(I),Z(ie),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0,(E=Ee.current)==null||E.call(Ee,o,I)},[F,P,se,o]),a.useEffect(()=>{var I,ie,D,ge,E,ce,ke;if(!(!d||!o)&&!se)try{const he=d,We=d.status||"unknown";if(!Y(he)){if(We==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ Initial recommendation returned no_match - rendering nothing"),te(null),Z(null),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0,z(o,null);return}throw new Error(`Initial recommendation is not a filled auction response (status=${We})`)}let ze=((I=he.recommendation)==null?void 0:I.format)||"tail";(ze==="weave"||ze==="product_card")&&(ze="tail"),te(he),Z(ze),je(null),_e(!1),ve.current=o,de.current=!1,pe.current=!0,z(o,he),(ie=Ee.current)==null||ie.call(Ee,o,he),l.log("[AdMeshRecommendations] โป๏ธ Using initial recommendation payload, skipping /aip/context fetch"),l.log("[AdMeshRecommendations] โ
Accepted initial generated recommendation payload",{messageId:o,recommendationId:he.recommendation_id,format:(D=he.recommendation)==null?void 0:D.format,brandName:(E=(ge=he.recommendation)==null?void 0:ge.creative)==null?void 0:E.brand_name,headline:(ke=(ce=he.recommendation)==null?void 0:ce.creative)==null?void 0:ke.headline,hasTracking:!!he.tracking})}catch(he){const We=he instanceof Error?he:new Error(String(he));pe.current=!1,l.warn(`[AdMeshRecommendations] โ ๏ธ Failed to reuse initial recommendation, will fall back to fetch: ${We.message}`)}},[se,d,o,z]),a.useEffect(()=>{if(!o||!s||s.trim()===""){l.log("[AdMeshRecommendations] Validation failed - missing required parameters"),_e(!1);return}if(se){l.log("[AdMeshRecommendations] โธ๏ธ Delegated session active, skipping /aip/context fetch",{messageId:o,conversationSessionId:h,delegationSessionId:M==null?void 0:M.delegation_session_id}),te(null),Z(null),je(null),_e(!1),de.current=!1;return}if(!(f!=null&&f.fetchPlatformResponse)){l.log("[AdMeshRecommendations] SDK fetchPlatformResponse not available"),_e(!1);return}if(pe.current){l.log("[AdMeshRecommendations] โญ๏ธ Initial recommendation provided, skipping duplicate fetch");return}if(ve.current===o){l.log("[AdMeshRecommendations] โญ๏ธ Already fetched for this messageId, skipping duplicate fetch");return}if(de.current){l.log("[AdMeshRecommendations] โญ๏ธ Fetch already in progress, skipping duplicate fetch");return}l.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context (single fetch)"),(async()=>{var ie,D,ge,E,ce,ke,he,We,ze;try{de.current=!0,_e(!0),je(null);const Se=await f.fetchPlatformResponse({query:s.trim(),sessionId:h,messageId:o,language:T,location:K,userId:B,model:C,...L&&L.length>0&&{messages:L}}),De=(Se==null?void 0:Se.status)||"unknown";if(!Y(Se)){if(De==="no_match"){l.log("[AdMeshRecommendations] โน๏ธ No recommendation returned from /aip/context"),te(null),Z(null),je(null),_e(!1),de.current=!1,ve.current=o,z(o,null);return}throw new Error(`No filled recommendation returned from /aip/context (status=${De})`)}te(Se),l.log("[AdMeshRecommendations] โ
Accepted fetched generated recommendation payload",{messageId:o,recommendationId:Se.recommendation_id,format:(ie=Se.recommendation)==null?void 0:ie.format,brandName:(ge=(D=Se.recommendation)==null?void 0:D.creative)==null?void 0:ge.brand_name,headline:(ce=(E=Se.recommendation)==null?void 0:E.creative)==null?void 0:ce.headline,hasTracking:!!Se.tracking});let Ae=((ke=Se.recommendation)==null?void 0:ke.format)||"tail";(Ae==="weave"||Ae==="product_card")&&(Ae="tail"),Z(Ae),ve.current=o,z(o,Se),l.log("[AdMeshRecommendations] ๐ Format detection:",{preferred_format:(he=Se.recommendation)==null?void 0:he.format,selected_format:Ae}),_e(!1),de.current=!1,(We=Ee.current)==null||We.call(Ee,o,Se)}catch(Se){const De=Se instanceof Error?Se:new Error(String(Se));De.message.includes("Failed to fetch")||De.message.includes("NetworkError")?l.warn(`[AdMeshRecommendations] โ ๏ธ Network error fetching recommendations(non - critical): ${De.message} `):l.error(`[AdMeshRecommendations] Error fetching recommendations: ${De.message} `),je(De),_e(!1),de.current=!1,(ze=ye.current)==null||ze.call(ye,De)}})()},[M==null?void 0:M.delegation_session_id,se,f,h,o,s,T,K,B,C,d,z]),a.useEffect(()=>{var ie,D,ge,E;if(!G||!p)return;const I=(D=(ie=G.recommendation)==null?void 0:ie.creative)!=null&&D.follow_up_suggestion&&((ge=G.tracking)!=null&&ge.followup_engagement_url)&&((E=G.tracking)!=null&&E.followup_exposure_url)?{label:G.recommendation.creative.follow_up_suggestion,query:G.recommendation.creative.follow_up_suggestion,engagement_url:G.tracking.followup_engagement_url,exposure_url:G.tracking.followup_exposure_url}:null;I&&p(I,G.recommendation_id)},[G,p]);const bt=a.useCallback(async I=>{if(!f||!h)throw new Error("AdMesh SDK activation requires an initialized session");const ie=await fetch(`${f.getApiBaseUrl()}/aip/delegation/activate`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({session_id:h,recommendation_id:I.recommendation_id,metadata:I.metadata})});if(!ie.ok){const ce=await ie.text();throw new Error(`Failed to activate delegation session: ${ie.status} ${ce}`)}const D=await ie.json(),ge={...I,delegation_session_id:D.delegation_session_id||I.delegation_session_id,session_id:D.session_id||h,brand_id:D.brand_id||I.brand_id,brand_name:D.brand_name||I.brand_name,mcp_endpoint:D.mcp_endpoint,eligibility_reason:D.eligibility_reason||I.eligibility_reason,delegate_reason:D.delegate_reason||I.delegate_reason,session_goal:D.session_goal||I.session_goal,desired_outcome_type:D.desired_outcome_type||I.desired_outcome_type,required_user_inputs:D.required_user_inputs||I.required_user_inputs||[],required_consent_types:D.required_consent_types||I.required_consent_types||[],success_outcome:D.success_outcome||I.success_outcome,fallback_message:D.fallback_message||I.fallback_message,session_mode:"inline",status:D.status||"active",capabilities:D.capabilities||I.capabilities||[],allowed_data_types:D.allowed_data_types||I.allowed_data_types||[],auth_model:D.auth_model||I.auth_model,handoff_protocol:D.handoff_protocol||I.handoff_protocol,supported_actions:D.supported_actions||I.supported_actions||[],metadata:D.metadata||I.metadata},E={delegation_session_id:D.delegation_session_id,recommendation_id:I.recommendation_id,session_id:D.session_id||h,brand_agent_id:D.brand_agent_id,brand_id:D.brand_id||I.brand_id,brand_name:D.brand_name||I.brand_name||"Brand",mcp_endpoint:D.mcp_endpoint,status:D.status||"active",activated_at:D.created_at,last_activity_at:D.updated_at,expires_at:D.expires_at||D.updated_at,eligibility_reason:D.eligibility_reason||I.eligibility_reason,delegate_reason:D.delegate_reason||I.delegate_reason,session_goal:D.session_goal||I.session_goal,desired_outcome_type:D.desired_outcome_type||I.desired_outcome_type,required_user_inputs:D.required_user_inputs||I.required_user_inputs||[],required_consent_types:D.required_consent_types||I.required_consent_types||[],success_outcome:D.success_outcome||I.success_outcome,fallback_message:D.fallback_message||I.fallback_message,capabilities:D.capabilities||I.capabilities||[],allowed_data_types:D.allowed_data_types||I.allowed_data_types||[],consent_requirements:D.consent_requirements||I.consent_requirements||[],auth_model:D.auth_model||I.auth_model,handoff_protocol:D.handoff_protocol||I.handoff_protocol,supported_actions:D.supported_actions||I.supported_actions||[],metadata:D.metadata||I.metadata};if(W(E),await f.trackPublisherAssistantEvent({event_name:"delegation_started",timestamp:new Date().toISOString(),session_id:h,recommendation_id:I.recommendation_id,delegation_session_id:D.delegation_session_id,brand_name:E.brand_name,status:D.status||"active",metadata:{brand_agent_id:D.brand_agent_id,source:"recommendation_card"}}).catch(ce=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to track delegation_started event:",ce)}),await f.reportDelegationSessionStarted(E,{brand_agent_id:D.brand_agent_id,brand_name:E.brand_name}).then(ce=>{ce&&W(ce)}).catch(ce=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report delegation session_started event:",ce)}),c){try{await c(ge)}catch(ce){l.warn("[AdMeshRecommendations] โ ๏ธ Host onDelegationActivated callback failed after successful delegation activation:",ce)}return}if(m)try{await m({...I.platform_response,delegation:{...I.platform_response.delegation,...ge,delegation_session_id:D.delegation_session_id,available:!0,status:D.status||"active"}})}catch(ce){l.warn("[AdMeshRecommendations] โ ๏ธ Host onStartDelegation callback failed after successful delegation activation:",ce)}},[S,c,m,f,h,W]),N=a.useCallback(async I=>{var ie,D;if(k){await k(I);return}!f||!h||await f.reportSponsoredRecommendation({session_id:h,message_id:o,recommendation_id:I.recommendation_id,reason:I.reason,brand_name:(D=(ie=I.recommendation.recommendation)==null?void 0:ie.creative)==null?void 0:D.brand_name,metadata:{reason:I.reason,source:"recommendation_card"}}).catch(ge=>{l.warn("[AdMeshRecommendations] โ ๏ธ Failed to report sponsored recommendation:",ge)})},[o,k,f,h]);if(!o||!s||s.trim()===""||ne||Ge)return null;if(!G||!xe)return l.log("[AdMeshRecommendations] ๐ซ Nothing to render",{messageId:o,hasPlatformResult:!!G,detectedFormat:xe,isLoading:ne,hasError:!!Ge}),null;l.log("[AdMeshRecommendations] ๐จ Rendering recommendation component",{messageId:o,recommendationId:G.recommendation_id,detectedFormat:xe,brandName:(ee=(X=G.recommendation)==null?void 0:X.creative)==null?void 0:ee.brand_name,headline:(Re=(re=G.recommendation)==null?void 0:re.creative)==null?void 0:Re.headline});const Q=typeof document<"u"&&w&&(x??!0)?document.getElementById(w):null;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"admesh-recommendations-container",style:{marginTop:"1rem"},children:n.jsx(qn,{recommendations:[G],theme:$,sessionId:h,triggerExposureUrl:u,onPasteToInput:g,onDelegationConsent:_,onDelegationActivated:bt,onStartDelegation:m,onRecommendationReport:N})}),Q&&f&&h?Hn.createPortal(n.jsx(Hr,{recommendation:G,theme:$,sdk:f,sessionId:h,onExecuteQuery:j}),Q):null]})},qr=({format:t="tail",onError:e,messageId:o,query:s,fallback:i,previousRecommendations:d})=>{const{sdk:u,sessionId:w,theme:g,apiKey:_,language:c,location:m,userId:k,model:j,messages:p}=on(),x=a.useRef(null),[f,h]=a.useState("");return a.useEffect(()=>{o&&h(`admesh-weave-fallback-${o}`)},[o]),l.log("[WeaveFallbackRecommendations] ๐จ Component render"),a.useEffect(()=>{if(l.log("[WeaveFallbackRecommendations] ๐ useEffect triggered",{fallback:i,hasPreviousRecommendations:d&&d.length>0,previousRecommendationsCount:(d==null?void 0:d.length)||0}),!i){l.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(l.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!s||s.trim()===""){l.log("[WeaveFallbackRecommendations] Validation failed - returning early");return}if(l.log("[WeaveFallbackRecommendations] โ
Validation passed"),!u||!f){l.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}const S=d&&d.length>0;l.log("[WeaveFallbackRecommendations] ๐ Checking previous recommendations:",{hasPreviousRecs:S,count:(d==null?void 0:d.length)||0,fallback:i,messageId:o}),S?(l.log(`[WeaveFallbackRecommendations] โป๏ธ Reusing ${d.length} previous recommendation(s), skipping API call`),(async()=>{var K,A,C,L,$,F,P;try{const z=d[0];if(l.log("[WeaveFallbackRecommendations] ๐ฆ Processing AIP response:",{hasAipResponse:!!z,recommendationId:(z==null?void 0:z.recommendation_id)||"",format:((K=z==null?void 0:z.recommendation)==null?void 0:K.format)||"unknown"}),z&&process.env.NODE_ENV==="development"&&l.log("[WeaveFallbackRecommendations] ๐ Recommendation received (DEV):",{recommendation_id:z==null?void 0:z.recommendation_id,click_url:((A=z==null?void 0:z.tracking)==null?void 0:A.click_url)||((L=(C=z==null?void 0:z.recommendation)==null?void 0:C.creative)==null?void 0:L.landing_page_url),format:($=z==null?void 0:z.recommendation)==null?void 0:$.format,full_response:z}),!z){l.warn("[WeaveFallbackRecommendations] โ ๏ธ Previous recommendation is empty, falling back to API call"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o});return}const M=u,W=M.getRenderer,O=M.getTracker,Y=(F=M.config)==null?void 0:F.theme;if(W&&O){const B={sessionId:w,messageId:o,recommendations:[z]},G=W.call(u),te=O.call(u),xe=(u==null?void 0:u.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com";await G.render({containerId:f,response:B,theme:g||Y,tracker:te,sessionId:w,apiKey:_||((P=u==null?void 0:u.config)==null?void 0:P.apiKey),apiBaseUrl:xe,language:c,location:m,userId:k,model:j,messages:p}),l.log("[WeaveFallbackRecommendations] โ
Recommendations rendered from previous response (no API call)")}else l.warn("[WeaveFallbackRecommendations] โ ๏ธ SDK internal methods not accessible, using showRecommendations (will use cached result)"),await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch(z){const M=z instanceof Error?z:new Error(String(z));l.error(`[WeaveFallbackRecommendations] Error rendering previous recommendations: ${M.message}`);try{await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o})}catch{e==null||e(M)}}})()):(l.log("[WeaveFallbackRecommendations] ๐ค No previous recommendations, calling sdk.showRecommendations"),(async()=>{try{if(!(u!=null&&u.showRecommendations)){l.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}await u.showRecommendations({query:s.trim(),containerId:f,sessionId:w,messageId:o}),l.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(K){const A=K instanceof Error?K:new Error(String(K));l.log(`[WeaveFallbackRecommendations] Error: ${A.message}`),e==null||e(A)}})())},[u,w,f,t,o,s,i,e,d,g]),!i||!o||!s||s.trim()===""?null:n.jsx("div",{ref:x,id:f,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Or=a.createContext(void 0),ms=({children:t,shouldRenderFallback:e,messageId:o,sessionId:s,query:i})=>n.jsx(Or.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:s,query:i},children:t}),ps=()=>a.useContext(Or),Nn=t=>{try{return new URL(t),!0}catch{return!1}},Cr=t=>t&&t.trim()?t.trim():"",Bt=t=>typeof t=="string"?t.trim():typeof t=="number"?String(t):"",gt=t=>Bt(t)||void 0,hs=(t,e)=>{const o=t.split(/\s+/).filter(Boolean);return o.length<=e?t:`${o.slice(0,e).join(" ")}...`},fs=(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 Bt(t)},gs=(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=Bt(t);return i?/%|off/i.test(i)?i:s==="amount"||s==="fixed"||s==="fixed_amount"?`${i} off`:`${i}% off`:""},be={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"},xs=({recommendations:t,theme:e,className:o="",style:s={},sessionId:i,triggerExposureUrl:d=!0,onDelegationConsent:u,onDelegationActivated:w,onStartDelegation:g,onPasteToInput:_})=>{var E,ce,ke,he,We,ze,Se,De,Ae,yt,st,jt,Pe,Oe,fe,it,Et,Rt,H,at,wt,Lt,Ut,q,Ce,Qe,ut,Tt,It,Ht,Dt,_t,Xe;if(!t||t.length===0)return l.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const c=t[0],m=((E=c==null?void 0:c.recommendation)==null?void 0:E.offerId)||"",k=((ce=c==null?void 0:c.tracking)==null?void 0:ce.exposure_url)||"",j=(c==null?void 0:c.recommendation_id)||"",p=((he=(ke=c==null?void 0:c.recommendation)==null?void 0:ke.creative)==null?void 0:he.description)||"",x=((We=c==null?void 0:c.recommendation)==null?void 0:We.disclosure)||"Sponsored",f=((Se=(ze=c==null?void 0:c.recommendation)==null?void 0:ze.creative)==null?void 0:Se.brand_name)||"",h=((Ae=(De=c==null?void 0:c.recommendation)==null?void 0:De.creative)==null?void 0:Ae.headline)||((st=(yt=c==null?void 0:c.recommendation)==null?void 0:yt.creative)==null?void 0:st.brand_name)||"",S=((Pe=(jt=c==null?void 0:c.recommendation)==null?void 0:jt.creative)==null?void 0:Pe.logo_url)||"",T=((Oe=c==null?void 0:c.tracking)==null?void 0:Oe.click_url)||((it=(fe=c==null?void 0:c.recommendation)==null?void 0:fe.creative)==null?void 0:it.landing_page_url)||"",K=Cr((Rt=(Et=c==null?void 0:c.recommendation)==null?void 0:Et.creative)==null?void 0:Rt.cta_text),A=((at=(H=c==null?void 0:c.recommendation)==null?void 0:H.creative)==null?void 0:at.products)||[],C=A.length>1,L=C?A.slice(0,4):[],$=((wt=c==null?void 0:c.recommendation)==null?void 0:wt.format)||"tail",F=$==="bridge",P=((Lt=c==null?void 0:c.delegation)==null?void 0:Lt.brand_name)||f,z=((Ut=c==null?void 0:c.delegation)==null?void 0:Ut.available)===!0,M=F&&z,W="Talk to Agent",O=!C&&!!K&&!!T;if(!f&&!h&&!p)return l.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering",{reason:"brand, headline, and description are missing",brandName:f,hasFirstRecommendation:!!c,recommendationId:j,recommendationKeys:c?Object.keys(c):[]}),null;let Y=f,B="";h&&h!==f&&(B=h),B&&(Y=`${f} โ ${B}`),l.debug("[AdMeshTailAd] ๐ Rendering with tracking data:",{recommendationId:j,productId:m,exposureUrl:k?"present":"MISSING",sessionId:i?"present":"MISSING",recommendationsCount:t.length,clickUrl:T||"MISSING",clickUrlSource:(q=c==null?void 0:c.tracking)!=null&&q.click_url?"tracking.click_url":(Qe=(Ce=c==null?void 0:c.recommendation)==null?void 0:Ce.creative)!=null&&Qe.landing_page_url?"recommendation.creative.landing_page_url":"none",shortDescription:p?"present":"MISSING",brandName:f,productName:h,headlineText:Y,triggerExposureUrl:d}),l.log("[AdMeshTailAd] โ
Rendering tail ad",{recommendationId:j,brandName:f,productName:h,hasDescription:!!p,hasClickUrl:!!T,hasLogoUrl:!!S,recommendationFormat:$});const G=(V,Ne)=>{Ne&&Ne.stopPropagation(),l.log(`AdMesh tail ad ${V} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({recommendationId:j,productId:m,clickUrl:T,source:V}).catch(()=>{l.error(`[AdMesh] Failed to track ${V} click`)})},te=V=>{V.stopPropagation(),G("tail_ad_brand_name")},xe=V=>{V.stopPropagation(),G("tail_ad_cta")},Z=V=>{V.stopPropagation(),G("tail_ad_logo")},ne=()=>{C||!T||(G("tail_ad_card"),typeof window<"u"&&window.open(T,"_blank","noopener,noreferrer"))},_e=V=>{C||!T||(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),ne())},[Ge,je]=a.useState(!1),[ve,de]=a.useState(!1),pe=a.useRef(null);a.useEffect(()=>()=>{pe.current&&(pe.current(!1),pe.current=null)},[]);const Ee=V=>{var Ne;V&&de(!0),(Ne=pe.current)==null||Ne.call(pe,V),pe.current=null,V||(de(!1),je(!1))},ye=async()=>u?await u(c):await new Promise(V=>{pe.current=V,je(!0)}),se=async()=>{if(j&&i)try{const V=typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",Ne=await fetch(`${V}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:j,session_id:i,is_test:!1})});Ne.ok||l.warn("[AdMesh Tail Ad] Delegation engagement tracking failed:",Ne.statusText)}catch(V){l.error("[AdMesh Tail Ad] Error tracking delegation engagement:",V)}},bt=async V=>{var kt,Pt,qt,St;if(V.preventDefault(),V.stopPropagation(),!c||!M)return;if(G("tail_ad_delegation_cta"),!await ye()){l.log("[AdMesh Tail Ad] Delegation consent declined");return}se();const ae=c.delegation,vt=ae!=null&&ae.available?{recommendation_id:c.recommendation_id,brand_id:gt(ae.brand_id),brand_name:gt(ae.brand_name||((Pt=(kt=c.recommendation)==null?void 0:kt.creative)==null?void 0:Pt.brand_name)),mcp_endpoint:gt(ae.mcp_endpoint),eligibility_reason:gt(ae.eligibility_reason),delegate_reason:gt(ae.delegate_reason),session_goal:gt(ae.session_goal),desired_outcome_type:ae.desired_outcome_type,required_user_inputs:Array.isArray(ae.required_user_inputs)?ae.required_user_inputs.filter(mt=>typeof mt=="string"):[],required_consent_types:Array.isArray(ae.required_consent_types)?ae.required_consent_types.filter(mt=>typeof mt=="string"):[],success_outcome:gt(ae.success_outcome),fallback_message:gt(ae.fallback_message),session_mode:gt(ae.session_mode),status:gt(ae.status),capabilities:ae.capabilities||[],allowed_data_types:ae.allowed_data_types||[],consent_requirements:ae.consent_requirements||[],auth_model:gt(ae.auth_model),handoff_protocol:ae.handoff_protocol&&typeof ae.handoff_protocol=="object"?ae.handoff_protocol:void 0,supported_actions:ae.supported_actions||[],metadata:ae.metadata&&typeof ae.metadata=="object"?ae.metadata:void 0,platform_response:c}:null;if(w&&vt){try{await w(vt)}finally{de(!1),je(!1)}return}if(g){try{await g(c)}finally{de(!1),je(!1)}return}const rt=((St=(qt=c.recommendation)==null?void 0:qt.creative)==null?void 0:St.follow_up_suggestion)||"";if(rt&&_){_(rt),de(!1),je(!1);return}if(rt&&typeof window<"u"&&window.__admesh_setMessage){window.__admesh_setMessage(rt),de(!1),je(!1);return}de(!1),je(!1)},[N,Q]=a.useState(!1),X=f?f.charAt(0).toUpperCase():"B",ee=be.surface,re=be.border,Re=(e==null?void 0:e.borderRadius)||((Tt=(ut=e==null?void 0:e.components)==null?void 0:ut.card)==null?void 0:Tt.borderRadius)||"8px",I="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",ie="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",D=((It=e==null?void 0:e.shadows)==null?void 0:It.medium)||((Dt=(Ht=e==null?void 0:e.components)==null?void 0:Ht.card)==null?void 0:Dt.boxShadow)||I,ge=((_t=e==null?void 0:e.shadows)==null?void 0:_t.large)||ie;return n.jsxs(hn,{productId:m,recommendationId:j,exposureUrl:k,sessionId:i,triggerExposureUrl:d,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:[n.jsx("style",{children:`
|
|
152
152
|
.admesh-tail-product-scroll {
|
|
153
153
|
-ms-overflow-style: none;
|
|
154
154
|
scrollbar-width: none;
|
|
@@ -1179,5 +1179,5 @@ ${T}`),x=x.replace(/\|\s*\|\s*(?=[A-Za-z0-9*])/g,`|
|
|
|
1179
1179
|
`),f=[];let h=0;for(;h<x.length;){const S=x[h],T=x[h+1]||"";if(S.includes("|")&&d(T)){f.length>0&&f[f.length-1].trim()&&f.push("");const{heading:K,headerLine:A}=u(S);for(K&&f.push(K),f.push(A,w(A,T)),h+=2;h<x.length&&x[h].includes("|")&&x[h].trim();)f.push(x[h]),h+=1;h<x.length&&x[h].trim()&&f.push("");continue}f.push(S),h+=1}return f.join(`
|
|
1180
1180
|
`)})(t).split(/\n\s*\n/).map(p=>p.trim()).filter(Boolean);return n.jsx("div",{style:{margin:0,color:e.textColor,fontSize:o},children:j.map((p,x)=>{const f=p.split(`
|
|
1181
1181
|
`).map(A=>A.trim()).filter(Boolean),h=f.every(A=>/^[-*]\s+/.test(A)),S=f.every(A=>/^\d+\.\s+/.test(A)),T=f.length===1&&/^#{1,3}\s+/.test(f[0]),K=_(f);if(T){const A=f[0].replace(/^#{1,3}\s+/,"");return n.jsx("h3",{style:{marginTop:x===0?0:"1rem",marginBottom:"0.75rem",fontWeight:"600",fontSize:"1.05em",color:e.textColor},children:s(A)},x)}if(K){const{heading:A,lines:C}=g(f),L=i(C[0]),$=C.slice(2).map(i).filter(F=>F.length===L.length);return n.jsxs("div",{style:{width:"100%",overflowX:"auto",marginBottom:"1rem"},children:[A?n.jsx("p",{style:{marginTop:x===0?0:"1rem",marginBottom:"0.75rem",fontWeight:600,color:e.textColor,fontSize:o},children:s(A)}):null,n.jsx("div",{style:{border:`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.28)"}`,borderRadius:8,overflowX:"auto"},children:n.jsxs("table",{style:{width:"100%",minWidth:L.length>3?520:void 0,borderCollapse:"collapse",color:e.textColor,fontSize:o,lineHeight:1.45},children:[n.jsx("thead",{children:n.jsx("tr",{children:L.map((F,P)=>n.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(F)},P))})}),n.jsx("tbody",{children:$.map((F,P)=>n.jsx("tr",{children:F.map((z,M)=>n.jsx("td",{style:{padding:"9px 10px",verticalAlign:"top",borderBottom:P===$.length-1?"none":`1px solid ${e.borderColor||"rgba(148, 163, 184, 0.18)"}`,whiteSpace:"normal"},children:s(z)},M))},P))})]})})]},x)}if(h||S){const A=S?"ol":"ul";return n.jsx(A,{style:{marginBottom:"1rem",paddingLeft:"1.25rem",color:e.textColor,fontSize:o},children:f.map((C,L)=>n.jsx("li",{style:{marginBottom:"0.45rem"},children:s(C.replace(/^([-*]|\d+\.)\s+/,""))},L))},x)}return n.jsx("p",{style:{marginBottom:"1rem",lineHeight:"1.6",color:e.textColor,fontSize:o,whiteSpace:"pre-wrap"},children:f.map((A,C)=>n.jsxs(a.Fragment,{children:[C>0&&n.jsx("br",{}),s(A)]},C))},x)})})};function mn(t){return t===void 0?void 0:typeof t=="number"?`${t}px`:t}function Er(t){if(typeof t=="number")return t;if(typeof t!="string")return;const e=Number(t.trim().replace(/px$/i,""));return Number.isFinite(e)&&e>0?e:void 0}function Xt(t){return t.replace(/\s+/g," ").trim()}function Is(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 d=s.length?s:o;return[i,...d].slice(0,4)}function Ds(t,e,o,s){const i=new Set,d=[],u=(j,p="information")=>{const x=Xt(j);if(!x)return;const f=x.toLowerCase();i.has(f)||(i.add(f),d.push({id:`followup_${d.length}_${f.replace(/[^a-z0-9]+/g,"_")}`,text:x,type:p,is_sponsored:!1}))},w=new Set,g=j=>{const p=Xt(j||"");if(!p)return;const x=p.replace(/^(how|why|what|when|where|which|who)\s+/i,"").replace(/\?+$/g,"").trim();x&&w.add(x)};(s||[]).forEach(j=>g(j==null?void 0:j.title)),(o||[]).forEach(j=>g(j==null?void 0:j.title)),e.split(/\n+/).map(j=>Xt(j.replace(/^[-*]\s+/,""))).filter(Boolean).filter(j=>j.length>=24&&j.length<=90).forEach(j=>{w.size>=6||g(j)});const c=Xt(t.replace(/[?.!]+$/g,"")),m=Array.from(w).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 ${c}`,"Give me the practical takeaway here"].forEach((j,p)=>{d.length>=3||u(j,p===0?"comparison":"information")}),d.slice(0,3)}function Ps(){if(typeof window>"u")return"unknown";const t=window.innerWidth;return t<768?"mobile":t<1024?"tablet":"desktop"}function Rr(t){return t?{shell:{position:"fixed",left:0,right:0,bottom:0,width:"100%",maxWidth:"100%",height:"calc(100dvh - env(safe-area-inset-bottom, 0px))",maxHeight:"calc(100dvh - env(safe-area-inset-bottom, 0px))",padding:0,margin:0,zIndex:2147483001,boxSizing:"border-box"},panelWidth:"100%",panelMaxWidth:"100%",panelHeight:"100%",panelMaxHeight:"100%",panelBorderRadius:"0"}:{shell:{position:"fixed",left:"50%",bottom:"12px",transform:"translateX(-50%)",width:"min(960px, calc(100vw - 24px))",maxWidth:"100%",maxHeight:"calc(100vh - 24px)",zIndex:2147483001,boxSizing:"border-box"},panelWidth:"min(960px, calc(100vw - 24px))",panelMaxWidth:"100%",panelHeight:"min(78vh, 760px)",panelMaxHeight:void 0,panelBorderRadius:"12px"}}function Qr(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 Tr(){var t;try{const e=(t=window.location.href)==null?void 0:t.trim();if(Qr(e))return e}catch{return}}function Ir(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=Tr()||(Qr(t)?t.trim():void 0);let o=e?window.location.pathname||"/":void 0;try{o=e?new URL(e).pathname||"/":void 0}catch{o=Tr()?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:Ps()}}function zs(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:Xt(e),type:"action",is_sponsored:!0,recommendation:t,metadata:{source:"assistant_query_recommendation",recommendation_id:o}}}function Bn(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)"}},$s={sm:{width:"320px",height:"400px"},md:{width:"400px",height:"500px"},lg:{width:"480px",height:"600px"},xl:{width:"560px",height:"700px"}},Ls={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}},Fs=({theme:t,className:e,style:o,triggerLabel:s="Ask Ava",headerTitle:i="Ask Ava",headerLogoUrl:d,showHeader:u=!0,showHeaderTitle:w=!0,showSubtitle:g=!0,layout:_="floating",surface:c="page",adSlotBehavior:m="expand",showCompactSlotHeader:k=!0,showCompactWelcomeMessage:j=!0,showCompactSlotInput:p=!0,showCompactSlotDisclaimer:x=!0,panelWidth:f,panelHeight:h,analyticsPageUrl:S,fontScale:T=1,position:K="bottom-right",size:A="md",defaultOpen:C,open:L,onOpenChange:$,autoOpen:F=!1,showWelcomeMessage:P=!1,welcomeMessage:z="Hi, Iโm Ava. Iโll help you find the best options.",placeholder:M="Ask me anything about products...",adsEnabled:W=!0,suggestions:O,maxSuggestions:Y=6,suggestionStyle:B="carousel",suggestionTrigger:G="always",suggestionPlacement:te="below",sponsoredCreativePlacement:xe="none",onlyShowWhenSponsored:Z=!1,variant:ne="default",queryHandler:_e,suggestionsLoader:Ge,disclaimerText:je,poweredByLabel:ve="Powered by AdMesh",subtitle:de="Publisher Assistant",onOpen:pe,onClose:Ee})=>{const{sdk:ye,sessionId:se,theme:bt,apiKey:N,userId:Q}=on(),{suggestions:X,isAnalyzingIntent:ee,intentError:re,retryIntentAnalysis:Re,activeDelegationSession:I,hasActiveDelegationSession:ie,stopDelegationSession:D,refreshDelegationActivity:ge}=Vn();Yr(),console.log("[AdMeshIntentAssistant] Context:",{sdk:ye,sessionId:se,hasContextTheme:!!bt});const E=t||bt||Ns,ce=(E==null?void 0:E.mode)||"light",ke=c==="ad-slot",he=(r=!1)=>ke&&!(r&&m==="expand"),[We,ze]=a.useState(C||F),Se=L!==void 0,De=Se?L:We,[Ae,yt]=a.useState(""),[st,jt]=a.useState(!1),[Pe,Oe]=a.useState([]),[fe,it]=a.useState(!1),[Et,Rt]=a.useState(null),[H,at]=a.useState(!1),[wt,Lt]=a.useState(new Set),[Ut,q]=a.useState(O||X||[]),[Ce,Qe]=a.useState(0),[ut,Tt]=a.useState(0),[It,Ht]=a.useState({}),Dt=a.useRef(null),_t=a.useRef(!1),Xe=a.useRef(null),V=a.useRef(new Map),Ne=a.useRef([]),ae=a.useRef(null),vt=a.useRef(null),rt=a.useRef(null),kt=a.useRef(!1),Pt=a.useRef(!1),qt=a.useRef(null),St=a.useRef(null),mt=a.useRef(null),[Jt,kn]=a.useState(!1),[Sn,Jr]=a.useState(!1),At=a.useRef(null),Je=a.useRef(null),Zr=!!(N!=null&&N.toLowerCase().startsWith("pub_")),Ze=ie()&&(I==null?void 0:I.session_id)===se?I:null,An=a.useRef(new Set),Gn=a.useRef(new Set),Yn=a.useRef(!1),Zt=ke&&m==="expand"&&(H||fe),[fn,eo]=a.useState(!1);a.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia("(max-width: 767px)"),b=()=>eo(r.matches);return b(),r.addEventListener("change",b),()=>r.removeEventListener("change",b)},[]),a.useEffect(()=>{if(!Zt||typeof document>"u")return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[Zt]);const Cn=ke&&m==="sticky"&&(H||Pe.length>0||fe),zt=mn(f)??"100%",en=mn(h)??"100%",to=Er(f),Qn=Er(h),Xn=ke&&(Qn??Number.POSITIVE_INFINITY)<=60,lt=ke&&(to??Number.POSITIVE_INFINITY)<=360&&(Qn??Number.POSITIVE_INFINITY)<=120,sn=a.useCallback(r=>b=>{b?V.current.set(r,b):V.current.delete(r)},[]),Ie=a.useCallback(async(r,b={})=>{if(!(!ye||!se))try{await ye.trackPublisherAssistantEvent({event_name:r,timestamp:new Date().toISOString(),session_id:se,...Ir(S),...b})}catch(y){console.warn(`[AdMeshIntentAssistant] Failed to track ${r}`,y)}},[S,ye,se]),an=a.useCallback((r,b,y)=>{var U,le;const v=b==null?void 0:b.recommendation_id;if(!v)return;const R=`${r}:${v}`;Gn.current.has(R)||(Gn.current.add(R),Ie("recommendation_shown",{message_id:r,query:y,recommendation_id:v,brand_name:(le=(U=b.recommendation)==null?void 0:U.creative)==null?void 0:le.brand_name,is_sponsored:!0}))},[Ie]),Mn=a.useCallback((r,b,y,v,R,U)=>{const le=Array.isArray(U)&&U.length?U.map((ue,Me)=>{const Le=Xt(ue.text||"");return Le?{id:`followup_llm_${Me}_${Le.toLowerCase().replace(/[^a-z0-9]+/g,"_")}`,text:Le,type:ue.type||"information",is_sponsored:!1}:null}).filter(ue=>!!ue).slice(0,3):Ds(r,b,y,v),Te=zs(R),He=Te?[Te,...le.slice(0,2)]:le.slice(0,3);He.length&&q(Bn(He))},[]),ln=a.useCallback((r,b)=>{const y=Xt(r.query||r.label||"");if(!y||!b)return;const v={id:b,text:y,type:"action",is_sponsored:!0,recommendation:{recommendation_id:b,recommendation:{creative:{follow_up_suggestion:y}},tracking:{followup_engagement_url:r.engagement_url,followup_exposure_url:r.exposure_url}}};q(R=>{const U=R.filter(le=>!le.is_sponsored).slice(0,3);return Bn([v,...U].slice(0,4))})},[]),Jn=a.useCallback(()=>{const r=ae.current,b=vt.current;if(!r||!b)return!1;const y=r.getBoundingClientRect(),v=b.getBoundingClientRect(),R=Math.max(0,r.scrollTop+v.top-y.top);return r.scrollTop=R,!0},[]);a.useLayoutEffect(()=>{var r;if(kt.current){Jn()&&(kt.current=!1);return}Pt.current||(r=St.current)==null||r.scrollIntoView({behavior:"smooth"})},[Pe,Jn]),a.useLayoutEffect(()=>{if(!ke||Zt)return;const r=qt.current;if(!r)return;const b=r.closest(".admesh-publisher-assistant-reactMount"),y=en;[r,b].forEach(R=>{R&&(R.style.width=zt,R.style.maxWidth=zt,R.style.height=y,R.style.maxHeight=y,R.style.overflow="hidden",R.style.boxSizing="border-box",R.dataset.admeshAdSlotExpanded=Cn?"true":"false")});const v=b==null?void 0:b.parentElement;v&&v!==document.body&&v!==document.documentElement&&(v.style.width=zt,v.style.maxWidth=zt,v.style.height=y,v.style.maxHeight=y,v.style.overflow="hidden",v.style.boxSizing="border-box")},[en,zt,Zt,ke,Cn]),a.useEffect(()=>{if(O&&O.length){q(O);return}X&&X.length&&q(r=>Is(r,X))},[O,X]),a.useEffect(()=>{if(ne!=="default"||!Ge)return;let r=!1;return Ge().then(b=>{!r&&Array.isArray(b)&&b.length&&q(b)}).catch(b=>{console.warn("[AdMeshIntentAssistant] Failed to load suggestions",b)}),()=>{r=!0}},[Ge,ne]),a.useEffect(()=>{if(!fe){Tt(0),Dt.current=null;return}Dt.current==null&&(Dt.current=typeof performance<"u"?performance.now():Date.now());const r=()=>{const y=Dt.current;if(y==null)return;const v=typeof performance<"u"?performance.now():Date.now();Tt(Math.floor((v-y)/1e3))};r();const b=window.setInterval(r,1e3);return()=>window.clearInterval(b)},[fe]),a.useEffect(()=>{if(!fe||ne!=="default"){Qe(0);return}const r=window.setInterval(()=>{Qe(b=>Math.min(b+1,7))},3e3);return()=>window.clearInterval(r)},[fe,ne]),a.useEffect(()=>{Yn.current||!ye||!se||(Yn.current=!0,Ie("assistant_loaded",{metadata:{layout:_,surface:c,variant:ne,default_open:C||F}}))},[F,C,_,ye,se,c,Ie,ne]);const Ft=a.useCallback(r=>{Se?$==null||$(r):ze(r),r?(Ie("assistant_opened",{metadata:{layout:_,surface:c,ad_slot_behavior:m,variant:ne,expanded:H}}),pe==null||pe()):Ee==null||Ee()},[Se,H,_,$,pe,Ee,c,Ie,ne]),Zn=a.useCallback(()=>{Ft(!0)},[Ft]),no=a.useCallback(()=>{Ft(!1)},[Ft]),ro=a.useCallback(()=>{at(r=>!r)},[]),er=a.useCallback(async(r,b,y,v,R,U,le)=>{var Te,He,ue;if(!ye)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{Ze&&await ge("turn_started",{source:"publisher_assistant",recommendation_id:Ze.recommendation_id}).catch(me=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_started",me)});const Me=await fetch(`${ye.getApiBaseUrl()}/api/chat/assistant`,{method:"POST",signal:U,headers:{"Content-Type":"application/json",Accept:"text/plain","Cache-Control":"no-cache",Authorization:`Bearer ${N}`},body:JSON.stringify({message:r,session_id:se||"default-session",message_id:b,user_id:Q,context:{timestamp:new Date().toISOString(),source:"admesh-ui-sdk",page_context:Ir(S),conversation_history:le,sponsored_recommendation:R!=null&&R.recommendation_id?{recommendation_id:R.recommendation_id,brand_name:(He=(Te=R.recommendation)==null?void 0:Te.creative)==null?void 0:He.brand_name}:void 0,active_delegation_session:Ze?{delegation_session_id:Ze.delegation_session_id,recommendation_id:Ze.recommendation_id,session_id:Ze.session_id,brand_name:Ze.brand_name,mcp_endpoint:Ze.mcp_endpoint,status:Ze.status}:void 0}})});if(!Me.ok)throw new Error(`API request failed: ${Me.status} ${Me.statusText}`);const Le=(ue=Me.body)==null?void 0:ue.getReader(),Nt=new TextDecoder;if(!Le)throw new Error("Response body is not readable");let Ke="",et,$t,pt,J,oe;return await(async()=>{try{for(;;){const{done:me,value:ht}=await Le.read();if(me)break;const ot=Nt.decode(ht,{stream:!0}).split(`
|
|
1182
|
-
`);for(const Yt of ot)if(Yt.startsWith("data: ")){const Pn=Yt.slice(6);if(Pn.trim()==="[DONE]")return Ze&&ge("turn_completed",{source:"publisher_assistant",recommendation_id:Ze.recommendation_id}).catch(Fe=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",Fe)}),{text:Ke,source_links:et,related_items:$t,followup_suggestions:pt,used_capability:J,response_time_ms:oe};try{const Fe=JSON.parse(Pn);switch(Fe.type){case"content":{const pr=Fe.content||"";Ke+=pr,y==null||y(pr);break}case"final":{Ke=Fe.reply||Ke,et=Array.isArray(Fe.source_links)?Fe.source_links:void 0,$t=Array.isArray(Fe.related_items)?Fe.related_items:void 0,pt=Array.isArray(Fe.followup_suggestions)?Fe.followup_suggestions:void 0,J=typeof Fe.used_capability=="string"?Fe.used_capability:J,oe=typeof Fe.response_time_ms=="number"?Fe.response_time_ms:oe;break}case"followup_suggestions":{pt=Array.isArray(Fe.followup_suggestions)?Fe.followup_suggestions:pt;break}case"error":throw new Error(Fe.message||"Unknown streaming error");case"session_start":v==null||v(),console.log("Session started:",Fe.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",Pn);continue}}}}catch(me){if(U!=null&&U.aborted)return{text:Ke,source_links:et,related_items:$t,followup_suggestions:pt,used_capability:J,response_time_ms:oe,error:"aborted"};throw console.error("Stream processing error:",me),me}finally{Le.releaseLock()}return{text:Ke,source_links:et,related_items:$t,followup_suggestions:pt,used_capability:J,response_time_ms:oe}})()}catch(Me){return U!=null&&U.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",Me),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:Me instanceof Error?Me.message:"request_failed"})}},[ye,se,N,Q,Ze,ge]),jn=a.useCallback(()=>{const r=At.current;if(!r||r.signal.aborted)return;r.abort(),it(!1),Xe.current=null,_t.current=!1;const b=Je.current;b&&Oe(y=>y.map(v=>v.id===b&&!v.content.trim()?{...v,content:"Generation stopped."}:v))},[]),Ot=a.useCallback(async r=>{var ue,Me,Le,Nt,Ke,et,$t,pt;if(!r.trim()||fe)return;const b=typeof performance<"u"?performance.now():Date.now(),y=r.trim(),v=Date.now().toString(),R=new AbortController,U=Xe.current,le=(U==null?void 0:U.recommendation)||null,Te=Pe.filter(J=>(J.role==="user"||J.role==="assistant")&&J.content.trim()).slice(-6).map(J=>({role:J.role,content:J.content.trim().slice(0,1200)}));At.current=R,Je.current=null,rt.current=v,kt.current=!0,Pt.current=!0,Xe.current=null,q(J=>J.some(oe=>oe.is_sponsored)?J.filter(oe=>!oe.is_sponsored):J),Rt(null);const He={id:v,role:"user",content:y,timestamp:new Date};if(Ie("query_submitted",{message_id:v,query:y}),Oe(J=>[...J,He]),yt(""),it(!0),ne==="default"&&_e){try{const J=(Date.now()+1).toString(),oe={id:J,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:null};_t.current&&(Lt(ht=>new Set([...ht,J])),_t.current=!1),Oe(ht=>[...ht,oe]),Je.current=J;const qe=await _e(y,{sponsoredSuggestion:U});if(R.signal.aborted){Xe.current=null;return}const me=qe.recommendation||le||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:r,hasResponseRecommendation:!!qe.recommendation,hasSponsoredSuggestionRecommendation:!!le,finalRecommendationId:me==null?void 0:me.recommendation_id}),Oe(ht=>ht.map(tt=>tt.id===J?{...tt,content:qe.answer,sourceLinks:qe.source_links,relatedItems:qe.related_items,initialRecommendation:me,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-b}:tt)),Mn(y,qe.answer,qe.source_links,qe.related_items,qe.recommendation||null,qe.followup_suggestions),Ie("answer_completed",{message_id:J,query:y,recommendation_id:me==null?void 0:me.recommendation_id,brand_name:(Me=(ue=me==null?void 0:me.recommendation)==null?void 0:ue.creative)==null?void 0:Me.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"completed",metadata:{variant:ne,source:"query_handler"}}),Xe.current=null}catch(J){console.error("Error sending message:",J);const oe=J instanceof Error?J.message:"Unknown error occurred";Rt(oe);const qe={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Oe(me=>[...me,qe]),Ie("answer_failed",{query:y,status:oe,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,metadata:{variant:ne,source:"query_handler"}}),Xe.current=null}finally{At.current===R&&(At.current=null,Je.current=null,it(!1))}return}if(!ye){setTimeout(()=>{if(R.signal.aborted){At.current===R&&(At.current=null,Je.current=null);return}const J={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:r};Oe(oe=>[...oe,J]),At.current===R&&(At.current=null,Je.current=null,it(!1))},1e3);return}try{const J=(Date.now()+1).toString(),oe=le,qe={id:J,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:oe};_t.current&&(Lt(tt=>new Set([...tt,J])),_t.current=!1),Oe(tt=>[...tt,qe]),Je.current=J;const me=await er(y,v,tt=>{Oe(ot=>ot.map(Yt=>Yt.id===J?{...Yt,content:Yt.content+tt}:Yt))},()=>{it(!0),Qe(0)},oe,R.signal,Te);if(R.signal.aborted){me.text.trim()||Oe(tt=>tt.map(ot=>ot.id===J&&!ot.content.trim()?{...ot,content:"Generation stopped."}:ot)),Ie("answer_failed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(Nt=(Le=oe==null?void 0:oe.recommendation)==null?void 0:Le.creative)==null?void 0:Nt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"aborted",metadata:{variant:ne,source:"api_chat_assistant"}}),Xe.current=null;return}const ht=typeof me.response_time_ms=="number"?me.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-b;Oe(tt=>tt.map(ot=>ot.id===J?{...ot,content:me.text,sourceLinks:me.source_links,relatedItems:me.related_items,initialRecommendation:ot.initialRecommendation||oe,responseTimeMs:ht}:ot)),Mn(y,me.text,me.source_links,me.related_items,null,me.followup_suggestions),me.error?Ie("answer_failed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(et=(Ke=oe==null?void 0:oe.recommendation)==null?void 0:Ke.creative)==null?void 0:et.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:me.error,metadata:{variant:ne,source:"api_chat_assistant"}}):Ie("answer_completed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(pt=($t=oe==null?void 0:oe.recommendation)==null?void 0:$t.creative)==null?void 0:pt.brand_name,used_capability:me.used_capability,latency_ms:ht,status:"completed",metadata:{variant:ne,source:"api_chat_assistant",response_time_ms:ht}}),Xe.current=null}catch(J){console.error("Error sending message:",J);const oe=J instanceof Error?J.message:"Unknown error occurred";Rt(oe);const qe={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Oe(me=>[...me,qe]),Ie("answer_failed",{query:y,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:oe,metadata:{variant:ne,source:"api_chat_assistant"}}),Xe.current=null}finally{At.current===R&&(At.current=null,Je.current=null,it(!1))}},[fe,er,_e,Mn,ye,Ie,ne]),Wt=Ut,gn=a.useMemo(()=>Wt.some(r=>r==null?void 0:r.is_sponsored),[Wt]),xn=a.useMemo(()=>Wt.filter(r=>!(r&&typeof r.id=="string")?!1:Z?gn:!0),[gn,Z,Wt]),Be=a.useMemo(()=>Bn(xn),[xn]),Vt=a.useMemo(()=>xe==="below-input-container"&&W?Be.find(r=>r.is_sponsored&&r.recommendation)??null:null,[W,Be,xe]),dn=a.useCallback(async r=>{var y,v,R,U,le,Te,He;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:r.text,is_sponsored:r.is_sponsored,hasRecommendation:!!r.recommendation,recommendationId:((y=r.recommendation)==null?void 0:y.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((R=(v=r.recommendation)==null?void 0:v.tracking)!=null&&R.followup_engagement_url),sessionId:se}),_t.current=r.is_sponsored||!1,Xe.current=r.is_sponsored?r:null;const b=Be.findIndex(ue=>ue.id===r.id);Ie("suggestion_clicked",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b>=0?b:void 0,is_sponsored:r.is_sponsored,recommendation_id:(U=r.recommendation)==null?void 0:U.recommendation_id,brand_name:(He=(Te=(le=r.recommendation)==null?void 0:le.recommendation)==null?void 0:Te.creative)==null?void 0:He.brand_name,query:r.text}),Ot(r.text),r.is_sponsored&&r.recommendation&&ye?setTimeout(async()=>{var ue;try{const Me=(ue=r.recommendation.tracking)==null?void 0:ue.followup_engagement_url,Le=r.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:Me,recommendationId:Le,sessionId:se}),Me&&Le&&se?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await ye.fireFollowupEngagement(Me,Le,se),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!Me,hasRecommendationId:!!Le,hasSessionId:!!se})}catch(Me){console.error("[AdMeshIntentAssistant] Error firing sponsored suggestion engagement:",Me)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[Ot,Be,ye,se,Ie]),bn=Ls[K],tr=$s[A];a.useEffect(()=>{if(Ne.current.forEach(r=>r()),Ne.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return Be.forEach((r,b)=>{const y=V.current.get(r.id);if(!y)return;const v=`${se||"anonymous"}:${r.id}:${r.is_sponsored?"s":"o"}`;if(An.current.has(v))return;let R=null,U=null;const le=()=>{R&&(clearTimeout(R),R=null),U==null||U.disconnect(),U=null},Te=()=>{var He,ue,Me,Le,Nt;if(An.current.has(v)){le();return}if(An.current.add(v),le(),Ie("suggestion_exposure",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b,is_sponsored:r.is_sponsored,recommendation_id:(He=r.recommendation)==null?void 0:He.recommendation_id,brand_name:(Le=(Me=(ue=r.recommendation)==null?void 0:ue.recommendation)==null?void 0:Me.creative)==null?void 0:Le.brand_name}),ye&&se&&r.is_sponsored&&r.recommendation){const Ke=(Nt=r.recommendation.tracking)==null?void 0:Nt.followup_exposure_url,et=r.recommendation.recommendation_id;Ke&&et?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Ke,recommendationId:et,suggestionText:r.text,sessionId:se}),ye.fireFollowupExposure(Ke,et,se)):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Ke,hasRecommendationId:!!et,suggestionText:r.text})}};U=new IntersectionObserver(He=>{const ue=He[0];if(ue){if(ue.intersectionRatio>=.5){R||(R=setTimeout(Te,1e3));return}R&&(clearTimeout(R),R=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),U.observe(y),Ne.current.push(le)}),()=>{Ne.current.forEach(r=>r()),Ne.current=[]}},[Be,ye,se,Ie,st]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:Wt.length,safeSuggestions:xn.length,isAnalyzingIntent:ee,hasIntentError:!!re,onlyShowWhenSponsored:Z,hasSponsoredSuggestions:gn,sponsoredCount:Wt.filter(r=>r==null?void 0:r.is_sponsored).length,nonSponsoredCount:Wt.filter(r=>r&&!(r!=null&&r.is_sponsored)).length,modalShouldAppear:Z?gn:!0,suggestions:Wt.map(r=>{var b,y,v;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&v.followup_engagement_url)}}),renderedSuggestions:Be.map(r=>{var b,y,v;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&v.followup_engagement_url)}})});const we={base:`${16*T}px`,sm:`${14*T}px`,xs:`${12*T}px`},nr=je||"AI-generated responses may contain errors. Please verify important information independently.",oo=["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..."],cn=r=>{const b=(r==null?void 0:r.accentColor)||Ct,y=(r==null?void 0:r.metaColor)||ir,v=(r==null?void 0:r.includeSteps)??ne==="default",R=`${ut}s`,U=v?`${oo[Ce]} (${R})`:`Generating answer... ${R}`;return n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:r!=null&&r.compact?"8px":"10px",color:y,fontSize:r!=null&&r.compact?we.xs:we.sm},children:[n.jsx("span",{style:{width:r!=null&&r.compact?8:9,height:r!=null&&r.compact?8:9,borderRadius:999,background:b,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${$e(Ve,.28)}`,flexShrink:0}}),n.jsx("span",{children:U})]})},rr=a.useCallback((r,b)=>{if(It[r.id])return;const y=b?"helpful":"not_helpful";Ht(v=>({...v,[r.id]:y})),Ie("answer_feedback",{message_id:r.id,query:r.userQuery,status:y,latency_ms:r.responseTimeMs,metadata:{helpful:b}})},[It,Ie]);function En(r,b){if(r.role!=="assistant"||!r.content.trim()||fe&&r.id===Je.current)return null;const y=(b==null?void 0:b.accentColor)||Ct,v=(b==null?void 0:b.metaColor)||ir,R=It[r.id],U=typeof r.responseTimeMs=="number";return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${ct}`,flexWrap:"wrap"},children:[n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto",flexWrap:"wrap"},children:[n.jsx("span",{style:{fontSize:we.xs,color:v,whiteSpace:"nowrap"},children:R?"Thanks for your feedback":"Is this helpful?"}),R?n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",background:$e(y,.12),color:y,flexShrink:0},children:R==="helpful"?n.jsx(br,{size:14}):n.jsx(xr,{size:14})}):n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[n.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>rr(r,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:v,cursor:"pointer"},children:n.jsx(br,{size:14})}),n.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>rr(r,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:v,cursor:"pointer"},children:n.jsx(xr,{size:14})})]})]}),U?n.jsxs("span",{style:{fontSize:we.xs,color:v,whiteSpace:"nowrap",flex:"0 1 auto",marginLeft:"auto"},children:["Answer Completed in ",Ts(r.responseTimeMs)]}):null]})}const un=a.useCallback(()=>{const r=mt.current;if(!r)return;const b=Math.max(0,r.scrollWidth-r.clientWidth);kn(r.scrollLeft>4),Jr(r.scrollLeft<b-4)},[]);a.useEffect(()=>(un(),window.addEventListener("resize",un),()=>window.removeEventListener("resize",un)),[un,Be.length]);const or=a.useCallback(r=>{const b=mt.current;b&&b.scrollBy({left:r==="left"?-Math.max(160,Math.floor(b.clientWidth*.75)):Math.max(160,Math.floor(b.clientWidth*.75)),behavior:"smooth"})},[]),$e=(r,b)=>{if(!r||!r.startsWith("#"))return`rgba(15, 23, 42, ${b})`;const y=r.slice(1),v=y.length===3?y.split("").map(Te=>`${Te}${Te}`).join(""):y;if(v.length!==6)return r;const R=parseInt(v.slice(0,2),16),U=parseInt(v.slice(2,4),16),le=parseInt(v.slice(4,6),16);return`rgba(${R}, ${U}, ${le}, ${b})`},Ve=E.primaryColor||"#3F037F",dt=E.surfaceColor||"#ffffff",so=E.backgroundColor||"#eef2ff",ct=E.borderColor||"#e5e7eb",Ue=E.textColor||"#111827",Kt=E.textSecondaryColor||"#6b7280";$e(Ve,.12);const sr=$e(Ve,.24);$e(Ve,.38);const io=dt,Ct=Ve,yn=E.primaryTextColor||"#ffffff",ir=Kt,ar=de||"Publisher Assistant",tn=ee&&Be.length===0&&Pe.length===0,Rn=dt,Tn=dt,Gt=ct,lr=ct,dr="0 16px 64px rgba(15, 23, 42, 0.14)",In=Kt,ao=Kt,lo=Ct,cr=so,co="none",uo="rgba(15, 23, 42, 0.18)";function ur(r){return Ze?n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:r==="default"?"10px 12px":"8px 10px",borderRadius:r==="default"?"14px":"12px",border:`1px solid ${sr}`,background:$e("#ffffff",.9),marginBottom:"4px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{color:Ct,fontSize:we.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),n.jsxs("div",{style:{color:Ue,fontSize:we.sm,fontWeight:600,lineHeight:1.3},children:[Ze.brand_name," agent is active"]})]}),n.jsx("button",{type:"button",onClick:()=>{D("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${sr}`,borderRadius:999,background:$e("#ffffff",.92),color:Ct,padding:"7px 12px",fontSize:we.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function mr(r,b=ke){const y=fn&&!b,v=b||y?"9px":"11px";return n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",paddingTop:b||r==="default"?"2px":"8px",marginTop:b?"0":r==="default"?"4px":0,flexShrink:0,textAlign:"center",width:"100%"},children:n.jsx("div",{style:{color:ao,fontSize:v,lineHeight:y?1.3:1.45,maxWidth:"100%",textAlign:"center"},children:nr})})}function Dn(r){const b=r==="publisher"?[180,220,196]:["100%","82%","68%"];return r==="publisher"?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:$e(Ue,.06),flexShrink:0}}),n.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:b.map((y,v)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:40,borderRadius:"6px",background:$e(Ue,.06),backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:"none",flexShrink:0}},`suggestion-skeleton-${v}`))}),n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:$e(Ue,.06),flexShrink:0}})]}):n.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:r==="publisher"?"10px":"12px"},children:b.map((y,v)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:r==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${$e(Ve,.08)} 0%, ${$e(Ve,.18)} 50%, ${$e(Ve,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:r==="publisher"?`0 8px 22px ${$e(Ve,.08)}`:"none"}},`suggestion-skeleton-${v}`))})}function mo(r=ke){if(fe)return null;if(tn)return Dn("publisher");if(!Be.length)return null;const b=r&&Xn,y=Be.slice(0,Y);return B==="stacked"?n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:r?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:r?"240px":void 0,paddingRight:r?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:y.map(v=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":v.is_sponsored?"true":void 0,ref:sn(v.id),onClick:()=>{ne==="default"&&(at(!0),_==="floating"&&Ft(!0)),dn(v)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:"8px",border:`1px solid ${v.is_sponsored?Ve:ct}`,background:v.is_sponsored?Ve:dt,color:v.is_sponsored?yn:Ue,padding:r?"8px 10px":"10px 14px",fontSize:r?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{style:{minWidth:0},children:v.text}),W&&v.is_sponsored&&n.jsx("span",{style:{flexShrink:0,borderRadius:"6px",background:$e("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},v.id))}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:b?"4px":lt?"5px":r?"6px":"10px",flexShrink:0},children:[!b&&n.jsx("button",{type:"button",onClick:()=>or("left"),disabled:!Jt,"aria-label":"Scroll suggestions left",style:{width:lt?20:r?24:28,height:lt?20:r?24:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:"#6b7280",fontSize:lt?"13px":void 0,lineHeight:1,cursor:Jt?"pointer":"default",opacity:Jt?1:.55},children:"โน"}),n.jsx("div",{ref:mt,onScroll:un,style:{display:"flex",gap:b?"4px":lt?"5px":r?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:y.map(v=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":v.is_sponsored?"true":void 0,ref:sn(v.id),onClick:()=>{ne==="default"&&(at(!0),_==="floating"&&Ft(!0)),dn(v)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:b?"4px":lt?"5px":"8px",whiteSpace:"nowrap",borderRadius:"6px",border:`1px solid ${v.is_sponsored?Ve:ct}`,background:v.is_sponsored?Ve:dt,color:v.is_sponsored?yn:Ue,padding:b?"4px 8px":lt?"5px 8px":r?"7px 10px":"8px 14px",fontSize:b?"10px":lt?"11px":r?"12px":"13px",fontWeight:500,lineHeight:b?1:lt?1.1:void 0,boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{children:v.text}),W&&v.is_sponsored&&n.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},v.id))}),!b&&n.jsx("button",{type:"button",onClick:()=>or("right"),disabled:!Sn,"aria-label":"Scroll suggestions right",style:{width:lt?20:r?24:28,height:lt?20:r?24:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:"#6b7280",fontSize:lt?"13px":void 0,lineHeight:1,cursor:Sn?"pointer":"default",opacity:Sn?1:.55},children:"โบ"})]})}function po(r=ke){if(r||!(Vt!=null&&Vt.recommendation))return null;const b=`publisher-sponsored-creative-${Vt.id}`;return n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"2px"},children:n.jsx(nn,{messageId:b,query:Vt.text,initialRecommendation:Vt.recommendation,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,Vt.text)},onError:y=>{console.error("[AdMeshIntentAssistant] Sponsored creative error:",y)}})})}function ho(r){var b,y;return(b=r.relatedItems)!=null&&b.length||!((y=r.sourceLinks)!=null&&y.length)?null:n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"16px"},children:[n.jsx("div",{style:{width:"100%",fontSize:"11px",fontWeight:600,color:Kt},children:"Sources"}),r.sourceLinks.map(v=>n.jsxs("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Ie("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:v.title,source_url:v.url}})},style:{color:Ct,fontSize:we.xs,textDecoration:"none",borderBottom:`1px solid ${$e(Ve,.18)}`},children:[v.title||v.url," ",n.jsx(Co,{size:12,style:{display:"inline",verticalAlign:"middle"},"aria-hidden":"true"})]},`${r.id}-${v.url}`))]})}function fo(r,b=ke){var y;return(y=r.relatedItems)!=null&&y.length?n.jsxs("div",{style:{marginTop:"14px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,color:Kt,marginBottom:"8px"},children:"Related reading"}),n.jsx("div",{style:{display:"flex",gap:b?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:r.relatedItems.slice(0,4).map(v=>n.jsxs("a",{className:"admesh-publisher-source",href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Ie("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:v.title,source_url:v.url,source_publisher:v.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:b?"6px":"10px",padding:b?"10px":"14px",borderRadius:"8px",textDecoration:"none",color:Ue,border:`1px solid ${ct}`,background:dt,boxShadow:"none",flex:b?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:b?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[n.jsx("div",{style:{fontSize:b?"12px":"14px",fontWeight:650,lineHeight:1.35,color:Ue,overflowWrap:"anywhere"},children:v.title||v.url}),v.publisher&&n.jsx("div",{style:{fontSize:b?"11px":"12px",color:Kt,lineHeight:1.4,overflowWrap:"anywhere"},children:v.publisher})]},`${r.id}-${v.url}`))})]}):null}function go(r=ke){const b=r?"13px":"15px";return n.jsxs("div",{ref:ae,style:{flex:r?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"thin",padding:r?"0 2px 4px":H?"16px 16px 8px":0},children:[Pe.map(y=>{const v=y.role==="user"&&y.id===rt.current;return n.jsx("div",{ref:v?vt:void 0,style:{marginBottom:r?"16px":"28px",textAlign:y.role==="user"?"right":"left"},children:(()=>{const U=!!y.content.trim()||!fe;return n.jsx(n.Fragment,{children:n.jsxs("div",{style:{display:y.role==="assistant"?"block":"inline-block",width:y.role==="assistant"?"100%":void 0,maxWidth:y.role==="assistant"?"100%":"76%",padding:y.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:y.role==="assistant"?0:"8px",background:y.role==="user"?$e(Ue,.05):"transparent",color:Ue,boxShadow:"none",border:"none",fontSize:y.role==="assistant"?b:r?"12px":"13px",lineHeight:y.role==="assistant"?1.62:1.4},children:[y.role==="assistant"?y.content.trim()?n.jsx(Wn,{content:y.content,theme:{...E,textColor:Ue},fontSize:b}):fe&&y.id===Je.current?cn({includeSteps:!0}):null:n.jsx("p",{style:{margin:0,color:Ue},children:y.content}),y.role==="assistant"&&ho(y),y.role==="assistant"&&fo(y,r),y.role==="assistant"&&En(y),y.role==="assistant"&&U&&wt.has(y.id)&&y.initialRecommendation&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(nn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation,onFollowupDetected:ln,onRecommendationsShown:(le,Te)=>{an(le,Te,y.userQuery)},onError:le=>{console.error("[AdMeshIntentAssistant] Recommendation error:",le)}})}),y.role==="assistant"&&U&&!wt.has(y.id)&&(y.initialRecommendation||Zr)&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(nn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation||void 0,onFollowupDetected:ln,onRecommendationsShown:(le,Te)=>{an(le,Te,y.userQuery)},onError:le=>{console.error("[AdMeshIntentAssistant] Recommendation error:",le)}})})]})})})()},y.id)}),Et&&n.jsx("div",{role:"alert",style:{color:Ue,fontSize:we.sm,border:`1px solid ${ct}`,borderLeft:"3px solid #b45309",borderRadius:"6px",padding:"12px"},children:"Unable to complete the answer. Please try again."}),n.jsx("div",{ref:St})]})}if(ne==="default"){let r=function(v){const R=Rr(fn);return Hn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:y}),n.jsx("div",{style:R.shell,children:v})]}),document.body)},b=function(v=!1){const R=he(v),U=v||R&&H,le=!U&&G==="input",Te=R&&!U&&Xn,He=U&&!(ke&&m==="expand"&&!v&&Zt),ue=U?Rr(fn):null,Me=!!(ue&&fn&&!R),Le=R?zt:ue?ue.panelWidth:_==="inline"?"100%":"min(420px, calc(100vw - 32px))",Nt=R?en:ue?ue.panelHeight:"auto",Ke=R?zt:(ue==null?void 0:ue.panelMaxWidth)??"100%",et=R?en:ue==null?void 0:ue.panelMaxHeight,$t=u&&!Te&&U;return n.jsxs("div",{className:"admesh-publisher-panel","data-compact":R?"true":"false",style:{"--publisher-accent":Ct,color:Ue,width:Le,maxWidth:Ke,height:Nt,maxHeight:et,boxSizing:"border-box",display:"flex",flexDirection:"column",background:U?Rn:io,borderRadius:!R&&ue?ue.panelBorderRadius:"12px",padding:U?0:R?"6px":0,boxShadow:Me?"none":U?dr:"none",border:Me||le?"none":`1px solid ${lr}`,overflow:"hidden",minHeight:R?0:void 0},children:[n.jsx("style",{children:Gr}),$t&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:R?"8px 10px":"14px 20px",background:Tn,color:Ue,borderBottom:`1px solid ${Gt}`,flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px",minWidth:0},children:[n.jsx("div",{style:{width:R?26:32,height:R?26:32,flexShrink:0,borderRadius:"6px",background:$e(Ue,.04),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:Ct,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:dt,padding:4}}):n.jsx(Un,{size:R?14:17,strokeWidth:1.5,"aria-hidden":"true"})}),(w||g)&&n.jsxs("div",{style:{minWidth:0,overflowWrap:"anywhere"},children:[w&&n.jsx("div",{style:{fontSize:R?"13px":"14px",fontWeight:600,lineHeight:1.1,letterSpacing:0},children:i}),g&&n.jsx("div",{style:{fontSize:R?"10px":"12px",color:In,marginTop:"2px"},children:ar})]})]}),U&&(!R||v)&&n.jsx("button",{type:"button",onClick:()=>at(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"8px",border:`1px solid ${Gt}`,background:dt,color:In,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(fr,{size:16,strokeWidth:1.5,"aria-hidden":"true"})})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Te?"2px":R?"6px":"16px",minHeight:0,flex:R||U?"1 1 0":void 0,overflow:R||U?"hidden":void 0,overscrollBehavior:"contain",padding:le?R?"4px":"8px":R?"8px":"20px",justifyContent:U?void 0:"center",background:Rn},children:[ur("default"),He&&go(R),!le&&n.jsxs(n.Fragment,{children:[R&&!U&&!Te&&n.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),R&&!U&&P&&j&&Pe.length===0&&n.jsx("div",{style:{fontSize:15,fontWeight:600,textAlign:"center"},children:z}),mo(R)]}),(le||!R||U||p)&&n.jsx(Ss,{value:Ae,onChange:yt,open:le&&st&&!H,onOpenChange:le?jt:Es,suggestions:Be.slice(0,Y),registerSuggestion:sn,loading:fe,analyzing:tn,compact:R,expanded:U,showLogo:!U,suggestionPlacement:te,logoUrl:d,title:i,placeholder:M,colors:{accent:Ct,accentText:yn,surface:cr,text:Ue,muted:Kt,border:ct},onStop:jn,onSend:()=>{Xe.current=null,_t.current=!1,at(!0),_==="floating"&&Ft(!0),Ot(Ae)},onSuggestion:pt=>{at(!0),_==="floating"&&Ft(!0),dn(pt)}}),U&&mr("default",R),!U&&G==="always"&&po(R)]})]})};const y={position:"fixed",inset:0,background:uo,backdropFilter:"blur(2px)",zIndex:2147483e3};return _==="inline"?ke?n.jsxs("div",{ref:qt,className:"admesh-component","data-admesh-theme":ce,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-behavior":m,"data-admesh-ad-slot-expanded":Cn?"true":"false",style:{width:zt,height:en,maxWidth:zt,maxHeight:en,position:"relative",overflow:"hidden"},children:[b(!1),Zt&&typeof document<"u"&&r(b(!0))]}):n.jsxs("div",{className:"admesh-component","data-admesh-theme":ce,style:{width:"100%",position:"relative"},children:[b(!1),H&&typeof document<"u"&&r(b(!0))]}):De?n.jsxs("div",{className:"admesh-component","data-admesh-theme":ce,children:[!H&&n.jsx("div",{style:{position:"fixed",...bn,zIndex:2147483001},children:b(!1)}),H&&typeof document<"u"&&r(b(!0))]}):n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsxs("button",{type:"button",onClick:Zn,style:{position:"fixed",...bn,zIndex:2147483e3,border:"none",borderRadius:"6px",background:E.primaryColor,color:yn,display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",fontWeight:600,padding:"12px 16px",boxShadow:"0 4px 16px rgba(15, 23, 42, 0.12)",cursor:"pointer"},children:[n.jsx(Un,{size:16,strokeWidth:1.5,"aria-hidden":"true"}),s]})})}return Be.length===0&&!tn?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):_==="inline"?n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:mn(f)??"100%",backgroundColor:"#eef2ff",fontSize:we.base,...o},children:n.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[tn?Dn("legacy"):Be.length>0&&n.jsx("div",{className:"flex flex-col gap-3",children:Be.slice(0,Y).map((r,b)=>n.jsxs("button",{ref:sn(r.id),onClick:()=>dn(r),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:b===0?"100%":b===1?"82%":"68%",backgroundColor:E.surfaceColor||"#ffffff",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:we.sm},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},r.id))}),Pe.length>0&&n.jsxs("div",{ref:ae,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:E.textColor,overscrollBehavior:"contain",WebkitOverflowScrolling:"touch"},children:[Pe.map(r=>{const b=r.role==="user"&&r.id===rt.current;return n.jsx("div",{ref:b?vt:void 0,className:r.role==="user"?"text-right":"text-left",children:n.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:r.role==="user"?E.primaryColor:"#ffffff",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,fontSize:we.sm},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx(Wn,{content:r.content,theme:E,fontSize:we.sm}),En(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):fe&&r.id===Je.current?cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:r.content})})},r.id)}),fe&&!Pe.some(r=>r.role==="assistant"&&r.id===Je.current&&!r.content.trim())&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})}),Et&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:"Connection issue. Please try again."}),n.jsx("div",{ref:St})]}),n.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"text",value:Ae,onChange:r=>yt(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(fe){r.preventDefault();return}Ot(Ae)}},placeholder:M,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textColor,fontSize:we.sm}}),n.jsx("button",{onClick:()=>{if(fe){jn();return}Ot(Ae)},disabled:!fe&&!Ae.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:fe?"#dc2626":E.primaryColor,color:"#ffffff"},children:fe?n.jsx(zn,{size:18}):n.jsx(gr,{size:18})})]})}),n.jsxs("div",{className:"space-y-2 text-center",children:[n.jsxs("p",{style:{color:E.textSecondaryColor,fontSize:we.xs,fontWeight:600},children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),n.jsx("p",{style:{color:E.textSecondaryColor,fontSize:we.xs,lineHeight:1.5},children:nr})]})]})})}):De?n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...H?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...bn,width:mn(f)??tr.width,height:mn(h)??tr.height},backgroundColor:H?Rn:E.backgroundColor,zIndex:9999,fontSize:we.base,borderRadius:H?"20px":"16px",border:H?`1px solid ${lr}`:"1px solid transparent",boxShadow:H?dr:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[u&&n.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:H?Gt:"transparent",background:H?Tn:E.backgroundColor,padding:H?"18px 20px":"16px"},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{style:{width:H?40:32,height:H?40:32,borderRadius:H?"14px":"10px",background:$e(Ve,.08),color:Ct,display:"flex",alignItems:"center",justifyContent:"center",fontSize:H?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(w||g&&H)&&n.jsxs("div",{children:[w&&n.jsx("div",{className:"font-medium",style:{color:E.textColor,fontSize:H?"20px":we.base,fontWeight:700,letterSpacing:H?"-0.02em":0},children:i}),g&&H&&n.jsx("div",{style:{color:In,fontSize:"12px",marginTop:"2px"},children:ar})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[!ke&&n.jsx("button",{onClick:ro,className:"transition-colors",title:H?"Minimize":"Expand",style:{width:H?36:28,height:H?36:28,borderRadius:H?"12px":"10px",border:`1px solid ${H?Gt:"transparent"}`,background:H?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:H?n.jsx(fr,{size:16,style:{color:E.textSecondaryColor}}):n.jsx(Io,{size:16,style:{color:E.textSecondaryColor}})}),n.jsx("button",{onClick:no,className:"transition-colors",style:{width:H?36:28,height:H?36:28,borderRadius:H?"12px":"10px",border:`1px solid ${H?Gt:"transparent"}`,background:H?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(zn,{size:16,style:{color:E.textSecondaryColor}})})]})]}),n.jsxs("div",{ref:ae,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:H?"20px":"16px"},children:[ur("legacy"),P&&Pe.length===0&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",children:n.jsx("p",{style:{color:E.textColor,margin:0,fontSize:we.sm},children:z})})}),Pe.map(r=>{const b=r.role==="user"&&r.id===rt.current;return n.jsxs("div",{ref:b?vt:void 0,className:"mb-3",children:[n.jsx("div",{className:r.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:r.role==="user"?lo:"transparent",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,border:"none",borderRadius:r.role==="user"?H?"14px":"12px":0,padding:r.role==="user"?H?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none"},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{fontSize:`calc(${we.sm} * 1.3)`,lineHeight:1.65},children:n.jsx(Wn,{content:r.content,theme:E,fontSize:`calc(${we.sm} * 1.3)`})}),En(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):fe&&r.id===Je.current?cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,fontSize:we.sm,lineHeight:"1.4"},children:r.content})}),r.role==="assistant"&&!wt.has(r.id)&&n.jsx(nn,{messageId:r.id,query:r.userQuery,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}}),r.role==="assistant"&&wt.has(r.id)&&r.initialRecommendation&&!fe&&n.jsxs("div",{className:"mb-4",children:[n.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),n.jsx(nn,{messageId:r.id,query:r.userQuery,initialRecommendation:r.initialRecommendation,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}})]})]},r.id)}),fe&&!Pe.some(r=>r.role==="assistant"&&r.id===Je.current&&!r.content.trim())&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})})}),Et&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textSecondaryColor},children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{style:{fontSize:we.xs},children:"โ ๏ธ"}),n.jsx("span",{style:{fontSize:we.sm},children:"Connection issue. Please try again."})]})})}),n.jsx("div",{ref:St})]}),Pe.length===0&&tn&&n.jsx("div",{className:"px-4 pb-2",children:Dn("legacy")}),Be.length>0&&Pe.length===0&&!tn&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:Be.slice(0,Y).map(r=>n.jsxs("button",{ref:sn(r.id),onClick:()=>dn(r),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:E.surfaceColor||"#f8fafc",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:we.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b"},children:"Ad"})]},r.id))})}),re&&!ee&&xn.length===0&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:n.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:E.surfaceColor,borderColor:E.borderColor,color:E.textSecondaryColor},children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("span",{style:{fontSize:we.sm},children:"Intent analysis failed"}),n.jsx("button",{onClick:Re,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:E.primaryColor,color:"#ffffff"},children:"Retry"})]}),n.jsx("span",{style:{fontSize:we.xs},children:re})]})})}),n.jsxs("div",{className:"p-3 border-t",style:{borderColor:H?Gt:"transparent",padding:H?"18px 20px":void 0,background:H?Tn:void 0},children:[n.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${Gt}`,borderRadius:H?"16px":"12px",background:cr,boxShadow:H?co:"none",padding:H?"8px 8px 8px 14px":void 0},children:[n.jsx("input",{type:"text",value:Ae,onChange:r=>yt(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(fe){r.preventDefault();return}Ot(Ae)}},placeholder:M,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textColor,fontSize:H?"15px":we.sm,"--tw-ring-color":E.primaryColor}}),n.jsx("button",{onClick:()=>{if(fe){jn();return}Ot(Ae)},disabled:!fe&&!Ae.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:fe?"#dc2626":E.primaryColor,color:"#ffffff",borderRadius:H?"12px":"10px",width:H?"46px":void 0,height:H?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:H?`0 10px 20px ${$e(Ve,.18)}`:"none"},children:fe?n.jsx(zn,{size:14}):n.jsx(gr,{size:14})})]}),mr("legacy")]})]})}):n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsx("button",{onClick:Zn,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",...bn,backgroundColor:E.primaryColor,color:"#ffffff",zIndex:9999,fontSize:we.base,...o},children:n.jsx("span",{className:"font-medium",children:s})})})},wn="admesh:streamingStart",_n="admesh:streamingComplete";function Ws(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(wn,{detail:o});window.dispatchEvent(s),l.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function Bs(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(_n,{detail:s});window.dispatchEvent(i),l.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function Us(t,e,o){const s=i=>{const d=i;d.detail.messageId===t&&d.detail.sessionId===e&&(l.log("[StreamingEvents] ๐จ Received streamingStart event"),o(d.detail))};return window.addEventListener(wn,s),()=>{window.removeEventListener(wn,s)}}function Xr(t,e,o){l.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const d=i;l.log("[StreamingEvents] ๐จ Received streamingComplete event (checking match)",{receivedMessageId:d.detail.messageId,receivedSessionId:d.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:d.detail.messageId===t,sessionIdMatch:d.detail.sessionId===e}),d.detail.messageId===t&&d.detail.sessionId===e?(l.log("[StreamingEvents] โ
Event matched! Calling callback"),o(d.detail)):l.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(_n,s),()=>{l.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(_n,s)}}const vn=()=>{const t=new Set,e=new Map,o=d=>{const u=e.get(d);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(d))};return{startTracking:({exposureUrl:d,recommendationId:u,linkElement:w,sessionId:g,logPrefix:_="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!d||!w){_&&l.warn(`${_} โ ๏ธ Missing exposure tracking data`);return}const c=`${g||"anonymous"}::${u||d}`;if(t.has(c)||e.has(c))return;const m={observer:void 0,timeoutId:null,viewableStart:null},k=()=>{o(c),t.add(c),fetch(d,{method:"GET",keepalive:!0}).then(()=>{_&&l.log(`${_} โ
Exposure pixel fired`)}).catch(()=>{_&&l.warn(`${_} โ ๏ธ Failed to fire exposure pixel`),t.delete(c)})},j=new IntersectionObserver(p=>{p.forEach(x=>{x.intersectionRatio>=.5?m.viewableStart===null&&(m.viewableStart=performance.now(),m.timeoutId=setTimeout(k,1e3)):(m.viewableStart=null,m.timeoutId&&(clearTimeout(m.timeoutId),m.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});m.observer=j,j.observe(w),e.set(c,m)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},Hs=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:d=[],onLinksFound:u,onNoLinksFound:w,children:g})=>{const[_,c]=a.useState(!1),[m,k]=a.useState(!0),[j,p]=a.useState(!1),x=a.useRef(vn()),f=a.useRef(u),h=a.useRef(w),S=a.useRef(t),T=a.useRef(s),K=a.useRef(o),A=a.useRef(i);a.useEffect(()=>{f.current=u,h.current=w,S.current=t,T.current=s,K.current=o,A.current=i},[u,w,t,s,o,i]),a.useEffect(()=>()=>{x.current.cleanup()},[]);const C=a.useCallback(({exposureUrl:$,recommendationId:F,linkElement:P})=>{x.current.startTracking({exposureUrl:$,recommendationId:F,linkElement:P,sessionId:K.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),L=a.useCallback(()=>{l.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const $=document.getElementById(S.current);if(!$){l.warn("[FinalLinkDetectionCheck] Container not found"),c(!0),w();return}const F=new Kn({autoAddLabels:!0,fireExposurePixels:!0}),P=d.length>0?d:[];l.log(`[FinalLinkDetectionCheck] ๐ Using ${P.length} recommendations for link detection`),P.length>0&&process.env.NODE_ENV==="development"&&P.forEach((M,W)=>{var O,Y,B,G,te,xe,Z,ne,_e;l.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${W+1} (DEV):`,{recommendation_id:M==null?void 0:M.recommendation_id,click_url:((O=M==null?void 0:M.tracking)==null?void 0:O.click_url)||((B=(Y=M==null?void 0:M.recommendation)==null?void 0:Y.creative)==null?void 0:B.landing_page_url),format:(G=M==null?void 0:M.recommendation)==null?void 0:G.format,brand_name:(Z=(xe=(te=M.render)==null?void 0:te.creative)==null?void 0:xe.advertiser)==null?void 0:Z.brand_name,cta_url:(_e=(ne=M.render)==null?void 0:ne.creative)==null?void 0:_e.landing_page_url})});const z=F.scanAndProcessLinks($,P,({exposureUrl:M,recommendationId:W,linkElement:O})=>C({exposureUrl:M,recommendationId:W,linkElement:O}));l.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${z.length} links`),z.length>0?(l.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),p(!0),f.current(z.length)):(l.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${P.length} previous recommendation(s) if available)`),p(!1),h.current()),c(!0)}catch{l.error("[FinalLinkDetectionCheck] Error during final check"),c(!0),h.current()}},[C,d]);return a.useEffect(()=>{l.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:d.length});let $=null,F=!1;const P=Xr(e,o,z=>{l.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:z.messageId,sessionId:z.sessionId,timestamp:z.timestamp}),F=!0,$&&(clearTimeout($),$=null),k(!1),setTimeout(()=>{L()},100)});return $=setTimeout(()=>{F||(l.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),k(!1),setTimeout(()=>{L()},100))},5e3),()=>{l.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),$&&clearTimeout($),P()}},[e,o]),m?n.jsx(n.Fragment,{}):_?j?(l.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),n.jsx(n.Fragment,{})):(l.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),n.jsx(n.Fragment,{children:g})):n.jsx(n.Fragment,{})},qs=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:d,className:u,query:w,onFallbackChange:g,onWeaveAttempt:_,onWeaveOutcome:c})=>{var M,W;const{sessionId:m,sdk:k,language:j,location:p,userId:x,model:f,messages:h}=on(),S=a.useRef(null),T=`weave-ad-container-${t}`,K=a.useRef(vn()),A=a.useRef(!1),C=a.useRef(null),[L,$]=a.useState([]),F=a.useRef([]);a.useEffect(()=>(C.current||(C.current=new Kn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{C.current&&(C.current.stopWatching(),C.current.clearCache())}),[]),a.useEffect(()=>()=>{K.current.cleanup()},[]),a.useEffect(()=>{(async()=>{var Y;if(!k||!(w!=null&&w.trim())||!t){l.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{l.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const B=await k.fetchPlatformResponse({query:w.trim(),sessionId:m,messageId:t,language:j,location:p,userId:x,model:f,messages:h}),G=(B==null?void 0:B.status)==="generated"?[B]:[];if($(G),F.current=G,l.log("[WeaveAdFormatContainer] ๐ฅ Got platform response:",{status:B==null?void 0:B.status,recommendationId:B==null?void 0:B.recommendation_id,hasRecommendation:!!(B!=null&&B.recommendation),format:(Y=B==null?void 0:B.recommendation)==null?void 0:Y.format}),B!=null&&B.recommendation){const te=B.recommendation.creative,xe=te.landing_page_url;l.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:te.brand_name,headline:te.headline,description:te.description,brandUrl:xe})}else l.log("[WeaveAdFormatContainer] โ ๏ธ No recommendation found in platform response")}catch(B){l.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",B),$([])}})()},[k,m,t,w]),a.useEffect(()=>{const O=S.current;if(!O||!C.current)return;const Y=C.current,B=({exposureUrl:xe,recommendationId:Z,linkElement:ne})=>{K.current.startTracking({exposureUrl:xe,recommendationId:Z,linkElement:ne,sessionId:m,logPrefix:"[WeaveAdFormatContainer]"})},te=setTimeout(()=>{l.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),_==null||_(t);const xe=F.current.length>0?F.current:[];l.log(`[WeaveAdFormatContainer] ๐ Using ${xe.length} recommendations for link detection`);try{const Z=Y.scanAndProcessLinks(O,xe,B);Z.length>0&&!A.current?(A.current=!0,l.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${Z.length} links detected`),c==null||c(t,!0,`Found ${Z.length} links`),s==null||s(Z.length),g==null||g(!1)):A.current||l.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(Z){const ne=Z instanceof Error?Z.message:String(Z);l.error(`[WeaveAdFormatContainer] Weave injection failed: ${ne}`),c==null||c(t,!1,ne),i==null||i(),g==null||g(!0)}},100);return Y.watchForNewLinks(O,F.current,B),()=>{clearTimeout(te),Y.stopWatching()}},[e,m,t,s,g,_,c]);const P=(W=(M=L[0])==null?void 0:M.recommendation)==null?void 0:W.format,z=P==="weave";return a.useEffect(()=>{w&&z&&l.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${P}) - skipping fallback recommendations`)},[w,z,P]),n.jsxs(n.Fragment,{children:[n.jsx("div",{ref:S,id:T,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),w&&!z&&n.jsx(Hs,{containerId:T,messageId:t,sessionId:m,sdk:k,query:w,recommendations:L,onLinksFound:O=>{l.log(`[WeaveAdFormatContainer] โ
Links found (${O}) - no fallback needed`),c==null||c(t,!0,`Found ${O} links in final check`),s==null||s(O),g==null||g(!1)},onNoLinksFound:()=>{l.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),l.log(`[WeaveAdFormatContainer] ๐ Passing ${L.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),i==null||i(),g==null||g(!0)},children:n.jsx(qr,{format:o,messageId:t,query:w,fallback:!0,onError:d,previousRecommendations:L.length>0?L:void 0})})]})},Os=t=>{const{sdk:e,sessionId:o}=on(),s=a.useRef(!1),i=a.useRef(0),d=a.useRef(!1),u=a.useRef(!1),w=a.useRef(null),g=a.useRef(vn());a.useEffect(()=>()=>{g.current.cleanup()},[]);const _=a.useCallback(({exposureUrl:h,recommendationId:S,linkElement:T})=>{g.current.startTracking({exposureUrl:h,recommendationId:S,linkElement:T,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),c=a.useRef(Date.now()),m=a.useRef(0),k=a.useRef(null),j=a.useRef([]),p=a.useRef(300),x=a.useCallback(async()=>{var h,S,T,K;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const A=document.getElementById(t.llmOutputContainerId);if(!A)return;const C=(h=e.getWeaveProcessor)==null?void 0:h.call(e);if(!C)return;const L=C.scanAndProcessLinks(A,[],({exposureUrl:F,recommendationId:P,linkElement:z})=>_({exposureUrl:F,recommendationId:P,linkElement:z}));i.current=L.length;const $=L.length>0;if($&&!d.current)d.current=!0,(S=t.onLinksDetected)==null||S.call(t,L.length),u.current=!0;else if(!$&&d.current)d.current=!1,u.current=!1;else if(!$&&!u.current){w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current),m.current=0,c.current=Date.now();const F=Math.max(100,p.current/3);k.current=setInterval(()=>{var W;const z=Date.now()-c.current,M=p.current;z>=M?(m.current++,m.current>=2&&(k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((W=t.onNoLinksDetected)==null||W.call(t),u.current=!0))):m.current=0},F);const P=Math.max(1500,p.current*5);w.current=setTimeout(()=>{var z;k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((z=t.onNoLinksDetected)==null||z.call(t),u.current=!0)},P)}else $&&u.current&&!d.current&&(w.current&&(clearTimeout(w.current),w.current=null),d.current=!0,(T=t.onLinksDetected)==null||T.call(t,L.length),u.current=!0)}catch(A){const C=A instanceof Error?A:new Error(String(A));(K=t.onError)==null||K.call(t,C)}finally{s.current=!1}}},[e,o,t,_]),f=a.useCallback(()=>{const h=j.current;if(h.length<2){p.current=300;return}const S=[];for(let A=1;A<h.length;A++)S.push(h[A]-h[A-1]);const T=S.reduce((A,C)=>A+C,0)/S.length,K=Math.max(100,Math.min(T*3,1e3));p.current=K},[]);return a.useEffect(()=>{const h=document.getElementById(t.llmOutputContainerId);if(!h)return;x();const S=new MutationObserver(()=>{const T=Date.now();c.current=T,m.current=0,j.current.push(T),j.current.length>10&&j.current.shift(),f(),x()});return S.observe(h,{childList:!0,subtree:!0,characterData:!1}),()=>{S.disconnect(),w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current)}},[t.llmOutputContainerId,x,f]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:d.current,shouldRenderFallback:!d.current&&u.current,processWeaveFormat:x}},Vs="1.0.31";exports.AdMeshBadge=Kr;exports.AdMeshCompactCard=qn;exports.AdMeshContext=On;exports.AdMeshFollowup=Hr;exports.AdMeshIntentAssistant=Fs;exports.AdMeshLayout=Nr;exports.AdMeshLinkTracker=Vr;exports.AdMeshProvider=Br;exports.AdMeshRecommendations=nn;exports.AdMeshRenderer=Ur;exports.AdMeshSDK=pn;exports.AdMeshTailAd=xs;exports.AdMeshTracker=$r;exports.AdMeshViewabilityTracker=hn;exports.STREAMING_COMPLETE_EVENT=_n;exports.STREAMING_START_EVENT=wn;exports.VERSION=Vs;exports.WeaveAdFormatContainer=qs;exports.WeaveAdFormatProvider=ms;exports.WeaveFallbackRecommendations=qr;exports.WeaveResponseProcessor=Kn;exports.callAnalyzeIntentEndpoint=Fr;exports.createInlineExposureTracker=vn;exports.dispatchStreamingCompleteEvent=Bs;exports.dispatchStreamingStartEvent=Ws;exports.extractHeadingsDirectly=Lr;exports.onStreamingComplete=Xr;exports.onStreamingStart=Us;exports.useAdMesh=on;exports.useAdMeshContext=Vn;exports.useAdMeshStyles=Yr;exports.useViewabilityTracker=zr;exports.useWeaveAdFormat=Os;exports.useWeaveAdFormatContext=ps;
|
|
1182
|
+
`);for(const Yt of ot)if(Yt.startsWith("data: ")){const Pn=Yt.slice(6);if(Pn.trim()==="[DONE]")return Ze&&ge("turn_completed",{source:"publisher_assistant",recommendation_id:Ze.recommendation_id}).catch(Fe=>{console.warn("[AdMeshIntentAssistant] Failed to report delegation turn_completed",Fe)}),{text:Ke,source_links:et,related_items:$t,followup_suggestions:pt,used_capability:J,response_time_ms:oe};try{const Fe=JSON.parse(Pn);switch(Fe.type){case"content":{const pr=Fe.content||"";Ke+=pr,y==null||y(pr);break}case"final":{Ke=Fe.reply||Ke,et=Array.isArray(Fe.source_links)?Fe.source_links:void 0,$t=Array.isArray(Fe.related_items)?Fe.related_items:void 0,pt=Array.isArray(Fe.followup_suggestions)?Fe.followup_suggestions:void 0,J=typeof Fe.used_capability=="string"?Fe.used_capability:J,oe=typeof Fe.response_time_ms=="number"?Fe.response_time_ms:oe;break}case"followup_suggestions":{pt=Array.isArray(Fe.followup_suggestions)?Fe.followup_suggestions:pt;break}case"error":throw new Error(Fe.message||"Unknown streaming error");case"session_start":v==null||v(),console.log("Session started:",Fe.session_id);break}}catch{console.warn("Failed to parse streaming chunk:",Pn);continue}}}}catch(me){if(U!=null&&U.aborted)return{text:Ke,source_links:et,related_items:$t,followup_suggestions:pt,used_capability:J,response_time_ms:oe,error:"aborted"};throw console.error("Stream processing error:",me),me}finally{Le.releaseLock()}return{text:Ke,source_links:et,related_items:$t,followup_suggestions:pt,used_capability:J,response_time_ms:oe}})()}catch(Me){return U!=null&&U.aborted?{text:"",error:"aborted"}:(console.error("Error calling assistant API:",Me),{text:"I'm having trouble connecting to my services right now. Please try again in a moment.",error:Me instanceof Error?Me.message:"request_failed"})}},[ye,se,N,Q,Ze,ge]),jn=a.useCallback(()=>{const r=At.current;if(!r||r.signal.aborted)return;r.abort(),it(!1),Xe.current=null,_t.current=!1;const b=Je.current;b&&Oe(y=>y.map(v=>v.id===b&&!v.content.trim()?{...v,content:"Generation stopped."}:v))},[]),Ot=a.useCallback(async r=>{var ue,Me,Le,Nt,Ke,et,$t,pt;if(!r.trim()||fe)return;const b=typeof performance<"u"?performance.now():Date.now(),y=r.trim(),v=Date.now().toString(),R=new AbortController,U=Xe.current,le=(U==null?void 0:U.recommendation)||null,Te=Pe.filter(J=>(J.role==="user"||J.role==="assistant")&&J.content.trim()).slice(-6).map(J=>({role:J.role,content:J.content.trim().slice(0,1200)}));At.current=R,Je.current=null,rt.current=v,kt.current=!0,Pt.current=!0,Xe.current=null,q(J=>J.some(oe=>oe.is_sponsored)?J.filter(oe=>!oe.is_sponsored):J),Rt(null);const He={id:v,role:"user",content:y,timestamp:new Date};if(Ie("query_submitted",{message_id:v,query:y}),Oe(J=>[...J,He]),yt(""),it(!0),ne==="default"&&_e){try{const J=(Date.now()+1).toString(),oe={id:J,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:null};_t.current&&(Lt(ht=>new Set([...ht,J])),_t.current=!1),Oe(ht=>[...ht,oe]),Je.current=J;const qe=await _e(y,{sponsoredSuggestion:U});if(R.signal.aborted){Xe.current=null;return}const me=qe.recommendation||le||null;console.log("[AdMeshIntentAssistant] Query handler completed:",{query:r,hasResponseRecommendation:!!qe.recommendation,hasSponsoredSuggestionRecommendation:!!le,finalRecommendationId:me==null?void 0:me.recommendation_id}),Oe(ht=>ht.map(tt=>tt.id===J?{...tt,content:qe.answer,sourceLinks:qe.source_links,relatedItems:qe.related_items,initialRecommendation:me,responseTimeMs:(typeof performance<"u"?performance.now():Date.now())-b}:tt)),Mn(y,qe.answer,qe.source_links,qe.related_items,qe.recommendation||null,qe.followup_suggestions),Ie("answer_completed",{message_id:J,query:y,recommendation_id:me==null?void 0:me.recommendation_id,brand_name:(Me=(ue=me==null?void 0:me.recommendation)==null?void 0:ue.creative)==null?void 0:Me.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"completed",metadata:{variant:ne,source:"query_handler"}}),Xe.current=null}catch(J){console.error("Error sending message:",J);const oe=J instanceof Error?J.message:"Unknown error occurred";Rt(oe);const qe={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Oe(me=>[...me,qe]),Ie("answer_failed",{query:y,status:oe,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,metadata:{variant:ne,source:"query_handler"}}),Xe.current=null}finally{At.current===R&&(At.current=null,Je.current=null,it(!1))}return}if(!ye){setTimeout(()=>{if(R.signal.aborted){At.current===R&&(At.current=null,Je.current=null);return}const J={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:r};Oe(oe=>[...oe,J]),At.current===R&&(At.current=null,Je.current=null,it(!1))},1e3);return}try{const J=(Date.now()+1).toString(),oe=le,qe={id:J,role:"assistant",content:"",timestamp:new Date,recommendations:[],userQuery:r,initialRecommendation:oe};_t.current&&(Lt(tt=>new Set([...tt,J])),_t.current=!1),Oe(tt=>[...tt,qe]),Je.current=J;const me=await er(y,v,tt=>{Oe(ot=>ot.map(Yt=>Yt.id===J?{...Yt,content:Yt.content+tt}:Yt))},()=>{it(!0),Qe(0)},oe,R.signal,Te);if(R.signal.aborted){me.text.trim()||Oe(tt=>tt.map(ot=>ot.id===J&&!ot.content.trim()?{...ot,content:"Generation stopped."}:ot)),Ie("answer_failed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(Nt=(Le=oe==null?void 0:oe.recommendation)==null?void 0:Le.creative)==null?void 0:Nt.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:"aborted",metadata:{variant:ne,source:"api_chat_assistant"}}),Xe.current=null;return}const ht=typeof me.response_time_ms=="number"?me.response_time_ms:(typeof performance<"u"?performance.now():Date.now())-b;Oe(tt=>tt.map(ot=>ot.id===J?{...ot,content:me.text,sourceLinks:me.source_links,relatedItems:me.related_items,initialRecommendation:ot.initialRecommendation||oe,responseTimeMs:ht}:ot)),Mn(y,me.text,me.source_links,me.related_items,null,me.followup_suggestions),me.error?Ie("answer_failed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(et=(Ke=oe==null?void 0:oe.recommendation)==null?void 0:Ke.creative)==null?void 0:et.brand_name,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:me.error,metadata:{variant:ne,source:"api_chat_assistant"}}):Ie("answer_completed",{message_id:J,query:y,recommendation_id:oe==null?void 0:oe.recommendation_id,brand_name:(pt=($t=oe==null?void 0:oe.recommendation)==null?void 0:$t.creative)==null?void 0:pt.brand_name,used_capability:me.used_capability,latency_ms:ht,status:"completed",metadata:{variant:ne,source:"api_chat_assistant",response_time_ms:ht}}),Xe.current=null}catch(J){console.error("Error sending message:",J);const oe=J instanceof Error?J.message:"Unknown error occurred";Rt(oe);const qe={id:(Date.now()+1).toString(),role:"assistant",content:"Sorry, I encountered an error. Please try again.",timestamp:new Date};Oe(me=>[...me,qe]),Ie("answer_failed",{query:y,latency_ms:(typeof performance<"u"?performance.now():Date.now())-b,status:oe,metadata:{variant:ne,source:"api_chat_assistant"}}),Xe.current=null}finally{At.current===R&&(At.current=null,Je.current=null,it(!1))}},[fe,er,_e,Mn,ye,Ie,ne]),Wt=Ut,gn=a.useMemo(()=>Wt.some(r=>r==null?void 0:r.is_sponsored),[Wt]),xn=a.useMemo(()=>Wt.filter(r=>!(r&&typeof r.id=="string")?!1:Z?gn:!0),[gn,Z,Wt]),Be=a.useMemo(()=>Bn(xn),[xn]),Vt=a.useMemo(()=>xe==="below-input-container"&&W?Be.find(r=>r.is_sponsored&&r.recommendation)??null:null,[W,Be,xe]),dn=a.useCallback(async r=>{var y,v,R,U,le,Te,He;console.log("[AdMeshIntentAssistant] ๐ฑ๏ธ Suggestion clicked:",{text:r.text,is_sponsored:r.is_sponsored,hasRecommendation:!!r.recommendation,recommendationId:((y=r.recommendation)==null?void 0:y.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((R=(v=r.recommendation)==null?void 0:v.tracking)!=null&&R.followup_engagement_url),sessionId:se}),_t.current=r.is_sponsored||!1,Xe.current=r.is_sponsored?r:null;const b=Be.findIndex(ue=>ue.id===r.id);Ie("suggestion_clicked",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b>=0?b:void 0,is_sponsored:r.is_sponsored,recommendation_id:(U=r.recommendation)==null?void 0:U.recommendation_id,brand_name:(He=(Te=(le=r.recommendation)==null?void 0:le.recommendation)==null?void 0:Te.creative)==null?void 0:He.brand_name,query:r.text}),Ot(r.text),r.is_sponsored&&r.recommendation&&ye?setTimeout(async()=>{var ue;try{const Me=(ue=r.recommendation.tracking)==null?void 0:ue.followup_engagement_url,Le=r.recommendation.recommendation_id;console.log("[AdMeshIntentAssistant] ๐ฏ Preparing to fire sponsored suggestion engagement:",{followupEngagementUrl:Me,recommendationId:Le,sessionId:se}),Me&&Le&&se?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing sponsored suggestion engagement tracking"),await ye.fireFollowupEngagement(Me,Le,se),console.log("[AdMeshIntentAssistant] โ
Engagement tracking fired successfully")):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing required data for engagement tracking:",{hasFollowupEngagementUrl:!!Me,hasRecommendationId:!!Le,hasSessionId:!!se})}catch(Me){console.error("[AdMeshIntentAssistant] Error firing sponsored suggestion engagement:",Me)}},0):console.log("[AdMeshIntentAssistant] โน๏ธ Not a sponsored suggestion or missing data, skipping engagement tracking")},[Ot,Be,ye,se,Ie]),bn=Ls[K],tr=$s[A];a.useEffect(()=>{if(Ne.current.forEach(r=>r()),Ne.current=[],!(typeof window>"u"||typeof IntersectionObserver>"u"))return Be.forEach((r,b)=>{const y=V.current.get(r.id);if(!y)return;const v=`${se||"anonymous"}:${r.id}:${r.is_sponsored?"s":"o"}`;if(An.current.has(v))return;let R=null,U=null;const le=()=>{R&&(clearTimeout(R),R=null),U==null||U.disconnect(),U=null},Te=()=>{var He,ue,Me,Le,Nt;if(An.current.has(v)){le();return}if(An.current.add(v),le(),Ie("suggestion_exposure",{suggestion_id:r.id,suggestion_text:r.text,suggestion_type:r.type,suggestion_position:b,is_sponsored:r.is_sponsored,recommendation_id:(He=r.recommendation)==null?void 0:He.recommendation_id,brand_name:(Le=(Me=(ue=r.recommendation)==null?void 0:ue.recommendation)==null?void 0:Me.creative)==null?void 0:Le.brand_name}),ye&&se&&r.is_sponsored&&r.recommendation){const Ke=(Nt=r.recommendation.tracking)==null?void 0:Nt.followup_exposure_url,et=r.recommendation.recommendation_id;Ke&&et?(console.log("[AdMeshIntentAssistant] ๐ฏ Firing viewable sponsored suggestion exposure:",{exposureUrl:Ke,recommendationId:et,suggestionText:r.text,sessionId:se}),ye.fireFollowupExposure(Ke,et,se)):console.warn("[AdMeshIntentAssistant] โ ๏ธ Missing exposure URL or recommendation ID for sponsored suggestion:",{hasExposureUrl:!!Ke,hasRecommendationId:!!et,suggestionText:r.text})}};U=new IntersectionObserver(He=>{const ue=He[0];if(ue){if(ue.intersectionRatio>=.5){R||(R=setTimeout(Te,1e3));return}R&&(clearTimeout(R),R=null)}},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"}),U.observe(y),Ne.current.push(le)}),()=>{Ne.current.forEach(r=>r()),Ne.current=[]}},[Be,ye,se,Ie,st]),console.log("[AdMeshIntentAssistant] ๐ฅ Received suggestions:",{totalSuggestions:Wt.length,safeSuggestions:xn.length,isAnalyzingIntent:ee,hasIntentError:!!re,onlyShowWhenSponsored:Z,hasSponsoredSuggestions:gn,sponsoredCount:Wt.filter(r=>r==null?void 0:r.is_sponsored).length,nonSponsoredCount:Wt.filter(r=>r&&!(r!=null&&r.is_sponsored)).length,modalShouldAppear:Z?gn:!0,suggestions:Wt.map(r=>{var b,y,v;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&v.followup_engagement_url)}}),renderedSuggestions:Be.map(r=>{var b,y,v;return{id:r==null?void 0:r.id,text:r==null?void 0:r.text,type:r==null?void 0:r.type,is_sponsored:r==null?void 0:r.is_sponsored,hasRecommendation:!!(r!=null&&r.recommendation),recommendationId:((b=r==null?void 0:r.recommendation)==null?void 0:b.recommendation_id)||void 0,hasFollowupEngagementUrl:!!((v=(y=r==null?void 0:r.recommendation)==null?void 0:y.tracking)!=null&&v.followup_engagement_url)}})});const we={base:`${16*T}px`,sm:`${14*T}px`,xs:`${12*T}px`},nr=je||"AI-generated responses may contain errors. Please verify important information independently.",oo=["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..."],cn=r=>{const b=(r==null?void 0:r.accentColor)||Ct,y=(r==null?void 0:r.metaColor)||ir,v=(r==null?void 0:r.includeSteps)??ne==="default",R=`${ut}s`,U=v?`${oo[Ce]} (${R})`:`Generating answer... ${R}`;return n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:r!=null&&r.compact?"8px":"10px",color:y,fontSize:r!=null&&r.compact?we.xs:we.sm},children:[n.jsx("span",{style:{width:r!=null&&r.compact?8:9,height:r!=null&&r.compact?8:9,borderRadius:999,background:b,animation:"admeshPulse 1.4s ease-in-out infinite",boxShadow:`0 0 0 0 ${$e(Ve,.28)}`,flexShrink:0}}),n.jsx("span",{children:U})]})},rr=a.useCallback((r,b)=>{if(It[r.id])return;const y=b?"helpful":"not_helpful";Ht(v=>({...v,[r.id]:y})),Ie("answer_feedback",{message_id:r.id,query:r.userQuery,status:y,latency_ms:r.responseTimeMs,metadata:{helpful:b}})},[It,Ie]);function En(r,b){if(r.role!=="assistant"||!r.content.trim()||fe&&r.id===Je.current)return null;const y=(b==null?void 0:b.accentColor)||Ct,v=(b==null?void 0:b.metaColor)||ir,R=It[r.id],U=typeof r.responseTimeMs=="number";return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginTop:"10px",paddingTop:"10px",borderTop:`1px solid ${ct}`,flexWrap:"wrap"},children:[n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",minWidth:0,flex:"1 1 auto",flexWrap:"wrap"},children:[n.jsx("span",{style:{fontSize:we.xs,color:v,whiteSpace:"nowrap"},children:R?"Thanks for your feedback":"Is this helpful?"}),R?n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",background:$e(y,.12),color:y,flexShrink:0},children:R==="helpful"?n.jsx(br,{size:14}):n.jsx(xr,{size:14})}):n.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",flexShrink:0},children:[n.jsx("button",{type:"button","aria-label":"Mark answer as helpful",onClick:()=>rr(r,!0),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:v,cursor:"pointer"},children:n.jsx(br,{size:14})}),n.jsx("button",{type:"button","aria-label":"Mark answer as not helpful",onClick:()=>rr(r,!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:v,cursor:"pointer"},children:n.jsx(xr,{size:14})})]})]}),U?n.jsxs("span",{style:{fontSize:we.xs,color:v,whiteSpace:"nowrap",flex:"0 1 auto",marginLeft:"auto"},children:["Answer Completed in ",Ts(r.responseTimeMs)]}):null]})}const un=a.useCallback(()=>{const r=mt.current;if(!r)return;const b=Math.max(0,r.scrollWidth-r.clientWidth);kn(r.scrollLeft>4),Jr(r.scrollLeft<b-4)},[]);a.useEffect(()=>(un(),window.addEventListener("resize",un),()=>window.removeEventListener("resize",un)),[un,Be.length]);const or=a.useCallback(r=>{const b=mt.current;b&&b.scrollBy({left:r==="left"?-Math.max(160,Math.floor(b.clientWidth*.75)):Math.max(160,Math.floor(b.clientWidth*.75)),behavior:"smooth"})},[]),$e=(r,b)=>{if(!r||!r.startsWith("#"))return`rgba(15, 23, 42, ${b})`;const y=r.slice(1),v=y.length===3?y.split("").map(Te=>`${Te}${Te}`).join(""):y;if(v.length!==6)return r;const R=parseInt(v.slice(0,2),16),U=parseInt(v.slice(2,4),16),le=parseInt(v.slice(4,6),16);return`rgba(${R}, ${U}, ${le}, ${b})`},Ve=E.primaryColor||"#3F037F",dt=E.surfaceColor||"#ffffff",so=E.backgroundColor||"#eef2ff",ct=E.borderColor||"#e5e7eb",Ue=E.textColor||"#111827",Kt=E.textSecondaryColor||"#6b7280";$e(Ve,.12);const sr=$e(Ve,.24);$e(Ve,.38);const io=dt,Ct=Ve,yn=E.primaryTextColor||"#ffffff",ir=Kt,ar=de||"Publisher Assistant",tn=ee&&Be.length===0&&Pe.length===0,Rn=dt,Tn=dt,Gt=ct,lr=ct,dr="0 16px 64px rgba(15, 23, 42, 0.14)",In=Kt,ao=Kt,lo=Ct,cr=so,co="none",uo="rgba(15, 23, 42, 0.18)";function ur(r){return Ze?n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:r==="default"?"10px 12px":"8px 10px",borderRadius:r==="default"?"14px":"12px",border:`1px solid ${sr}`,background:$e("#ffffff",.9),marginBottom:"4px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{color:Ct,fontSize:we.xs,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Agent Connected"}),n.jsxs("div",{style:{color:Ue,fontSize:we.sm,fontWeight:600,lineHeight:1.3},children:[Ze.brand_name," agent is active"]})]}),n.jsx("button",{type:"button",onClick:()=>{D("user_stopped",{source:"publisher_assistant"})},style:{border:`1px solid ${sr}`,borderRadius:999,background:$e("#ffffff",.92),color:Ct,padding:"7px 12px",fontSize:we.xs,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Stop"})]}):null}function mr(r,b=ke){const y=fn&&!b,v=b||y?"9px":"11px";return n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",paddingTop:b||r==="default"?"2px":"8px",marginTop:b?"0":r==="default"?"4px":0,flexShrink:0,textAlign:"center",width:"100%"},children:n.jsx("div",{style:{color:ao,fontSize:v,lineHeight:y?1.3:1.45,maxWidth:"100%",textAlign:"center"},children:nr})})}function Dn(r){const b=r==="publisher"?[180,220,196]:["100%","82%","68%"];return r==="publisher"?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:$e(Ue,.06),flexShrink:0}}),n.jsx("div",{style:{display:"flex",gap:"10px",overflow:"hidden",flex:1},children:b.map((y,v)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:40,borderRadius:"6px",background:$e(Ue,.06),backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:"none",flexShrink:0}},`suggestion-skeleton-${v}`))}),n.jsx("div",{style:{width:28,height:28,borderRadius:"6px",background:$e(Ue,.06),flexShrink:0}})]}):n.jsx("div",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:r==="publisher"?"10px":"12px"},children:b.map((y,v)=>n.jsx("div",{style:{width:y,maxWidth:"100%",height:r==="publisher"?40:52,borderRadius:999,background:`linear-gradient(90deg, ${$e(Ve,.08)} 0%, ${$e(Ve,.18)} 50%, ${$e(Ve,.08)} 100%)`,backgroundSize:"200% 100%",animation:"admeshShimmer 1.4s ease-in-out infinite",boxShadow:r==="publisher"?`0 8px 22px ${$e(Ve,.08)}`:"none"}},`suggestion-skeleton-${v}`))})}function mo(r=ke){if(fe)return null;if(tn)return Dn("publisher");if(!Be.length)return null;const b=r&&Xn,y=Be.slice(0,Y);return B==="stacked"?n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:r?"6px":"8px",flexShrink:0,overflowY:"auto",maxHeight:r?"240px":void 0,paddingRight:r?"2px":0,scrollbarWidth:"none",msOverflowStyle:"none"},children:y.map(v=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":v.is_sponsored?"true":void 0,ref:sn(v.id),onClick:()=>{ne==="default"&&(at(!0),_==="floating"&&Ft(!0)),dn(v)},type:"button",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",width:"100%",minWidth:0,borderRadius:"8px",border:`1px solid ${v.is_sponsored?Ve:ct}`,background:v.is_sponsored?Ve:dt,color:v.is_sponsored?yn:Ue,padding:r?"8px 10px":"10px 14px",fontSize:r?"12px":"13px",fontWeight:500,lineHeight:1.25,textAlign:"left",boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{style:{minWidth:0},children:v.text}),W&&v.is_sponsored&&n.jsx("span",{style:{flexShrink:0,borderRadius:"6px",background:$e("#ffffff",.18),padding:"2px 6px",fontSize:"10px",fontWeight:700},children:"Ad"})]},v.id))}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:b?"4px":lt?"5px":r?"6px":"10px",flexShrink:0},children:[!b&&n.jsx("button",{type:"button",onClick:()=>or("left"),disabled:!Jt,"aria-label":"Scroll suggestions left",style:{width:lt?20:r?24:28,height:lt?20:r?24:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:"#6b7280",fontSize:lt?"13px":void 0,lineHeight:1,cursor:Jt?"pointer":"default",opacity:Jt?1:.55},children:"โน"}),n.jsx("div",{ref:mt,onScroll:un,style:{display:"flex",gap:b?"4px":lt?"5px":r?"6px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",flex:1},children:y.map(v=>n.jsxs("button",{className:"admesh-publisher-suggestion","data-admesh-sponsored":v.is_sponsored?"true":void 0,ref:sn(v.id),onClick:()=>{ne==="default"&&(at(!0),_==="floating"&&Ft(!0)),dn(v)},type:"button",style:{display:"inline-flex",alignItems:"center",gap:b?"4px":lt?"5px":"8px",whiteSpace:"nowrap",borderRadius:"6px",border:`1px solid ${v.is_sponsored?Ve:ct}`,background:v.is_sponsored?Ve:dt,color:v.is_sponsored?yn:Ue,padding:b?"4px 8px":lt?"5px 8px":r?"7px 10px":"8px 14px",fontSize:b?"10px":lt?"11px":r?"12px":"13px",fontWeight:500,lineHeight:b?1:lt?1.1:void 0,boxShadow:"none",cursor:"pointer"},children:[n.jsx("span",{children:v.text}),W&&v.is_sponsored&&n.jsx("sup",{style:{fontSize:"10px",opacity:.9},children:"Ad"})]},v.id))}),!b&&n.jsx("button",{type:"button",onClick:()=>or("right"),disabled:!Sn,"aria-label":"Scroll suggestions right",style:{width:lt?20:r?24:28,height:lt?20:r?24:28,borderRadius:"6px",border:`1px solid ${ct}`,background:dt,color:"#6b7280",fontSize:lt?"13px":void 0,lineHeight:1,cursor:Sn?"pointer":"default",opacity:Sn?1:.55},children:"โบ"})]})}function po(r=ke){if(r||!(Vt!=null&&Vt.recommendation))return null;const b=`publisher-sponsored-creative-${Vt.id}`;return n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"2px"},children:n.jsx(nn,{messageId:b,query:Vt.text,initialRecommendation:Vt.recommendation,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,Vt.text)},onError:y=>{console.error("[AdMeshIntentAssistant] Sponsored creative error:",y)}})})}function ho(r){var b,y;return(b=r.relatedItems)!=null&&b.length||!((y=r.sourceLinks)!=null&&y.length)?null:n.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"16px"},children:[n.jsx("div",{style:{width:"100%",fontSize:"11px",fontWeight:600,color:Kt},children:"Sources"}),r.sourceLinks.map(v=>n.jsxs("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Ie("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:v.title,source_url:v.url}})},style:{color:Ct,fontSize:we.xs,textDecoration:"none",borderBottom:`1px solid ${$e(Ve,.18)}`},children:[v.title||v.url," ",n.jsx(Co,{size:12,style:{display:"inline",verticalAlign:"middle"},"aria-hidden":"true"})]},`${r.id}-${v.url}`))]})}function fo(r,b=ke){var y;return(y=r.relatedItems)!=null&&y.length?n.jsxs("div",{style:{marginTop:"14px"},children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,color:Kt,marginBottom:"8px"},children:"Related reading"}),n.jsx("div",{style:{display:"flex",gap:b?"8px":"10px",overflowX:"auto",scrollbarWidth:"none",msOverflowStyle:"none",padding:"2px 2px 6px",maxWidth:"100%",scrollSnapType:"x proximity"},children:r.relatedItems.slice(0,4).map(v=>n.jsxs("a",{className:"admesh-publisher-source",href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>{Ie("source_link_clicked",{message_id:r.id,query:r.userQuery,metadata:{source_title:v.title,source_url:v.url,source_publisher:v.publisher,source_type:"related_item"}})},style:{display:"flex",flexDirection:"column",gap:b?"6px":"10px",padding:b?"10px":"14px",borderRadius:"8px",textDecoration:"none",color:Ue,border:`1px solid ${ct}`,background:dt,boxShadow:"none",flex:b?"0 0 min(220px, calc(100% - 8px))":"0 0 min(250px, calc(100% - 16px))",minWidth:0,maxWidth:b?"220px":"250px",flexShrink:0,scrollSnapAlign:"start",boxSizing:"border-box"},children:[n.jsx("div",{style:{fontSize:b?"12px":"14px",fontWeight:650,lineHeight:1.35,color:Ue,overflowWrap:"anywhere"},children:v.title||v.url}),v.publisher&&n.jsx("div",{style:{fontSize:b?"11px":"12px",color:Kt,lineHeight:1.4,overflowWrap:"anywhere"},children:v.publisher})]},`${r.id}-${v.url}`))})]}):null}function go(r=ke){const b=r?"13px":"15px";return n.jsxs("div",{ref:ae,style:{flex:r?"1 1 0":1,minHeight:0,maxHeight:"100%",overflowY:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"thin",padding:r?"0 2px 4px":H?"16px 16px 8px":0},children:[Pe.map(y=>{const v=y.role==="user"&&y.id===rt.current;return n.jsx("div",{ref:v?vt:void 0,style:{marginBottom:r?"16px":"28px",textAlign:y.role==="user"?"right":"left"},children:(()=>{const U=!!y.content.trim()||!fe;return n.jsx(n.Fragment,{children:n.jsxs("div",{style:{display:y.role==="assistant"?"block":"inline-block",width:y.role==="assistant"?"100%":void 0,maxWidth:y.role==="assistant"?"100%":"76%",padding:y.role==="assistant"?"4px 6px 4px 2px":"10px 14px",borderRadius:y.role==="assistant"?0:"8px",background:y.role==="user"?$e(Ue,.05):"transparent",color:Ue,boxShadow:"none",border:"none",fontSize:y.role==="assistant"?b:r?"12px":"13px",lineHeight:y.role==="assistant"?1.62:1.4,textAlign:"left",overflowWrap:"anywhere"},children:[y.role==="assistant"?y.content.trim()?n.jsx(Wn,{content:y.content,theme:{...E,textColor:Ue},fontSize:b}):fe&&y.id===Je.current?cn({includeSteps:!0}):null:n.jsx("p",{style:{margin:0,color:Ue},children:y.content}),y.role==="assistant"&&ho(y),y.role==="assistant"&&fo(y,r),y.role==="assistant"&&En(y),y.role==="assistant"&&U&&wt.has(y.id)&&y.initialRecommendation&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(nn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation,onFollowupDetected:ln,onRecommendationsShown:(le,Te)=>{an(le,Te,y.userQuery)},onError:le=>{console.error("[AdMeshIntentAssistant] Recommendation error:",le)}})}),y.role==="assistant"&&U&&!wt.has(y.id)&&(y.initialRecommendation||Zr)&&n.jsx("div",{"data-admesh-ad-content":!0,style:{marginTop:"14px"},children:n.jsx(nn,{messageId:y.id,query:y.userQuery,initialRecommendation:y.initialRecommendation||void 0,onFollowupDetected:ln,onRecommendationsShown:(le,Te)=>{an(le,Te,y.userQuery)},onError:le=>{console.error("[AdMeshIntentAssistant] Recommendation error:",le)}})})]})})})()},y.id)}),Et&&n.jsx("div",{role:"alert",style:{color:Ue,fontSize:we.sm,border:`1px solid ${ct}`,borderLeft:"3px solid #b45309",borderRadius:"6px",padding:"12px"},children:"Unable to complete the answer. Please try again."}),n.jsx("div",{ref:St})]})}if(ne==="default"){let r=function(v){const R=Rr(fn);return Hn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:y}),n.jsx("div",{style:R.shell,children:v})]}),document.body)},b=function(v=!1){const R=he(v),U=v||R&&H,le=!U&&G==="input",Te=R&&!U&&Xn,He=U&&!(ke&&m==="expand"&&!v&&Zt),ue=U?Rr(fn):null,Me=!!(ue&&fn&&!R),Le=R?zt:ue?ue.panelWidth:_==="inline"?"100%":"min(420px, calc(100vw - 32px))",Nt=R?en:ue?ue.panelHeight:"auto",Ke=R?zt:(ue==null?void 0:ue.panelMaxWidth)??"100%",et=R?en:ue==null?void 0:ue.panelMaxHeight,$t=u&&!Te&&U;return n.jsxs("div",{className:"admesh-publisher-panel","data-compact":R?"true":"false",style:{"--publisher-accent":Ct,color:Ue,width:Le,maxWidth:Ke,height:Nt,maxHeight:et,boxSizing:"border-box",display:"flex",flexDirection:"column",background:U?Rn:io,borderRadius:!R&&ue?ue.panelBorderRadius:"12px",padding:U?0:R?"6px":0,boxShadow:Me?"none":U?dr:"none",border:Me||le?"none":`1px solid ${lr}`,overflow:"hidden",minHeight:R?0:void 0},children:[n.jsx("style",{children:Gr}),$t&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:R?"8px 10px":"14px 20px",background:Tn,color:Ue,borderBottom:`1px solid ${Gt}`,flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px",minWidth:0},children:[n.jsx("div",{style:{width:R?26:32,height:R?26:32,flexShrink:0,borderRadius:"6px",background:$e(Ue,.04),display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,fontWeight:700,color:Ct,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:dt,padding:4}}):n.jsx(Un,{size:R?14:17,strokeWidth:1.5,"aria-hidden":"true"})}),(w||g)&&n.jsxs("div",{style:{minWidth:0,overflowWrap:"anywhere"},children:[w&&n.jsx("div",{style:{fontSize:R?"13px":"14px",fontWeight:600,lineHeight:1.1,letterSpacing:0},children:i}),g&&n.jsx("div",{style:{fontSize:R?"10px":"12px",color:In,marginTop:"2px"},children:ar})]})]}),U&&(!R||v)&&n.jsx("button",{type:"button",onClick:()=>at(!1),"aria-label":"Minimize assistant",style:{width:36,height:36,borderRadius:"8px",border:`1px solid ${Gt}`,background:dt,color:In,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(fr,{size:16,strokeWidth:1.5,"aria-hidden":"true"})})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Te?"2px":R?"6px":"16px",minHeight:0,flex:R||U?"1 1 0":void 0,overflow:R||U?"hidden":void 0,overscrollBehavior:"contain",padding:le?R?"4px":"8px":R?"8px":"20px",justifyContent:U?void 0:"center",background:Rn},children:[ur("default"),He&&go(R),!le&&n.jsxs(n.Fragment,{children:[R&&!U&&!Te&&n.jsx("div",{"aria-hidden":"true",style:{flex:"1 1 auto",minHeight:0}}),R&&!U&&P&&j&&Pe.length===0&&n.jsx("div",{style:{fontSize:15,fontWeight:600,textAlign:"center"},children:z}),mo(R)]}),(le||!R||U||p)&&n.jsx(Ss,{value:Ae,onChange:yt,open:le&&st&&!H,onOpenChange:le?jt:Es,suggestions:Be.slice(0,Y),registerSuggestion:sn,loading:fe,analyzing:tn,compact:R,expanded:U,showLogo:!U,suggestionPlacement:te,logoUrl:d,title:i,placeholder:M,colors:{accent:Ct,accentText:yn,surface:cr,text:Ue,muted:Kt,border:ct},onStop:jn,onSend:()=>{Xe.current=null,_t.current=!1,at(!0),_==="floating"&&Ft(!0),Ot(Ae)},onSuggestion:pt=>{at(!0),_==="floating"&&Ft(!0),dn(pt)}}),U&&mr("default",R),!U&&G==="always"&&po(R)]})]})};const y={position:"fixed",inset:0,background:uo,backdropFilter:"blur(2px)",zIndex:2147483e3};return _==="inline"?ke?n.jsxs("div",{ref:qt,className:"admesh-component","data-admesh-theme":ce,"data-admesh-surface":"ad-slot","data-admesh-ad-slot-behavior":m,"data-admesh-ad-slot-expanded":Cn?"true":"false",style:{width:zt,height:en,maxWidth:zt,maxHeight:en,position:"relative",overflow:"hidden"},children:[b(!1),Zt&&typeof document<"u"&&r(b(!0))]}):n.jsxs("div",{className:"admesh-component","data-admesh-theme":ce,style:{width:"100%",position:"relative"},children:[b(!1),H&&typeof document<"u"&&r(b(!0))]}):De?n.jsxs("div",{className:"admesh-component","data-admesh-theme":ce,children:[!H&&n.jsx("div",{style:{position:"fixed",...bn,zIndex:2147483001},children:b(!1)}),H&&typeof document<"u"&&r(b(!0))]}):n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsxs("button",{type:"button",onClick:Zn,style:{position:"fixed",...bn,zIndex:2147483e3,border:"none",borderRadius:"6px",background:E.primaryColor,color:yn,display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",fontWeight:600,padding:"12px 16px",boxShadow:"0 4px 16px rgba(15, 23, 42, 0.12)",cursor:"pointer"},children:[n.jsx(Un,{size:16,strokeWidth:1.5,"aria-hidden":"true"}),s]})})}return Be.length===0&&!tn?(console.log("[AdMeshIntentAssistant] No suggestions available - not rendering"),null):_==="inline"?n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsx("div",{className:`overflow-hidden rounded-[2rem] ${e||""}`,style:{width:mn(f)??"100%",backgroundColor:"#eef2ff",fontSize:we.base,...o},children:n.jsxs("div",{className:"space-y-4 rounded-[1.75rem] p-4",style:{backgroundColor:"rgba(255, 255, 255, 0.35)"},children:[tn?Dn("legacy"):Be.length>0&&n.jsx("div",{className:"flex flex-col gap-3",children:Be.slice(0,Y).map((r,b)=>n.jsxs("button",{ref:sn(r.id),onClick:()=>dn(r),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:b===0?"100%":b===1?"82%":"68%",backgroundColor:E.surfaceColor||"#ffffff",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:we.sm},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"ml-1 rounded-full px-1.5 py-0.5",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b",fontSize:"9px",lineHeight:1},children:"Ad"})]},r.id))}),Pe.length>0&&n.jsxs("div",{ref:ae,className:"max-h-[280px] space-y-3 overflow-y-auto rounded-[1.5rem] bg-white/80 p-4",style:{color:E.textColor,overscrollBehavior:"contain",WebkitOverflowScrolling:"touch"},children:[Pe.map(r=>{const b=r.role==="user"&&r.id===rt.current;return n.jsx("div",{ref:b?vt:void 0,className:r.role==="user"?"text-right":"text-left",children:n.jsx("div",{className:"inline-block max-w-[85%] rounded-2xl px-4 py-3",style:{backgroundColor:r.role==="user"?E.primaryColor:"#ffffff",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,fontSize:we.sm,textAlign:"left",overflowWrap:"anywhere"},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx(Wn,{content:r.content,theme:E,fontSize:we.sm}),En(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):fe&&r.id===Je.current?cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,lineHeight:"1.4"},children:r.content})})},r.id)}),fe&&!Pe.some(r=>r.role==="assistant"&&r.id===Je.current&&!r.content.trim())&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})}),Et&&n.jsx("div",{className:"text-sm",style:{color:E.textSecondaryColor},children:"Connection issue. Please try again."}),n.jsx("div",{ref:St})]}),n.jsx("div",{className:"rounded-[1.5rem] bg-white p-3 shadow-sm",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"text",value:Ae,onChange:r=>yt(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(fe){r.preventDefault();return}Ot(Ae)}},placeholder:M,className:"min-w-0 flex-1 rounded-full px-4 py-3 focus:outline-none",style:{backgroundColor:E.backgroundColor||"#ffffff",color:E.textColor,fontSize:we.sm}}),n.jsx("button",{onClick:()=>{if(fe){jn();return}Ot(Ae)},disabled:!fe&&!Ae.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:fe?"#dc2626":E.primaryColor,color:"#ffffff"},children:fe?n.jsx(zn,{size:18}):n.jsx(gr,{size:18})})]})}),n.jsxs("div",{className:"space-y-2 text-center",children:[n.jsxs("p",{style:{color:E.textSecondaryColor,fontSize:we.xs,fontWeight:600},children:["Powered by"," ",n.jsx("a",{href:"https://useadmesh.com",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"none",fontWeight:700},children:"AdMesh"})]}),n.jsx("p",{style:{color:E.textSecondaryColor,fontSize:we.xs,lineHeight:1.5},children:nr})]})]})})}):De?n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsxs("div",{className:`flex flex-col overflow-hidden ${e||""}`,style:{position:"fixed",display:"flex",flexDirection:"column",...H?{top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"min(1040px, calc(100vw - 40px))",height:"min(84vh, 820px)",maxWidth:"1040px",maxHeight:"820px"}:{...bn,width:mn(f)??tr.width,height:mn(h)??tr.height},backgroundColor:H?Rn:E.backgroundColor,zIndex:9999,fontSize:we.base,borderRadius:H?"20px":"16px",border:H?`1px solid ${lr}`:"1px solid transparent",boxShadow:H?dr:"0 20px 40px rgba(15, 23, 42, 0.12)",...o},children:[u&&n.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:H?Gt:"transparent",background:H?Tn:E.backgroundColor,padding:H?"18px 20px":"16px"},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{style:{width:H?40:32,height:H?40:32,borderRadius:H?"14px":"10px",background:$e(Ve,.08),color:Ct,display:"flex",alignItems:"center",justifyContent:"center",fontSize:H?"15px":"13px",fontWeight:700,flexShrink:0,overflow:"hidden"},children:d?n.jsx("img",{src:d,alt:`${i||"Assistant"} logo`,style:{width:"100%",height:"100%",objectFit:"contain",background:"#ffffff",padding:4}}):(i||"AA").slice(0,2).toUpperCase()}),(w||g&&H)&&n.jsxs("div",{children:[w&&n.jsx("div",{className:"font-medium",style:{color:E.textColor,fontSize:H?"20px":we.base,fontWeight:700,letterSpacing:H?"-0.02em":0},children:i}),g&&H&&n.jsx("div",{style:{color:In,fontSize:"12px",marginTop:"2px"},children:ar})]})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[!ke&&n.jsx("button",{onClick:ro,className:"transition-colors",title:H?"Minimize":"Expand",style:{width:H?36:28,height:H?36:28,borderRadius:H?"12px":"10px",border:`1px solid ${H?Gt:"transparent"}`,background:H?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:H?n.jsx(fr,{size:16,style:{color:E.textSecondaryColor}}):n.jsx(Io,{size:16,style:{color:E.textSecondaryColor}})}),n.jsx("button",{onClick:no,className:"transition-colors",style:{width:H?36:28,height:H?36:28,borderRadius:H?"12px":"10px",border:`1px solid ${H?Gt:"transparent"}`,background:H?"#ffffff":"transparent",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(zn,{size:16,style:{color:E.textSecondaryColor}})})]})]}),n.jsxs("div",{ref:ae,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:H?"20px":"16px"},children:[ur("legacy"),P&&Pe.length===0&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",children:n.jsx("p",{style:{color:E.textColor,margin:0,fontSize:we.sm},children:z})})}),Pe.map(r=>{const b=r.role==="user"&&r.id===rt.current;return n.jsxs("div",{ref:b?vt:void 0,className:"mb-3",style:{textAlign:r.role==="user"?"right":"left"},children:[n.jsx("div",{className:r.role==="user"?"inline-block max-w-[85%] ml-auto":"max-w-[92%]",style:{backgroundColor:r.role==="user"?lo:"transparent",color:r.role==="user"?E.primaryTextColor||"#ffffff":E.textColor,border:"none",borderRadius:r.role==="user"?H?"14px":"12px":0,padding:r.role==="user"?H?"12px 14px":void 0:"2px 6px 2px 2px",boxShadow:"none",textAlign:"left",overflowWrap:"anywhere"},children:r.role==="assistant"?r.content.trim()?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{fontSize:`calc(${we.sm} * 1.3)`,lineHeight:1.65},children:n.jsx(Wn,{content:r.content,theme:E,fontSize:`calc(${we.sm} * 1.3)`})}),En(r,{accentColor:E.primaryColor,metaColor:E.textSecondaryColor})]}):fe&&r.id===Je.current?cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1}):null:n.jsx("p",{style:{margin:0,fontSize:we.sm,lineHeight:"1.4"},children:r.content})}),r.role==="assistant"&&!wt.has(r.id)&&n.jsx(nn,{messageId:r.id,query:r.userQuery,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}}),r.role==="assistant"&&wt.has(r.id)&&r.initialRecommendation&&!fe&&n.jsxs("div",{className:"mb-4",children:[n.jsx("div",{className:"text-xs text-gray-500 mb-2 font-semibold",children:"Sponsored Recommendation"}),n.jsx(nn,{messageId:r.id,query:r.userQuery,initialRecommendation:r.initialRecommendation,onFollowupDetected:ln,onRecommendationsShown:(y,v)=>{an(y,v,r.userQuery)},onError:y=>{console.error("[AdMeshIntentAssistant] Recommendations error:",y)}})]})]},r.id)}),fe&&!Pe.some(r=>r.role==="assistant"&&r.id===Je.current&&!r.content.trim())&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg",style:{backgroundColor:"transparent"},children:cn({compact:!0,accentColor:E.primaryColor,metaColor:E.textSecondaryColor,includeSteps:!1})})}),Et&&n.jsx("div",{className:"mb-3",children:n.jsx("div",{className:"inline-block p-2 rounded-lg border",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textSecondaryColor},children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{style:{fontSize:we.xs},children:"โ ๏ธ"}),n.jsx("span",{style:{fontSize:we.sm},children:"Connection issue. Please try again."})]})})}),n.jsx("div",{ref:St})]}),Pe.length===0&&tn&&n.jsx("div",{className:"px-4 pb-2",children:Dn("legacy")}),Be.length>0&&Pe.length===0&&!tn&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:Be.slice(0,Y).map(r=>n.jsxs("button",{ref:sn(r.id),onClick:()=>dn(r),className:"relative flex w-full items-center text-left transition-all duration-200",style:{backgroundColor:E.surfaceColor||"#f8fafc",color:E.textColor||"#1e293b",border:`1px solid ${E.borderColor||"#e2e8f0"}`,fontSize:we.sm,padding:"10px 12px",borderRadius:"999px",fontWeight:500},children:[n.jsx("span",{className:"leading-tight",children:r.text}),W&&r.is_sponsored&&n.jsx("sup",{className:"absolute right-1 top-1 rounded-full px-1.5 py-0.5 tracking-wide",style:{fontSize:"9px",lineHeight:1,backgroundColor:E.backgroundColor||"#ffffff",color:E.textSecondaryColor||"#64748b"},children:"Ad"})]},r.id))})}),re&&!ee&&xn.length===0&&n.jsx("div",{className:"px-4 pb-2",children:n.jsx("div",{className:"flex flex-col gap-2",children:n.jsxs("div",{className:"p-3 rounded-lg border",style:{backgroundColor:E.surfaceColor,borderColor:E.borderColor,color:E.textSecondaryColor},children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("span",{style:{fontSize:we.sm},children:"Intent analysis failed"}),n.jsx("button",{onClick:Re,className:"text-xs px-2 py-1 rounded",style:{backgroundColor:E.primaryColor,color:"#ffffff"},children:"Retry"})]}),n.jsx("span",{style:{fontSize:we.xs},children:re})]})})}),n.jsxs("div",{className:"p-3 border-t",style:{borderColor:H?Gt:"transparent",padding:H?"18px 20px":void 0,background:H?Tn:void 0},children:[n.jsxs("div",{className:"flex gap-2",style:{alignItems:"center",border:`1px solid ${Gt}`,borderRadius:H?"16px":"12px",background:cr,boxShadow:H?co:"none",padding:H?"8px 8px 8px 14px":void 0},children:[n.jsx("input",{type:"text",value:Ae,onChange:r=>yt(r.target.value),onKeyPress:r=>{if(r.key==="Enter"){if(fe){r.preventDefault();return}Ot(Ae)}},placeholder:M,className:"flex-1 px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",style:{backgroundColor:"transparent",borderColor:"transparent",color:E.textColor,fontSize:H?"15px":we.sm,"--tw-ring-color":E.primaryColor}}),n.jsx("button",{onClick:()=>{if(fe){jn();return}Ot(Ae)},disabled:!fe&&!Ae.trim(),className:"transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:fe?"#dc2626":E.primaryColor,color:"#ffffff",borderRadius:H?"12px":"10px",width:H?"46px":void 0,height:H?"46px":void 0,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:H?`0 10px 20px ${$e(Ve,.18)}`:"none"},children:fe?n.jsx(zn,{size:14}):n.jsx(gr,{size:14})})]}),mr("legacy")]})]})}):n.jsx("div",{className:"admesh-component","data-admesh-theme":ce,children:n.jsx("button",{onClick:Zn,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",...bn,backgroundColor:E.primaryColor,color:"#ffffff",zIndex:9999,fontSize:we.base,...o},children:n.jsx("span",{className:"font-medium",children:s})})})},wn="admesh:streamingStart",_n="admesh:streamingComplete";function Ws(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},s=new CustomEvent(wn,{detail:o});window.dispatchEvent(s),l.log("[StreamingEvents] ๐ข Dispatched streamingStart event",{messageId:t,sessionId:e})}function Bs(t,e,o){const s={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},i=new CustomEvent(_n,{detail:s});window.dispatchEvent(i),l.log("[StreamingEvents] ๐ข Dispatched streamingComplete event",{messageId:t,sessionId:e,metadata:o})}function Us(t,e,o){const s=i=>{const d=i;d.detail.messageId===t&&d.detail.sessionId===e&&(l.log("[StreamingEvents] ๐จ Received streamingStart event"),o(d.detail))};return window.addEventListener(wn,s),()=>{window.removeEventListener(wn,s)}}function Xr(t,e,o){l.log("[StreamingEvents] ๐ Setting up streamingComplete listener",{expectedMessageId:t,expectedSessionId:e});const s=i=>{const d=i;l.log("[StreamingEvents] ๐จ Received streamingComplete event (checking match)",{receivedMessageId:d.detail.messageId,receivedSessionId:d.detail.sessionId,expectedMessageId:t,expectedSessionId:e,messageIdMatch:d.detail.messageId===t,sessionIdMatch:d.detail.sessionId===e}),d.detail.messageId===t&&d.detail.sessionId===e?(l.log("[StreamingEvents] โ
Event matched! Calling callback"),o(d.detail)):l.log("[StreamingEvents] โ ๏ธ Event did not match - ignoring")};return window.addEventListener(_n,s),()=>{l.log("[StreamingEvents] ๐งน Removing streamingComplete listener"),window.removeEventListener(_n,s)}}const vn=()=>{const t=new Set,e=new Map,o=d=>{const u=e.get(d);u&&(u.observer.disconnect(),u.timeoutId&&clearTimeout(u.timeoutId),e.delete(d))};return{startTracking:({exposureUrl:d,recommendationId:u,linkElement:w,sessionId:g,logPrefix:_="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!d||!w){_&&l.warn(`${_} โ ๏ธ Missing exposure tracking data`);return}const c=`${g||"anonymous"}::${u||d}`;if(t.has(c)||e.has(c))return;const m={observer:void 0,timeoutId:null,viewableStart:null},k=()=>{o(c),t.add(c),fetch(d,{method:"GET",keepalive:!0}).then(()=>{_&&l.log(`${_} โ
Exposure pixel fired`)}).catch(()=>{_&&l.warn(`${_} โ ๏ธ Failed to fire exposure pixel`),t.delete(c)})},j=new IntersectionObserver(p=>{p.forEach(x=>{x.intersectionRatio>=.5?m.viewableStart===null&&(m.viewableStart=performance.now(),m.timeoutId=setTimeout(k,1e3)):(m.viewableStart=null,m.timeoutId&&(clearTimeout(m.timeoutId),m.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});m.observer=j,j.observe(w),e.set(c,m)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},Hs=({containerId:t,messageId:e,sessionId:o,sdk:s,query:i,recommendations:d=[],onLinksFound:u,onNoLinksFound:w,children:g})=>{const[_,c]=a.useState(!1),[m,k]=a.useState(!0),[j,p]=a.useState(!1),x=a.useRef(vn()),f=a.useRef(u),h=a.useRef(w),S=a.useRef(t),T=a.useRef(s),K=a.useRef(o),A=a.useRef(i);a.useEffect(()=>{f.current=u,h.current=w,S.current=t,T.current=s,K.current=o,A.current=i},[u,w,t,s,o,i]),a.useEffect(()=>()=>{x.current.cleanup()},[]);const C=a.useCallback(({exposureUrl:$,recommendationId:F,linkElement:P})=>{x.current.startTracking({exposureUrl:$,recommendationId:F,linkElement:P,sessionId:K.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),L=a.useCallback(()=>{l.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const $=document.getElementById(S.current);if(!$){l.warn("[FinalLinkDetectionCheck] Container not found"),c(!0),w();return}const F=new Kn({autoAddLabels:!0,fireExposurePixels:!0}),P=d.length>0?d:[];l.log(`[FinalLinkDetectionCheck] ๐ Using ${P.length} recommendations for link detection`),P.length>0&&process.env.NODE_ENV==="development"&&P.forEach((M,W)=>{var O,Y,B,G,te,xe,Z,ne,_e;l.log(`[FinalLinkDetectionCheck] ๐ Recommendation ${W+1} (DEV):`,{recommendation_id:M==null?void 0:M.recommendation_id,click_url:((O=M==null?void 0:M.tracking)==null?void 0:O.click_url)||((B=(Y=M==null?void 0:M.recommendation)==null?void 0:Y.creative)==null?void 0:B.landing_page_url),format:(G=M==null?void 0:M.recommendation)==null?void 0:G.format,brand_name:(Z=(xe=(te=M.render)==null?void 0:te.creative)==null?void 0:xe.advertiser)==null?void 0:Z.brand_name,cta_url:(_e=(ne=M.render)==null?void 0:ne.creative)==null?void 0:_e.landing_page_url})});const z=F.scanAndProcessLinks($,P,({exposureUrl:M,recommendationId:W,linkElement:O})=>C({exposureUrl:M,recommendationId:W,linkElement:O}));l.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${z.length} links`),z.length>0?(l.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),p(!0),f.current(z.length)):(l.log(`[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will use ${P.length} previous recommendation(s) if available)`),p(!1),h.current()),c(!0)}catch{l.error("[FinalLinkDetectionCheck] Error during final check"),c(!0),h.current()}},[C,d]);return a.useEffect(()=>{l.log("[FinalLinkDetectionCheck] โณ Setting up listener",{messageId:e,sessionId:o,recommendationsCount:d.length});let $=null,F=!1;const P=Xr(e,o,z=>{l.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event",{messageId:z.messageId,sessionId:z.sessionId,timestamp:z.timestamp}),F=!0,$&&(clearTimeout($),$=null),k(!1),setTimeout(()=>{L()},100)});return $=setTimeout(()=>{F||(l.warn("[FinalLinkDetectionCheck] โฑ๏ธ Timeout: streamingComplete event not received, triggering fallback check anyway"),k(!1),setTimeout(()=>{L()},100))},5e3),()=>{l.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),$&&clearTimeout($),P()}},[e,o]),m?n.jsx(n.Fragment,{}):_?j?(l.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),n.jsx(n.Fragment,{})):(l.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),n.jsx(n.Fragment,{children:g})):n.jsx(n.Fragment,{})},qs=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:s,onNoLinksDetected:i,onError:d,className:u,query:w,onFallbackChange:g,onWeaveAttempt:_,onWeaveOutcome:c})=>{var M,W;const{sessionId:m,sdk:k,language:j,location:p,userId:x,model:f,messages:h}=on(),S=a.useRef(null),T=`weave-ad-container-${t}`,K=a.useRef(vn()),A=a.useRef(!1),C=a.useRef(null),[L,$]=a.useState([]),F=a.useRef([]);a.useEffect(()=>(C.current||(C.current=new Kn({autoAddLabels:!0,fireExposurePixels:!0})),()=>{C.current&&(C.current.stopWatching(),C.current.clearCache())}),[]),a.useEffect(()=>()=>{K.current.cleanup()},[]),a.useEffect(()=>{(async()=>{var Y;if(!k||!(w!=null&&w.trim())||!t){l.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{l.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const B=await k.fetchPlatformResponse({query:w.trim(),sessionId:m,messageId:t,language:j,location:p,userId:x,model:f,messages:h}),G=(B==null?void 0:B.status)==="generated"?[B]:[];if($(G),F.current=G,l.log("[WeaveAdFormatContainer] ๐ฅ Got platform response:",{status:B==null?void 0:B.status,recommendationId:B==null?void 0:B.recommendation_id,hasRecommendation:!!(B!=null&&B.recommendation),format:(Y=B==null?void 0:B.recommendation)==null?void 0:Y.format}),B!=null&&B.recommendation){const te=B.recommendation.creative,xe=te.landing_page_url;l.log("[WeaveAdFormatContainer] ๐ฏ Found creative in platform response:",{brandName:te.brand_name,headline:te.headline,description:te.description,brandUrl:xe})}else l.log("[WeaveAdFormatContainer] โ ๏ธ No recommendation found in platform response")}catch(B){l.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",B),$([])}})()},[k,m,t,w]),a.useEffect(()=>{const O=S.current;if(!O||!C.current)return;const Y=C.current,B=({exposureUrl:xe,recommendationId:Z,linkElement:ne})=>{K.current.startTracking({exposureUrl:xe,recommendationId:Z,linkElement:ne,sessionId:m,logPrefix:"[WeaveAdFormatContainer]"})},te=setTimeout(()=>{l.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),_==null||_(t);const xe=F.current.length>0?F.current:[];l.log(`[WeaveAdFormatContainer] ๐ Using ${xe.length} recommendations for link detection`);try{const Z=Y.scanAndProcessLinks(O,xe,B);Z.length>0&&!A.current?(A.current=!0,l.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${Z.length} links detected`),c==null||c(t,!0,`Found ${Z.length} links`),s==null||s(Z.length),g==null||g(!1)):A.current||l.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(Z){const ne=Z instanceof Error?Z.message:String(Z);l.error(`[WeaveAdFormatContainer] Weave injection failed: ${ne}`),c==null||c(t,!1,ne),i==null||i(),g==null||g(!0)}},100);return Y.watchForNewLinks(O,F.current,B),()=>{clearTimeout(te),Y.stopWatching()}},[e,m,t,s,g,_,c]);const P=(W=(M=L[0])==null?void 0:M.recommendation)==null?void 0:W.format,z=P==="weave";return a.useEffect(()=>{w&&z&&l.log(`[WeaveAdFormatContainer] ๐ฏ Format is "weave" (preferred: ${P}) - skipping fallback recommendations`)},[w,z,P]),n.jsxs(n.Fragment,{children:[n.jsx("div",{ref:S,id:T,className:u,"data-weave-ad-format":"true","data-message-id":t,children:e}),w&&!z&&n.jsx(Hs,{containerId:T,messageId:t,sessionId:m,sdk:k,query:w,recommendations:L,onLinksFound:O=>{l.log(`[WeaveAdFormatContainer] โ
Links found (${O}) - no fallback needed`),c==null||c(t,!0,`Found ${O} links in final check`),s==null||s(O),g==null||g(!1)},onNoLinksFound:()=>{l.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),l.log(`[WeaveAdFormatContainer] ๐ Passing ${L.length} recommendation(s) to fallback component`),c==null||c(t,!1,"No links detected in final check"),i==null||i(),g==null||g(!0)},children:n.jsx(qr,{format:o,messageId:t,query:w,fallback:!0,onError:d,previousRecommendations:L.length>0?L:void 0})})]})},Os=t=>{const{sdk:e,sessionId:o}=on(),s=a.useRef(!1),i=a.useRef(0),d=a.useRef(!1),u=a.useRef(!1),w=a.useRef(null),g=a.useRef(vn());a.useEffect(()=>()=>{g.current.cleanup()},[]);const _=a.useCallback(({exposureUrl:h,recommendationId:S,linkElement:T})=>{g.current.startTracking({exposureUrl:h,recommendationId:S,linkElement:T,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),c=a.useRef(Date.now()),m=a.useRef(0),k=a.useRef(null),j=a.useRef([]),p=a.useRef(300),x=a.useCallback(async()=>{var h,S,T,K;if(!(!e||!o||s.current)){s.current=!0,i.current=0;try{const A=document.getElementById(t.llmOutputContainerId);if(!A)return;const C=(h=e.getWeaveProcessor)==null?void 0:h.call(e);if(!C)return;const L=C.scanAndProcessLinks(A,[],({exposureUrl:F,recommendationId:P,linkElement:z})=>_({exposureUrl:F,recommendationId:P,linkElement:z}));i.current=L.length;const $=L.length>0;if($&&!d.current)d.current=!0,(S=t.onLinksDetected)==null||S.call(t,L.length),u.current=!0;else if(!$&&d.current)d.current=!1,u.current=!1;else if(!$&&!u.current){w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current),m.current=0,c.current=Date.now();const F=Math.max(100,p.current/3);k.current=setInterval(()=>{var W;const z=Date.now()-c.current,M=p.current;z>=M?(m.current++,m.current>=2&&(k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((W=t.onNoLinksDetected)==null||W.call(t),u.current=!0))):m.current=0},F);const P=Math.max(1500,p.current*5);w.current=setTimeout(()=>{var z;k.current&&(clearInterval(k.current),k.current=null),!d.current&&!u.current&&((z=t.onNoLinksDetected)==null||z.call(t),u.current=!0)},P)}else $&&u.current&&!d.current&&(w.current&&(clearTimeout(w.current),w.current=null),d.current=!0,(T=t.onLinksDetected)==null||T.call(t,L.length),u.current=!0)}catch(A){const C=A instanceof Error?A:new Error(String(A));(K=t.onError)==null||K.call(t,C)}finally{s.current=!1}}},[e,o,t,_]),f=a.useCallback(()=>{const h=j.current;if(h.length<2){p.current=300;return}const S=[];for(let A=1;A<h.length;A++)S.push(h[A]-h[A-1]);const T=S.reduce((A,C)=>A+C,0)/S.length,K=Math.max(100,Math.min(T*3,1e3));p.current=K},[]);return a.useEffect(()=>{const h=document.getElementById(t.llmOutputContainerId);if(!h)return;x();const S=new MutationObserver(()=>{const T=Date.now();c.current=T,m.current=0,j.current.push(T),j.current.length>10&&j.current.shift(),f(),x()});return S.observe(h,{childList:!0,subtree:!0,characterData:!1}),()=>{S.disconnect(),w.current&&clearTimeout(w.current),k.current&&clearInterval(k.current)}},[t.llmOutputContainerId,x,f]),{isProcessing:s.current,detectedLinksCount:i.current,linksFound:d.current,shouldRenderFallback:!d.current&&u.current,processWeaveFormat:x}},Vs="1.0.31";exports.AdMeshBadge=Kr;exports.AdMeshCompactCard=qn;exports.AdMeshContext=On;exports.AdMeshFollowup=Hr;exports.AdMeshIntentAssistant=Fs;exports.AdMeshLayout=Nr;exports.AdMeshLinkTracker=Vr;exports.AdMeshProvider=Br;exports.AdMeshRecommendations=nn;exports.AdMeshRenderer=Ur;exports.AdMeshSDK=pn;exports.AdMeshTailAd=xs;exports.AdMeshTracker=$r;exports.AdMeshViewabilityTracker=hn;exports.STREAMING_COMPLETE_EVENT=_n;exports.STREAMING_START_EVENT=wn;exports.VERSION=Vs;exports.WeaveAdFormatContainer=qs;exports.WeaveAdFormatProvider=ms;exports.WeaveFallbackRecommendations=qr;exports.WeaveResponseProcessor=Kn;exports.callAnalyzeIntentEndpoint=Fr;exports.createInlineExposureTracker=vn;exports.dispatchStreamingCompleteEvent=Bs;exports.dispatchStreamingStartEvent=Ws;exports.extractHeadingsDirectly=Lr;exports.onStreamingComplete=Xr;exports.onStreamingStart=Us;exports.useAdMesh=on;exports.useAdMeshContext=Vn;exports.useAdMeshStyles=Yr;exports.useViewabilityTracker=zr;exports.useWeaveAdFormat=Os;exports.useWeaveAdFormatContext=ps;
|
|
1183
1183
|
//# sourceMappingURL=index.js.map
|