admesh-ui-sdk 0.19.6 → 0.19.7
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 +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +392 -392
- package/dist/index.mjs.map +1 -1
- package/dist/sdk/AdMeshRenderer.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var xe=Object.defineProperty;var ye=(t,e,r)=>e in t?xe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var
|
|
1
|
+
"use strict";var xe=Object.defineProperty;var ye=(t,e,r)=>e in t?xe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var j=(t,e,r)=>ye(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react/jsx-runtime"),g=require("react"),we=require("react-dom/client"),ke=t=>{try{return new URL(t),!0}catch{return!1}},Z=(t,e)=>{const r=new Map;e.forEach(m=>{m.admesh_link&&r.set(m.admesh_link,m)});const i=/\[([^\]]+)\]\(([^)]+)\)/g,n=[];let a=0,s,d=0;for(;(s=i.exec(t))!==null;){const[m,h,x]=s,c=r.get(x);s.index>a&&n.push(t.slice(a,s.index)),c?(d++,n.push(o.jsx("a",{href:c.admesh_link,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:p=>{console.log("AdMesh summary link clicked:",{adId:c.ad_id,productId:c.product_id,title:c.title||c.recommendation_title,brand:c.brand,pricing:c.pricing,admeshLink:c.admesh_link,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:c.ad_id,productId:c.product_id,admeshLink:c.admesh_link,source:"summary"})},children:h},`summary-link-${d}`))):(console.warn(`[AdMesh Summary] No recommendation found for link: [${h}](${x}), creating regular link`),ke(x)?(d++,n.push(o.jsx("a",{href:x,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:p=>{console.log("AdMesh summary unmatched link clicked:",{linkText:h,url:x,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({url:x,linkText:h,source:"summary_unmatched"})},children:h},`summary-link-${d}`))):(console.warn(`[AdMesh Summary] Invalid URL in markdown link: [${h}](${x})`),n.push(h))),a=s.index+m.length}return a<t.length&&n.push(t.slice(a)),n},G=({summaryText:t,recommendations:e,theme:r,className:i="",style:n={},onLinkClick:a})=>{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 d=Z(t,[]);return o.jsx("div",{className:`admesh-summary-unit ${i}`,style:n,children:o.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed",children:d.map((m,h)=>o.jsx(g.Fragment,{children:m},h))})})}const s=Z(t,e);return o.jsxs("div",{className:`admesh-summary-unit ${i}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...n},children:[o.jsx("div",{className:"summary-content",children:o.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed text-base",children:s.map((d,m)=>o.jsx(g.Fragment,{children:d},m))})}),o.jsx("div",{className:"mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:o.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})})]})};function ve(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var q={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 ee;function _e(){return ee||(ee=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var a="",
|
|
5
|
+
*/var ee;function _e(){return ee||(ee=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var a="",s=0;s<arguments.length;s++){var d=arguments[s];d&&(a=n(a,i(d)))}return a}function i(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return r.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var s="";for(var d in a)e.call(a,d)&&a[d]&&(s=n(s,d));return s}function n(a,s){return s?a?a+" "+s:a+s:a}t.exports?(r.default=r,t.exports=r):window.classNames=r})()})(q)),q.exports}var Se=_e();const P=ve(Se),Me="https://api.useadmesh.com/track";let Y={apiBaseUrl:Me,enabled:!0,debug:!1,retryAttempts:3,retryDelay:1e3};const Ce=t=>{Y={...Y,...t}},oe=t=>{const[e,r]=g.useState(!1),[i,n]=g.useState(null),a=g.useMemo(()=>({...Y,...t}),[t]),s=g.useCallback((c,p)=>{a.debug&&console.log(`[AdMesh Tracker] ${c}`,p)},[a.debug]),d=g.useCallback(async(c,p)=>{if(!a.enabled){s("Tracking disabled, skipping event",{eventType:c,data:p});return}if(!p.adId||!p.admeshLink){const b="Missing required tracking data: adId and admeshLink are required";s(b,p),n(b);return}r(!0),n(null);const u={event_type:c,ad_id:p.adId,admesh_link:p.admeshLink,product_id:p.productId,user_id:p.userId,session_id:p.sessionId,revenue:p.revenue,conversion_type:p.conversionType,metadata:p.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};s(`Sending ${c} event`,u);let v=null;for(let b=1;b<=(a.retryAttempts||3);b++)try{const S=await fetch(`${a.apiBaseUrl}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!S.ok)throw new Error(`HTTP ${S.status}: ${S.statusText}`);const T=await S.json();s(`${c} event tracked successfully`,T),r(!1);return}catch(S){v=S,s(`Attempt ${b} failed for ${c} event`,S),b<(a.retryAttempts||3)&&await new Promise(T=>setTimeout(T,(a.retryDelay||1e3)*b))}const _=`Failed to track ${c} event after ${a.retryAttempts} attempts: ${v==null?void 0:v.message}`;s(_,v),n(_),r(!1)},[a,s]),m=g.useCallback(async c=>d("click",c),[d]),h=g.useCallback(async c=>d("view",c),[d]),x=g.useCallback(async c=>(!c.revenue&&!c.conversionType&&s("Warning: Conversion tracking without revenue or conversion type",c),d("conversion",c)),[d,s]);return{trackClick:m,trackView:h,trackConversion:x,isTracking:e,error:i}},Te=(t,e,r)=>{try{const i=new URL(t);return i.searchParams.set("ad_id",e),i.searchParams.set("utm_source","admesh"),i.searchParams.set("utm_medium","recommendation"),r&&Object.entries(r).forEach(([n,a])=>{i.searchParams.set(n,a)}),i.toString()}catch(i){return console.warn("[AdMesh] Invalid URL provided to buildAdMeshLink:",t,i),t}},je=(t,e)=>({adId:t.ad_id,admeshLink:t.admesh_link,productId:t.product_id,...e}),U=({adId:t,admeshLink:e,productId:r,children:i,trackingData:n,className:a,style:s})=>{const{trackClick:d,trackView:m}=oe(),h=g.useRef(null),x=g.useRef(!1);g.useEffect(()=>{if(!h.current||x.current)return;const p=new IntersectionObserver(u=>{u.forEach(v=>{v.isIntersecting&&!x.current&&(x.current=!0,m({adId:t,admeshLink:e,productId:r,...n}).catch(console.error))})},{threshold:.5,rootMargin:"0px"});return p.observe(h.current),()=>{p.disconnect()}},[t,e,r,n,m]);const c=g.useCallback(async p=>{try{await d({adId:t,admeshLink:e,productId:r,...n})}catch(_){console.error("Failed to track click:",_)}p.target.closest("a")||window.open(e,"_blank","noopener,noreferrer")},[t,e,r,n,d]);return o.jsx("div",{ref:h,className:a,onClick:c,style:{cursor:"pointer",...s},children:i})};U.displayName="AdMeshLinkTracker";const Ie=`
|
|
6
6
|
/* AdMesh UI SDK - Complete Self-Contained Styles */
|
|
7
7
|
|
|
8
8
|
/* CSS Reset for AdMesh components */
|
|
@@ -670,7 +670,7 @@
|
|
|
670
670
|
.admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
671
671
|
.admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
|
|
672
672
|
}
|
|
673
|
-
`;let H=!1;const ne=()=>{g.useEffect(()=>{if(H)return;const t=document.createElement("style");return t.id="admesh-ui-sdk-styles",t.textContent=Ie,document.getElementById("admesh-ui-sdk-styles")||(document.head.appendChild(t),H=!0),()=>{const e=document.getElementById("admesh-ui-sdk-styles");e&&document.head.contains(e)&&(document.head.removeChild(e),H=!1)}},[])},F=(t,e={})=>{const r=t.intent_match_score||0,i=e.customLabels||{};return r>=.8?i.partnerRecommendation||"Smart Pick":r>=.6?i.partnerMatch||"Partner Recommendation":r>=.3?i.promotedOption||"Promoted Match":i.relatedOption||"Related"},J=(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."},Ae=(t=!0,e=!1)=>t?e?"These curated recommendations are from partners who compensate us for referrals.":"Personalized Sponsoreds: All results are from vetted partners who compensate us for qualified matches. We've ranked them based on relevance to your specific needs.":"Expanded Results: While these don't perfectly match your query, they're related solutions from our partner network. All partners compensate us for referrals.",Ne=(t,e=!1)=>{const r=t.intent_match_score||0;return e?"Promoted Match":r>=.8?"Smart Pick":r>=.6?"Partner Recommendation":"Promoted Match"},Ee=()=>"We've partnered with trusted providers to bring you relevant solutions. These partners compensate us for qualified referrals, which helps us keep our service free.",De=t=>({"Top Match":"Smart Pick",Sponsored:"Smart Pick","Perfect Fit":"Smart Pick","Great Match":"Partner Recommendation",Recommended:"Partner Recommendation","Good Fit":"Promoted Match",Featured:"Promoted Match","Popular Choice":"Popular Choice","Premium Pick":"Premium Pick","Free Tier":"Free Tier","AI Powered":"AI Powered",Popular:"Popular",New:"New","Trial Available":"Trial Available","Related Option":"Related Option","Alternative Solution":"Alternative Solution","Expanded Match":"Expanded Match"})[t]||t,Re=(t,e="button")=>{const r=t.recommendation_title||t.title;return e==="link"?r:t.trial_days&&t.trial_days>0?`Try ${r}`:"Learn More"},Pe=t=>t.some(e=>(e.intent_match_score||0)>=.8),Fe=(t=!1)=>t?"":"Recommendations ",B=({recommendation:t,theme:e,showBadges:r=!0,showFeatures:i=!1,variation:s="default",expandable:a=!1,className:n,style:d})=>{var v,_,x,S,j,M,E,A,h,k,l,y,w,D,N,C,L,$;ne();const[m,p]=g.useState(!1);g.useMemo(()=>{var X;const I=[],V=F(t);(V==="Smart Pick"||V==="Partner Recommendation"||V==="Promoted Match")&&I.push("Top Match"),t.trial_days&&t.trial_days>0&&I.push("Trial Available");const ge=["ai","artificial intelligence","machine learning","ml","automation"];return(((X=t.keywords)==null?void 0:X.some(z=>ge.some(be=>z.toLowerCase().includes(be))))||t.title.toLowerCase().includes("ai"))&&I.push("AI Powered"),t.badges&&t.badges.length>0&&t.badges.forEach(z=>{["Top Match","Free Tier","AI Powered","Popular","New","Trial Available"].includes(z)&&!I.includes(z)&&I.push(z)}),I},[t]),Math.round((((v=t.meta)==null?void 0:v.intent_match_score)||t.intent_match_score||0)*100);const c=s==="simple"?{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title,isSimple:!0}:{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title},u=P("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",n),f=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":(_=e.shadows)==null?void 0:_.small,"--admesh-shadow-md":(x=e.shadows)==null?void 0:x.medium,"--admesh-shadow-lg":(S=e.shadows)==null?void 0:S.large,"--admesh-spacing-sm":(j=e.spacing)==null?void 0:j.small,"--admesh-spacing-md":(M=e.spacing)==null?void 0:M.medium,"--admesh-spacing-lg":(E=e.spacing)==null?void 0:E.large,"--admesh-font-size-sm":(A=e.fontSize)==null?void 0:A.small,"--admesh-font-size-base":(h=e.fontSize)==null?void 0:h.base,"--admesh-font-size-lg":(k=e.fontSize)==null?void 0:k.large,"--admesh-font-size-title":(l=e.fontSize)==null?void 0:l.title,fontFamily:e.fontFamily,width:((w=(y=e.components)==null?void 0:y.productCard)==null?void 0:w.width)||"100%"}:{width:"100%"};return s==="simple"?o.jsxs("div",{className:P("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",n),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(D=e==null?void 0:e.components)==null?void 0:D.productCard,...d},"data-admesh-theme":e==null?void 0:e.mode,children:[o.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:J(t,F(t)),children:F(t)}),o.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[c.description," "]}),o.jsx(U,{adId:((N=t.meta)==null?void 0:N.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:o.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:c.ctaText})})]}):o.jsx("div",{className:u,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(C=e==null?void 0:e.components)==null?void 0:C.productCard,...d},"data-admesh-theme":e==null?void 0:e.mode,children:o.jsxs("div",{className:"h-full flex flex-col",style:f,children:[o.jsx("div",{className:"mb-1.5",children:o.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:J(t,F(t)),children:F(t)})}),o.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&o.jsx("img",{src:t.product_logo.url,alt:`${t.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:I=>{I.target.style.display="none"}}),o.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:c.title})]}),o.jsx("div",{className:"flex-shrink-0",children:o.jsx(U,{adId:((L=t.meta)==null?void 0:L.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:(($=t.meta)==null?void 0:$.intent_match_score)||t.intent_match_score,component:"product_card_cta"},children:o.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",o.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})]})})})]}),o.jsx("div",{className:"mb-3",children:o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:c.description})}),i&&t.features&&t.features.length>0&&o.jsxs("div",{className:"mb-2",children:[o.jsx("div",{className:"text-xs font-medium mb-1.5",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:"Key Features"}),o.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[t.features.slice(0,4).map((I,V)=>o.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:[o.jsx("svg",{className:"h-3 w-3 mr-0.5 inline",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),I]},V)),t.features.length>4&&o.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"]})]})]}),o.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:o.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[o.jsx("span",{children:"Sponsored"}),o.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};B.displayName="AdMeshProductCard";const se=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:i="",cardClassName:s="",onProductClick:a,showPricing:n=!0,showRatings:d=!0,showBrand:m=!0,showSource:p=!1,showShipping:b=!0,maxCards:c=10,cardWidth:u="md",theme:f="auto",borderRadius:v="md",shadow:_="sm"})=>{if(!t||t.length===0)return console.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const x=t.slice(0,c),S=()=>{switch(u){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"}},j=()=>{switch(v){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},M=()=>{switch(_){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"}},E=()=>f==="dark"?"bg-gray-900 text-white":f==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",A=l=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(l),h=l=>{const y=[],w=Math.floor(l),D=l%1!==0;for(let C=0;C<w;C++)y.push(o.jsx("span",{className:"text-yellow-400",children:"★"},C));D&&y.push(o.jsx("span",{className:"text-yellow-400",children:"☆"},"half"));const N=5-Math.ceil(l);for(let C=0;C<N;C++)y.push(o.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"☆"},`empty-${C}`));return y},k=l=>{if(a)a(l);else{const y=l.admesh_link||l.url;y&&window.open(y,"_blank","noopener,noreferrer")}};return(!products||products.length===0)&&(!t||t.length===0)?null:o.jsxs("div",{className:P("w-full",i),children:[r&&o.jsxs("div",{className:"mb-4",children:[o.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),o.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),o.jsxs("div",{className:"relative",children:[x.length===0?o.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):o.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:x.map(l=>{var w;const y=l.product_id||l.id||l.ad_id;return o.jsxs("div",{className:P(S(),j(),M(),E(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",s),onClick:()=>k(l),children:[o.jsxs("div",{className:"relative aspect-square w-full overflow-hidden",children:[l.image_url?o.jsx("img",{src:l.image_url,alt:l.title,className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy"}):o.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:o.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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&&l.discount_percentage&&l.discount_percentage>0&&o.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(l.discount_percentage),"%"]}),p&&l.source&&o.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs font-medium px-2 py-1 rounded",children:l.source.toUpperCase()})]}),o.jsxs("div",{className:"p-3",children:[m&&l.brand&&o.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 uppercase tracking-wide",children:l.brand}),o.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:l.title}),d&&l.rating&&o.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[o.jsx("div",{className:"flex text-sm",children:h(l.rating)}),o.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",l.review_count||0,")"]})]}),n&&l.price&&o.jsx("div",{className:"mb-2",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-lg font-bold text-gray-900 dark:text-white",children:A(l.price)}),l.original_price&&l.original_price>l.price&&o.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400 line-through",children:A(l.original_price)})]})}),b&&((w=l.shipping_info)==null?void 0:w.free_shipping_over_35)&&o.jsx("div",{className:"text-xs text-green-600 dark:text-green-400 font-medium",children:"Free shipping over $35"}),l.availability&&l.availability!=="unknown"&&o.jsx("div",{className:P("text-xs font-medium mt-1",l.availability==="in_stock"?"text-green-600 dark:text-green-400":"text-red-600 dark:text-red-400"),children:l.availability==="in_stock"?"In Stock":"Out of Stock"})]})]},y)})}),x.length>0&&o.jsxs(o.Fragment,{children:[o.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:o.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),o.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:o.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),o.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[o.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),o.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),o.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
673
|
+
`;let H=!1;const ne=()=>{g.useEffect(()=>{if(H)return;const t=document.createElement("style");return t.id="admesh-ui-sdk-styles",t.textContent=Ie,document.getElementById("admesh-ui-sdk-styles")||(document.head.appendChild(t),H=!0),()=>{const e=document.getElementById("admesh-ui-sdk-styles");e&&document.head.contains(e)&&(document.head.removeChild(e),H=!1)}},[])},F=(t,e={})=>{const r=t.intent_match_score||0,i=e.customLabels||{};return r>=.8?i.partnerRecommendation||"Smart Pick":r>=.6?i.partnerMatch||"Partner Recommendation":r>=.3?i.promotedOption||"Promoted Match":i.relatedOption||"Related"},J=(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."},Ae=(t=!0,e=!1)=>t?e?"These curated recommendations are from partners who compensate us for referrals.":"Personalized Sponsoreds: All results are from vetted partners who compensate us for qualified matches. We've ranked them based on relevance to your specific needs.":"Expanded Results: While these don't perfectly match your query, they're related solutions from our partner network. All partners compensate us for referrals.",Ne=(t,e=!1)=>{const r=t.intent_match_score||0;return e?"Promoted Match":r>=.8?"Smart Pick":r>=.6?"Partner Recommendation":"Promoted Match"},Ee=()=>"We've partnered with trusted providers to bring you relevant solutions. These partners compensate us for qualified referrals, which helps us keep our service free.",Re=t=>({"Top Match":"Smart Pick",Sponsored:"Smart Pick","Perfect Fit":"Smart Pick","Great Match":"Partner Recommendation",Recommended:"Partner Recommendation","Good Fit":"Promoted Match",Featured:"Promoted Match","Popular Choice":"Popular Choice","Premium Pick":"Premium Pick","Free Tier":"Free Tier","AI Powered":"AI Powered",Popular:"Popular",New:"New","Trial Available":"Trial Available","Related Option":"Related Option","Alternative Solution":"Alternative Solution","Expanded Match":"Expanded Match"})[t]||t,De=(t,e="button")=>{const r=t.recommendation_title||t.title;return e==="link"?r:t.trial_days&&t.trial_days>0?`Try ${r}`:"Learn More"},Pe=t=>t.some(e=>(e.intent_match_score||0)>=.8),Fe=(t=!1)=>t?"":"Recommendations ",B=({recommendation:t,theme:e,showBadges:r=!0,showFeatures:i=!1,variation:n="default",expandable:a=!1,className:s,style:d})=>{var v,_,b,S,T,M,E,A,f,k,l,y,w,R,N,C,L,$;ne();const[m,h]=g.useState(!1);g.useMemo(()=>{var X;const I=[],V=F(t);(V==="Smart Pick"||V==="Partner Recommendation"||V==="Promoted Match")&&I.push("Top Match"),t.trial_days&&t.trial_days>0&&I.push("Trial Available");const ge=["ai","artificial intelligence","machine learning","ml","automation"];return(((X=t.keywords)==null?void 0:X.some(z=>ge.some(be=>z.toLowerCase().includes(be))))||t.title.toLowerCase().includes("ai"))&&I.push("AI Powered"),t.badges&&t.badges.length>0&&t.badges.forEach(z=>{["Top Match","Free Tier","AI Powered","Popular","New","Trial Available"].includes(z)&&!I.includes(z)&&I.push(z)}),I},[t]),Math.round((((v=t.meta)==null?void 0:v.intent_match_score)||t.intent_match_score||0)*100);const c=n==="simple"?{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title,isSimple:!0}:{title:t.recommendation_title||t.title,description:t.recommendation_description||t.description||t.reason,ctaText:t.recommendation_title||t.title},p=P("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",s),u=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":(_=e.shadows)==null?void 0:_.small,"--admesh-shadow-md":(b=e.shadows)==null?void 0:b.medium,"--admesh-shadow-lg":(S=e.shadows)==null?void 0:S.large,"--admesh-spacing-sm":(T=e.spacing)==null?void 0:T.small,"--admesh-spacing-md":(M=e.spacing)==null?void 0:M.medium,"--admesh-spacing-lg":(E=e.spacing)==null?void 0:E.large,"--admesh-font-size-sm":(A=e.fontSize)==null?void 0:A.small,"--admesh-font-size-base":(f=e.fontSize)==null?void 0:f.base,"--admesh-font-size-lg":(k=e.fontSize)==null?void 0:k.large,"--admesh-font-size-title":(l=e.fontSize)==null?void 0:l.title,fontFamily:e.fontFamily,width:((w=(y=e.components)==null?void 0:y.productCard)==null?void 0:w.width)||"100%"}:{width:"100%"};return n==="simple"?o.jsxs("div",{className:P("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",s),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(R=e==null?void 0:e.components)==null?void 0:R.productCard,...d},"data-admesh-theme":e==null?void 0:e.mode,children:[o.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:J(t,F(t)),children:F(t)}),o.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[c.description," "]}),o.jsx(U,{adId:((N=t.meta)==null?void 0:N.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:o.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:c.ctaText})})]}):o.jsx("div",{className:p,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(C=e==null?void 0:e.components)==null?void 0:C.productCard,...d},"data-admesh-theme":e==null?void 0:e.mode,children:o.jsxs("div",{className:"h-full flex flex-col",style:u,children:[o.jsx("div",{className:"mb-1.5",children:o.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:J(t,F(t)),children:F(t)})}),o.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&o.jsx("img",{src:t.product_logo.url,alt:`${t.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:I=>{I.target.style.display="none"}}),o.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:c.title})]}),o.jsx("div",{className:"flex-shrink-0",children:o.jsx(U,{adId:((L=t.meta)==null?void 0:L.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:(($=t.meta)==null?void 0:$.intent_match_score)||t.intent_match_score,component:"product_card_cta"},children:o.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",o.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})]})})})]}),o.jsx("div",{className:"mb-3",children:o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:c.description})}),i&&t.features&&t.features.length>0&&o.jsxs("div",{className:"mb-2",children:[o.jsx("div",{className:"text-xs font-medium mb-1.5",style:{color:(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#666666"},children:"Key Features"}),o.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[t.features.slice(0,4).map((I,V)=>o.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:[o.jsx("svg",{className:"h-3 w-3 mr-0.5 inline",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),I]},V)),t.features.length>4&&o.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"]})]})]}),o.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:o.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[o.jsx("span",{children:"Sponsored"}),o.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};B.displayName="AdMeshProductCard";const se=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:i="",cardClassName:n="",onProductClick:a,showPricing:s=!0,showRatings:d=!0,showBrand:m=!0,showSource:h=!1,showShipping:x=!0,maxCards:c=10,cardWidth:p="md",theme:u="auto",borderRadius:v="md",shadow:_="sm"})=>{if(!t||t.length===0)return console.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const b=t.slice(0,c),S=()=>{switch(p){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"}},T=()=>{switch(v){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},M=()=>{switch(_){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"}},E=()=>u==="dark"?"bg-gray-900 text-white":u==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",A=l=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(l),f=l=>{const y=[],w=Math.floor(l),R=l%1!==0;for(let C=0;C<w;C++)y.push(o.jsx("span",{className:"text-yellow-400",children:"★"},C));R&&y.push(o.jsx("span",{className:"text-yellow-400",children:"☆"},"half"));const N=5-Math.ceil(l);for(let C=0;C<N;C++)y.push(o.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"☆"},`empty-${C}`));return y},k=l=>{if(a)a(l);else{const y=l.admesh_link||l.url;y&&window.open(y,"_blank","noopener,noreferrer")}};return(!products||products.length===0)&&(!t||t.length===0)?null:o.jsxs("div",{className:P("w-full",i),children:[r&&o.jsxs("div",{className:"mb-4",children:[o.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),o.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),o.jsxs("div",{className:"relative",children:[b.length===0?o.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):o.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:b.map(l=>{var w;const y=l.product_id||l.id||l.ad_id;return o.jsxs("div",{className:P(S(),T(),M(),E(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",n),onClick:()=>k(l),children:[o.jsxs("div",{className:"relative aspect-square w-full overflow-hidden",children:[l.image_url?o.jsx("img",{src:l.image_url,alt:l.title,className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy"}):o.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:o.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),s&&l.discount_percentage&&l.discount_percentage>0&&o.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(l.discount_percentage),"%"]}),h&&l.source&&o.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs font-medium px-2 py-1 rounded",children:l.source.toUpperCase()})]}),o.jsxs("div",{className:"p-3",children:[m&&l.brand&&o.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 uppercase tracking-wide",children:l.brand}),o.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:l.title}),d&&l.rating&&o.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[o.jsx("div",{className:"flex text-sm",children:f(l.rating)}),o.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",l.review_count||0,")"]})]}),s&&l.price&&o.jsx("div",{className:"mb-2",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-lg font-bold text-gray-900 dark:text-white",children:A(l.price)}),l.original_price&&l.original_price>l.price&&o.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400 line-through",children:A(l.original_price)})]})}),x&&((w=l.shipping_info)==null?void 0:w.free_shipping_over_35)&&o.jsx("div",{className:"text-xs text-green-600 dark:text-green-400 font-medium",children:"Free shipping over $35"}),l.availability&&l.availability!=="unknown"&&o.jsx("div",{className:P("text-xs font-medium mt-1",l.availability==="in_stock"?"text-green-600 dark:text-green-400":"text-red-600 dark:text-red-400"),children:l.availability==="in_stock"?"In Stock":"Out of Stock"})]})]},y)})}),b.length>0&&o.jsxs(o.Fragment,{children:[o.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:o.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),o.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:o.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),o.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[o.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),o.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),o.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
674
674
|
.scrollbar-hide {
|
|
675
675
|
-ms-overflow-style: none;
|
|
676
676
|
scrollbar-width: none;
|
|
@@ -684,5 +684,5 @@
|
|
|
684
684
|
-webkit-box-orient: vertical;
|
|
685
685
|
overflow: hidden;
|
|
686
686
|
}
|
|
687
|
-
`}})]})},Le=t=>{var s,a,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=((s=t.recommendations)==null?void 0:s.filter(d=>d&&d.admesh_link&&(d.title||d.recommendation_title)))||[],i=((a=t.recommendations)==null?void 0:a.length)===0;return r.length===0&&!i&&e.push("No valid recommendations found (missing admesh_link or title)"),{isValid:r.length>0,isEmpty:i,validCount:r.length,totalCount:((n=t.recommendations)==null?void 0:n.length)||0,warnings:e}},ae=({response:t,theme:e,className:r="",style:i={},onRecommendationClick:s,onLinkClick:a})=>{const n=Le(t);if(n.warnings.length>0&&console.warn("[AdMesh Summary Layout] Validation warnings:",n.warnings),n.isEmpty)return console.log("[AdMesh Summary Layout] Empty recommendations array - not rendering anything"),null;if(!n.isValid)return console.error("[AdMesh Summary Layout] Invalid response object"),null;const{layout_type:d="citation",citation_summary:m,recommendations:p=[],requires_summary:b=!0}=t;console.log(`[AdMesh Summary Layout] Rendering ${d} layout with ${n.validCount}/${n.totalCount} valid recommendations`);const c=()=>{switch(d){case"citation":return m&&b?o.jsx(G,{summaryText:m,recommendations:p,theme:e,onLinkClick:a}):o.jsxs("div",{className:"fallback-citation",children:[o.jsx("p",{className:"text-gray-700 dark:text-gray-300 mb-3",children:"Based on your query, I'd recommend checking out these options:"}),o.jsx(B,{recommendation:p[0],theme:e})]});case"product_cards":case"product":return o.jsx("div",{className:"product-cards-layout",children:p.slice(0,3).map((u,f)=>o.jsx(B,{recommendation:u,theme:e,className:"mb-4"},u.ad_id||`rec-${f}`))});case"ecommerce":return o.jsx(se,{recommendations:p.slice(0,3),theme:(e==null?void 0:e.mode)||"light"});default:return console.warn(`[AdMesh Summary Layout] Unknown layout type: ${d}`),m?o.jsx(G,{summaryText:m,recommendations:p,theme:e,onLinkClick:a}):o.jsx(B,{recommendation:p[0],theme:e})}};return o.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',...i},children:c()})},ie=({response:t,theme:e,className:r,style:i,onRecommendationClick:s,onLinkClick:a})=>t?t.recommendations&&Array.isArray(t.recommendations)&&t.recommendations.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):o.jsx(ae,{response:t,theme:e,className:r,style:i,onRecommendationClick:s,onLinkClick:a}):(console.error("[AdMeshLayout] response prop is required"),null),de=({recommendation:t,theme:e,variation:r="default",expandable:i=!1,className:s,style:a})=>{var c,u,f,v,_;const[n,d]=g.useState(!1),p=(()=>{const x=t.content_variations;return r==="question"&&(x!=null&&x.question)?{title:x.question.cta||t.recommendation_title||t.title,description:x.question.text,ctaText:x.question.cta||t.recommendation_title||t.title}:r==="statement"&&(x!=null&&x.statement)?{title:t.recommendation_title||t.title,description:x.statement.text,ctaText:x.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}})(),b=P("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":i&&(r==="question"||r==="statement")},s);return o.jsx("div",{className:b,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((u=(c=e==null?void 0:e.components)==null?void 0:c.inlineRecommendation)==null?void 0:u.width)||"100%",...(f=e==null?void 0:e.components)==null?void 0:f.productCard,...a},"data-admesh-theme":e==null?void 0:e.mode,children:o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&o.jsx("img",{src:t.product_logo.url,alt:`${t.title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:x=>{x.target.style.display="none"}}),o.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:p.title})]}),o.jsx("div",{className:"flex-shrink-0",children:o.jsx(U,{adId:((v=t.meta)==null?void 0:v.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((_=t.meta)==null?void 0:_.intent_match_score)||t.intent_match_score,component:"inline_card_cta"},children:o.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",o.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})]})})})]}),p.description&&o.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:p.description}),o.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[o.jsx("span",{children:"Sponsored"}),o.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};de.displayName="AdMeshInlineCard";const Ve={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},ze={"Top Match":"★","Free Tier":"◆","AI Powered":"◉",Popular:"▲",New:"●","Trial Available":"◈"},ce=({type:t,variant:e,size:r="md",className:i,style:s})=>{const a=e||Ve[t]||"secondary",n=ze[t],d=P("admesh-component","admesh-badge",`admesh-badge--${a}`,`admesh-badge--${r}`,i);return o.jsxs("span",{className:d,style:s,children:[n&&o.jsx("span",{className:"admesh-badge__icon",children:n}),o.jsx("span",{className:"admesh-badge__text",children:t})]})};ce.displayName="AdMeshBadge";function Be(t,e,r){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...r}}function Ue(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function $e(t){const e=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth,s=e.height,a=e.width;if(s===0||a===0)return 0;const n=Math.max(0,e.top),d=Math.min(r,e.bottom),m=Math.max(0,e.left),p=Math.min(i,e.right),b=Math.max(0,d-n),c=Math.max(0,p-m),u=b*c,f=s*a;return f>0?u/f:0}function te(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,i=e-t;return i<=0?100:Math.min(100,r/i*100)}function Oe(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,i=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+i}}function qe(t){const e=t.getBoundingClientRect(),r=Oe(t),i=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,a=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Ue(i),viewportWidth:i,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:r.top,adPositionLeft:r.left,isDarkMode:a,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function He(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function We(){return`batch_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Ke(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function O(t=new Date){return t.toISOString()}function Ge(t){return t.length===0?0:t.reduce((r,i)=>r+i,0)/t.length}function re(t,e){let r;return function(...s){r||(t(...s),r=!0,setTimeout(()=>r=!1,e))}}async function Ye(t,e,r=3,i=1e3){let s=null;for(let a=0;a<r;a++){try{const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok)return!0;s=new Error(`HTTP ${n.status}: ${n.statusText}`)}catch(n){s=n}a<r-1&&await new Promise(n=>setTimeout(n,i*Math.pow(2,a)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",s),!1}async function Je(t,e,r,i=3,s=1e3){if(t.length===0)return!0;const a={batchId:We(),sessionId:e,createdAt:O(),events:t,eventCount:t.length};let n=null;for(let d=0;d<i;d++){try{const m=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(m.ok)return!0;n=new Error(`HTTP ${m.status}: ${m.statusText}`)}catch(m){n=m}d<i-1&&await new Promise(m=>setTimeout(m,s*Math.pow(2,d)))}return console.error("[AdMesh Viewability] Failed to send analytics batch:",n),!1}const Qe={enabled:!0,apiEndpoint:"https://api.useadmesh.com/analytics/ui-sdk/viewability",enableBatching:!0,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!0,maxRetries:3,retryDelay:1e3};let Q=Qe;const Xe=t=>{Q={...Q,...t}};function le({adId:t,productId:e,offerId:r,agentId:i,elementRef:s,config:a}){const n={...Q,...a},d=g.useRef(He()),[m,p]=g.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:O(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:n.enabled}),b=g.useRef(null),c=g.useRef(null),u=g.useRef(null),f=g.useRef(null),v=g.useRef(null),_=g.useRef([]),x=g.useRef([]),S=g.useRef(null),j=g.useCallback((h,k)=>{n.debug&&console.log(`[AdMesh Viewability] ${h}`,k)},[n.debug]),M=g.useCallback(async(h,k)=>{if(!n.enabled||!s.current||!b.current)return;const l=qe(s.current),y={eventType:h,timestamp:O(),sessionId:d.current,adId:t,productId:e,offerId:r,agentId:i,timeMetrics:m.timeMetrics,engagementMetrics:m.engagementMetrics,contextMetrics:l,mrcStandards:b.current,isViewable:m.isViewable,metadata:k};j(`Event: ${h}`,y),n.onEvent&&n.onEvent(y),n.enableBatching?(x.current.push(y),x.current.length>=n.batchSize?await E():(S.current&&clearTimeout(S.current),S.current=setTimeout(E,n.batchTimeout))):await Ye(y,n.apiEndpoint,n.maxRetries,n.retryDelay)},[n,t,e,r,i,s,m,j]),E=g.useCallback(async()=>{if(x.current.length===0)return;const h=[...x.current];x.current=[],S.current&&(clearTimeout(S.current),S.current=null),await Je(h,d.current,n.apiEndpoint,n.maxRetries,n.retryDelay)&&n.onBatchSent&&n.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:d.current,createdAt:O(),events:h,eventCount:h.length})},[n]),A=g.useCallback(re(()=>{if(!s.current)return;const h=$e(s.current),k=Date.now(),l=new Date(m.timeMetrics.loadedAt).getTime();p(y=>{const w={...y};h>0&&_.current.push(h);const D=y.isVisible,N=h>0;if(N&&!D)c.current=k,w.engagementMetrics.viewportEnterCount++,w.timeMetrics.timeToFirstVisible||(w.timeMetrics.timeToFirstVisible=k-l,w.engagementMetrics.scrollDepthAtFirstVisible=te(),M("ad_visible"));else if(!N&&D){if(c.current){const C=k-c.current;w.timeMetrics.totalVisibleDuration+=C,c.current=null}w.engagementMetrics.viewportExitCount++,M("ad_hidden")}else if(N&&D&&c.current){const C=k-c.current;w.timeMetrics.totalVisibleDuration+=C,c.current=k}if(w.isVisible=N,w.visibilityPercentage=h,h>w.engagementMetrics.maxVisibilityPercentage&&(w.engagementMetrics.maxVisibilityPercentage=h),_.current.length>0&&(w.engagementMetrics.averageVisibilityPercentage=Ge(_.current)),b.current){const C=y.isViewable,L=Ke(h,w.timeMetrics.totalVisibleDuration,b.current);if(L&&!C)w.isViewable=!0,w.timeMetrics.timeToViewable=k-l,u.current=k,M("ad_viewable");else if(L&&C&&u.current){const $=k-u.current;w.timeMetrics.totalViewableDuration+=$,u.current=k}}return w.engagementMetrics.currentScrollDepth=te(),w})},100),[s,m.timeMetrics.loadedAt,M]);return g.useEffect(()=>{if(!s.current)return;const h=s.current.getBoundingClientRect();b.current=Be(h.width,h.height,n.mrcStandards),j("Initialized MRC standards",b.current),M("ad_loaded")},[s,n.mrcStandards,j,M]),g.useEffect(()=>{if(!n.enabled||!s.current)return;const h=new IntersectionObserver(k=>{k.forEach(()=>{A()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return h.observe(s.current),()=>{h.disconnect()}},[n.enabled,s,A]),g.useEffect(()=>{if(!n.enabled)return;const h=re(()=>{A()},100);return window.addEventListener("scroll",h,{passive:!0}),()=>window.removeEventListener("scroll",h)},[n.enabled,A]),g.useEffect(()=>{if(!n.enabled||!s.current)return;const h=s.current,k=()=>{f.current=Date.now(),p(y=>({...y,engagementMetrics:{...y.engagementMetrics,hoverCount:y.engagementMetrics.hoverCount+1}})),M("ad_hover_start")},l=()=>{if(f.current){const y=Date.now()-f.current;p(w=>({...w,timeMetrics:{...w.timeMetrics,totalHoverDuration:w.timeMetrics.totalHoverDuration+y}})),f.current=null,M("ad_hover_end",{hoverDuration:y})}};return h.addEventListener("mouseenter",k),h.addEventListener("mouseleave",l),()=>{h.removeEventListener("mouseenter",k),h.removeEventListener("mouseleave",l)}},[n.enabled,s,M]),g.useEffect(()=>{if(!n.enabled||!s.current)return;const h=s.current,k=()=>{v.current=Date.now(),M("ad_focus")},l=()=>{if(v.current){const y=Date.now()-v.current;p(w=>({...w,timeMetrics:{...w.timeMetrics,totalFocusDuration:w.timeMetrics.totalFocusDuration+y}})),v.current=null,M("ad_blur",{focusDuration:y})}};return h.addEventListener("focus",k),h.addEventListener("blur",l),()=>{h.removeEventListener("focus",k),h.removeEventListener("blur",l)}},[n.enabled,s,M]),g.useEffect(()=>{if(!n.enabled||!s.current)return;const h=s.current,k=()=>{p(l=>({...l,engagementMetrics:{...l.engagementMetrics,wasClicked:!0}})),M("ad_click")};return h.addEventListener("click",k),()=>{h.removeEventListener("click",k)}},[n.enabled,s,M]),g.useEffect(()=>()=>{const h=Date.now(),k=new Date(m.timeMetrics.loadedAt).getTime(),l=h-k;p(y=>({...y,timeMetrics:{...y.timeMetrics,sessionDuration:l}})),M("ad_unloaded",{sessionDuration:l}),E()},[]),m}const me=({adId:t,productId:e,offerId:r,agentId:i,children:s,config:a,className:n,style:d,onViewabilityChange:m,onVisible:p,onViewable:b,onClick:c})=>{const u=g.useRef(null),f=le({adId:t,productId:e,offerId:r,agentId:i,elementRef:u,config:a}),v=g.useRef(f.isViewable);g.useEffect(()=>{f.isViewable!==v.current&&(v.current=f.isViewable,m&&m(f.isViewable),f.isViewable&&b&&b())},[f.isViewable,m,b]);const _=g.useRef(f.isVisible);g.useEffect(()=>{f.isVisible!==_.current&&(_.current=f.isVisible,f.isVisible&&p&&p())},[f.isVisible,p]);const x=S=>{c&&c()};return o.jsx("div",{ref:u,className:n,style:d,onClick:x,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":f.isViewable,"data-is-visible":f.isVisible,"data-visibility-percentage":f.visibilityPercentage.toFixed(2),children:s})};me.displayName="AdMeshViewabilityTracker";const W="admesh_session_id",K="admesh_session_timestamp",Ze=1800*1e3;class ue{constructor(e=!1){T(this,"debug");this.debug=e}generateSessionId(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}createSession(){const e=this.generateSessionId();return this.storeSessionId(e),this.debug&&console.log("[SessionManager] Created session:",e),e}storeSessionId(e){try{typeof window<"u"&&window.localStorage&&(localStorage.setItem(W,e),localStorage.setItem(K,Date.now().toString()))}catch(r){this.debug&&console.warn("[SessionManager] Failed to store session ID:",r)}}getStoredSessionId(){try{if(typeof window>"u"||!window.localStorage)return null;const e=localStorage.getItem(W),r=localStorage.getItem(K);return!e||!r?null:Date.now()-parseInt(r,10)>Ze?(this.debug&&console.log("[SessionManager] Session expired"),this.clearStoredSessionId(),null):e}catch(e){return this.debug&&console.warn("[SessionManager] Failed to get stored session ID:",e),null}}clearStoredSessionId(){try{typeof window<"u"&&window.localStorage&&(localStorage.removeItem(W),localStorage.removeItem(K))}catch(e){this.debug&&console.warn("[SessionManager] Failed to clear session ID:",e)}}closeSession(e){this.debug&&console.log("[SessionManager] Closing session:",e),this.clearStoredSessionId()}isSessionValid(e){return this.getStoredSessionId()===e}}class he{constructor(e){T(this,"apiKey");T(this,"apiBaseUrl");T(this,"debug");this.apiKey=e.apiKey,this.apiBaseUrl=e.apiBaseUrl||"https://api.useadmesh.com",this.debug=e.debug||!1}async fetchRecommendations(e){try{const r=`${this.apiBaseUrl}/agent/recommend`,i={query:e.query,format:e.format||"auto",...e.previous_query&&{previous_query:e.previous_query},...e.previous_summary&&{previous_summary:e.previous_summary},...e.session_id&&{session_id:e.session_id},...e.is_fallback_allowed!==void 0&&{is_fallback_allowed:e.is_fallback_allowed}};this.debug&&(console.log("[Fetcher] Calling endpoint:",r),console.log("[Fetcher] Payload:",i));const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!s.ok){const d=(await s.json().catch(()=>({}))).detail||`HTTP ${s.status}`;throw new Error(`Failed to fetch recommendations: ${d}`)}const a=await s.json();return this.debug&&console.log("[Fetcher] Response:",a),a}catch(r){throw this.debug&&console.error("[Fetcher] Error fetching recommendations:",r),r}}}class pe{constructor(e){T(this,"debug");T(this,"firedExposures",new Set);this.debug=e.debug||!1}fireExposure(e,r,i){const s=`${i}_${r}`;if(this.firedExposures.has(s)){this.debug&&console.log("[Tracker] Exposure already fired for:",r);return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(a=>{this.debug&&console.warn("[Tracker] Failed to fire exposure:",a)}),this.debug&&console.log("[Tracker] Fired exposure for:",r)}catch(a){this.debug&&console.error("[Tracker] Error firing exposure:",a)}}fireClick(e,r,i){try{fetch(e,{method:"GET",keepalive:!0}).catch(s=>{this.debug&&console.warn("[Tracker] Failed to fire click:",s)}),this.debug&&console.log("[Tracker] Fired click for:",r)}catch(s){this.debug&&console.error("[Tracker] Error firing click:",s)}}fireConversion(e,r,i){try{fetch(e,{method:"GET",keepalive:!0}).catch(s=>{this.debug&&console.warn("[Tracker] Failed to fire conversion:",s)}),this.debug&&console.log("[Tracker] Fired conversion for:",r)}catch(s){this.debug&&console.error("[Tracker] Error firing conversion:",s)}}clearFiredExposures(){this.firedExposures.clear(),this.debug&&console.log("[Tracker] Cleared fired exposures")}}class fe{constructor(e=!1){T(this,"debug");T(this,"roots",new Map);this.debug=e}async render(e){var r,i,s,a;try{const n=document.getElementById(e.containerId);if(!n)throw new Error(`Container with ID "${e.containerId}" not found`);this.debug&&console.log("[Renderer] Rendering recommendations in container:",e.containerId);const d=this.roots.get(e.containerId);d&&d.unmount();const m=we.createRoot(n),p=(b,c)=>{var f,v;const u=(v=(f=e.response.response)==null?void 0:f.recommendations)==null?void 0:v.find(_=>{var x;return((x=_.meta)==null?void 0:x.ad_id)===b||_.ad_id===b});u!=null&&u.click_url&&e.tracker.fireClick(u.click_url,b,e.sessionId),e.onRecommendationClick&&e.onRecommendationClick(b,c),window.open(c,"_blank")};m.render(o.jsx(ie,{response:{layout_type:(r=e.response.response)==null?void 0:r.layout_type,citation_summary:(i=e.response.response)==null?void 0:i.summary,recommendations:((s=e.response.response)==null?void 0:s.recommendations)||[],requires_summary:!!((a=e.response.response)!=null&&a.summary)},theme:e.theme,onRecommendationClick:b=>{var f;const c=((f=b.meta)==null?void 0:f.ad_id)||b.ad_id||"",u=b.admesh_link||"";p(c,u)}})),this.roots.set(e.containerId,m),this.debug&&console.log("[Renderer] Rendered successfully")}catch(n){throw this.debug&&console.error("[Renderer] Error rendering:",n),n}}unmount(e){const r=this.roots.get(e);r&&(r.unmount(),this.roots.delete(e),this.debug&&console.log("[Renderer] Unmounted container:",e))}unmountAll(){for(const[e,r]of this.roots.entries())r.unmount(),this.debug&&console.log("[Renderer] Unmounted container:",e);this.roots.clear()}}class et{constructor(e){T(this,"config");T(this,"sessionManager");T(this,"fetcher");T(this,"renderer");T(this,"tracker");T(this,"currentSessionId",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiBaseUrl:e.apiBaseUrl||"https://api.useadmesh.com",debug:e.debug||!1,...e},this.sessionManager=new ue(this.config.debug),this.fetcher=new he(this.config),this.renderer=new fe(this.config.debug),this.tracker=new pe(this.config),this.currentSessionId=this.sessionManager.getStoredSessionId(),this.config.debug&&this.currentSessionId&&console.log("[AdMeshSDK] Restored session:",this.currentSessionId)}async showRecommendations(e){var r,i;try{this.config.debug&&console.log("[AdMeshSDK] Fetching recommendations for query:",e.query),this.currentSessionId||(this.currentSessionId=this.sessionManager.createSession(),this.config.debug&&console.log("[AdMeshSDK] Created new session:",this.currentSessionId));const s=await this.fetcher.fetchRecommendations({query:e.query,format:e.format||"auto",previous_query:e.previousQuery,previous_summary:e.previousSummary,session_id:this.currentSessionId,is_fallback_allowed:e.isFallbackAllowed!==!1});if(this.config.debug&&console.log("[AdMeshSDK] Received recommendations:",s),await this.renderer.render({containerId:e.containerId,response:s,theme:e.theme||this.config.theme,onRecommendationClick:e.onRecommendationClick,tracker:this.tracker,sessionId:this.currentSessionId}),(r=s.response)!=null&&r.recommendations){for(const a of s.response.recommendations)if(a.exposure_url){const n=((i=a.meta)==null?void 0:i.ad_id)||a.ad_id||"";this.tracker.fireExposure(a.exposure_url,n,this.currentSessionId)}}}catch(s){throw console.error("[AdMeshSDK] Error showing recommendations:",s),s}}closeSession(){this.currentSessionId&&(this.config.debug&&console.log("[AdMeshSDK] Closing session:",this.currentSessionId),this.sessionManager.closeSession(this.currentSessionId),this.currentSessionId=null)}getSessionId(){return this.currentSessionId}createNewSession(){return this.currentSessionId=this.sessionManager.createSession(),this.config.debug&&console.log("[AdMeshSDK] Created new session:",this.currentSessionId),this.currentSessionId}setSessionId(e){this.currentSessionId=e,this.sessionManager.storeSessionId(e),this.config.debug&&console.log("[AdMeshSDK] Set session ID:",e)}}const R=(t={})=>{const e={mode:"light",primaryColor:"#000000",secondaryColor:"#666666",accentColor:"#000000",backgroundColor:"#ffffff",surfaceColor:"#ffffff",borderColor:"#e5e7eb",textColor:"#000000",textSecondaryColor:"#666666",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:{small:"12px",base:"14px",large:"16px",title:"18px"},borderRadius:"8px",spacing:{small:"4px",medium:"8px",large:"16px"},shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.1)",medium:"0 4px 6px rgba(0, 0, 0, 0.1)",large:"0 10px 15px rgba(0, 0, 0, 0.1)"},icons:{expandIcon:"▼",collapseIcon:"▲",starIcon:"★",checkIcon:"✓",arrowIcon:"→"},gradients:{primary:"#000000",secondary:"#666666",accent:"#000000"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"},card:{width:"auto"},button:{width:"auto"}}},r={...e,...t,fontSize:{...e.fontSize,...t.fontSize},spacing:{...e.spacing,...t.spacing},shadows:{...e.shadows,...t.shadows},icons:{...e.icons,...t.icons},components:{...e.components,...t.components}};return ot(r)},tt=(t={})=>R({...{mode:"dark",primaryColor:"#ffffff",secondaryColor:"#9ca3af",accentColor:"#ffffff",backgroundColor:"#000000",surfaceColor:"#111111",borderColor:"#333333",textColor:"#ffffff",textSecondaryColor:"#9ca3af",shadows:{small:"0 1px 3px rgba(255, 255, 255, 0.1)",medium:"0 4px 6px rgba(255, 255, 255, 0.1)",large:"0 10px 15px rgba(255, 255, 255, 0.1)"},gradients:{primary:"#ffffff",secondary:"#9ca3af",accent:"#ffffff"}},...t}),rt={get minimal(){return R({primaryColor:"#000000",secondaryColor:"#666666",borderRadius:"4px",shadows:{small:"none",medium:"0 1px 3px rgba(0, 0, 0, 0.1)",large:"0 2px 6px rgba(0, 0, 0, 0.1)"},gradients:{primary:"#000000",secondary:"#666666",accent:"#000000"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})},get vibrant(){return R({primaryColor:"#8b5cf6",secondaryColor:"#06b6d4",accentColor:"#f59e0b",borderRadius:"12px",gradients:{primary:"#8b5cf6",secondary:"#06b6d4",accent:"#f59e0b"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})},get corporate(){return R({primaryColor:"#1e40af",secondaryColor:"#059669",backgroundColor:"#f8fafc",surfaceColor:"#ffffff",borderColor:"#cbd5e1",borderRadius:"6px",fontFamily:'"Inter", -apple-system, BlinkMacSystemFont, sans-serif',components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})},get highContrast(){return R({primaryColor:"#000000",secondaryColor:"#ffffff",backgroundColor:"#ffffff",surfaceColor:"#f5f5f5",borderColor:"#000000",textColor:"#000000",textSecondaryColor:"#333333",borderRadius:"0px",shadows:{small:"none",medium:"0 0 0 2px #000000",large:"0 0 0 3px #000000"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})}},ot=(t={})=>{const e=t.components||{},r={productCard:{width:"100%",...e.productCard},citationUnit:{width:"100%",...e.citationUnit},inlineRecommendation:{width:"100%",...e.inlineRecommendation},expandableUnit:{width:"100%",...e.expandableUnit},compareTable:{width:"100%",...e.compareTable},card:{width:"auto",...e.card},button:{width:"auto",...e.button}};return{...t,components:{...e,...r}}},nt=(...t)=>{const e=R();return t.reduce((r,i)=>i?{...r,...i,mode:i.mode||r.mode}:r,e)},st=t=>{var r,i,s,a,n,d;const e=getComputedStyle(t);return{primaryColor:((r=e.getPropertyValue("--admesh-primary-color"))==null?void 0:r.trim())||void 0,secondaryColor:((i=e.getPropertyValue("--admesh-secondary-color"))==null?void 0:i.trim())||void 0,backgroundColor:((s=e.getPropertyValue("--admesh-background-color"))==null?void 0:s.trim())||void 0,textColor:((a=e.getPropertyValue("--admesh-text-color"))==null?void 0:a.trim())||void 0,borderRadius:((n=e.getPropertyValue("--admesh-border-radius"))==null?void 0:n.trim())||void 0,fontFamily:((d=e.getPropertyValue("--admesh-font-family"))==null?void 0:d.trim())||void 0}},at="0.2.1",it={trackingEnabled:!0,debug:!1,theme:{mode:"light",accentColor:"#2563eb"}};exports.AdMeshBadge=ce;exports.AdMeshEcommerceCards=se;exports.AdMeshInlineCard=de;exports.AdMeshLayout=ie;exports.AdMeshLinkTracker=U;exports.AdMeshProductCard=B;exports.AdMeshRecommendationFetcher=he;exports.AdMeshRenderer=fe;exports.AdMeshSDK=et;exports.AdMeshSessionManager=ue;exports.AdMeshSummaryLayout=ae;exports.AdMeshSummaryUnit=G;exports.AdMeshTracker=pe;exports.AdMeshViewabilityTracker=me;exports.DEFAULT_CONFIG=it;exports.VERSION=at;exports.buildAdMeshLink=Te;exports.createAdMeshTheme=R;exports.createDarkTheme=tt;exports.extractTrackingData=je;exports.getBadgeText=De;exports.getCtaText=Re;exports.getInlineDisclosure=Ne;exports.getInlineTooltip=Ee;exports.getLabelTooltip=J;exports.getPoweredByText=Fe;exports.getRecommendationLabel=F;exports.getSectionDisclosure=Ae;exports.hasHighQualityMatches=Pe;exports.mergeThemes=nt;exports.setAdMeshTrackerConfig=Ce;exports.setViewabilityTrackerConfig=Xe;exports.themeFromCSSProperties=st;exports.themePresets=rt;exports.useAdMeshStyles=ne;exports.useAdMeshTracker=oe;exports.useViewabilityTracker=le;
|
|
687
|
+
`}})]})},Le=t=>{var n,a,s;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=((n=t.recommendations)==null?void 0:n.filter(d=>d&&d.admesh_link&&(d.title||d.recommendation_title)))||[],i=((a=t.recommendations)==null?void 0:a.length)===0;return r.length===0&&!i&&e.push("No valid recommendations found (missing admesh_link or title)"),{isValid:r.length>0,isEmpty:i,validCount:r.length,totalCount:((s=t.recommendations)==null?void 0:s.length)||0,warnings:e}},ae=({response:t,theme:e,className:r="",style:i={},onRecommendationClick:n,onLinkClick:a})=>{const s=Le(t);if(s.warnings.length>0&&console.warn("[AdMesh Summary Layout] Validation warnings:",s.warnings),s.isEmpty)return console.log("[AdMesh Summary Layout] Empty recommendations array - not rendering anything"),null;if(!s.isValid)return console.error("[AdMesh Summary Layout] Invalid response object"),null;const{layout_type:d="citation",citation_summary:m,recommendations:h=[],requires_summary:x=!0}=t;console.log(`[AdMesh Summary Layout] Rendering ${d} layout with ${s.validCount}/${s.totalCount} valid recommendations`);const c=()=>{switch(d){case"citation":return m&&x?o.jsx(G,{summaryText:m,recommendations:h,theme:e,onLinkClick:a}):o.jsxs("div",{className:"fallback-citation",children:[o.jsx("p",{className:"text-gray-700 dark:text-gray-300 mb-3",children:"Based on your query, I'd recommend checking out these options:"}),o.jsx(B,{recommendation:h[0],theme:e})]});case"product_cards":case"product":return o.jsx("div",{className:"product-cards-layout",children:h.slice(0,3).map((p,u)=>o.jsx(B,{recommendation:p,theme:e,className:"mb-4"},p.ad_id||`rec-${u}`))});case"ecommerce":return o.jsx(se,{recommendations:h.slice(0,3),theme:(e==null?void 0:e.mode)||"light"});default:return console.warn(`[AdMesh Summary Layout] Unknown layout type: ${d}`),m?o.jsx(G,{summaryText:m,recommendations:h,theme:e,onLinkClick:a}):o.jsx(B,{recommendation:h[0],theme:e})}};return o.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',...i},children:c()})},ie=({response:t,theme:e,className:r,style:i,onRecommendationClick:n,onLinkClick:a})=>t?t.recommendations&&Array.isArray(t.recommendations)&&t.recommendations.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):o.jsx(ae,{response:t,theme:e,className:r,style:i,onRecommendationClick:n,onLinkClick:a}):(console.error("[AdMeshLayout] response prop is required"),null),de=({recommendation:t,theme:e,variation:r="default",expandable:i=!1,className:n,style:a})=>{var c,p,u,v,_;const[s,d]=g.useState(!1),h=(()=>{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}})(),x=P("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":i&&(r==="question"||r==="statement")},n);return o.jsx("div",{className:x,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((p=(c=e==null?void 0:e.components)==null?void 0:c.inlineRecommendation)==null?void 0:p.width)||"100%",...(u=e==null?void 0:e.components)==null?void 0:u.productCard,...a},"data-admesh-theme":e==null?void 0:e.mode,children:o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.product_logo&&o.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"}}),o.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:h.title})]}),o.jsx("div",{className:"flex-shrink-0",children:o.jsx(U,{adId:((v=t.meta)==null?void 0:v.ad_id)||t.ad_id||"",admeshLink:t.admesh_link,productId:t.product_id,trackingData:{title:t.title,matchScore:((_=t.meta)==null?void 0:_.intent_match_score)||t.intent_match_score,component:"inline_card_cta"},children:o.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",o.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})]})})})]}),h.description&&o.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:h.description}),o.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[o.jsx("span",{children:"Sponsored"}),o.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};de.displayName="AdMeshInlineCard";const Ve={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},ze={"Top Match":"★","Free Tier":"◆","AI Powered":"◉",Popular:"▲",New:"●","Trial Available":"◈"},ce=({type:t,variant:e,size:r="md",className:i,style:n})=>{const a=e||Ve[t]||"secondary",s=ze[t],d=P("admesh-component","admesh-badge",`admesh-badge--${a}`,`admesh-badge--${r}`,i);return o.jsxs("span",{className:d,style:n,children:[s&&o.jsx("span",{className:"admesh-badge__icon",children:s}),o.jsx("span",{className:"admesh-badge__text",children:t})]})};ce.displayName="AdMeshBadge";function Be(t,e,r){const n=t*e>242500;return{...{visibilityThreshold:n?.3:.5,minimumDuration:1e3,isLargeAd:n},...r}}function Ue(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function $e(t){const e=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth,n=e.height,a=e.width;if(n===0||a===0)return 0;const s=Math.max(0,e.top),d=Math.min(r,e.bottom),m=Math.max(0,e.left),h=Math.min(i,e.right),x=Math.max(0,d-s),c=Math.max(0,h-m),p=x*c,u=n*a;return u>0?p/u:0}function te(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,i=e-t;return i<=0?100:Math.min(100,r/i*100)}function Oe(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,i=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+i}}function qe(t){const e=t.getBoundingClientRect(),r=Oe(t),i=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight,a=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Ue(i),viewportWidth:i,viewportHeight:n,adWidth:e.width,adHeight:e.height,adPositionTop:r.top,adPositionLeft:r.left,isDarkMode:a,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function He(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function We(){return`batch_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Ke(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function O(t=new Date){return t.toISOString()}function Ge(t){return t.length===0?0:t.reduce((r,i)=>r+i,0)/t.length}function re(t,e){let r;return function(...n){r||(t(...n),r=!0,setTimeout(()=>r=!1,e))}}async function Ye(t,e,r=3,i=1e3){let n=null;for(let a=0;a<r;a++){try{const s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(s.ok)return!0;n=new Error(`HTTP ${s.status}: ${s.statusText}`)}catch(s){n=s}a<r-1&&await new Promise(s=>setTimeout(s,i*Math.pow(2,a)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",n),!1}async function Je(t,e,r,i=3,n=1e3){if(t.length===0)return!0;const a={batchId:We(),sessionId:e,createdAt:O(),events:t,eventCount:t.length};let s=null;for(let d=0;d<i;d++){try{const m=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(m.ok)return!0;s=new Error(`HTTP ${m.status}: ${m.statusText}`)}catch(m){s=m}d<i-1&&await new Promise(m=>setTimeout(m,n*Math.pow(2,d)))}return console.error("[AdMesh Viewability] Failed to send analytics batch:",s),!1}const Qe={enabled:!0,apiEndpoint:"https://api.useadmesh.com/analytics/ui-sdk/viewability",enableBatching:!0,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!0,maxRetries:3,retryDelay:1e3};let Q=Qe;const Xe=t=>{Q={...Q,...t}};function le({adId:t,productId:e,offerId:r,agentId:i,elementRef:n,config:a}){const s={...Q,...a},d=g.useRef(He()),[m,h]=g.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:O(),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}),x=g.useRef(null),c=g.useRef(null),p=g.useRef(null),u=g.useRef(null),v=g.useRef(null),_=g.useRef([]),b=g.useRef([]),S=g.useRef(null),T=g.useCallback((f,k)=>{s.debug&&console.log(`[AdMesh Viewability] ${f}`,k)},[s.debug]),M=g.useCallback(async(f,k)=>{if(!s.enabled||!n.current||!x.current)return;const l=qe(n.current),y={eventType:f,timestamp:O(),sessionId:d.current,adId:t,productId:e,offerId:r,agentId:i,timeMetrics:m.timeMetrics,engagementMetrics:m.engagementMetrics,contextMetrics:l,mrcStandards:x.current,isViewable:m.isViewable,metadata:k};T(`Event: ${f}`,y),s.onEvent&&s.onEvent(y),s.enableBatching?(b.current.push(y),b.current.length>=s.batchSize?await E():(S.current&&clearTimeout(S.current),S.current=setTimeout(E,s.batchTimeout))):await Ye(y,s.apiEndpoint,s.maxRetries,s.retryDelay)},[s,t,e,r,i,n,m,T]),E=g.useCallback(async()=>{if(b.current.length===0)return;const f=[...b.current];b.current=[],S.current&&(clearTimeout(S.current),S.current=null),await Je(f,d.current,s.apiEndpoint,s.maxRetries,s.retryDelay)&&s.onBatchSent&&s.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:d.current,createdAt:O(),events:f,eventCount:f.length})},[s]),A=g.useCallback(re(()=>{if(!n.current)return;const f=$e(n.current),k=Date.now(),l=new Date(m.timeMetrics.loadedAt).getTime();h(y=>{const w={...y};f>0&&_.current.push(f);const R=y.isVisible,N=f>0;if(N&&!R)c.current=k,w.engagementMetrics.viewportEnterCount++,w.timeMetrics.timeToFirstVisible||(w.timeMetrics.timeToFirstVisible=k-l,w.engagementMetrics.scrollDepthAtFirstVisible=te(),M("ad_visible"));else if(!N&&R){if(c.current){const C=k-c.current;w.timeMetrics.totalVisibleDuration+=C,c.current=null}w.engagementMetrics.viewportExitCount++,M("ad_hidden")}else if(N&&R&&c.current){const C=k-c.current;w.timeMetrics.totalVisibleDuration+=C,c.current=k}if(w.isVisible=N,w.visibilityPercentage=f,f>w.engagementMetrics.maxVisibilityPercentage&&(w.engagementMetrics.maxVisibilityPercentage=f),_.current.length>0&&(w.engagementMetrics.averageVisibilityPercentage=Ge(_.current)),x.current){const C=y.isViewable,L=Ke(f,w.timeMetrics.totalVisibleDuration,x.current);if(L&&!C)w.isViewable=!0,w.timeMetrics.timeToViewable=k-l,p.current=k,M("ad_viewable");else if(L&&C&&p.current){const $=k-p.current;w.timeMetrics.totalViewableDuration+=$,p.current=k}}return w.engagementMetrics.currentScrollDepth=te(),w})},100),[n,m.timeMetrics.loadedAt,M]);return g.useEffect(()=>{if(!n.current)return;const f=n.current.getBoundingClientRect();x.current=Be(f.width,f.height,s.mrcStandards),T("Initialized MRC standards",x.current),M("ad_loaded")},[n,s.mrcStandards,T,M]),g.useEffect(()=>{if(!s.enabled||!n.current)return;const f=new IntersectionObserver(k=>{k.forEach(()=>{A()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return f.observe(n.current),()=>{f.disconnect()}},[s.enabled,n,A]),g.useEffect(()=>{if(!s.enabled)return;const f=re(()=>{A()},100);return window.addEventListener("scroll",f,{passive:!0}),()=>window.removeEventListener("scroll",f)},[s.enabled,A]),g.useEffect(()=>{if(!s.enabled||!n.current)return;const f=n.current,k=()=>{u.current=Date.now(),h(y=>({...y,engagementMetrics:{...y.engagementMetrics,hoverCount:y.engagementMetrics.hoverCount+1}})),M("ad_hover_start")},l=()=>{if(u.current){const y=Date.now()-u.current;h(w=>({...w,timeMetrics:{...w.timeMetrics,totalHoverDuration:w.timeMetrics.totalHoverDuration+y}})),u.current=null,M("ad_hover_end",{hoverDuration:y})}};return f.addEventListener("mouseenter",k),f.addEventListener("mouseleave",l),()=>{f.removeEventListener("mouseenter",k),f.removeEventListener("mouseleave",l)}},[s.enabled,n,M]),g.useEffect(()=>{if(!s.enabled||!n.current)return;const f=n.current,k=()=>{v.current=Date.now(),M("ad_focus")},l=()=>{if(v.current){const y=Date.now()-v.current;h(w=>({...w,timeMetrics:{...w.timeMetrics,totalFocusDuration:w.timeMetrics.totalFocusDuration+y}})),v.current=null,M("ad_blur",{focusDuration:y})}};return f.addEventListener("focus",k),f.addEventListener("blur",l),()=>{f.removeEventListener("focus",k),f.removeEventListener("blur",l)}},[s.enabled,n,M]),g.useEffect(()=>{if(!s.enabled||!n.current)return;const f=n.current,k=()=>{h(l=>({...l,engagementMetrics:{...l.engagementMetrics,wasClicked:!0}})),M("ad_click")};return f.addEventListener("click",k),()=>{f.removeEventListener("click",k)}},[s.enabled,n,M]),g.useEffect(()=>()=>{const f=Date.now(),k=new Date(m.timeMetrics.loadedAt).getTime(),l=f-k;h(y=>({...y,timeMetrics:{...y.timeMetrics,sessionDuration:l}})),M("ad_unloaded",{sessionDuration:l}),E()},[]),m}const me=({adId:t,productId:e,offerId:r,agentId:i,children:n,config:a,className:s,style:d,onViewabilityChange:m,onVisible:h,onViewable:x,onClick:c})=>{const p=g.useRef(null),u=le({adId:t,productId:e,offerId:r,agentId:i,elementRef:p,config:a}),v=g.useRef(u.isViewable);g.useEffect(()=>{u.isViewable!==v.current&&(v.current=u.isViewable,m&&m(u.isViewable),u.isViewable&&x&&x())},[u.isViewable,m,x]);const _=g.useRef(u.isVisible);g.useEffect(()=>{u.isVisible!==_.current&&(_.current=u.isVisible,u.isVisible&&h&&h())},[u.isVisible,h]);const b=S=>{c&&c()};return o.jsx("div",{ref:p,className:s,style:d,onClick:b,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":u.isViewable,"data-is-visible":u.isVisible,"data-visibility-percentage":u.visibilityPercentage.toFixed(2),children:n})};me.displayName="AdMeshViewabilityTracker";const W="admesh_session_id",K="admesh_session_timestamp",Ze=1800*1e3;class ue{constructor(e=!1){j(this,"debug");this.debug=e}generateSessionId(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}createSession(){const e=this.generateSessionId();return this.storeSessionId(e),this.debug&&console.log("[SessionManager] Created session:",e),e}storeSessionId(e){try{typeof window<"u"&&window.localStorage&&(localStorage.setItem(W,e),localStorage.setItem(K,Date.now().toString()))}catch(r){this.debug&&console.warn("[SessionManager] Failed to store session ID:",r)}}getStoredSessionId(){try{if(typeof window>"u"||!window.localStorage)return null;const e=localStorage.getItem(W),r=localStorage.getItem(K);return!e||!r?null:Date.now()-parseInt(r,10)>Ze?(this.debug&&console.log("[SessionManager] Session expired"),this.clearStoredSessionId(),null):e}catch(e){return this.debug&&console.warn("[SessionManager] Failed to get stored session ID:",e),null}}clearStoredSessionId(){try{typeof window<"u"&&window.localStorage&&(localStorage.removeItem(W),localStorage.removeItem(K))}catch(e){this.debug&&console.warn("[SessionManager] Failed to clear session ID:",e)}}closeSession(e){this.debug&&console.log("[SessionManager] Closing session:",e),this.clearStoredSessionId()}isSessionValid(e){return this.getStoredSessionId()===e}}class he{constructor(e){j(this,"apiKey");j(this,"apiBaseUrl");j(this,"debug");this.apiKey=e.apiKey,this.apiBaseUrl=e.apiBaseUrl||"https://api.useadmesh.com",this.debug=e.debug||!1}async fetchRecommendations(e){try{const r=`${this.apiBaseUrl}/agent/recommend`,i={query:e.query,format:e.format||"auto",...e.previous_query&&{previous_query:e.previous_query},...e.previous_summary&&{previous_summary:e.previous_summary},...e.session_id&&{session_id:e.session_id},...e.is_fallback_allowed!==void 0&&{is_fallback_allowed:e.is_fallback_allowed}};this.debug&&(console.log("[Fetcher] Calling endpoint:",r),console.log("[Fetcher] Payload:",i));const n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!n.ok){const d=(await n.json().catch(()=>({}))).detail||`HTTP ${n.status}`;throw new Error(`Failed to fetch recommendations: ${d}`)}const a=await n.json();return this.debug&&console.log("[Fetcher] Response:",a),a}catch(r){throw this.debug&&console.error("[Fetcher] Error fetching recommendations:",r),r}}}class pe{constructor(e){j(this,"debug");j(this,"firedExposures",new Set);this.debug=e.debug||!1}fireExposure(e,r,i){const n=`${i}_${r}`;if(this.firedExposures.has(n)){this.debug&&console.log("[Tracker] Exposure already fired for:",r);return}this.firedExposures.add(n);try{fetch(e,{method:"GET",keepalive:!0}).catch(a=>{this.debug&&console.warn("[Tracker] Failed to fire exposure:",a)}),this.debug&&console.log("[Tracker] Fired exposure for:",r)}catch(a){this.debug&&console.error("[Tracker] Error firing exposure:",a)}}fireClick(e,r,i){try{fetch(e,{method:"GET",keepalive:!0}).catch(n=>{this.debug&&console.warn("[Tracker] Failed to fire click:",n)}),this.debug&&console.log("[Tracker] Fired click for:",r)}catch(n){this.debug&&console.error("[Tracker] Error firing click:",n)}}fireConversion(e,r,i){try{fetch(e,{method:"GET",keepalive:!0}).catch(n=>{this.debug&&console.warn("[Tracker] Failed to fire conversion:",n)}),this.debug&&console.log("[Tracker] Fired conversion for:",r)}catch(n){this.debug&&console.error("[Tracker] Error firing conversion:",n)}}clearFiredExposures(){this.firedExposures.clear(),this.debug&&console.log("[Tracker] Cleared fired exposures")}}class fe{constructor(e=!1){j(this,"debug");j(this,"roots",new Map);this.debug=e}async render(e){var r,i,n,a,s,d;try{const m=document.getElementById(e.containerId);if(!m)throw new Error(`Container with ID "${e.containerId}" not found`);this.debug&&console.log("[Renderer] Rendering recommendations in container:",e.containerId);const h=this.roots.get(e.containerId);h&&h.unmount();const x=we.createRoot(m),c=(u,v)=>{var b,S;const _=(S=(b=e.response.response)==null?void 0:b.recommendations)==null?void 0:S.find(T=>{var M;return((M=T.meta)==null?void 0:M.ad_id)===u||T.ad_id===u});_!=null&&_.click_url&&e.tracker.fireClick(_.click_url,u,e.sessionId),e.onRecommendationClick&&e.onRecommendationClick(u,v),window.open(v,"_blank")},p=((r=e.response.response)==null?void 0:r.citation_summary)||((i=e.response.response)==null?void 0:i.summary);this.debug&&(console.log("[Renderer] Full response:",e.response),console.log("[Renderer] Citation summary:",p),console.log("[Renderer] Recommendations:",(n=e.response.response)==null?void 0:n.recommendations),console.log("[Renderer] Layout type:",(a=e.response.response)==null?void 0:a.layout_type)),x.render(o.jsx(ie,{response:{layout_type:(s=e.response.response)==null?void 0:s.layout_type,citation_summary:p,recommendations:((d=e.response.response)==null?void 0:d.recommendations)||[],requires_summary:!!p},theme:e.theme,onRecommendationClick:u=>{var b;const v=((b=u.meta)==null?void 0:b.ad_id)||u.ad_id||"",_=u.admesh_link||"";c(v,_)}})),this.roots.set(e.containerId,x),this.debug&&console.log("[Renderer] Rendered successfully")}catch(m){throw this.debug&&console.error("[Renderer] Error rendering:",m),m}}unmount(e){const r=this.roots.get(e);r&&(r.unmount(),this.roots.delete(e),this.debug&&console.log("[Renderer] Unmounted container:",e))}unmountAll(){for(const[e,r]of this.roots.entries())r.unmount(),this.debug&&console.log("[Renderer] Unmounted container:",e);this.roots.clear()}}class et{constructor(e){j(this,"config");j(this,"sessionManager");j(this,"fetcher");j(this,"renderer");j(this,"tracker");j(this,"currentSessionId",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiBaseUrl:e.apiBaseUrl||"https://api.useadmesh.com",debug:e.debug||!1,...e},this.sessionManager=new ue(this.config.debug),this.fetcher=new he(this.config),this.renderer=new fe(this.config.debug),this.tracker=new pe(this.config),this.currentSessionId=this.sessionManager.getStoredSessionId(),this.config.debug&&this.currentSessionId&&console.log("[AdMeshSDK] Restored session:",this.currentSessionId)}async showRecommendations(e){var r,i;try{this.config.debug&&console.log("[AdMeshSDK] Fetching recommendations for query:",e.query),this.currentSessionId||(this.currentSessionId=this.sessionManager.createSession(),this.config.debug&&console.log("[AdMeshSDK] Created new session:",this.currentSessionId));const n=await this.fetcher.fetchRecommendations({query:e.query,format:e.format||"auto",previous_query:e.previousQuery,previous_summary:e.previousSummary,session_id:this.currentSessionId,is_fallback_allowed:e.isFallbackAllowed!==!1});if(this.config.debug&&console.log("[AdMeshSDK] Received recommendations:",n),await this.renderer.render({containerId:e.containerId,response:n,theme:e.theme||this.config.theme,onRecommendationClick:e.onRecommendationClick,tracker:this.tracker,sessionId:this.currentSessionId}),(r=n.response)!=null&&r.recommendations){for(const a of n.response.recommendations)if(a.exposure_url){const s=((i=a.meta)==null?void 0:i.ad_id)||a.ad_id||"";this.tracker.fireExposure(a.exposure_url,s,this.currentSessionId)}}}catch(n){throw console.error("[AdMeshSDK] Error showing recommendations:",n),n}}closeSession(){this.currentSessionId&&(this.config.debug&&console.log("[AdMeshSDK] Closing session:",this.currentSessionId),this.sessionManager.closeSession(this.currentSessionId),this.currentSessionId=null)}getSessionId(){return this.currentSessionId}createNewSession(){return this.currentSessionId=this.sessionManager.createSession(),this.config.debug&&console.log("[AdMeshSDK] Created new session:",this.currentSessionId),this.currentSessionId}setSessionId(e){this.currentSessionId=e,this.sessionManager.storeSessionId(e),this.config.debug&&console.log("[AdMeshSDK] Set session ID:",e)}}const D=(t={})=>{const e={mode:"light",primaryColor:"#000000",secondaryColor:"#666666",accentColor:"#000000",backgroundColor:"#ffffff",surfaceColor:"#ffffff",borderColor:"#e5e7eb",textColor:"#000000",textSecondaryColor:"#666666",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:{small:"12px",base:"14px",large:"16px",title:"18px"},borderRadius:"8px",spacing:{small:"4px",medium:"8px",large:"16px"},shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.1)",medium:"0 4px 6px rgba(0, 0, 0, 0.1)",large:"0 10px 15px rgba(0, 0, 0, 0.1)"},icons:{expandIcon:"▼",collapseIcon:"▲",starIcon:"★",checkIcon:"✓",arrowIcon:"→"},gradients:{primary:"#000000",secondary:"#666666",accent:"#000000"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"},card:{width:"auto"},button:{width:"auto"}}},r={...e,...t,fontSize:{...e.fontSize,...t.fontSize},spacing:{...e.spacing,...t.spacing},shadows:{...e.shadows,...t.shadows},icons:{...e.icons,...t.icons},components:{...e.components,...t.components}};return ot(r)},tt=(t={})=>D({...{mode:"dark",primaryColor:"#ffffff",secondaryColor:"#9ca3af",accentColor:"#ffffff",backgroundColor:"#000000",surfaceColor:"#111111",borderColor:"#333333",textColor:"#ffffff",textSecondaryColor:"#9ca3af",shadows:{small:"0 1px 3px rgba(255, 255, 255, 0.1)",medium:"0 4px 6px rgba(255, 255, 255, 0.1)",large:"0 10px 15px rgba(255, 255, 255, 0.1)"},gradients:{primary:"#ffffff",secondary:"#9ca3af",accent:"#ffffff"}},...t}),rt={get minimal(){return D({primaryColor:"#000000",secondaryColor:"#666666",borderRadius:"4px",shadows:{small:"none",medium:"0 1px 3px rgba(0, 0, 0, 0.1)",large:"0 2px 6px rgba(0, 0, 0, 0.1)"},gradients:{primary:"#000000",secondary:"#666666",accent:"#000000"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})},get vibrant(){return D({primaryColor:"#8b5cf6",secondaryColor:"#06b6d4",accentColor:"#f59e0b",borderRadius:"12px",gradients:{primary:"#8b5cf6",secondary:"#06b6d4",accent:"#f59e0b"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})},get corporate(){return D({primaryColor:"#1e40af",secondaryColor:"#059669",backgroundColor:"#f8fafc",surfaceColor:"#ffffff",borderColor:"#cbd5e1",borderRadius:"6px",fontFamily:'"Inter", -apple-system, BlinkMacSystemFont, sans-serif',components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})},get highContrast(){return D({primaryColor:"#000000",secondaryColor:"#ffffff",backgroundColor:"#ffffff",surfaceColor:"#f5f5f5",borderColor:"#000000",textColor:"#000000",textSecondaryColor:"#333333",borderRadius:"0px",shadows:{small:"none",medium:"0 0 0 2px #000000",large:"0 0 0 3px #000000"},components:{productCard:{width:"100%"},citationUnit:{width:"100%"},inlineRecommendation:{width:"100%"},expandableUnit:{width:"100%"},compareTable:{width:"100%"}}})}},ot=(t={})=>{const e=t.components||{},r={productCard:{width:"100%",...e.productCard},citationUnit:{width:"100%",...e.citationUnit},inlineRecommendation:{width:"100%",...e.inlineRecommendation},expandableUnit:{width:"100%",...e.expandableUnit},compareTable:{width:"100%",...e.compareTable},card:{width:"auto",...e.card},button:{width:"auto",...e.button}};return{...t,components:{...e,...r}}},nt=(...t)=>{const e=D();return t.reduce((r,i)=>i?{...r,...i,mode:i.mode||r.mode}:r,e)},st=t=>{var r,i,n,a,s,d;const e=getComputedStyle(t);return{primaryColor:((r=e.getPropertyValue("--admesh-primary-color"))==null?void 0:r.trim())||void 0,secondaryColor:((i=e.getPropertyValue("--admesh-secondary-color"))==null?void 0:i.trim())||void 0,backgroundColor:((n=e.getPropertyValue("--admesh-background-color"))==null?void 0:n.trim())||void 0,textColor:((a=e.getPropertyValue("--admesh-text-color"))==null?void 0:a.trim())||void 0,borderRadius:((s=e.getPropertyValue("--admesh-border-radius"))==null?void 0:s.trim())||void 0,fontFamily:((d=e.getPropertyValue("--admesh-font-family"))==null?void 0:d.trim())||void 0}},at="0.2.1",it={trackingEnabled:!0,debug:!1,theme:{mode:"light",accentColor:"#2563eb"}};exports.AdMeshBadge=ce;exports.AdMeshEcommerceCards=se;exports.AdMeshInlineCard=de;exports.AdMeshLayout=ie;exports.AdMeshLinkTracker=U;exports.AdMeshProductCard=B;exports.AdMeshRecommendationFetcher=he;exports.AdMeshRenderer=fe;exports.AdMeshSDK=et;exports.AdMeshSessionManager=ue;exports.AdMeshSummaryLayout=ae;exports.AdMeshSummaryUnit=G;exports.AdMeshTracker=pe;exports.AdMeshViewabilityTracker=me;exports.DEFAULT_CONFIG=it;exports.VERSION=at;exports.buildAdMeshLink=Te;exports.createAdMeshTheme=D;exports.createDarkTheme=tt;exports.extractTrackingData=je;exports.getBadgeText=Re;exports.getCtaText=De;exports.getInlineDisclosure=Ne;exports.getInlineTooltip=Ee;exports.getLabelTooltip=J;exports.getPoweredByText=Fe;exports.getRecommendationLabel=F;exports.getSectionDisclosure=Ae;exports.hasHighQualityMatches=Pe;exports.mergeThemes=nt;exports.setAdMeshTrackerConfig=Ce;exports.setViewabilityTrackerConfig=Xe;exports.themeFromCSSProperties=st;exports.themePresets=rt;exports.useAdMeshStyles=ne;exports.useAdMeshTracker=oe;exports.useViewabilityTracker=le;
|
|
688
688
|
//# sourceMappingURL=index.js.map
|