admesh-ui-sdk 1.0.0 → 1.0.1
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/AdMeshRecommendations.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +395 -398
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdMeshRecommendations.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshRecommendations.tsx"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"AdMeshRecommendations.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshRecommendations.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAsC,MAAM,OAAO,CAAC;AAI3D,MAAM,WAAW,OAAO;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,MAAM,WAAW,0BAA0B;IACzC,4CAA4C;IAC5C,QAAQ,EAAE,OAAO,EAAE,CAAC;IAEpB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,UAAU,GAAG,YAAY,GAAG,cAAc,GAAG,UAAU,GAAG,WAAW,CAAC;IAEhH,uDAAuD;IACvD,sBAAsB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IAErD,iCAAiC;IACjC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,eAAO,MAAM,qBAAqB,EAAE,KAAK,CAAC,EAAE,CAAC,0BAA0B,CA8FtE,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var ge=Object.defineProperty;var fe=(t,e,r)=>e in t?ge(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var S=(t,e,r)=>fe(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),be=require("react-dom/client"),f=require("react");function xe(t,e,r){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...r}}function ye(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function we(t){const e=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,n=window.innerWidth||document.documentElement.clientWidth,i=e.height,o=e.width;if(i===0||o===0)return 0;const d=Math.max(0,e.top),a=Math.min(r,e.bottom),c=Math.max(0,e.left),m=Math.min(n,e.right),u=Math.max(0,a-d),h=Math.max(0,m-c),l=u*h,g=i*o;return g>0?l/g:0}function G(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,n=e-t;return n<=0?100:Math.min(100,r/n*100)}function ke(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,n=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+n}}function ve(t){const e=t.getBoundingClientRect(),r=ke(t),n=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,o=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ye(n),viewportWidth:n,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:r.top,adPositionLeft:r.left,isDarkMode:o,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function _e(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Me(){return`batch_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Se(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function B(t=new Date){return t.toISOString()}function Ae(t){return t.length===0?0:t.reduce((r,n)=>r+n,0)/t.length}function J(t,e){let r;return function(...i){r||(t(...i),r=!0,setTimeout(()=>r=!1,e))}}async function je(t,e,r=3,n=1e3){if(!e||e.trim()==="")return!0;let i=null;for(let o=0;o<r;o++){try{const d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0});if(d.ok)return!0;const a=await d.text().catch(()=>"");i=new Error(`HTTP ${d.status}: ${d.statusText} - ${a}`)}catch(d){i=d}o<r-1&&await new Promise(d=>setTimeout(d,n*Math.pow(2,o)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",i),!1}async function Ce(t,e,r,n=3,i=1e3){if(t.length===0||!r||r.trim()==="")return!0;const o={batchId:Me(),sessionId:e,createdAt:B(),events:t,eventCount:t.length};let d=null;for(let a=0;a<n;a++){try{const c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});if(c.ok)return!0;const m=await c.text().catch(()=>"");d=new Error(`HTTP ${c.status}: ${c.statusText} - ${m}`)}catch(c){d=c}a<n-1&&await new Promise(c=>setTimeout(c,i*Math.pow(2,a)))}return console.error("[AdMesh Viewability] Failed to send analytics batch:",d),!1}const Te={enabled:!0,apiEndpoint:"https://api.useadmesh.com/api/recommendations/viewability/batch",enableBatching:!0,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let Ee=Te;function te({adId:t,productId:e,offerId:r,agentId:n,recommendationId:i,elementRef:o,config:d}){const a={...Ee,...d},c=f.useRef(_e()),[m,u]=f.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:B(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:a.enabled}),h=f.useRef(null),l=f.useRef(null),g=f.useRef(null),b=f.useRef(null),w=f.useRef(null),_=f.useRef([]),j=f.useRef([]),C=f.useRef(null),T=f.useCallback((x,p)=>{a.debug&&console.log(`[AdMesh Viewability] ${x}`,p)},[a.debug]),M=f.useCallback(async(x,p)=>{if(!a.enabled||!o.current||!h.current)return;if(!["ad_viewable","ad_click"].includes(x)){T(`Skipping non-critical event: ${x} (only ad_viewable and ad_click are sent)`);return}const v=ve(o.current),y={eventType:x,timestamp:B(),sessionId:c.current,adId:t,productId:e,offerId:r,agentId:n,recommendationId:i,timeMetrics:m.timeMetrics,engagementMetrics:m.engagementMetrics,contextMetrics:v,mrcStandards:h.current,isViewable:m.isViewable,metadata:p};T(`Sending critical event: ${x}`,y),a.onEvent&&a.onEvent(y),a.enableBatching?(j.current.push(y),j.current.length>=a.batchSize?await L():(C.current&&clearTimeout(C.current),C.current=setTimeout(L,a.batchTimeout))):await je(y,a.apiEndpoint,a.maxRetries,a.retryDelay)},[a,t,e,r,n,o,m,T]),L=f.useCallback(async()=>{if(j.current.length===0)return;const x=[...j.current];j.current=[],C.current&&(clearTimeout(C.current),C.current=null),await Ce(x,c.current,a.apiEndpoint,a.maxRetries,a.retryDelay)&&a.onBatchSent&&a.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:c.current,createdAt:B(),events:x,eventCount:x.length})},[a,T]),N=f.useCallback(J(()=>{if(!o.current)return;const x=we(o.current),p=Date.now(),k=new Date(m.timeMetrics.loadedAt).getTime();u(v=>{const y={...v};x>0&&_.current.push(x);const E=v.isVisible,A=x>0;if(A&&!E)l.current=p,y.engagementMetrics.viewportEnterCount++,y.timeMetrics.timeToFirstVisible||(y.timeMetrics.timeToFirstVisible=p-k,y.engagementMetrics.scrollDepthAtFirstVisible=G(),M("ad_visible"));else if(!A&&E){if(l.current){const I=p-l.current;y.timeMetrics.totalVisibleDuration+=I,l.current=null}y.engagementMetrics.viewportExitCount++,M("ad_hidden")}else if(A&&E&&l.current){const I=p-l.current;y.timeMetrics.totalVisibleDuration+=I,l.current=p}if(y.isVisible=A,y.visibilityPercentage=x,x>y.engagementMetrics.maxVisibilityPercentage&&(y.engagementMetrics.maxVisibilityPercentage=x),_.current.length>0&&(y.engagementMetrics.averageVisibilityPercentage=Ae(_.current)),h.current){const I=v.isViewable,R=Se(x,y.timeMetrics.totalVisibleDuration,h.current);if(R&&!I)y.isViewable=!0,y.timeMetrics.timeToViewable=p-k,g.current=p,M("ad_viewable");else if(R&&I&&g.current){const P=p-g.current;y.timeMetrics.totalViewableDuration+=P,g.current=p}}return y.engagementMetrics.currentScrollDepth=G(),y})},100),[o,m.timeMetrics.loadedAt,M]);return f.useEffect(()=>{if(!o.current)return;const x=o.current.getBoundingClientRect();h.current=xe(x.width,x.height,a.mrcStandards),T("Initialized MRC standards",h.current),M("ad_loaded")},[o,a.mrcStandards,T,M]),f.useEffect(()=>{if(!a.enabled||!o.current)return;const x=new IntersectionObserver(p=>{p.forEach(()=>{N()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return x.observe(o.current),()=>{x.disconnect()}},[a.enabled,o,N]),f.useEffect(()=>{if(!a.enabled)return;const x=J(()=>{N()},100);return window.addEventListener("scroll",x,{passive:!0}),()=>window.removeEventListener("scroll",x)},[a.enabled,N]),f.useEffect(()=>{if(!a.enabled||!o.current)return;const x=o.current,p=()=>{b.current=Date.now(),u(v=>({...v,engagementMetrics:{...v.engagementMetrics,hoverCount:v.engagementMetrics.hoverCount+1}})),M("ad_hover_start")},k=()=>{if(b.current){const v=Date.now()-b.current;u(y=>({...y,timeMetrics:{...y.timeMetrics,totalHoverDuration:y.timeMetrics.totalHoverDuration+v}})),b.current=null,M("ad_hover_end",{hoverDuration:v})}};return x.addEventListener("mouseenter",p),x.addEventListener("mouseleave",k),()=>{x.removeEventListener("mouseenter",p),x.removeEventListener("mouseleave",k)}},[a.enabled,o,M]),f.useEffect(()=>{if(!a.enabled||!o.current)return;const x=o.current,p=()=>{w.current=Date.now(),M("ad_focus")},k=()=>{if(w.current){const v=Date.now()-w.current;u(y=>({...y,timeMetrics:{...y.timeMetrics,totalFocusDuration:y.timeMetrics.totalFocusDuration+v}})),w.current=null,M("ad_blur",{focusDuration:v})}};return x.addEventListener("focus",p),x.addEventListener("blur",k),()=>{x.removeEventListener("focus",p),x.removeEventListener("blur",k)}},[a.enabled,o,M]),f.useEffect(()=>{if(!a.enabled||!o.current)return;const x=o.current,p=()=>{u(k=>({...k,engagementMetrics:{...k.engagementMetrics,wasClicked:!0}})),M("ad_click")};return x.addEventListener("click",p),()=>{x.removeEventListener("click",p)}},[a.enabled,o,M]),f.useEffect(()=>()=>{const x=Date.now(),p=new Date(m.timeMetrics.loadedAt).getTime(),k=x-p;u(v=>({...v,timeMetrics:{...v.timeMetrics,sessionDuration:k}})),M("ad_unloaded",{sessionDuration:k}),L()},[]),m}const D=({adId:t,productId:e,offerId:r,agentId:n,children:i,config:o,className:d,style:a,onViewabilityChange:c,onVisible:m,onViewable:u,onClick:h})=>{const l=f.useRef(null),g=te({adId:t,productId:e,offerId:r,agentId:n,elementRef:l,config:o}),b=f.useRef(g.isViewable);f.useEffect(()=>{g.isViewable!==b.current&&(b.current=g.isViewable,c&&c(g.isViewable),g.isViewable&&u&&u())},[g.isViewable,c,u]);const w=f.useRef(g.isVisible);f.useEffect(()=>{g.isVisible!==w.current&&(w.current=g.isVisible,g.isVisible&&m&&m())},[g.isVisible,m]);const _=()=>{h&&h()};return s.jsx("div",{ref:l,className:d,style:a,onClick:_,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":g.isViewable,"data-is-visible":g.isVisible,"data-visibility-percentage":g.visibilityPercentage.toFixed(2),children:i})};D.displayName="AdMeshViewabilityTracker";const Le=t=>{try{return new URL(t),!0}catch{return!1}},Q=(t,e)=>{const r=new Map,n=new Map;e.forEach(m=>{m.admesh_link&&r.set(m.admesh_link,m),m.click_url&&n.set(m.click_url,m)}),console.log("[AdMesh Summary] Processing recommendations:",{totalRecommendations:e.length,recommendationFields:e.map(m=>({ad_id:m.ad_id,click_url:m.click_url,admesh_link:m.admesh_link,title:m.title||m.recommendation_title}))}),r.size>0||n.size>0?console.log("[AdMesh Summary] Available recommendation links:",{admesh_links:Array.from(r.keys()),click_urls:Array.from(n.keys())}):console.warn("[AdMesh Summary] No click_url or admesh_link found in recommendations!");const i=/\[([^\]]+)\]\(([^)]+)\)/g,o=[];let d=0,a,c=0;for(;(a=i.exec(t))!==null;){const[m,u,h]=a;console.log("[AdMesh Summary] Processing markdown link:",{linkText:u,url:h,urlLength:h.length});let l=r.get(h)||n.get(h);if(console.log("[AdMesh Summary] URL match result:",{found:!!l,matchedBy:l?"exact_match":"none"}),l||(l=e.find(g=>g.ad_id&&h.includes(g.ad_id)),l&&console.log("[AdMesh Summary] Found by ad_id match")),a.index>d&&o.push(t.slice(d,a.index)),l){c++;const g=h||l.click_url||l.admesh_link;o.push(s.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary link clicked:",{adId:l.ad_id,productId:l.product_id,title:l.title||l.recommendation_title,brand:l.brand,pricing:l.pricing,clickUrl:l.click_url,admeshLink:l.admesh_link,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:l.ad_id,productId:l.product_id,clickUrl:l.click_url,admeshLink:l.admesh_link,source:"summary"}).catch(b=>{console.error("[AdMesh] Failed to track summary link click:",b)})},children:u},`summary-link-${c}`))}else console.warn(`[AdMesh Summary] No recommendation found for link: [${u}](${h}), creating regular link`,{availableLinks:Array.from(r.keys()),totalRecommendations:e.length,urlToMatch:h}),Le(h)?(c++,o.push(s.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary unmatched link clicked:",{linkText:u,url:h,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({url:h,linkText:u,source:"summary_unmatched"}).catch(g=>{console.error("[AdMesh] Failed to track unmatched link click:",g)})},children:u},`summary-link-${c}`))):(console.warn(`[AdMesh Summary] Invalid URL in markdown link: [${u}](${h})`),o.push(u));d=a.index+m.length}return d<t.length&&o.push(t.slice(d)),o},q=({summaryText:t,recommendations:e,theme:r,className:n="",style:i={}})=>{var a,c,m;if(!t||!t.trim())return console.warn("[AdMesh Summary] No summary text provided"),null;if(!e||e.length===0){console.warn("[AdMesh Summary] No recommendations provided");const u=Q(t,[]);return s.jsx("div",{className:`admesh-summary-unit ${n}`,style:i,children:s.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed",children:u.map((h,l)=>s.jsx(f.Fragment,{children:h},l))})})}const o=Q(t,e),d=((c=(a=e[0])==null?void 0:a.meta)==null?void 0:c.ad_id)||((m=e[0])==null?void 0:m.ad_id)||"";return s.jsx(D,{adId:d,className:`admesh-summary-unit ${n}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...i},children:s.jsxs("div",{children:[s.jsx("div",{className:"summary-content",children:s.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed text-base",children:o.map((u,h)=>s.jsx(f.Fragment,{children:u},h))})}),s.jsx("div",{className:"mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:s.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})})]})})};function Ne(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var W={exports:{}};/*!
|
|
1
|
+
"use strict";var fe=Object.defineProperty;var ge=(t,e,r)=>e in t?fe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var S=(t,e,r)=>ge(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),be=require("react-dom/client"),g=require("react");function xe(t,e,r){const i=t*e>242500;return{...{visibilityThreshold:i?.3:.5,minimumDuration:1e3,isLargeAd:i},...r}}function ye(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function we(t){const e=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,n=window.innerWidth||document.documentElement.clientWidth,i=e.height,o=e.width;if(i===0||o===0)return 0;const d=Math.max(0,e.top),a=Math.min(r,e.bottom),c=Math.max(0,e.left),l=Math.min(n,e.right),h=Math.max(0,a-d),p=Math.max(0,l-c),m=h*p,f=i*o;return f>0?m/f:0}function G(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,n=e-t;return n<=0?100:Math.min(100,r/n*100)}function ke(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,n=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+n}}function ve(t){const e=t.getBoundingClientRect(),r=ke(t),n=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,o=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ye(n),viewportWidth:n,viewportHeight:i,adWidth:e.width,adHeight:e.height,adPositionTop:r.top,adPositionLeft:r.left,isDarkMode:o,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function _e(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Me(){return`batch_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Se(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function B(t=new Date){return t.toISOString()}function Ae(t){return t.length===0?0:t.reduce((r,n)=>r+n,0)/t.length}function J(t,e){let r;return function(...i){r||(t(...i),r=!0,setTimeout(()=>r=!1,e))}}async function je(t,e,r=3,n=1e3){if(!e||e.trim()==="")return!0;let i=null;for(let o=0;o<r;o++){try{const d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0});if(d.ok)return!0;const a=await d.text().catch(()=>"");i=new Error(`HTTP ${d.status}: ${d.statusText} - ${a}`)}catch(d){i=d}o<r-1&&await new Promise(d=>setTimeout(d,n*Math.pow(2,o)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",i),!1}async function Ce(t,e,r,n=3,i=1e3){if(t.length===0||!r||r.trim()==="")return!0;const o={batchId:Me(),sessionId:e,createdAt:B(),events:t,eventCount:t.length};let d=null;for(let a=0;a<n;a++){try{const c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});if(c.ok)return!0;const l=await c.text().catch(()=>"");d=new Error(`HTTP ${c.status}: ${c.statusText} - ${l}`)}catch(c){d=c}a<n-1&&await new Promise(c=>setTimeout(c,i*Math.pow(2,a)))}return console.error("[AdMesh Viewability] Failed to send analytics batch:",d),!1}const Te={enabled:!0,apiEndpoint:"https://api.useadmesh.com/api/recommendations/viewability/batch",enableBatching:!0,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let Ee=Te;function te({adId:t,productId:e,offerId:r,agentId:n,recommendationId:i,elementRef:o,config:d}){const a={...Ee,...d},c=g.useRef(_e()),[l,h]=g.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:B(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:a.enabled}),p=g.useRef(null),m=g.useRef(null),f=g.useRef(null),b=g.useRef(null),y=g.useRef(null),v=g.useRef([]),j=g.useRef([]),C=g.useRef(null),T=g.useCallback((x,u)=>{a.debug&&console.log(`[AdMesh Viewability] ${x}`,u)},[a.debug]),M=g.useCallback(async(x,u)=>{if(!a.enabled||!o.current||!p.current)return;if(!["ad_viewable","ad_click"].includes(x)){T(`Skipping non-critical event: ${x} (only ad_viewable and ad_click are sent)`);return}const _=ve(o.current),w={eventType:x,timestamp:B(),sessionId:c.current,adId:t,productId:e,offerId:r,agentId:n,recommendationId:i,timeMetrics:l.timeMetrics,engagementMetrics:l.engagementMetrics,contextMetrics:_,mrcStandards:p.current,isViewable:l.isViewable,metadata:u};T(`Sending critical event: ${x}`,w),a.onEvent&&a.onEvent(w),a.enableBatching?(j.current.push(w),j.current.length>=a.batchSize?await L():(C.current&&clearTimeout(C.current),C.current=setTimeout(L,a.batchTimeout))):await je(w,a.apiEndpoint,a.maxRetries,a.retryDelay)},[a,t,e,r,n,o,l,T]),L=g.useCallback(async()=>{if(j.current.length===0)return;const x=[...j.current];j.current=[],C.current&&(clearTimeout(C.current),C.current=null),await Ce(x,c.current,a.apiEndpoint,a.maxRetries,a.retryDelay)&&a.onBatchSent&&a.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:c.current,createdAt:B(),events:x,eventCount:x.length})},[a,T]),N=g.useCallback(J(()=>{if(!o.current)return;const x=we(o.current),u=Date.now(),k=new Date(l.timeMetrics.loadedAt).getTime();h(_=>{const w={..._};x>0&&v.current.push(x);const E=_.isVisible,A=x>0;if(A&&!E)m.current=u,w.engagementMetrics.viewportEnterCount++,w.timeMetrics.timeToFirstVisible||(w.timeMetrics.timeToFirstVisible=u-k,w.engagementMetrics.scrollDepthAtFirstVisible=G(),M("ad_visible"));else if(!A&&E){if(m.current){const I=u-m.current;w.timeMetrics.totalVisibleDuration+=I,m.current=null}w.engagementMetrics.viewportExitCount++,M("ad_hidden")}else if(A&&E&&m.current){const I=u-m.current;w.timeMetrics.totalVisibleDuration+=I,m.current=u}if(w.isVisible=A,w.visibilityPercentage=x,x>w.engagementMetrics.maxVisibilityPercentage&&(w.engagementMetrics.maxVisibilityPercentage=x),v.current.length>0&&(w.engagementMetrics.averageVisibilityPercentage=Ae(v.current)),p.current){const I=_.isViewable,R=Se(x,w.timeMetrics.totalVisibleDuration,p.current);if(R&&!I)w.isViewable=!0,w.timeMetrics.timeToViewable=u-k,f.current=u,M("ad_viewable");else if(R&&I&&f.current){const P=u-f.current;w.timeMetrics.totalViewableDuration+=P,f.current=u}}return w.engagementMetrics.currentScrollDepth=G(),w})},100),[o,l.timeMetrics.loadedAt,M]);return g.useEffect(()=>{if(!o.current)return;const x=o.current.getBoundingClientRect();p.current=xe(x.width,x.height,a.mrcStandards),T("Initialized MRC standards",p.current),M("ad_loaded")},[o,a.mrcStandards,T,M]),g.useEffect(()=>{if(!a.enabled||!o.current)return;const x=new IntersectionObserver(u=>{u.forEach(()=>{N()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return x.observe(o.current),()=>{x.disconnect()}},[a.enabled,o,N]),g.useEffect(()=>{if(!a.enabled)return;const x=J(()=>{N()},100);return window.addEventListener("scroll",x,{passive:!0}),()=>window.removeEventListener("scroll",x)},[a.enabled,N]),g.useEffect(()=>{if(!a.enabled||!o.current)return;const x=o.current,u=()=>{b.current=Date.now(),h(_=>({..._,engagementMetrics:{..._.engagementMetrics,hoverCount:_.engagementMetrics.hoverCount+1}})),M("ad_hover_start")},k=()=>{if(b.current){const _=Date.now()-b.current;h(w=>({...w,timeMetrics:{...w.timeMetrics,totalHoverDuration:w.timeMetrics.totalHoverDuration+_}})),b.current=null,M("ad_hover_end",{hoverDuration:_})}};return x.addEventListener("mouseenter",u),x.addEventListener("mouseleave",k),()=>{x.removeEventListener("mouseenter",u),x.removeEventListener("mouseleave",k)}},[a.enabled,o,M]),g.useEffect(()=>{if(!a.enabled||!o.current)return;const x=o.current,u=()=>{y.current=Date.now(),M("ad_focus")},k=()=>{if(y.current){const _=Date.now()-y.current;h(w=>({...w,timeMetrics:{...w.timeMetrics,totalFocusDuration:w.timeMetrics.totalFocusDuration+_}})),y.current=null,M("ad_blur",{focusDuration:_})}};return x.addEventListener("focus",u),x.addEventListener("blur",k),()=>{x.removeEventListener("focus",u),x.removeEventListener("blur",k)}},[a.enabled,o,M]),g.useEffect(()=>{if(!a.enabled||!o.current)return;const x=o.current,u=()=>{h(k=>({...k,engagementMetrics:{...k.engagementMetrics,wasClicked:!0}})),M("ad_click")};return x.addEventListener("click",u),()=>{x.removeEventListener("click",u)}},[a.enabled,o,M]),g.useEffect(()=>()=>{const x=Date.now(),u=new Date(l.timeMetrics.loadedAt).getTime(),k=x-u;h(_=>({..._,timeMetrics:{..._.timeMetrics,sessionDuration:k}})),M("ad_unloaded",{sessionDuration:k}),L()},[]),l}const D=({adId:t,productId:e,offerId:r,agentId:n,children:i,config:o,className:d,style:a,onViewabilityChange:c,onVisible:l,onViewable:h,onClick:p})=>{const m=g.useRef(null),f=te({adId:t,productId:e,offerId:r,agentId:n,elementRef:m,config:o}),b=g.useRef(f.isViewable);g.useEffect(()=>{f.isViewable!==b.current&&(b.current=f.isViewable,c&&c(f.isViewable),f.isViewable&&h&&h())},[f.isViewable,c,h]);const y=g.useRef(f.isVisible);g.useEffect(()=>{f.isVisible!==y.current&&(y.current=f.isVisible,f.isVisible&&l&&l())},[f.isVisible,l]);const v=()=>{p&&p()};return s.jsx("div",{ref:m,className:d,style:a,onClick:v,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":f.isViewable,"data-is-visible":f.isVisible,"data-visibility-percentage":f.visibilityPercentage.toFixed(2),children:i})};D.displayName="AdMeshViewabilityTracker";const Le=t=>{try{return new URL(t),!0}catch{return!1}},Q=(t,e)=>{const r=new Map,n=new Map;e.forEach(l=>{l.admesh_link&&r.set(l.admesh_link,l),l.click_url&&n.set(l.click_url,l)}),console.log("[AdMesh Summary] Processing recommendations:",{totalRecommendations:e.length,recommendationFields:e.map(l=>({ad_id:l.ad_id,click_url:l.click_url,admesh_link:l.admesh_link,title:l.title||l.recommendation_title}))}),r.size>0||n.size>0?console.log("[AdMesh Summary] Available recommendation links:",{admesh_links:Array.from(r.keys()),click_urls:Array.from(n.keys())}):console.warn("[AdMesh Summary] No click_url or admesh_link found in recommendations!");const i=/\[([^\]]+)\]\(([^)]+)\)/g,o=[];let d=0,a,c=0;for(;(a=i.exec(t))!==null;){const[l,h,p]=a;console.log("[AdMesh Summary] Processing markdown link:",{linkText:h,url:p,urlLength:p.length});let m=r.get(p)||n.get(p);if(console.log("[AdMesh Summary] URL match result:",{found:!!m,matchedBy:m?"exact_match":"none"}),m||(m=e.find(f=>f.ad_id&&p.includes(f.ad_id)),m&&console.log("[AdMesh Summary] Found by ad_id match")),a.index>d&&o.push(t.slice(d,a.index)),m){c++;const f=p||m.click_url||m.admesh_link;o.push(s.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary link clicked:",{adId:m.ad_id,productId:m.product_id,title:m.title||m.recommendation_title,brand:m.brand,pricing:m.pricing,clickUrl:m.click_url,admeshLink:m.admesh_link,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:m.ad_id,productId:m.product_id,clickUrl:m.click_url,admeshLink:m.admesh_link,source:"summary"}).catch(b=>{console.error("[AdMesh] Failed to track summary link click:",b)})},children:h},`summary-link-${c}`))}else console.warn(`[AdMesh Summary] No recommendation found for link: [${h}](${p}), creating regular link`,{availableLinks:Array.from(r.keys()),totalRecommendations:e.length,urlToMatch:p}),Le(p)?(c++,o.push(s.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary unmatched link clicked:",{linkText:h,url:p,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({url:p,linkText:h,source:"summary_unmatched"}).catch(f=>{console.error("[AdMesh] Failed to track unmatched link click:",f)})},children:h},`summary-link-${c}`))):(console.warn(`[AdMesh Summary] Invalid URL in markdown link: [${h}](${p})`),o.push(h));d=a.index+l.length}return d<t.length&&o.push(t.slice(d)),o},q=({summaryText:t,recommendations:e,theme:r,className:n="",style:i={}})=>{var a,c,l;if(!t||!t.trim())return console.warn("[AdMesh Summary] No summary text provided"),null;if(!e||e.length===0){console.warn("[AdMesh Summary] No recommendations provided");const h=Q(t,[]);return s.jsx("div",{className:`admesh-summary-unit ${n}`,style:i,children:s.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed",children:h.map((p,m)=>s.jsx(g.Fragment,{children:p},m))})})}const o=Q(t,e),d=((c=(a=e[0])==null?void 0:a.meta)==null?void 0:c.ad_id)||((l=e[0])==null?void 0:l.ad_id)||"";return s.jsx(D,{adId:d,className:`admesh-summary-unit ${n}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...i},children:s.jsxs("div",{children:[s.jsx("div",{className:"summary-content",children:s.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed text-base",children:o.map((h,p)=>s.jsx(g.Fragment,{children:h},p))})}),s.jsx("div",{className:"mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:s.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})})]})})};function Ne(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var W={exports:{}};/*!
|
|
2
2
|
Copyright (c) 2018 Jed Watson.
|
|
3
3
|
Licensed under the MIT License (MIT), see
|
|
4
4
|
http://jedwatson.github.io/classnames
|
|
5
|
-
*/var X;function Ie(){return X||(X=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var o="",d=0;d<arguments.length;d++){var a=arguments[d];a&&(o=i(o,n(a)))}return o}function n(o){if(typeof o=="string"||typeof o=="number")return o;if(typeof o!="object")return"";if(Array.isArray(o))return r.apply(null,o);if(o.toString!==Object.prototype.toString&&!o.toString.toString().includes("[native code]"))return o.toString();var d="";for(var a in o)e.call(o,a)&&o[a]&&(d=i(d,a));return d}function i(o,d){return d?o?o+" "+d:o+d:o}t.exports?(r.default=r,t.exports=r):window.classNames=r})()})(W)),W.exports}var Pe=Ie();const F=Ne(Pe),Fe="https://api.useadmesh.com/track";let De={enabled:!0,retryAttempts:3,retryDelay:1e3};const re=t=>{const[e,r]=
|
|
5
|
+
*/var X;function Ie(){return X||(X=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var o="",d=0;d<arguments.length;d++){var a=arguments[d];a&&(o=i(o,n(a)))}return o}function n(o){if(typeof o=="string"||typeof o=="number")return o;if(typeof o!="object")return"";if(Array.isArray(o))return r.apply(null,o);if(o.toString!==Object.prototype.toString&&!o.toString.toString().includes("[native code]"))return o.toString();var d="";for(var a in o)e.call(o,a)&&o[a]&&(d=i(d,a));return d}function i(o,d){return d?o?o+" "+d:o+d:o}t.exports?(r.default=r,t.exports=r):window.classNames=r})()})(W)),W.exports}var Pe=Ie();const F=Ne(Pe),Fe="https://api.useadmesh.com/track";let De={enabled:!0,retryAttempts:3,retryDelay:1e3};const re=t=>{const[e,r]=g.useState(!1),[n,i]=g.useState(null),o=g.useMemo(()=>({...De,...t}),[t]),d=g.useCallback(async(h,p)=>{if(!o.enabled)return;if(!p.adId||!p.admeshLink){i("Missing required tracking data: adId and admeshLink are required");return}r(!0),i(null);const m={event_type:h,ad_id:p.adId,admesh_link:p.admeshLink,product_id:p.productId,user_id:p.userId,session_id:p.sessionId,revenue:p.revenue,conversion_type:p.conversionType,metadata:p.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};let f=null;for(let y=1;y<=(o.retryAttempts||3);y++)try{const v=await fetch(`${Fe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});if(!v.ok)throw new Error(`HTTP ${v.status}: ${v.statusText}`);await v.json(),r(!1);return}catch(v){f=v,y<(o.retryAttempts||3)&&await new Promise(j=>setTimeout(j,(o.retryDelay||1e3)*y))}const b=`Failed to track ${h} event after ${o.retryAttempts} attempts: ${f==null?void 0:f.message}`;i(b),r(!1)},[o]),a=g.useCallback(async h=>d("click",h),[d]),c=g.useCallback(async h=>d("view",h),[d]),l=g.useCallback(async h=>d("conversion",h),[d]);return{trackClick:a,trackView:c,trackConversion:l,isTracking:e,error:n}},V=({adId:t,admeshLink:e,productId:r,children:n,trackingData:i,className:o,style:d})=>{const{trackClick:a,trackView:c}=re(),l=g.useRef(null),h=g.useRef(!1);g.useEffect(()=>{if(!l.current||h.current)return;const m=new IntersectionObserver(f=>{f.forEach(b=>{b.isIntersecting&&!h.current&&(h.current=!0,c({adId:t,admeshLink:e,productId:r,...i}).catch(console.error))})},{threshold:.5,rootMargin:"0px"});return m.observe(l.current),()=>{m.disconnect()}},[t,e,r,i,c]);const p=g.useCallback(m=>{a({adId:t,admeshLink:e,productId:r,...i}).catch(y=>{console.error("[AdMesh] Failed to track click:",y)}),m.target.closest("a")||window.open(e,"_blank","noopener,noreferrer")},[t,e,r,i,a]);return s.jsx("div",{ref:l,className:o,onClick:p,style:{cursor:"pointer",...d},children:n})};V.displayName="AdMeshLinkTracker";const U="admesh-ui-sdk-styles",H="admesh-ui-sdk-reset",Re=`
|
|
6
6
|
/* AdMesh UI SDK - CSS Reset & Normalization */
|
|
7
7
|
.admesh-component,
|
|
8
8
|
.admesh-component * {
|
|
@@ -970,7 +970,7 @@
|
|
|
970
970
|
.admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
971
971
|
.admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
|
|
972
972
|
}
|
|
973
|
-
`;let Z=!1;const oe=()=>{f.useEffect(()=>{if(!Z){try{Ve();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=$e,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),Z=!0}catch(t){console.error("[AdMesh] Failed to inject styles:",t)}return()=>{}}},[])},$=(t,e={})=>{const r=t.intent_match_score||0,n=e.customLabels||{};return r>=.8?n.partnerRecommendation||"Smart Pick":r>=.6?n.partnerMatch||"Partner Recommendation":r>=.3?n.promotedOption||"Promoted Match":n.relatedOption||"Related"},ee=(t,e)=>{const r=t.intent_match_score||0;return r>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":r>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":r>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},z=({recommendation:t,theme:e,showFeatures:r=!1,variation:n="default",className:i,style:o})=>{var l,g,b,w,_,j,C,T,M,L,N,x,p,k,v,y,E,A,I,R;oe();const a=n==="simple"?{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title,isSimple:!0}:{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title},c=F("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",i),m=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(l=e.shadows)==null?void 0:l.small,"--admesh-shadow-md":(g=e.shadows)==null?void 0:g.medium,"--admesh-shadow-lg":(b=e.shadows)==null?void 0:b.large,"--admesh-spacing-sm":(w=e.spacing)==null?void 0:w.small,"--admesh-spacing-md":(_=e.spacing)==null?void 0:_.medium,"--admesh-spacing-lg":(j=e.spacing)==null?void 0:j.large,"--admesh-font-size-sm":(C=e.fontSize)==null?void 0:C.small,"--admesh-font-size-base":(T=e.fontSize)==null?void 0:T.base,"--admesh-font-size-lg":(M=e.fontSize)==null?void 0:M.large,"--admesh-font-size-title":(L=e.fontSize)==null?void 0:L.title,fontFamily:e.fontFamily,width:((x=(N=e.components)==null?void 0:N.productCard)==null?void 0:x.width)||"100%"}:{width:"100%"};if(n==="simple"){const P=((p=t.meta)==null?void 0:p.ad_id)||t.ad_id||"",O=t.product_id||"";return s.jsx(D,{adId:P,productId:O,className:F("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",i),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(k=e==null?void 0:e.components)==null?void 0:k.productCard,...o},children:s.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[s.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:ee(t,$(t)),children:$(t)}),s.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[a.description," "]}),s.jsx(V,{adId:((v=t.meta)==null?void 0:v.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:t.intent_match_score,component:"simple_ad_cta"},children:s.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:a.ctaText})})]})})}const u=((y=t.meta)==null?void 0:y.ad_id)||t.ad_id||"",h=t.product_id||"";return s.jsx(D,{adId:u,productId:h,className:c,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(E=e==null?void 0:e.components)==null?void 0:E.productCard,...o},children:s.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(A=e==null?void 0:e.components)==null?void 0:A.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:s.jsxs("div",{className:"h-full flex flex-col",style:m,children:[s.jsx("div",{className:"mb-1.5",children:s.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:ee(t,$(t)),children:$(t)})}),s.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&s.jsx("img",{src:t.product_logo.url,alt:`${t.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:P=>{P.target.style.display="none"}}),s.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:a.title})]}),s.jsx("div",{className:"flex-shrink-0",children:s.jsx(V,{adId:((I=t.meta)==null?void 0:I.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((R=t.meta)==null?void 0:R.intent_match_score)||t.intent_match_score,component:"product_card_cta"},children:s.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:["Visit",s.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),s.jsx("div",{className:"mb-3",children:s.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:a.description})}),r&&t.features&&t.features.length>0&&s.jsxs("div",{className:"mb-2",children:[s.jsx("div",{className:"text-xs font-medium mb-1.5",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:"Key Features"}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[t.features.slice(0,4).map((P,O)=>s.jsxs("span",{className:"text-xs px-2 py-1 rounded-full border",style:{backgroundColor:(e==null?void 0:e.mode)==="dark"?"#111111":"#f5f5f5",color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",borderColor:(e==null?void 0:e.mode)==="dark"?"#333333":"#e5e7eb"},children:[s.jsx("svg",{className:"h-3 w-3 mr-0.5 inline",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),P]},O)),t.features.length>4&&s.jsxs("span",{className:"text-xs px-2 py-1",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:["+",t.features.length-4," more"]})]})]}),s.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:s.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[s.jsx("span",{children:"Sponsored"}),s.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};z.displayName="AdMeshProductCard";const ae=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:n="",cardClassName:i="",onProductClick:o,showPricing:d=!0,showRatings:a=!0,showBrand:c=!0,showSource:m=!1,showShipping:u=!0,maxCards:h=10,cardWidth:l="md",theme:g="auto",borderRadius:b="md",shadow:w="sm"})=>{if(!t||t.length===0)return console.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const _=t.slice(0,h),j=()=>{switch(l){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},C=()=>{switch(b){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},T=()=>{switch(w){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},M=()=>g==="dark"?"bg-gray-900 text-white":g==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",L=p=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(p),N=p=>{const k=[],v=Math.floor(p),y=p%1!==0;for(let A=0;A<v;A++)k.push(s.jsx("span",{className:"text-yellow-400",children:"★"},A));y&&k.push(s.jsx("span",{className:"text-yellow-400",children:"☆"},"half"));const E=5-Math.ceil(p);for(let A=0;A<E;A++)k.push(s.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"☆"},`empty-${A}`));return k},x=p=>{if(o)o(p);else{const k=p.admesh_link||p.url;k&&window.open(k,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:s.jsxs("div",{className:F("w-full",n),children:[r&&s.jsxs("div",{className:"mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),s.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),s.jsxs("div",{className:"relative",children:[_.length===0?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):s.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:_.map(p=>{var E;const k=p.product_id||p.id||p.ad_id,v=p.ad_id||p.product_id||"",y=p.product_id||"";return s.jsx(D,{adId:v,productId:y,className:F(j(),C(),T(),M(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",i),onClick:()=>x(p),children:s.jsxs("div",{children:[s.jsxs("div",{className:"relative aspect-square w-full overflow-hidden",children:[p.image_url?s.jsx("img",{src:p.image_url,alt:p.title,className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy"}):s.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:s.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),d&&p.discount_percentage&&p.discount_percentage>0&&s.jsxs("div",{className:"absolute top-2 left-2 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded",children:["-",Math.round(p.discount_percentage),"%"]}),m&&p.source&&s.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs font-medium px-2 py-1 rounded",children:p.source.toUpperCase()})]}),s.jsxs("div",{className:"p-3",children:[c&&p.brand&&s.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 uppercase tracking-wide",children:p.brand}),s.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:p.title}),a&&p.rating&&s.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[s.jsx("div",{className:"flex text-sm",children:N(p.rating)}),s.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",p.review_count||0,")"]})]}),d&&p.price&&s.jsx("div",{className:"mb-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-lg font-bold text-gray-900 dark:text-white",children:L(p.price)}),p.original_price&&p.original_price>p.price&&s.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400 line-through",children:L(p.original_price)})]})}),u&&((E=p.shipping_info)==null?void 0:E.free_shipping_over_35)&&s.jsx("div",{className:"text-xs text-green-600 dark:text-green-400 font-medium",children:"Free shipping over $35"}),p.availability&&p.availability!=="unknown"&&s.jsx("div",{className:F("text-xs font-medium mt-1",p.availability==="in_stock"?"text-green-600 dark:text-green-400":"text-red-600 dark:text-red-400"),children:p.availability==="in_stock"?"In Stock":"Out of Stock"})]})]})},k)})}),_.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),s.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[s.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),s.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),s.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
973
|
+
`;let Z=!1;const oe=()=>{g.useEffect(()=>{if(!Z){try{Ve();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=$e,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),Z=!0}catch(t){console.error("[AdMesh] Failed to inject styles:",t)}return()=>{}}},[])},$=(t,e={})=>{const r=t.intent_match_score||0,n=e.customLabels||{};return r>=.8?n.partnerRecommendation||"Smart Pick":r>=.6?n.partnerMatch||"Partner Recommendation":r>=.3?n.promotedOption||"Promoted Match":n.relatedOption||"Related"},ee=(t,e)=>{const r=t.intent_match_score||0;return r>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":r>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":r>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},z=({recommendation:t,theme:e,showFeatures:r=!1,variation:n="default",className:i,style:o})=>{var m,f,b,y,v,j,C,T,M,L,N,x,u,k,_,w,E,A,I,R;oe();const a=n==="simple"?{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title,isSimple:!0}:{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title},c=F("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",i),l=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(m=e.shadows)==null?void 0:m.small,"--admesh-shadow-md":(f=e.shadows)==null?void 0:f.medium,"--admesh-shadow-lg":(b=e.shadows)==null?void 0:b.large,"--admesh-spacing-sm":(y=e.spacing)==null?void 0:y.small,"--admesh-spacing-md":(v=e.spacing)==null?void 0:v.medium,"--admesh-spacing-lg":(j=e.spacing)==null?void 0:j.large,"--admesh-font-size-sm":(C=e.fontSize)==null?void 0:C.small,"--admesh-font-size-base":(T=e.fontSize)==null?void 0:T.base,"--admesh-font-size-lg":(M=e.fontSize)==null?void 0:M.large,"--admesh-font-size-title":(L=e.fontSize)==null?void 0:L.title,fontFamily:e.fontFamily,width:((x=(N=e.components)==null?void 0:N.productCard)==null?void 0:x.width)||"100%"}:{width:"100%"};if(n==="simple"){const P=((u=t.meta)==null?void 0:u.ad_id)||t.ad_id||"",O=t.product_id||"";return s.jsx(D,{adId:P,productId:O,className:F("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",i),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(k=e==null?void 0:e.components)==null?void 0:k.productCard,...o},children:s.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[s.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:ee(t,$(t)),children:$(t)}),s.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[a.description," "]}),s.jsx(V,{adId:((_=t.meta)==null?void 0:_.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:t.intent_match_score,component:"simple_ad_cta"},children:s.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:a.ctaText})})]})})}const h=((w=t.meta)==null?void 0:w.ad_id)||t.ad_id||"",p=t.product_id||"";return s.jsx(D,{adId:h,productId:p,className:c,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(E=e==null?void 0:e.components)==null?void 0:E.productCard,...o},children:s.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(A=e==null?void 0:e.components)==null?void 0:A.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:s.jsxs("div",{className:"h-full flex flex-col",style:l,children:[s.jsx("div",{className:"mb-1.5",children:s.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:ee(t,$(t)),children:$(t)})}),s.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&s.jsx("img",{src:t.product_logo.url,alt:`${t.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:P=>{P.target.style.display="none"}}),s.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:a.title})]}),s.jsx("div",{className:"flex-shrink-0",children:s.jsx(V,{adId:((I=t.meta)==null?void 0:I.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((R=t.meta)==null?void 0:R.intent_match_score)||t.intent_match_score,component:"product_card_cta"},children:s.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:["Visit",s.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),s.jsx("div",{className:"mb-3",children:s.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:a.description})}),r&&t.features&&t.features.length>0&&s.jsxs("div",{className:"mb-2",children:[s.jsx("div",{className:"text-xs font-medium mb-1.5",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:"Key Features"}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[t.features.slice(0,4).map((P,O)=>s.jsxs("span",{className:"text-xs px-2 py-1 rounded-full border",style:{backgroundColor:(e==null?void 0:e.mode)==="dark"?"#111111":"#f5f5f5",color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",borderColor:(e==null?void 0:e.mode)==="dark"?"#333333":"#e5e7eb"},children:[s.jsx("svg",{className:"h-3 w-3 mr-0.5 inline",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),P]},O)),t.features.length>4&&s.jsxs("span",{className:"text-xs px-2 py-1",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:["+",t.features.length-4," more"]})]})]}),s.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:s.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[s.jsx("span",{children:"Sponsored"}),s.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};z.displayName="AdMeshProductCard";const ae=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:n="",cardClassName:i="",onProductClick:o,showPricing:d=!0,showRatings:a=!0,showBrand:c=!0,showSource:l=!1,showShipping:h=!0,maxCards:p=10,cardWidth:m="md",theme:f="auto",borderRadius:b="md",shadow:y="sm"})=>{if(!t||t.length===0)return console.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const v=t.slice(0,p),j=()=>{switch(m){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},C=()=>{switch(b){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},T=()=>{switch(y){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},M=()=>f==="dark"?"bg-gray-900 text-white":f==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",L=u=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(u),N=u=>{const k=[],_=Math.floor(u),w=u%1!==0;for(let A=0;A<_;A++)k.push(s.jsx("span",{className:"text-yellow-400",children:"★"},A));w&&k.push(s.jsx("span",{className:"text-yellow-400",children:"☆"},"half"));const E=5-Math.ceil(u);for(let A=0;A<E;A++)k.push(s.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"☆"},`empty-${A}`));return k},x=u=>{if(o)o(u);else{const k=u.admesh_link||u.url;k&&window.open(k,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:s.jsxs("div",{className:F("w-full",n),children:[r&&s.jsxs("div",{className:"mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),s.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),s.jsxs("div",{className:"relative",children:[v.length===0?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):s.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:v.map(u=>{var E;const k=u.product_id||u.id||u.ad_id,_=u.ad_id||u.product_id||"",w=u.product_id||"";return s.jsx(D,{adId:_,productId:w,className:F(j(),C(),T(),M(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",i),onClick:()=>x(u),children:s.jsxs("div",{children:[s.jsxs("div",{className:"relative aspect-square w-full overflow-hidden",children:[u.image_url?s.jsx("img",{src:u.image_url,alt:u.title,className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy"}):s.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:s.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),d&&u.discount_percentage&&u.discount_percentage>0&&s.jsxs("div",{className:"absolute top-2 left-2 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded",children:["-",Math.round(u.discount_percentage),"%"]}),l&&u.source&&s.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs font-medium px-2 py-1 rounded",children:u.source.toUpperCase()})]}),s.jsxs("div",{className:"p-3",children:[c&&u.brand&&s.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 uppercase tracking-wide",children:u.brand}),s.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:u.title}),a&&u.rating&&s.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[s.jsx("div",{className:"flex text-sm",children:N(u.rating)}),s.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",u.review_count||0,")"]})]}),d&&u.price&&s.jsx("div",{className:"mb-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-lg font-bold text-gray-900 dark:text-white",children:L(u.price)}),u.original_price&&u.original_price>u.price&&s.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400 line-through",children:L(u.original_price)})]})}),h&&((E=u.shipping_info)==null?void 0:E.free_shipping_over_35)&&s.jsx("div",{className:"text-xs text-green-600 dark:text-green-400 font-medium",children:"Free shipping over $35"}),u.availability&&u.availability!=="unknown"&&s.jsx("div",{className:F("text-xs font-medium mt-1",u.availability==="in_stock"?"text-green-600 dark:text-green-400":"text-red-600 dark:text-red-400"),children:u.availability==="in_stock"?"In Stock":"Out of Stock"})]})]})},k)})}),v.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),s.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[s.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),s.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),s.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
974
974
|
.scrollbar-hide {
|
|
975
975
|
-ms-overflow-style: none;
|
|
976
976
|
scrollbar-width: none;
|
|
@@ -984,5 +984,5 @@
|
|
|
984
984
|
-webkit-box-orient: vertical;
|
|
985
985
|
overflow: hidden;
|
|
986
986
|
}
|
|
987
|
-
`}})]})},Be=t=>{var i,o,d;const e=[];if(!t)return{isValid:!1,isEmpty:!0,warnings:["No response object provided"]};(!t.recommendations||!Array.isArray(t.recommendations))&&e.push("No recommendations array found in response"),t.layout_type==="citation"&&!t.citation_summary&&e.push("Citation layout specified but no citation_summary provided");const r=((i=t.recommendations)==null?void 0:i.filter(a=>a&&a.admesh_link&&(a.title||a.recommendation_title)))||[],n=((o=t.recommendations)==null?void 0:o.length)===0;return r.length===0&&!n&&e.push("No valid recommendations found (missing admesh_link or title)"),{isValid:r.length>0,isEmpty:n,validCount:r.length,totalCount:((d=t.recommendations)==null?void 0:d.length)||0,warnings:e}},se=({response:t,theme:e,className:r="",style:n={},onLinkClick:i})=>{const o=Be(t);if(o.warnings.length>0&&console.warn("[AdMesh Summary Layout] Validation warnings:",o.warnings),o.isEmpty)return console.log("[AdMesh Summary Layout] Empty recommendations array - not rendering anything"),null;if(!o.isValid)return console.error("[AdMesh Summary Layout] Invalid response object"),null;const{layout_type:d="citation",citation_summary:a,recommendations:c=[],requires_summary:m=!0}=t;console.log(`[AdMesh Summary Layout] Rendering ${d} layout with ${o.validCount}/${o.totalCount} valid recommendations`);const u=()=>{switch(d){case"citation":return a&&m?s.jsx(q,{summaryText:a,recommendations:c,theme:e,onLinkClick:i}):s.jsxs("div",{className:"fallback-citation",children:[s.jsx("p",{className:"text-gray-700 dark:text-gray-300 mb-3",children:"Based on your query, I'd recommend checking out these options:"}),s.jsx(z,{recommendation:c[0],theme:e})]});case"product_cards":case"product":return s.jsx("div",{className:"product-cards-layout",children:c.slice(0,3).map((h,l)=>s.jsx(z,{recommendation:h,theme:e,className:"mb-4"},h.ad_id||`rec-${l}`))});case"ecommerce":return s.jsx(ae,{recommendations:c.slice(0,3),theme:(e==null?void 0:e.mode)||"light"});default:return console.warn(`[AdMesh Summary Layout] Unknown layout type: ${d}`),a?s.jsx(q,{summaryText:a,recommendations:c,theme:e,onLinkClick:i}):s.jsx(z,{recommendation:c[0],theme:e})}};return s.jsx("div",{className:`admesh-summary-layout admesh-layout-${d} ${r}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...n},children:u()})},ne=({response:t,theme:e,className:r,style:n,onLinkClick:i})=>t?t.recommendations&&Array.isArray(t.recommendations)&&t.recommendations.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):s.jsx(se,{response:t,theme:e,className:r,style:n,onLinkClick:i}):(console.error("[AdMeshLayout] response prop is required"),null);class ie{constructor(e){S(this,"firedExposures",new Set);S(this,"debug",!1);S(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,r,n){const i=`${n}_${r}`;if(this.firedExposures.has(i)){this.debug&&console.log("[Tracker] Exposure already fired for:",r);return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(o=>{this.debug&&console.warn("[Tracker] Failed to fire exposure:",o)}),this.debug&&console.log("[Tracker] Fired MRC-compliant exposure for:",r)}catch(o){this.debug&&console.error("[Tracker] Error firing exposure:",o)}}async fireExposureWithMRCCompliance(e,r,n,i){const o=`${n}_${r}`;if(this.firedExposures.has(o)){this.debug&&console.log("[Tracker] MRC exposure already fired for:",r);return}return new Promise(d=>{let a=null,c=null;const m=new IntersectionObserver(l=>{l.forEach(g=>{const b=g.intersectionRatio*100;b>=this.mrcThreshold.visibilityPercentage?a===null&&(a=Date.now(),this.debug&&console.log("[Tracker] Ad reached MRC visibility threshold:",{adId:r,visibilityPercentage:b.toFixed(2)}),c=setTimeout(()=>{this.fireExposure(e,r,n),m.disconnect(),d()},this.mrcThreshold.minimumDurationMs)):a!==null&&(c&&(clearTimeout(c),c=null),a=null,this.debug&&console.log("[Tracker] Ad visibility dropped below MRC threshold:",{adId:r,visibilityPercentage:b.toFixed(2)}))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});m.observe(i);const h=setTimeout(()=>{m.disconnect(),c&&clearTimeout(c),d()},3e4);i.__admeshTrackerCleanup=()=>{m.disconnect(),c&&clearTimeout(c),clearTimeout(h)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class de{constructor(){S(this,"roots",new Map)}async render(e){var r,n,i,o;try{const d=document.getElementById(e.containerId);if(!d)throw new Error(`Container with ID "${e.containerId}" not found`);const a=this.roots.get(e.containerId);a&&a.unmount();const c=be.createRoot(d),m=((r=e.response.response)==null?void 0:r.citation_summary)||((n=e.response.response)==null?void 0:n.summary);c.render(s.jsx(ne,{response:{layout_type:(i=e.response.response)==null?void 0:i.layout_type,citation_summary:m,recommendations:((o=e.response.response)==null?void 0:o.recommendations)||[],requires_summary:!!m},theme:e.theme})),this.roots.set(e.containerId,c)}catch(d){throw d}}unmount(e){const r=this.roots.get(e);r&&(r.unmount(),this.roots.delete(e))}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class ce{constructor(e={}){S(this,"autoAddLabels");S(this,"fireExposurePixels");S(this,"labelStyle");S(this,"processedLinks",new Set);S(this,"mutationObserver",null);var r,n,i,o;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((r=e.labelStyle)==null?void 0:r.fontSize)||"0.75em",fontWeight:((n=e.labelStyle)==null?void 0:n.fontWeight)||"bold",color:((i=e.labelStyle)==null?void 0:i.color)||"#666",marginLeft:((o=e.labelStyle)==null?void 0:o.marginLeft)||"2px"}}getLinksToProcess(e){const n=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return n.length>0?Array.from(n):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,r,n){if(!e)return[];const i=[],o=this.getLinksToProcess(e),d=new Map(r.filter(a=>a.click_url).map(a=>[a.click_url,a]));return o.forEach(a=>{var h;const c=a.getAttribute("href")||"",m=`${c}`;if(this.processedLinks.has(m))return;const u=d.get(c);if(u){this.processedLinks.add(m);const l={element:a,href:c,text:a.textContent||"",hasAdLabel:this.hasAdLabel(a),matchedRecommendation:{ad_id:u.ad_id||((h=u.meta)==null?void 0:h.ad_id)||"",click_url:u.click_url,exposure_url:u.exposure_url}};this.autoAddLabels&&!l.hasAdLabel&&(this.addAdLabel(a),l.hasAdLabel=!0),this.fireExposurePixels&&u.exposure_url&&n&&l.matchedRecommendation&&n(u.exposure_url,l.matchedRecommendation.ad_id),i.push(l)}}),i}hasAdLabel(e){const r=e.nextSibling;if(r&&r.nodeType===Node.TEXT_NODE&&(r.textContent||"").includes("[Ad]"))return!0;const n=e.parentElement;if(n){const i=n.innerHTML;if(i.includes("<sub>[Ad]</sub>")||i.includes("[Ad]"))return!0}return!1}addAdLabel(e){var n;const r=document.createElement("sub");r.textContent="[Ad]",r.style.fontSize=this.labelStyle.fontSize,r.style.fontWeight=this.labelStyle.fontWeight,r.style.color=this.labelStyle.color,r.style.marginLeft=this.labelStyle.marginLeft,(n=e.parentNode)==null||n.insertBefore(r,e.nextSibling)}watchForNewLinks(e,r,n){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,r,n)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}class le{constructor(e){S(this,"config");S(this,"apiBaseUrl","https://api.useadmesh.com");S(this,"renderer",null);S(this,"tracker",null);S(this,"weaveProcessor",null);S(this,"weaveCache",new Map);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme}}static createSession(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}static createMessageId(e){const r=Date.now(),n=Math.random().toString(36).substring(2,15);return`msg_${e}_${r}_${n}`}getRenderer(){return this.renderer||(this.renderer=new de),this.renderer}getTracker(){return this.tracker||(this.tracker=new ie({apiKey:this.config.apiKey})),this.tracker}getWeaveProcessor(){return this.weaveProcessor||(this.weaveProcessor=new ce({autoAddLabels:!0,fireExposurePixels:!0})),this.weaveProcessor}async showRecommendations(e){var r,n;try{const i=await this.fetchRecommendationsFromAPI({query:e.query,format:e.format||"auto",previousQuery:e.previousQuery,previousSummary:e.previousSummary,sessionId:e.session_id,messageId:e.message_id,isFallbackAllowed:e.isFallbackAllowed!==!1});if(e.format==="weave")await this.handleWeaveFormat(e,i);else{const o=this.getRenderer(),d=this.getTracker();if(await o.render({containerId:e.containerId,response:i,theme:e.theme||this.config.theme,tracker:d,sessionId:e.session_id||""}),(r=i.response)!=null&&r.recommendations){for(const a of i.response.recommendations)if(a.exposure_url){const c=((n=a.meta)==null?void 0:n.ad_id)||a.ad_id||"";d.fireExposure(a.exposure_url,c,e.session_id||"")}}}}catch(i){throw console.error("[AdMeshSDK] Error showing recommendations:",i),i}}async handleWeaveFormat(e,r){var h,l,g,b;const n=e.session_id||"",i=e.message_id||"",o=e.timeoutMs||900,d=e.fallbackFormat||"citation",a=`${n}:${i}`;if(this.weaveCache.set(a,((h=r.response)==null?void 0:h.recommendations)||[]),e.llmOutputContainerId)try{if(await this.scanLLMOutputForAdMeshLinks(e.llmOutputContainerId,((l=r.response)==null?void 0:l.recommendations)||[],n,o)){console.log("[AdMeshSDK] Weave format: AdMesh links detected in LLM output. Skipping fallback UI.");return}}catch(w){console.error("[AdMeshSDK] Error scanning LLM output for AdMesh links:",w)}console.log("[AdMeshSDK] Weave format: No AdMesh links detected. Rendering fallback UI with format:",d);const c={...r,response:{...r.response,layout_type:d}},m=this.getRenderer(),u=this.getTracker();if(await m.render({containerId:e.containerId,response:c,theme:e.theme||this.config.theme,tracker:u,sessionId:n}),(g=r.response)!=null&&g.recommendations){for(const w of r.response.recommendations)if(w.exposure_url){const _=((b=w.meta)==null?void 0:b.ad_id)||w.ad_id||"";u.fireExposure(w.exposure_url,_,n)}}}async scanLLMOutputForAdMeshLinks(e,r,n,i){const o=document.getElementById(e);if(!o)return console.warn(`[AdMeshSDK] LLM output container not found: ${e}`),!1;const d=Date.now(),a=100;let c=!1,m=null;try{const u=new Promise(g=>{const b=new MutationObserver(()=>{this.scanAndLabelAds(e,r,n)&&!c&&(c=!0,console.log("[AdMeshSDK] AdMesh links detected via MutationObserver"),g(!0))});b.observe(o,{childList:!0,subtree:!0,characterData:!1}),m=b}),h=(async()=>{for(;Date.now()-d<i;){if(this.scanAndLabelAds(e,r,n)&&!c)return c=!0,console.log("[AdMeshSDK] AdMesh links detected via polling"),!0;await this.sleep(a)}return!1})();return await Promise.race([u,h])}finally{m&&m.disconnect()}}scanAndLabelAds(e,r,n){const i=document.getElementById(e);if(!i)return!1;const o=this.getWeaveProcessor(),d=this.getTracker();return o.scanAndProcessLinks(i,r,(c,m)=>{d.fireExposure(c,m,n)}).length>0}async fetchRecommendationsFromAPI(e){const r=`${this.apiBaseUrl}/agent/recommend`,n={query:e.query,format:e.format||"auto"};e.previousQuery&&(n.previous_query=e.previousQuery),e.previousSummary&&(n.previous_summary=e.previousSummary),e.sessionId&&(n.session_id=e.sessionId),e.messageId&&(n.message_id=e.messageId),e.isFallbackAllowed!==void 0&&(n.is_fallback_allowed=e.isFallbackAllowed);const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(n)});if(!i.ok){const a=(await i.json().catch(()=>({}))).detail||`HTTP ${i.status}`;throw new Error(`Failed to fetch recommendations: ${a}`)}return await i.json()}sleep(e){return new Promise(r=>setTimeout(r,e))}}const K=f.createContext(void 0);function me(){const t=f.useContext(K);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}const Oe=({apiKey:t,chatId:e,theme:r,children:n})=>{const i=f.useRef(null),[o,d]=f.useState(new Set);f.useEffect(()=>{if(!t){console.warn("[AdMeshProvider] ⚠️ AdMesh API key not configured");return}try{i.current=new le({apiKey:t,theme:r}),console.log("[AdMeshProvider] ✅ AdMesh SDK initialized")}catch(c){console.error("[AdMeshProvider] ❌ Failed to initialize AdMesh SDK:",c)}return()=>{console.log("[AdMeshProvider] 🧹 Provider unmounted")}},[t,r]);const a={sdk:i.current,apiKey:t,chatId:e,theme:r,processedMessageIds:o,markMessageAsProcessed:c=>{d(m=>{const u=new Set(m);return u.add(c),u})},isMessageProcessed:c=>o.has(c)};return s.jsx(K.Provider,{value:a,children:n})};function Y(){const t=me();return{sdk:t.sdk,apiKey:t.apiKey,chatId:t.chatId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const We=({messages:t,format:e="auto",onRecommendationsShown:r,onError:n})=>{const{sdk:i,chatId:o,markMessageAsProcessed:d,isMessageProcessed:a}=Y();return f.useEffect(()=>{(async()=>{if(!i){console.warn("[AdMeshRecommendations] ⚠️ SDK not initialized");return}const m=[...t].reverse().find(l=>l.role==="assistant");if(!m)return;const u=[...t].reverse().find(l=>l.role==="user");if(!u)return;const h=u.messageId;if(!a(h)){d(h);try{const l=`admesh-recommendations-${m.messageId}`;console.log("[AdMeshRecommendations] 📊 Showing recommendations:",{sessionId:o,messageId:h,query:u.content.substring(0,50)+"...",containerId:l}),await i.showRecommendations({query:u.content,containerId:l,format:e,session_id:o,message_id:h}),r==null||r(h)}catch(l){const g=l instanceof Error?l:new Error(String(l));console.error("[AdMeshRecommendations] ❌ Error showing recommendations:",g),n==null||n(g)}}})()},[t,i,o,e,d,a,r,n]),null},ue=({recommendation:t,theme:e,variation:r="default",expandable:n=!1,className:i,style:o})=>{var m,u,h,l,g;const a=(()=>{const b=t.content_variations;return r==="question"&&(b!=null&&b.question)?{title:b.question.cta||t.recommendation_title||t.title,description:b.question.text,ctaText:b.question.cta||t.recommendation_title||t.title}:r==="statement"&&(b!=null&&b.statement)?{title:t.recommendation_title||t.title,description:b.statement.text,ctaText:b.statement.cta||t.recommendation_title||t.title}:{title:t.recommendation_title||t.title,description:t.recommendation_description||t.reason||"",ctaText:t.recommendation_title||t.title}})(),c=F("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":n&&(r==="question"||r==="statement")},i);return s.jsx("div",{className:c,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((u=(m=e==null?void 0:e.components)==null?void 0:m.inlineRecommendation)==null?void 0:u.width)||"100%",...(h=e==null?void 0:e.components)==null?void 0:h.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&s.jsx("img",{src:t.product_logo.url,alt:`${t.title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:b=>{b.target.style.display="none"}}),s.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:a.title})]}),s.jsx("div",{className:"flex-shrink-0",children:s.jsx(V,{adId:((l=t.meta)==null?void 0:l.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((g=t.meta)==null?void 0:g.intent_match_score)||t.intent_match_score,component:"inline_card_cta"},children:s.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[r==="question"?"Try":"Visit",s.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),a.description&&s.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:a.description}),s.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:s.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[s.jsx("span",{children:"Sponsored"}),s.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};ue.displayName="AdMeshInlineCard";const Ue={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},He={"Top Match":"★","Free Tier":"◆","AI Powered":"◉",Popular:"▲",New:"●","Trial Available":"◈"},he=({type:t,variant:e,size:r="md",className:n,style:i})=>{const o=e||Ue[t]||"secondary",d=He[t],a=F("admesh-component","admesh-badge",`admesh-badge--${o}`,`admesh-badge--${r}`,n);return s.jsxs("span",{className:a,style:i,children:[d&&s.jsx("span",{className:"admesh-badge__icon",children:d}),s.jsx("span",{className:"admesh-badge__text",children:t})]})};he.displayName="AdMeshBadge";const pe=t=>{const{sdk:e,chatId:r}=Y(),n=f.useRef(!1),i=f.useRef(0),o=f.useRef(!1),d=f.useRef(!1),a=f.useCallback(async()=>{var c,m,u,h;if(!(!e||!r||n.current)){n.current=!0,i.current=0;try{const l=document.getElementById(t.llmOutputContainerId);if(!l){console.warn(`[useWeaveAdFormat] Container not found: ${t.llmOutputContainerId}`);return}const g=(c=e.getWeaveProcessor)==null?void 0:c.call(e);if(!g){console.warn("[useWeaveAdFormat] WeaveResponseProcessor not available");return}const b=g.scanAndProcessLinks(l,[],(_,j)=>{console.log("[useWeaveAdFormat] Exposure tracked:",{adId:j,exposureUrl:_})});i.current=b.length;const w=b.length>0;w&&!o.current?(o.current=!0,console.log(`[useWeaveAdFormat] Detected ${b.length} AdMesh links`),(m=t.onLinksDetected)==null||m.call(t,b.length),d.current=!0):!w&&o.current?(o.current=!1,d.current=!1):!w&&!d.current&&(console.log("[useWeaveAdFormat] No AdMesh links detected - fallback UI should be rendered"),(u=t.onNoLinksDetected)==null||u.call(t),d.current=!0)}catch(l){const g=l instanceof Error?l:new Error(String(l));console.error("[useWeaveAdFormat] Error processing Weave format:",g),(h=t.onError)==null||h.call(t,g)}finally{n.current=!1}}},[e,r,t]);return f.useEffect(()=>{const c=document.getElementById(t.llmOutputContainerId);if(!c)return;a();const m=new MutationObserver(()=>{a()});return m.observe(c,{childList:!0,subtree:!0,characterData:!1}),()=>{m.disconnect()}},[t.llmOutputContainerId,a]),{isProcessing:n.current,detectedLinksCount:i.current,linksFound:o.current,shouldRenderFallback:!o.current,processWeaveFormat:a}},qe=({messageId:t,children:e,timeoutMs:r=900,fallbackFormat:n="citation",onLinksDetected:i,onNoLinksDetected:o,onError:d,className:a,fallbackUI:c})=>{const m=f.useRef(null),u=`weave-ad-container-${t}`,{detectedLinksCount:h,shouldRenderFallback:l}=pe({llmOutputContainerId:u,timeoutMs:r,fallbackFormat:n,onLinksDetected:i,onNoLinksDetected:o,onError:d});return s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:m,id:u,className:a,"data-weave-ad-format":"true","data-message-id":t,"data-detected-links":h,"data-links-found":h>0,children:e}),l&&c&&s.jsx("div",{"data-weave-fallback-ui":"true","data-message-id":t,children:c})]})},Ke="1.0.0";exports.AdMeshBadge=he;exports.AdMeshContext=K;exports.AdMeshEcommerceCards=ae;exports.AdMeshInlineCard=ue;exports.AdMeshLayout=ne;exports.AdMeshLinkTracker=V;exports.AdMeshProductCard=z;exports.AdMeshProvider=Oe;exports.AdMeshRecommendations=We;exports.AdMeshRenderer=de;exports.AdMeshSDK=le;exports.AdMeshSummaryLayout=se;exports.AdMeshSummaryUnit=q;exports.AdMeshTracker=ie;exports.AdMeshViewabilityTracker=D;exports.VERSION=Ke;exports.WeaveAdFormatContainer=qe;exports.WeaveResponseProcessor=ce;exports.useAdMesh=Y;exports.useAdMeshContext=me;exports.useAdMeshStyles=oe;exports.useAdMeshTracker=re;exports.useViewabilityTracker=te;exports.useWeaveAdFormat=pe;
|
|
987
|
+
`}})]})},Be=t=>{var i,o,d;const e=[];if(!t)return{isValid:!1,isEmpty:!0,warnings:["No response object provided"]};(!t.recommendations||!Array.isArray(t.recommendations))&&e.push("No recommendations array found in response"),t.layout_type==="citation"&&!t.citation_summary&&e.push("Citation layout specified but no citation_summary provided");const r=((i=t.recommendations)==null?void 0:i.filter(a=>a&&a.admesh_link&&(a.title||a.recommendation_title)))||[],n=((o=t.recommendations)==null?void 0:o.length)===0;return r.length===0&&!n&&e.push("No valid recommendations found (missing admesh_link or title)"),{isValid:r.length>0,isEmpty:n,validCount:r.length,totalCount:((d=t.recommendations)==null?void 0:d.length)||0,warnings:e}},se=({response:t,theme:e,className:r="",style:n={},onLinkClick:i})=>{const o=Be(t);if(o.warnings.length>0&&console.warn("[AdMesh Summary Layout] Validation warnings:",o.warnings),o.isEmpty)return console.log("[AdMesh Summary Layout] Empty recommendations array - not rendering anything"),null;if(!o.isValid)return console.error("[AdMesh Summary Layout] Invalid response object"),null;const{layout_type:d="citation",citation_summary:a,recommendations:c=[],requires_summary:l=!0}=t;console.log(`[AdMesh Summary Layout] Rendering ${d} layout with ${o.validCount}/${o.totalCount} valid recommendations`);const h=()=>{switch(d){case"citation":return a&&l?s.jsx(q,{summaryText:a,recommendations:c,theme:e,onLinkClick:i}):s.jsxs("div",{className:"fallback-citation",children:[s.jsx("p",{className:"text-gray-700 dark:text-gray-300 mb-3",children:"Based on your query, I'd recommend checking out these options:"}),s.jsx(z,{recommendation:c[0],theme:e})]});case"product_cards":case"product":return s.jsx("div",{className:"product-cards-layout",children:c.slice(0,3).map((p,m)=>s.jsx(z,{recommendation:p,theme:e,className:"mb-4"},p.ad_id||`rec-${m}`))});case"ecommerce":return s.jsx(ae,{recommendations:c.slice(0,3),theme:(e==null?void 0:e.mode)||"light"});default:return console.warn(`[AdMesh Summary Layout] Unknown layout type: ${d}`),a?s.jsx(q,{summaryText:a,recommendations:c,theme:e,onLinkClick:i}):s.jsx(z,{recommendation:c[0],theme:e})}};return s.jsx("div",{className:`admesh-summary-layout admesh-layout-${d} ${r}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...n},children:h()})},ne=({response:t,theme:e,className:r,style:n,onLinkClick:i})=>t?t.recommendations&&Array.isArray(t.recommendations)&&t.recommendations.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):s.jsx(se,{response:t,theme:e,className:r,style:n,onLinkClick:i}):(console.error("[AdMeshLayout] response prop is required"),null);class ie{constructor(e){S(this,"firedExposures",new Set);S(this,"debug",!1);S(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,r,n){const i=`${n}_${r}`;if(this.firedExposures.has(i)){this.debug&&console.log("[Tracker] Exposure already fired for:",r);return}this.firedExposures.add(i);try{fetch(e,{method:"GET",keepalive:!0}).catch(o=>{this.debug&&console.warn("[Tracker] Failed to fire exposure:",o)}),this.debug&&console.log("[Tracker] Fired MRC-compliant exposure for:",r)}catch(o){this.debug&&console.error("[Tracker] Error firing exposure:",o)}}async fireExposureWithMRCCompliance(e,r,n,i){const o=`${n}_${r}`;if(this.firedExposures.has(o)){this.debug&&console.log("[Tracker] MRC exposure already fired for:",r);return}return new Promise(d=>{let a=null,c=null;const l=new IntersectionObserver(m=>{m.forEach(f=>{const b=f.intersectionRatio*100;b>=this.mrcThreshold.visibilityPercentage?a===null&&(a=Date.now(),this.debug&&console.log("[Tracker] Ad reached MRC visibility threshold:",{adId:r,visibilityPercentage:b.toFixed(2)}),c=setTimeout(()=>{this.fireExposure(e,r,n),l.disconnect(),d()},this.mrcThreshold.minimumDurationMs)):a!==null&&(c&&(clearTimeout(c),c=null),a=null,this.debug&&console.log("[Tracker] Ad visibility dropped below MRC threshold:",{adId:r,visibilityPercentage:b.toFixed(2)}))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});l.observe(i);const p=setTimeout(()=>{l.disconnect(),c&&clearTimeout(c),d()},3e4);i.__admeshTrackerCleanup=()=>{l.disconnect(),c&&clearTimeout(c),clearTimeout(p)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class de{constructor(){S(this,"roots",new Map)}async render(e){var r,n,i,o;try{const d=document.getElementById(e.containerId);if(!d)throw new Error(`Container with ID "${e.containerId}" not found`);const a=this.roots.get(e.containerId);a&&a.unmount();const c=be.createRoot(d),l=((r=e.response.response)==null?void 0:r.citation_summary)||((n=e.response.response)==null?void 0:n.summary);c.render(s.jsx(ne,{response:{layout_type:(i=e.response.response)==null?void 0:i.layout_type,citation_summary:l,recommendations:((o=e.response.response)==null?void 0:o.recommendations)||[],requires_summary:!!l},theme:e.theme})),this.roots.set(e.containerId,c)}catch(d){throw d}}unmount(e){const r=this.roots.get(e);r&&(r.unmount(),this.roots.delete(e))}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class ce{constructor(e={}){S(this,"autoAddLabels");S(this,"fireExposurePixels");S(this,"labelStyle");S(this,"processedLinks",new Set);S(this,"mutationObserver",null);var r,n,i,o;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((r=e.labelStyle)==null?void 0:r.fontSize)||"0.75em",fontWeight:((n=e.labelStyle)==null?void 0:n.fontWeight)||"bold",color:((i=e.labelStyle)==null?void 0:i.color)||"#666",marginLeft:((o=e.labelStyle)==null?void 0:o.marginLeft)||"2px"}}getLinksToProcess(e){const n=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return n.length>0?Array.from(n):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,r,n){if(!e)return[];const i=[],o=this.getLinksToProcess(e),d=new Map(r.filter(a=>a.click_url).map(a=>[a.click_url,a]));return o.forEach(a=>{var p;const c=a.getAttribute("href")||"",l=`${c}`;if(this.processedLinks.has(l))return;const h=d.get(c);if(h){this.processedLinks.add(l);const m={element:a,href:c,text:a.textContent||"",hasAdLabel:this.hasAdLabel(a),matchedRecommendation:{ad_id:h.ad_id||((p=h.meta)==null?void 0:p.ad_id)||"",click_url:h.click_url,exposure_url:h.exposure_url}};this.autoAddLabels&&!m.hasAdLabel&&(this.addAdLabel(a),m.hasAdLabel=!0),this.fireExposurePixels&&h.exposure_url&&n&&m.matchedRecommendation&&n(h.exposure_url,m.matchedRecommendation.ad_id),i.push(m)}}),i}hasAdLabel(e){const r=e.nextSibling;if(r&&r.nodeType===Node.TEXT_NODE&&(r.textContent||"").includes("[Ad]"))return!0;const n=e.parentElement;if(n){const i=n.innerHTML;if(i.includes("<sub>[Ad]</sub>")||i.includes("[Ad]"))return!0}return!1}addAdLabel(e){var n;const r=document.createElement("sub");r.textContent="[Ad]",r.style.fontSize=this.labelStyle.fontSize,r.style.fontWeight=this.labelStyle.fontWeight,r.style.color=this.labelStyle.color,r.style.marginLeft=this.labelStyle.marginLeft,(n=e.parentNode)==null||n.insertBefore(r,e.nextSibling)}watchForNewLinks(e,r,n){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,r,n)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}class le{constructor(e){S(this,"config");S(this,"apiBaseUrl","https://api.useadmesh.com");S(this,"renderer",null);S(this,"tracker",null);S(this,"weaveProcessor",null);S(this,"weaveCache",new Map);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme}}static createSession(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}static createMessageId(e){const r=Date.now(),n=Math.random().toString(36).substring(2,15);return`msg_${e}_${r}_${n}`}getRenderer(){return this.renderer||(this.renderer=new de),this.renderer}getTracker(){return this.tracker||(this.tracker=new ie({apiKey:this.config.apiKey})),this.tracker}getWeaveProcessor(){return this.weaveProcessor||(this.weaveProcessor=new ce({autoAddLabels:!0,fireExposurePixels:!0})),this.weaveProcessor}async showRecommendations(e){var r,n;try{const i=await this.fetchRecommendationsFromAPI({query:e.query,format:e.format||"auto",previousQuery:e.previousQuery,previousSummary:e.previousSummary,sessionId:e.session_id,messageId:e.message_id,isFallbackAllowed:e.isFallbackAllowed!==!1});if(e.format==="weave")await this.handleWeaveFormat(e,i);else{const o=this.getRenderer(),d=this.getTracker();if(await o.render({containerId:e.containerId,response:i,theme:e.theme||this.config.theme,tracker:d,sessionId:e.session_id||""}),(r=i.response)!=null&&r.recommendations){for(const a of i.response.recommendations)if(a.exposure_url){const c=((n=a.meta)==null?void 0:n.ad_id)||a.ad_id||"";d.fireExposure(a.exposure_url,c,e.session_id||"")}}}}catch(i){throw console.error("[AdMeshSDK] Error showing recommendations:",i),i}}async handleWeaveFormat(e,r){var p,m,f,b;const n=e.session_id||"",i=e.message_id||"",o=e.timeoutMs||900,d=e.fallbackFormat||"citation",a=`${n}:${i}`;if(this.weaveCache.set(a,((p=r.response)==null?void 0:p.recommendations)||[]),e.llmOutputContainerId)try{if(await this.scanLLMOutputForAdMeshLinks(e.llmOutputContainerId,((m=r.response)==null?void 0:m.recommendations)||[],n,o)){console.log("[AdMeshSDK] Weave format: AdMesh links detected in LLM output. Skipping fallback UI.");return}}catch(y){console.error("[AdMeshSDK] Error scanning LLM output for AdMesh links:",y)}console.log("[AdMeshSDK] Weave format: No AdMesh links detected. Rendering fallback UI with format:",d);const c={...r,response:{...r.response,layout_type:d}},l=this.getRenderer(),h=this.getTracker();if(await l.render({containerId:e.containerId,response:c,theme:e.theme||this.config.theme,tracker:h,sessionId:n}),(f=r.response)!=null&&f.recommendations){for(const y of r.response.recommendations)if(y.exposure_url){const v=((b=y.meta)==null?void 0:b.ad_id)||y.ad_id||"";h.fireExposure(y.exposure_url,v,n)}}}async scanLLMOutputForAdMeshLinks(e,r,n,i){const o=document.getElementById(e);if(!o)return console.warn(`[AdMeshSDK] LLM output container not found: ${e}`),!1;const d=Date.now(),a=100;let c=!1,l=null;try{const h=new Promise(f=>{const b=new MutationObserver(()=>{this.scanAndLabelAds(e,r,n)&&!c&&(c=!0,console.log("[AdMeshSDK] AdMesh links detected via MutationObserver"),f(!0))});b.observe(o,{childList:!0,subtree:!0,characterData:!1}),l=b}),p=(async()=>{for(;Date.now()-d<i;){if(this.scanAndLabelAds(e,r,n)&&!c)return c=!0,console.log("[AdMeshSDK] AdMesh links detected via polling"),!0;await this.sleep(a)}return!1})();return await Promise.race([h,p])}finally{l&&l.disconnect()}}scanAndLabelAds(e,r,n){const i=document.getElementById(e);if(!i)return!1;const o=this.getWeaveProcessor(),d=this.getTracker();return o.scanAndProcessLinks(i,r,(c,l)=>{d.fireExposure(c,l,n)}).length>0}async fetchRecommendationsFromAPI(e){const r=`${this.apiBaseUrl}/agent/recommend`,n={query:e.query,format:e.format||"auto"};e.previousQuery&&(n.previous_query=e.previousQuery),e.previousSummary&&(n.previous_summary=e.previousSummary),e.sessionId&&(n.session_id=e.sessionId),e.messageId&&(n.message_id=e.messageId),e.isFallbackAllowed!==void 0&&(n.is_fallback_allowed=e.isFallbackAllowed);const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(n)});if(!i.ok){const a=(await i.json().catch(()=>({}))).detail||`HTTP ${i.status}`;throw new Error(`Failed to fetch recommendations: ${a}`)}return await i.json()}sleep(e){return new Promise(r=>setTimeout(r,e))}}const K=g.createContext(void 0);function me(){const t=g.useContext(K);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}const Oe=({apiKey:t,chatId:e,theme:r,children:n})=>{const i=g.useRef(null),[o,d]=g.useState(new Set);g.useEffect(()=>{if(!t){console.warn("[AdMeshProvider] ⚠️ AdMesh API key not configured");return}try{i.current=new le({apiKey:t,theme:r}),console.log("[AdMeshProvider] ✅ AdMesh SDK initialized")}catch(c){console.error("[AdMeshProvider] ❌ Failed to initialize AdMesh SDK:",c)}return()=>{console.log("[AdMeshProvider] 🧹 Provider unmounted")}},[t,r]);const a={sdk:i.current,apiKey:t,chatId:e,theme:r,processedMessageIds:o,markMessageAsProcessed:c=>{d(l=>{const h=new Set(l);return h.add(c),h})},isMessageProcessed:c=>o.has(c)};return s.jsx(K.Provider,{value:a,children:n})};function Y(){const t=me();return{sdk:t.sdk,apiKey:t.apiKey,chatId:t.chatId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const We=({messages:t,format:e="auto",onRecommendationsShown:r,onError:n})=>{const{sdk:i,chatId:o,markMessageAsProcessed:d,isMessageProcessed:a}=Y(),c=g.useRef(null),[l,h]=g.useState("");return g.useEffect(()=>{const p=[...t].reverse().find(m=>m.role==="assistant");p&&h(`admesh-recommendations-${p.messageId}`)},[t]),g.useEffect(()=>{(async()=>{if(!i||!l||![...t].reverse().find(y=>y.role==="assistant"))return;const f=[...t].reverse().find(y=>y.role==="user");if(!f)return;const b=f.messageId;if(!a(b)){d(b);try{console.log("[AdMeshRecommendations] 📊 Showing recommendations:",{sessionId:o,messageId:b,query:f.content.substring(0,50)+"...",containerId:l}),await i.showRecommendations({query:f.content,containerId:l,format:e,session_id:o,message_id:b}),r==null||r(b)}catch(y){const v=y instanceof Error?y:new Error(String(y));console.error("[AdMeshRecommendations] ❌ Error showing recommendations:",v),n==null||n(v)}}})()},[t,i,o,l,e,d,a,r,n]),s.jsx("div",{ref:c,id:l,className:"admesh-recommendations-container"})},ue=({recommendation:t,theme:e,variation:r="default",expandable:n=!1,className:i,style:o})=>{var l,h,p,m,f;const a=(()=>{const b=t.content_variations;return r==="question"&&(b!=null&&b.question)?{title:b.question.cta||t.recommendation_title||t.title,description:b.question.text,ctaText:b.question.cta||t.recommendation_title||t.title}:r==="statement"&&(b!=null&&b.statement)?{title:t.recommendation_title||t.title,description:b.statement.text,ctaText:b.statement.cta||t.recommendation_title||t.title}:{title:t.recommendation_title||t.title,description:t.recommendation_description||t.reason||"",ctaText:t.recommendation_title||t.title}})(),c=F("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":n&&(r==="question"||r==="statement")},i);return s.jsx("div",{className:c,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((h=(l=e==null?void 0:e.components)==null?void 0:l.inlineRecommendation)==null?void 0:h.width)||"100%",...(p=e==null?void 0:e.components)==null?void 0:p.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&s.jsx("img",{src:t.product_logo.url,alt:`${t.title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:b=>{b.target.style.display="none"}}),s.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:a.title})]}),s.jsx("div",{className:"flex-shrink-0",children:s.jsx(V,{adId:((m=t.meta)==null?void 0:m.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((f=t.meta)==null?void 0:f.intent_match_score)||t.intent_match_score,component:"inline_card_cta"},children:s.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[r==="question"?"Try":"Visit",s.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),a.description&&s.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:a.description}),s.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:s.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[s.jsx("span",{children:"Sponsored"}),s.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};ue.displayName="AdMeshInlineCard";const Ue={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},He={"Top Match":"★","Free Tier":"◆","AI Powered":"◉",Popular:"▲",New:"●","Trial Available":"◈"},he=({type:t,variant:e,size:r="md",className:n,style:i})=>{const o=e||Ue[t]||"secondary",d=He[t],a=F("admesh-component","admesh-badge",`admesh-badge--${o}`,`admesh-badge--${r}`,n);return s.jsxs("span",{className:a,style:i,children:[d&&s.jsx("span",{className:"admesh-badge__icon",children:d}),s.jsx("span",{className:"admesh-badge__text",children:t})]})};he.displayName="AdMeshBadge";const pe=t=>{const{sdk:e,chatId:r}=Y(),n=g.useRef(!1),i=g.useRef(0),o=g.useRef(!1),d=g.useRef(!1),a=g.useCallback(async()=>{var c,l,h,p;if(!(!e||!r||n.current)){n.current=!0,i.current=0;try{const m=document.getElementById(t.llmOutputContainerId);if(!m){console.warn(`[useWeaveAdFormat] Container not found: ${t.llmOutputContainerId}`);return}const f=(c=e.getWeaveProcessor)==null?void 0:c.call(e);if(!f){console.warn("[useWeaveAdFormat] WeaveResponseProcessor not available");return}const b=f.scanAndProcessLinks(m,[],(v,j)=>{console.log("[useWeaveAdFormat] Exposure tracked:",{adId:j,exposureUrl:v})});i.current=b.length;const y=b.length>0;y&&!o.current?(o.current=!0,console.log(`[useWeaveAdFormat] Detected ${b.length} AdMesh links`),(l=t.onLinksDetected)==null||l.call(t,b.length),d.current=!0):!y&&o.current?(o.current=!1,d.current=!1):!y&&!d.current&&(console.log("[useWeaveAdFormat] No AdMesh links detected - fallback UI should be rendered"),(h=t.onNoLinksDetected)==null||h.call(t),d.current=!0)}catch(m){const f=m instanceof Error?m:new Error(String(m));console.error("[useWeaveAdFormat] Error processing Weave format:",f),(p=t.onError)==null||p.call(t,f)}finally{n.current=!1}}},[e,r,t]);return g.useEffect(()=>{const c=document.getElementById(t.llmOutputContainerId);if(!c)return;a();const l=new MutationObserver(()=>{a()});return l.observe(c,{childList:!0,subtree:!0,characterData:!1}),()=>{l.disconnect()}},[t.llmOutputContainerId,a]),{isProcessing:n.current,detectedLinksCount:i.current,linksFound:o.current,shouldRenderFallback:!o.current,processWeaveFormat:a}},qe=({messageId:t,children:e,timeoutMs:r=900,fallbackFormat:n="citation",onLinksDetected:i,onNoLinksDetected:o,onError:d,className:a,fallbackUI:c})=>{const l=g.useRef(null),h=`weave-ad-container-${t}`,{detectedLinksCount:p,shouldRenderFallback:m}=pe({llmOutputContainerId:h,timeoutMs:r,fallbackFormat:n,onLinksDetected:i,onNoLinksDetected:o,onError:d});return s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:l,id:h,className:a,"data-weave-ad-format":"true","data-message-id":t,"data-detected-links":p,"data-links-found":p>0,children:e}),m&&c&&s.jsx("div",{"data-weave-fallback-ui":"true","data-message-id":t,children:c})]})},Ke="1.0.0";exports.AdMeshBadge=he;exports.AdMeshContext=K;exports.AdMeshEcommerceCards=ae;exports.AdMeshInlineCard=ue;exports.AdMeshLayout=ne;exports.AdMeshLinkTracker=V;exports.AdMeshProductCard=z;exports.AdMeshProvider=Oe;exports.AdMeshRecommendations=We;exports.AdMeshRenderer=de;exports.AdMeshSDK=le;exports.AdMeshSummaryLayout=se;exports.AdMeshSummaryUnit=q;exports.AdMeshTracker=ie;exports.AdMeshViewabilityTracker=D;exports.VERSION=Ke;exports.WeaveAdFormatContainer=qe;exports.WeaveResponseProcessor=ce;exports.useAdMesh=Y;exports.useAdMeshContext=me;exports.useAdMeshStyles=oe;exports.useAdMeshTracker=re;exports.useViewabilityTracker=te;exports.useWeaveAdFormat=pe;
|
|
988
988
|
//# sourceMappingURL=index.js.map
|