admesh-ui-sdk 1.0.3 โ†’ 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,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 C=(t,e,r)=>fe(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=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,a=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),s=Math.min(r,e.bottom),l=Math.max(0,e.left),c=Math.min(a,e.right),m=Math.max(0,s-d),u=Math.max(0,c-l),h=m*u,g=i*o;return g>0?h/g:0}function G(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,a=e-t;return a<=0?100:Math.min(100,r/a*100)}function ke(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,a=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+a}}function ve(t){const e=t.getBoundingClientRect(),r=ke(t),a=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(a),viewportWidth:a,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 Ae(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function V(t=new Date){return t.toISOString()}function Se(t){return t.length===0?0:t.reduce((r,a)=>r+a,0)/t.length}function J(t,e){let r;return function(...i){r||(t(...i),r=!0,setTimeout(()=>r=!1,e))}}async function Ce(t,e,r=3,a=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 s=await d.text().catch(()=>"");i=new Error(`HTTP ${d.status}: ${d.statusText} - ${s}`)}catch(d){i=d}o<r-1&&await new Promise(d=>setTimeout(d,a*Math.pow(2,o)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",i),!1}async function je(t,e,r,a=3,i=1e3){if(t.length===0||!r||r.trim()==="")return!0;const o={batchId:Me(),sessionId:e,createdAt:V(),events:t,eventCount:t.length};let d=null;for(let s=0;s<a;s++){try{const l=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});if(l.ok)return!0;const c=await l.text().catch(()=>"");d=new Error(`HTTP ${l.status}: ${l.statusText} - ${c}`)}catch(l){d=l}s<a-1&&await new Promise(l=>setTimeout(l,i*Math.pow(2,s)))}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 Le=Te;function te({adId:t,productId:e,offerId:r,agentId:a,recommendationId:i,elementRef:o,config:d}){const s={...Le,...d},l=f.useRef(_e()),[c,m]=f.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:V(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:s.enabled}),u=f.useRef(null),h=f.useRef(null),g=f.useRef(null),b=f.useRef(null),y=f.useRef(null),k=f.useRef([]),M=f.useRef([]),S=f.useRef(null),T=f.useCallback((x,p)=>{s.debug&&console.log(`[AdMesh Viewability] ${x}`,p)},[s.debug]),A=f.useCallback(async(x,p)=>{if(!s.enabled||!o.current||!u.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:V(),sessionId:l.current,adId:t,productId:e,offerId:r,agentId:a,recommendationId:i,timeMetrics:c.timeMetrics,engagementMetrics:c.engagementMetrics,contextMetrics:_,mrcStandards:u.current,isViewable:c.isViewable,metadata:p};T(`Sending critical event: ${x}`,w),s.onEvent&&s.onEvent(w),s.enableBatching?(M.current.push(w),M.current.length>=s.batchSize?await E():(S.current&&clearTimeout(S.current),S.current=setTimeout(E,s.batchTimeout))):await Ce(w,s.apiEndpoint,s.maxRetries,s.retryDelay)},[s,t,e,r,a,o,c,T]),E=f.useCallback(async()=>{if(M.current.length===0)return;const x=[...M.current];M.current=[],S.current&&(clearTimeout(S.current),S.current=null),await je(x,l.current,s.apiEndpoint,s.maxRetries,s.retryDelay)&&s.onBatchSent&&s.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:l.current,createdAt:V(),events:x,eventCount:x.length})},[s,T]),N=f.useCallback(J(()=>{if(!o.current)return;const x=we(o.current),p=Date.now(),v=new Date(c.timeMetrics.loadedAt).getTime();m(_=>{const w={..._};x>0&&k.current.push(x);const L=_.isVisible,j=x>0;if(j&&!L)h.current=p,w.engagementMetrics.viewportEnterCount++,w.timeMetrics.timeToFirstVisible||(w.timeMetrics.timeToFirstVisible=p-v,w.engagementMetrics.scrollDepthAtFirstVisible=G(),A("ad_visible"));else if(!j&&L){if(h.current){const F=p-h.current;w.timeMetrics.totalVisibleDuration+=F,h.current=null}w.engagementMetrics.viewportExitCount++,A("ad_hidden")}else if(j&&L&&h.current){const F=p-h.current;w.timeMetrics.totalVisibleDuration+=F,h.current=p}if(w.isVisible=j,w.visibilityPercentage=x,x>w.engagementMetrics.maxVisibilityPercentage&&(w.engagementMetrics.maxVisibilityPercentage=x),k.current.length>0&&(w.engagementMetrics.averageVisibilityPercentage=Se(k.current)),u.current){const F=_.isViewable,D=Ae(x,w.timeMetrics.totalVisibleDuration,u.current);if(D&&!F)w.isViewable=!0,w.timeMetrics.timeToViewable=p-v,g.current=p,A("ad_viewable");else if(D&&F&&g.current){const P=p-g.current;w.timeMetrics.totalViewableDuration+=P,g.current=p}}return w.engagementMetrics.currentScrollDepth=G(),w})},100),[o,c.timeMetrics.loadedAt,A]);return f.useEffect(()=>{if(!o.current)return;const x=o.current.getBoundingClientRect();u.current=xe(x.width,x.height,s.mrcStandards),T("Initialized MRC standards",u.current),A("ad_loaded")},[o,s.mrcStandards,T,A]),f.useEffect(()=>{if(!s.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()}},[s.enabled,o,N]),f.useEffect(()=>{if(!s.enabled)return;const x=J(()=>{N()},100);return window.addEventListener("scroll",x,{passive:!0}),()=>window.removeEventListener("scroll",x)},[s.enabled,N]),f.useEffect(()=>{if(!s.enabled||!o.current)return;const x=o.current,p=()=>{b.current=Date.now(),m(_=>({..._,engagementMetrics:{..._.engagementMetrics,hoverCount:_.engagementMetrics.hoverCount+1}})),A("ad_hover_start")},v=()=>{if(b.current){const _=Date.now()-b.current;m(w=>({...w,timeMetrics:{...w.timeMetrics,totalHoverDuration:w.timeMetrics.totalHoverDuration+_}})),b.current=null,A("ad_hover_end",{hoverDuration:_})}};return x.addEventListener("mouseenter",p),x.addEventListener("mouseleave",v),()=>{x.removeEventListener("mouseenter",p),x.removeEventListener("mouseleave",v)}},[s.enabled,o,A]),f.useEffect(()=>{if(!s.enabled||!o.current)return;const x=o.current,p=()=>{y.current=Date.now(),A("ad_focus")},v=()=>{if(y.current){const _=Date.now()-y.current;m(w=>({...w,timeMetrics:{...w.timeMetrics,totalFocusDuration:w.timeMetrics.totalFocusDuration+_}})),y.current=null,A("ad_blur",{focusDuration:_})}};return x.addEventListener("focus",p),x.addEventListener("blur",v),()=>{x.removeEventListener("focus",p),x.removeEventListener("blur",v)}},[s.enabled,o,A]),f.useEffect(()=>{if(!s.enabled||!o.current)return;const x=o.current,p=()=>{m(v=>({...v,engagementMetrics:{...v.engagementMetrics,wasClicked:!0}})),A("ad_click")};return x.addEventListener("click",p),()=>{x.removeEventListener("click",p)}},[s.enabled,o,A]),f.useEffect(()=>()=>{const x=Date.now(),p=new Date(c.timeMetrics.loadedAt).getTime(),v=x-p;m(_=>({..._,timeMetrics:{..._.timeMetrics,sessionDuration:v}})),A("ad_unloaded",{sessionDuration:v}),E()},[]),c}const I=({adId:t,productId:e,offerId:r,agentId:a,children:i,config:o,className:d,style:s,onViewabilityChange:l,onVisible:c,onViewable:m,onClick:u})=>{const h=f.useRef(null),g=te({adId:t,productId:e,offerId:r,agentId:a,elementRef:h,config:o}),b=f.useRef(g.isViewable);f.useEffect(()=>{g.isViewable!==b.current&&(b.current=g.isViewable,l&&l(g.isViewable),g.isViewable&&m&&m())},[g.isViewable,l,m]);const y=f.useRef(g.isVisible);f.useEffect(()=>{g.isVisible!==y.current&&(y.current=g.isVisible,g.isVisible&&c&&c())},[g.isVisible,c]);const k=()=>{u&&u()};return n.jsx("div",{ref:h,className:d,style:s,onClick:k,"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})};I.displayName="AdMeshViewabilityTracker";const Ee=t=>{try{return new URL(t),!0}catch{return!1}},Q=(t,e)=>{const r=new Map,a=new Map;e.forEach(c=>{c.admesh_link&&r.set(c.admesh_link,c),c.click_url&&a.set(c.click_url,c)}),console.log("[AdMesh Summary] Processing recommendations:",{totalRecommendations:e.length,recommendationFields:e.map(c=>({ad_id:c.ad_id,click_url:c.click_url,admesh_link:c.admesh_link,title:c.title||c.recommendation_title}))}),r.size>0||a.size>0?console.log("[AdMesh Summary] Available recommendation links:",{admesh_links:Array.from(r.keys()),click_urls:Array.from(a.keys())}):console.warn("[AdMesh Summary] No click_url or admesh_link found in recommendations!");const i=/\[([^\]]+)\]\(([^)]+)\)/g,o=[];let d=0,s,l=0;for(;(s=i.exec(t))!==null;){const[c,m,u]=s;console.log("[AdMesh Summary] Processing markdown link:",{linkText:m,url:u,urlLength:u.length});let h=r.get(u)||a.get(u);if(console.log("[AdMesh Summary] URL match result:",{found:!!h,matchedBy:h?"exact_match":"none"}),h||(h=e.find(g=>g.ad_id&&u.includes(g.ad_id)),h&&console.log("[AdMesh Summary] Found by ad_id match")),s.index>d&&o.push(t.slice(d,s.index)),h){l++;const g=u||h.click_url||h.admesh_link;o.push(n.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:h.ad_id,productId:h.product_id,title:h.title||h.recommendation_title,brand:h.brand,pricing:h.pricing,clickUrl:h.click_url,admeshLink:h.admesh_link,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:h.ad_id,productId:h.product_id,clickUrl:h.click_url,admeshLink:h.admesh_link,source:"summary"}).catch(b=>{console.error("[AdMesh] Failed to track summary link click:",b)})},children:m},`summary-link-${l}`))}else console.warn(`[AdMesh Summary] No recommendation found for link: [${m}](${u}), creating regular link`,{availableLinks:Array.from(r.keys()),totalRecommendations:e.length,urlToMatch:u}),Ee(u)?(l++,o.push(n.jsx("a",{href:u,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:m,url:u,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({url:u,linkText:m,source:"summary_unmatched"}).catch(g=>{console.error("[AdMesh] Failed to track unmatched link click:",g)})},children:m},`summary-link-${l}`))):(console.warn(`[AdMesh Summary] Invalid URL in markdown link: [${m}](${u})`),o.push(m));d=s.index+c.length}return d<t.length&&o.push(t.slice(d)),o},q=({summaryText:t,recommendations:e,theme:r,className:a="",style:i={}})=>{var s,l,c;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 m=Q(t,[]);return n.jsx("div",{className:`admesh-summary-unit ${a}`,style:i,children:n.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed",children:m.map((u,h)=>n.jsx(f.Fragment,{children:u},h))})})}const o=Q(t,e),d=((l=(s=e[0])==null?void 0:s.meta)==null?void 0:l.ad_id)||((c=e[0])==null?void 0:c.ad_id)||"";return n.jsx(I,{adId:d,className:`admesh-summary-unit ${a}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...i},children:n.jsxs("div",{children:[n.jsx("div",{className:"summary-content",children:n.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed text-base",children:o.map((m,u)=>n.jsx(f.Fragment,{children:m},u))})}),n.jsx("div",{className:"mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:n.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 O={exports:{}};/*!
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 C=(t,e,r)=>fe(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),be=require("react-dom/client"),f=require("react");function xe(t,e,r){const d=t*e>242500;return{...{visibilityThreshold:d?.3:.5,minimumDuration:1e3,isLargeAd:d},...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,a=window.innerWidth||document.documentElement.clientWidth,d=e.height,o=e.width;if(d===0||o===0)return 0;const n=Math.max(0,e.top),s=Math.min(r,e.bottom),l=Math.max(0,e.left),c=Math.min(a,e.right),m=Math.max(0,s-n),u=Math.max(0,c-l),h=m*u,g=d*o;return g>0?h/g:0}function G(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,a=e-t;return a<=0?100:Math.min(100,r/a*100)}function ve(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,a=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+a}}function ke(t){const e=t.getBoundingClientRect(),r=ve(t),a=window.innerWidth||document.documentElement.clientWidth,d=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(a),viewportWidth:a,viewportHeight:d,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 Ae(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function V(t=new Date){return t.toISOString()}function Se(t){return t.length===0?0:t.reduce((r,a)=>r+a,0)/t.length}function X(t,e){let r;return function(...d){r||(t(...d),r=!0,setTimeout(()=>r=!1,e))}}async function Ce(t,e,r=3,a=1e3){if(!e||e.trim()==="")return!0;let d=null;for(let o=0;o<r;o++){try{const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0});if(n.ok)return!0;const s=await n.text().catch(()=>"");d=new Error(`HTTP ${n.status}: ${n.statusText} - ${s}`)}catch(n){d=n}o<r-1&&await new Promise(n=>setTimeout(n,a*Math.pow(2,o)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",d),!1}async function Te(t,e,r,a=3,d=1e3){if(t.length===0||!r||r.trim()==="")return!0;const o={batchId:Me(),sessionId:e,createdAt:V(),events:t,eventCount:t.length};let n=null;for(let s=0;s<a;s++){try{const l=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});if(l.ok)return!0;const c=await l.text().catch(()=>"");n=new Error(`HTTP ${l.status}: ${l.statusText} - ${c}`)}catch(l){n=l}s<a-1&&await new Promise(l=>setTimeout(l,d*Math.pow(2,s)))}return console.error("[AdMesh Viewability] Failed to send analytics batch:",n),!1}const Le={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 je=Le;function te({adId:t,productId:e,offerId:r,agentId:a,recommendationId:d,elementRef:o,config:n}){const s={...je,...n},l=f.useRef(_e()),[c,m]=f.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:V(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:s.enabled}),u=f.useRef(null),h=f.useRef(null),g=f.useRef(null),b=f.useRef(null),y=f.useRef(null),v=f.useRef([]),M=f.useRef([]),S=f.useRef(null),L=f.useCallback((x,p)=>{s.debug&&console.log(`[AdMesh Viewability] ${x}`,p)},[s.debug]),A=f.useCallback(async(x,p)=>{if(!s.enabled||!o.current||!u.current)return;if(!["ad_viewable","ad_click"].includes(x)){L(`Skipping non-critical event: ${x} (only ad_viewable and ad_click are sent)`);return}const _=ke(o.current),w={eventType:x,timestamp:V(),sessionId:l.current,adId:t,productId:e,offerId:r,agentId:a,recommendationId:d,timeMetrics:c.timeMetrics,engagementMetrics:c.engagementMetrics,contextMetrics:_,mrcStandards:u.current,isViewable:c.isViewable,metadata:p};L(`Sending critical event: ${x}`,w),s.onEvent&&s.onEvent(w),s.enableBatching?(M.current.push(w),M.current.length>=s.batchSize?await E():(S.current&&clearTimeout(S.current),S.current=setTimeout(E,s.batchTimeout))):await Ce(w,s.apiEndpoint,s.maxRetries,s.retryDelay)},[s,t,e,r,a,o,c,L]),E=f.useCallback(async()=>{if(M.current.length===0)return;const x=[...M.current];M.current=[],S.current&&(clearTimeout(S.current),S.current=null),await Te(x,l.current,s.apiEndpoint,s.maxRetries,s.retryDelay)&&s.onBatchSent&&s.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:l.current,createdAt:V(),events:x,eventCount:x.length})},[s,L]),N=f.useCallback(X(()=>{if(!o.current)return;const x=we(o.current),p=Date.now(),k=new Date(c.timeMetrics.loadedAt).getTime();m(_=>{const w={..._};x>0&&v.current.push(x);const j=_.isVisible,T=x>0;if(T&&!j)h.current=p,w.engagementMetrics.viewportEnterCount++,w.timeMetrics.timeToFirstVisible||(w.timeMetrics.timeToFirstVisible=p-k,w.engagementMetrics.scrollDepthAtFirstVisible=G(),A("ad_visible"));else if(!T&&j){if(h.current){const F=p-h.current;w.timeMetrics.totalVisibleDuration+=F,h.current=null}w.engagementMetrics.viewportExitCount++,A("ad_hidden")}else if(T&&j&&h.current){const F=p-h.current;w.timeMetrics.totalVisibleDuration+=F,h.current=p}if(w.isVisible=T,w.visibilityPercentage=x,x>w.engagementMetrics.maxVisibilityPercentage&&(w.engagementMetrics.maxVisibilityPercentage=x),v.current.length>0&&(w.engagementMetrics.averageVisibilityPercentage=Se(v.current)),u.current){const F=_.isViewable,D=Ae(x,w.timeMetrics.totalVisibleDuration,u.current);if(D&&!F)w.isViewable=!0,w.timeMetrics.timeToViewable=p-k,g.current=p,A("ad_viewable");else if(D&&F&&g.current){const P=p-g.current;w.timeMetrics.totalViewableDuration+=P,g.current=p}}return w.engagementMetrics.currentScrollDepth=G(),w})},100),[o,c.timeMetrics.loadedAt,A]);return f.useEffect(()=>{if(!o.current)return;const x=o.current.getBoundingClientRect();u.current=xe(x.width,x.height,s.mrcStandards),L("Initialized MRC standards",u.current),A("ad_loaded")},[o,s.mrcStandards,L,A]),f.useEffect(()=>{if(!s.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()}},[s.enabled,o,N]),f.useEffect(()=>{if(!s.enabled)return;const x=X(()=>{N()},100);return window.addEventListener("scroll",x,{passive:!0}),()=>window.removeEventListener("scroll",x)},[s.enabled,N]),f.useEffect(()=>{if(!s.enabled||!o.current)return;const x=o.current,p=()=>{b.current=Date.now(),m(_=>({..._,engagementMetrics:{..._.engagementMetrics,hoverCount:_.engagementMetrics.hoverCount+1}})),A("ad_hover_start")},k=()=>{if(b.current){const _=Date.now()-b.current;m(w=>({...w,timeMetrics:{...w.timeMetrics,totalHoverDuration:w.timeMetrics.totalHoverDuration+_}})),b.current=null,A("ad_hover_end",{hoverDuration:_})}};return x.addEventListener("mouseenter",p),x.addEventListener("mouseleave",k),()=>{x.removeEventListener("mouseenter",p),x.removeEventListener("mouseleave",k)}},[s.enabled,o,A]),f.useEffect(()=>{if(!s.enabled||!o.current)return;const x=o.current,p=()=>{y.current=Date.now(),A("ad_focus")},k=()=>{if(y.current){const _=Date.now()-y.current;m(w=>({...w,timeMetrics:{...w.timeMetrics,totalFocusDuration:w.timeMetrics.totalFocusDuration+_}})),y.current=null,A("ad_blur",{focusDuration:_})}};return x.addEventListener("focus",p),x.addEventListener("blur",k),()=>{x.removeEventListener("focus",p),x.removeEventListener("blur",k)}},[s.enabled,o,A]),f.useEffect(()=>{if(!s.enabled||!o.current)return;const x=o.current,p=()=>{m(k=>({...k,engagementMetrics:{...k.engagementMetrics,wasClicked:!0}})),A("ad_click")};return x.addEventListener("click",p),()=>{x.removeEventListener("click",p)}},[s.enabled,o,A]),f.useEffect(()=>()=>{const x=Date.now(),p=new Date(c.timeMetrics.loadedAt).getTime(),k=x-p;m(_=>({..._,timeMetrics:{..._.timeMetrics,sessionDuration:k}})),A("ad_unloaded",{sessionDuration:k}),E()},[]),c}const I=({adId:t,productId:e,offerId:r,agentId:a,children:d,config:o,className:n,style:s,onViewabilityChange:l,onVisible:c,onViewable:m,onClick:u})=>{const h=f.useRef(null),g=te({adId:t,productId:e,offerId:r,agentId:a,elementRef:h,config:o}),b=f.useRef(g.isViewable);f.useEffect(()=>{g.isViewable!==b.current&&(b.current=g.isViewable,l&&l(g.isViewable),g.isViewable&&m&&m())},[g.isViewable,l,m]);const y=f.useRef(g.isVisible);f.useEffect(()=>{g.isVisible!==y.current&&(y.current=g.isVisible,g.isVisible&&c&&c())},[g.isVisible,c]);const v=()=>{u&&u()};return i.jsx("div",{ref:h,className:n,style:s,onClick:v,"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:d})};I.displayName="AdMeshViewabilityTracker";const Ee=t=>{try{return new URL(t),!0}catch{return!1}},J=(t,e)=>{const r=new Map,a=new Map;e.forEach(c=>{c.admesh_link&&r.set(c.admesh_link,c),c.click_url&&a.set(c.click_url,c)}),console.log("[AdMesh Summary] Processing recommendations:",{totalRecommendations:e.length,recommendationFields:e.map(c=>({ad_id:c.ad_id,click_url:c.click_url,admesh_link:c.admesh_link,title:c.title||c.recommendation_title}))}),r.size>0||a.size>0?console.log("[AdMesh Summary] Available recommendation links:",{admesh_links:Array.from(r.keys()),click_urls:Array.from(a.keys())}):console.warn("[AdMesh Summary] No click_url or admesh_link found in recommendations!");const d=/\[([^\]]+)\]\(([^)]+)\)/g,o=[];let n=0,s,l=0;for(;(s=d.exec(t))!==null;){const[c,m,u]=s;console.log("[AdMesh Summary] Processing markdown link:",{linkText:m,url:u,urlLength:u.length});let h=r.get(u)||a.get(u);if(console.log("[AdMesh Summary] URL match result:",{found:!!h,matchedBy:h?"exact_match":"none"}),h||(h=e.find(g=>g.ad_id&&u.includes(g.ad_id)),h&&console.log("[AdMesh Summary] Found by ad_id match")),s.index>n&&o.push(t.slice(n,s.index)),h){l++;const g=u||h.click_url||h.admesh_link;o.push(i.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:h.ad_id,productId:h.product_id,title:h.title||h.recommendation_title,brand:h.brand,pricing:h.pricing,clickUrl:h.click_url,admeshLink:h.admesh_link,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:h.ad_id,productId:h.product_id,clickUrl:h.click_url,admeshLink:h.admesh_link,source:"summary"}).catch(b=>{console.error("[AdMesh] Failed to track summary link click:",b)})},children:m},`summary-link-${l}`))}else console.warn(`[AdMesh Summary] No recommendation found for link: [${m}](${u}), creating regular link`,{availableLinks:Array.from(r.keys()),totalRecommendations:e.length,urlToMatch:u}),Ee(u)?(l++,o.push(i.jsx("a",{href:u,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:m,url:u,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({url:u,linkText:m,source:"summary_unmatched"}).catch(g=>{console.error("[AdMesh] Failed to track unmatched link click:",g)})},children:m},`summary-link-${l}`))):(console.warn(`[AdMesh Summary] Invalid URL in markdown link: [${m}](${u})`),o.push(m));n=s.index+c.length}return n<t.length&&o.push(t.slice(n)),o},q=({summaryText:t,recommendations:e,theme:r,className:a="",style:d={}})=>{var s,l,c;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 m=J(t,[]);return i.jsx("div",{className:`admesh-summary-unit ${a}`,style:d,children:i.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed",children:m.map((u,h)=>i.jsx(f.Fragment,{children:u},h))})})}const o=J(t,e),n=((l=(s=e[0])==null?void 0:s.meta)==null?void 0:l.ad_id)||((c=e[0])==null?void 0:c.ad_id)||"";return i.jsx(I,{adId:n,className:`admesh-summary-unit ${a}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...d},children:i.jsxs("div",{children:[i.jsx("div",{className:"summary-content",children:i.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed text-base",children:o.map((m,u)=>i.jsx(f.Fragment,{children:m},u))})}),i.jsx("div",{className:"mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:i.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 B={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 Fe(){return X||(X=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var o="",d=0;d<arguments.length;d++){var s=arguments[d];s&&(o=i(o,a(s)))}return o}function a(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 s in o)e.call(o,s)&&o[s]&&(d=i(d,s));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})()})(O)),O.exports}var Pe=Fe();const R=Ne(Pe),Re="https://api.useadmesh.com/track";let Ie={enabled:!0,retryAttempts:3,retryDelay:1e3};const re=t=>{const[e,r]=f.useState(!1),[a,i]=f.useState(null),o=f.useMemo(()=>({...Ie,...t}),[t]),d=f.useCallback(async(m,u)=>{if(!o.enabled)return;if(!u.adId||!u.admeshLink){i("Missing required tracking data: adId and admeshLink are required");return}r(!0),i(null);const h={event_type:m,ad_id:u.adId,admesh_link:u.admeshLink,product_id:u.productId,user_id:u.userId,session_id:u.sessionId,revenue:u.revenue,conversion_type:u.conversionType,metadata:u.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};let g=null;for(let y=1;y<=(o.retryAttempts||3);y++)try{const k=await fetch(`${Re}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!k.ok)throw new Error(`HTTP ${k.status}: ${k.statusText}`);await k.json(),r(!1);return}catch(k){g=k,y<(o.retryAttempts||3)&&await new Promise(M=>setTimeout(M,(o.retryDelay||1e3)*y))}const b=`Failed to track ${m} event after ${o.retryAttempts} attempts: ${g==null?void 0:g.message}`;i(b),r(!1)},[o]),s=f.useCallback(async m=>d("click",m),[d]),l=f.useCallback(async m=>d("view",m),[d]),c=f.useCallback(async m=>d("conversion",m),[d]);return{trackClick:s,trackView:l,trackConversion:c,isTracking:e,error:a}},W=({adId:t,admeshLink:e,productId:r,children:a,trackingData:i,className:o,style:d})=>{const{trackClick:s,trackView:l}=re(),c=f.useRef(null),m=f.useRef(!1);f.useEffect(()=>{if(!c.current||m.current)return;const h=new IntersectionObserver(g=>{g.forEach(b=>{b.isIntersecting&&!m.current&&(m.current=!0,l({adId:t,admeshLink:e,productId:r,...i}).catch(console.error))})},{threshold:.5,rootMargin:"0px"});return h.observe(c.current),()=>{h.disconnect()}},[t,e,r,i,l]);const u=f.useCallback(h=>{s({adId:t,admeshLink:e,productId:r,...i}).catch(y=>{console.error("[AdMesh] Failed to track click:",y)}),h.target.closest("a")||window.open(e,"_blank","noopener,noreferrer")},[t,e,r,i,s]);return n.jsx("div",{ref:c,className:o,onClick:u,style:{cursor:"pointer",...d},children:a})};W.displayName="AdMeshLinkTracker";const U="admesh-ui-sdk-styles",H="admesh-ui-sdk-reset",De=`
5
+ */var Q;function Fe(){return Q||(Q=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var o="",n=0;n<arguments.length;n++){var s=arguments[n];s&&(o=d(o,a(s)))}return o}function a(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 n="";for(var s in o)e.call(o,s)&&o[s]&&(n=d(n,s));return n}function d(o,n){return n?o?o+" "+n:o+n:o}t.exports?(r.default=r,t.exports=r):window.classNames=r})()})(B)),B.exports}var Pe=Fe();const R=Ne(Pe),Re="https://api.useadmesh.com/track";let Ie={enabled:!0,retryAttempts:3,retryDelay:1e3};const re=t=>{const[e,r]=f.useState(!1),[a,d]=f.useState(null),o=f.useMemo(()=>({...Ie,...t}),[t]),n=f.useCallback(async(m,u)=>{if(!o.enabled)return;if(!u.adId||!u.admeshLink){d("Missing required tracking data: adId and admeshLink are required");return}r(!0),d(null);const h={event_type:m,ad_id:u.adId,admesh_link:u.admeshLink,product_id:u.productId,user_id:u.userId,session_id:u.sessionId,revenue:u.revenue,conversion_type:u.conversionType,metadata:u.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};let g=null;for(let y=1;y<=(o.retryAttempts||3);y++)try{const v=await fetch(`${Re}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!v.ok)throw new Error(`HTTP ${v.status}: ${v.statusText}`);await v.json(),r(!1);return}catch(v){g=v,y<(o.retryAttempts||3)&&await new Promise(M=>setTimeout(M,(o.retryDelay||1e3)*y))}const b=`Failed to track ${m} event after ${o.retryAttempts} attempts: ${g==null?void 0:g.message}`;d(b),r(!1)},[o]),s=f.useCallback(async m=>n("click",m),[n]),l=f.useCallback(async m=>n("view",m),[n]),c=f.useCallback(async m=>n("conversion",m),[n]);return{trackClick:s,trackView:l,trackConversion:c,isTracking:e,error:a}},z=({adId:t,admeshLink:e,productId:r,children:a,trackingData:d,className:o,style:n})=>{const{trackClick:s,trackView:l}=re(),c=f.useRef(null),m=f.useRef(!1);f.useEffect(()=>{if(!c.current||m.current)return;const h=new IntersectionObserver(g=>{g.forEach(b=>{b.isIntersecting&&!m.current&&(m.current=!0,l({adId:t,admeshLink:e,productId:r,...d}).catch(console.error))})},{threshold:.5,rootMargin:"0px"});return h.observe(c.current),()=>{h.disconnect()}},[t,e,r,d,l]);const u=f.useCallback(h=>{s({adId:t,admeshLink:e,productId:r,...d}).catch(y=>{console.error("[AdMesh] Failed to track click:",y)}),h.target.closest("a")||window.open(e,"_blank","noopener,noreferrer")},[t,e,r,d,s]);return i.jsx("div",{ref:c,className:o,onClick:u,style:{cursor:"pointer",...n},children:a})};z.displayName="AdMeshLinkTracker";const U="admesh-ui-sdk-styles",H="admesh-ui-sdk-reset",De=`
6
6
  /* AdMesh UI SDK - CSS Reset & Normalization */
7
7
  .admesh-component,
8
8
  .admesh-component * {
@@ -91,7 +91,7 @@
91
91
  .admesh-component[data-admesh-theme="light"] {
92
92
  color-scheme: light;
93
93
  }
94
- `,ze=`
94
+ `,We=`
95
95
  /* AdMesh Core Component Styles */
96
96
 
97
97
  .admesh-component {
@@ -302,7 +302,7 @@
302
302
  font-size: 0.875rem;
303
303
  }
304
304
  }
305
- `,We=()=>{if(!(typeof document>"u")&&!(document.getElementById(H)&&document.getElementById(U))){if(!document.getElementById(H)){const t=document.createElement("style");t.id=H,t.textContent=De,document.head.appendChild(t)}if(!document.getElementById(U)){const t=document.createElement("style");t.id=U,t.textContent=ze,document.head.appendChild(t)}}},$e=`
305
+ `,ze=()=>{if(!(typeof document>"u")&&!(document.getElementById(H)&&document.getElementById(U))){if(!document.getElementById(H)){const t=document.createElement("style");t.id=H,t.textContent=De,document.head.appendChild(t)}if(!document.getElementById(U)){const t=document.createElement("style");t.id=U,t.textContent=We,document.head.appendChild(t)}}},$e=`
306
306
  /* AdMesh UI SDK - Complete Self-Contained Styles */
307
307
 
308
308
  /* CSS Reset for AdMesh components */
@@ -970,7 +970,7 @@
970
970
  .admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
971
971
  .admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
972
972
  }
973
- `;let Z=!1;const oe=()=>{f.useEffect(()=>{if(!Z){try{We();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,a=e.customLabels||{};return r>=.8?a.partnerRecommendation||"Smart Pick":r>=.6?a.partnerMatch||"Partner Recommendation":r>=.3?a.promotedOption||"Promoted Match":a.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:a="default",className:i,style:o})=>{var h,g,b,y,k,M,S,T,A,E,N,x,p,v,_,w,L,j,F,D;oe();const s=a==="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.meta.description||t.reason,ctaText:t.recommendation_title||t.title},l=R("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),c=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(h=e.shadows)==null?void 0:h.small,"--admesh-shadow-md":(g=e.shadows)==null?void 0:g.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":(k=e.spacing)==null?void 0:k.medium,"--admesh-spacing-lg":(M=e.spacing)==null?void 0:M.large,"--admesh-font-size-sm":(S=e.fontSize)==null?void 0:S.small,"--admesh-font-size-base":(T=e.fontSize)==null?void 0:T.base,"--admesh-font-size-lg":(A=e.fontSize)==null?void 0:A.large,"--admesh-font-size-title":(E=e.fontSize)==null?void 0:E.title,fontFamily:e.fontFamily,width:((x=(N=e.components)==null?void 0:N.productCard)==null?void 0:x.width)||"100%"}:{width:"100%"};if(a==="simple"){const P=((p=t.meta)==null?void 0:p.ad_id)||t.ad_id||"",B=t.product_id||"";return n.jsx(I,{adId:P,productId:B,className:R("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',...(v=e==null?void 0:e.components)==null?void 0:v.productCard,...o},children:n.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[n.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)}),n.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[s.description," "]}),n.jsx(W,{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:n.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:s.ctaText})})]})})}const m=((w=t.meta)==null?void 0:w.ad_id)||t.ad_id||"",u=t.product_id||"";return n.jsx(I,{adId:m,productId:u,className:l,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(L=e==null?void 0:e.components)==null?void 0:L.productCard,...o},children:n.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(j=e==null?void 0:e.components)==null?void 0:j.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:n.jsxs("div",{className:"h-full flex flex-col",style:c,children:[n.jsx("div",{className:"mb-1.5",children:n.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)})}),n.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&n.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"}}),n.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:s.title})]}),n.jsx("div",{className:"flex-shrink-0",children:n.jsx(W,{adId:((F=t.meta)==null?void 0:F.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((D=t.meta)==null?void 0:D.intent_match_score)||t.intent_match_score,component:"product_card_cta"},children:n.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",n.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n.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"})})]})})})]}),n.jsx("div",{className:"mb-3",children:n.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:s.description})}),r&&t.features&&t.features.length>0&&n.jsxs("div",{className:"mb-2",children:[n.jsx("div",{className:"text-xs font-medium mb-1.5",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:"Key Features"}),n.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[t.features.slice(0,4).map((P,B)=>n.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:[n.jsx("svg",{className:"h-3 w-3 mr-0.5 inline",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n.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]},B)),t.features.length>4&&n.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"]})]})]}),n.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:n.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[n.jsx("span",{children:"Sponsored"}),n.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};z.displayName="AdMeshProductCard";const se=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:a="",cardClassName:i="",onProductClick:o,showPricing:d=!0,showRatings:s=!0,showBrand:l=!0,showSource:c=!1,showShipping:m=!0,maxCards:u=10,cardWidth:h="md",theme:g="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 k=t.slice(0,u),M=()=>{switch(h){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"}},S=()=>{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"}},A=()=>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",E=p=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(p),N=p=>{const v=[],_=Math.floor(p),w=p%1!==0;for(let j=0;j<_;j++)v.push(n.jsx("span",{className:"text-yellow-400",children:"โ˜…"},j));w&&v.push(n.jsx("span",{className:"text-yellow-400",children:"โ˜†"},"half"));const L=5-Math.ceil(p);for(let j=0;j<L;j++)v.push(n.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"โ˜†"},`empty-${j}`));return v},x=p=>{if(o)o(p);else{const v=p.admesh_link||p.url;v&&window.open(v,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:n.jsxs("div",{className:R("w-full",a),children:[r&&n.jsxs("div",{className:"mb-4",children:[n.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),n.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),n.jsxs("div",{className:"relative",children:[k.length===0?n.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):n.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:k.map(p=>{var L;const v=p.product_id||p.id||p.ad_id,_=p.ad_id||p.product_id||"",w=p.product_id||"";return n.jsx(I,{adId:_,productId:w,className:R(M(),S(),T(),A(),"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:n.jsxs("div",{children:[n.jsxs("div",{className:"relative aspect-square w-full overflow-hidden",children:[p.image_url?n.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"}):n.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:n.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n.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&&n.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),"%"]}),c&&p.source&&n.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()})]}),n.jsxs("div",{className:"p-3",children:[l&&p.brand&&n.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 uppercase tracking-wide",children:p.brand}),n.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:p.title}),s&&p.rating&&n.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[n.jsx("div",{className:"flex text-sm",children:N(p.rating)}),n.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",p.review_count||0,")"]})]}),d&&p.price&&n.jsx("div",{className:"mb-2",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-lg font-bold text-gray-900 dark:text-white",children:E(p.price)}),p.original_price&&p.original_price>p.price&&n.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400 line-through",children:E(p.original_price)})]})}),m&&((L=p.shipping_info)==null?void 0:L.free_shipping_over_35)&&n.jsx("div",{className:"text-xs text-green-600 dark:text-green-400 font-medium",children:"Free shipping over $35"}),p.availability&&p.availability!=="unknown"&&n.jsx("div",{className:R("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"})]})]})},v)})}),k.length>0&&n.jsxs(n.Fragment,{children:[n.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:n.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),n.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:n.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),n.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),n.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),n.jsx("style",{dangerouslySetInnerHTML:{__html:`
973
+ `;let Z=!1;const oe=()=>{f.useEffect(()=>{if(!Z){try{ze();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,a=e.customLabels||{};return r>=.8?a.partnerRecommendation||"Smart Pick":r>=.6?a.partnerMatch||"Partner Recommendation":r>=.3?a.promotedOption||"Promoted Match":a.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."},W=({recommendation:t,theme:e,showFeatures:r=!1,variation:a="default",className:d,style:o})=>{var h,g,b,y,v,M,S,L,A,E,N,x,p,k,_,w,j,T,F,D;oe();const s=a==="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.meta.description||t.reason,ctaText:t.recommendation_title||t.title},l=R("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",d),c=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(h=e.shadows)==null?void 0:h.small,"--admesh-shadow-md":(g=e.shadows)==null?void 0:g.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":(M=e.spacing)==null?void 0:M.large,"--admesh-font-size-sm":(S=e.fontSize)==null?void 0:S.small,"--admesh-font-size-base":(L=e.fontSize)==null?void 0:L.base,"--admesh-font-size-lg":(A=e.fontSize)==null?void 0:A.large,"--admesh-font-size-title":(E=e.fontSize)==null?void 0:E.title,fontFamily:e.fontFamily,width:((x=(N=e.components)==null?void 0:N.productCard)==null?void 0:x.width)||"100%"}:{width:"100%"};if(a==="simple"){const P=((p=t.meta)==null?void 0:p.ad_id)||t.ad_id||"",O=t.product_id||"";return i.jsx(I,{adId:P,productId:O,className:R("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",d),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:i.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:ee(t,$(t)),children:$(t)}),i.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[s.description," "]}),i.jsx(z,{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:i.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:s.ctaText})})]})})}const m=((w=t.meta)==null?void 0:w.ad_id)||t.ad_id||"",u=t.product_id||"";return i.jsx(I,{adId:m,productId:u,className:l,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(j=e==null?void 0:e.components)==null?void 0:j.productCard,...o},children:i.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(T=e==null?void 0:e.components)==null?void 0:T.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",style:c,children:[i.jsx("div",{className:"mb-1.5",children:i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:ee(t,$(t)),children:$(t)})}),i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&i.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"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:s.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(z,{adId:((F=t.meta)==null?void 0:F.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((D=t.meta)==null?void 0:D.intent_match_score)||t.intent_match_score,component:"product_card_cta"},children:i.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:["Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),i.jsx("div",{className:"mb-3",children:i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:s.description})}),r&&t.features&&t.features.length>0&&i.jsxs("div",{className:"mb-2",children:[i.jsx("div",{className:"text-xs font-medium mb-1.5",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:"Key Features"}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[t.features.slice(0,4).map((P,O)=>i.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:[i.jsx("svg",{className:"h-3 w-3 mr-0.5 inline",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.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&&i.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"]})]})]}),i.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};W.displayName="AdMeshProductCard";const se=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:a="",cardClassName:d="",onProductClick:o,showPricing:n=!0,showRatings:s=!0,showBrand:l=!0,showSource:c=!1,showShipping:m=!0,maxCards:u=10,cardWidth:h="md",theme:g="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,u),M=()=>{switch(h){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"}},S=()=>{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"}},L=()=>{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"}},A=()=>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",E=p=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(p),N=p=>{const k=[],_=Math.floor(p),w=p%1!==0;for(let T=0;T<_;T++)k.push(i.jsx("span",{className:"text-yellow-400",children:"โ˜…"},T));w&&k.push(i.jsx("span",{className:"text-yellow-400",children:"โ˜†"},"half"));const j=5-Math.ceil(p);for(let T=0;T<j;T++)k.push(i.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"โ˜†"},`empty-${T}`));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:i.jsxs("div",{className:R("w-full",a),children:[r&&i.jsxs("div",{className:"mb-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),i.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),i.jsxs("div",{className:"relative",children:[v.length===0?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):i.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:v.map(p=>{var j;const k=p.product_id||p.id||p.ad_id,_=p.ad_id||p.product_id||"",w=p.product_id||"";return i.jsx(I,{adId:_,productId:w,className:R(M(),S(),L(),A(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",d),onClick:()=>x(p),children:i.jsxs("div",{children:[i.jsxs("div",{className:"relative aspect-square w-full overflow-hidden",children:[p.image_url?i.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"}):i.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:i.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),n&&p.discount_percentage&&p.discount_percentage>0&&i.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),"%"]}),c&&p.source&&i.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()})]}),i.jsxs("div",{className:"p-3",children:[l&&p.brand&&i.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 uppercase tracking-wide",children:p.brand}),i.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:p.title}),s&&p.rating&&i.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[i.jsx("div",{className:"flex text-sm",children:N(p.rating)}),i.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",p.review_count||0,")"]})]}),n&&p.price&&i.jsx("div",{className:"mb-2",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-lg font-bold text-gray-900 dark:text-white",children:E(p.price)}),p.original_price&&p.original_price>p.price&&i.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400 line-through",children:E(p.original_price)})]})}),m&&((j=p.shipping_info)==null?void 0:j.free_shipping_over_35)&&i.jsx("div",{className:"text-xs text-green-600 dark:text-green-400 font-medium",children:"Free shipping over $35"}),p.availability&&p.availability!=="unknown"&&i.jsx("div",{className:R("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)})}),v.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),i.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),i.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),i.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),i.jsx("style",{dangerouslySetInnerHTML:{__html:`
974
974
  .scrollbar-hide {
975
975
  -ms-overflow-style: none;
976
976
  scrollbar-width: none;
@@ -984,5 +984,5 @@
984
984
  -webkit-box-orient: vertical;
985
985
  overflow: hidden;
986
986
  }
987
- `}})]})},Ve=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(s=>s&&s.admesh_link&&(s.title||s.recommendation_title)))||[],a=((o=t.recommendations)==null?void 0:o.length)===0;return r.length===0&&!a&&e.push("No valid recommendations found (missing admesh_link or title)"),{isValid:r.length>0,isEmpty:a,validCount:r.length,totalCount:((d=t.recommendations)==null?void 0:d.length)||0,warnings:e}},ne=({response:t,theme:e,className:r="",style:a={},onLinkClick:i})=>{const o=Ve(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:s,recommendations:l=[],requires_summary:c=!0}=t;console.log(`[AdMesh Summary Layout] Rendering ${d} layout with ${o.validCount}/${o.totalCount} valid recommendations`);const m=()=>{switch(d){case"citation":return s&&c?n.jsx(q,{summaryText:s,recommendations:l,theme:e,onLinkClick:i}):n.jsxs("div",{className:"fallback-citation",children:[n.jsx("p",{className:"text-gray-700 dark:text-gray-300 mb-3",children:"Based on your query, I'd recommend checking out these options:"}),n.jsx(z,{recommendation:l[0],theme:e})]});case"product_cards":case"product":return n.jsx("div",{className:"product-cards-layout",children:l.slice(0,3).map((u,h)=>n.jsx(z,{recommendation:u,theme:e,className:"mb-4"},u.ad_id||`rec-${h}`))});case"ecommerce":return n.jsx(se,{recommendations:l.slice(0,3),theme:(e==null?void 0:e.mode)||"light"});default:return console.warn(`[AdMesh Summary Layout] Unknown layout type: ${d}`),s?n.jsx(q,{summaryText:s,recommendations:l,theme:e,onLinkClick:i}):n.jsx(z,{recommendation:l[0],theme:e})}};return n.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',...a},children:m()})},ae=({response:t,theme:e,className:r,style:a,onLinkClick:i})=>t?t.recommendations&&Array.isArray(t.recommendations)&&t.recommendations.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):n.jsx(ne,{response:t,theme:e,className:r,style:a,onLinkClick:i}):(console.error("[AdMeshLayout] response prop is required"),null);class ie{constructor(e){C(this,"firedExposures",new Set);C(this,"debug",!1);C(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,r,a){const i=`${a}_${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,a,i){const o=`${a}_${r}`;if(this.firedExposures.has(o)){this.debug&&console.log("[Tracker] MRC exposure already fired for:",r);return}return new Promise(d=>{let s=null,l=null;const c=new IntersectionObserver(h=>{h.forEach(g=>{const b=g.intersectionRatio*100;b>=this.mrcThreshold.visibilityPercentage?s===null&&(s=Date.now(),this.debug&&console.log("[Tracker] Ad reached MRC visibility threshold:",{adId:r,visibilityPercentage:b.toFixed(2)}),l=setTimeout(()=>{this.fireExposure(e,r,a),c.disconnect(),d()},this.mrcThreshold.minimumDurationMs)):s!==null&&(l&&(clearTimeout(l),l=null),s=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"});c.observe(i);const u=setTimeout(()=>{c.disconnect(),l&&clearTimeout(l),d()},3e4);i.__admeshTrackerCleanup=()=>{c.disconnect(),l&&clearTimeout(l),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class de{constructor(){C(this,"roots",new Map)}async render(e){var r,a,i,o;try{const d=document.getElementById(e.containerId);if(!d)throw new Error(`Container with ID "${e.containerId}" not found`);const s=this.roots.get(e.containerId);s&&s.unmount();const l=be.createRoot(d),c=((r=e.response.response)==null?void 0:r.citation_summary)||((a=e.response.response)==null?void 0:a.summary);l.render(n.jsx(ae,{response:{layout_type:(i=e.response.response)==null?void 0:i.layout_type,citation_summary:c,recommendations:((o=e.response.response)==null?void 0:o.recommendations)||[],requires_summary:!!c},theme:e.theme})),this.roots.set(e.containerId,l)}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={}){C(this,"autoAddLabels");C(this,"fireExposurePixels");C(this,"labelStyle");C(this,"processedLinks",new Set);C(this,"mutationObserver",null);var r,a,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:((a=e.labelStyle)==null?void 0:a.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 a=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return a.length>0?Array.from(a):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,r,a){if(!e)return[];const i=[];if(r.length>0){const o=this.getLinksToProcess(e),d=new Map(r.filter(s=>s.click_url).map(s=>[s.click_url,s]));o.forEach(s=>{var u;const l=s.getAttribute("href")||"",c=`${l}`;if(this.processedLinks.has(c))return;const m=d.get(l);if(m){this.processedLinks.add(c);const h={element:s,href:l,text:s.textContent||"",hasAdLabel:this.hasAdLabel(s),matchedRecommendation:{ad_id:m.ad_id||((u=m.meta)==null?void 0:u.ad_id)||"",click_url:m.click_url,exposure_url:m.exposure_url}};this.autoAddLabels&&!h.hasAdLabel&&(this.addAdLabel(s),h.hasAdLabel=!0),this.fireExposurePixels&&m.exposure_url&&a&&h.matchedRecommendation&&a(m.exposure_url,h.matchedRecommendation.ad_id),i.push(h)}})}else{const o=Array.from(e.querySelectorAll("a"));console.log("[WeaveResponseProcessor] ๐Ÿ” Scanning for AdMesh links:",{totalLinksInContainer:o.length,containerHTML:e.innerHTML.substring(0,200),allLinks:o.map(d=>{var s;return{href:d.getAttribute("href"),text:(s=d.textContent)==null?void 0:s.substring(0,50)}})}),o.forEach(d=>{const s=d.getAttribute("href")||"",l=`${s}`;if(this.processedLinks.has(l))return;if(this.isAdMeshLink(s)){console.log("[WeaveResponseProcessor] โœ… Found AdMesh link:",{href:s,text:d.textContent}),this.processedLinks.add(l);const m={element:d,href:s,text:d.textContent||"",hasAdLabel:this.hasAdLabel(d),matchedRecommendation:void 0};d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer"),console.log('[WeaveResponseProcessor] ๐Ÿ”— Set target="_blank" and rel="noopener noreferrer"'),this.autoAddLabels&&!m.hasAdLabel&&(this.addAdLabel(d),m.hasAdLabel=!0),this.fireExposurePixels&&a&&a(s,this.extractAdIdFromUrl(s)),i.push(m)}}),console.log("[WeaveResponseProcessor] ๐Ÿ“Š Scan complete:",{adMeshLinksFound:i.length,totalLinksScanned:o.length})}return i}hasAdLabel(e){var a;let r=e.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const i=r.textContent||"";if(i.trim()===""){r=r.nextSibling;continue}if(i.includes("[Ad]"))return!0;break}if(r&&r.nodeType===Node.ELEMENT_NODE){const i=r;if((i.tagName==="SUB"||i.tagName==="SPAN")&&((a=i.textContent)!=null&&a.includes("[Ad]")))return!0}return!1}addAdLabel(e){var a;if(console.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to link:",{href:e.getAttribute("href"),text:e.textContent}),this.hasAdLabel(e)){console.log("[WeaveResponseProcessor] โ„น๏ธ [Ad] label already exists, skipping");return}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,r.style.cursor="default",r.style.borderBottom=`1px dotted ${this.labelStyle.color}`,r.style.whiteSpace="nowrap",r.title="Why this ad? This is a sponsored recommendation based on your search query.",r.addEventListener("mouseenter",()=>{r.style.opacity="0.7"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1"}),(a=e.parentNode)==null||a.insertBefore(r,e.nextSibling),console.log("[WeaveResponseProcessor] โœ… [Ad] label created and inserted to the right of link")}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(i=>e.includes(i)))return console.log("[WeaveResponseProcessor] ๐ŸŽฏ Matched known AdMesh domain:",{href:e}),!0;try{if(new URL(e).pathname.startsWith("/click/"))return console.log("[WeaveResponseProcessor] ๐ŸŽฏ Matched /click/ pattern:",{href:e}),!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return console.log("[WeaveResponseProcessor] ๐ŸŽฏ Matched /click/ regex pattern:",{href:e}),!0}return!1}extractAdIdFromUrl(e){try{const r=e.match(/\/click\/([^/?]+)/);return r&&r[1]?r[1]:e}catch{return e}}watchForNewLinks(e,r,a){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,r,a)}),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){C(this,"config");C(this,"apiBaseUrl");C(this,"renderer",null);C(this,"tracker",null);C(this,"weaveProcessor",null);C(this,"weaveCache",new Map);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}static createSession(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}static createMessageId(e){const r=Date.now(),a=Math.random().toString(36).substring(2,15);return`msg_${e}_${r}_${a}`}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,a;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 s of i.response.recommendations)if(s.exposure_url){const l=((a=s.meta)==null?void 0:a.ad_id)||s.ad_id||"";d.fireExposure(s.exposure_url,l,e.session_id||"")}}}}catch(i){throw console.error("[AdMeshSDK] Error showing recommendations:",i),i}}async handleWeaveFormat(e,r){var u,h,g,b;const a=e.session_id||"",i=e.message_id||"",o=e.timeoutMs||900,d=e.fallbackFormat||"citation",s=`${a}:${i}`;if(this.weaveCache.set(s,((u=r.response)==null?void 0:u.recommendations)||[]),e.llmOutputContainerId)try{if(await this.scanLLMOutputForAdMeshLinks(e.llmOutputContainerId,((h=r.response)==null?void 0:h.recommendations)||[],a,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 l={...r,response:{...r.response,layout_type:d}},c=this.getRenderer(),m=this.getTracker();if(await c.render({containerId:e.containerId,response:l,theme:e.theme||this.config.theme,tracker:m,sessionId:a}),(g=r.response)!=null&&g.recommendations){for(const y of r.response.recommendations)if(y.exposure_url){const k=((b=y.meta)==null?void 0:b.ad_id)||y.ad_id||"";m.fireExposure(y.exposure_url,k,a)}}}async scanLLMOutputForAdMeshLinks(e,r,a,i){const o=document.getElementById(e);if(!o)return console.warn(`[AdMeshSDK] LLM output container not found: ${e}`),!1;const d=Date.now(),s=100;let l=!1,c=null;try{const m=new Promise(g=>{const b=new MutationObserver(()=>{this.scanAndLabelAds(e,r,a)&&!l&&(l=!0,console.log("[AdMeshSDK] AdMesh links detected via MutationObserver"),g(!0))});b.observe(o,{childList:!0,subtree:!0,characterData:!1}),c=b}),u=(async()=>{for(;Date.now()-d<i;){if(this.scanAndLabelAds(e,r,a)&&!l)return l=!0,console.log("[AdMeshSDK] AdMesh links detected via polling"),!0;await this.sleep(s)}return!1})();return await Promise.race([m,u])}finally{c&&c.disconnect()}}scanAndLabelAds(e,r,a){const i=document.getElementById(e);if(!i)return!1;const o=this.getWeaveProcessor(),d=this.getTracker();return o.scanAndProcessLinks(i,r,(l,c)=>{d.fireExposure(l,c,a)}).length>0}async fetchRecommendationsFromAPI(e){const r=`${this.apiBaseUrl}/agent/recommend`,a={query:e.query,format:e.format||"auto"};e.previousQuery&&(a.previous_query=e.previousQuery),e.previousSummary&&(a.previous_summary=e.previousSummary),e.sessionId&&(a.session_id=e.sessionId),e.messageId&&(a.message_id=e.messageId),e.isFallbackAllowed!==void 0&&(a.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(a)});if(!i.ok){const s=(await i.json().catch(()=>({}))).detail||`HTTP ${i.status}`;throw new Error(`Failed to fetch recommendations: ${s}`)}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 Be=({apiKey:t,sessionId:e,theme:r,apiBaseUrl:a,children:i})=>{const o=f.useRef(null),[d,s]=f.useState(new Set);f.useEffect(()=>{if(!t){console.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}try{o.current=new le({apiKey:t,theme:r,apiBaseUrl:a}),console.log("[AdMeshProvider] โœ… AdMesh SDK initialized"),a&&console.log(`[AdMeshProvider] ๐Ÿ“ Using custom API base URL: ${a}`)}catch(c){console.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK:",c)}return()=>{console.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,r,a]);const l={sdk:o.current,apiKey:t,sessionId:e,theme:r,processedMessageIds:d,markMessageAsProcessed:c=>{s(m=>{const u=new Set(m);return u.add(c),u})},isMessageProcessed:c=>d.has(c)};return n.jsx(K.Provider,{value:l,children:i})};function Y(){const t=me();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const Oe=({messages:t,format:e="auto",onRecommendationsShown:r,onError:a})=>{const{sdk:i,sessionId:o,markMessageAsProcessed:d,isMessageProcessed:s}=Y(),l=f.useRef(null),[c,m]=f.useState("");return f.useEffect(()=>{const u=[...t].reverse().find(h=>h.role==="assistant");u&&m(`admesh-recommendations-${u.messageId}`)},[t]),f.useEffect(()=>{(async()=>{if(!i||!c||![...t].reverse().find(y=>y.role==="assistant"))return;const g=[...t].reverse().find(y=>y.role==="user");if(!g)return;const b=g.messageId;if(!s(b)){d(b);try{console.log("[AdMeshRecommendations] ๐Ÿ“Š Showing recommendations:",{sessionId:o,messageId:b,query:g.content.substring(0,50)+"...",containerId:c}),await i.showRecommendations({query:g.content,containerId:c,format:e,session_id:o,message_id:b}),r==null||r(b)}catch(y){const k=y instanceof Error?y:new Error(String(y));console.error("[AdMeshRecommendations] โŒ Error showing recommendations:",k),a==null||a(k)}}})()},[t,i,o,c,e,d,s,r,a]),n.jsx("div",{ref:l,id:c,className:"admesh-recommendations-container"})},ue=({recommendation:t,theme:e,variation:r="default",expandable:a=!1,className:i,style:o})=>{var c,m,u,h,g;const s=(()=>{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}})(),l=R("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":a&&(r==="question"||r==="statement")},i);return n.jsx("div",{className:l,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((m=(c=e==null?void 0:e.components)==null?void 0:c.inlineRecommendation)==null?void 0:m.width)||"100%",...(u=e==null?void 0:e.components)==null?void 0:u.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:n.jsxs("div",{className:"h-full flex flex-col",children:[n.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&n.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"}}),n.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:s.title})]}),n.jsx("div",{className:"flex-shrink-0",children:n.jsx(W,{adId:((h=t.meta)==null?void 0:h.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:n.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",n.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n.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.description&&n.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:s.description}),n.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:n.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[n.jsx("span",{children:"Sponsored"}),n.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:a,style:i})=>{const o=e||Ue[t]||"secondary",d=He[t],s=R("admesh-component","admesh-badge",`admesh-badge--${o}`,`admesh-badge--${r}`,a);return n.jsxs("span",{className:s,style:i,children:[d&&n.jsx("span",{className:"admesh-badge__icon",children:d}),n.jsx("span",{className:"admesh-badge__text",children:t})]})};he.displayName="AdMeshBadge";const pe=t=>{const{sdk:e,sessionId:r}=Y(),a=f.useRef(!1),i=f.useRef(0),o=f.useRef(!1),d=f.useRef(!1),s=f.useRef(null),l=f.useCallback(async()=>{var c,m,u,h;if(!e||!r||a.current){console.log("[useWeaveAdFormat] ๐Ÿšซ Skipping - sdk:",!!e,"sessionId:",!!r,"processing:",a.current);return}a.current=!0,i.current=0;try{const g=document.getElementById(t.llmOutputContainerId);if(!g){console.warn(`[useWeaveAdFormat] โŒ Container not found: ${t.llmOutputContainerId}`);return}console.log("[useWeaveAdFormat] โœ… Container found:",{id:t.llmOutputContainerId,hasContent:!!g.innerHTML,contentLength:g.innerHTML.length,contentPreview:g.innerHTML.substring(0,150)});const b=(c=e.getWeaveProcessor)==null?void 0:c.call(e);if(!b){console.warn("[useWeaveAdFormat] โŒ WeaveResponseProcessor not available");return}console.log("[useWeaveAdFormat] โœ… WeaveResponseProcessor available"),console.log("[useWeaveAdFormat] ๐Ÿ” Starting link scan...");const y=b.scanAndProcessLinks(g,[],(M,S)=>{console.log("[useWeaveAdFormat] ๐Ÿ“ Exposure tracked:",{adId:S,exposureUrl:M})});i.current=y.length;const k=y.length>0;console.log("[useWeaveAdFormat] ๐Ÿ“Š Scan result:",{detectedLinksCount:y.length,hasLinks:k,linksFoundRef:o.current,callbackFiredRef:d.current,detectedLinks:y.map(M=>{var S;return{href:M.href,text:(S=M.text)==null?void 0:S.substring(0,50)}})}),k&&!o.current?(o.current=!0,console.log(`[useWeaveAdFormat] โœ… Detected ${y.length} AdMesh links`),(m=t.onLinksDetected)==null||m.call(t,y.length),d.current=!0):!k&&o.current?(console.log("[useWeaveAdFormat] โš ๏ธ Links were found before but now they're gone"),o.current=!1,d.current=!1):!k&&!d.current?(console.log("[useWeaveAdFormat] โณ No links found yet - starting 500ms debounce timer"),s.current&&(console.log("[useWeaveAdFormat] ๐Ÿ”„ Clearing existing debounce timer"),clearTimeout(s.current)),s.current=setTimeout(()=>{var M;!o.current&&!d.current?(console.log("[useWeaveAdFormat] โฐ Debounce timer fired - No AdMesh links detected - fallback UI should be rendered"),(M=t.onNoLinksDetected)==null||M.call(t),d.current=!0):console.log("[useWeaveAdFormat] โฐ Debounce timer fired - but links were found during streaming, skipping callback")},500)):k&&d.current&&!o.current?(console.log(`[useWeaveAdFormat] ๐ŸŽฏ AdMesh links detected during streaming: ${y.length}`),s.current&&(console.log("[useWeaveAdFormat] ๐Ÿ”„ Clearing debounce timer - links found during streaming"),clearTimeout(s.current),s.current=null),o.current=!0,(u=t.onLinksDetected)==null||u.call(t,y.length),d.current=!0):console.log("[useWeaveAdFormat] โ„น๏ธ No state change needed",{hasLinks:k,linksFoundRef:o.current,callbackFiredRef:d.current})}catch(g){const b=g instanceof Error?g:new Error(String(g));console.error("[useWeaveAdFormat] Error processing Weave format:",b),(h=t.onError)==null||h.call(t,b)}finally{a.current=!1}},[e,r,t]);return f.useEffect(()=>{const c=document.getElementById(t.llmOutputContainerId);if(!c)return;l();const m=new MutationObserver(()=>{l()});return m.observe(c,{childList:!0,subtree:!0,characterData:!1}),()=>{m.disconnect(),s.current&&clearTimeout(s.current)}},[t.llmOutputContainerId,l]),{isProcessing:a.current,detectedLinksCount:i.current,linksFound:o.current,shouldRenderFallback:!o.current,processWeaveFormat:l}},qe=({messageId:t,children:e,timeoutMs:r=900,fallbackFormat:a="citation",onLinksDetected:i,onNoLinksDetected:o,onError:d,className:s,fallbackUI:l})=>{const c=f.useRef(null),m=`weave-ad-container-${t}`,{detectedLinksCount:u,shouldRenderFallback:h}=pe({llmOutputContainerId:m,timeoutMs:r,fallbackFormat:a,onLinksDetected:g=>{console.log(`[WeaveAdFormatContainer] โœ… Links detected for message ${t}:`,g),i==null||i(g)},onNoLinksDetected:()=>{console.log(`[WeaveAdFormatContainer] โŒ No links detected for message ${t} - rendering fallback UI`),o==null||o()},onError:d});return console.log(`[WeaveAdFormatContainer] ๐Ÿ“Š Render state for message ${t}:`,{containerId:m,detectedLinksCount:u,shouldRenderFallback:h,hasFallbackUI:!!l}),n.jsxs(n.Fragment,{children:[n.jsx("div",{ref:c,id:m,className:s,"data-weave-ad-format":"true","data-message-id":t,"data-detected-links":u,"data-links-found":u>0,children:e}),h&&l&&n.jsx("div",{"data-weave-fallback-ui":"true","data-message-id":t,children:l})]})},Ke="1.0.0";exports.AdMeshBadge=he;exports.AdMeshContext=K;exports.AdMeshEcommerceCards=se;exports.AdMeshInlineCard=ue;exports.AdMeshLayout=ae;exports.AdMeshLinkTracker=W;exports.AdMeshProductCard=z;exports.AdMeshProvider=Be;exports.AdMeshRecommendations=Oe;exports.AdMeshRenderer=de;exports.AdMeshSDK=le;exports.AdMeshSummaryLayout=ne;exports.AdMeshSummaryUnit=q;exports.AdMeshTracker=ie;exports.AdMeshViewabilityTracker=I;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
+ `}})]})},Ve=t=>{var d,o,n;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=((d=t.recommendations)==null?void 0:d.filter(s=>s&&s.admesh_link&&(s.title||s.recommendation_title)))||[],a=((o=t.recommendations)==null?void 0:o.length)===0;return r.length===0&&!a&&e.push("No valid recommendations found (missing admesh_link or title)"),{isValid:r.length>0,isEmpty:a,validCount:r.length,totalCount:((n=t.recommendations)==null?void 0:n.length)||0,warnings:e}},ne=({response:t,theme:e,className:r="",style:a={},onLinkClick:d})=>{const o=Ve(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:n="citation",citation_summary:s,recommendations:l=[],requires_summary:c=!0}=t;console.log(`[AdMesh Summary Layout] Rendering ${n} layout with ${o.validCount}/${o.totalCount} valid recommendations`);const m=()=>{switch(n){case"citation":return s&&c?i.jsx(q,{summaryText:s,recommendations:l,theme:e,onLinkClick:d}):i.jsxs("div",{className:"fallback-citation",children:[i.jsx("p",{className:"text-gray-700 dark:text-gray-300 mb-3",children:"Based on your query, I'd recommend checking out these options:"}),i.jsx(W,{recommendation:l[0],theme:e})]});case"product_cards":case"product":return i.jsx("div",{className:"product-cards-layout",children:l.slice(0,3).map((u,h)=>i.jsx(W,{recommendation:u,theme:e,className:"mb-4"},u.ad_id||`rec-${h}`))});case"ecommerce":return i.jsx(se,{recommendations:l.slice(0,3),theme:(e==null?void 0:e.mode)||"light"});default:return console.warn(`[AdMesh Summary Layout] Unknown layout type: ${n}`),s?i.jsx(q,{summaryText:s,recommendations:l,theme:e,onLinkClick:d}):i.jsx(W,{recommendation:l[0],theme:e})}};return i.jsx("div",{className:`admesh-summary-layout admesh-layout-${n} ${r}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...a},children:m()})},ae=({response:t,theme:e,className:r,style:a,onLinkClick:d})=>t?t.recommendations&&Array.isArray(t.recommendations)&&t.recommendations.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):i.jsx(ne,{response:t,theme:e,className:r,style:a,onLinkClick:d}):(console.error("[AdMeshLayout] response prop is required"),null);class ie{constructor(e){C(this,"firedExposures",new Set);C(this,"debug",!1);C(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,r,a){const d=`${a}_${r}`;if(this.firedExposures.has(d)){this.debug&&console.log("[Tracker] Exposure already fired for:",r);return}this.firedExposures.add(d);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,a,d){const o=`${a}_${r}`;if(this.firedExposures.has(o)){this.debug&&console.log("[Tracker] MRC exposure already fired for:",r);return}return new Promise(n=>{let s=null,l=null;const c=new IntersectionObserver(h=>{h.forEach(g=>{const b=g.intersectionRatio*100;b>=this.mrcThreshold.visibilityPercentage?s===null&&(s=Date.now(),this.debug&&console.log("[Tracker] Ad reached MRC visibility threshold:",{adId:r,visibilityPercentage:b.toFixed(2)}),l=setTimeout(()=>{this.fireExposure(e,r,a),c.disconnect(),n()},this.mrcThreshold.minimumDurationMs)):s!==null&&(l&&(clearTimeout(l),l=null),s=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"});c.observe(d);const u=setTimeout(()=>{c.disconnect(),l&&clearTimeout(l),n()},3e4);d.__admeshTrackerCleanup=()=>{c.disconnect(),l&&clearTimeout(l),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class de{constructor(){C(this,"roots",new Map)}async render(e){var r,a,d,o;try{const n=document.getElementById(e.containerId);if(!n)throw new Error(`Container with ID "${e.containerId}" not found`);const s=this.roots.get(e.containerId);s&&s.unmount();const l=be.createRoot(n),c=((r=e.response.response)==null?void 0:r.citation_summary)||((a=e.response.response)==null?void 0:a.summary);l.render(i.jsx(ae,{response:{layout_type:(d=e.response.response)==null?void 0:d.layout_type,citation_summary:c,recommendations:((o=e.response.response)==null?void 0:o.recommendations)||[],requires_summary:!!c},theme:e.theme})),this.roots.set(e.containerId,l)}catch(n){throw n}}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={}){C(this,"autoAddLabels");C(this,"fireExposurePixels");C(this,"labelStyle");C(this,"processedLinks",new Set);C(this,"mutationObserver",null);var r,a,d,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:((a=e.labelStyle)==null?void 0:a.fontWeight)||"bold",color:((d=e.labelStyle)==null?void 0:d.color)||"#666",marginLeft:((o=e.labelStyle)==null?void 0:o.marginLeft)||"2px"}}getLinksToProcess(e){const a=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return a.length>0?Array.from(a):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,r,a){if(!e)return[];const d=[];if(r.length>0){const o=this.getLinksToProcess(e),n=new Map(r.filter(s=>s.click_url).map(s=>[s.click_url,s]));o.forEach(s=>{var u;const l=s.getAttribute("href")||"",c=`${l}`;if(this.processedLinks.has(c))return;const m=n.get(l);if(m){this.processedLinks.add(c);const h={element:s,href:l,text:s.textContent||"",hasAdLabel:this.hasAdLabel(s),matchedRecommendation:{ad_id:m.ad_id||((u=m.meta)==null?void 0:u.ad_id)||"",click_url:m.click_url,exposure_url:m.exposure_url}};this.autoAddLabels&&!h.hasAdLabel&&(this.addAdLabel(s),h.hasAdLabel=!0),this.fireExposurePixels&&m.exposure_url&&a&&h.matchedRecommendation&&a(m.exposure_url,h.matchedRecommendation.ad_id),d.push(h)}})}else{const o=Array.from(e.querySelectorAll("a"));console.log("[WeaveResponseProcessor] ๐Ÿ” Scanning for AdMesh links:",{totalLinksInContainer:o.length,containerHTML:e.innerHTML.substring(0,200),allLinks:o.map(n=>{var s;return{href:n.getAttribute("href"),text:(s=n.textContent)==null?void 0:s.substring(0,50)}})}),o.forEach(n=>{const s=n.getAttribute("href")||"",l=`${s}`;if(this.processedLinks.has(l))return;if(this.isAdMeshLink(s)){console.log("[WeaveResponseProcessor] โœ… Found AdMesh link:",{href:s,text:n.textContent}),this.processedLinks.add(l);const m={element:n,href:s,text:n.textContent||"",hasAdLabel:this.hasAdLabel(n),matchedRecommendation:void 0};n.setAttribute("target","_blank"),n.setAttribute("rel","noopener noreferrer"),console.log('[WeaveResponseProcessor] ๐Ÿ”— Set target="_blank" and rel="noopener noreferrer"'),this.autoAddLabels&&!m.hasAdLabel&&(this.addAdLabel(n),m.hasAdLabel=!0),this.fireExposurePixels&&a&&a(s,this.extractAdIdFromUrl(s)),d.push(m)}}),console.log("[WeaveResponseProcessor] ๐Ÿ“Š Scan complete:",{adMeshLinksFound:d.length,totalLinksScanned:o.length})}return d}hasAdLabel(e){var d,o;let r=e.previousSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const n=r.textContent||"";if(n.trim()===""){r=r.previousSibling;continue}if(n.includes("[Ad]"))return console.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label on LEFT side of link"),!0;break}if(r&&r.nodeType===Node.ELEMENT_NODE){const n=r;if((n.tagName==="SUB"||n.tagName==="SPAN")&&((d=n.textContent)!=null&&d.includes("[Ad]")))return console.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label element on LEFT side of link"),!0}let a=e.nextSibling;for(;a&&a.nodeType===Node.TEXT_NODE;){const n=a.textContent||"";if(n.trim()===""){a=a.nextSibling;continue}if(n.includes("[Ad]"))return console.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label on RIGHT side of link"),!0;break}if(a&&a.nodeType===Node.ELEMENT_NODE){const n=a;if((n.tagName==="SUB"||n.tagName==="SPAN")&&((o=n.textContent)!=null&&o.includes("[Ad]")))return console.log("[WeaveResponseProcessor] โ„น๏ธ Found [Ad] label element on RIGHT side of link"),!0}return!1}addAdLabel(e){var o;if(console.log("[WeaveResponseProcessor] ๐Ÿท๏ธ Adding [Ad] label to link:",{href:e.getAttribute("href"),text:e.textContent}),this.hasAdLabel(e)){console.log("[WeaveResponseProcessor] โ„น๏ธ [Ad] label already exists, skipping");return}this.removeLeftAdLabel(e);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,r.style.cursor="pointer",r.style.borderBottom=`1px dotted ${this.labelStyle.color}`,r.style.whiteSpace="nowrap",r.title="Why this ad? This is a sponsored recommendation based on your search query.";let a=!1;r.addEventListener("mouseenter",()=>{r.style.opacity="0.7"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1",a&&(a=!1)}),r.addEventListener("click",n=>{n.stopPropagation(),a=!a,a?(console.log("[WeaveResponseProcessor] ๐Ÿ‘† [Ad] label clicked - tooltip shown"),r.style.textDecoration="underline",r.style.opacity="0.7"):(console.log("[WeaveResponseProcessor] ๐Ÿ‘† [Ad] label clicked - tooltip hidden"),r.style.textDecoration="none",r.style.opacity="1")});const d=n=>{a&&n.target!==r&&(a=!1,r.style.textDecoration="none",r.style.opacity="1")};document.addEventListener("click",d),(o=e.parentNode)==null||o.insertBefore(r,e.nextSibling),console.log("[WeaveResponseProcessor] โœ… [Ad] label created and inserted to the RIGHT of link")}removeLeftAdLabel(e){var a,d,o;let r=e.previousSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const n=r.textContent||"";if(n.trim()===""){r=r.previousSibling;continue}if(n.includes("[Ad]")){console.log("[WeaveResponseProcessor] ๐Ÿ—‘๏ธ Removing [Ad] label text from LEFT side of link"),(a=r.parentNode)==null||a.removeChild(r);return}break}if(r&&r.nodeType===Node.ELEMENT_NODE){const n=r;(n.tagName==="SUB"||n.tagName==="SPAN")&&((d=n.textContent)!=null&&d.includes("[Ad]"))&&(console.log("[WeaveResponseProcessor] ๐Ÿ—‘๏ธ Removing [Ad] label element from LEFT side of link"),(o=n.parentNode)==null||o.removeChild(n))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(d=>e.includes(d)))return console.log("[WeaveResponseProcessor] ๐ŸŽฏ Matched known AdMesh domain:",{href:e}),!0;try{if(new URL(e).pathname.startsWith("/click/"))return console.log("[WeaveResponseProcessor] ๐ŸŽฏ Matched /click/ pattern:",{href:e}),!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return console.log("[WeaveResponseProcessor] ๐ŸŽฏ Matched /click/ regex pattern:",{href:e}),!0}return!1}extractAdIdFromUrl(e){try{const r=e.match(/\/click\/([^/?]+)/);return r&&r[1]?r[1]:e}catch{return e}}watchForNewLinks(e,r,a){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,r,a)}),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){C(this,"config");C(this,"apiBaseUrl");C(this,"renderer",null);C(this,"tracker",null);C(this,"weaveProcessor",null);C(this,"weaveCache",new Map);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}static createSession(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}static createMessageId(e){const r=Date.now(),a=Math.random().toString(36).substring(2,15);return`msg_${e}_${r}_${a}`}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,a;try{const d=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,d);else{const o=this.getRenderer(),n=this.getTracker();if(await o.render({containerId:e.containerId,response:d,theme:e.theme||this.config.theme,tracker:n,sessionId:e.session_id||""}),(r=d.response)!=null&&r.recommendations){for(const s of d.response.recommendations)if(s.exposure_url){const l=((a=s.meta)==null?void 0:a.ad_id)||s.ad_id||"";n.fireExposure(s.exposure_url,l,e.session_id||"")}}}}catch(d){throw console.error("[AdMeshSDK] Error showing recommendations:",d),d}}async handleWeaveFormat(e,r){var u,h,g,b;const a=e.session_id||"",d=e.message_id||"",o=e.timeoutMs||900,n=e.fallbackFormat||"citation",s=`${a}:${d}`;if(this.weaveCache.set(s,((u=r.response)==null?void 0:u.recommendations)||[]),e.llmOutputContainerId)try{if(await this.scanLLMOutputForAdMeshLinks(e.llmOutputContainerId,((h=r.response)==null?void 0:h.recommendations)||[],a,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:",n);const l={...r,response:{...r.response,layout_type:n}},c=this.getRenderer(),m=this.getTracker();if(await c.render({containerId:e.containerId,response:l,theme:e.theme||this.config.theme,tracker:m,sessionId:a}),(g=r.response)!=null&&g.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||"";m.fireExposure(y.exposure_url,v,a)}}}async scanLLMOutputForAdMeshLinks(e,r,a,d){const o=document.getElementById(e);if(!o)return console.warn(`[AdMeshSDK] LLM output container not found: ${e}`),!1;const n=Date.now(),s=100;let l=!1,c=null;try{const m=new Promise(g=>{const b=new MutationObserver(()=>{this.scanAndLabelAds(e,r,a)&&!l&&(l=!0,console.log("[AdMeshSDK] AdMesh links detected via MutationObserver"),g(!0))});b.observe(o,{childList:!0,subtree:!0,characterData:!1}),c=b}),u=(async()=>{for(;Date.now()-n<d;){if(this.scanAndLabelAds(e,r,a)&&!l)return l=!0,console.log("[AdMeshSDK] AdMesh links detected via polling"),!0;await this.sleep(s)}return!1})();return await Promise.race([m,u])}finally{c&&c.disconnect()}}scanAndLabelAds(e,r,a){const d=document.getElementById(e);if(!d)return!1;const o=this.getWeaveProcessor(),n=this.getTracker();return o.scanAndProcessLinks(d,r,(l,c)=>{n.fireExposure(l,c,a)}).length>0}async fetchRecommendationsFromAPI(e){const r=`${this.apiBaseUrl}/agent/recommend`,a={query:e.query,format:e.format||"auto"};e.previousQuery&&(a.previous_query=e.previousQuery),e.previousSummary&&(a.previous_summary=e.previousSummary),e.sessionId&&(a.session_id=e.sessionId),e.messageId&&(a.message_id=e.messageId),e.isFallbackAllowed!==void 0&&(a.is_fallback_allowed=e.isFallbackAllowed);const d=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(a)});if(!d.ok){const s=(await d.json().catch(()=>({}))).detail||`HTTP ${d.status}`;throw new Error(`Failed to fetch recommendations: ${s}`)}return await d.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,sessionId:e,theme:r,apiBaseUrl:a,children:d})=>{const o=f.useRef(null),[n,s]=f.useState(new Set);f.useEffect(()=>{if(!t){console.warn("[AdMeshProvider] โš ๏ธ AdMesh API key not configured");return}try{o.current=new le({apiKey:t,theme:r,apiBaseUrl:a}),console.log("[AdMeshProvider] โœ… AdMesh SDK initialized"),a&&console.log(`[AdMeshProvider] ๐Ÿ“ Using custom API base URL: ${a}`)}catch(c){console.error("[AdMeshProvider] โŒ Failed to initialize AdMesh SDK:",c)}return()=>{console.log("[AdMeshProvider] ๐Ÿงน Provider unmounted")}},[t,r,a]);const l={sdk:o.current,apiKey:t,sessionId:e,theme:r,processedMessageIds:n,markMessageAsProcessed:c=>{s(m=>{const u=new Set(m);return u.add(c),u})},isMessageProcessed:c=>n.has(c)};return i.jsx(K.Provider,{value:l,children:d})};function Y(){const t=me();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const Be=({messages:t,format:e="auto",onRecommendationsShown:r,onError:a})=>{const{sdk:d,sessionId:o,markMessageAsProcessed:n,isMessageProcessed:s}=Y(),l=f.useRef(null),[c,m]=f.useState("");return f.useEffect(()=>{const u=[...t].reverse().find(h=>h.role==="assistant");u&&m(`admesh-recommendations-${u.messageId}`)},[t]),f.useEffect(()=>{(async()=>{if(!d||!c||![...t].reverse().find(y=>y.role==="assistant"))return;const g=[...t].reverse().find(y=>y.role==="user");if(!g)return;const b=g.messageId;if(!s(b)){n(b);try{console.log("[AdMeshRecommendations] ๐Ÿ“Š Showing recommendations:",{sessionId:o,messageId:b,query:g.content.substring(0,50)+"...",containerId:c}),await d.showRecommendations({query:g.content,containerId:c,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),a==null||a(v)}}})()},[t,d,o,c,e,n,s,r,a]),i.jsx("div",{ref:l,id:c,className:"admesh-recommendations-container"})},ue=({recommendation:t,theme:e,variation:r="default",expandable:a=!1,className:d,style:o})=>{var c,m,u,h,g;const s=(()=>{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}})(),l=R("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":a&&(r==="question"||r==="statement")},d);return i.jsx("div",{className:l,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((m=(c=e==null?void 0:e.components)==null?void 0:c.inlineRecommendation)==null?void 0:m.width)||"100%",...(u=e==null?void 0:e.components)==null?void 0:u.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",children:[i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&i.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"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:s.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(z,{adId:((h=t.meta)==null?void 0:h.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:i.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[r==="question"?"Try":"Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),s.description&&i.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:s.description}),i.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};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:a,style:d})=>{const o=e||Ue[t]||"secondary",n=He[t],s=R("admesh-component","admesh-badge",`admesh-badge--${o}`,`admesh-badge--${r}`,a);return i.jsxs("span",{className:s,style:d,children:[n&&i.jsx("span",{className:"admesh-badge__icon",children:n}),i.jsx("span",{className:"admesh-badge__text",children:t})]})};he.displayName="AdMeshBadge";const pe=t=>{const{sdk:e,sessionId:r}=Y(),a=f.useRef(!1),d=f.useRef(0),o=f.useRef(!1),n=f.useRef(!1),s=f.useRef(null),l=f.useCallback(async()=>{var c,m,u,h;if(!e||!r||a.current){console.log("[useWeaveAdFormat] ๐Ÿšซ Skipping - sdk:",!!e,"sessionId:",!!r,"processing:",a.current);return}a.current=!0,d.current=0;try{const g=document.getElementById(t.llmOutputContainerId);if(!g){console.warn(`[useWeaveAdFormat] โŒ Container not found: ${t.llmOutputContainerId}`);return}console.log("[useWeaveAdFormat] โœ… Container found:",{id:t.llmOutputContainerId,hasContent:!!g.innerHTML,contentLength:g.innerHTML.length,contentPreview:g.innerHTML.substring(0,150)});const b=(c=e.getWeaveProcessor)==null?void 0:c.call(e);if(!b){console.warn("[useWeaveAdFormat] โŒ WeaveResponseProcessor not available");return}console.log("[useWeaveAdFormat] โœ… WeaveResponseProcessor available"),console.log("[useWeaveAdFormat] ๐Ÿ” Starting link scan...");const y=b.scanAndProcessLinks(g,[],(M,S)=>{console.log("[useWeaveAdFormat] ๐Ÿ“ Exposure tracked:",{adId:S,exposureUrl:M})});d.current=y.length;const v=y.length>0;console.log("[useWeaveAdFormat] ๐Ÿ“Š Scan result:",{detectedLinksCount:y.length,hasLinks:v,linksFoundRef:o.current,callbackFiredRef:n.current,detectedLinks:y.map(M=>{var S;return{href:M.href,text:(S=M.text)==null?void 0:S.substring(0,50)}})}),v&&!o.current?(o.current=!0,console.log(`[useWeaveAdFormat] โœ… Detected ${y.length} AdMesh links`),(m=t.onLinksDetected)==null||m.call(t,y.length),n.current=!0):!v&&o.current?(console.log("[useWeaveAdFormat] โš ๏ธ Links were found before but now they're gone"),o.current=!1,n.current=!1):!v&&!n.current?(console.log("[useWeaveAdFormat] โณ No links found yet - starting 500ms debounce timer"),s.current&&(console.log("[useWeaveAdFormat] ๐Ÿ”„ Clearing existing debounce timer"),clearTimeout(s.current)),s.current=setTimeout(()=>{var M;!o.current&&!n.current?(console.log("[useWeaveAdFormat] โฐ Debounce timer fired - No AdMesh links detected - fallback UI should be rendered"),(M=t.onNoLinksDetected)==null||M.call(t),n.current=!0):console.log("[useWeaveAdFormat] โฐ Debounce timer fired - but links were found during streaming, skipping callback")},500)):v&&n.current&&!o.current?(console.log(`[useWeaveAdFormat] ๐ŸŽฏ AdMesh links detected during streaming: ${y.length}`),s.current&&(console.log("[useWeaveAdFormat] ๐Ÿ”„ Clearing debounce timer - links found during streaming"),clearTimeout(s.current),s.current=null),o.current=!0,(u=t.onLinksDetected)==null||u.call(t,y.length),n.current=!0):console.log("[useWeaveAdFormat] โ„น๏ธ No state change needed",{hasLinks:v,linksFoundRef:o.current,callbackFiredRef:n.current})}catch(g){const b=g instanceof Error?g:new Error(String(g));console.error("[useWeaveAdFormat] Error processing Weave format:",b),(h=t.onError)==null||h.call(t,b)}finally{a.current=!1}},[e,r,t]);return f.useEffect(()=>{const c=document.getElementById(t.llmOutputContainerId);if(!c)return;l();const m=new MutationObserver(()=>{l()});return m.observe(c,{childList:!0,subtree:!0,characterData:!1}),()=>{m.disconnect(),s.current&&clearTimeout(s.current)}},[t.llmOutputContainerId,l]),{isProcessing:a.current,detectedLinksCount:d.current,linksFound:o.current,shouldRenderFallback:!o.current,processWeaveFormat:l}},qe=({messageId:t,children:e,timeoutMs:r=900,fallbackFormat:a="citation",onLinksDetected:d,onNoLinksDetected:o,onError:n,className:s,fallbackUI:l})=>{const c=f.useRef(null),m=`weave-ad-container-${t}`,{detectedLinksCount:u,shouldRenderFallback:h}=pe({llmOutputContainerId:m,timeoutMs:r,fallbackFormat:a,onLinksDetected:g=>{console.log(`[WeaveAdFormatContainer] โœ… Links detected for message ${t}:`,g),d==null||d(g)},onNoLinksDetected:()=>{console.log(`[WeaveAdFormatContainer] โŒ No links detected for message ${t} - rendering fallback UI`),o==null||o()},onError:n});return console.log(`[WeaveAdFormatContainer] ๐Ÿ“Š Render state for message ${t}:`,{containerId:m,detectedLinksCount:u,shouldRenderFallback:h,hasFallbackUI:!!l}),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:c,id:m,className:s,"data-weave-ad-format":"true","data-message-id":t,"data-detected-links":u,"data-links-found":u>0,children:e}),h&&l&&i.jsx("div",{"data-weave-fallback-ui":"true","data-message-id":t,children:l})]})},Ke="1.0.0";exports.AdMeshBadge=he;exports.AdMeshContext=K;exports.AdMeshEcommerceCards=se;exports.AdMeshInlineCard=ue;exports.AdMeshLayout=ae;exports.AdMeshLinkTracker=z;exports.AdMeshProductCard=W;exports.AdMeshProvider=Oe;exports.AdMeshRecommendations=Be;exports.AdMeshRenderer=de;exports.AdMeshSDK=le;exports.AdMeshSummaryLayout=ne;exports.AdMeshSummaryUnit=q;exports.AdMeshTracker=ie;exports.AdMeshViewabilityTracker=I;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