@selwise/widget 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +0,0 @@
1
- /*! For license information please see index.mjs.LICENSE.txt */
2
- var e={48(e,t){Object.defineProperty(t,"__esModule",{value:!0})},115(e,t){Object.defineProperty(t,"__esModule",{value:!0})},126(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(187),t),o(n(213),t),o(n(927),t)},142(e,t){function n(e){return[{field:"buttonText",label:e?.buttonTextLabel||"Button Text",type:"text",placeholder:e?.buttonTextPlaceholder||"Shop Now"},{field:"buttonUrl",label:e?.buttonUrlLabel||"Button URL",type:"url",placeholder:"https://..."}]}function i(e){return{field:"imageUrl",label:e?.label||"Image",type:"image-upload",placeholder:e?.placeholder||"https://..."}}function o(e){return[{field:"title",label:e?.titleLabel||"Title",type:"text",placeholder:e?.titlePlaceholder||"Special Offer"},{field:"text",label:e?.textLabel||"Description",type:"textarea",placeholder:e?.textPlaceholder||"Limited time offer..."}]}function r(e){const t=[{key:"backgroundColor",label:"Background Color",type:"color",default:e.backgroundColor||"#1a1a1a"},{key:"textColor",label:"Text Color",type:"color",default:e.textColor||"#ffffff"},{key:"buttonColor",label:"Button Color",type:"color",default:e.buttonColor||"#ffffff"},{key:"buttonTextColor",label:"Button Text Color",type:"color",default:e.buttonTextColor||"#1a1a1a"}];return e.extraColors&&Object.entries(e.extraColors).forEach(([e,n])=>{t.push({key:e,label:n.label,type:"color",default:n.default})}),{title:"Colors",fields:t}}function a(e={}){const t=[];return!1!==e.includeRadius&&t.push({key:"borderRadius",label:"Border Radius",type:"select",options:e.borderRadiusOptions||["0px","4px","8px","12px","16px"],default:e.borderRadiusDefault||"8px"}),t.push({key:"padding",label:"Padding",type:"select",options:e.paddingOptions||["0px","4px","8px","12px","16px","20px","24px"],default:e.paddingDefault||"16px"}),e.extraFields&&t.push(...e.extraFields),{title:"Layout",fields:t}}function s(e={}){const t=[];return!1!==e.includeShadow&&t.push({key:"shadow",label:"Shadow",type:"select",options:e.shadowOptions||["none","sm","md","lg","xl"],default:e.shadowDefault||"md"}),!1!==e.includeBorder&&t.push({key:e.borderKey||"border",label:e.borderLabel||"Border",type:"text",default:e.borderDefault||"none",placeholder:"1px solid #e5e7eb"}),e.extraFields&&t.push(...e.extraFields),{title:"Effects",fields:t}}function l(e={}){const t=[{key:"fontSize",label:"Font Size",type:"select",options:e.fontSizeOptions||["12px","14px","16px","18px"],default:e.fontSizeDefault||"14px"},{key:"fontWeight",label:"Font Weight",type:"select",options:e.fontWeightOptions||["normal","medium","semibold","bold"],default:e.fontWeightDefault||"medium"}];return e.extraFields&&t.push(...e.extraFields),{title:"Typography",fields:t}}function c(e={}){return{title:"Close Button",fields:[{key:"showCloseButton",label:"Show Close Button",type:"toggle",default:e.showDefault??!0},{key:"closeButtonColor",label:"Close Button Color",type:"color",default:e.colorDefault||"#ffffff"}]}}function d(e){return t.TYPE_STYLE_CONFIGS[e]||t.TYPE_STYLE_CONFIGS.custom}Object.defineProperty(t,"__esModule",{value:!0}),t.SHADOW_VALUES=t.TYPE_STYLE_CONFIGS=t.TYPE_CONTENT_FIELDS=t.WIDGET_TYPES=void 0,t.getWidgetTypeConfig=function(e){return t.WIDGET_TYPES.find(t=>t.value===e)},t.getDefaultStyles=function(e){const n=t.TYPE_STYLE_CONFIGS[e]||t.TYPE_STYLE_CONFIGS.custom,i={};return n.forEach(e=>{e.fields.forEach(e=>{i[e.key]=e.default})}),i},t.getContentFields=function(e){return t.TYPE_CONTENT_FIELDS[e]||t.TYPE_CONTENT_FIELDS.custom},t.getStyleSections=d,t.getShadowValue=function(e){return t.SHADOW_VALUES[e]||"none"},t.getAllowedStyleKeys=function(e){return d(e).flatMap(e=>e.fields.map(e=>e.key))},t.WIDGET_TYPES=[{value:"announcement_bar",label:"Announcement Bar",description:"Top or bottom bar for announcements",icon:"MessageSquare",placementType:"fixed",placementOptions:["top","bottom"]},{value:"inline_banner",label:"Inline Banner",description:"Banner inserted into page content",icon:"Layout",placementType:"selector"},{value:"floating_button",label:"Floating Button",description:"Fixed position floating action button",icon:"MousePointerClick",placementType:"fixed",placementOptions:["bottom-right","bottom-left","top-right","top-left"]},{value:"exit_intent_popup",label:"Exit Intent Popup",description:"Popup triggered when user tries to leave",icon:"LogOut",placementType:"fixed",placementOptions:["center"]},{value:"slide_in",label:"Slide In",description:"Panel that slides in from side or bottom",icon:"PanelRight",placementType:"fixed",placementOptions:["right","left","bottom"]},{value:"embedded_card",label:"Embedded Card",description:"Card inserted into page content",icon:"LayoutGrid",placementType:"selector"},{value:"sticky_footer",label:"Sticky Footer",description:"Fixed footer bar at bottom of page",icon:"PanelBottom",placementType:"fixed",placementOptions:["bottom"]},{value:"countdown_timer",label:"Countdown Timer",description:"Timer with countdown to end date",icon:"Timer",placementType:"fixed",placementOptions:["top","bottom"]},{value:"cookie_consent",label:"Cookie Consent",description:"GDPR compliant cookie consent banner",icon:"Shield",placementType:"fixed",placementOptions:["top","bottom","center-modal","bottom-left","bottom-right"]},{value:"custom",label:"Custom Widget",description:"Custom HTML/CSS widget",icon:"Code",placementType:"both",placementOptions:["top","bottom"]},{value:"product_view_count",label:"Product View Count",description:"Shows how many people viewed a product",icon:"Eye",placementType:"selector"},{value:"cart_count",label:"Cart Count",description:"Shows how many have product in cart",icon:"ShoppingCart",placementType:"selector"},{value:"newsletter",label:"Newsletter",description:"Email capture widget with consent-aware newsletter signup flow",icon:"Mail",placementType:"both",placementOptions:["bottom-right","bottom-left","center"]}],t.TYPE_CONTENT_FIELDS={announcement_bar:[{field:"text",label:"Announcement Text",type:"text",placeholder:"Free shipping on orders over $50!"},...n(),i({label:"Icon / Logo"})],inline_banner:[...o({titlePlaceholder:"Special Offer",textPlaceholder:"Limited time offer..."}),...n({buttonTextPlaceholder:"Learn More"}),i()],floating_button:[{field:"text",label:"Button Text/Icon",type:"text",placeholder:"💬"},{field:"tooltip",label:"Tooltip",type:"text",placeholder:"Chat with us"},{field:"buttonUrl",label:"Link URL",type:"url",placeholder:"https://..."}],exit_intent_popup:[...o({titlePlaceholder:"Wait! Before you go...",textLabel:"Message",textPlaceholder:"Get 10% off your first order!"}),...n({buttonTextPlaceholder:"Get Discount"}),i()],slide_in:[...o({titlePlaceholder:"Special Offer",textLabel:"Message",textPlaceholder:"Subscribe to our newsletter..."}),...n({buttonTextPlaceholder:"Subscribe"}),i()],embedded_card:[...o({titlePlaceholder:"Featured Product",textPlaceholder:"Amazing product..."}),...n({buttonTextPlaceholder:"View Details"}),i()],sticky_footer:[{field:"text",label:"Message",type:"text",placeholder:"Free shipping on all orders!"},{field:"subtext",label:"Sub-text",type:"text",placeholder:"Limited time only"},...n()],countdown_timer:[{field:"title",label:"Title",type:"text",placeholder:"Sale ends in:"},{field:"text",label:"Sub-text",type:"text",placeholder:"Hurry! Limited stock"},{field:"endDate",label:"End Date",type:"datetime-local"},...n({buttonTextPlaceholder:"Shop Sale"})],cookie_consent:[{field:"headline",label:"Headline",type:"text",placeholder:"We use cookies"},{field:"text",label:"Description",type:"textarea",placeholder:"To improve your experience, we use cookies..."},{field:"buttonText",label:"Accept Button Text",type:"text",placeholder:"Accept All"},{field:"declineButtonText",label:"Decline Button Text",type:"text",placeholder:"Decline"},{field:"customizeButtonText",label:"Customize Button Text",type:"text",placeholder:"Customize"}],custom:[{field:"html",label:"Custom HTML",type:"textarea",placeholder:"<div>Your custom HTML here...</div>"},{field:"css",label:"Custom CSS",type:"textarea",placeholder:".my-widget { ... }"}],product_view_count:[{field:"template",label:"Metin Şablonu",type:"select",options:["Bu ürünü son {timePeriod} içinde {count} kişi görüntüledi","{count} kişi bu ürünü görüntüledi","Popüler! {count} görüntülenme","Son {timePeriod}: {count} görüntüleme"],placeholder:"Select a template or customize below"},{field:"customText",label:"Özel Metin (şablonu geçersiz kılar)",type:"text",placeholder:"{count}, {timePeriod} kullanın"},{field:"timePeriod",label:"Zaman Periyodu",type:"select",options:["1h","24h","7d","30d"],default:"24h"},{field:"showIcon",label:"İkon Göster",type:"checkbox",default:!0},{field:"iconType",label:"İkon",type:"select",options:["eye","users","trending-up","flame"],default:"eye"},{field:"productId",label:"Ürün ID (SKU)",type:"text",placeholder:"Otomatik algılanır veya manuel girin",required:!1}],cart_count:[{field:"template",label:"Metin Şablonu",type:"select",options:["Bu ürün şu an {count} kişinin sepetinde","{count} kişi sepete ekledi","Tükeniyor! Sadece {count} adet kaldı","Şu an {count} kişi bunu istiyor"],placeholder:"Select a template or customize below"},{field:"customText",label:"Özel Metin (şablonu geçersiz kılar)",type:"text",placeholder:"{count} kullanın"},{field:"metricType",label:"Metrik Türü",type:"select",options:["active_carts"],default:"active_carts"},{field:"showIcon",label:"İkon Göster",type:"checkbox",default:!0},{field:"iconType",label:"İkon",type:"select",options:["shopping-cart","shopping-bag","users","fire"],default:"shopping-cart"},{field:"productId",label:"Ürün ID (SKU)",type:"text",placeholder:"Otomatik algılanır veya manuel girin",required:!1}],newsletter:[{field:"headline",label:"Headline",type:"text",placeholder:"Join our newsletter"},{field:"text",label:"Description",type:"textarea",placeholder:"Get product updates, launches, and growth tips."},{field:"emailPlaceholder",label:"Email Placeholder",type:"text",placeholder:"you@example.com"},{field:"buttonText",label:"Button Text",type:"text",placeholder:"Subscribe"},{field:"successMessage",label:"Success Message",type:"text",placeholder:"Thanks! Please check your inbox to confirm."},{field:"errorMessage",label:"Error Message",type:"text",placeholder:"Unable to subscribe right now. Please try again."}]},t.TYPE_STYLE_CONFIGS={announcement_bar:[r({backgroundColor:"#1a1a1a",textColor:"#ffffff",buttonColor:"#ffffff",buttonTextColor:"#1a1a1a"}),l({fontSizeDefault:"14px"}),{title:"Layout",fields:[{key:"padding",label:"Padding",type:"select",options:["8px","12px","16px","20px"],default:"12px"},{key:"borderBottom",label:"Border Bottom",type:"text",default:"none",placeholder:"1px solid #333"}]},{title:"Image",fields:[{key:"imageSize",label:"Icon Size",type:"select",options:["20px","24px","28px","32px","40px"],default:"24px"},{key:"imageBorderRadius",label:"Icon Radius",type:"select",options:["0px","4px","8px","50%"],default:"4px"},{key:"imageSpacing",label:"Icon Spacing",type:"select",options:["4px","8px","12px","16px"],default:"8px"}]},c()],inline_banner:[r({backgroundColor:"#6366f1",textColor:"#ffffff",buttonColor:"#ffffff",buttonTextColor:"#6366f1"}),a({paddingDefault:"16px"}),s({shadowDefault:"md"}),{title:"Image",fields:[{key:"imageMode",label:"Image Mode",type:"select",options:["thumbnail","cover","fullWidth"],default:"thumbnail"},{key:"imageSize",label:"Thumbnail Size",type:"select",options:["40px","48px","60px","80px","128px"],default:"60px",condition:e=>"thumbnail"===e.imageMode},{key:"imageAspectRatio",label:"Aspect Ratio",type:"select",options:["auto","16/9","4/3","1/1"],default:"auto",condition:e=>"thumbnail"!==e.imageMode},{key:"imageObjectFit",label:"Object Fit",type:"select",options:["cover","contain","fill"],default:"cover"},{key:"imageBorderRadius",label:"Image Radius",type:"select",options:["0px","4px","8px","50%"],default:"8px"}]},{title:"Content Layout",fields:[{key:"contentDirection",label:"Direction",type:"select",options:["row","column"],default:"row"},{key:"contentAlignment",label:"Alignment",type:"select",options:["left","center","right"],default:"left"},{key:"imageSpacing",label:"Image Spacing",type:"select",options:["0px","8px","12px","16px","24px"],default:"16px"}]}],floating_button:[{title:"Colors",fields:[{key:"backgroundColor",label:"Background Color",type:"color",default:"#6366f1"},{key:"textColor",label:"Icon/Text Color",type:"color",default:"#ffffff"}]},{title:"Size & Shape",fields:[{key:"size",label:"Button Size",type:"select",options:["48px","56px","64px","72px"],default:"56px"},{key:"borderRadius",label:"Border Radius",type:"select",options:["8px","12px","16px","50%"],default:"50%"}]},s({shadowDefault:"lg",includeBorder:!1,extraFields:[{key:"pulseAnimation",label:"Pulse Animation",type:"toggle",default:!1}]}),{title:"Tooltip",fields:[{key:"tooltipBgColor",label:"Tooltip Background",type:"color",default:"#1a1a1a"},{key:"tooltipTextColor",label:"Tooltip Text",type:"color",default:"#ffffff"}]}],exit_intent_popup:[r({backgroundColor:"#ffffff",textColor:"#1a1a1a",buttonColor:"#6366f1",buttonTextColor:"#ffffff"}),{title:"Overlay",fields:[{key:"overlayColor",label:"Overlay Color",type:"color",default:"#000000"},{key:"overlayOpacity",label:"Overlay Opacity",type:"range",min:0,max:100,step:5,default:50},{key:"overlayBlur",label:"Overlay Blur",type:"select",options:["none","2px","4px","8px"],default:"none"}]},{title:"Layout",fields:[{key:"maxWidth",label:"Max Width",type:"select",options:["320px","400px","480px","560px"],default:"400px"},{key:"padding",label:"Padding",type:"select",options:["16px","20px","24px","32px"],default:"24px"},{key:"borderRadius",label:"Border Radius",type:"select",options:["0px","8px","12px","16px","24px"],default:"12px"}]},{title:"Image",fields:[{key:"imageMode",label:"Image Mode",type:"select",options:["thumbnail","cover","fullWidth"],default:"cover"},{key:"imageSize",label:"Thumbnail Size",type:"select",options:["48px","60px","80px","120px"],default:"80px",condition:e=>"thumbnail"===e.imageMode},{key:"imagePosition",label:"Image Position",type:"select",options:["top","bottom","left","right"],default:"top"},{key:"imageAspectRatio",label:"Aspect Ratio",type:"select",options:["auto","16/9","4/3","1/1"],default:"auto"},{key:"imageObjectFit",label:"Object Fit",type:"select",options:["cover","contain","fill"],default:"cover"},{key:"imageBorderRadius",label:"Image Radius",type:"select",options:["0px","4px","8px","12px"],default:"8px",condition:e=>"fullWidth"!==e.imageMode}]},{title:"Animation",fields:[{key:"animation",label:"Animation",type:"select",options:["none","fade","scale","slide"],default:"scale"},{key:"shadow",label:"Shadow",type:"select",options:["none","lg","xl","2xl"],default:"2xl"}]}],slide_in:[r({backgroundColor:"#ffffff",textColor:"#1a1a1a",buttonColor:"#6366f1",buttonTextColor:"#ffffff"}),{title:"Layout",fields:[{key:"width",label:"Width",type:"select",options:["280px","320px","360px","400px"],default:"320px"},{key:"padding",label:"Padding",type:"select",options:["12px","16px","20px","24px"],default:"16px"},{key:"borderRadius",label:"Border Radius",type:"select",options:["0px","8px","12px","16px"],default:"12px"}]},{title:"Image",fields:[{key:"imageMode",label:"Image Mode",type:"select",options:["cover","contain","fullWidth"],default:"cover"},{key:"imageAspectRatio",label:"Aspect Ratio",type:"select",options:["auto","16/9","4/3","1/1","3/4"],default:"auto"},{key:"imageObjectFit",label:"Object Fit",type:"select",options:["cover","contain","fill"],default:"cover"},{key:"imageBorderRadius",label:"Image Radius",type:"select",options:["0px","4px","8px","12px"],default:"8px",condition:e=>"fullWidth"!==e.imageMode}]},s({shadowDefault:"xl",shadowOptions:["none","lg","xl","2xl"]}),{title:"Position",fields:[{key:"offsetX",label:"Horizontal Offset",type:"select",options:["8px","12px","16px","24px"],default:"16px"},{key:"offsetY",label:"Vertical Offset",type:"select",options:["8px","12px","16px","24px"],default:"16px"}]}],embedded_card:[r({backgroundColor:"#ffffff",textColor:"#1a1a1a",buttonColor:"#6366f1",buttonTextColor:"#ffffff"}),a({borderRadiusDefault:"12px",paddingDefault:"16px"}),s({shadowDefault:"md",borderDefault:"1px solid #e5e7eb"}),{title:"Image",fields:[{key:"imageMode",label:"Image Mode",type:"select",options:["cover","contain","fullWidth"],default:"cover"},{key:"imageAspectRatio",label:"Aspect Ratio",type:"select",options:["auto","16/9","4/3","1/1","3/4"],default:"16/9"},{key:"imageObjectFit",label:"Object Fit",type:"select",options:["cover","contain","fill"],default:"cover"},{key:"imagePosition",label:"Image Position",type:"select",options:["top","bottom"],default:"top"},{key:"imageBorderRadius",label:"Image Radius",type:"select",options:["0px","8px","12px"],default:"8px",condition:e=>"fullWidth"!==e.imageMode}]},{title:"Content Layout",fields:[{key:"contentAlignment",label:"Alignment",type:"select",options:["left","center","right"],default:"left"}]}],sticky_footer:[r({backgroundColor:"#1a1a1a",textColor:"#ffffff",buttonColor:"#ffffff",buttonTextColor:"#1a1a1a"}),{title:"Layout",fields:[{key:"padding",label:"Padding",type:"select",options:["8px","12px","16px","20px"],default:"12px"},{key:"fontSize",label:"Font Size",type:"select",options:["12px","14px","16px"],default:"14px"}]},s({shadowDefault:"lg",shadowOptions:["none","sm","md","lg"],borderKey:"borderTop",borderLabel:"Border Top",borderDefault:"none"}),c()],countdown_timer:[r({backgroundColor:"#dc2626",textColor:"#ffffff",buttonColor:"#ffffff",buttonTextColor:"#dc2626"}),{title:"Timer Style",fields:[{key:"timerBgColor",label:"Timer Background",type:"color",default:"rgba(255,255,255,0.2)"},{key:"timerFontSize",label:"Timer Font Size",type:"select",options:["14px","16px","18px","20px"],default:"16px"},{key:"timerFontWeight",label:"Timer Font Weight",type:"select",options:["normal","medium","semibold","bold"],default:"bold"}]},{title:"Layout",fields:[{key:"padding",label:"Padding",type:"select",options:["8px","12px","16px"],default:"12px"},{key:"separatorStyle",label:"Separator Style",type:"select",options:["colon","dot","slash","none"],default:"colon"}]}],cookie_consent:[r({backgroundColor:"#1f2937",textColor:"#f3f4f6",buttonColor:"#3b82f6",buttonTextColor:"#ffffff",extraColors:{declineButtonColor:{label:"Decline Button Color",default:"#6b7280"},declineButtonTextColor:{label:"Decline Button Text Color",default:"#ffffff"},customizeButtonColor:{label:"Customize Button Color",default:"#4b5563"},customizeButtonTextColor:{label:"Customize Button Text Color",default:"#ffffff"},linkColor:{label:"Link Color",default:"#60a5fa"}}}),{title:"Layout",fields:[{key:"padding",label:"Padding",type:"select",options:["12px","16px","20px","24px"],default:"16px"},{key:"borderRadius",label:"Border Radius",type:"select",options:["0px","4px","8px","12px","16px"],default:"8px"},{key:"shadow",label:"Shadow",type:"select",options:["none","sm","md","lg"],default:"lg"},{key:"maxWidth",label:"Max Width",type:"select",options:["400px","600px","800px","1200px","none"],default:"none"}]},{title:"Typography",fields:[{key:"headlineFontSize",label:"Headline Font Size",type:"select",options:["14px","16px","18px","20px","24px"],default:"18px"},{key:"headlineFontWeight",label:"Headline Font Weight",type:"select",options:["normal","medium","semibold","bold"],default:"semibold"},{key:"textFontSize",label:"Text Font Size",type:"select",options:["12px","14px","16px"],default:"14px"},{key:"buttonFontSize",label:"Button Font Size",type:"select",options:["12px","14px","16px"],default:"14px"},{key:"buttonFontWeight",label:"Button Font Weight",type:"select",options:["normal","medium","semibold","bold"],default:"medium"}]},{title:"Behavior",fields:[{key:"showDeclineButton",label:"Show Decline Button",type:"toggle",default:!0},{key:"showCustomizeButton",label:"Show Customize Button",type:"toggle",default:!0},{key:"showCloseButton",label:"Show Close Button",type:"toggle",default:!1},{key:"autoHideAfterMs",label:"Auto Hide After (ms)",type:"number",default:0,min:0,max:6e4,step:1e3}]},{title:"Consent Settings",fields:[{key:"granularEnabled",label:"Enable Granular Consent",type:"toggle",default:!0},{key:"requiredCategories",label:"Required Categories",type:"text",default:"necessary",placeholder:"necessary,analytics"},{key:"timeoutMs",label:"Decision Timeout (ms)",type:"number",default:0,min:0,max:3e5,step:1e3}]}],custom:[{title:"Container",fields:[{key:"containerPadding",label:"Container Padding",type:"select",options:["0px","8px","16px","24px"],default:"0px"},{key:"containerBackground",label:"Container Background",type:"color",default:"transparent"}]}],product_view_count:[{title:"Renkler",fields:[{key:"backgroundColor",label:"Arkaplan Rengi",type:"color",default:"#f0fdf4"},{key:"textColor",label:"Metin Rengi",type:"color",default:"#166534"},{key:"iconColor",label:"İkon Rengi",type:"color",default:"#22c55e"},{key:"counterColor",label:"Sayaç Rengi",type:"color",default:"#16a34a"}]},{title:"Düzen",fields:[{key:"borderRadius",label:"Köşe Yuvarlama",type:"select",options:["0px","4px","8px","12px","16px","50px"],default:"8px"},{key:"padding",label:"İç Boşluk",type:"select",options:["8px","12px","16px","20px"],default:"12px"},{key:"display",label:"Görünüm",type:"select",options:["inline","block","flex"],default:"inline"},{key:"fontSize",label:"Font Boyutu",type:"select",options:["12px","14px","16px","18px"],default:"14px"}]},{title:"Animasyon",fields:[{key:"animateCounter",label:"Animasyonlu Sayaç",type:"toggle",default:!0},{key:"animationDuration",label:"Animasyon Süresi (ms)",type:"select",options:["500","1000","1500","2000"],default:"1000"},{key:"separator",label:"Ayıraç",type:"select",options:["comma","dot","space","none"],default:"comma"}]}],cart_count:[{title:"Renkler",fields:[{key:"backgroundColor",label:"Arkaplan Rengi",type:"color",default:"#fef3c7"},{key:"textColor",label:"Metin Rengi",type:"color",default:"#92400e"},{key:"iconColor",label:"İkon Rengi",type:"color",default:"#f59e0b"},{key:"counterColor",label:"Sayaç Rengi",type:"color",default:"#ea580c"}]},{title:"Düzen",fields:[{key:"borderRadius",label:"Köşe Yuvarlama",type:"select",options:["0px","4px","8px","12px","16px","50px"],default:"8px"},{key:"padding",label:"İç Boşluk",type:"select",options:["8px","12px","16px","20px"],default:"12px"},{key:"display",label:"Görünüm",type:"select",options:["inline","block","flex"],default:"inline"},{key:"fontSize",label:"Font Boyutu",type:"select",options:["12px","14px","16px","18px"],default:"14px"}]},{title:"Animasyon",fields:[{key:"animateCounter",label:"Animasyonlu Sayaç",type:"toggle",default:!0},{key:"animationDuration",label:"Animasyon Süresi (ms)",type:"select",options:["500","1000","1500","2000"],default:"1000"},{key:"separator",label:"Ayıraç",type:"select",options:["comma","dot","space","none"],default:"comma"}]},{title:"Aciliyet Rozeti",fields:[{key:"showBadge",label:"Rozet Göster",type:"toggle",default:!1},{key:"badgeText",label:"Rozet Metni",type:"text",default:"HOT"},{key:"badgeColor",label:"Rozet Rengi",type:"color",default:"#dc2626"},{key:"badgeTextColor",label:"Rozet Metin Rengi",type:"color",default:"#ffffff"}]}],newsletter:[r({backgroundColor:"#ffffff",textColor:"#111827",buttonColor:"#111827",buttonTextColor:"#ffffff",extraColors:{inputBackgroundColor:{label:"Input Background",default:"#f9fafb"},inputTextColor:{label:"Input Text",default:"#111827"},inputBorderColor:{label:"Input Border",default:"#d1d5db"}}}),l({fontSizeDefault:"14px",extraFields:[{key:"headlineFontSize",label:"Headline Size",type:"select",options:["16px","18px","20px","24px"],default:"20px"}]}),a({paddingDefault:"16px",borderRadiusDefault:"12px",extraFields:[{key:"maxWidth",label:"Max Width",type:"select",options:["280px","320px","360px","420px","100%"],default:"360px"}]}),s({shadowDefault:"lg",extraFields:[{key:"showCloseButton",label:"Show Close Button",type:"toggle",default:!0}]})]},t.SHADOW_VALUES={none:"none",sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)",xl:"0 20px 25px -5px rgba(0, 0, 0, 0.1)","2xl":"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},187(e,t){Object.defineProperty(t,"__esModule",{value:!0})},213(e,t){function n(e){const n=t.RECOMMENDATION_STYLE_CONFIGS[e];return n?n.fields.reduce((e,t)=>(e[t.key]=t.default,e),{}):{}}Object.defineProperty(t,"__esModule",{value:!0}),t.RECOMMENDATION_STYLE_CONFIGS=t.RECOMMENDATION_PLATFORMS=t.RECOMMENDATION_INSERT_POSITIONS=t.RECOMMENDATION_TRIGGERS=t.RECOMMENDATION_DISPLAY_TYPES=t.RECOMMENDATION_STRATEGIES=void 0,t.getDefaultRecommendationConfig=function(){return{strategy:"bestsellers",displayType:"slider",trigger:"page_load",insertPosition:"append",cartPlatform:"custom",maxProducts:12,productsPerRow:4,autoplay:!1,autoplaySpeed:3e3,loop:!0,pauseOnHover:!0,slidesPerView:4,slidesPerViewTablet:3,slidesPerViewMobile:2,slideGap:16,title:"Recommended for You",subtitle:"",excludeOutOfStock:!0,showOnAllPages:!0,includeUrls:[],excludeUrls:[],containerSelector:"",addToCartEnabled:!1,addToCartConfig:{},triggerConfig:{},arrowStyles:n("arrowStyles"),dotStyles:n("dotStyles"),titleStyles:n("titleStyles"),subtitleStyles:n("subtitleStyles"),containerStyles:n("containerStyles")}},t.RECOMMENDATION_STRATEGIES=["manual","category_based","bestsellers","new_arrivals","on_sale","viewed_together","bought_together","user_history","similar_products","trending","ai_personalized","custom_query"],t.RECOMMENDATION_DISPLAY_TYPES=["slider","grid","carousel","list","masonry"],t.RECOMMENDATION_TRIGGERS=["page_load","scroll","exit_intent","time_delay","add_to_cart","custom"],t.RECOMMENDATION_INSERT_POSITIONS=["append","prepend","before","after","replace"],t.RECOMMENDATION_PLATFORMS=["custom","shopify","woocommerce","magento","prestashop","akinon","custom_api"],t.RECOMMENDATION_STYLE_CONFIGS={arrowStyles:{id:"arrowStyles",title:"Arrows",fields:[{key:"enabled",label:"Enabled",type:"toggle",default:!0},{key:"style",label:"Style",type:"select",default:"circle",options:["circle","square","minimal"]},{key:"size",label:"Size",type:"number",default:40,min:20,max:120},{key:"color",label:"Color",type:"color",default:"#333333"},{key:"backgroundColor",label:"Background",type:"color",default:"#ffffff"},{key:"borderColor",label:"Border Color",type:"color",default:"#e5e5e5"},{key:"borderWidth",label:"Border Width",type:"number",default:1,min:0,max:10},{key:"borderRadius",label:"Border Radius",type:"number",default:50,min:0,max:200},{key:"iconSize",label:"Icon Size",type:"number",default:16,min:8,max:64},{key:"hoverColor",label:"Hover Color",type:"color",default:"#000000"},{key:"hoverBackgroundColor",label:"Hover Background",type:"color",default:"#f5f5f5"},{key:"position",label:"Position",type:"select",default:"outside",options:["inside","outside"]},{key:"offset",label:"Offset",type:"number",default:-20,min:-200,max:200}]},dotStyles:{id:"dotStyles",title:"Dots",fields:[{key:"enabled",label:"Enabled",type:"toggle",default:!0},{key:"style",label:"Style",type:"select",default:"circle",options:["circle","bar","line"]},{key:"size",label:"Size",type:"number",default:10,min:2,max:40},{key:"color",label:"Color",type:"color",default:"#cccccc"},{key:"activeColor",label:"Active Color",type:"color",default:"#333333"},{key:"gap",label:"Gap",type:"number",default:8,min:0,max:64},{key:"position",label:"Position",type:"select",default:"bottom",options:["bottom","below"]},{key:"offset",label:"Offset",type:"number",default:20,min:-200,max:200}]},titleStyles:{id:"titleStyles",title:"Title",fields:[{key:"enabled",label:"Enabled",type:"toggle",default:!0},{key:"fontSize",label:"Font Size",type:"number",default:24,min:8,max:96},{key:"fontWeight",label:"Font Weight",type:"select",default:"bold",options:["normal","medium","semibold","bold"]},{key:"color",label:"Color",type:"color",default:"#111111"},{key:"textAlign",label:"Text Align",type:"select",default:"left",options:["left","center","right"]},{key:"marginBottom",label:"Margin Bottom",type:"number",default:16,min:0,max:200}]},subtitleStyles:{id:"subtitleStyles",title:"Subtitle",fields:[{key:"enabled",label:"Enabled",type:"toggle",default:!1},{key:"fontSize",label:"Font Size",type:"number",default:14,min:8,max:96},{key:"fontWeight",label:"Font Weight",type:"select",default:"normal",options:["normal","medium","semibold","bold"]},{key:"color",label:"Color",type:"color",default:"#666666"},{key:"textAlign",label:"Text Align",type:"select",default:"left",options:["left","center","right"]},{key:"marginBottom",label:"Margin Bottom",type:"number",default:24,min:0,max:200}]},containerStyles:{id:"containerStyles",title:"Container",fields:[{key:"backgroundColor",label:"Background",type:"color",default:"transparent"},{key:"padding",label:"Padding",type:"text",default:"40px 20px"},{key:"borderRadius",label:"Border Radius",type:"number",default:0,min:0,max:120},{key:"maxWidth",label:"Max Width",type:"text",default:"1200px"},{key:"margin",label:"Margin",type:"text",default:"0 auto"}]}}},259(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.resolveInlineBannerLayout=function(e){const t=e.contentDirection||"row",n=e.contentAlignment||"left",i="center"===n?"center":"right"===n?"flex-end":"flex-start";return{effectiveDirection:"fullWidth"===(e.imageMode||"thumbnail")&&"row"===t?"column":t,alignItems:i,textAlign:n,ctaAlignSelf:i}}},273(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.validateCanonicalEvent=function(e){return o.has(e)},t.validateFrequencyInterval=d,t.validateFrequencyCapPayload=function(e){if(null==e)return{valid:!0};if(!c(e))return{valid:!1,message:"invalid frequency cap payload"};const t=Object.keys(e).filter(e=>!l.has(e));if(t.length>0)return{valid:!1,message:`invalid frequency cap key: ${t.join(", ")}`,invalidKeys:t};for(const t of["perSession","perDay","perWeek","total"])if(void 0!==e[t]&&(!Number.isInteger(e[t])||e[t]<0))return{valid:!1,message:`invalid frequency cap value: ${t}`};return void 0===e.minInterval||"string"==typeof e.minInterval&&d(e.minInterval)?{valid:!0}:{valid:!1,message:"invalid frequency cap minInterval"}},t.validateDataLayerConfig=function(e){if(!c(e))return{valid:!1,message:"invalid data layer config payload"};if(void 0!==e.pageDetection&&("string"!=typeof e.pageDetection||!a.has(e.pageDetection)))return{valid:!1,message:"invalid page detection mode"};if(void 0!==e.pageTypePatterns){if(!c(e.pageTypePatterns))return{valid:!1,message:"invalid page type patterns payload"};const t=new Set(Object.keys(i.DEFAULT_PAGE_TYPE_PATTERNS)),n=Object.keys(e.pageTypePatterns).filter(e=>!t.has(e));if(n.length>0)return{valid:!1,message:`invalid page type pattern key: ${n.join(", ")}`,invalidKeys:n}}if(void 0!==e.cookieConsent){if(!c(e.cookieConsent))return{valid:!1,message:"invalid cookie consent payload"};if(void 0!==e.cookieConsent.requiredCategories){if(!Array.isArray(e.cookieConsent.requiredCategories))return{valid:!1,message:"invalid required categories payload"};if(e.cookieConsent.requiredCategories.filter(e=>"string"!=typeof e||!r.has(e)).length>0)return{valid:!1,message:"invalid required categories value"}}}const t=function(e){if(void 0===e)return{valid:!0};if(!c(e))return{valid:!1,message:"invalid tracking modules payload"};const t=new Set(Object.keys(i.TRACKING_MODULES)),n=Object.keys(e).filter(e=>!t.has(e));if(n.length>0)return{valid:!1,message:`invalid tracking module key: ${n.join(", ")}`,invalidKeys:n};for(const[t,n]of Object.entries(e)){if(!c(n))return{valid:!1,message:`invalid tracking module payload: ${t}`};if("enabled"in n&&"boolean"!=typeof n.enabled)return{valid:!1,message:`invalid tracking module enabled flag: ${t}`}}return{valid:!0}}(e.trackingModules);return t.valid?{valid:!0}:t},t.sanitizeDataLayerConfig=function(e){const t={...i.TRACKING_MODULES},n=c(e.trackingModules)?e.trackingModules:{};for(const e of Object.keys(t)){const i=n[e];c(i)&&"boolean"==typeof i.enabled&&(t[e]={enabled:i.enabled,...c(i.config)?{config:i.config}:{}})}const o={...i.COOKIE_CONSENT_DEFAULTS,...c(e.cookieConsent)?e.cookieConsent:{}};return Array.isArray(o.requiredCategories)&&(o.requiredCategories=o.requiredCategories.filter(e=>"string"==typeof e&&r.has(e))),o.requiredCategories&&0!==o.requiredCategories.length||(o.requiredCategories=i.COOKIE_CONSENT_DEFAULTS.requiredCategories),{pageTypePatterns:c(e.pageTypePatterns)?{...i.DEFAULT_PAGE_TYPE_PATTERNS,...e.pageTypePatterns}:{...i.DEFAULT_PAGE_TYPE_PATTERNS},trackingModules:t,cookieConsent:o}};const i=n(555),o=new Set(i.CANONICAL_EVENTS),r=new Set(["necessary","analytics","marketing","preferences"]),a=new Set(["auto","manual","patterns"]),s=new Set(i.FREQUENCY_CAP_INTERVALS),l=new Set(["perSession","perDay","perWeek","total","minInterval"]);function c(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function d(e){return s.has(e)}},529(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(115),t),o(n(142),t),o(n(818),t),o(n(259),t)},542(e,t){function n(){const e=t.SEARCH_STYLE_CONFIGS,n={};return e.forEach(e=>{e.fields.forEach(e=>{n[e.key]=e.default})}),n}Object.defineProperty(t,"__esModule",{value:!0}),t.SUGGESTION_STYLE_CONFIGS=t.SUGGESTION_STYLE_SECTIONS=t.SUGGESTION_SOURCES=t.SHADOW_VALUES=t.DEFAULT_ANIMATION_CONFIG=t.DEFAULT_RESULT_ITEM_CONFIG=t.DEFAULT_CATEGORY_CONFIG=t.SEARCH_STYLE_CONFIGS=t.STYLE_CONFIGS=t.TRANSLATION_SECTION=t.UNIVERSAL_STYLE_SECTIONS=t.CATEGORY_DISPLAY_MODES=t.SEARCH_FLOATING_POSITIONS=t.SEARCH_POSITIONS=void 0,t.getDefaultSearchStyles=n,t.getDefaultSearchConfig=function(){return{isEnabled:!1,styles:n(),searchOnFocus:!1,keepOpen:!1,mobileFullscreen:!0}},t.getShadowValue=function(e){return t.SHADOW_VALUES[e]||"none"},t.getPositionConfig=function(e){return t.SEARCH_POSITIONS.find(t=>t.value===e)},t.getDefaultSuggestionStyles=function(){const e={};return t.SUGGESTION_STYLE_SECTIONS.forEach(t=>{t.fields.forEach(t=>{e[t.key]=t.default})}),e},t.SEARCH_POSITIONS=[{value:"inline",label:"Inline",description:"Insert search box at a specific location using CSS selector",icon:"LayoutTemplate",requiresSelector:!0},{value:"modal",label:"Modal Popup",description:"Centered popup overlay triggered by button or hotkey",icon:"Maximize2"},{value:"floating",label:"Floating Button",description:"Floating search button in corner of screen",icon:"Circle"},{value:"sidebar",label:"Sidebar Panel",description:"Full-height sidebar panel slides in from side",icon:"PanelRight"},{value:"fullscreen",label:"Fullscreen",description:"Full-page overlay with large search experience",icon:"Maximize"}],t.SEARCH_FLOATING_POSITIONS=[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}],t.CATEGORY_DISPLAY_MODES=[{value:"none",label:"None",description:"No category filters shown"},{value:"chips",label:"Filter Chips",description:"Horizontal chips above results"},{value:"sidebar",label:"Sidebar",description:"Category tree in left sidebar"},{value:"dropdown",label:"Dropdown",description:"Category dropdown selector"}],t.UNIVERSAL_STYLE_SECTIONS=[{id:"colors",title:"Colors",icon:"Palette",fields:[{key:"backgroundColor",label:"Background",type:"color",default:"#ffffff"},{key:"textColor",label:"Text Color",type:"color",default:"#1f2937"},{key:"accentColor",label:"Accent Color",type:"color",default:"#6366f1"},{key:"borderColor",label:"Border Color",type:"color",default:"#e5e7eb"},{key:"gradientStart",label:"Gradient Start",type:"color",default:"#6366f1"},{key:"gradientEnd",label:"Gradient End",type:"color",default:"#8b5cf6"},{key:"overlayColor",label:"Overlay Color",type:"color",default:"rgba(0,0,0,0.4)"},{key:"overlayOpacity",label:"Overlay Opacity %",type:"range",min:0,max:100,default:50}]},{id:"input",title:"Search Input",icon:"Search",fields:[{key:"inputBg",label:"Input Background",type:"color",default:"#f9fafb"},{key:"inputBorder",label:"Input Border",type:"color",default:"#d1d5db"},{key:"inputFocus",label:"Input Focus",type:"color",default:"#6366f1"},{key:"inputBorderWidth",label:"Border Width",type:"select",options:["0px","1px","2px","3px","4px"],default:"2px"},{key:"inputRadius",label:"Input Radius",type:"select",options:["0px","4px","8px","12px","24px","9999px"],default:"8px"},{key:"inputHeight",label:"Input Height",type:"select",options:["36px","40px","44px","48px","52px"],default:"44px"},{key:"inputShadow",label:"Input Shadow",type:"select",options:["none","sm","md","lg"],default:"sm"},{key:"inputIcon",label:"Show Icon",type:"toggle",default:!0},{key:"inputSize",label:"Input Styles",type:"select",options:["normal","large","xlarge"],default:"normal"}]},{id:"results",title:"Results Container",icon:"Layout",fields:[{key:"maxHeight",label:"Max Height",type:"select",options:["auto","300px","400px","500px","600px","80vh"],default:"400px"},{key:"containerRadius",label:"Container Radius",type:"select",options:["0px","8px","12px","16px","24px"],default:"12px"},{key:"containerShadow",label:"Container Shadow",type:"select",options:["none","sm","md","lg","xl","2xl"],default:"lg"},{key:"containerBorder",label:"Container Border",type:"toggle",default:!0},{key:"sidebarWidth",label:"Sidebar Width (if applicable)",type:"select",options:["300px","400px","480px","600px"],default:"480px"},{key:"sidebarBg",label:"Sidebar Background",type:"color",default:"#ffffff"}]},{id:"items",title:"Result Items",icon:"Grid",fields:[{key:"gridColumns",label:"Grid Columns",type:"select",options:["1","2","3","4"],default:"1"},{key:"itemGap",label:"Item Gap",type:"select",options:["0px","4px","8px","12px","16px","20px","24px"],default:"12px"},{key:"itemPadding",label:"Item Padding",type:"select",options:["8px","12px","16px","20px","24px"],default:"12px"},{key:"itemRadius",label:"Item Radius",type:"select",options:["0px","4px","8px","12px","16px"],default:"8px"},{key:"itemHoverBg",label:"Hover Background",type:"color",default:"#f9fafb"},{key:"itemShadow",label:"Item Shadow",type:"select",options:["none","sm","md","lg"],default:"none"},{key:"itemHoverShadow",label:"Hover Shadow",type:"select",options:["none","sm","md","lg","xl"],default:"none"},{key:"resultDivider",label:"Show Dividers",type:"toggle",default:!0},{key:"itemHoverScale",label:"Hover Scale Effect",type:"toggle",default:!1},{key:"cardAspect",label:"Card Aspect Ratio",type:"select",options:["auto","1/1","4/3","3/4","16/9"],default:"auto"}]},{id:"images",title:"Images",icon:"Image",fields:[{key:"imageSize",label:"Image Size",type:"select",options:["32px","40px","48px","56px","64px","72px","80px","100%"],default:"56px"},{key:"imageHeight",label:"Image Height (Fixed)",type:"select",options:["auto","100px","120px","150px","180px","200px"],default:"auto"},{key:"imageRadius",label:"Image Radius",type:"select",options:["0px","4px","8px","12px","50%"],default:"8px"},{key:"imageObjectFit",label:"Object Fit",type:"select",options:["cover","contain","fill"],default:"cover"},{key:"imageOverlay",label:"Dark Overlay",type:"toggle",default:!1},{key:"imageBorder",label:"Image Border",type:"toggle",default:!1}]},{id:"typography",title:"Typography",icon:"Type",fields:[{key:"fontFamily",label:"Font Family",type:"font",default:"inherit"},{key:"titleSize",label:"Title Size",type:"select",options:["12px","13px","14px","15px","16px","18px","20px","24px"],default:"14px"},{key:"titleWeight",label:"Title Weight",type:"select",options:["normal","medium","semibold","bold"],default:"medium"},{key:"descSize",label:"Description Size",type:"select",options:["10px","11px","12px","13px","14px"],default:"12px"},{key:"priceSize",label:"Price Size",type:"select",options:["12px","13px","14px","15px","16px","18px","20px"],default:"14px"},{key:"priceColor",label:"Price Color",type:"color",default:"#059669"},{key:"oldPriceColor",label:"Old Price Color",type:"color",default:"#9ca3af"},{key:"showOverlay",label:"Text Overlay on Image",type:"toggle",default:!1},{key:"overlayPosition",label:"Overlay Position",type:"select",options:["bottom","center","full"],default:"bottom"}]},{id:"badges",title:"Badges & Highlights",icon:"Tag",fields:[{key:"discountBadgeBg",label:"Discount Badge Bg",type:"color",default:"#dc2626"},{key:"discountBadgeText",label:"Discount Badge Text",type:"color",default:"#ffffff"},{key:"badgeRadius",label:"Badge Radius",type:"select",options:["0px","2px","4px","8px","9999px"],default:"4px"},{key:"highlightBg",label:"Highlight Match Bg",type:"color",default:"#fef08a"},{key:"highlightText",label:"Highlight Match Text",type:"color",default:"#1f2937"},{key:"highlightRadius",label:"Highlight Radius",type:"select",options:["0px","2px","4px"],default:"2px"},{key:"showDiscountBadge",label:"Show Discount",type:"toggle",default:!0},{key:"showStockBadge",label:"Show Stock",type:"toggle",default:!1}]},{id:"animation",title:"Animations",icon:"Zap",fields:[{key:"animationType",label:"Animation Type",type:"select",options:["none","fade","slide","scale"],default:"fade"},{key:"transitionDuration",label:"Duration",type:"select",options:["100ms","200ms","300ms","400ms"],default:"200ms"},{key:"staggerDelay",label:"Stagger Delay",type:"select",options:["0ms","30ms","50ms","80ms"],default:"30ms"}]},{id:"category_style",title:"Category Styling",icon:"FolderTree",fields:[{key:"categoryActiveBg",label:"Active Category Bg",type:"color",default:"#6366f1"},{key:"categoryActiveText",label:"Active Category Text",type:"color",default:"#ffffff"},{key:"categoryPadding",label:"Category Padding",type:"select",options:["8px","12px","16px"],default:"12px"},{key:"categorySidebarWidth",label:"Sidebar Width",type:"select",options:["120px","150px","180px","200px","250px"],default:"120px"},{key:"categoryNaming",label:"Category Naming",type:"select",options:["full_path","last_part","first_part"],default:"full_path"},{key:"categoryRadius",label:"Category Radius",type:"select",options:["4px","8px","12px"],default:"8px"}]},{id:"localization",title:"Currency & Localization",icon:"Languages",fields:[{key:"currencySymbol",label:"Currency Symbol",type:"text",default:"$",placeholder:"$ or €"},{key:"currencyPosition",label:"Currency Position",type:"select",options:["left","right","left-space","right-space"],default:"left"},{key:"priceDecimals",label:"Decimals",type:"select",options:["0","2"],default:"2"},{key:"decimalSeparator",label:"Decimal Separator",type:"text",default:".",placeholder:"."},{key:"thousandSeparator",label:"Thousand Separator",type:"text",default:",",placeholder:","}]},{id:"custom_css",title:"Custom CSS",icon:"Code",fields:[{key:"customCss",label:"Custom CSS",type:"textarea",default:"",placeholder:".ws-search-item { background: red; }"}]}],t.TRANSLATION_SECTION={id:"translations",title:"Text & Translations",icon:"Languages",fields:[{key:"textSearchHeader",label:"Header Title",type:"text",default:"Search",placeholder:"Search"},{key:"textPlaceholder",label:"Input Placeholder",type:"text",default:"Search products...",placeholder:"Search products..."},{key:"textLoading",label:"Loading Text",type:"text",default:"Searching...",placeholder:"Searching..."},{key:"textEmpty",label:"No Results Text",type:"text",default:"No products found",placeholder:"No products found"},{key:"textInStock",label:"In Stock Text",type:"text",default:"In Stock",placeholder:"In Stock"},{key:"textOutOfStock",label:"Out of Stock Text",type:"text",default:"Out of Stock",placeholder:"Out of Stock"},{key:"textCategories",label:"Categories Title",type:"text",default:"Categories",placeholder:"Categories"},{key:"textAll",label:'"All" Label',type:"text",default:"All",placeholder:"All"},{key:"textFooter",label:"Footer Text",type:"text",default:"{total} products found in {time}ms",placeholder:"{total} products found in {time}ms"}]},t.STYLE_CONFIGS=t.UNIVERSAL_STYLE_SECTIONS,t.SEARCH_STYLE_CONFIGS=t.UNIVERSAL_STYLE_SECTIONS,t.DEFAULT_CATEGORY_CONFIG={displayMode:"none",showCount:!0,maxVisible:10,expandable:!0,hierarchical:!1},t.DEFAULT_RESULT_ITEM_CONFIG={layout:"list",showImage:!0,showDescription:!1,showPrice:!0,showOldPrice:!0,showDiscount:!0,showStock:!1,showCategory:!1,showRating:!1,imageSize:"medium",imagePosition:"left",truncateTitle:60,truncateDescription:100},t.DEFAULT_ANIMATION_CONFIG={type:"fade",duration:200,easing:"ease-out"},t.SHADOW_VALUES={none:"none",sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)",xl:"0 20px 25px -5px rgba(0, 0, 0, 0.1)","2xl":"0 25px 50px -12px rgba(0, 0, 0, 0.25)"},t.SUGGESTION_SOURCES=[{value:"manual",label:"Manual Only",description:"Only show items you manually add"},{value:"dynamic",label:"Dynamic Only",description:"Automatically show based on search analytics"},{value:"both",label:"Both",description:"Show both manual and dynamic items"}],t.SUGGESTION_STYLE_SECTIONS=[{id:"suggestion_general",title:"General",icon:"Layout",fields:[{key:"sectionHeaderColor",label:"Header Color",type:"color",default:"#9ca3af"},{key:"sectionHeaderSize",label:"Header Size",type:"select",options:["10px","11px","12px","13px"],default:"11px"},{key:"sectionHeaderWeight",label:"Header Weight",type:"select",options:["400","500","600","700"],default:"600"},{key:"sectionSpacing",label:"Section Spacing",type:"select",options:["12px","16px","20px","24px"],default:"16px"},{key:"sectionDivider",label:"Show Dividers",type:"toggle",default:!0},{key:"sectionDividerColor",label:"Divider Color",type:"color",default:"#f3f4f6"}]},{id:"suggestion_recent",title:"Recent Searches",icon:"History",fields:[{key:"recentIconColor",label:"Icon Color",type:"color",default:"#d1d5db"},{key:"recentTextColor",label:"Text Color",type:"color",default:"#374151"},{key:"recentHoverBg",label:"Hover Background",type:"color",default:"#f8fafc"},{key:"recentClearColor",label:"Clear Button Color",type:"color",default:"#6366f1"},{key:"textRecentSearches",label:"Section Title",type:"text",default:"Recent Searches",placeholder:"Recent Searches"},{key:"textClearRecent",label:"Clear Button Text",type:"text",default:"Clear",placeholder:"Clear"}]},{id:"suggestion_popular_searches",title:"Popular Searches",icon:"TrendingUp",fields:[{key:"popularSearchIconColor",label:"Icon Color",type:"color",default:"#fbbf24"},{key:"popularSearchTextColor",label:"Text Color",type:"color",default:"#374151"},{key:"popularSearchHoverBg",label:"Hover Background",type:"color",default:"#f8fafc"},{key:"textPopularSearches",label:"Section Title",type:"text",default:"Popular Searches",placeholder:"Popular Searches"}]},{id:"suggestion_categories",title:"Popular Categories",icon:"Tags",fields:[{key:"categoryCardBg",label:"Card Background",type:"color",default:"#f8fafc"},{key:"categoryCardBorder",label:"Card Border",type:"color",default:"transparent"},{key:"categoryCardRadius",label:"Card Radius",type:"select",options:["8px","10px","12px","16px"],default:"12px"},{key:"categoryCardHoverBg",label:"Card Hover Bg",type:"color",default:"#f1f5f9"},{key:"categoryCardHoverBorder",label:"Card Hover Border",type:"color",default:"#6366f1"},{key:"categoryImageSize",label:"Image Size",type:"select",options:["36px","40px","48px","56px","64px"],default:"48px"},{key:"categoryImageRadius",label:"Image Radius",type:"select",options:["6px","8px","10px","12px","50%"],default:"10px"},{key:"categoryImageBg",label:"Image Background",type:"color",default:"#e2e8f0"},{key:"categoryNameColor",label:"Name Color",type:"color",default:"#475569"},{key:"categoryNameSize",label:"Name Size",type:"select",options:["11px","12px","13px","14px"],default:"12px"},{key:"categoryColumns",label:"Columns",type:"select",options:["auto","2","3","4","5","6"],default:"auto"},{key:"categoryGap",label:"Gap",type:"select",options:["8px","10px","12px","16px"],default:"10px"},{key:"textPopularCategories",label:"Section Title",type:"text",default:"Popular Categories",placeholder:"Popular Categories"}]},{id:"suggestion_products",title:"Popular Products",icon:"Package",fields:[{key:"productCardBg",label:"Card Background",type:"color",default:"#ffffff"},{key:"productCardBorder",label:"Card Border",type:"color",default:"#e2e8f0"},{key:"productCardRadius",label:"Card Radius",type:"select",options:["8px","10px","12px","16px"],default:"12px"},{key:"productCardHoverBorder",label:"Hover Border",type:"color",default:"#6366f1"},{key:"productCardShadow",label:"Card Shadow",type:"select",options:["none","0 1px 3px rgba(0,0,0,0.04)","0 2px 8px rgba(0,0,0,0.08)","0 4px 12px rgba(0,0,0,0.1)"],default:"0 1px 3px rgba(0,0,0,0.04)"},{key:"productCardHoverShadow",label:"Hover Shadow",type:"select",options:["none","0 4px 12px rgba(0,0,0,0.08)","0 8px 24px rgba(0,0,0,0.12)","0 12px 32px rgba(0,0,0,0.15)"],default:"0 8px 24px rgba(0,0,0,0.12)"},{key:"productImageHeight",label:"Image Height",type:"select",options:["80px","100px","120px","140px"],default:"100px"},{key:"productImageBg",label:"Image Background",type:"color",default:"#f8fafc"},{key:"productNameColor",label:"Name Color",type:"color",default:"#1e293b"},{key:"productNameSize",label:"Name Size",type:"select",options:["12px","13px","14px","15px"],default:"13px"},{key:"productPriceColor",label:"Price Color",type:"color",default:"#059669"},{key:"productPriceSize",label:"Price Size",type:"select",options:["13px","14px","15px","16px"],default:"15px"},{key:"productOldPriceColor",label:"Old Price Color",type:"color",default:"#9ca3af"},{key:"productColumns",label:"Columns",type:"select",options:["auto","2","3","4"],default:"auto"},{key:"productGap",label:"Gap",type:"select",options:["8px","12px","16px","20px"],default:"12px"},{key:"textPopularProducts",label:"Section Title",type:"text",default:"Popular Products",placeholder:"Popular Products"}]}],t.SUGGESTION_STYLE_CONFIGS=t.SUGGESTION_STYLE_SECTIONS},555(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.FREQUENCY_CAP_INTERVALS=t.COOKIE_CONSENT_DEFAULTS=t.TRACKING_MODULES=t.DEFAULT_PAGE_TYPE_PATTERNS=t.EVENT_CATEGORIES=t.CANONICAL_EVENTS=void 0,t.CANONICAL_EVENTS=["page_view","virtual_page_view","widget_view","category_view","product_view","product_click","product_impression","product_dwell_time","add_to_cart","remove_from_cart","update_cart","cart_abandon","cart_restore","checkout_begin","checkout_progress","checkout_option","purchase","user_signup","user_login","user_logout","user_update","search_instant_open","search_query","search_filter","search_sort","search_page","search_results","search_zero_results","search_close","impression","click","close","view","hover","scroll","slider_navigate","slider_swipe","widget_impression","script_injected","script_error","identify","category_filter","recent_search_click","popular_search_click","popular_category_click","popular_product_click","wishlist","custom_event"],t.EVENT_CATEGORIES={page_view:"page",virtual_page_view:"page",widget_view:"engagement",category_view:"commerce",product_view:"commerce",product_click:"search",product_impression:"commerce",product_dwell_time:"commerce",add_to_cart:"commerce",remove_from_cart:"commerce",update_cart:"commerce",cart_abandon:"commerce",cart_restore:"commerce",checkout_begin:"commerce",checkout_progress:"commerce",checkout_option:"commerce",purchase:"commerce",user_signup:"user",user_login:"user",user_logout:"user",user_update:"user",search_instant_open:"search",search_query:"search",search_filter:"search",search_sort:"search",search_page:"search",search_results:"search",search_zero_results:"search",search_close:"search",impression:"engagement",click:"engagement",close:"engagement",view:"engagement",hover:"engagement",scroll:"engagement",slider_navigate:"recommendation",slider_swipe:"recommendation",widget_impression:"recommendation",script_injected:"system",script_error:"system",identify:"user",category_filter:"search",recent_search_click:"search",popular_search_click:"search",popular_category_click:"search",popular_product_click:"search",wishlist:"commerce",custom_event:"engagement"},t.DEFAULT_PAGE_TYPE_PATTERNS={home:"^/$|\\/index\\.html?$",product:"\\/(products?|p|item)s?\\/[a-z0-9-]+",category:"\\/(categories?|c|collection)s?\\/[a-z0-9-]+",search:"\\/(search|find)",checkout:"\\/(checkout|payment|order)",cart:"\\/(cart|basket)",account:"\\/(account|profile|my-account)"},t.TRACKING_MODULES={page:{enabled:!0},product:{enabled:!0},basket:{enabled:!0},checkout:{enabled:!0},user:{enabled:!1},search:{enabled:!1}},t.COOKIE_CONSENT_DEFAULTS={enabled:!1,variableName:"__wcmp_consent",waitForConsent:!1,defaultConsent:!0,granularEnabled:!1,requiredCategories:["necessary"],timeoutMs:5e3,storageKey:"selwise_consent",consentChangeCallback:""},t.FREQUENCY_CAP_INTERVALS=["","15m","30m","1h","2h","6h","12h","1d","1w"]},561(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(48),t),o(n(542),t),o(n(882),t)},664(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(773),t),o(n(555),t),o(n(273),t)},773(e,t){Object.defineProperty(t,"__esModule",{value:!0})},818(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.isWidgetType=function(e){return"string"==typeof e&&r.has(e)},t.validatePlacement=function(e,t){if(null==t)return{valid:!0};if(!a(t))return{valid:!1,message:"invalid position for widget type"};const n=(0,i.getWidgetTypeConfig)(e);if(!n)return{valid:!1,message:"invalid position for widget type"};if(void 0!==t.position){if("string"!=typeof t.position)return{valid:!1,message:"invalid position for widget type"};const e=n.placementOptions||[];if(e.length>0&&!e.includes(t.position))return{valid:!1,message:"invalid position for widget type"}}if(void 0!==t.insertPosition&&("string"!=typeof t.insertPosition||!o.has(t.insertPosition)))return{valid:!1,message:"invalid insert position for widget type"};if(void 0!==t.placementType){if("fixed"!==t.placementType&&"selector"!==t.placementType)return{valid:!1,message:"invalid placement type for widget type"};if("fixed"===n.placementType&&"fixed"!==t.placementType)return{valid:!1,message:"invalid placement type for widget type"};if("selector"===n.placementType&&"selector"!==t.placementType)return{valid:!1,message:"invalid placement type for widget type"}}return"selector"!==s(e,t)||"string"==typeof t.selector&&t.selector.trim()?{valid:!0}:{valid:!1,message:"selector is required for selector placement"}},t.validateStyles=function(e,t){if(null==t)return{valid:!0};if(!a(t))return{valid:!1,message:"invalid style key"};const n=new Set((0,i.getAllowedStyleKeys)(e)),o=Object.keys(t).filter(e=>!n.has(e));return o.length>0?{valid:!1,message:`invalid style key: ${o.join(", ")}`,invalidKeys:o}:{valid:!0}},t.sanitizeStyles=function(e,t){const n=(0,i.getDefaultStyles)(e);if(!a(t))return n;const o=new Set((0,i.getAllowedStyleKeys)(e)),r={...n};for(const[e,n]of Object.entries(t))o.has(e)&&(r[e]=n);return r},t.sanitizePlacement=function(e,t){const n=(0,i.getWidgetTypeConfig)(e),r=a(t)?t:{},l={};if("string"==typeof r.selector&&r.selector.trim().length>0&&(l.selector=r.selector.trim()),"string"==typeof r.insertPosition&&o.has(r.insertPosition)&&(l.insertPosition=r.insertPosition),n?.placementOptions?.length){const e=new Set(n.placementOptions);"string"==typeof r.position&&e.has(r.position)?l.position=r.position:"selector"!==n.placementType&&(l.position=n.placementOptions[0])}const c=s(e,r);return l.placementType=c,a(r.conflictResolution)&&(l.conflictResolution=r.conflictResolution),a(r.frequencyCap)&&(l.frequencyCap=r.frequencyCap),l};const i=n(142),o=new Set(["before","after","inside-start","inside-end","replace"]),r=new Set(i.WIDGET_TYPES.map(e=>e.value));function a(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function s(e,t){const n=(0,i.getWidgetTypeConfig)(e);return n?"fixed"===n.placementType?"fixed":"selector"===n.placementType||"selector"===t.placementType?"selector":"fixed"===t.placementType?"fixed":"string"==typeof t.selector&&t.selector.trim().length>0?"selector":"fixed":"fixed"}},882(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.getAllowedSearchStyleKeys=p,t.getAllowedSuggestionStyleKeys=h,t.validateSearchStyles=g,t.sanitizeSearchStyles=function(e){const t=(0,i.getDefaultSearchStyles)();if(!u(e))return t;const n=new Set(p()),o={...t};for(const[t,i]of Object.entries(e))n.has(t)&&(o[t]=i);return o},t.sanitizeSuggestionStyles=function(e){const t=(0,i.getDefaultSuggestionStyles)();if(!u(e))return t;const n=new Set(h()),o={...t};for(const[t,i]of Object.entries(e))n.has(t)&&(o[t]=i);return o},t.validateSearchConfig=function(e){return void 0===e.position||"string"==typeof e.position&&l.has(e.position)?void 0===e.floatingPosition||"string"==typeof e.floatingPosition&&c.has(e.floatingPosition)?void 0===e.categoryDisplayMode||"string"==typeof e.categoryDisplayMode&&d.has(e.categoryDisplayMode)?void 0===e.resultLayout||"string"==typeof e.resultLayout&&o.includes(e.resultLayout)?void 0===e.imageSize||"string"==typeof e.imageSize&&r.has(e.imageSize)?void 0===e.imagePosition||"string"==typeof e.imagePosition&&a.has(e.imagePosition)?void 0===e.animationType||"string"==typeof e.animationType&&s.has(e.animationType)?g(e.stylesJson,e.suggestionStylesJson):{valid:!1,message:"invalid animation type"}:{valid:!1,message:"invalid image position"}:{valid:!1,message:"invalid image size"}:{valid:!1,message:"invalid result layout"}:{valid:!1,message:"invalid category display mode"}:{valid:!1,message:"invalid floating position"}:{valid:!1,message:"invalid search position"}};const i=n(542),o=["list","grid","compact","large"],r=new Set(["small","medium","large"]),a=new Set(["left","top","right"]),s=new Set(["none","fade","slide","scale"]),l=new Set(i.SEARCH_POSITIONS.map(e=>e.value)),c=new Set(i.SEARCH_FLOATING_POSITIONS.map(e=>e.value)),d=new Set(i.CATEGORY_DISPLAY_MODES.map(e=>e.value));function u(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function p(){return i.SEARCH_STYLE_CONFIGS.flatMap(e=>e.fields.map(e=>e.key))}function h(){return i.SUGGESTION_STYLE_CONFIGS.flatMap(e=>e.fields.map(e=>e.key))}function g(e,t){if(void 0!==e){if(!u(e))return{valid:!1,message:"invalid search style payload"};const t=new Set(p()),n=Object.keys(e).filter(e=>!t.has(e));if(n.length>0)return{valid:!1,message:`invalid style key: ${n.join(", ")}`,invalidKeys:n}}if(void 0!==t){if(!u(t))return{valid:!1,message:"invalid suggestion style payload"};const e=new Set(h()),n=Object.keys(t).filter(t=>!e.has(t));if(n.length>0)return{valid:!1,message:`invalid style key: ${n.join(", ")}`,invalidKeys:n}}return{valid:!0}}},927(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.validateRecommendationConfig=function(e){if(!o(e))return{valid:!1,message:"invalid recommendation payload"};if(void 0!==e.strategy&&!i.RECOMMENDATION_STRATEGIES.includes(e.strategy))return{valid:!1,message:"invalid recommendation strategy"};if(void 0!==e.displayType&&!i.RECOMMENDATION_DISPLAY_TYPES.includes(e.displayType))return{valid:!1,message:"invalid display type"};if(void 0!==e.trigger&&!i.RECOMMENDATION_TRIGGERS.includes(e.trigger))return{valid:!1,message:"invalid trigger type"};if(void 0!==e.insertPosition&&!i.RECOMMENDATION_INSERT_POSITIONS.includes(e.insertPosition))return{valid:!1,message:"invalid insert position"};if(void 0!==e.cartPlatform&&!i.RECOMMENDATION_PLATFORMS.includes(e.cartPlatform))return{valid:!1,message:"invalid cart platform"};const t=["arrowStyles","dotStyles","titleStyles","subtitleStyles","containerStyles"];for(const n of t){const t=a(n,e[n]);if(!t.valid)return t}return{valid:!0}},t.sanitizeRecommendationConfig=function(e){const t=(0,i.getDefaultRecommendationConfig)();if(!o(e))return t;const n=["arrowStyles","dotStyles","titleStyles","subtitleStyles","containerStyles"],a={...t,...e};a.showOnAllPages=void 0===e.showOnAllPages?t.showOnAllPages:Boolean(e.showOnAllPages),a.includeUrls=r(e.includeUrls),a.excludeUrls=r(e.excludeUrls);for(const t of n){const n=i.RECOMMENDATION_STYLE_CONFIGS[t],r=n.fields.reduce((e,t)=>(e[t.key]=t.default,e),{}),s=o(e[t])?e[t]:{},l=new Set(n.fields.map(e=>e.key));for(const[e,t]of Object.entries(s))l.has(e)&&(r[e]=t);a[t]=r}return a};const i=n(213);function o(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const i of e){if("string"!=typeof i)continue;const e=i.trim();e&&(t.has(e)||(t.add(e),n.push(e)))}return n}function a(e,t){if(void 0===t)return{valid:!0};if(!o(t))return{valid:!1,message:`invalid ${e} payload`};const n=i.RECOMMENDATION_STYLE_CONFIGS[e],r=new Set(n.fields.map(e=>e.key)),a=Object.keys(t).filter(e=>!r.has(e));return a.length>0?{valid:!1,message:`invalid style key: ${a.join(", ")}`,invalidKeys:a}:{valid:!0}}}},t={};function n(i){var o=t[i];if(void 0!==o)return o.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);let i=!1;var o=n(529);const r="selwise_sid",a="selwise_vid",s="selwise_suid",l="selwise_supid",c="selwise_journey_id",d="selwise_journey_created",u="selwise_correlation_id",p="selwise_correlation_created",h="selwise_test_mode",g="selwise_last_touch",m="selwise_last_touch_reco",f="selwise_last_touch_search",y="selwise_experiments",b="selwise_consent",w="selwise_interacted_",S="selwise_merged_vids",x="selwise_user_traits",v={necessary:["page_view","click","form_submit","button_click"],analytics:["product_view","search","add_to_cart","remove_from_cart","checkout","purchase","view_content"],marketing:["impression","banner_click","campaign_view"],preferences:["theme_change","language_change","currency_change"]},C="data-selwise-root",k="data-selwise-entity-id",T="data-selwise-entity-type",I=`[${C}="true"]`,E=new Map;function _(e){return{none:"none",sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)",xl:"0 20px 25px -5px rgba(0, 0, 0, 0.1)","2xl":"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}[e||"none"]||"none"}function P(e){return{normal:"400",medium:"500",semibold:"600",bold:"700"}[e||"normal"]||"400"}function A(e,t,n){const i="campaign"===t.__entityType?"campaign":"widget";e.dataset.widgetId=t.id,e.dataset.campaignId=n.id,e.dataset.widgetType=t.type,e.setAttribute(C,"true"),e.setAttribute(k,t.id),e.setAttribute(T,i)}function $(e){const t=E.get(e);t&&(t.observer&&t.observer.disconnect(),null!==t.timeoutId&&clearTimeout(t.timeoutId),E.delete(e))}function O(e,t,n=6e3){$(e);const i=()=>{try{const n=t();return n&&$(e),n}catch(t){return console.error("[Selwise] Deferred renderer failed:",t),$(e),!0}};if(i())return;if("undefined"==typeof MutationObserver||!document.documentElement)return;const o=new MutationObserver(()=>{i()});o.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0});const r=window.setTimeout(()=>{$(e)},n);E.set(e,{observer:o,timeoutId:r})}function D(e,t){const n=document.createElement("button");return n.className="selwise-close",n.style.color=e,n.innerHTML="×",n.addEventListener("click",e=>{e.stopPropagation(),t()}),n}function M(e,t){try{const{selector:n,insertPosition:i="after"}=t,o=document.querySelector(n||"");if(!o)return console.warn(`[Selwise] Selector not found: ${n}`),!1;switch(i){case"before":o.parentNode?.insertBefore(e,o);break;case"after":default:o.parentNode?.insertBefore(e,o.nextSibling);break;case"inside-start":o.insertBefore(e,o.firstChild);break;case"inside-end":o.appendChild(e);break;case"replace":o.replaceWith(e)}return!0}catch(e){return!1}}function N(e){try{return!!localStorage.getItem(`${w}${e}`)}catch{return!1}}function R(e){try{localStorage.setItem(`${w}${e}`,"true")}catch{}}function L(e){if(!e)return"#";const t=e.trim();return t&&/^(https?:|mailto:|tel:|\/|#)/i.test(t)?t:"#"}function B(e){if(!function(e){if(!e)return!1;const t=e.trim();return!!t&&/^(https?:|data:image\/|blob:|\/)/i.test(t)}(e.imageUrl))return null;const t=document.createElement("img");var n,i;return t.src=e.imageUrl.trim(),t.alt=e.alt||"",t.loading=e.loading||"lazy",n=t,i=function(e){const t=e.mode||"thumbnail",n=e.size||"60px",i=e.aspectRatio||"auto",o=e.objectFit||"cover",r={borderRadius:e.borderRadius||"8px",objectFit:o,display:"block"};return"thumbnail"===t?(r.width=n,r.height=n,r.flexShrink="0",r):(r.width="100%","fullWidth"===t?(r.height="auto","auto"!==i&&(r.aspectRatio=i),r):("auto"!==i&&(r.aspectRatio=i),r))}(e),Object.entries(i).forEach(([e,t])=>{null!=t&&""!==t&&n.style.setProperty(e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),t)}),t}function U(e,t,n,i=6e3){const o=t.placementConfigJson||{},r=(a=o)?"string"!=typeof a.selector?"":a.selector.trim():"";var a;if(!r)return $(n),console.warn(`[Selwise] Selector is required for widget type "${t.type}": ${t.id}`),!1;const s={...o,selector:r};return M(e,s)?($(n),!0):(O(n,()=>M(e,s),i),!1)}let z=!1;function F(e,t,n,i){const o=document.createElement("div");o.className="selwise-countdown-unit";const r=document.createElement("div");r.className="selwise-countdown-value",r.dataset.unit=e,r.style.fontSize=n,r.style.fontWeight=P(i),r.textContent="00";const a=document.createElement("div");return a.className="selwise-countdown-label",a.textContent=t,o.appendChild(r),o.appendChild(a),o}let q=!1;function j(e){q=e}function H(){if("undefined"==typeof localStorage)return!1;try{return q||"true"===localStorage.getItem("selwise_test_mode")||"true"===localStorage.getItem("selwise_debug")}catch{return q}}const W=(e,...t)=>{H()&&console.log(`[${e}]`,...t)},G=(e,...t)=>{H()&&console.debug(`[${e}]`,...t)},K=(e,...t)=>{console.error(`[${e}]`,...t)},J=(e,...t)=>{console.warn(`[${e}]`,...t)};function V(e,t){try{const n=`${b}_${e}`;if(localStorage.setItem(n,JSON.stringify(t)),window.Selwise?._consentChangeCallback)try{const e=window.Selwise._consentChangeCallback;"function"==typeof window[e]&&window[e]("granted",t)}catch{}}catch{}}function Y(e,t){const n=window.Selwise?.siteKey;if(!n)return null;const i=function(e){try{const t=`${b}_${e}`,n=localStorage.getItem(t);if(n)return JSON.parse(n)}catch{}return null}(n);if(i?.granted)return null;const o=t.contentJson||{},r=t.stylesJson||{};W("CookieConsent","campaign payload:",{content:o,styles:r});const a=r,s=window.Selwise?.trackingConfig?.cookieConsent||{},l=e.configJson||{},c={granularEnabled:a.granularEnabled??s.granularEnabled??l.granularEnabled??!1,requiredCategories:(d=a.requiredCategories??s.requiredCategories??l.requiredCategories??"necessary",Array.isArray(d)?d:"string"==typeof d?d.split(",").map(e=>e.trim()).filter(Boolean):["necessary"]),timeoutMs:a.timeoutMs??s.timeoutMs??l.timeoutMs??0};var d;const u=c.granularEnabled??!1,p=new Set(c.requiredCategories||["necessary"]),h=c.timeoutMs||0;W("Selwise","Cookie consent config:",{isGranular:u,requiredCategories:Array.from(p),timeoutMs:h});const g={granted:!1,timestamp:Date.now(),categories:{necessary:!0,analytics:p.has("analytics"),marketing:p.has("marketing"),preferences:p.has("preferences")}},{headline:m,text:f,buttonText:y,declineButtonText:w="Decline",customizeButtonText:S="Customize",subtext:x,linkText:v,linkUrl:C,policyLinkText:k,policyLinkUrl:T}=o,{backgroundColor:I="#1a1a1a",textColor:E="#ffffff",buttonColor:P,buttonTextColor:$,declineButtonColor:O,declineButtonTextColor:D,customizeButtonColor:M,customizeButtonTextColor:N,padding:R="16px",borderRadius:B="8px",shadow:U="lg",border:z="none",maxWidth:F,showDeclineButton:q=!0,showCustomizeButton:j=!0,showCloseButton:H=!1,autoHideAfterMs:G=0,linkColor:K="#60a5fa",headlineFontSize:J,headlineFontWeight:Y,textFontSize:Q,buttonFontSize:X,buttonFontWeight:Z}=r,ee=m||"We use cookies",te=f||x||"",ne=e.placementConfigJson?.position||"bottom",ie=P||E,oe=$||I,re=O||"transparent",ae=D||E,se=O?"none":`1px solid ${E}`,le=M||"transparent",ce=N||E,de=v||k||"",ue=L(String(C||T||"")),pe=e=>function(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}(String(e??"")),he=document.createElement("div");he.className=`selwise-widget selwise-bar selwise-bar-${ne} selwise-consent-banner`,he.style.cssText=`\n background-color: ${I};\n color: ${E};\n flex-wrap: wrap;\n padding: ${R};\n border-radius: ${B};\n box-shadow: ${_(U)};\n ${z&&"none"!==z?`border: ${z};`:""}\n ${F&&"bottom"===ne?`max-width: ${F}; left: 50%; bottom: 20px;`:""}\n ${"center-modal"===ne?`\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n max-width: ${F||"500px"};\n width: ${F?"auto":"90%"};\n z-index: 2147483647;\n `:"bottom-left"===ne?`\n position: fixed;\n bottom: 20px;\n left: 20px;\n max-width: ${F||"400px"};\n z-index: 2147483647;\n `:"bottom-right"===ne?`\n position: fixed;\n bottom: 20px;\n right: 20px;\n max-width: ${F||"400px"};\n z-index: 2147483647;\n `:`\n position: fixed;\n ${"top"===ne?"top: 0;":"bottom: 0;"}\n left: 0;\n right: 0;\n z-index: 2147483647;\n `}\n `,A(he,e,t);const ge={necessary:{label:"Essential",description:"Required for basic functionality"},analytics:{label:"Analytics",description:"Track user behavior and site usage"},marketing:{label:"Marketing",description:"Personalized ads and campaigns"},preferences:{label:"Preferences",description:"Remember user settings"}};let me={...g};function fe(){he.innerHTML=u&&we?`\n <div class="selwise-consent-customize" style="max-width: 500px; margin: 0 auto; position: relative;">\n ${H?`<button type="button" class="selwise-consent-close" style="position: absolute; top: -6px; right: -6px; background: transparent; border: none; color: ${pe(E)}; font-size: 18px; cursor: pointer; opacity: 0.75;">×</button>`:""}\n <h3 style="font-size: ${pe(J||"16px")}; font-weight: ${pe(Y||"600")}; margin-bottom: 12px;">Customize your preferences</h3>\n <div style="margin-bottom: 16px;">\n ${Object.entries(ge).map(([e,t])=>{const n="necessary"===e,i=me.categories[e];return`\n <div class="selwise-consent-category" style="display: flex; align-items: center; justify-content: space-between; padding: 10px; background: rgba(255,255,255,0.05); border-radius: 6px; margin-bottom: 8px;">\n <div style="flex: 1;">\n <div style="font-size: 14px; font-weight: 500;">${pe(t.label)}</div>\n <div style="font-size: 12px; opacity: 0.7;">${pe(t.description)}</div>\n </div>\n <button\n type="button"\n class="selwise-consent-toggle selwise-consent-toggle-${e}"\n data-category="${e}"\n style="${n?"opacity: 0.5; cursor: not-allowed;":""} cursor: pointer; width: 44px; height: 24px; border-radius: 12px; background: ${i?"#22c55e":"#4b5563"}; position: relative; transition: background 0.2s;"\n ${n?"disabled":""}\n >\n <span style="position: absolute; top: 2px; ${i?"left: 22px;":"left: 2px;"} width: 20px; height: 20px; background: white; border-radius: 50%; transition: left 0.2s;"></span>\n </button>\n </div>\n `}).join("")}\n </div>\n <div style="display: flex; gap: 8px; justify-content: flex-end;">\n <button class="selwise-bar-btn selwise-back" style="background: transparent; border: 1px solid ${pe(E)}; color: ${pe(E)}; padding: 8px 16px; border-radius: 6px; font-size: ${pe(X||"13px")}; font-weight: ${pe(Z||"normal")}; cursor: pointer;">\n Back\n </button>\n <button class="selwise-bar-btn selwise-save" style="background: ${pe(ie)}; color: ${pe(oe)}; padding: 8px 16px; border-radius: 6px; font-size: ${pe(X||"13px")}; font-weight: ${pe(Z||"normal")}; cursor: pointer;">\n Save Preferences\n </button>\n </div>\n </div>\n `:`\n ${H?`<button type="button" class="selwise-consent-close" style="position: absolute; top: 8px; right: 10px; background: transparent; border: none; color: ${pe(E)}; font-size: 18px; cursor: pointer; opacity: 0.75;">×</button>`:""}\n <span class="selwise-bar-text" style="flex: 1; min-width: 200px; margin-right: 16px;">\n <span style="font-size: ${pe(J||"16px")}; font-weight: ${pe(Y||"600")}; display: block;">${pe(ee)}</span>\n ${te?`<span style="font-size: ${pe(Q||"14px")}; font-weight: normal; opacity: 0.9; display: block;">${pe(te)}</span>`:""}\n ${de&&"#"!==ue?`<a class="selwise-consent-link" href="${pe(ue)}" target="_blank" rel="noopener noreferrer" style="font-size: ${pe(Q||"14px")}; color: ${pe(K)}; margin-top: 4px; display: inline-block; text-decoration: underline;">${pe(de)}</a>`:""}\n </span>\n <div style="display: flex; gap: 8px; flex-shrink: 0;">\n ${q?`\n <button class="selwise-bar-btn selwise-decline" style="background: ${pe(re)}; color: ${pe(ae)}; border: ${pe(se)}; padding: 8px 16px; border-radius: 6px; font-size: ${pe(X||"13px")}; font-weight: ${pe(Z||"normal")}; cursor: pointer;">\n ${pe(w)}\n </button>\n `:""}\n ${u&&j?`\n <button class="selwise-bar-btn selwise-customize" style="background: ${pe(le)}; color: ${pe(ce)}; border: ${pe("transparent"===le?`1px solid ${E}`:"none")}; padding: 8px 16px; border-radius: 6px; font-size: ${pe(X||"13px")}; font-weight: ${pe(Z||"normal")}; cursor: pointer;">\n ${pe(S)}\n </button>\n `:""}\n <button class="selwise-bar-btn selwise-accept" style="background: ${pe(ie)}; color: ${pe(oe)}; padding: 8px 16px; border-radius: 6px; font-size: ${pe(X||"13px")}; font-weight: ${pe(Z||"normal")}; cursor: pointer;">\n ${pe(y||"Accept")}\n </button>\n </div>\n `}let ye,be,we=!1,Se=!1;const xe=()=>{ye&&(clearTimeout(ye),ye=void 0),be&&(clearTimeout(be),be=void 0)};function ve(e,t){const i=o.buttonUrl;i&&fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,state:t})}).catch(()=>{});const r=window.Selwise||{},a=r.apiUrl&&`${r.apiUrl}/public/sites/${n}/consent`;a&&fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:t.categories,visitorId:r.visitorId,sessionId:r.sessionId,siteUserId:r.siteUserId,action:e})}).catch(()=>{}),window.Selwise?._flushConsentQueue&&window.Selwise._flushConsentQueue()}return fe(),he.addEventListener("click",e=>{const t=e.target;if(t.classList.contains("selwise-customize"))return we=!0,void fe();if(t.classList.contains("selwise-back"))return we=!1,void fe();if(t.classList.contains("selwise-consent-close"))return Se=!0,xe(),void he.remove();if(t.classList.contains("selwise-consent-toggle")){const e=t.getAttribute("data-category");return void(e&&"necessary"!==e&&(me.categories[e]=!me.categories[e],fe()))}if(t.classList.contains("selwise-accept")){Se=!0,xe();const e={granted:!0,timestamp:Date.now(),categories:{necessary:!0,analytics:!0,marketing:!0,preferences:!0}};return V(n,e),he.remove(),void ve("accepted",e)}if(t.classList.contains("selwise-save"))return Se=!0,xe(),me.granted=!0,me.timestamp=Date.now(),V(n,me),he.remove(),void ve("customized",me);if(t.classList.contains("selwise-decline")){Se=!0,xe();const e={granted:!0,timestamp:Date.now(),categories:{necessary:!0,analytics:!1,marketing:!1,preferences:!1}};return V(n,e),he.remove(),void ve("declined",e)}}),h>0&&(ye=window.setTimeout(()=>{if(Se)return;Se=!0;const e={granted:!0,timestamp:Date.now(),categories:{...g.categories}};V(n,e),he.remove(),ve("timeout",e),xe()},h)),G>0&&(be=window.setTimeout(()=>{Se||(Se=!0,he.remove(),xe())},G)),document.body.appendChild(he),he}const{entries:Q,setPrototypeOf:X,isFrozen:Z,getPrototypeOf:ee,getOwnPropertyDescriptor:te}=Object;let{freeze:ne,seal:ie,create:oe}=Object,{apply:re,construct:ae}="undefined"!=typeof Reflect&&Reflect;ne||(ne=function(e){return e}),ie||(ie=function(e){return e}),re||(re=function(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;o<n;o++)i[o-2]=arguments[o];return e.apply(t,i)}),ae||(ae=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return new e(...n)});const se=ve(Array.prototype.forEach),le=ve(Array.prototype.lastIndexOf),ce=ve(Array.prototype.pop),de=ve(Array.prototype.push),ue=ve(Array.prototype.splice),pe=ve(String.prototype.toLowerCase),he=ve(String.prototype.toString),ge=ve(String.prototype.match),me=ve(String.prototype.replace),fe=ve(String.prototype.indexOf),ye=ve(String.prototype.trim),be=ve(Object.prototype.hasOwnProperty),we=ve(RegExp.prototype.test),Se=(xe=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return ae(xe,t)});var xe;function ve(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];return re(e,t,i)}}function Ce(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:pe;X&&X(e,null);let i=t.length;for(;i--;){let o=t[i];if("string"==typeof o){const e=n(o);e!==o&&(Z(t)||(t[i]=e),o=e)}e[o]=!0}return e}function ke(e){for(let t=0;t<e.length;t++)be(e,t)||(e[t]=null);return e}function Te(e){const t=oe(null);for(const[n,i]of Q(e))be(e,n)&&(Array.isArray(i)?t[n]=ke(i):i&&"object"==typeof i&&i.constructor===Object?t[n]=Te(i):t[n]=i);return t}function Ie(e,t){for(;null!==e;){const n=te(e,t);if(n){if(n.get)return ve(n.get);if("function"==typeof n.value)return ve(n.value)}e=ee(e)}return function(){return null}}const Ee=ne(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),_e=ne(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Pe=ne(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Ae=ne(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),$e=ne(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Oe=ne(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),De=ne(["#text"]),Me=ne(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ne=ne(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Re=ne(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Le=ne(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Be=ie(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Ue=ie(/<%[\w\W]*|[\w\W]*%>/gm),ze=ie(/\$\{[\w\W]*/gm),Fe=ie(/^data-[\-\w.\u00B7-\uFFFF]+$/),qe=ie(/^aria-[\-\w]+$/),je=ie(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),He=ie(/^(?:\w+script|data):/i),We=ie(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ge=ie(/^html$/i),Ke=ie(/^[a-z][.\w]*(-[.\w]+)+$/i);var Je=Object.freeze({__proto__:null,ARIA_ATTR:qe,ATTR_WHITESPACE:We,CUSTOM_ELEMENT:Ke,DATA_ATTR:Fe,DOCTYPE_NAME:Ge,ERB_EXPR:Ue,IS_ALLOWED_URI:je,IS_SCRIPT_OR_DATA:He,MUSTACHE_EXPR:Be,TMPLIT_EXPR:ze});const Ve=function(){return"undefined"==typeof window?null:window};var Ye=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Ve();const n=t=>e(t);if(n.version="3.3.1",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let{document:i}=t;const o=i,r=o.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:h,trustedTypes:g}=t,m=c.prototype,f=Ie(m,"cloneNode"),y=Ie(m,"remove"),b=Ie(m,"nextSibling"),w=Ie(m,"childNodes"),S=Ie(m,"parentNode");if("function"==typeof s){const e=i.createElement("template");e.content&&e.content.ownerDocument&&(i=e.content.ownerDocument)}let x,v="";const{implementation:C,createNodeIterator:k,createDocumentFragment:T,getElementsByTagName:I}=i,{importNode:E}=o;let _={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof Q&&"function"==typeof S&&C&&void 0!==C.createHTMLDocument;const{MUSTACHE_EXPR:P,ERB_EXPR:A,TMPLIT_EXPR:$,DATA_ATTR:O,ARIA_ATTR:D,IS_SCRIPT_OR_DATA:M,ATTR_WHITESPACE:N,CUSTOM_ELEMENT:R}=Je;let{IS_ALLOWED_URI:L}=Je,B=null;const U=Ce({},[...Ee,..._e,...Pe,...$e,...De]);let z=null;const F=Ce({},[...Me,...Ne,...Re,...Le]);let q=Object.seal(oe(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),j=null,H=null;const W=Object.seal(oe(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let G=!0,K=!0,J=!1,V=!0,Y=!1,X=!0,Z=!1,ee=!1,te=!1,ie=!1,re=!1,ae=!1,xe=!0,ve=!1,ke=!0,Be=!1,Ue={},ze=null;const Fe=Ce({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let qe=null;const He=Ce({},["audio","video","img","source","image","track"]);let We=null;const Ke=Ce({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ye="http://www.w3.org/1998/Math/MathML",Qe="http://www.w3.org/2000/svg",Xe="http://www.w3.org/1999/xhtml";let Ze=Xe,et=!1,tt=null;const nt=Ce({},[Ye,Qe,Xe],he);let it=Ce({},["mi","mo","mn","ms","mtext"]),ot=Ce({},["annotation-xml"]);const rt=Ce({},["title","style","font","a","script"]);let at=null;const st=["application/xhtml+xml","text/html"];let lt=null,ct=null;const dt=i.createElement("form"),ut=function(e){return e instanceof RegExp||e instanceof Function},pt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!ct||ct!==e){if(e&&"object"==typeof e||(e={}),e=Te(e),at=-1===st.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,lt="application/xhtml+xml"===at?he:pe,B=be(e,"ALLOWED_TAGS")?Ce({},e.ALLOWED_TAGS,lt):U,z=be(e,"ALLOWED_ATTR")?Ce({},e.ALLOWED_ATTR,lt):F,tt=be(e,"ALLOWED_NAMESPACES")?Ce({},e.ALLOWED_NAMESPACES,he):nt,We=be(e,"ADD_URI_SAFE_ATTR")?Ce(Te(Ke),e.ADD_URI_SAFE_ATTR,lt):Ke,qe=be(e,"ADD_DATA_URI_TAGS")?Ce(Te(He),e.ADD_DATA_URI_TAGS,lt):He,ze=be(e,"FORBID_CONTENTS")?Ce({},e.FORBID_CONTENTS,lt):Fe,j=be(e,"FORBID_TAGS")?Ce({},e.FORBID_TAGS,lt):Te({}),H=be(e,"FORBID_ATTR")?Ce({},e.FORBID_ATTR,lt):Te({}),Ue=!!be(e,"USE_PROFILES")&&e.USE_PROFILES,G=!1!==e.ALLOW_ARIA_ATTR,K=!1!==e.ALLOW_DATA_ATTR,J=e.ALLOW_UNKNOWN_PROTOCOLS||!1,V=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Y=e.SAFE_FOR_TEMPLATES||!1,X=!1!==e.SAFE_FOR_XML,Z=e.WHOLE_DOCUMENT||!1,ie=e.RETURN_DOM||!1,re=e.RETURN_DOM_FRAGMENT||!1,ae=e.RETURN_TRUSTED_TYPE||!1,te=e.FORCE_BODY||!1,xe=!1!==e.SANITIZE_DOM,ve=e.SANITIZE_NAMED_PROPS||!1,ke=!1!==e.KEEP_CONTENT,Be=e.IN_PLACE||!1,L=e.ALLOWED_URI_REGEXP||je,Ze=e.NAMESPACE||Xe,it=e.MATHML_TEXT_INTEGRATION_POINTS||it,ot=e.HTML_INTEGRATION_POINTS||ot,q=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(q.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(q.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(q.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Y&&(K=!1),re&&(ie=!0),Ue&&(B=Ce({},De),z=[],!0===Ue.html&&(Ce(B,Ee),Ce(z,Me)),!0===Ue.svg&&(Ce(B,_e),Ce(z,Ne),Ce(z,Le)),!0===Ue.svgFilters&&(Ce(B,Pe),Ce(z,Ne),Ce(z,Le)),!0===Ue.mathMl&&(Ce(B,$e),Ce(z,Re),Ce(z,Le))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?W.tagCheck=e.ADD_TAGS:(B===U&&(B=Te(B)),Ce(B,e.ADD_TAGS,lt))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?W.attributeCheck=e.ADD_ATTR:(z===F&&(z=Te(z)),Ce(z,e.ADD_ATTR,lt))),e.ADD_URI_SAFE_ATTR&&Ce(We,e.ADD_URI_SAFE_ATTR,lt),e.FORBID_CONTENTS&&(ze===Fe&&(ze=Te(ze)),Ce(ze,e.FORBID_CONTENTS,lt)),e.ADD_FORBID_CONTENTS&&(ze===Fe&&(ze=Te(ze)),Ce(ze,e.ADD_FORBID_CONTENTS,lt)),ke&&(B["#text"]=!0),Z&&Ce(B,["html","head","body"]),B.table&&(Ce(B,["tbody"]),delete j.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Se('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Se('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=e.TRUSTED_TYPES_POLICY,v=x.createHTML("")}else void 0===x&&(x=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+o+" could not be created."),null}}(g,r)),null!==x&&"string"==typeof v&&(v=x.createHTML(""));ne&&ne(e),ct=e}},ht=Ce({},[..._e,...Pe,...Ae]),gt=Ce({},[...$e,...Oe]),mt=function(e){de(n.removed,{element:e});try{S(e).removeChild(e)}catch(t){y(e)}},ft=function(e,t){try{de(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){de(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ie||re)try{mt(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},yt=function(e){let t=null,n=null;if(te)e="<remove></remove>"+e;else{const t=ge(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===at&&Ze===Xe&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=x?x.createHTML(e):e;if(Ze===Xe)try{t=(new h).parseFromString(o,at)}catch(e){}if(!t||!t.documentElement){t=C.createDocument(Ze,"template",null);try{t.documentElement.innerHTML=et?v:o}catch(e){}}const r=t.body||t.documentElement;return e&&n&&r.insertBefore(i.createTextNode(n),r.childNodes[0]||null),Ze===Xe?I.call(t,Z?"html":"body")[0]:Z?t.documentElement:r},bt=function(e){return k.call(e.ownerDocument||e,e,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},wt=function(e){return e instanceof p&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof u)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},St=function(e){return"function"==typeof l&&e instanceof l};function xt(e,t,i){se(e,e=>{e.call(n,t,i,ct)})}const vt=function(e){let t=null;if(xt(_.beforeSanitizeElements,e,null),wt(e))return mt(e),!0;const i=lt(e.nodeName);if(xt(_.uponSanitizeElement,e,{tagName:i,allowedTags:B}),X&&e.hasChildNodes()&&!St(e.firstElementChild)&&we(/<[/\w!]/g,e.innerHTML)&&we(/<[/\w!]/g,e.textContent))return mt(e),!0;if(7===e.nodeType)return mt(e),!0;if(X&&8===e.nodeType&&we(/<[/\w]/g,e.data))return mt(e),!0;if(!(W.tagCheck instanceof Function&&W.tagCheck(i))&&(!B[i]||j[i])){if(!j[i]&&kt(i)){if(q.tagNameCheck instanceof RegExp&&we(q.tagNameCheck,i))return!1;if(q.tagNameCheck instanceof Function&&q.tagNameCheck(i))return!1}if(ke&&!ze[i]){const t=S(e)||e.parentNode,n=w(e)||e.childNodes;if(n&&t)for(let i=n.length-1;i>=0;--i){const o=f(n[i],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,b(e))}}return mt(e),!0}return e instanceof c&&!function(e){let t=S(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});const n=pe(e.tagName),i=pe(t.tagName);return!!tt[e.namespaceURI]&&(e.namespaceURI===Qe?t.namespaceURI===Xe?"svg"===n:t.namespaceURI===Ye?"svg"===n&&("annotation-xml"===i||it[i]):Boolean(ht[n]):e.namespaceURI===Ye?t.namespaceURI===Xe?"math"===n:t.namespaceURI===Qe?"math"===n&&ot[i]:Boolean(gt[n]):e.namespaceURI===Xe?!(t.namespaceURI===Qe&&!ot[i])&&!(t.namespaceURI===Ye&&!it[i])&&!gt[n]&&(rt[n]||!ht[n]):!("application/xhtml+xml"!==at||!tt[e.namespaceURI]))}(e)?(mt(e),!0):"noscript"!==i&&"noembed"!==i&&"noframes"!==i||!we(/<\/no(script|embed|frames)/i,e.innerHTML)?(Y&&3===e.nodeType&&(t=e.textContent,se([P,A,$],e=>{t=me(t,e," ")}),e.textContent!==t&&(de(n.removed,{element:e.cloneNode()}),e.textContent=t)),xt(_.afterSanitizeElements,e,null),!1):(mt(e),!0)},Ct=function(e,t,n){if(xe&&("id"===t||"name"===t)&&(n in i||n in dt))return!1;if(K&&!H[t]&&we(O,t));else if(G&&we(D,t));else if(W.attributeCheck instanceof Function&&W.attributeCheck(t,e));else if(!z[t]||H[t]){if(!(kt(e)&&(q.tagNameCheck instanceof RegExp&&we(q.tagNameCheck,e)||q.tagNameCheck instanceof Function&&q.tagNameCheck(e))&&(q.attributeNameCheck instanceof RegExp&&we(q.attributeNameCheck,t)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(t,e))||"is"===t&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&we(q.tagNameCheck,n)||q.tagNameCheck instanceof Function&&q.tagNameCheck(n))))return!1}else if(We[t]);else if(we(L,me(n,N,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==fe(n,"data:")||!qe[e])if(J&&!we(M,me(n,N,"")));else if(n)return!1;return!0},kt=function(e){return"annotation-xml"!==e&&ge(e,R)},Tt=function(e){xt(_.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||wt(e))return;const i={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:z,forceKeepAttr:void 0};let o=t.length;for(;o--;){const r=t[o],{name:a,namespaceURI:s,value:l}=r,c=lt(a),d=l;let u="value"===a?d:ye(d);if(i.attrName=c,i.attrValue=u,i.keepAttr=!0,i.forceKeepAttr=void 0,xt(_.uponSanitizeAttribute,e,i),u=i.attrValue,!ve||"id"!==c&&"name"!==c||(ft(a,e),u="user-content-"+u),X&&we(/((--!?|])>)|<\/(style|title|textarea)/i,u)){ft(a,e);continue}if("attributename"===c&&ge(u,"href")){ft(a,e);continue}if(i.forceKeepAttr)continue;if(!i.keepAttr){ft(a,e);continue}if(!V&&we(/\/>/i,u)){ft(a,e);continue}Y&&se([P,A,$],e=>{u=me(u,e," ")});const p=lt(e.nodeName);if(Ct(p,c,u)){if(x&&"object"==typeof g&&"function"==typeof g.getAttributeType)if(s);else switch(g.getAttributeType(p,c)){case"TrustedHTML":u=x.createHTML(u);break;case"TrustedScriptURL":u=x.createScriptURL(u)}if(u!==d)try{s?e.setAttributeNS(s,a,u):e.setAttribute(a,u),wt(e)?mt(e):ce(n.removed)}catch(t){ft(a,e)}}else ft(a,e)}xt(_.afterSanitizeAttributes,e,null)},It=function e(t){let n=null;const i=bt(t);for(xt(_.beforeSanitizeShadowDOM,t,null);n=i.nextNode();)xt(_.uponSanitizeShadowNode,n,null),vt(n),Tt(n),n.content instanceof a&&e(n.content);xt(_.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=null,r=null,s=null,c=null;if(et=!e,et&&(e="\x3c!--\x3e"),"string"!=typeof e&&!St(e)){if("function"!=typeof e.toString)throw Se("toString is not a function");if("string"!=typeof(e=e.toString()))throw Se("dirty is not a string, aborting")}if(!n.isSupported)return e;if(ee||pt(t),n.removed=[],"string"==typeof e&&(Be=!1),Be){if(e.nodeName){const t=lt(e.nodeName);if(!B[t]||j[t])throw Se("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof l)i=yt("\x3c!----\x3e"),r=i.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?i=r:i.appendChild(r);else{if(!ie&&!Y&&!Z&&-1===e.indexOf("<"))return x&&ae?x.createHTML(e):e;if(i=yt(e),!i)return ie?null:ae?v:""}i&&te&&mt(i.firstChild);const d=bt(Be?e:i);for(;s=d.nextNode();)vt(s),Tt(s),s.content instanceof a&&It(s.content);if(Be)return e;if(ie){if(re)for(c=T.call(i.ownerDocument);i.firstChild;)c.appendChild(i.firstChild);else c=i;return(z.shadowroot||z.shadowrootmode)&&(c=E.call(o,c,!0)),c}let u=Z?i.outerHTML:i.innerHTML;return Z&&B["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&we(Ge,i.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+i.ownerDocument.doctype.name+">\n"+u),Y&&se([P,A,$],e=>{u=me(u,e," ")}),x&&ae?x.createHTML(u):u},n.setConfig=function(){pt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),ee=!0},n.clearConfig=function(){ct=null,ee=!1},n.isValidAttribute=function(e,t,n){ct||pt({});const i=lt(e),o=lt(t);return Ct(i,o,n)},n.addHook=function(e,t){"function"==typeof t&&de(_[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=le(_[e],t);return-1===n?void 0:ue(_[e],n,1)[0]}return ce(_[e])},n.removeHooks=function(e){_[e]=[]},n.removeAllHooks=function(){_={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Qe={ALLOWED_TAGS:["div","span","p","section","article","header","footer","main","nav","aside","h1","h2","h3","h4","h5","h6","strong","em","b","i","u","s","small","mark","sub","sup","br","hr","ul","ol","li","dl","dt","dd","a","img","picture","source","figure","figcaption","video","audio","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","form","input","button","select","option","optgroup","textarea","label","fieldset","legend","blockquote","pre","code","kbd","samp","var","time","address","abbr","cite","q","svg","path","circle","rect","line","polyline","polygon","ellipse","g","text","tspan","defs","use","style"],ALLOWED_ATTR:["id","class","style","title","lang","dir","hidden","tabindex","role","aria-label","aria-labelledby","aria-describedby","aria-hidden","aria-live","aria-atomic","aria-busy","aria-controls","aria-current","aria-disabled","aria-expanded","aria-haspopup","aria-invalid","aria-pressed","aria-selected","data-*","href","target","rel","download","src","srcset","sizes","alt","width","height","loading","decoding","poster","controls","autoplay","loop","muted","playsinline","preload","type","name","value","placeholder","disabled","readonly","required","checked","selected","multiple","min","max","step","pattern","maxlength","minlength","for","form","autocomplete","autofocus","colspan","rowspan","scope","headers","viewBox","xmlns","fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","d","cx","cy","r","rx","ry","x","y","x1","y1","x2","y2","points","transform","opacity","fill-opacity","stroke-opacity"],ALLOWED_URI_REGEXP:/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|xxx):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,ADD_URI_SAFE_ATTR:["href","src","srcset"],FORBID_TAGS:["script","iframe","object","embed","base","meta","link"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]};function Xe(e,t){if(!e)return"";const n=t?{...Qe,...t}:Qe;return Ye.sanitize(e,n)}function Ze(e){return e?Ye.sanitize(e,{...Qe,ADD_TAGS:["img","picture","source"],ADD_ATTR:["loading","decoding","srcset","sizes","data-product-id","data-action"]}):""}function et(e){if(!e)return"";let t=e.replace(/expression\s*\([^)]*\)/gi,"");return t=t.replace(/behavior\s*:\s*[^;]*/gi,""),t=t.replace(/-moz-binding\s*:\s*[^;]*/gi,""),t=t.replace(/javascript\s*:/gi,""),t=t.replace(/data\s*:/gi,""),t=t.replace(/@import\s+[^;]*/gi,""),t}class tt{constructor(){this.pendingScripts=new Map}execute(e){if(e.code?.trim())switch(e.timing){case"immediate":this.executeNow(e);break;case"domReady":"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>this.executeNow(e)):this.executeNow(e);break;case"customEvent":e.eventName&&(this.pendingScripts.set(e.eventName,e),document.addEventListener(e.eventName,()=>{this.executeNow(e)},{once:!0}))}}executeNow(e){try{const t=document.createElement("script");t.setAttribute("data-selwise-custom-js","true");const n=e.context?`const context = ${JSON.stringify(e.context)};`:"";t.textContent=`(function() { ${n} ${e.code} }).call(window);`,e.container?e.container.appendChild(t):document.body.appendChild(t)}catch(e){K("Selwise","Script execution error:",e)}}triggerCustomEvent(e){const t=new CustomEvent(e);document.dispatchEvent(t)}destroy(){this.pendingScripts.clear(),document.querySelectorAll("script[data-selwise-custom-js]").forEach(e=>e.remove())}}function nt(e,t="comma"){if(e>=1e6)return(e/1e6).toFixed(1).replace(/\.0$/,"")+"M";if(e>=1e3)return(e/1e3).toFixed(1).replace(/\.0$/,"")+"K";switch(t){case"dot":return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,".");case"space":return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ");case"none":return e.toString();default:return e.toLocaleString()}}function it(e,t,n,i,o="comma"){const r=performance.now(),a=n-t;requestAnimationFrame(function n(s){const l=s-r,c=Math.min(l/i,1),d=1-Math.pow(1-c,4),u=Math.round(t+a*d);e.textContent=nt(u,o),c<1&&requestAnimationFrame(n)})}async function ot(e,t={},n=5e3){const i=new AbortController,o=setTimeout(()=>i.abort(),n);try{const n=await fetch(e,{...t,signal:i.signal});return clearTimeout(o),n}catch(e){if(clearTimeout(o),e instanceof Error&&"AbortError"===e.name)throw new Error(`Request timeout after ${n}ms`);throw e}}function rt(e,t){const n=t.contentJson||{},i=t.stylesJson||{},o=function(e){return e.productId||document.querySelector("[data-product-id]")?.getAttribute("data-product-id")||document.querySelector("[data-product-sku]")?.getAttribute("data-product-sku")||document.querySelector("[data-selwise-product]")?.getAttribute("data-selwise-product")||null}(n);if(!o)return null;const r=window.Selwise?.apiUrl||"",a=window.Selwise?.siteKey||"",{container:s,counterElements:l,timePeriod:c}=function(e,t,n,i){const o=document.createElement("div");o.className="selwise-widget selwise-product-view-count",o.style.backgroundColor=i.backgroundColor||"#f0fdf4",o.style.color=i.textColor||"#166534",o.style.borderRadius=i.borderRadius||"8px",o.style.padding=i.padding||"12px",o.style.display="block"===i.display?"block":"flex"===i.display?"flex":"inline-flex",o.style.alignItems="center",o.style.gap="8px",o.style.fontFamily="system-ui, -apple-system, sans-serif",o.style.fontSize=i.fontSize||"14px",A(o,e,t);const r={eye:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>',users:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>',"trending-up":'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>',flame:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>'};if(!1!==n.showIcon){const e=document.createElement("span");e.className="selwise-icon",e.style.color=i.iconColor||i.textColor||"#166534",e.style.flexShrink="0",e.style.display="inline-flex",e.style.alignItems="center",e.innerHTML=r[n.iconType||"eye"]||r.eye,o.appendChild(e)}const a=document.createElement("span");a.className="selwise-text";const s=n.timePeriod||"24h";!function(e,t){const n=t.split("{count}");for(let t=0;t<n.length;t+=1){const i=n[t];if(i&&e.appendChild(document.createTextNode(i)),t<n.length-1){const t=document.createElement("span");t.className="selwise-counter-placeholder",e.appendChild(t)}}}(a,(n.customText||n.template||"{count} kişi bu ürünü görüntüledi").replace(/\{timePeriod\}/g,s)),o.appendChild(a);const l=function(e,t){const n=Array.from(e.querySelectorAll(".selwise-counter-placeholder")),i=[];if(n.forEach(e=>{const n=document.createElement("span");n.className="selwise-counter",n.style.fontWeight="700",n.style.color=t,n.textContent="...",e.replaceWith(n),i.push(n)}),0===i.length){const n=document.createElement("span");n.className="selwise-counter",n.style.fontWeight="700",n.style.color=t,n.textContent="...",e.appendChild(document.createTextNode(" ")),e.appendChild(n),i.push(n)}return i}(a,i.counterColor||i.textColor||"#166534");return{container:o,counterElements:l,timePeriod:s}}(e,t,n,i);return function(e,t){const{selector:n,insertPosition:i="after"}=t||{};if(n){const t=document.querySelector(n);if(!t)return!1;switch(i){case"before":t.parentNode?.insertBefore(e,t);break;case"after":t.parentNode?.insertBefore(e,t.nextSibling);break;case"inside-start":t.insertBefore(e,t.firstChild);break;case"inside-end":t.appendChild(e);break;case"replace":t.replaceWith(e)}return!0}const o=document.querySelector("[data-product-id]")||document.querySelector(".product")||document.querySelector('[itemtype*="Product"]');return!!o&&(o.appendChild(e),!0)}(s,e.placementConfigJson||{})?(async function(e,t,n,i,o,r){try{const a=`${e}/public/sites/${t}/product-metrics/view-count?product=${encodeURIComponent(n)}&period=${i}`,s=await ot(a,{},5e3);if(!s.ok)throw new Error("Failed to fetch product view count");const l=(await s.json()).count||0;if(!1!==r.animateCounter)o.forEach(e=>{it(e,0,l,r.animationDuration||1e3,r.separator||"comma")});else{const e=nt(l,r.separator||"comma");o.forEach(t=>{t.textContent=e})}}catch(e){console.error("[Selwise] Error fetching product view count:",e),o.forEach(e=>{e.textContent="—"})}}(r,a,o,c,l,i),s):null}function at(e,t){const n=t.contentJson||{},i=t.stylesJson||{},o=function(e){return e.productId||document.querySelector("[data-product-id]")?.getAttribute("data-product-id")||document.querySelector("[data-product-sku]")?.getAttribute("data-product-sku")||document.querySelector("[data-selwise-product]")?.getAttribute("data-selwise-product")||null}(n);if(!o)return null;const r=window.Selwise?.apiUrl||"",a=window.Selwise?.siteKey||"",{container:s,counterElements:l,metricType:c}=function(e,t,n,i){const o=document.createElement("div");if(o.className="selwise-widget selwise-cart-count",o.style.backgroundColor=i.backgroundColor||"#fef3c7",o.style.color=i.textColor||"#92400e",o.style.borderRadius=i.borderRadius||"8px",o.style.padding=i.padding||"12px",o.style.display="block"===i.display?"block":"flex"===i.display?"flex":"inline-flex",o.style.alignItems="center",o.style.gap="8px",o.style.fontFamily="system-ui, -apple-system, sans-serif",o.style.fontSize=i.fontSize||"14px",o.style.position="relative",A(o,e,t),!1!==i.showBadge){const e=document.createElement("span");e.className="selwise-badge",e.style.backgroundColor=i.badgeColor||"#dc2626",e.style.color=i.badgeTextColor||"#ffffff",e.style.padding="2px 6px",e.style.borderRadius="4px",e.style.fontSize="10px",e.style.fontWeight="700",e.style.position="absolute",e.style.top="-6px",e.style.right="-6px",e.style.textTransform="uppercase",e.textContent=i.badgeText||"HOT",o.appendChild(e)}const r={"shopping-cart":'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>',"shopping-bag":'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>',users:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>',fire:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>'};if(!1!==n.showIcon){const e=document.createElement("span");e.className="selwise-icon",e.style.color=i.iconColor||i.textColor||"#92400e",e.style.flexShrink="0",e.style.display="inline-flex",e.style.alignItems="center",e.innerHTML=r[n.iconType||"shopping-cart"]||r["shopping-cart"],o.appendChild(e)}const a=document.createElement("span");a.className="selwise-text",function(e,t){const n=t.split("{count}");for(let t=0;t<n.length;t+=1){const i=n[t];if(i&&e.appendChild(document.createTextNode(i)),t<n.length-1){const t=document.createElement("span");t.className="selwise-counter-placeholder",e.appendChild(t)}}}(a,n.customText||n.template||"{count} kişi sepete ekledi"),o.appendChild(a);const s=function(e,t){const n=Array.from(e.querySelectorAll(".selwise-counter-placeholder")),i=[];if(n.forEach(e=>{const n=document.createElement("span");n.className="selwise-counter",n.style.fontWeight="700",n.style.color=t,n.textContent="...",e.replaceWith(n),i.push(n)}),0===i.length){const n=document.createElement("span");n.className="selwise-counter",n.style.fontWeight="700",n.style.color=t,n.textContent="...",e.appendChild(document.createTextNode(" ")),e.appendChild(n),i.push(n)}return i}(a,i.counterColor||i.textColor||"#ea580c");return{container:o,counterElements:s,metricType:n.metricType||"active_carts"}}(e,t,n,i);return function(e,t){const{selector:n,insertPosition:i="after"}=t||{};if(n){const t=document.querySelector(n);if(!t)return!1;switch(i){case"before":t.parentNode?.insertBefore(e,t);break;case"after":t.parentNode?.insertBefore(e,t.nextSibling);break;case"inside-start":t.insertBefore(e,t.firstChild);break;case"inside-end":t.appendChild(e);break;case"replace":t.replaceWith(e)}return!0}const o=document.querySelector("[data-product-id]")||document.querySelector(".product")||document.querySelector('[itemtype*="Product"]');return!!o&&(o.appendChild(e),!0)}(s,e.placementConfigJson||{})?(async function(e,t,n,i,o,r){try{const a=`${e}/public/sites/${t}/product-metrics/cart-count?product=${encodeURIComponent(n)}&metric=${i}`,s=await ot(a,{},5e3);if(!s.ok)throw new Error("Failed to fetch cart count");const l=(await s.json()).count||0;if(!1!==r.animateCounter)o.forEach(e=>{it(e,0,l,r.animationDuration||1e3,r.separator||"comma")});else{const e=nt(l,r.separator||"comma");o.forEach(t=>{t.textContent=e})}}catch(e){console.error("[Selwise] Error fetching cart count:",e),o.forEach(e=>{e.textContent="—"})}}(r,a,o,c,l,i),s):null}const st=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function lt(){const e=document.documentElement?.lang?.slice(0,2).toLowerCase(),t=(navigator?.language||"").slice(0,2).toLowerCase();return"tr"===(e||t)?"tr":"en"}function ct(e,t,n){if("idle"===t)return e.textContent="",e.style.display="none",void e.removeAttribute("data-state");e.textContent=n,e.style.display="block",e.setAttribute("data-state",t),e.style.color="error"!==t?"pending"!==t?"#166534":"#b45309":"#dc2626"}class dt{render(e,t){!function(){if(i)return;const e=document.createElement("style");e.id="selwise-styles",e.textContent="\n .selwise-widget {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n box-sizing: border-box;\n line-height: 1.5;\n }\n .selwise-widget * {\n box-sizing: inherit;\n }\n \n /* Announcement Bar */\n .selwise-bar {\n position: fixed;\n left: 0;\n right: 0;\n z-index: 99999;\n padding: 12px 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 16px;\n animation: selwise-slide-down 0.3s ease-out;\n }\n .selwise-bar-top { top: 0; }\n .selwise-bar-bottom { bottom: 0; animation-name: selwise-slide-up; }\n .selwise-bar-text { font-size: 14px; font-weight: 500; }\n .selwise-bar-btn {\n padding: 8px 16px;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 600;\n text-decoration: none;\n cursor: pointer;\n border: none;\n transition: opacity 0.2s, transform 0.2s;\n }\n .selwise-bar-btn:hover { opacity: 0.9; transform: scale(1.02); }\n .selwise-close {\n position: absolute;\n right: 16px;\n background: none;\n border: none;\n cursor: pointer;\n opacity: 0.7;\n font-size: 20px;\n padding: 4px;\n line-height: 1;\n }\n .selwise-close:hover { opacity: 1; }\n \n /* Floating Button */\n .selwise-floating {\n position: fixed;\n z-index: 99998;\n padding: 14px 20px;\n border-radius: 30px;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n text-decoration: none;\n box-shadow: 0 4px 14px rgba(0,0,0,0.2);\n animation: selwise-pop-in 0.3s ease-out;\n transition: transform 0.2s, box-shadow 0.2s;\n }\n .selwise-floating:hover { transform: scale(1.05); box-shadow: 0 6px 20px rgba(0,0,0,0.25); }\n .selwise-floating-bottom-right { bottom: 20px; right: 20px; }\n .selwise-floating-bottom-left { bottom: 20px; left: 20px; }\n .selwise-floating-top-right { top: 20px; right: 20px; }\n .selwise-floating-top-left { top: 20px; left: 20px; }\n .selwise-floating-tooltip {\n position: absolute;\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.18s ease-out;\n white-space: nowrap;\n transform: translateX(-50%);\n left: 50%;\n bottom: calc(100% + 8px);\n }\n .selwise-floating:hover .selwise-floating-tooltip {\n opacity: 1;\n }\n \n /* Popup/Modal */\n .selwise-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0,0,0,0.6);\n z-index: 99999;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: selwise-fade-in 0.3s ease-out;\n }\n .selwise-popup {\n background: white;\n border-radius: 16px;\n max-width: 500px;\n width: 90%;\n padding: 32px;\n box-shadow: 0 20px 60px rgba(0,0,0,0.3);\n position: relative;\n animation: selwise-scale-in 0.3s ease-out;\n }\n .selwise-popup-title { font-size: 24px; font-weight: 700; margin-bottom: 12px; }\n .selwise-popup-text { font-size: 16px; margin-bottom: 24px; opacity: 0.8; }\n .selwise-popup-img { width: 100%; border-radius: 8px; margin-bottom: 20px; }\n \n /* Slide In */\n .selwise-slide {\n position: fixed;\n z-index: 99998;\n background: white;\n box-shadow: -4px 0 20px rgba(0,0,0,0.15);\n padding: 24px;\n max-width: 360px;\n width: 100%;\n }\n .selwise-slide-right { right: 0; top: 50%; transform: translateY(-50%); animation: selwise-slide-left 0.4s ease-out; }\n .selwise-slide-left { left: 0; top: 50%; transform: translateY(-50%); animation: selwise-slide-right 0.4s ease-out; }\n .selwise-slide-bottom { bottom: 0; left: 50%; transform: translateX(-50%); max-width: 500px; animation: selwise-slide-up 0.4s ease-out; }\n \n /* Embedded Card */\n .selwise-card {\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 2px 12px rgba(0,0,0,0.08);\n margin: 16px 0;\n }\n .selwise-card-img { width: 100%; height: 180px; object-fit: cover; }\n .selwise-card-body { padding: 20px; }\n .selwise-card-title { font-size: 18px; font-weight: 600; margin-bottom: 8px; }\n .selwise-card-text { font-size: 14px; margin-bottom: 16px; opacity: 0.7; }\n \n /* Sticky Footer */\n .selwise-footer {\n position: fixed;\n bottom: 0;\n left: 0;\n right: 0;\n z-index: 99997;\n padding: 16px 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 20px;\n animation: selwise-slide-up 0.3s ease-out;\n box-shadow: 0 -2px 10px rgba(0,0,0,0.1);\n }\n \n /* Countdown Timer */\n .selwise-countdown {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 16px;\n border-radius: 8px;\n font-weight: 600;\n }\n .selwise-countdown-unit {\n text-align: center;\n min-width: 40px;\n }\n .selwise-countdown-value {\n font-size: 24px;\n font-weight: 700;\n line-height: 1;\n }\n .selwise-countdown-label {\n font-size: 10px;\n text-transform: uppercase;\n opacity: 0.7;\n }\n .selwise-countdown-sep {\n font-size: 20px;\n font-weight: 700;\n opacity: 0.5;\n }\n \n /* Inline Banner */\n .selwise-inline {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px 24px;\n border-radius: 8px;\n margin: 16px 0;\n }\n \n /* Animations */\n @keyframes selwise-slide-down {\n from { transform: translateY(-100%); }\n to { transform: translateY(0); }\n }\n @keyframes selwise-slide-up {\n from { transform: translateY(100%); }\n to { transform: translateY(0); }\n }\n @keyframes selwise-slide-left {\n from { transform: translateX(100%) translateY(-50%); }\n to { transform: translateX(0) translateY(-50%); }\n }\n @keyframes selwise-slide-right {\n from { transform: translateX(-100%) translateY(-50%); }\n to { transform: translateX(0) translateY(-50%); }\n }\n @keyframes selwise-pop-in {\n from { transform: scale(0.8); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n @keyframes selwise-fade-in {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n @keyframes selwise-scale-in {\n from { transform: scale(0.9); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n @keyframes selwise-pulse {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.05); }\n }\n ",document.head.appendChild(e),i=!0}();const n={...t,stylesJson:(r=e.type,a=t.stylesJson,(0,o.isWidgetType)(r)?(0,o.sanitizeStyles)(r,a||{}):a||{})};var r,a;switch(e.type){case"announcement_bar":return function(e,t){if(N(e.id))return null;const n=t.contentJson||{},i=t.stylesJson||{},o=n.text||n.headline||"",r=n.subtext||"",a=e.placementConfigJson.position||"top",s=i.backgroundColor||"#1a1a1a",l=i.textColor||"#ffffff",c=i.buttonColor||l,d=i.buttonTextColor||s,u=i.padding||"12px",p=i.fontSize||"14px",h=i.fontWeight||"medium",g=i.borderBottom,m=!1!==i.showCloseButton,f=i.closeButtonColor||l,y=i.imageSize||"24px",b=i.imageBorderRadius||"4px",w=i.imageSpacing||"8px",S=document.createElement("div");S.className=`selwise-widget selwise-bar selwise-bar-${a}`,S.style.backgroundColor=s,S.style.color=l,S.style.padding=u,S.style.fontSize=p,S.style.fontWeight=P(h),S.style.gap="12px",g&&"none"!==g&&(S.style.borderBottom=g),A(S,e,t);const x=B({imageUrl:n.imageUrl,mode:"thumbnail",size:y,borderRadius:b,objectFit:"cover",alt:""});x&&(x.style.marginRight=w,S.appendChild(x));const v=document.createElement("span");if(v.className="selwise-bar-text",v.textContent=`${o}${r?` - ${r}`:""}`,S.appendChild(v),n.buttonText){const t=document.createElement("a");t.href=L(n.buttonUrl),t.className="selwise-bar-btn",t.style.background=c,t.style.color=d,t.textContent=n.buttonText,t.addEventListener("click",()=>R(e.id)),S.appendChild(t)}if(m){const e=D(f,()=>{try{S.remove()}catch(e){console.error("[AnnouncementBar] Failed to remove bar:",e)}});e&&S.appendChild(e)}return document.body.appendChild(S),S}(e,n);case"inline_banner":return function(e,t){const n=t.contentJson||{},i=t.stylesJson||{},r=n.title||n.headline||"",a=n.text||"",s=n.subtext||"",l=i.backgroundColor||"#f3f4f6",c=i.textColor||"#1f2937",d=i.buttonColor||c,u=i.buttonTextColor||l,p=i.padding||"16px",h=i.borderRadius||"8px",g=i.shadow||"md",m=i.border,f=i.imageMode||"thumbnail",y=i.imageSize||"60px",b=i.imageAspectRatio||"auto",w=i.imageObjectFit||"cover",S=i.imageBorderRadius||"8px",x=i.imageSpacing||"16px",{effectiveDirection:v,alignItems:C,textAlign:k,ctaAlignSelf:T}=(0,o.resolveInlineBannerLayout)({imageMode:f,contentDirection:i.contentDirection,contentAlignment:i.contentAlignment}),I=document.createElement("div");I.className="selwise-widget selwise-inline",I.style.backgroundColor=l,I.style.color=c,I.style.padding=p,I.style.borderRadius=h,I.style.boxShadow=_(g),I.style.display="flex",I.style.flexDirection=v,I.style.gap=x,I.style.alignItems=C,I.style.textAlign=k,m&&"none"!==m&&(I.style.border=m),A(I,e,t);const E=B({imageUrl:n.imageUrl,mode:f,size:y,aspectRatio:b,objectFit:w,borderRadius:"fullWidth"===f?"0px":S,alt:""});E&&I.appendChild(E);const P=document.createElement("div");if(P.className="selwise-banner-content",P.style.flex="1",P.style.minWidth="0",P.style.display="flex",P.style.flexDirection="column",P.style.gap="4px",P.style.alignItems=C,P.style.textAlign=k,r){const e=document.createElement("h4");e.style.fontSize="16px",e.style.fontWeight="600",e.style.margin="0",e.textContent=r,P.appendChild(e)}if(a||s){const e=document.createElement("p");e.style.fontSize="14px",e.style.fontWeight="500",e.style.margin="0",e.style.opacity="0.9",e.textContent=[a,s].filter(Boolean).join(a?" - ":""),P.appendChild(e)}let $=null;return n.buttonText&&($=document.createElement("a"),$.href=L(n.buttonUrl),$.textContent=n.buttonText,$.style.padding="10px 20px",$.style.background=d,$.style.color=u,$.style.borderRadius="6px",$.style.textDecoration="none",$.style.fontSize="13px",$.style.fontWeight="600",$.style.whiteSpace="nowrap",$.style.display="inline-block",$.style.alignSelf=T),"row"===v&&$?(I.appendChild(P),I.appendChild($)):($&&($.style.marginTop="8px",P.appendChild($)),I.appendChild(P)),U(I,e,`inline-banner:${e.id}`)?I:null}(e,n);case"floating_button":return function(e,t){const n=t.contentJson||{},i=t.stylesJson||{},{text:o="Click me",buttonUrl:r="#"}=n,{backgroundColor:a="#3b82f6",textColor:s="#ffffff",size:l="56px",borderRadius:c="50%",shadow:d="lg",pulseAnimation:u=!1,tooltipBgColor:p="#1a1a1a",tooltipTextColor:h="#ffffff"}=i,g=e.placementConfigJson.position||"bottom-right",m="top"===g?"top-right":"bottom"===g?"bottom-right":"left"===g?"bottom-left":"right"===g?"bottom-right":g,f=document.createElement("a");f.href=L(r),f.className=`selwise-widget selwise-floating selwise-floating-${m}`,f.style.backgroundColor=a,f.style.color=s,f.style.borderRadius=String(c),f.style.boxShadow=_(String(d)),f.textContent=o;const y={small:"12px 16px",medium:"14px 20px",large:"16px 24px","48px":"48px","56px":"56px","64px":"64px","72px":"72px"},b=y[String(l)]||String(l);/^\d+px$/.test(b)?(f.style.width=b,f.style.height=b,f.style.padding="0"):f.style.padding=b||y.medium;const w=(n.tooltip||"").trim();if(w){const e=document.createElement("span");e.className="selwise-floating-tooltip",e.style.backgroundColor=String(p),e.style.color=String(h),e.style.padding="4px 8px",e.style.borderRadius="6px",e.style.fontSize="11px",e.style.boxShadow="0 6px 16px rgba(0,0,0,0.15)",e.textContent=w,f.appendChild(e)}return u&&(f.style.animation="selwise-pulse 2s infinite"),A(f,e,t),document.body.appendChild(f),f}(e,n);case"exit_intent_popup":return function(e,t){if(N(e.id))return null;if(z)return null;z=!0;const n=t.contentJson||{},i=t.stylesJson||{},o=n.title||n.headline||"",r=n.text||n.subtext||"",a=i.backgroundColor||"#ffffff",s=i.textColor||"#1f2937",l=i.buttonColor||s,c=i.buttonTextColor||a,d=i.overlayColor||"#000000",u=i.overlayOpacity??50,p=i.overlayBlur||"none",h=i.maxWidth||"400px",g=i.padding||"24px",m=i.borderRadius||"12px",f=i.shadow||"2xl",y=i.animation||"scale",b=i.imageMode||"cover",w=i.imageSize||"80px",S=i.imagePosition||"top",x=i.imageAspectRatio||"auto",v=i.imageObjectFit||"cover",C=i.imageBorderRadius||"8px",k="none"!==p?`backdrop-filter:blur(${p});`:"";let T=d;var I,E;d.startsWith("#")&&(I=d,E=Number(u),T=`rgba(${parseInt(I.slice(1,3),16)}, ${parseInt(I.slice(3,5),16)}, ${parseInt(I.slice(5,7),16)}, ${E/100})`);let P="animation: selwise-scale-in 0.3s ease-out;";"none"===y?P="animation: none;":"fade"===y?P="animation: selwise-fade-in 0.3s ease-out;":"slide"===y&&(P="animation: selwise-slide-up 0.3s ease-out;");const $=document.createElement("div");$.className="selwise-widget selwise-overlay",$.style.display="none",$.style.backgroundColor=T,$.style.cssText+=k,A($,e,t);const O=document.createElement("div");O.className="selwise-popup",O.style.background=a,O.style.color=s,O.style.maxWidth=h,O.style.padding=g,O.style.borderRadius=m,O.style.boxShadow=_(f),O.style.cssText+=P;const D=document.createElement("button");D.className="selwise-close",D.style.color=s,D.style.top="12px",D.style.right="12px",D.style.position="absolute",D.textContent="×",D.addEventListener("click",()=>$.remove()),O.appendChild(D);const M=B({imageUrl:n.imageUrl,mode:b,size:w,aspectRatio:x,objectFit:v,borderRadius:"fullWidth"===b?"0px":C,alt:""});M&&(M.className="selwise-popup-img",M.style.marginBottom="20px");const U=document.createElement("div");if(U.style.flex="1",o){const e=document.createElement("div");e.className="selwise-popup-title",e.textContent=o,U.appendChild(e)}if(r){const e=document.createElement("div");e.className="selwise-popup-text",e.textContent=r,U.appendChild(e)}if(n.buttonText){const t=document.createElement("a");t.href=L(n.buttonUrl),t.className="selwise-bar-btn",t.style.display="block",t.style.textAlign="center",t.style.background=l,t.style.color=c,t.textContent=n.buttonText,t.addEventListener("click",()=>R(e.id)),U.appendChild(t)}if(!M||"left"!==S&&"right"!==S)M&&"top"===S&&O.appendChild(M),O.appendChild(U),M&&"bottom"===S&&O.appendChild(M);else{const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="right"===S?"row-reverse":"row",e.style.gap="16px",e.style.alignItems="center",M.style.marginBottom="0",e.appendChild(M),e.appendChild(U),O.appendChild(e)}return $.appendChild(O),$.addEventListener("click",e=>{e.target===$&&$.remove()}),document.body.appendChild($),document.addEventListener("mouseleave",e=>{e.clientY<=0&&"none"===$.style.display&&($.style.display="flex")},{once:!0}),$}(e,n);case"slide_in":return function(e,t){if(N(e.id))return null;const n=t.contentJson||{},i=t.stylesJson||{},o=e.placementConfigJson.position||"right",r=n.title||n.headline||"",a=n.text||n.subtext||"",s=i.backgroundColor||"#ffffff",l=i.textColor||"#1f2937",c=i.buttonColor||l,d=i.buttonTextColor||s,u=i.width||"320px",p=i.padding||"16px",h=i.borderRadius||"12px",g=i.shadow||"xl",m=i.border,f=i.offsetX||"16px",y=i.offsetY||"16px",b=i.imageMode||"cover",w=i.imageAspectRatio||"auto",S=i.imageObjectFit||"cover",x=i.imageBorderRadius||"8px",v=document.createElement("div");v.className=`selwise-widget selwise-slide selwise-slide-${o}`,v.style.backgroundColor=s,v.style.color=l,v.style.width=u,v.style.padding=p,v.style.borderRadius=h,v.style.boxShadow=_(g),m&&"none"!==m&&(v.style.border=m),"right"===o||"left"===o?(v.style[o]=f,v.style.bottom=y,v.style.top="auto",v.style.transform="none"):"bottom"===o&&(v.style.bottom=y),A(v,e,t);const C=document.createElement("button");C.className="selwise-close",C.style.color=l,C.style.top="8px",C.style.right="8px",C.style.position="absolute",C.textContent="×",C.addEventListener("click",()=>v.remove()),v.appendChild(C);const k=B({imageUrl:n.imageUrl,mode:b,aspectRatio:w,objectFit:S,borderRadius:"fullWidth"===b?"0px":x,alt:""});if(k&&(k.style.marginBottom="16px",v.appendChild(k)),r){const e=document.createElement("div");e.style.fontSize="18px",e.style.fontWeight="600",e.style.marginBottom="8px",e.textContent=r,v.appendChild(e)}if(a){const e=document.createElement("div");e.style.fontSize="14px",e.style.marginBottom="16px",e.style.opacity="0.8",e.textContent=a,v.appendChild(e)}if(n.buttonText){const t=document.createElement("a");t.href=L(n.buttonUrl),t.className="selwise-bar-btn",t.style.display="block",t.style.textAlign="center",t.style.background=c,t.style.color=d,t.textContent=n.buttonText,t.addEventListener("click",()=>R(e.id)),v.appendChild(t)}return document.body.appendChild(v),v}(e,n);case"embedded_card":return function(e,t){const n=t.contentJson||{},i=t.stylesJson||{},o=n.title||n.headline||"",r=n.text||n.subtext||"",a=i.backgroundColor||"#ffffff",s=i.textColor||"#1f2937",l=i.buttonColor||s,c=i.buttonTextColor||a,d=i.borderRadius||"12px",u=i.padding||"16px",p=i.shadow||"md",h=i.border,g=i.contentAlignment||"left",m=i.imageMode||"cover",f=i.imagePosition||"top",y=i.imageAspectRatio||"16/9",b=i.imageObjectFit||"cover",w=i.imageBorderRadius||"8px",S=document.createElement("div");S.className="selwise-widget selwise-card",S.style.backgroundColor=a,S.style.color=s,S.style.borderRadius=d,S.style.boxShadow=_(p),S.style.overflow="hidden",S.style.textAlign=g,h&&"none"!==h&&(S.style.border=h),A(S,e,t);const x=B({imageUrl:n.imageUrl,mode:m,aspectRatio:y,objectFit:b,borderRadius:"fullWidth"===m?"0px":w,alt:""}),v=document.createElement("div");if(v.className="selwise-card-body",v.style.padding=u,o){const e=document.createElement("div");e.className="selwise-card-title",e.style.fontSize="16px",e.style.fontWeight="600",e.style.marginBottom="8px",e.textContent=o,v.appendChild(e)}if(r){const e=document.createElement("div");e.className="selwise-card-text",e.style.fontSize="14px",e.style.opacity="0.8",e.style.marginBottom="12px",e.textContent=r,v.appendChild(e)}if(n.buttonText){const e=document.createElement("a");e.href=L(n.buttonUrl),e.className="selwise-bar-btn",e.style.display="inline-block",e.style.background=l,e.style.color=c,e.textContent=n.buttonText,v.appendChild(e)}return"top"===f?(x&&S.appendChild(x),S.appendChild(v)):(S.appendChild(v),x&&S.appendChild(x)),U(S,e,`embedded-card:${e.id}`)?S:null}(e,n);case"sticky_footer":return function(e,t){const n=t.contentJson||{},i=t.stylesJson||{},{text:o,headline:r,subtext:a,buttonText:s,buttonUrl:l}=n,{backgroundColor:c="#1a1a1a",textColor:d="#ffffff",buttonColor:u,buttonTextColor:p,closeButtonColor:h,showCloseButton:g=!0,padding:m="12px",fontSize:f="14px",fontWeight:y="medium",borderTop:b,shadow:w="lg"}=i,S=o||r||"",x=u||d,v=p||c,C=document.createElement("div");C.className="selwise-widget selwise-footer",C.style.backgroundColor=c,C.style.color=d,C.style.padding=m,C.style.fontSize=f,C.style.fontWeight=P(y),C.style.boxShadow=_(w),b&&"none"!==b&&(C.style.borderTop=b),A(C,e,t);const k=document.createElement("span");if(k.className="selwise-bar-text",k.textContent=`${S}${a?` - ${a}`:""}`,C.appendChild(k),s){const e=document.createElement("a");e.href=L(l),e.className="selwise-bar-btn",e.style.background=x,e.style.color=v,e.textContent=s,C.appendChild(e)}return!1!==g&&C.appendChild(D(h||d,()=>C.remove())),document.body.appendChild(C),C}(e,n);case"countdown_timer":return function(e,t){const n=t.contentJson||{},i=t.stylesJson||{},{title:o,headline:r,text:a,subtext:s,buttonText:l,buttonUrl:c,endDate:d}=n,{backgroundColor:u="#ef4444",textColor:p="#ffffff",timerBgColor:h,timerTextColor:g,separatorStyle:m="colon",buttonColor:f,buttonTextColor:y,padding:b="12px",fontSize:w="14px",fontWeight:S="medium",timerFontSize:x="24px",timerFontWeight:v="700"}=i,C=e.placementConfigJson.position||"top",k=o||r||"",T=a||s||"",I=f||p,E=y||u,_=h||"rgba(0,0,0,0.1)",$=g||p,O=document.createElement("div");if(O.className=`selwise-widget selwise-bar selwise-bar-${C}`,O.style.backgroundColor=u,O.style.color=p,O.style.padding=b,O.style.fontSize=w,O.style.fontWeight=P(S),A(O,e,t),k){const e=document.createElement("span");e.className="selwise-bar-text",e.style.marginRight="8px",e.textContent=k,O.appendChild(e)}const M=document.createElement("div");M.className="selwise-countdown",M.style.background=_,M.style.color=$;const N="dot"===m?"•":"slash"===m?"/":"none"===m?"":":",R=()=>{if(!N)return;const e=document.createElement("span");e.className="selwise-countdown-sep",e.textContent=N,M.appendChild(e)};if(M.appendChild(F("days","Days",x,v)),R(),M.appendChild(F("hours","Hours",x,v)),R(),M.appendChild(F("minutes","Mins",x,v)),R(),M.appendChild(F("seconds","Secs",x,v)),O.appendChild(M),T){const e=document.createElement("span");e.className="selwise-bar-text",e.style.marginLeft="8px",e.textContent=T,O.appendChild(e)}if(l){const e=document.createElement("a");e.href=L(c),e.className="selwise-bar-btn",e.style.background=I,e.style.color=E,e.textContent=l,O.appendChild(e)}let B;if(O.appendChild(D(p,()=>{O.remove(),B&&clearInterval(B)})),document.body.appendChild(O),d){const e=new Date(d).getTime(),t=()=>{const t=Date.now(),n=Math.max(0,e-t),i=Math.floor(n/864e5),o=Math.floor(n%864e5/36e5),r=Math.floor(n%36e5/6e4),a=Math.floor(n%6e4/1e3),s=O.querySelector('[data-unit="days"]'),l=O.querySelector('[data-unit="hours"]'),c=O.querySelector('[data-unit="minutes"]'),d=O.querySelector('[data-unit="seconds"]');s&&(s.textContent=String(i).padStart(2,"0")),l&&(l.textContent=String(o).padStart(2,"0")),c&&(c.textContent=String(r).padStart(2,"0")),d&&(d.textContent=String(a).padStart(2,"0")),n<=0&&B&&clearInterval(B)};t(),B=window.setInterval(t,1e3)}return O}(e,n);case"cookie_consent":return Y(e,n);case"custom":return function(e,t){const{html:n,css:i,javascript:o,jsTiming:r}=t.contentJson,a=t.stylesJson||{};if(!n)return null;const s=document.createElement("div");var l;if(s.className="selwise-widget selwise-custom",s.style.padding=String(a.containerPadding||"0px"),s.style.backgroundColor=String(a.containerBackground||"transparent"),s.innerHTML=(l=n)?Ye.sanitize(l,{...Qe,ADD_TAGS:["style"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur"]}):"",A(s,e,t),i){const e=document.createElement("style");e.setAttribute("data-selwise-custom-css","true"),e.textContent=et(i),s.appendChild(e)}const c=e.placementConfigJson||{};if("selector"===c.placementType||"string"==typeof c.selector){if(!U(s,e,`custom:${e.id}`))return null}else document.body.appendChild(s);if(o){const n=new tt;n.execute({code:o,timing:r||"immediate",container:s,context:{widget:e,campaign:t}}),s._scriptExecutor=n}return s}(e,n);case"product_view_count":return function(e,t){const n=`product-view-count:${e.id}`,i=rt(e,t);return i?($(n),i):(O(n,()=>{const n=rt(e,t);return Boolean(n)},7e3),null)}(e,n);case"cart_count":return function(e,t){const n=`cart-count:${e.id}`,i=at(e,t);return i?($(n),i):(O(n,()=>{const n=at(e,t);return Boolean(n)},7e3),null)}(e,n);case"newsletter":return function(e,t){const n=t.contentJson||{},i=t.stylesJson||{},o=document.createElement("div");if(o.className="selwise-widget selwise-newsletter",o.style.backgroundColor=String(i.backgroundColor||"#ffffff"),o.style.color=String(i.textColor||"#111827"),o.style.padding=String(i.padding||"16px"),o.style.borderRadius=String(i.borderRadius||"12px"),o.style.boxShadow=_(String(i.shadow||"lg")),o.style.maxWidth=String(i.maxWidth||"360px"),o.style.width="calc(100vw - 32px)",o.style.border=String(i.border||"1px solid #e5e7eb"),o.style.zIndex="99998",o.style.boxSizing="border-box",o.style.fontSize=String(i.fontSize||"14px"),o.style.fontWeight=String(i.fontWeight||"normal"),A(o,e,t),!1!==i.showCloseButton){const e=D(String(i.textColor||"#111827"),()=>{o.remove()});e.style.top="10px",e.style.right="10px",o.appendChild(e)}const r=document.createElement("h4");r.className="selwise-newsletter-title",r.textContent=String(n.headline||"Join our newsletter"),r.style.margin="0 0 8px",r.style.fontSize=String(i.headlineFontSize||"20px"),r.style.fontWeight="700",o.appendChild(r);const a=document.createElement("p");a.className="selwise-newsletter-description",a.textContent=String(n.text||"Get updates and offers delivered to your inbox."),a.style.margin="0 0 12px",a.style.opacity="0.88",a.style.lineHeight="1.5",o.appendChild(a);const s=document.createElement("form");s.className="selwise-newsletter-form",s.style.display="grid",s.style.gridTemplateColumns="1fr auto",s.style.gap="8px";const l=document.createElement("input");l.type="email",l.required=!0,l.className="selwise-newsletter-input",l.placeholder=String(n.emailPlaceholder||"you@example.com"),l.style.width="100%",l.style.padding="10px 12px",l.style.borderRadius="8px",l.style.border=`1px solid ${String(i.inputBorderColor||"#d1d5db")}`,l.style.backgroundColor=String(i.inputBackgroundColor||"#f9fafb"),l.style.color=String(i.inputTextColor||"#111827"),l.style.outline="none";const c=document.createElement("button");c.type="submit",c.className="selwise-newsletter-submit",c.textContent=String(n.buttonText||"Subscribe"),c.style.padding="10px 14px",c.style.border="none",c.style.borderRadius="8px",c.style.cursor="pointer",c.style.fontWeight="600",c.style.backgroundColor=String(i.buttonColor||"#111827"),c.style.color=String(i.buttonTextColor||"#ffffff"),s.appendChild(l),s.appendChild(c),o.appendChild(s);const d=document.createElement("p");d.className="selwise-newsletter-status",d.style.margin="10px 0 0",d.style.display="none",d.style.fontSize="12px",d.style.lineHeight="1.4",o.appendChild(d),s.addEventListener("submit",async e=>{e.preventDefault();const t=l.value.trim().toLowerCase();if(!st.test(t))return void ct(d,"error",String(n.errorMessage||"Please enter a valid email address."));const i=function(){const e=window.Selwise,t=e?.siteKey,n=e?.apiUrl;return t&&n?{siteKey:t,apiUrl:n,visitorId:"function"==typeof e.getVisitorId?e.getVisitorId():void 0,siteUserId:"function"==typeof e.getSiteUserId?e.getSiteUserId():void 0}:null}();if(!i)return void ct(d,"error",String(n.errorMessage||"Widget runtime is not initialized."));const o=String(n.buttonText||"Subscribe");c.disabled=!0,l.disabled=!0,c.textContent="Submitting...",ct(d,"idle","");try{const e=await fetch(`${i.apiUrl}/public/sites/${i.siteKey}/newsletter`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t,locale:lt(),visitorId:i.visitorId,siteUserId:i.siteUserId,sourcePath:window.location.pathname||"/",referrer:document.referrer||void 0,autoConnectUsers:!0})}),o=await e.json().catch(()=>({})),r=function(e){return e.success?"pending_confirmation"===e.status?{state:"pending",message:e.message||"Please check your inbox and confirm your subscription."}:{state:"success",message:e.message||"Subscription completed successfully."}:{state:"error",message:e.message||"Unable to subscribe right now. Please try again."}}(e.ok?o:{success:!1,message:o.message||String(n.errorMessage||"Unable to subscribe right now.")});o.message||("pending"===r.state&&(r.message="Please check your inbox and confirm your subscription."),"success"===r.state&&(r.message=String(n.successMessage||"You are subscribed.")),"error"===r.state&&(r.message=String(n.errorMessage||"Unable to subscribe right now. Please try again."))),ct(d,r.state,r.message),"error"===r.state?(c.disabled=!1,l.disabled=!1):(c.disabled=!0,l.disabled=!0)}catch{ct(d,"error",String(n.errorMessage||"Unable to subscribe right now. Please try again.")),c.disabled=!1,l.disabled=!1}finally{c.disabled?c.textContent="Done":c.textContent=o}});const u=e.placementConfigJson||{};if("selector"===u.placementType||"string"==typeof u.selector){const t=`newsletter:${e.id}`;return U(o,e,t)?o:null}const p=function(e){const t=(e||"bottom-right").toLowerCase();return"center"===t||"center-modal"===t?{top:"50%",left:"50%",transform:"translate(-50%, -50%)"}:"bottom-left"===t||"left"===t?{bottom:"20px",left:"20px"}:"top-left"===t?{top:"20px",left:"20px"}:"top-right"===t||"top"===t?{top:"20px",right:"20px"}:{bottom:"20px",right:"20px"}}(String(u.position||"bottom-right"));return o.style.position="fixed",p.top&&(o.style.top=p.top),p.right&&(o.style.right=p.right),p.bottom&&(o.style.bottom=p.bottom),p.left&&(o.style.left=p.left),p.transform&&(o.style.transform=p.transform),document.body.appendChild(o),o}(e,n);default:return console.warn(`[Selwise] Unknown widget type: ${e.type}`),null}}}class ut{normalizeSelector(e){return e&&"string"==typeof e?e.trim().replace(/\s+/g," ").toLowerCase():""}normalizePlacementPosition(e){return e&&"string"==typeof e?e.trim().toLowerCase():""}buildConflictScope(e){if(e.scope&&"string"==typeof e.scope&&e.scope.trim().length>0)return e.scope;const t=this.normalizeSelector(e.selector);if(t)return`selector:${t}`;const n=this.normalizePlacementPosition(e.placementPosition);return n?`fixed:${n}`:`entity:${e.id}`}resolve(e,t){if(0===e.length)return{selected:[],rejected:[],reason:"No widgets to resolve"};if(1===e.length)return{selected:[e[0]],rejected:[],reason:"Single widget, no conflict"};const n=e.filter(e=>"random"===e.conflictBehavior);if(e.filter(e=>"all"===e.conflictBehavior).length>0)return{selected:e,rejected:[],reason:"All widgets shown (behavior=all)"};if(n.length===e.length){const t=this.selectRandom(e);return{selected:t,rejected:e.filter(e=>!t.includes(e)),reason:"Random selection"}}const i=[...e].sort((e,t)=>{const n=e.priority??0,i=t.priority??0;return i!==n?i-n:e.id.localeCompare(t.id)}),o=i[0].priority??0,r=[i.filter(e=>(e.priority??0)===o)[0]];return{selected:r,rejected:e.filter(e=>!r.includes(e)),reason:`Highest priority (${o})`}}selectRandom(e){return 0===e.length?[]:1===e.length?[e[0]]:[e[Math.floor(Math.random()*e.length)]]}widgetsConflict(e,t){return this.buildConflictScope(e)===this.buildConflictScope(t)}groupByConflicts(e){const t=[],n=new Set;for(const i of e){if(n.has(i.id))continue;const o=[i];n.add(i.id);for(const t of e)t.id===i.id||n.has(t.id)||this.widgetsConflict(i,t)&&(o.push(t),n.add(t.id));o.length>1?t.push(o):t.push([i])}return t}resolveAll(e){return this.groupByConflicts(e).map(e=>this.resolve(e))}parseConfig(e){const t=(e.placementConfigJson||e.placementConfig||{}).conflictResolution||{};return{priority:e.priority??t.priority??0,behavior:t.behavior||"highest_priority"}}applyConfig(e){const t=this.parseConfig(e),n=this.buildConflictScope(e);return{...e,scope:n,priority:t.priority,conflictBehavior:t.behavior}}}let pt=null;function ht(){return pt||(pt=new ut),pt}const gt="https://api.selwise.com",mt="/api/v1";function ft(e){if(!e)return null;const t=e.trim();return t.length>0?t:null}function yt(e){const t="undefined"!=typeof process?ft(process.env?.NEXT_PUBLIC_API_URL):null,n=ft(e),i=t||n||gt;try{const e=new URL(i),t=function(e){const t=e.replace(/\/+$/,"");return t&&"/"!==t?t===mt||t.endsWith(mt)?t:`${t}${mt}`:mt}(e.pathname||"/");return`${e.origin}${t}`}catch{return`${gt}${mt}`}}const bt=new Map;let wt=null;function St(){return wt||(wt=function(){if("undefined"!=typeof localStorage)try{const e="__selwise_storage_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),localStorage}catch(e){G("Selwise","localStorage unavailable:",e)}if("undefined"!=typeof sessionStorage)try{const e="__selwise_storage_test__";return sessionStorage.setItem(e,"test"),sessionStorage.removeItem(e),J("Selwise","Using sessionStorage (persists until tab close)"),sessionStorage}catch(e){G("Selwise","sessionStorage unavailable:",e)}return J("Selwise","Using in-memory storage (persists until page refresh only). Visitor ID and experiments will reset on refresh."),{getItem:e=>bt.get(e)||null,setItem:(e,t)=>bt.set(e,t),removeItem:e=>bt.delete(e)}}()),wt}function xt(e){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`${e}_${crypto.randomUUID()}`;if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const t=new Uint8Array(16);return crypto.getRandomValues(t),`${e}_${Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}`}return J("Selwise","crypto.getRandomValues not available, using less secure fallback"),`${e}_${Date.now().toString(36)}${Math.random().toString(36).substring(2,15)}`}function vt(){const e=St();try{let e=sessionStorage.getItem(r);return e||(e=xt("sid"),sessionStorage.setItem(r,e)),e}catch{let t=e.getItem(r);return t||(t=xt("sid"),e.setItem(r,t)),t}}function Ct(){const e=St();let t=e.getItem(a);return t||(t=xt("vid"),e.setItem(a,t)),t}function kt(){return St().getItem(s)||void 0}function Tt(){const e=St(),t=Ct();let n=e.getItem(c);const i=e.getItem(d);if(n&&i){const o=parseInt(i,10);if(Date.now()-o<18e5){const i=`journey_${t}`;if(n.startsWith(i))return e.setItem(d,Date.now().toString()),n}}return n=`journey_${t}_${Date.now()}`,e.setItem(c,n),e.setItem(d,Date.now().toString()),n}function It(){const e=Date.now().toString(36);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const t=new Uint8Array(8);return crypto.getRandomValues(t),`eid_${e}_${Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}`}return`eid_${e}_${Math.random().toString(36).substring(2,10)}`}const Et=new Set(["productId","productSku","sku"]);function _t(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t={};for(const[n,i]of Object.entries(e))Et.has(n)||(t[n]=i);return t}const Pt="events";class At{constructor(){this.db=null,this.initialized=!1,this.initPromise=null,this.disabled=!1,this.initPromise=this.init()}async init(){if(this.disabled)return!1;if("undefined"==typeof indexedDB)return this.disabled=!0,!1;try{return this.db=await new Promise((e,t)=>{const n=indexedDB.open("selwise_event_queue",1);n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result),n.onupgradeneeded=e=>{const t=e.target.result;if(!t.objectStoreNames.contains(Pt)){const e=t.createObjectStore(Pt,{keyPath:"id",autoIncrement:!0});e.createIndex("queuedAt","queuedAt"),e.createIndex("eventId","eventId",{unique:!0})}}}),this.initialized=!0,await this.cleanupOldEvents(),!0}catch(e){return this.disabled=!0,!1}}async ready(){return this.initialized?null!==this.db:!!this.initPromise&&this.initPromise}async store(e){if(await this.ready()&&0!==e.length)try{const t=this.db.transaction([Pt],"readwrite").objectStore(Pt),n=Date.now();for(const i of e)await this.getByEventId(i.eventId)||t.add({...i,queuedAt:n});await this.enforceSizeLimit()}catch(e){}}async retrieve(e=50){if(!await this.ready())return[];try{const t=this.db.transaction([Pt],"readonly").objectStore(Pt).index("queuedAt"),n=await new Promise((n,i)=>{const o=t.openCursor(null,"next"),r=[];o.onsuccess=t=>{const i=t.target.result;i&&r.length<e?(r.push(i.value),i.continue()):n(r)},o.onerror=()=>i(o.error)});return n.length>0&&await this.remove(n.map(e=>e.id)),n.map(({id:e,queuedAt:t,...n})=>n)}catch(e){return[]}}async getByEventId(e){if(!this.db)return null;try{const t=this.db.transaction([Pt],"readonly").objectStore(Pt).index("eventId");return await new Promise((n,i)=>{const o=t.get(e);o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error)})}catch{return null}}async remove(e){if(this.db&&0!==e.length)try{const t=this.db.transaction([Pt],"readwrite").objectStore(Pt);for(const n of e)t.delete(n)}catch{}}async enforceSizeLimit(){if(this.db)try{const e=await this.getCount();if(e>1e3){const t=e-1e3,n=this.db.transaction([Pt],"readwrite").objectStore(Pt).index("queuedAt");let i=0;n.openCursor(null,"next").onsuccess=e=>{const n=e.target.result;n&&i<t&&(n.delete(),i++,n.continue())}}}catch{}}async getCount(){if(!this.db)return 0;try{const e=this.db.transaction([Pt],"readonly").objectStore(Pt);return await new Promise((t,n)=>{const i=e.count();i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}catch{return 0}}async cleanupOldEvents(){if(this.db)try{const e=Date.now()-864e5,t=this.db.transaction([Pt],"readwrite").objectStore(Pt).index("queuedAt"),n=IDBKeyRange.upperBound(e);t.openCursor(n).onsuccess=e=>{const t=e.target.result;t&&(t.delete(),t.continue())}}catch{}}async getStats(){if(!await this.ready())return{count:0,oldestTimestamp:null};try{const e=await this.getCount();let t=null;if(e>0){const e=this.db.transaction([Pt],"readonly").objectStore(Pt).index("queuedAt");t=await new Promise(t=>{const n=e.openCursor(null,"next");n.onsuccess=e=>{const n=e.target.result;t(n?n.value.queuedAt:null)},n.onerror=()=>t(null)})}return{count:e,oldestTimestamp:t}}catch{return{count:0,oldestTimestamp:null}}}async clear(){if(await this.ready())try{this.db.transaction([Pt],"readwrite").objectStore(Pt).clear()}catch{}}isAvailable(){return!this.disabled&&this.initialized&&null!==this.db}}let $t=null;const Ot="selwise_event_queue";class Dt{constructor(e={}){this.queue=[],this.consentQueue=[],this.flushTimeout=null,this.pageHideHandler=null,this.isFlushing=!1,this.consentChecked=!1,this.consentGranted=!1,this.useIndexedDBForConsent=!0,this.maxRetries=3,this.maxQueueSize=100,this.maxStorageEvents=50,this.debugMode=!1,this.processedEvents=new Set,this.lastEventId=null,this.journeyEventCount=0,this.metrics={eventsDropped:0,batchesFailed:0,sendBeaconFailed:0,overflowStored:0},this.initialized=!1,this.config={apiUrl:yt(e.apiUrl),siteKey:e.siteKey||"",batchSize:e.batchSize??50,flushInterval:e.flushInterval??3e4,enablePersistence:e.enablePersistence??!0,enableSendBeacon:e.enableSendBeacon??!0},this.maxRetries=e.maxRetries??3,this.maxQueueSize=e.maxQueueSize??100,this.maxStorageEvents=e.maxStorageEvents??50,this.debugMode=e.debugMode??!1,this.overflowStorage=($t||($t=new At),$t),this.tabCorrelationId=this.generateTabCorrelationId(),this.sessionData={sessionId:e.sessionId||this.generateSessionId(),visitorId:e.visitorId||this.generateVisitorId(),siteUserId:e.siteUserId},this.config.enablePersistence&&this.loadFromStorage(),this.config.enableSendBeacon&&this.setupPageHideHandler(),this.startCleanupInterval(),this.debugMode&&W("EventBatcher","Initialized with config:",{...this.config,maxRetries:this.maxRetries,maxQueueSize:this.maxQueueSize,maxStorageEvents:this.maxStorageEvents})}async initialize(){if(!this.initialized)try{await this.loadFromOverflowStorage(),this.queue.length>0&&(this.debugMode&&W("EventBatcher","Flushing",this.queue.length,"recovered events"),await this.flush())}catch(e){this.debugMode&&K("EventBatcher","Initialization error:",e)}finally{this.initialized=!0}}isReady(){return this.initialized}setSessionData(e,t,n){this.sessionData={sessionId:e,visitorId:t,siteUserId:n}}setSiteKey(e){this.config.siteKey=e}updateConfig(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize,this.debugMode&&W("EventBatcher","batchSize updated:",e.batchSize)),void 0!==e.flushInterval&&(this.config.flushInterval=e.flushInterval,this.debugMode&&W("EventBatcher","flushInterval updated:",e.flushInterval)),void 0!==e.enablePersistence&&(this.config.enablePersistence=e.enablePersistence,this.debugMode&&W("EventBatcher","enablePersistence updated:",e.enablePersistence)),void 0!==e.enableSendBeacon&&(this.config.enableSendBeacon=e.enableSendBeacon,this.debugMode&&W("EventBatcher","enableSendBeacon updated:",e.enableSendBeacon)),void 0!==e.maxRetries&&(this.maxRetries=e.maxRetries,this.debugMode&&W("EventBatcher","maxRetries updated:",e.maxRetries)),void 0!==e.maxQueueSize&&(this.maxQueueSize=e.maxQueueSize,this.debugMode&&W("EventBatcher","maxQueueSize updated:",e.maxQueueSize)),void 0!==e.maxStorageEvents&&(this.maxStorageEvents=e.maxStorageEvents,this.debugMode&&W("EventBatcher","maxStorageEvents updated:",e.maxStorageEvents)),void 0!==e.debugMode&&(this.debugMode=e.debugMode,W("EventBatcher","debugMode updated:",e.debugMode))}add(e){const t={...e,metadata:_t(e.metadata)};if(t.eventId||(t.eventId=It()),this.processedEvents.has(t.eventId))return;t.timestamp=t.timestamp||Date.now(),t.eventTs=t.eventTs||t.timestamp,t.eventSchemaVersion=t.eventSchemaVersion||1,t.retryCount=t.retryCount||0;const n=function(){const e=St();let t=e.getItem(u);const n=e.getItem(p);if(t&&n){const e=parseInt(n,10);if(Date.now()-e<864e5)return t}return t=xt("corr"),e.setItem(u,t),e.setItem(p,Date.now().toString()),t}();if(t.correlationId=`${n}_${this.tabCorrelationId}`,t.parentEventId=this.lastEventId??void 0,t.journeyId=Tt(),this.lastEventId=t.eventId,this.config.siteKey&&!this.checkConsentForEvent(t))return this.consentQueue.push(t),void(this.debugMode&&W("EventBatcher","Event queued pending consent:",t.name));this.queue.length>=this.maxQueueSize?this.storeInOverflow([t]):(this.queue.push(t),this.processedEvents.add(t.eventId),this.config.enablePersistence&&this.saveToStorage(),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush())}checkConsentForEvent(e){const t=e.name,n=Object.keys(v);for(const e of n)if(v[e].indexOf(t)>=0){try{const t=`${b}_${this.config.siteKey}`,n=localStorage.getItem(t);if(n){const t=JSON.parse(n);return t.categories?.[e]??!1}}catch{}return!1}return!0}scheduleFlush(){this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=window.setTimeout(()=>{this.flush()},this.config.flushInterval)}async flush(){if(this.isFlushing||0===this.queue.length)return;if(!this.config.siteKey)return this.queue=[],void this.saveToStorage();this.isFlushing=!0;const e=this.queue.splice(0);try{await this.sendBatch(e)?e.forEach(e=>this.processedEvents.delete(e.eventId)):this.requeueEvents(e)}catch(t){this.requeueEvents(e)}finally{this.isFlushing=!1,this.saveToStorage()}}async sendBatch(e){(function(){const e=St().getItem(d);if(!e)return!0;const t=parseInt(e,10);return Date.now()-t>=18e5})()&&(this.journeyEventCount=0);const t=e.map((e,t)=>this.journeyEventCount+t+1),n=e.map((e,n)=>({...e,eventSchemaVersion:e.eventSchemaVersion||1,eventTs:e.eventTs||e.timestamp||Date.now(),metadata:_t(e.metadata),journeySequence:t[n]})),i={sessionId:this.sessionData.sessionId,visitorId:this.sessionData.visitorId,journeyId:Tt(),siteUserId:this.sessionData.siteUserId,pageUrl:window.location.href,referrer:document.referrer||void 0,events:n};try{const t=(await fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0})).ok;return t?this.journeyEventCount+=e.length:(this.metrics.batchesFailed++,this.reportMetric("batch_failure",1)),t}catch(e){return this.metrics.batchesFailed++,this.reportMetric("batch_failure",1),!1}}requeueEvents(e){for(const t of e)t.retryCount=(t.retryCount||0)+1,t.retryCount<=this.maxRetries?this.queue.length<this.maxQueueSize?this.queue.push(t):this.storeInOverflow([t]):(this.debugMode&&W("EventBatcher","Dropped event after",this.maxRetries,"retries:",t.eventId),this.metrics.eventsDropped++);this.queue.sort((e,t)=>{const n=e.retryCount||0,i=t.retryCount||0;return n!==i?n-i:e.timestamp-t.timestamp})}setupPageHideHandler(){this.pageHideHandler=()=>{if(0===this.queue.length||!this.config.siteKey)return;const e=this.queue.splice(0),t=e.map((e,t)=>this.journeyEventCount+t+1),n=e.map((e,n)=>({...e,eventSchemaVersion:e.eventSchemaVersion||1,eventTs:e.eventTs||e.timestamp||Date.now(),metadata:_t(e.metadata),journeySequence:t[n]})),i={sessionId:this.sessionData.sessionId,visitorId:this.sessionData.visitorId,journeyId:Tt(),siteUserId:this.sessionData.siteUserId,pageUrl:window.location.href,referrer:document.referrer||void 0,events:n},o=new Blob([JSON.stringify(i)],{type:"application/json"});navigator.sendBeacon?navigator.sendBeacon(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/events/batch`,o)?this.persistPendingJourneyIncrement(e.length):(this.metrics.sendBeaconFailed++,this.reportMetric("sendBeacon_failure",1),this.queue.push(...e)):this.queue.push(...e)},document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.pageHideHandler?.()}),window.addEventListener("beforeunload",()=>{this.pageHideHandler?.()})}persistPendingJourneyIncrement(e){try{const t={count:e,timestamp:Date.now(),journeyId:Tt()};localStorage.setItem("selwise_pending_journey_increment",JSON.stringify(t))}catch{}}async recoverPendingJourneyIncrement(){try{const e=localStorage.getItem("selwise_pending_journey_increment");if(!e)return;const t=JSON.parse(e);if(Date.now()-t.timestamp>3e5)return void localStorage.removeItem("selwise_pending_journey_increment");localStorage.removeItem("selwise_pending_journey_increment")}catch{localStorage.removeItem("selwise_pending_journey_increment")}}saveToStorage(){if(this.config.enablePersistence)try{if(!this.checkStorageQuota())return void(this.debugMode&&W("EventBatcher","Storage quota exceeded, skipping save"));const e={version:2,queue:this.queue.slice(0,this.maxStorageEvents),timestamp:Date.now()};localStorage.setItem(Ot,JSON.stringify(e)),this.debugMode&&W("EventBatcher","Saved",e.queue.length,"events to storage")}catch(e){this.debugMode&&W("EventBatcher","Failed to save to storage:",e)}}checkStorageQuota(){try{const e=2097152;let t=0;for(let e=0;e<localStorage.length;e++){const n=localStorage.key(e);if(n&&n.startsWith("selwise_")){const e=localStorage.getItem(n);e&&(t+=n.length+e.length)}}const n=JSON.stringify({version:2,queue:this.queue.slice(0,this.maxStorageEvents),timestamp:Date.now()}).length;if(t+n>e){this.cleanupOldStorage();let t=0;for(let e=0;e<localStorage.length;e++){const n=localStorage.key(e);if(n&&n.startsWith("selwise_")){const e=localStorage.getItem(n);e&&(t+=n.length+e.length)}}return t+n<=e}return!0}catch{return!0}}cleanupOldStorage(){try{const e="selwise_journey_state",t=localStorage.getItem(e);if(t)try{const n=JSON.parse(t),i=18e5;n.lastEventTime&&Date.now()-n.lastEventTime>i&&(localStorage.removeItem(e),this.debugMode&&W("EventBatcher","Cleaned up expired journey state"))}catch{localStorage.removeItem(e)}}catch{}}loadFromStorage(){try{const e=localStorage.getItem(Ot);if(!e)return;const t=JSON.parse(e);if(2===t.version&&Array.isArray(t.queue)){const e=Date.now()-864e5;this.queue=t.queue.filter(t=>t.timestamp>e).map(e=>({...e,metadata:_t(e.metadata)}))}localStorage.removeItem(Ot)}catch{localStorage.removeItem(Ot)}}getQueueSize(){return this.queue.length}getProcessedCount(){return this.processedEvents.size}clear(){this.queue=[],this.consentQueue=[],this.processedEvents.clear(),this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.config.enablePersistence&&localStorage.removeItem(Ot)}resetCorrelation(){this.lastEventId=null,this.debugMode&&W("EventBatcher","Correlation tracking reset")}getConsentQueueSize(){return this.consentQueue.length}flushConsentQueue(){if(0===this.consentQueue.length)return;this.debugMode&&W("EventBatcher","Flushing consent queue:",this.consentQueue.length,"events");const e=this.consentQueue.splice(0);for(const t of e)this.checkConsentForEvent(t)?(this.queue.push(t),this.processedEvents.add(t.eventId)):this.consentQueue.push(t);this.queue.length>0&&(this.config.enablePersistence&&this.saveToStorage(),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush()),this.debugMode&&W("EventBatcher","Consent queue flushed. Main queue:",this.queue.length,"Remaining consent queue:",this.consentQueue.length)}destroy(){this.clear(),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),this.pageHideHandler&&(document.removeEventListener("visibilitychange",this.pageHideHandler),window.removeEventListener("beforeunload",this.pageHideHandler),this.pageHideHandler=null)}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{this.cleanupProcessedEvents()},3e5),this.debugMode&&W("EventBatcher","Cleanup interval started")}cleanupProcessedEvents(){if(this.processedEvents.size>5e3){const e=Array.from(this.processedEvents);this.processedEvents=new Set(e.slice(-5e3)),this.debugMode&&W("EventBatcher","Cleaned up processed events, kept last 5000")}this.consentQueue.length>100&&(this.consentQueue=this.consentQueue.slice(-50),this.debugMode&&W("EventBatcher","Cleaned up consent queue, kept last 50"))}generateSessionId(){return`sess_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}generateVisitorId(){let e=null;try{e=localStorage.getItem("selwise_visitor_id"),e||(e=`vis_${Date.now()}_${Math.random().toString(36).substring(2,15)}`,localStorage.setItem("selwise_visitor_id",e))}catch{e=`vis_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}return e}generateTabCorrelationId(){return`tab_${Math.random().toString(36).substring(2,11)}`}storeInOverflow(e){this.overflowStorage.store(e).then(()=>{this.metrics.overflowStored+=e.length,this.debugMode&&W("EventBatcher","Stored",e.length,"events in overflow storage")}).catch(()=>{this.metrics.eventsDropped+=e.length,this.debugMode&&J("EventBatcher","Overflow storage unavailable, dropped",e.length,"events")})}async loadFromOverflowStorage(){if(this.overflowStorage.isAvailable())try{const e=await this.overflowStorage.retrieve(this.maxQueueSize);if(e.length>0){this.debugMode&&W("EventBatcher","Loaded",e.length,"events from overflow storage");for(const t of e){if(!(this.queue.length<this.maxQueueSize))break;this.queue.push({...t,metadata:_t(t.metadata)})}}}catch(e){this.debugMode&&K("EventBatcher","Failed to load overflow storage:",e)}}getMetrics(){return{...this.metrics,queueSize:this.queue.length,processedCount:this.processedEvents.size,consentQueueSize:this.consentQueue.length,overflowStats:{count:0,oldestTimestamp:null}}}async getOverflowStats(){return this.overflowStorage.getStats()}reportMetric(e,t){if(!this.config.siteKey)return;const n=`${this.config.apiUrl}/public/sites/${this.config.siteKey}/metrics`;if(navigator.sendBeacon){const i=new Blob([JSON.stringify({name:e,value:t,timestamp:Date.now()})],{type:"application/json"});navigator.sendBeacon(n,i)}else fetch(n,{method:"POST",body:JSON.stringify({name:e,value:t,timestamp:Date.now()}),keepalive:!0}).catch(()=>{})}async flushMetrics(){if(!this.config.siteKey)return;const e=await this.getOverflowStats(),t={metrics:{eventsDropped:this.metrics.eventsDropped,batchesFailed:this.metrics.batchesFailed,sendBeaconFailed:this.metrics.sendBeaconFailed,overflowStored:this.metrics.overflowStored,overflowCount:e.count},timestamp:Date.now()};try{await fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/metrics`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0}),this.metrics={eventsDropped:0,batchesFailed:0,sendBeaconFailed:0,overflowStored:0}}catch{}}}class Mt{constructor(e=yt(),t="",n){this.queue=[],this.flushTimeout=null,this.viewObservers=new Map,this.viewedElements=new Set,this.hoverStartTimes=new Map,this.useAdvancedBatching=!1,this.spaCleanupSetup=!1,this.apiUrl=e,this.siteKey=t,this.sessionId=vt(),this.visitorId=Ct(),this.siteUserId=kt(),!1!==n?.enabled&&n&&(this.useAdvancedBatching=!0,this.batcher=new Dt({...n,apiUrl:this.apiUrl,siteKey:this.siteKey,sessionId:this.sessionId,visitorId:this.visitorId,siteUserId:this.siteUserId}))}enableSPACleanup(){this.spaCleanupSetup||(this.setupSPACleanup(),this.spaCleanupSetup=!0)}setSiteKey(e){this.siteKey=e,this.batcher&&this.batcher.setSiteKey(e)}setBatcherConfig(e){if(!1===e.enabled)return this.useAdvancedBatching=!1,this.batcher?.destroy(),void(this.batcher=void 0);!0!==e.enabled||this.useAdvancedBatching||(this.useAdvancedBatching=!0),this.batcher?this.batcher.updateConfig(e):(this.batcher=new Dt({...e,apiUrl:this.apiUrl,siteKey:this.siteKey,sessionId:this.sessionId,visitorId:this.visitorId,siteUserId:this.siteUserId}),this.useAdvancedBatching=!0)}setSiteUserId(e){this.siteUserId=e,function(e){const t=St();e?t.setItem(s,e):t.removeItem(s)}(e)}getSessionId(){return this.sessionId}getVisitorId(){return this.visitorId}getSiteUserId(){return this.siteUserId}getJourneyId(){try{const e=localStorage.getItem(c),t=localStorage.getItem(d);if(e&&t){const n=parseInt(t,10);if(Date.now()-n<18e5)return e}return null}catch{return null}}endJourney(){try{localStorage.removeItem(c),localStorage.removeItem(d)}catch{}}getJourneyState(){try{const e=localStorage.getItem(c),t=localStorage.getItem(d);if(!e||!t)return{journeyId:null,age:null,isValid:!1};const n=parseInt(t,10),i=Date.now()-n;return{journeyId:e,age:i,isValid:i<18e5}}catch{return{journeyId:null,age:null,isValid:!1}}}getSiteUserProfileId(){try{return localStorage.getItem(l)||void 0}catch{return}}async identify(e,t){const n=this.siteUserId;this.setSiteUserId(e),this.batcher&&this.batcher.setSessionData(this.sessionId,this.visitorId,e);try{const i=await fetch(`${this.apiUrl}/public/sites/${this.siteKey}/users/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({externalId:e,visitorId:this.visitorId,sessionId:this.sessionId,traits:t,pageUrl:window.location.href,userAgent:navigator.userAgent}),keepalive:!0});if(i.ok){const o=await i.json();if((o.merged||o.aliases)&&this.updateMergedVisitorIds(o.aliases||[this.visitorId]),o.user?.id)try{localStorage.setItem(l,o.user.id)}catch{}return(n!==e||o.merged)&&this.track("identify",{entityType:"user",entityId:e,metadata:{...t,previousId:n,visitorId:this.visitorId,merged:o.merged}}),{success:!0,merged:o.merged}}}catch(e){G("Selwise","Identity merge API call failed, using local tracking:",e)}return n!==e&&this.track("identify",{entityType:"user",entityId:e,metadata:{...t,previousId:n,visitorId:this.visitorId,merged:!1}}),{success:!1,merged:!1}}async setTraits(e){if(!this.siteKey)return!1;try{const t=JSON.parse(localStorage.getItem(x)||"{}");t&&"object"==typeof t&&!Array.isArray(t)?localStorage.setItem(x,JSON.stringify({...t,...e})):localStorage.setItem(x,JSON.stringify(e))}catch(e){G("Selwise","Failed to cache traits:",e)}try{const t=await fetch(`${this.apiUrl}/public/sites/${this.siteKey}/users/traits`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({externalId:this.siteUserId,visitorId:this.siteUserId?void 0:this.visitorId,traits:e}),keepalive:!0});if(t.ok)return!0===(await t.json()).success}catch(e){G("Selwise","Set traits API call failed:",e)}return!1}updateMergedVisitorIds(e){try{const t=JSON.parse(localStorage.getItem(S)||"[]");if(Array.isArray(t)){const n=new Set([...t,...e]);localStorage.setItem(S,JSON.stringify([...n]))}else{const t=new Set(e);localStorage.setItem(S,JSON.stringify([...t]))}}catch(e){G("Selwise","Failed to update merged visitor IDs:",e)}}getMergedVisitorIds(){try{const e=JSON.parse(localStorage.getItem(S)||"[]");return Array.isArray(e)?e:[]}catch(e){return G("Selwise","Failed to get merged visitor IDs:",e),[]}}track(e,t){const n=Date.now(),i=It(),o=_t(t?.metadata),r={eventId:i,eventSchemaVersion:1,eventTs:n,name:e,entityType:t?.entityType,entityId:t?.entityId,metadata:o};if("click"===e&&("campaign"===t?.entityType||"widget"===t?.entityType))try{sessionStorage.setItem(g,JSON.stringify({ts:Date.now(),campaignId:"campaign"===t.entityType&&t.entityId||null,widgetId:"widget"===t.entityType&&t.entityId||null}))}catch{}this.useAdvancedBatching&&this.batcher?this.batcher.add({...r,timestamp:Date.now()}):(this.queue.push(r),this.scheduleFlush())}trackView(e,t,n,i){const o=`${t}_${n}`;if(this.viewedElements.has(o))return;let r=null,a=null;const s=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting&&e.intersectionRatio>=.5?r||(r=Date.now(),a=window.setTimeout(()=>{this.viewedElements.has(o)||(this.viewedElements.add(o),this.track("view",{entityType:t,entityId:n,metadata:{...i,viewDuration:Date.now()-(r||Date.now()),scrollDepth:Math.round(window.scrollY/document.body.scrollHeight*100)}}))},1e3)):(a&&(clearTimeout(a),a=null),r=null)})},{threshold:.5});s.observe(e),this.viewObservers.set(o,s)}trackProductImpression(e,t,n,i){const o=`product_${t}_${n}`;if(this.viewedElements.has(o))return;const r=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting&&e.intersectionRatio>=.5&&(this.viewedElements.has(o)||(this.viewedElements.add(o),this.track("product_impression",{entityType:"recommendation",entityId:t,metadata:{productItemCode:n,position:i}}),r.disconnect()))})},{threshold:.5});r.observe(e)}trackHoverStart(e,t){const n=`${e}_${t}`;this.hoverStartTimes.set(n,Date.now())}trackHoverEnd(e,t,n){const i=`${e}_${t}`,o=this.hoverStartTimes.get(i);if(o){const r=Date.now()-o;this.hoverStartTimes.delete(i),r>=500&&this.track("hover",{entityType:e,entityId:t,metadata:{...n,hoverDuration:r}})}}trackScroll(e,t,n){this.track("scroll",{entityType:e,entityId:t,metadata:{scrollPercent:n}})}trackSliderNavigate(e,t,n,i){this.track("slider_navigate",{entityType:"recommendation",entityId:e,metadata:{direction:t,fromSlide:n,toSlide:i}})}trackSliderSwipe(e,t){this.track("slider_swipe",{entityType:"recommendation",entityId:e,metadata:{direction:t}})}trackSearchOpen(e="click"){this.track("search_instant_open",{entityType:"search",metadata:{trigger:e}})}trackSearchClose(e,t,n){this.track("search_close",{entityType:"search",metadata:{query:e,resultCount:t,dwellTime:n}})}trackCategoryFilter(e,t){this.track("category_filter",{entityType:"search",metadata:{categoryName:e,resultCount:t}})}trackRecentSearchClick(e){this.track("recent_search_click",{entityType:"search",metadata:{query:e}})}trackPopularSearchClick(e){this.track("popular_search_click",{entityType:"search",metadata:{query:e}})}trackPopularCategoryClick(e){this.track("popular_category_click",{entityType:"search",metadata:{categoryName:e}})}trackPopularProductClick(e){this.track("popular_product_click",{entityType:"search",metadata:{productItemCode:e}})}trackZeroResults(e){this.track("search_zero_results",{entityType:"search",metadata:{query:e}})}async trackOrder(e){if(!this.siteKey)return;const t=(e.orderId||"").toString().trim();if(!t)return;const n={...e,orderId:t},i=(()=>{try{const e=JSON.parse(sessionStorage.getItem(g)||"null"),t=JSON.parse(sessionStorage.getItem(m)||"null"),n=JSON.parse(sessionStorage.getItem(f)||"null"),i=e?.ts?Number(e.ts):0,o=t?.ts?Number(t.ts):0,r=n?.ts?Number(n.ts):0,a=Math.max(i,o,r);return 0===a?{}:r===a?{source:"search",searchProductId:n.productItemCode,searchQuery:n.query}:o===a?{source:"recommendation",recommendationWidgetId:t.recommendationWidgetId}:{source:"campaign",campaignId:e?.campaignId||void 0,widgetId:e?.widgetId||void 0}}catch{return{}}})(),o=(()=>{try{const e=localStorage.getItem(y);return e?JSON.parse(e):{}}catch(e){return{}}})();try{(await fetch(`${this.apiUrl}/public/sites/${this.siteKey}/orders`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,sessionId:this.sessionId,pageUrl:window.location.href,referrer:document.referrer||void 0,attribution:i,visitorId:n.visitorId||this.visitorId,siteUserId:n.siteUserId||this.siteUserId,experimentAssignments:o}),keepalive:!0})).ok&&(function(){const e=St();e.removeItem(u),e.removeItem(p)}(),this.batcher?.resetCorrelation())}catch(e){}}scheduleFlush(){this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=window.setTimeout(()=>this.flush(),1e3)}async flush(){if(0===this.queue.length)return;if(!this.siteKey)return void(this.queue=[]);const e=this.queue.splice(0).map(e=>({...e,eventSchemaVersion:e.eventSchemaVersion||1,eventTs:e.eventTs||Date.now(),metadata:_t(e.metadata)}));try{await fetch(`${this.apiUrl}/public/sites/${this.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.sessionId,visitorId:this.visitorId,journeyId:Tt(),siteUserId:this.siteUserId,pageUrl:window.location.href,referrer:document.referrer||void 0,events:e}),keepalive:!0})}catch(t){this.queue.push(...e)}}cleanup(){this.viewObservers.forEach(e=>e.disconnect()),this.viewObservers.clear(),this.viewedElements.clear(),this.hoverStartTimes.clear(),this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.batcher&&(this.batcher.destroy(),this.batcher=void 0)}setupSPACleanup(){const e=history.pushState,t=history.replaceState;history.pushState=(...t)=>{e.apply(history,t),this.scheduleDeferredCleanup()},history.replaceState=(...e)=>{t.apply(history,e),this.scheduleDeferredCleanup()},window.addEventListener("popstate",()=>{this.scheduleDeferredCleanup()}),window.addEventListener("hashchange",()=>{this.scheduleDeferredCleanup()})}scheduleDeferredCleanup(){setTimeout(()=>{this.viewObservers.size>0&&0===this.queue.length&&this.cleanup()},1e3)}async flushBatcher(){this.batcher?await this.batcher.flush():await this.flush()}getBatcherStats(){return this.batcher?{queueSize:this.batcher.getQueueSize(),consentQueueSize:this.batcher.getConsentQueueSize(),processedCount:this.batcher.getProcessedCount(),enabled:this.useAdvancedBatching}:{queueSize:this.queue.length,consentQueueSize:0,processedCount:0,enabled:!1}}async initialize(){this.batcher&&await this.batcher.initialize()}isReady(){return!this.batcher||this.batcher.isReady()}flushConsentQueue(){this.batcher&&this.batcher.flushConsentQueue()}setupConsentCallback(){if("undefined"!=typeof window){const e=window.Selwise;if(!e||"object"!=typeof e)return;e._flushConsentQueue=()=>this.flushConsentQueue(),"function"!=typeof e.getConsentState&&(e.getConsentState=()=>{try{if(!this.siteKey)return null;const e=`${b}_${this.siteKey}`,t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}})}}}var Nt=n(664);const Rt=new Map;class Lt{constructor(){this.storageKey="selwise_frequency_caps",this.storage=function(){if("undefined"!=typeof localStorage)try{const e="__selwise_frequency_caps_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{}return{getItem:e=>Rt.get(e)||null,setItem:(e,t)=>{Rt.set(e,t)},removeItem:e=>{Rt.delete(e)}}}()}parseInterval(e){if(!(0,Nt.validateFrequencyInterval)(e))return 0;const t=e.match(/^(\d+)([hmdw])$/);if(!t)return 0;const n=parseInt(t[1],10);switch(t[2]){case"h":return 60*n*60*1e3;case"m":return 60*n*1e3;case"d":return 24*n*60*60*1e3;case"w":return 7*n*24*60*60*1e3;default:return 0}}getStorage(){try{const e=this.storage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch{return{}}}setStorage(e){try{this.storage.setItem(this.storageKey,JSON.stringify(e))}catch(e){J("FrequencyCapManager","Could not save to localStorage:",e)}}resetCountersIfNeeded(e){const t=Date.now(),n=new Date(e.sessionStart).getTime(),i=new Date(e.dayStart).getTime(),o=new Date(e.weekStart).getTime();return t-n>18e5&&(e.sessionCount=0,e.sessionStart=new Date(t).toISOString()),new Date(t).toDateString()!==new Date(i).toDateString()&&(e.dayCount=0,e.dayStart=new Date(t).toISOString()),this.getWeekNumber(t)!==this.getWeekNumber(o)&&(e.weekCount=0,e.weekStart=new Date(t).toISOString()),e}getWeekNumber(e){const t=new Date(e);return`${t.getFullYear()}-W${this.getIsoWeek(t)}`}getIsoWeek(e){const t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())),n=t.getUTCDay()||7;t.setUTCDate(t.getUTCDate()+4-n);const i=new Date(Date.UTC(t.getUTCFullYear(),0,1));return Math.ceil(((t.getTime()-i.getTime())/864e5+1)/7)}getWidgetData(e){const t=this.getStorage(),n=Date.now();if(!t[e]){const i={sessionCount:0,dayCount:0,weekCount:0,totalCount:0,sessionStart:new Date(n).toISOString(),dayStart:new Date(n).toISOString(),weekStart:new Date(n).toISOString()};return t[e]=i,this.setStorage(t),i}const i=this.resetCountersIfNeeded(t[e]);return t[e]=i,this.setStorage(t),i}canShow(e,t){if(!t||0===Object.keys(t).length)return{allowed:!0};const n=this.getWidgetData(e);if(void 0!==t.perSession&&n.sessionCount>=t.perSession)return{allowed:!1,reason:"perSession",currentCount:n.sessionCount,limit:t.perSession};if(void 0!==t.perDay&&n.dayCount>=t.perDay)return{allowed:!1,reason:"perDay",currentCount:n.dayCount,limit:t.perDay};if(void 0!==t.perWeek&&n.weekCount>=t.perWeek)return{allowed:!1,reason:"perWeek",currentCount:n.weekCount,limit:t.perWeek};if(void 0!==t.total&&n.totalCount>=t.total)return{allowed:!1,reason:"total",currentCount:n.totalCount,limit:t.total};if(t.minInterval&&n.lastShownAt){const e=new Date(n.lastShownAt).getTime(),i=this.parseInterval(t.minInterval);if(Date.now()-e<i)return{allowed:!1,reason:"minInterval",nextShowAt:new Date(e+i)}}return{allowed:!0}}recordShown(e){const t=this.getStorage(),n=Date.now();let i=t[e];i||(i=this.getWidgetData(e)),i=this.resetCountersIfNeeded(i),i.sessionCount++,i.dayCount++,i.weekCount++,i.totalCount++,i.lastShownAt=new Date(n).toISOString(),t[e]=i,this.setStorage(t)}getDisplayCounts(e){return this.getStorage()[e]||null}reset(e){const t=this.getStorage();delete t[e],this.setStorage(t)}resetAll(){this.storage.removeItem(this.storageKey)}cleanup(){const e=this.getStorage(),t=Date.now()-2592e6;let n=!1;for(const i in e){const o=e[i];o.lastShownAt&&new Date(o.lastShownAt).getTime()<t&&(delete e[i],n=!0)}n&&this.setStorage(e)}}let Bt=null;function Ut(){return Bt||(Bt=new Lt),Bt}function zt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ft(e){if(Array.isArray(e))return e.map(e=>Ft(e));if(zt(e)){const t={};for(const[n,i]of Object.entries(e))t[n]=Ft(i);return t}return e}function qt(e,t){const n=Ft(e||{});if(!zt(t))return n;for(const[e,i]of Object.entries(t)){if(void 0===i)continue;const t=n[e];Array.isArray(i)?n[e]=Ft(i):zt(i)?zt(t)?n[e]=qt(t,i):n[e]=qt({},i):n[e]=i}return n}function jt(e){const t={...e};return void 0===t.title&&void 0!==t.titleText&&(t.title=t.titleText),void 0===t.title&&void 0!==t.headline&&(t.title=t.headline),void 0===t.headline&&void 0!==t.title&&(t.headline=t.title),void 0===t.text&&void 0!==t.description&&(t.text=t.description),void 0===t.text&&void 0!==t.subtext&&(t.text=t.subtext),void 0===t.text&&void 0!==t.subtitle&&(t.text=t.subtitle),void 0===t.description&&void 0!==t.text&&(t.description=t.text),void 0===t.subtext&&void 0!==t.text&&(t.subtext=t.text),void 0===t.subtitle&&void 0!==t.subtext&&(t.subtitle=t.subtext),void 0===t.buttonText&&void 0!==t.ctaText&&(t.buttonText=t.ctaText),void 0===t.buttonUrl&&void 0!==t.ctaUrl&&(t.buttonUrl=t.ctaUrl),t}function Ht(e){return zt(e)&&"string"==typeof e.experimentId&&"string"==typeof e.variantId}function Wt(e){if(!e)return null;const t=e.variantConfig??e.config;if(!zt(t))return null;let n=qt({},t);const i="search_config"===e.targetType?"search":"recommendation"===e.targetType?"recommendation":void 0;if(i&&zt(n[i])){const e=n[i];delete n[i],n=qt(n,e)}return zt(n.content)&&(n.content=jt(n.content)),zt(n.styles)&&(n.styles=function(e){const t={...e};if(void 0===t.textColor&&void 0!==t.color&&(t.textColor=t.color),void 0===t.backgroundColor&&void 0!==t.background&&(t.backgroundColor=t.background),void 0===t.borderRadius&&void 0!==t.radius&&(t.borderRadius=t.radius),void 0===t.border&&(t.borderColor||t.borderWidth)){const e=t.borderWidth||"1px",n=t.borderStyle||"solid",i=t.borderColor||"currentColor";t.border=`${e} ${n} ${i}`}return t}(n.styles)),zt(n.placement)&&(n.placement=function(e){const t={...e};var n;return void 0!==t.insertPosition&&(t.insertPosition="prepend"===(n=t.insertPosition)?"inside-start":"append"===n?"inside-end":n),t}(n.placement)),n}class Gt{constructor(e,t,n){this.assignments={},this.initialized=!1,this.impressionCache=new Set,this.MAX_CACHE_SIZE=1e3,this.excludedTargetsCache=null,this.siteKey=e,this.visitorId=t,this.apiBaseUrl=n,this.loadFromStorage(),this.startCleanupInterval()}async init(){if(!this.initialized)try{const e=encodeURIComponent(this.siteKey),t=await fetch(`${this.apiBaseUrl}/public/experiments/assign?siteKey=${e}&visitorId=${this.visitorId}`);if(t.ok){const e=function(e){const t={},n=e=>{for(const n of e)Ht(n)&&(t[n.experimentId]=n)};return Array.isArray(e)?(n(e),t):zt(e)?Array.isArray(e.assignments)?(n(e.assignments),t):(n(Object.values(e)),t):t}(await t.json());this.assignments=e,this.saveToStorage(),this.initialized=!0,this.excludedTargetsCache=null,W("Selwise","Experiments initialized:",this.assignments)}}catch(e){J("Selwise","Failed to load experiments:",e)}}loadFromStorage(){try{const e=localStorage.getItem(y);if(e){const t=JSON.parse(e);t&&"object"==typeof t&&!Array.isArray(t)?this.assignments=t:(J("Selwise","Invalid experiments data in storage, using empty object"),this.assignments={})}}catch(e){G("Selwise","Failed to load experiments from storage:",e),this.assignments={}}}saveToStorage(){try{localStorage.setItem(y,JSON.stringify(this.assignments))}catch(e){}}getVariant(e){return this.assignments[e]||null}getAssignmentByTargetId(e){return Object.values(this.assignments).find(t=>t.targetId===e)||null}getAssignmentByTargetType(e){return Object.values(this.assignments).find(t=>t.targetType===e)||null}getConfig(e,t,n=null){const i=Wt(this.getVariant(e));return i&&void 0!==i[t]?i[t]:n}shouldRenderTarget(e){return!this.isTargetExcluded(e)}getAllExcludedTargets(){if(this.excludedTargetsCache)return this.excludedTargetsCache;const e=new Map;for(const t of Object.values(this.assignments))if(t.excludedTargetIds&&Array.isArray(t.excludedTargetIds))for(const n of t.excludedTargetIds)e.set(n,t.experimentId);return this.excludedTargetsCache=e,e}isTargetExcluded(e){return this.getAllExcludedTargets().has(e)}getExcludingExperiment(e){return this.getAllExcludedTargets().get(e)||null}getVariantModuleForTarget(e){for(const t of Object.values(this.assignments))if(t.controlTargetId===e){if(t.effectiveTargetId===t.controlTargetId)continue;return t}return null}isVariantModule(e){for(const t of Object.values(this.assignments)){if(t.moduleData){const n=t.moduleData;if((n.data?.id||n.id)===e)return!0}if(t.effectiveTargetId===e)return!0}return!1}getVisitorId(){return this.visitorId}getAssignedVariant(e){const t=this.getVariant(e);return t?.variantId||null}getAllAssignments(){return Object.values(this.assignments)}isDifferentModuleMode(e){const t=this.getVariant(e);return"different_module"===t?.experimentMode}getExperimentMode(e){const t=this.getVariant(e);return t?.experimentMode||null}async trackImpression(e){const t=this.getVariant(e);if(!t)return;const n=`${e}:${t.variantId}`;if(!this.impressionCache.has(n))try{if(await this.sendEvent(e,t.variantId,"impression"),this.impressionCache.add(n),this.impressionCache.size>this.MAX_CACHE_SIZE){const e=this.impressionCache.values().next().value;e&&this.impressionCache.delete(e)}}catch(e){J("Selwise","Failed to track impression:",e)}}async trackConversion(e,t){const n=this.getVariant(e);if(n)try{await this.sendEvent(e,n.variantId,"conversion",t)}catch(e){J("Selwise","Failed to track conversion:",e)}}async trackEvent(e,t){try{const n=encodeURIComponent(this.siteKey);await fetch(`${this.apiBaseUrl}/public/experiments/track-event?siteKey=${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:this.visitorId,eventName:e,data:t})})}catch(e){J("Selwise","Failed to track experiment event:",e)}}async sendEvent(e,t,n,i){const o=encodeURIComponent(this.siteKey);await fetch(`${this.apiBaseUrl}/public/experiments/track?siteKey=${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({experimentId:e,variantId:t,eventType:n,revenue:i})})}destroy(){this.impressionCache.clear(),this.excludedTargetsCache=null,this.assignments={},this.initialized=!1,this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0)}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{if(this.impressionCache.size>.8*this.MAX_CACHE_SIZE){const e=Array.from(this.impressionCache),t=Math.floor(.2*this.MAX_CACHE_SIZE);this.impressionCache=new Set(e.slice(-t)),G("Experiments","Cleaned up impression cache")}},6e5)}}const Kt={showOnAllPages:!0,includeUrls:[],excludeUrls:[]};function Jt(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const i of e){if("string"!=typeof i)continue;const e=i.trim();e&&(t.has(e)||(t.add(e),n.push(e)))}return n}function Vt(e,t){const n=String(e||"").toLowerCase(),i=String(t||"").toLowerCase().trim();if(!i)return!1;if(i.includes("*")){const e=i.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${e}$`).test(n)}return n===i||n.includes(i)}function Yt(e,t){const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{...Kt};const t=e;return{showOnAllPages:Boolean(t.showOnAllPages??Kt.showOnAllPages),includeUrls:Jt(t.includeUrls),excludeUrls:Jt(t.excludeUrls)}}(e),i=String(t||"");if(n.excludeUrls.length>0&&n.excludeUrls.some(e=>Vt(i,e)))return!1;if(!1===n.showOnAllPages){if(0===n.includeUrls.length)return!1;if(!i)return!1;if(!n.includeUrls.some(e=>Vt(i,e)))return!1}return!0}class Qt{constructor(e,t,n,i,o,r){this.segmentCache=new Map,this.segmentCacheTimestamps=new Map,this.apiUrl=e,this.siteKey=t,this.visitorId=n,this.sessionId=i,this.siteUserId=o,this.siteUserProfileId=r}updateUserIdentifiers(e,t){this.siteUserId=e,this.siteUserProfileId=t}async shouldShow(e,t){const n=this.normalizeSegmentIds(t);if(W("SegmentManager","Evaluating segment targeting:",{mode:e,segmentIds:n,visitorId:this.visitorId,sessionId:this.sessionId}),"all"===e||0===n.length)return W("SegmentManager",'Mode is "all" or no segments, showing content'),!0;const i=await this.evaluateSegments(n),o=Object.keys(i).filter(e=>i[e]);if(W("SegmentManager","Evaluation results:",{results:i,matchedSegments:o,mode:e}),"include"===e){const e=o.length>0;return W("SegmentManager","Include mode: "+(e?"SHOW":"HIDE")),e}if("exclude"===e){const e=0===o.length;return W("SegmentManager","Exclude mode: "+(e?"SHOW":"HIDE")),e}return!0}async evaluateSegments(e){const t=Date.now();if(0===e.filter(e=>{if(!this.segmentCache.has(e))return!0;const n=this.segmentCacheTimestamps.get(e);return!n||t-n>3e5}).length){const t={};return e.forEach(e=>{t[e]=this.segmentCache.get(e)||!1}),t}try{const t={segmentIds:this.normalizeSegmentIds(e),visitorId:this.visitorId,siteUserId:this.siteUserId,siteUserProfileId:this.siteUserProfileId,sessionId:this.sessionId,deviceType:this.getDeviceType(),referrer:document.referrer,pageUrl:window.location.href};W("SegmentManager","Calling API to evaluate segments:",{endpoint:`${this.apiUrl}/public/segments/evaluate?siteKey=${this.siteKey}`,payload:t});const n=await fetch(`${this.apiUrl}/public/segments/evaluate?siteKey=${this.siteKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)return K("SegmentManager","API returned error:",n.status,n.statusText),this.getFallbackResults(e);const i=await n.json();W("SegmentManager","API response:",i);const o=Date.now();return Object.keys(i.results).forEach(e=>{this.segmentCache.set(e,i.results[e]),this.segmentCacheTimestamps.set(e,o)}),i.results}catch(t){return K("SegmentManager","Error evaluating segments:",t),this.getFallbackResults(e)}}getDeviceType(){const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e)?"mobile":"desktop"}getFallbackResults(e){const t={};return e.forEach(e=>{t[e]=!1}),t}normalizeSegmentIds(e){return Array.isArray(e)?Array.from(new Set(e.filter(e=>"string"==typeof e).map(e=>e.trim()).filter(e=>e.length>0))).sort():[]}clearCache(){this.segmentCache.clear(),this.segmentCacheTimestamps.clear()}}const Xt=[];function Zt(e){return!(!e||"string"!=typeof e)&&Xt.includes(e)}let en=!1,tn=null;function nn(e){if("console"===e.category)return!1;if("ui"===e.category&&"click"===e.type){const t=e.message||"";if(!t.includes("selwise-")&&!t.includes("data-selwise-"))return!1}if("xhr"===e.category||"fetch"===e.category){const t=e.data?.url||"";try{const e=new URL(t,window.location.href),n=document.currentScript,i=n?.getAttribute("data-api-url");let o="";if(i)try{o=new URL(i).origin}catch{}const r=e.pathname.startsWith("/api/v1/public/sites/");if(!(o&&e.origin===o||r))return!1;if(e.origin===window.location.origin&&!r)return!1}catch{return!1}}return!0}function on(e){if(e.request?.headers&&delete e.request.headers,e.request?.cookies){const t={},n="selwise_";for(const[i,o]of Object.entries(e.request.cookies))i.startsWith(n)&&(t[i]=o);e.request.cookies=t}if(e.request?.query_string)try{const t=new URLSearchParams(e.request.query_string),n={},i=["utm_source","utm_medium","utm_campaign"];for(const e of i)t.has(e)&&(n[e]=t.get(e)||"");e.request.query_string=new URLSearchParams(n).toString()}catch{delete e.request.query_string}if(e.contexts?.localStorage&&delete e.contexts.localStorage,e.contexts?.sessionStorage&&delete e.contexts.sessionStorage,e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(nn)),e.exception?.values)for(const t of e.exception.values)t.stacktrace?.frames&&(t.stacktrace.frames=rn(t.stacktrace.frames));return e.stacktrace?.frames&&(e.stacktrace.frames=rn(e.stacktrace.frames)),e.tags=e.tags||{},e.tags.widgetVersion="client",e.level||(e.level="error"),e}function rn(e){return Array.isArray(e)?e.filter(e=>{const t=e.filename||"",n=e.abs_path||"";if(!t||"<anonymous>"===t||"[native code]"===t)return!0;const i=t.includes("selwise")||t.includes("Selwise")||n.includes("selwise")||n.includes("Selwise"),o=t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("safari-extension://")||t.startsWith("edge-extension://")||t.startsWith("node:");return i||o}):[]}var an,sn,ln,cn,dn,un;!function(e){e.HOME="home",e.PRODUCT="product",e.CATEGORY="category",e.SEARCH="search",e.CHECKOUT="checkout",e.CART="cart",e.ACCOUNT="account",e.OTHER="other"}(an||(an={})),function(e){e[e.BASKET=1]="BASKET",e[e.CUSTOMER=2]="CUSTOMER",e[e.PAYMENT=3]="PAYMENT",e[e.PURCHASE=4]="PURCHASE"}(sn||(sn={})),function(e){e.SIGNUP="signup",e.SIGNIN="signin",e.SIGNOUT="signout",e.UPDATE="update"}(ln||(ln={})),function(e){e.ADD="add",e.REMOVE="remove",e.UPDATE="update"}(cn||(cn={})),function(e){e.KEYWORD="keyword",e.FILTER="filter",e.PAGE="page",e.ORDER="order"}(dn||(dn={})),function(e){e.NECESSARY="necessary",e.ANALYTICS="analytics",e.MARKETING="marketing",e.PREFERENCES="preferences"}(un||(un={})),un.NECESSARY;const pn="selwise_dl_state",hn="selwise_dl_cart",gn="selwise_dl_cart_time",mn="selwise_dl_last_page",fn="selwise_dl_page_views",yn="selwise_dl_session_start",bn={HOME:an.HOME,PRODUCT:an.PRODUCT,CATEGORY:an.CATEGORY,SEARCH:an.SEARCH,CHECKOUT:an.CHECKOUT,CART:an.CART,ACCOUNT:an.ACCOUNT,OTHER:an.OTHER},wn={home:new RegExp(Nt.DEFAULT_PAGE_TYPE_PATTERNS.home,"i"),product:new RegExp(Nt.DEFAULT_PAGE_TYPE_PATTERNS.product,"i"),category:new RegExp(Nt.DEFAULT_PAGE_TYPE_PATTERNS.category,"i"),search:new RegExp(Nt.DEFAULT_PAGE_TYPE_PATTERNS.search,"i"),checkout:new RegExp(Nt.DEFAULT_PAGE_TYPE_PATTERNS.checkout,"i"),cart:new RegExp(Nt.DEFAULT_PAGE_TYPE_PATTERNS.cart,"i"),account:new RegExp(Nt.DEFAULT_PAGE_TYPE_PATTERNS.account,"i")},Sn="datalayer",xn=['body[class*="product"]','body[class*="item"]','[itemtype*="Product"]','[itemscope][itemtype*="Product"]',".product-single",".product-type-simple",".product-type-variable",".product-info-main","[data-product-id]"];class vn{constructor(e){this.lastTrackedUrl="",this.titleObserver=null,this.config=e,this.setupTitleObserver()}setupTitleObserver(){const e=document.querySelector("title");e&&(this.titleObserver=new MutationObserver(()=>{this.maybeTrackPageView()}),this.titleObserver.observe(e,{subtree:!0,characterData:!0,childList:!0}))}maybeTrackPageView(){window.location.href!==this.lastTrackedUrl&&this.trackPageView()}detectPageType(){const e=window.location.pathname+window.location.search,t=this.config.config.pageTypePatterns||wn;for(const[n,i]of Object.entries(t))if(("string"==typeof i?new RegExp(i):i).test(e))return n;return this.detectPageTypeFromDom()||bn.OTHER}detectPageTypeFromDom(){const e=document.body.className.toLowerCase();return e.includes("product")||e.includes("item")?bn.PRODUCT:e.includes("category")||e.includes("collection")||e.includes("catalog")?bn.CATEGORY:e.includes("checkout")?bn.CHECKOUT:e.includes("cart")||e.includes("basket")?bn.CART:e.includes("account")||e.includes("profile")||e.includes("my-account")?bn.ACCOUNT:document.querySelector('[itemtype*="Product"]')?bn.PRODUCT:null}getPageMetadata(e){const t={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now()};if(t.pageType=e,t.pageTitle=document.title,t.pagePath=window.location.pathname,t.pageSearch=window.location.search,t.pageHash=window.location.hash,t.language=document.documentElement.lang||navigator.language||"en",e===bn.PRODUCT){const e=this.extractProductInfoFromDom();e&&(t.productInfo=e)}if(e===bn.CATEGORY){const e=this.extractCategoryInfoFromDom();e&&(t.categoryInfo=e)}return t}extractProductInfoFromDom(){const e=document.querySelector('script[type="application/ld+json"]');if(e)try{const t=JSON.parse(e.textContent||"{}");if("Product"===t["@type"])return{productItemCode:t.productID||t.sku||void 0,name:t.name,price:t.offers?.price||void 0,currency:t.offers?.priceCurrency||void 0,availability:t.offers?.availability||void 0}}catch{}const t=this.getMetaContent("product:product_id")||this.getMetaContent("product:id")||this.getMetaContent("product:upc"),n=this.getMetaContent("og:title")||this.getMetaContent("product:name")||this.getMetaContent("twitter:title"),i=this.getMetaContent("product:price:amount")||this.getMetaContent("product:price")||this.getMetaContent("og:price:amount"),o=this.getMetaContent("product:price:currency")||this.getMetaContent("og:price:currency");return n||t?{productItemCode:t,name:n,price:i,currency:o}:null}extractCategoryInfoFromDom(){const e=this.getMetaContent("category")||this.getMetaContent("product:category")||this.getMetaContent("og:type"),t=document.querySelector('[itemtype*="BreadcrumbList"]');if(t){const n=t.querySelectorAll('[itemprop="itemListElement"]'),i=[];if(n.forEach(e=>{const t=e.querySelector('[itemprop="name"]')?.textContent;t&&i.push(t)}),i.length>0)return{category:e,categories:i}}return e?{category:e,categories:[e]}:null}getMetaContent(e){let t=document.querySelector(`meta[name="${e}"]`);return t?t.getAttribute("content")||void 0:(t=document.querySelector(`meta[property="${e}"]`),t&&t.getAttribute("content")||void 0)}trackPageView(e){const t=window.location.href;if(t===this.lastTrackedUrl&&!e)return;this.lastTrackedUrl=t;const n=this.detectPageType(),i=e?.page?.type||n,o=this.getPageMetadata(i);e?.page&&Object.assign(o,{pageTitle:e.page.title||o.pageTitle,pageType:e.page.type||o.pageType,categories:e.page.categories,tags:e.page.tags,params:e.page.params}),this.config.tracker.track("page_view",{entityType:"page",entityId:i,metadata:o}),this.log("Tracked page_view:",i,o),this.storeLastPageType(i)}storeLastPageType(e){try{sessionStorage.setItem(mn,e)}catch{}}getLastPageType(){try{return sessionStorage.getItem(mn)||null}catch{return null}}processDataLayer(e){"virtual_page_view"===e.event?this.trackVirtualPageView(e):this.trackPageView(e)}trackVirtualPageView(e){const t=e.page?.type||this.detectPageType(),n={dataSource:Sn,pageUrl:e.page?.url||window.location.href,referrer:e.page?.referrer||document.referrer,timestamp:Date.now(),pageTitle:e.page?.title||document.title,pagePath:e.page?.path||window.location.pathname,pageType:t,virtual:!0,categories:e.page?.categories,tags:e.page?.tags,params:e.page?.params};this.config.tracker.track("virtual_page_view",{entityType:"page",entityId:t,metadata:n}),this.log("Tracked virtual_page_view:",t,n)}incrementPageViewCount(){try{const e=parseInt(sessionStorage.getItem(fn)||"0",10)+1;return sessionStorage.setItem(fn,e.toString()),e}catch{return 1}}getPageViewCount(){try{return parseInt(sessionStorage.getItem(fn)||"0",10)}catch{return 0}}log(...e){W("PageTracker",...e)}destroy(){this.titleObserver&&(this.titleObserver.disconnect(),this.titleObserver=null)}}class Cn{constructor(e){this.lastTrackedProduct="",this.impressionObserver=null,this.trackedProducts=new Set,this.dwellTimeStartTime=null,this.dwellTimeAccumulated=0,this.visibilityHandler=this.handleVisibilityChange.bind(this),this.beforeUnloadHandler=this.handleBeforeUnload.bind(this),this.pageHideHandler=this.handlePageHide.bind(this),this.config=e}isProductPage(){const e=this.config.config.pageTypePatterns;if(e?.product){const t=window.location.pathname+window.location.search;if(e.product.test(t))return!0}for(const e of xn)try{if(document.querySelector(e))return!0}catch{}return!1}extractProductFromDom(){const e=this.extractFromSchema();if(e)return e;const t=this.extractFromMetaTags();if(t)return t;return this.extractFromDataAttributes()||null}extractFromSchema(){const e=document.querySelectorAll('script[type="application/ld+json"]');for(const t of e)try{const e=JSON.parse(t.textContent||"{}");if("Product"===e["@type"])return this.parseSchemaProduct(e);if(e["@graph"]){const t=e["@graph"].find(e=>"Product"===e["@type"]);if(t)return this.parseSchemaProduct(t)}}catch{}return null}parseSchemaProduct(e){const t=e.sku||e.productID||e.mpn;if(!t)return null;let n;if(e.offers){const t=Array.isArray(e.offers)?e.offers[0]:e.offers;n=t.price?parseFloat(t.price):void 0}return{productItemCode:t,name:e.name,price:n,category:e.category||e.keywords?.[0]}}extractFromMetaTags(){const e=e=>{const t=document.querySelector(`meta[property="${e}"], meta[name="${e}"]`);return t?.getAttribute("content")},t=e("product:sku")||e("product:retailer_item_id")||e("product:product_id")||e("product:id")||e("product:upc")||e("product:ean")||e("product:isbn");if(!t)return null;const n=e("product:price:amount")||e("product:price"),i=n?parseFloat(n):void 0;return{productItemCode:t,name:e("og:title")||e("product:name")||void 0,price:i,category:e("product:category")||void 0}}extractFromDataAttributes(){const e=document.querySelector("[data-product-sku], [data-product-id], [data-product], [data-item-id]");if(!e)return null;const t=e.getAttribute("data-product-sku")||e.getAttribute("data-item-id")||e.getAttribute("data-product-id");return t?{productItemCode:t,name:e.getAttribute("data-product-name")||void 0,price:e.getAttribute("data-product-price")?parseFloat(e.getAttribute("data-product-price")):void 0,category:e.getAttribute("data-product-category")||void 0}:null}trackProductView(e){let t=e;if(!t&&this.isProductPage()){const e=this.extractProductFromDom();e&&(t={sku:e.productItemCode,title:e.title,price:e.price,category:e.category})}const n=t?.sku;if(!t||!n)return void this.log("No product data available for tracking");if(this.lastTrackedProduct===n)return void this.log("Product already tracked:",n);this.lastTrackedProduct=n;const i={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),productItemCode:n,productName:t.title,productPrice:t.price,productCategory:t.category,productSubCategory:t.subCategory,productVariant:t.variant,productBrand:t.brand,productQuantity:t.quantity||1,productInStock:t.inStock};this.config.tracker.track("product_view",{entityType:"product",entityId:n,metadata:i}),this.log("Tracked product_view:",n,i),this.startDwellTimeTracking()}trackProductClick(e){const t=e?.sku;if(!e||!t)return void this.log("No product data for click tracking");const n={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),productItemCode:t,productName:e.title,productPrice:e.price,productCategory:e.category,productPosition:e.position,productList:e.list};this.config.tracker.track("product_click",{entityType:"product",entityId:t,metadata:n}),this.log("Tracked product_click:",t,n)}trackProductImpressions(e){for(const t of e){const e=t.sku;if(!e)continue;const n=`impression_${e}`;if(this.trackedProducts.has(n))continue;const i={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),productItemCode:e,productName:t.title,productPrice:t.price,productPosition:t.position};this.config.tracker.track("product_impression",{entityType:"product",entityId:e,metadata:i}),this.trackedProducts.add(n)}this.log("Tracked",e.length,"product impressions")}setupImpressionTracking(e="[data-product-sku], [data-product-id], [data-track-product]"){this.impressionObserver&&this.impressionObserver.disconnect(),this.impressionObserver=new IntersectionObserver(e=>{for(const t of e)if(t.isIntersecting&&t.intersectionRatio>=.5){const e=t.target,n=e.getAttribute("data-product-sku")||e.getAttribute("data-track-product")||e.getAttribute("data-product-id");if(n&&!this.trackedProducts.has(`impression_${n}`)){const t=e.getAttribute("data-product-name")||void 0,i=e.getAttribute("data-product-price")?parseFloat(e.getAttribute("data-product-price")):void 0;e.getAttribute("data-product-position")&&parseInt(e.getAttribute("data-product-position"),10),this.trackProductClick({sku:n,title:t,price:i}),this.trackedProducts.add(`impression_${n}`)}}},{threshold:.5}),document.querySelectorAll(e).forEach(e=>{this.impressionObserver?.observe(e)}),this.log("Setup impression tracking for selector:",e)}startDwellTimeTracking(){this.dwellTimeStartTime=Date.now(),this.dwellTimeAccumulated=0,document.addEventListener("visibilitychange",this.visibilityHandler),window.addEventListener("beforeunload",this.beforeUnloadHandler),window.addEventListener("pagehide",this.pageHideHandler),W("ProductTracker","Started dwell time tracking for product:",this.lastTrackedProduct),this.log("Started dwell time tracking")}handleVisibilityChange(){document.hidden?(this.dwellTimeStartTime&&(this.dwellTimeAccumulated+=Date.now()-this.dwellTimeStartTime,this.dwellTimeStartTime=null),this.log("Dwell time paused (page hidden)")):(this.dwellTimeStartTime||(this.dwellTimeStartTime=Date.now()),this.log("Dwell time resumed (page visible)"))}handleBeforeUnload(){const e=this.getTotalDwellTime(),t=Math.round(e/1e3);if(this.log("handleBeforeUnload called:",{totalDwellTime:e,totalSeconds:t,lastProduct:this.lastTrackedProduct}),t>0&&this.lastTrackedProduct){const e={sessionId:this.config.tracker.getSessionId(),visitorId:this.config.tracker.getVisitorId(),pageUrl:window.location.href,events:[{name:"product_dwell_time",entityType:"product",entityId:this.lastTrackedProduct,productItemCode:this.lastTrackedProduct,metadata:{dwellTimeSeconds:t,dataSource:Sn}}]},n=`${this.config.apiUrl}/public/sites/${this.config.siteKey}/events/batch`;this.log("Sending dwell time via sendBeacon:",n,e);const i=new Blob([JSON.stringify(e)],{type:"application/json"}),o=navigator.sendBeacon(n,i);this.log("sendBeacon result:",o)}}handlePageHide(){this.handleBeforeUnload()}getTotalDwellTime(){let e=this.dwellTimeAccumulated;return this.dwellTimeStartTime&&(e+=Date.now()-this.dwellTimeStartTime),e}stopDwellTimeTracking(){document.removeEventListener("visibilitychange",this.visibilityHandler),window.removeEventListener("beforeunload",this.beforeUnloadHandler),window.removeEventListener("pagehide",this.pageHideHandler);const e=this.getTotalDwellTime(),t=Math.round(e/1e3);if(W("ProductTracker","stopDwellTimeTracking called:",{totalMs:e,totalSeconds:t,lastProduct:this.lastTrackedProduct,apiUrl:this.config.apiUrl,siteKey:this.config.siteKey}),this.log("stopDwellTimeTracking called:",{totalMs:e,totalSeconds:t,lastProduct:this.lastTrackedProduct}),this.lastTrackedProduct){const e={sessionId:this.config.tracker.getSessionId(),visitorId:this.config.tracker.getVisitorId(),pageUrl:window.location.href,events:[{name:"product_dwell_time",entityType:"product",entityId:this.lastTrackedProduct,productItemCode:this.lastTrackedProduct,metadata:{dwellTimeSeconds:t,dataSource:Sn}}]},n=`${this.config.apiUrl}/public/sites/${this.config.siteKey}/events/batch`;W("ProductTracker","Sending dwell time to:",n),W("ProductTracker","Payload:",e),fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}).then(e=>e.json()).then(e=>W("ProductTracker","Dwell time sent successfully:",e)).catch(e=>K("ProductTracker","Failed to send dwell time event:",e)),this.log("Tracked product_dwell_time via fetch:",this.lastTrackedProduct,`${t}s`)}this.dwellTimeStartTime=null,this.dwellTimeAccumulated=0}processDataLayer(e){const t=e.product?.sku;if(e.product&&t)switch(e.event){case"product_view":default:this.trackProductView(e.product);break;case"product_click":this.trackProductClick(e.product);break;case"product_impression":Array.isArray(e.products)?this.trackProductImpressions(e.products):this.trackProductClick(e.product)}else this.log("No product data in event:",e.event)}clearTrackedProducts(){this.trackedProducts.clear(),this.lastTrackedProduct=""}log(...e){W("ProductTracker",...e)}destroy(){this.stopDwellTimeTracking(),this.impressionObserver&&(this.impressionObserver.disconnect(),this.impressionObserver=null),this.trackedProducts.clear()}}class kn{constructor(e){this.currentCart=null,this.checkInterval=null,this.lastTrackedCartId="",this.config=e}storeCartSnapshot(e){try{sessionStorage.setItem(hn,JSON.stringify(e)),sessionStorage.setItem(gn,Date.now().toString())}catch(e){this.log("Failed to store cart snapshot:",e)}}getStoredCartSnapshot(){try{const e=sessionStorage.getItem(hn),t=sessionStorage.getItem(gn);if(!e||!t)return null;const n=JSON.parse(e);return n.timestamp=parseInt(t,10),n}catch(e){return this.log("Failed to retrieve cart snapshot:",e),null}}clearCartSnapshot(){try{sessionStorage.removeItem(hn),sessionStorage.removeItem(gn)}catch{}}checkCartAbandonment(){const e=this.getStoredCartSnapshot();if(!e)return;const t=Date.now(),n=60*this.config.config.cartAbandonmentTimeout*1e3,i=t-e.timestamp;i>n&&e.products.length>0?(this.log("Detected abandoned cart:",e),this.trackCartAbandon(e,i),this.clearCartSnapshot()):this.log("Stored cart is not abandoned yet, age:",Math.round(i/1e3),"seconds")}startCartMonitoring(){this.checkInterval||(this.checkInterval=window.setInterval(()=>{this.checkCartAbandonment()},6e4),this.log("Started cart abandonment monitoring"))}stopCartMonitoring(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this.log("Stopped cart abandonment monitoring"))}trackCartAbandon(e,t){const n=this.getBasketProductItemCodes(e.products),i={dataSource:Sn,pageUrl:e.url,referrer:document.referrer,timestamp:Date.now(),cartAge:t,cartValue:e.total,cartCurrency:e.currency,productCount:e.products.length,productItemCodes:n,products:e.products.map(e=>({productItemCode:this.resolveProductItemCode(e),quantity:e.quantity,price:e.price,totalPrice:e.totalPrice,title:e.title,category:e.category}))};this.config.tracker.track("cart_abandon",{entityType:"basket",entityId:e.url,metadata:i}),this.log("Tracked cart_abandon:",i)}trackAddToCart(e){if(!e||!e.products||0===e.products.length)return void this.log("No basket products for add_to_cart tracking");const t=e.products[0],n=this.resolveProductItemCode(t);if(!n)return void this.log("Missing productItemCode for add_to_cart event");const i=e.id||this.generateCartId(),o=this.getBasketProductItemCodes(e.products);this.updateCartState(e,i);const r={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),cartId:i,productItemCode:n,productName:t.title,productCategory:t.category,productPrice:t.price,quantity:t.quantity,totalPrice:e.total,currency:e.currency,productItemCodes:o};this.config.tracker.track("add_to_cart",{entityType:"basket",entityId:n,metadata:r}),this.log("Tracked add_to_cart:",n,r),this.storeCartSnapshot(this.currentCart)}trackRemoveFromCart(e){if(!e||!e.products||0===e.products.length)return void this.log("No basket products for remove_from_cart tracking");const t=e.products[0],n=this.resolveProductItemCode(t);if(!n)return void this.log("Missing productItemCode for remove_from_cart event");const i=e.id||this.lastTrackedCartId,o=this.getBasketProductItemCodes(e.products),r={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),cartId:i,productItemCode:n,productName:t.title,quantity:t.quantity,totalPrice:e.total,currency:e.currency,productItemCodes:o};this.config.tracker.track("remove_from_cart",{entityType:"basket",entityId:n,metadata:r}),this.log("Tracked remove_from_cart:",n,r),this.updateCartState(e,i)}trackCartUpdate(e){if(!e)return;const t=e.id||this.generateCartId(),n=this.getBasketProductItemCodes(e.products),i={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),cartId:t,productCount:e.products?.length||0,totalPrice:e.total,currency:e.currency,productItemCodes:n};this.config.tracker.track("update_cart",{entityType:"basket",entityId:t,metadata:i}),this.log("Tracked update_cart:",t,i),this.updateCartState(e,t)}trackCartRestore(e){const t=this.getStoredCartSnapshot();if(!t&&!e)return;const n=e?{products:e.products||[],total:e.total||0,currency:e.currency||"USD",timestamp:Date.now(),url:window.location.href}:t,i=this.getBasketProductItemCodes(n.products),o={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),cartValue:n.total,currency:n.currency,productCount:n.products.length,productItemCodes:i,products:n.products.map(e=>({productItemCode:this.resolveProductItemCode(e),quantity:e.quantity,price:e.price,totalPrice:e.totalPrice,title:e.title,category:e.category,variant:e.variant,image:e.image,url:e.url}))};this.config.tracker.track("cart_restore",{entityType:"basket",entityId:n.url,metadata:o}),this.log("Tracked cart_restore:",o),this.clearCartSnapshot()}updateCartState(e,t){e&&(this.currentCart={products:e.products||[],total:e.total||0,currency:e.currency||"USD",timestamp:Date.now(),url:window.location.href},this.lastTrackedCartId=t)}generateCartId(){return`cart_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}resolveProductItemCode(e){if(!e)return null;const t=e.sku;if(!t)return null;const n=t.trim();return n.length>0?n:null}getBasketProductItemCodes(e){if(!e||0===e.length)return[];const t=new Set,n=[];for(const i of e){const e=this.resolveProductItemCode(i);e&&!t.has(e)&&(t.add(e),n.push(e))}return n}processDataLayer(e){if(e.basket)switch(e.event){case"add_to_cart":default:this.trackAddToCart(e.basket);break;case"remove_from_cart":this.trackRemoveFromCart(e.basket);break;case"update_cart":this.trackCartUpdate(e.basket);break;case"cart_abandon":if(this.currentCart){const e=Date.now()-this.currentCart.timestamp;this.trackCartAbandon(this.currentCart,e)}break;case"cart_restore":this.trackCartRestore(e.basket)}else this.log("No basket data in event:",e.event)}getCurrentCart(){return this.currentCart}log(...e){W("BasketTracker",...e)}destroy(){this.stopCartMonitoring()}}class Tn{constructor(e){this.checkoutState=null,this.checkoutStorageKey=`${pn}_checkout`,this.config=e,this.loadCheckoutState()}loadCheckoutState(){try{const e=sessionStorage.getItem(this.checkoutStorageKey);e&&(this.checkoutState=JSON.parse(e),this.log("Loaded checkout state:",this.checkoutState))}catch(e){this.log("Failed to load checkout state:",e)}}saveCheckoutState(){if(this.checkoutState)try{sessionStorage.setItem(this.checkoutStorageKey,JSON.stringify(this.checkoutState))}catch(e){this.log("Failed to save checkout state:",e)}}clearCheckoutState(){this.checkoutState=null;try{sessionStorage.removeItem(this.checkoutStorageKey)}catch{}}trackCheckoutBegin(e){if(!e)return;const t=e.products||[],n=this.getProductItemCodes(t),i=e.totalPrice,o=e.currency;this.checkoutState={step:1,beganAt:Date.now(),totalPrice:i,currency:o,productCount:t.length,products:t},this.saveCheckoutState();const r={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),checkoutStep:1,totalPrice:i,currency:o,productCount:t.length,productItemCodes:n,products:t.map(e=>({productItemCode:this.resolveProductItemCode(e),quantity:e.quantity,price:e.price,name:e.title,category:e.category}))};this.config.tracker.track("checkout_begin",{entityType:"checkout",entityId:"step_1",metadata:r}),this.log("Tracked checkout_begin:",r)}trackCheckoutProgress(e){if(!e||!e.step)return void this.log("No checkout step in progress event");const t=e.step,n=e.option,i=e.products||this.checkoutState?.products||[],o=this.getProductItemCodes(i),r=e.totalPrice??this.checkoutState?.totalPrice,a=e.currency??this.checkoutState?.currency;this.checkoutState&&(this.checkoutState.step=t,r&&(this.checkoutState.totalPrice=r),a&&(this.checkoutState.currency=a),i.length>0&&(this.checkoutState.products=i),this.saveCheckoutState());const s=this.checkoutState?Date.now()-this.checkoutState.beganAt:0,l={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),checkoutStep:t,checkoutOption:n,totalPrice:r,currency:a,productCount:i.length,productItemCodes:o,timeInCheckout:s,stepName:this.getStepName(t)};this.config.tracker.track("checkout_progress",{entityType:"checkout",entityId:`step_${t}`,metadata:l}),this.log("Tracked checkout_progress:",t,l)}trackCheckoutOption(e){if(!e||!e.option)return void this.log("No checkout option in event");const t=e.option,n=e.step||this.checkoutState?.step||2,i={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),checkoutStep:n,checkoutOption:t,optionType:this.getOptionType(t)};this.config.tracker.track("checkout_option",{entityType:"checkout",entityId:`step_${n}`,metadata:i}),this.log("Tracked checkout_option:",t,i)}trackPurchase(e){if(!e||!e.id)return void this.log("No order data for purchase tracking");const t=e.products||[],n=this.getProductItemCodes(t),i=this.checkoutState?Date.now()-this.checkoutState.beganAt:0,o={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),orderId:e.id,total:e.total,subtotal:e.subtotal,discountTotal:e.discountTotal,shippingTotal:e.shippingTotal,taxTotal:e.taxTotal,currency:e.currency,status:e.status,placedAt:e.placedAt,coupon:e.coupon,productCount:t.length,productItemCode:n[0],productItemCodes:n,timeInCheckout:i,products:t.map(e=>({productItemCode:this.resolveProductItemCode(e),quantity:e.quantity,price:e.price,totalPrice:e.totalPrice,name:e.title,category:e.category}))};this.config.tracker.track("purchase",{entityType:"checkout",entityId:e.id,metadata:o}),this.log("Tracked purchase:",e.id,o),this.clearCheckoutState();try{sessionStorage.removeItem(hn),sessionStorage.removeItem(gn)}catch{}}getStepName(e){return{1:"basket",2:"customer",3:"payment",4:"purchase"}[e]||`step_${e}`}getOptionType(e){const t=e.toLowerCase();return t.includes("credit")||t.includes("card")?"credit_card":t.includes("paypal")?"paypal":t.includes("apple")&&t.includes("pay")?"apple_pay":t.includes("google")&&t.includes("pay")?"google_pay":t.includes("bank")||t.includes("transfer")?"bank_transfer":t.includes("cod")||t.includes("cash")?"cash_on_delivery":t.includes("shipping")?"shipping_method":t.includes("pickup")?"store_pickup":"other"}resolveProductItemCode(e){if(!e)return null;const t=e.sku;if(!t)return null;const n=t.trim();return n.length>0?n:null}getProductItemCodes(e){if(!e||0===e.length)return[];const t=new Set,n=[];for(const i of e){const e=this.resolveProductItemCode(i);e&&!t.has(e)&&(t.add(e),n.push(e))}return n}detectCheckoutStep(){const e=window.location.href.toLowerCase(),t=window.location.pathname.toLowerCase();return t.includes("thank")||t.includes("confirm")||t.includes("success")||t.includes("complete")?4:t.includes("payment")||t.includes("billing")||e.includes("step=3")?3:t.includes("shipping")||t.includes("customer")||t.includes("address")||e.includes("step=2")?2:t.includes("cart")||t.includes("basket")||e.includes("step=1")?1:null}autoTrackCheckoutStep(){const e=this.detectCheckoutStep();null!==e&&e>=1&&e<=3&&(1!==e||this.checkoutState?this.trackCheckoutProgress({step:e}):this.trackCheckoutBegin({step:e}))}processDataLayer(e){switch(e.event){case"checkout_begin":this.trackCheckoutBegin(e.checkout);break;case"checkout_progress":this.trackCheckoutProgress(e.checkout);break;case"checkout_option":this.trackCheckoutOption(e.checkout);break;case"purchase":this.trackPurchase(e.order);break;default:this.log("Unknown checkout event:",e.event)}}getCheckoutState(){return this.checkoutState}log(...e){W("CheckoutTracker",...e)}destroy(){this.clearCheckoutState()}}class In{constructor(e){this.userState=null,this.userStorageKey=`${pn}_user`,this.config=e,this.sessionStartTime=Date.now(),this.loadUserState(),this.initSessionStart()}initSessionStart(){try{const e=sessionStorage.getItem(yn);e?this.sessionStartTime=parseInt(e,10):sessionStorage.setItem(yn,Date.now().toString())}catch{}}loadUserState(){try{const e=sessionStorage.getItem(this.userStorageKey);if(e){const t=JSON.parse(e);Date.now()-t.lastUpdate<18e5?(this.userState=t,this.log("Loaded user state:",this.userState)):sessionStorage.removeItem(this.userStorageKey)}}catch(e){this.log("Failed to load user state:",e)}}saveUserState(){if(this.userState)try{this.userState.lastUpdate=Date.now(),sessionStorage.setItem(this.userStorageKey,JSON.stringify(this.userState))}catch(e){this.log("Failed to save user state:",e)}}clearUserState(){this.userState=null;try{sessionStorage.removeItem(this.userStorageKey)}catch{}}async hashEmail(e){const t=e.toLowerCase().trim();if(window.crypto&&window.crypto.subtle)try{const e=(new TextEncoder).encode(t),n=await window.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return btoa(t)}async trackUserSignup(e){if(!e)return;const t=e.id,n=e.email,i=n?await this.hashEmail(n):void 0;this.userState={userId:t,email:i,loggedIn:!0,newCustomer:e.newCustomer??!0,customerSince:e.customerSince||(new Date).toISOString(),lastUpdate:Date.now()},this.saveUserState(),t&&this.config.tracker.identify(t,{email:i,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName,newCustomer:!0});const o={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),userId:t,email:i,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName,gender:e.gender,age:e.age,birthday:e.birthday,newCustomer:!0,method:e.method};this.config.tracker.track("user_signup",{entityType:"user",entityId:t||"unknown",metadata:o}),this.log("Tracked user_signup:",t,o)}async trackUserLogin(e){if(!e)return;const t=e.id,n=e.email,i=n?await this.hashEmail(n):void 0;this.userState={userId:t,email:i,loggedIn:!0,newCustomer:e.newCustomer??!1,customerSince:e.customerSince,lastUpdate:Date.now()},this.saveUserState(),t&&this.config.tracker.identify(t,{email:i,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName,newCustomer:e.newCustomer});const o={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),userId:t,email:i,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName,gender:e.gender,loggedIn:!0,method:e.method};this.config.tracker.track("user_login",{entityType:"user",entityId:t||"unknown",metadata:o}),this.log("Tracked user_login:",t,o)}trackUserLogout(e){const t=e?.id||this.userState?.userId,n={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),userId:t,sessionDuration:Date.now()-this.sessionStartTime};this.config.tracker.track("user_logout",{entityType:"user",entityId:t||"unknown",metadata:n}),this.log("Tracked user_logout:",t,n),this.clearUserState(),this.sessionStartTime=Date.now();try{sessionStorage.setItem(yn,Date.now().toString())}catch{}}async trackUserUpdate(e){if(!e)return;const t=e.id||this.userState?.userId,n=e.email,i=n?await this.hashEmail(n):void 0;this.userState&&(t&&(this.userState.userId=t),i&&(this.userState.email=i),this.userState.lastUpdate=Date.now(),this.saveUserState());const o={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),userId:t,email:i,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName,gender:e.gender,age:e.age,birthday:e.birthday,updateFields:e.updateFields};this.config.tracker.track("user_update",{entityType:"user",entityId:t||"unknown",metadata:o}),this.log("Tracked user_update:",t,o),t&&this.config.tracker.identify(t,{email:i,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName})}async trackUserData(e){e&&!0===e.loggedIn&&("signup"===e.step?await this.trackUserSignup(e):this.userState?.userId&&this.userState.userId===e.id?await this.trackUserUpdate(e):await this.trackUserLogin(e))}getUserState(){return this.userState}isLoggedIn(){return this.userState?.loggedIn??!1}getUserId(){return this.userState?.userId}getSessionDuration(){return Date.now()-this.sessionStartTime}async processDataLayer(e){if(e.user)switch(e.event){case"user_signup":await this.trackUserSignup(e.user);break;case"user_login":await this.trackUserLogin(e.user);break;case"user_logout":this.trackUserLogout(e.user);break;case"user_update":await this.trackUserUpdate(e.user);break;default:await this.trackUserData(e.user)}else this.log("No user data in event:",e.event)}log(...e){W("UserTracker",...e)}destroy(){}}class En{constructor(e){this.searchState={},this.searchStorageKey="selwise_dl_search_state",this.config=e,this.loadSearchState()}loadSearchState(){try{const e=sessionStorage.getItem(this.searchStorageKey);e&&(this.searchState=JSON.parse(e),this.log("Loaded search state:",this.searchState))}catch(e){this.log("Failed to load search state:",e)}}saveSearchState(){try{sessionStorage.setItem(this.searchStorageKey,JSON.stringify(this.searchState))}catch(e){this.log("Failed to save search state:",e)}}clearSearchState(){this.searchState={};try{sessionStorage.removeItem(this.searchStorageKey)}catch{}}trackSearchOpen(e){const t=Date.now();this.searchState={openedAt:t,lastQueryTime:t},this.saveSearchState();const n={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:t,instant:!0,searchType:"instant",category:e?.category};this.config.tracker.track("search_instant_open",{entityType:"search",entityId:"instant",metadata:n}),this.log("Tracked search_instant_open:",n)}trackSearchQuery(e){if(!e)return;const t=e.query,n=Date.now();this.searchState={...this.searchState,query:t,results:e.results,category:e.category,sortBy:e.sortBy,sortOrder:e.sortOrder,page:e.page||1,perPage:e.perPage,lastQueryTime:n},this.saveSearchState();const i={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:n,query:t,queryLength:t?.length||0,results:e.results,category:e.category,instant:e.instant||!1,searchType:e.instant?"instant":"keyword",sortBy:e.sortBy,sortOrder:e.sortOrder,page:e.page||1,perPage:e.perPage},o=t?`search_${t.toLowerCase().substring(0,50)}`:"search";this.config.tracker.track("search_query",{entityType:"search",entityId:o,metadata:i}),this.log("Tracked search_query:",t,i)}trackSearchFilter(e){if(!e||!e.filters||0===e.filters.length)return void this.log("No filters in search data");const t=Date.now();this.searchState.filters=e.filters,this.searchState.lastQueryTime=t,this.saveSearchState();const n=this.serializeFilters(e.filters),i={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:t,query:e.query,category:e.category,filters:n,filterCount:e.filters.length,trigger:e.trigger||"filter"};this.config.tracker.track("search_filter",{entityType:"search",entityId:e.query||"filter",metadata:i}),this.log("Tracked search_filter:",n,i)}trackSearchSort(e){if(!e)return;const t=Date.now();this.searchState.sortBy=e.sortBy,this.searchState.sortOrder=e.sortOrder,this.searchState.lastQueryTime=t,this.saveSearchState();const n={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:t,query:e.query,sortBy:e.sortBy,sortOrder:e.sortOrder,trigger:e.trigger||"order"};this.config.tracker.track("search_sort",{entityType:"search",entityId:e.query||"sort",metadata:n}),this.log("Tracked search_sort:",e.sortBy,n)}trackSearchPage(e){if(!e||!e.page)return void this.log("No page number in search data");const t=Date.now();this.searchState.page=e.page,this.searchState.lastQueryTime=t,this.saveSearchState();const n={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:t,query:e.query,page:e.page,perPage:e.perPage,results:e.results,trigger:e.trigger||"page"};this.config.tracker.track("search_page",{entityType:"search",entityId:e.query||"page",metadata:n}),this.log("Tracked search_page:",e.page,n)}trackSearchResults(e){if(!e)return;const t=Date.now();this.searchState.results=e.results,this.searchState.lastQueryTime=t,this.saveSearchState();const n={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:t,query:e.query,results:e.results,zeroResults:0===(e.results||0)};this.config.tracker.track("search_results",{entityType:"search",entityId:e.query||"results",metadata:n}),0===(e.results||0)&&e.query&&this.config.tracker.track("search_zero_results",{entityType:"search",entityId:e.query,metadata:{...n,zeroResultsQuery:e.query}}),this.log("Tracked search_results:",e.results,n)}trackSearchClose(e){const t=this.searchState.openedAt,n=Date.now(),i=t?n-t:0,o={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:n,query:e?.query||this.searchState.query,results:e?.results||this.searchState.results,dwellTime:i,interactionType:this.getInteractionType(i)};this.config.tracker.track("search_close",{entityType:"search",entityId:e?.query||this.searchState.query||"close",metadata:o}),this.log("Tracked search_close:",i,"ms",o),this.clearSearchState()}serializeFilters(e){const t={};for(const n of e)t[n.facet]=n.values;return t}getInteractionType(e){return e<2e3?"quick_close":e<5e3?"short_browse":e<15e3?"moderate_browse":"long_browse"}getSearchState(){return{...this.searchState}}getTimeSinceLastSearch(){return this.searchState.lastQueryTime?Date.now()-this.searchState.lastQueryTime:0}processDataLayer(e){if(e.search)switch(e.event){case"search_instant_open":this.trackSearchOpen(e.search);break;case"search_query":default:this.trackSearchQuery(e.search);break;case"search_filter":this.trackSearchFilter(e.search);break;case"search_sort":this.trackSearchSort(e.search);break;case"search_page":this.trackSearchPage(e.search);break;case"search_results":this.trackSearchResults(e.search)}else this.log("No search data in event:",e.event)}log(...e){W("SearchTracker",...e)}destroy(){this.clearSearchState()}}class _n{constructor(e){this.originalPush=null,this.initialized=!1,this.processedEvents=new Set,this.config={dataLayerName:"dataLayer",debugMode:!1,enabled:!0,...e},this.dataLayerArray=this.getDataLayer()}getDataLayer(){const e=this.config.dataLayerName||"dataLayer",t=window;if(!t[e])return t[e]=[],this.log(`Initialized empty window.${e} array`),t[e];const n=t[e];return Array.isArray(n)?n:(this.log(`Warning: window.${e} is not an array`),t[e]=[],t[e])}init(){if(this.initialized||!this.config.enabled)return;if(this.dataLayerArray=this.getDataLayer(),!this.dataLayerArray)return void this.log("External dataLayer not found");this.originalPush=this.dataLayerArray.push.bind(this.dataLayerArray);const e=this;this.dataLayerArray.push=function(...t){const n=e.originalPush.apply(this,t);for(const n of t)n&&"object"==typeof n&&e.processDataLayerItem(n);return n},this.processExistingEvents(),this.initialized=!0,this.log("External dataLayer listener initialized")}processExistingEvents(){for(const e of this.dataLayerArray)e&&"object"==typeof e&&this.processDataLayerItem(e,!0)}processDataLayerItem(e,t=!1){if(!e||"object"!=typeof e)return;const n=e.event||null;if(!n&&("consent"===e[0]||e.gtm?.start||"gtm.js"===e.event))return;if(!n||this.isInternalEvent(n,e))return;const i=this.getMappedEvent(n);if(!i)return;const o=this.createEventId(e,t);if(this.processedEvents.has(o))return;this.processedEvents.add(o);const r=this.extractEventData(e);this.trackMappedEvent(i,n,r)}isInternalEvent(e,t){return!!e&&!(!["gtm.js","gtm.dom","gtm.load","gtm.elementVisibility","gtm.triggerGroup","gtm.scroll","gtm.formSubmit","gtm.click","gtm.linkClick","gtm.historyChange","gtm.video","gtm.timer","remarketingEvent","cookieseal.init","cookieseal_marketing","cookieseal_performance","cookieseal_functional","session_property","visilabs_loaded","PrimeWidgets","cartInfo"].includes(e)&&"consent"!==e&&!t[2]?.ad_storage&&!0!==t.noninteraction)}getMappedEvent(e){if(!e)return null;if(this.config.reverseMapping[e])return this.config.reverseMapping[e];for(const[t,n]of Object.entries(this.config.reverseMapping))if(t.includes("*")&&new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e))return n;return null}extractEventData(e){const t={source:"external_dataLayer",originalEvent:e.event,timestamp:Date.now()};e.vl_ecommerce&&(t.vl_ecommerce=e.vl_ecommerce),e.vl_label&&(t.vl_label=e.vl_label),"GAEvent"===e.event&&(t.eventCategory=e.eventCategory,t.eventAction=e.eventAction,t.eventLabel=e.eventLabel,t.eventValue=e.eventValue),e.cartItems&&(t.cartItems=e.cartItems),e.vl_ecommerce?.detail?.product&&(t.product=e.vl_ecommerce.detail.product),e.vl_ecommerce?.cart?.products&&(t.products=e.vl_ecommerce.cart.products),e.google_tag_params&&(t.googleTagParams=e.google_tag_params),e.ecommerce&&(t.ecommerce=this.extractEcommerceData(e.ecommerce));for(const n of Object.keys(e))(n.startsWith("cd_")||n.startsWith("dimension"))&&(t[n]=e[n]);return t}extractEcommerceData(e){const t={};return e.detail?(t.action="detail",t.products=e.detail.products):e.add?(t.action="add",t.products=e.add.products):e.remove?(t.action="remove",t.products=e.remove.products):e.purchase?(t.action="purchase",t.products=e.purchase.products,t.purchaseData={actionField:e.purchase.actionField}):e.checkout?(t.action="checkout",t.products=e.checkout.products):e.impressions?(t.action="impressions",t.products=e.impressions):e.click?(t.action="click",t.products=e.click.products):e.cart&&(t.action="cart",t.products=e.cart.products),t}createEventId(e,t){return[e.event,e.gtm?.uniqueEventId||Date.now(),t?"existing":"new"].join(":")}trackMappedEvent(e,t,n){this.log(`Mapping event: ${t} -> ${e}`);const{entityType:i,entityId:o}=this.determineEntityContext(e,n);this.config.tracker.track(e,{entityType:i,entityId:o,metadata:{...n,mappedFrom:t,sessionId:this.config.tracker.getSessionId(),visitorId:this.config.tracker.getVisitorId()}})}determineEntityContext(e,t){const n={page_view:"page",product_view:"product",add_to_cart:"basket",remove_from_cart:"basket",purchase:"order",search:"search",user_login:"user",user_logout:"user"}[e]||"custom";let i;return t.vl_ecommerce?.detail?.product?.id?i=t.vl_ecommerce.detail.product.id:t.ecommerce?.products?.[0]?.id?i=t.ecommerce.products[0].id:t.products?.[0]?.id&&(i=t.products[0].id),"order"===n&&t.ecommerce?.purchase?.actionField?.id&&(i=t.ecommerce.purchase.actionField.id),{entityType:n,entityId:i}}updateMapping(e){this.config.reverseMapping=e,this.log("Updated reverse mapping:",e)}setEnabled(e){this.config.enabled=e,e&&!this.initialized&&this.init()}getDetectedEvents(){const e=new Set;for(const t of this.dataLayerArray)t&&"object"==typeof t&&t.event&&e.add(t.event);return Array.from(e)}getMappedEvents(){return Object.keys(this.config.reverseMapping).filter(e=>this.config.reverseMapping[e])}clearProcessedCache(){this.processedEvents.clear(),this.log("Cleared processed events cache")}destroy(){this.dataLayerArray&&this.originalPush&&(this.dataLayerArray.push=this.originalPush),this.initialized=!1,this.processedEvents.clear(),this.log("External dataLayer listener destroyed")}log(...e){W("ExternalDataLayerListener",...e)}}class Pn{constructor(e){this.sessionCartContents=new Map,this.globalCartContents=new Set,this.config=e}trackAddToCartWithAssociations(e){if(!e||!e.products||0===e.products.length)return;const t=this.config.tracker.getSessionId(),n=this.config.tracker.getVisitorId(),i=this.sessionCartContents.get(t)?.products||[];for(const o of e.products){const r=this.resolveProductItemCode(o);if(!r)continue;const a=[],s=[];for(const e of i)e===r||a.includes(e)||a.push(e);for(const e of this.globalCartContents)e===r||s.includes(e)||e===r||s.push(e);const l=this.getBasketProductItemCodes(e.products),c={dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),productName:o.title,productItemCode:r,productItemCodes:l,productCategory:o.category,quantity:o.quantity||1,price:o.price,currency:e.currency,cartId:e.id,cartAssociations:{session:a,cart:s},cartSize:{session:i.length,global:this.globalCartContents.size},sessionId:t,visitorId:n};this.config.tracker.track("add_to_cart",{entityType:"basket",entityId:r,metadata:c}),i.includes(r)||i.push(r),this.globalCartContents.add(r),this.log("Tracked add_to_cart with associations:",r,{sessionAssociations:a,cartAssociations:s})}this.sessionCartContents.set(t,{products:i,lastUpdated:Date.now()})}updateCartContents(e){const t=this.config.tracker.getSessionId(),n=e.map(e=>this.resolveProductItemCode(e)).filter(e=>!!e);this.sessionCartContents.set(t,{products:n,lastUpdated:Date.now()});for(const e of n)this.globalCartContents.add(e);this.log("Updated cart contents:",n)}clearCart(e){const t=e||this.config.tracker.getSessionId();this.sessionCartContents.delete(t),this.log("Cleared session cart:",t)}clearAllCarts(){this.sessionCartContents.clear(),this.globalCartContents.clear(),this.log("Cleared all cart data")}getSessionCart(e){const t=e||this.config.tracker.getSessionId();return this.sessionCartContents.get(t)?.products||[]}getGlobalCart(){return Array.from(this.globalCartContents)}processDataLayer(e){if(e.basket)switch(e.event){case"add_to_cart":this.trackAddToCartWithAssociations(e.basket);break;case"update_cart":case"remove_from_cart":e.basket.products&&this.updateCartContents(e.basket.products);break;case"purchase":case"checkout_begin":this.clearCart();break;default:e.basket.products&&e.basket.products.length>0&&this.trackAddToCartWithAssociations(e.basket)}}destroy(){this.sessionCartContents.clear(),this.globalCartContents.clear()}resolveProductItemCode(e){if(!e)return null;const t=e.sku;if(!t)return null;const n=t.trim();return n.length>0?n:null}getBasketProductItemCodes(e){if(!e||0===e.length)return[];const t=new Set,n=[];for(const i of e){const e=this.resolveProductItemCode(i);e&&!t.has(e)&&(t.add(e),n.push(e))}return n}log(...e){W("CartAssociationTracker",...e)}}const An=new Map;class $n{constructor(e,t,n,i={}){this.isInitialized=!1,this.isDestroyed=!1,this.observer=null,this.debounceTimer=null,this.lastProcessedIndex=0,this.originalPush=null,this.originalHistoryPushState=null,this.originalHistoryReplaceState=null,this.popStateListener=null,this.lastPageUrl="",this.lastPageTitle="",this.consentState=null,this.consentTimeoutTimer=null,this.lastConsentValue=null,this.eventBuffer=[],this.flushTimer=null,this.tracker=e,this.siteKey=t,this.apiUrl=n,this.dataLayerName=i.variableName||"selwiseLayer";const o=this.normalizeTrackingModules(i.trackingModules),r=this.normalizePageTypePatterns(i.pageTypePatterns);this.config={enabled:i.enabled??!0,variableName:i.variableName,pageDetection:i.pageDetection??"auto",autoPageTracking:i.autoPageTracking??!0,cartAbandonmentTimeout:i.cartAbandonmentTimeout??30,pageTypePatterns:r,debugMode:i.debugMode??!1,cookieConsent:i.cookieConsent,trackingModules:o,bufferSize:i.bufferSize??10,flushInterval:i.flushInterval??1e3,reverseEventMapping:i.reverseEventMapping,externalDataLayerName:i.externalDataLayerName},this.cookieConsent=i.cookieConsent,this.trackingModules=o,this.attachToGlobalApi=i.attachToGlobalApi??!1,this.log("DataLayerManager constructor called with config:",this.config)}normalizeTrackingModules(e){return{page:{...Nt.TRACKING_MODULES.page,...e?.page||{}},product:{...Nt.TRACKING_MODULES.product,...e?.product||{}},basket:{...Nt.TRACKING_MODULES.basket,...e?.basket||{}},checkout:{...Nt.TRACKING_MODULES.checkout,...e?.checkout||{}},user:{...Nt.TRACKING_MODULES.user,...e?.user||{}},search:{...Nt.TRACKING_MODULES.search,...e?.search||{}}}}normalizePageTypePatterns(e){const t=e&&Object.keys(e).length>0?e:wn,n={};for(const[e,i]of Object.entries(t))if(i instanceof RegExp)n[e]=i;else if("string"==typeof i&&i.trim().length>0)try{n[e]=new RegExp(i,"i")}catch{this.log(`Invalid regex for page type "${e}", using default pattern`),n[e]=wn[e]||wn.home}return Object.keys(n).length>0?n:{...wn}}isModuleEnabled(e){return Boolean(this.trackingModules?.[e]?.enabled)}shouldAutoTrackPageViews(){if(!this.config.autoPageTracking||!this.pageTracker||!this.isModuleEnabled("page"))return!1;if("manual"===this.config.pageDetection)return!1;if("patterns"===this.config.pageDetection){const e=`${window.location.pathname}${window.location.search}`;return Object.values(this.config.pageTypePatterns||{}).some(t=>t.test(e))}return!0}shouldObservePageChanges(){return this.shouldAutoTrackPageViews()||this.isModuleEnabled("product")||this.isModuleEnabled("checkout")}init(){if(this.isInitialized)this.log("DataLayerManager already initialized");else if(this.isDestroyed)this.log("DataLayerManager was destroyed, cannot reinitialize");else if(this.config.enabled){this.log("Initializing DataLayerManager...");try{this.initializeDataLayer(),this.setupPushInterception(),this.setupObserver(),this.initializeSubTrackers(),this.processLayer(),this.shouldAutoTrackPageViews()&&this.trackInitialPageView(),this.runAutomaticModuleTracking(),this.attachToGlobalApi&&this.exposePublicApi(),this.checkCartAbandonment(),this.initExternalListener(),this.initConsentTracking(),this.isInitialized=!0,this.log("DataLayerManager initialized successfully")}catch(e){K("DataLayerManager","Initialization failed:",e),this.isInitialized=!1}}else this.log("Data layer is disabled by config")}initializeDataLayer(){const e=this.dataLayerName;window[e]?this.log(`window.${e} already exists, length:`,window[e].length):(window[e]=[],this.log(`Created window.${e} array`))}getDataLayer(){return window[this.dataLayerName]||[]}setupPushInterception(){const e=this.getDataLayer();e&&e.push&&(this.originalPush=e.push.bind(e),e.push=(...e)=>{const t=this.originalPush(...e);return this.scheduleProcess(),t},this.log("Setup push interception"))}setupObserver(){this.observer=new MutationObserver(()=>{this.shouldObservePageChanges()&&this.checkPageChange()}),this.observer.observe(document,{childList:!0,subtree:!0}),this.originalHistoryPushState=history.pushState,this.originalHistoryReplaceState=history.replaceState,history.pushState=(...e)=>{this.originalHistoryPushState?.apply(history,e),this.onHistoryChange()},history.replaceState=(...e)=>{this.originalHistoryReplaceState?.apply(history,e),this.onHistoryChange()},this.popStateListener=()=>{this.onHistoryChange()},window.addEventListener("popstate",this.popStateListener),this.log("Setup MutationObserver and History API listeners")}onHistoryChange(){this.shouldObservePageChanges()&&this.checkPageChange(),this.scheduleProcess()}checkPageChange(){const e=window.location.href,t=document.title;e===this.lastPageUrl&&t===this.lastPageTitle||(this.log("Page change detected:",e),this.shouldAutoTrackPageViews()&&An.delete("page_view:"),this.lastPageUrl=e,this.lastPageTitle=t,this.productTracker&&this.productTracker.stopDwellTimeTracking(),this.shouldAutoTrackPageViews()&&this.pageTracker&&this.pageTracker.trackPageView(),this.runAutomaticModuleTracking())}initializeSubTrackers(){const e={siteKey:this.siteKey,apiUrl:this.apiUrl,tracker:this.tracker,config:this.config,scheduleProcess:()=>this.scheduleProcess()};this.isModuleEnabled("page")&&(this.pageTracker=new vn(e),this.log("Page tracker enabled")),this.isModuleEnabled("product")&&(this.productTracker=new Cn(e),this.log("Product tracker enabled")),this.isModuleEnabled("basket")&&(this.basketTracker=new kn(e),this.log("Basket tracker enabled")),this.isModuleEnabled("checkout")&&(this.checkoutTracker=new Tn(e),this.log("Checkout tracker enabled")),this.isModuleEnabled("user")&&(this.userTracker=new In(e),this.log("User tracker enabled")),this.isModuleEnabled("search")&&(this.searchTracker=new En(e),this.log("Search tracker enabled")),this.isModuleEnabled("basket")&&(this.cartAssociationTracker=new Pn(e),this.log("Cart association tracker enabled")),this.log("Initialized sub-trackers")}trackInitialPageView(){this.lastPageUrl=window.location.href,this.lastPageTitle=document.title,this.pageTracker&&this.pageTracker.trackPageView()}checkCartAbandonment(){this.basketTracker&&(this.basketTracker.checkCartAbandonment(),this.basketTracker.startCartMonitoring())}runAutomaticModuleTracking(){this.checkoutTracker&&this.checkoutTracker.autoTrackCheckoutStep(),this.productTracker&&this.productTracker.isProductPage()&&this.productTracker.trackProductView()}initExternalListener(){const e=this.config.reverseEventMapping,t=this.config.externalDataLayerName||"dataLayer";if(e&&0!==Object.keys(e).length)try{this.externalListener=new _n({tracker:this.tracker,reverseMapping:e,dataLayerName:t,debugMode:this.config.debugMode,enabled:!0}),this.externalListener.init(),this.log("External dataLayer listener initialized with mapping:",e)}catch(e){this.log("Failed to initialize external dataLayer listener:",e)}else this.log("No reverse event mapping configured, skipping external listener")}scheduleProcess(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout(()=>{this.processLayer(),this.debounceTimer=null},100)}processLayer(){if(this.isDestroyed)return;const e=this.getDataLayer();if(!e)return;const t=e.slice(this.lastProcessedIndex);if(0!==t.length){this.log("Processing",t.length,"new data layer events");for(const e of t)this.enqueueEvent(e);this.lastProcessedIndex=e.length}}enqueueEvent(e){this.eventBuffer.push(e);const t=Math.max(1,this.config.bufferSize||1),n=Math.max(100,this.config.flushInterval||1e3);this.eventBuffer.length>=t?this.flushEventBuffer():this.flushTimer||(this.flushTimer=window.setTimeout(()=>{this.flushEventBuffer()},n))}flushEventBuffer(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),0===this.eventBuffer.length)return;const e=[...this.eventBuffer];this.eventBuffer=[];for(const t of e)this.processEvent(t)}hasConsent(e){if(!this.cookieConsent?.enabled)return!0;const t=this.loadConsentState();if(!t){const e=this.cookieConsent.variableName||"__wcmp_consent",t=window[e];return!0===t||"granted"===t||1===t||!(!this.cookieConsent.defaultConsent||void 0!==t)||(this.log("Cookie consent not given, blocking event"),!1)}if(this.cookieConsent.granularEnabled&&e){const n=t[e];return n||this.log(`Consent denied for category: ${e}`),n}return t.analytics||t.necessary}initConsentTracking(){if(!this.cookieConsent?.enabled)return;this.log("Initializing cookie consent tracking..."),this.consentState=this.loadConsentState(),this.cookieConsent.waitForConsent&&this.cookieConsent.timeoutMs&&(this.consentTimeoutTimer=window.setTimeout(()=>{this.log("Consent timeout reached, using default consent"),!this.consentState&&this.cookieConsent?.defaultConsent&&(this.consentState={necessary:!0,analytics:this.cookieConsent.defaultConsent,marketing:!1,preferences:!1}),this.processLayer(),this.flushEventBuffer()},this.cookieConsent.timeoutMs)),this.setupConsentChangeDetection();const e=this.cookieConsent.variableName||"__wcmp_consent",t=window[e];void 0!==t&&this.updateConsentFromWindow(t),this.log("Cookie consent tracking initialized")}setupConsentChangeDetection(){const e=setInterval(()=>{if(this.isDestroyed)return void clearInterval(e);const t=this.cookieConsent?.variableName||"__wcmp_consent",n=window[t];n!==this.lastConsentValue&&(this.lastConsentValue=n,this.updateConsentFromWindow(n));const i=this.cookieConsent?.storageKey||"selwise_consent",o=this.loadStoredConsent(i);if(o){const e=JSON.stringify(this.consentState);this.consentState=o.granted,e!==JSON.stringify(this.consentState)&&(this.log("Consent state changed from storage"),this.onConsentChange(o))}},1e3);this.consentCheckInterval=e}updateConsentFromWindow(e){this.log("Updating consent from window variable:",e),"boolean"==typeof e?this.consentState={necessary:!0,analytics:e,marketing:e,preferences:e}:e&&"object"==typeof e?this.consentState={necessary:!0,analytics:e.analytics??e.all??!1,marketing:e.marketing??e.all??!1,preferences:e.preferences??e.all??!1}:"granted"===e||1===e?this.consentState={necessary:!0,analytics:!0,marketing:!0,preferences:!0}:"denied"!==e&&0!==e||(this.consentState={necessary:!0,analytics:!1,marketing:!1,preferences:!1}),this.callConsentChangeCallback(),this.processLayer(),this.flushEventBuffer()}loadStoredConsent(e){try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n.expiresAt&&Date.now()>n.expiresAt?(localStorage.removeItem(e),null):n}catch{return null}}loadConsentState(){if(this.consentState)return this.consentState;const e=this.cookieConsent?.storageKey||"selwise_consent",t=this.loadStoredConsent(e);return t?t.granted:null}onConsentChange(e){this.log("Consent changed:",e),this.callConsentChangeCallback(),this.processLayer(),this.flushEventBuffer()}callConsentChangeCallback(){const e=this.cookieConsent?.consentChangeCallback;if(e)try{const t=window[e];"function"==typeof t&&(t(this.consentState),this.log(`Called consent change callback: ${e}`))}catch(e){this.log("Error calling consent change callback:",e)}}getConsentState(){return this.consentState}grantConsent(e){this.consentState={necessary:!0,analytics:!0,marketing:!1,preferences:!1,...e};const t=this.cookieConsent?.storageKey||"selwise_consent",n={granted:this.consentState,timestamp:Date.now(),expiresAt:Date.now()+31536e6};localStorage.setItem(t,JSON.stringify(n)),this.log("Consent granted:",this.consentState),this.callConsentChangeCallback(),this.processLayer(),this.flushEventBuffer()}revokeConsent(e){if(!this.consentState)return;if(e)for(const t of e)"necessary"!==t&&(this.consentState[t]=!1);else this.consentState.analytics=!1,this.consentState.marketing=!1,this.consentState.preferences=!1;const t=this.cookieConsent?.storageKey||"selwise_consent",n={granted:this.consentState,timestamp:Date.now(),expiresAt:Date.now()+31536e6};localStorage.setItem(t,JSON.stringify(n)),this.log("Consent revoked:",this.consentState),this.callConsentChangeCallback()}processEvent(e){if(!e.event)return void this.log("Skipping event without event name:",e);if(!this.hasConsent())return void this.log("Event blocked due to cookie consent:",e.event);const t=function(e){return e.product?.id?`${e.event}:${e.product.id}`:e.basket?.id?`${e.event}:${e.basket.id}`:e.checkout?.orderNo?`${e.event}:${e.checkout.orderNo}`:e.user?.id?`${e.event}:${e.user.id}`:e.search?.query?`${e.event}:${e.search.query}`:e.event||"unknown"}(e);if(function(e){const t=e,n=An.get(t)||0,i=Date.now();return i-n<1e3||(An.set(t,i),!1)}(t))this.log("Throttled event:",t);else switch(this.log("Processing event:",e.event),e.event){case"page_view":case"virtual_page_view":this.pageTracker?.processDataLayer(e);break;case"product_view":case"product_click":case"product_impression":this.productTracker?.processDataLayer(e);break;case"add_to_cart":case"remove_from_cart":case"update_cart":case"cart_abandon":case"cart_restore":this.basketTracker?.processDataLayer(e),this.cartAssociationTracker?.processDataLayer(e);break;case"checkout_begin":case"checkout_progress":case"checkout_option":case"purchase":this.checkoutTracker?.processDataLayer(e);break;case"user_signup":case"user_login":case"user_logout":case"user_update":this.userTracker?.processDataLayer(e);break;case"search_instant_open":case"search_query":case"search_filter":case"search_sort":case"search_page":case"search_results":this.searchTracker?.processDataLayer(e);break;case"custom":this.trackCustomEvent(e);break;default:this.log("Unknown event type, tracking as custom:",e.event),this.trackCustomEvent(e)}}trackCustomEvent(e){const t=e.custom?.type||e.custom?.name||e.event||"custom";this.tracker.track(t,{entityType:"custom",entityId:e.custom?.name||void 0,metadata:{dataSource:Sn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),...e.custom?.params,...e}})}exposePublicApi(){if(!window.Selwise)return;const e=this.dataLayerName;"function"!=typeof window.Selwise.pushDataLayer&&(window.Selwise.pushDataLayer=t=>{Array.isArray(window[e])||(window[e]=[]),window[e].push(t)}),"function"!=typeof window.Selwise.getDataLayer&&(window.Selwise.getDataLayer=()=>this.getDataLayer()),"function"!=typeof window.Selwise.getConsentState&&(window.Selwise.getConsentState=()=>this.getConsentState()),"function"!=typeof window.Selwise.grantConsent&&(window.Selwise.grantConsent=e=>{this.grantConsent(e)}),"function"!=typeof window.Selwise.revokeConsent&&(window.Selwise.revokeConsent=e=>{this.revokeConsent(e)}),this.log("Exposed public API")}updateConfig(e){if(void 0!==e.enabled&&(this.config.enabled=e.enabled),void 0!==e.variableName&&(this.config.variableName=e.variableName,this.dataLayerName=e.variableName||"selwiseLayer"),void 0!==e.pageDetection&&(this.config.pageDetection=e.pageDetection),void 0!==e.autoPageTracking&&(this.config.autoPageTracking=e.autoPageTracking),void 0!==e.cartAbandonmentTimeout&&(this.config.cartAbandonmentTimeout=e.cartAbandonmentTimeout),void 0!==e.pageTypePatterns&&(this.config.pageTypePatterns=this.normalizePageTypePatterns(e.pageTypePatterns)),void 0!==e.debugMode&&(this.config.debugMode=e.debugMode),void 0!==e.cookieConsent&&(this.config.cookieConsent=e.cookieConsent,this.cookieConsent=e.cookieConsent),void 0!==e.trackingModules){const t=this.normalizeTrackingModules(e.trackingModules);this.config.trackingModules=t,this.trackingModules=t}void 0!==e.bufferSize&&(this.config.bufferSize=e.bufferSize),void 0!==e.flushInterval&&(this.config.flushInterval=e.flushInterval),void 0!==e.attachToGlobalApi&&(this.attachToGlobalApi=e.attachToGlobalApi),this.log("Config updated:",this.config)}getConfig(){return{...this.config}}getLayerState(e=100){const t=this.getDataLayer();return t.length?t.slice(-e):[]}push(e){Array.isArray(window[this.dataLayerName])||(window[this.dataLayerName]=[]),window[this.dataLayerName].push(e)}log(...e){W("DataLayerManager",...e)}destroy(){this.log("Destroying DataLayerManager..."),this.observer&&(this.observer.disconnect(),this.observer=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.originalHistoryPushState&&(history.pushState=this.originalHistoryPushState,this.originalHistoryPushState=null),this.originalHistoryReplaceState&&(history.replaceState=this.originalHistoryReplaceState,this.originalHistoryReplaceState=null),this.popStateListener&&(window.removeEventListener("popstate",this.popStateListener),this.popStateListener=null),this.flushEventBuffer(),this.consentTimeoutTimer&&(clearTimeout(this.consentTimeoutTimer),this.consentTimeoutTimer=null);const e=this.consentCheckInterval;e&&(clearInterval(e),this.consentCheckInterval=null),this.getDataLayer().length&&this.originalPush&&(window[this.dataLayerName].push=this.originalPush,this.originalPush=null),this.pageTracker?.destroy(),this.productTracker?.destroy(),this.basketTracker?.destroy(),this.checkoutTracker?.destroy(),this.userTracker?.destroy(),this.searchTracker?.destroy(),this.cartAssociationTracker?.destroy(),this.externalListener?.destroy(),An.clear(),this.eventBuffer=[],this.isDestroyed=!0,this.isInitialized=!1,this.log("DataLayerManager destroyed")}}function On(e,t){const n=t||{},i=n.currencySymbol||"$",o=n.currencyPosition||"left",r=parseInt(n.priceDecimals||"2"),a=n.decimalSeparator||".",s=n.thousandSeparator||",",l=Number(e).toFixed(r),[c,d]=l.split("."),u=c.replace(/\B(?=(\d{3})+(?!\d))/g,s),p=d?`${u}${a}${d}`:u;return"right"===o?`${p}${i}`:"left-space"===o?`${i} ${p}`:"right-space"===o?`${p} ${i}`:`${i}${p}`}function Dn(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function Mn(e){const t=function(e){if(!e)return e;const t=document.createElement("textarea");t.innerHTML=e;let n=t.value;return(n.includes("&lt;")||n.includes("&gt;")||n.includes("&amp;"))&&(t.innerHTML=n,n=t.value),n}(e);if(t.includes(">")){const e=t.split(">").map(e=>e.trim());return e[e.length-1]}return t}function Nn(e,t){let n=.1;"sm"===e&&(n=.05),"2xl"===e&&(n=.25);let i=`rgba(0,0,0,${n})`;if(t){const e=parseInt(t.slice(1,3),16),o=parseInt(t.slice(3,5),16),r=parseInt(t.slice(5,7),16);isNaN(e)||(i=`rgba(${e},${o},${r},${n})`)}const o={none:"none",sm:`0 1px 2px 0 ${i}`,md:`0 4px 6px -1px ${i}`,lg:`0 10px 15px -3px ${i}`,xl:`0 20px 25px -5px ${i}`,"2xl":`0 25px 50px -12px ${i}`};return o[e]||o.lg}function Rn(e="",t=20){return`\n <svg class="${e}" width="${t}" height="${t}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M21 21L15 15M17 10C17 13.866 13.866 17 10 17C6.13401 17 3 13.866 3 10C3 6.13401 6.13401 3 10 3C13.866 3 17 6.13401 17 10Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n `}function Ln(e=24){return`\n <svg width="${e}" height="${e}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n `}const Bn="ws_recent_searches";function Un(e=5,t){try{const n=localStorage.getItem(`${Bn}_${t}`);if(!n)return[];const i=JSON.parse(n);return Array.isArray(i)?i.slice(0,e):[]}catch{return[]}}var zn=n(561);async function Fn(e,t,n,i,o,r,a,s){try{sessionStorage.setItem(f,JSON.stringify({ts:Date.now(),productItemCode:t,query:s||void 0}))}catch{}try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/search/click`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({productItemCode:t,sessionId:n,category:a||void 0,query:s||void 0,visitorId:i,siteUserId:o,pageUrl:window.location.href,referrer:document.referrer||void 0,eventId:r})})}catch{}}function qn(e,t,n){switch(t){case"shopify":return function(e){const t=e.variantId||e.id;return fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:t,quantity:1})}).then(e=>e.json()).then(()=>{document.dispatchEvent(new CustomEvent("cart:updated")),window.Shopify?.theme?.ajaxCart&&window.Shopify.theme.ajaxCart.load()}).catch(e=>{console.error("[Cart] Shopify add to cart error:",e)})}(e);case"woocommerce":return function(e){const t=e.wooProductId||e.id;return fetch("/?wc-ajax=add_to_cart",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`product_id=${t}&quantity=1`}).then(e=>e.json()).then(()=>{"undefined"!=typeof jQuery&&jQuery(document.body).trigger("wc_fragment_refresh")}).catch(e=>{console.error("[Cart] WooCommerce add to cart error:",e)})}(e);case"magento":return function(e){const t=document.querySelector('input[name="form_key"]')?.value||"",n=e.magentoProductId||e.id;return fetch("/checkout/cart/add/",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`product=${n}&qty=1&form_key=${t}`}).then(()=>{window.customerData&&window.customerData.reload(["cart"],!0)}).catch(e=>{console.error("[Cart] Magento add to cart error:",e)})}(e);case"prestashop":return function(e){const t=e.prestaProductId||e.id,n=e.attributeId||0;return fetch("/index.php?fc=module&module=ajax_cart&controller=add",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`id_product=${t}&id_product_attribute=${n}&qty=1`}).then(e=>e.json()).then(()=>{window.prestashop&&window.prestashop.emit("updateCart",{reason:{}})}).catch(e=>{console.error("[Cart] PrestaShop add to cart error:",e)})}(e);case"akinon":return async function(e,t){t?.setLoading();try{const n=(()=>{const e=`; ${document.cookie}`.split("; csrftoken=");if(2===e.length){const t=e.pop();if(t)return t.split(";").shift()}})(),i={product:e.itemCode||e.id,quantity:1,attributes:{}},o=await fetch("/baskets/basket/",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","X-Requested-With":"XMLHttpRequest",...n?{"X-CSRFToken":n}:{}},body:JSON.stringify(i)});if(!o.ok)throw new Error(`HTTP ${o.status}`);{const e=await o.json();t?.setSuccess(),document.dispatchEvent(new CustomEvent("akinon:basket:updated",{detail:{basket:e}})),window.akinonBasket&&window.akinonBasket.refresh(),setTimeout(()=>t?.reset(),1500)}}catch(e){console.error("[Cart] Akinon add to cart error:",e),t?.setError(),setTimeout(()=>t?.reset(),2e3)}}(e,n?.buttonState);case"custom":return function(e,t){if(t)try{const i=1,o=e.itemCode||e.id,r={productItemCode:o,productId:e.id,itemCode:o,productName:e.title||e.name||"",productPrice:e.price,quantity:i,product:e},a=(n=r,t.replace(/\$\{([A-Za-z_$][A-Za-z0-9_$]*)\}/g,(e,t)=>Object.prototype.hasOwnProperty.call(n,t)?function(e){if(null==e)return"";if("object"==typeof e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}(n[t]):e));new Function("productItemCode","productId","itemCode","productName","productPrice","quantity","product",a)(r.productItemCode,r.productId,r.itemCode,r.productName,r.productPrice,r.quantity,r.product)}catch(e){console.error("[Cart] Custom cart script error:",e)}var n}(e,n?.customScript);default:return}}function jn(e,t){const n=e?.textContent||t?.default||"Add to Cart";return{button:e,originalText:n,setLoading:()=>{e&&(e.textContent=t?.loading||"Adding...",e.disabled=!0)},setSuccess:()=>{e&&(e.textContent=t?.success||"Added!")},setError:()=>{e&&(e.textContent=t?.error||"Error")},reset:()=>{e&&(e.textContent=n,e.disabled=!1)}}}function Hn(e,t){const{showSearchIcon:n=!0,showCloseIcon:i=!0,getSearchIcon:o,getCloseIcon:r}=t,a=e.styles||{},s=document.createElement("div");return s.className="ws-search-wrapper",s.innerHTML=`\n <div class="ws-search-input-wrap">\n ${n?o("ws-search-icon"):""}\n <input\n type="text"\n class="ws-search-input ${n?"":"no-icon"}"\n placeholder="${a.textPlaceholder||e.placeholder||"Search products..."}"\n autocomplete="off"\n />\n ${i?`<button class="ws-search-clear" type="button">${r(12)}</button>`:""}\n </div>\n <div class="ws-search-results layout-${e.resultLayout||"list"}"></div>\n `,s}function Wn(e,t){if(!e.selector)return null;const n=()=>{const t=document.querySelector(e.selector);if(t){const n=Hn(e,{showSearchIcon:!0,showCloseIcon:!0,getSearchIcon:Rn,getCloseIcon:Ln}),i=n.querySelector(".ws-search-input"),o=n.querySelector(".ws-search-results");return t.innerHTML="",t.appendChild(n),{container:n,input:i,resultsContainer:o}}return null},i=n();if(i)return i;G("WidgetSearch","Selector not found immediately, observing DOM...");const o=new MutationObserver(()=>{n()&&(o.disconnect(),t(),G("WidgetSearch","Selector found and search rendered"))});return o.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{o.disconnect(),J("WidgetSearch","Selector not found after timeout:",e.selector)},1e4),null}function Gn(e,t,n,i){i(t);const o=document.createElement("div");o.className="ws-search-overlay",o.addEventListener("click",e=>{e.target===o&&n()});const r=document.createElement("div");r.className="ws-search-modal";const a=Hn(e,{showSearchIcon:!0,showCloseIcon:!0,getSearchIcon:Rn,getCloseIcon:Ln}),s=a.querySelector(".ws-search-input"),l=a.querySelector(".ws-search-results");return r.appendChild(a),o.appendChild(r),document.body.appendChild(o),{container:a,input:s,resultsContainer:l,overlayElement:o}}const Kn="data-selwise-action",Jn="data-product-id",Vn="add-to-cart";function Yn(e,t,n){return t?"custom"===t.template&&t.customHTML?function(e,t,n){if(!t.customHTML)return"";let i=t.customHTML;(t.fields||[]).forEach(t=>{if(t.id&&t.productField){const n=e[t.productField]??"";i=i.replace(new RegExp(`\\$\\{${t.id}\\}`,"g"),String(n))}});const o=e.itemCode||e.id,r={id:e.id,productId:e.id,itemCode:o,sku:e.sku||"",name:e.title,title:e.title,description:e.description,shortDescription:e.shortDescription||"",shortDesc:e.shortDescription||"",image:e.imageUrl,imageUrl:e.imageUrl,url:e.url,link:e.url,price:e.price,formattedPrice:n.formatPrice(e.price),oldPrice:e.originalPrice,formattedOldPrice:e.originalPrice?n.formatPrice(e.originalPrice):"",originalPrice:e.originalPrice,discount:e.discountRate||"",discountRate:e.discountRate||"",salePercentage:e.originalPrice&&e.price?Math.round((e.originalPrice-e.price)/e.originalPrice*100):"",brand:e.brand||"",category:e.categories||"",categories:e.categories||"",isSale:!!e.originalPrice&&e.originalPrice>e.price,isNew:e.isNew||!1,isBestseller:e.isBestseller||!1,stock:e.stock,inStock:!1!==e.inStock,rating:e.rating||"",reviewCount:e.reviewCount||"",widgetId:n.widgetId||"",source:n.source,addToCartAttrs:`${Kn}="${Vn}" ${Jn}="${o}"`};return Object.entries(r).forEach(([e,t])=>{const n=null!=t?t:"";i=i.replace(new RegExp(`\\$\\{${e}\\}`,"g"),String(n))}),Ze(i)}(e,t,n):function(e,t,n){const i=e.itemCode||e.id,o=t.layoutType||"vertical",r=t.imagePosition||"top",a="horizontal"===o,s=a?"row":"column",l=t.imageSize||"cover";let c="";t.showBadges&&(e.isNew&&(c+='<span class="selwise-badge selwise-badge-new">New</span>'),e.isSale&&(c+='<span class="selwise-badge selwise-badge-sale">Sale</span>'),e.isBestseller&&(c+='<span class="selwise-badge selwise-badge-bestseller">Bestseller</span>'));const d=`\n <div class="selwise-card-image" style="position:relative;width:${a?"40%":"100%"};height:${a?"auto":"200px"};flex-shrink:0;overflow:hidden;">\n <a href="${e.url}" style="display:block;width:100%;height:100%;">\n <img src="${e.imageUrl}" alt="${Qn(e.title)}" loading="lazy" style="width:100%;height:100%;object-fit:${l};" />\n </a>\n ${c?`<div class="selwise-badges">${c}</div>`:""}\n </div>\n `,u=t.fields||[];let p="";u.forEach(o=>{if((void 0!==o.visible?o.visible:o.enabled)&&"image"!==o.type)switch(o.type){case"text":const r=function(e,t){if(t.productField){const n=t.productField;return"name"===n?e.title:e[n]||""}return"price"===t.type?e.price:"old_price"===t.type?e.originalPrice:"text"===t.type&&"name"===t.id?e.title:""}(e,o),a="name"===o.id||"title"===o.productField;p+=`<div class="selwise-card-text ${a?"selwise-card-title":""}">${Qn(String(r))}</div>`;break;case"price":p+=`<div class="selwise-card-price">${n.formatPrice(e.price)}</div>`;break;case"old_price":e.originalPrice&&(p+=`<div class="selwise-card-old-price">${n.formatPrice(e.originalPrice)}</div>`);break;case"rating":e.rating&&(p+=`<div class="selwise-card-rating">${"★".repeat(Math.floor(e.rating))}${"☆".repeat(5-Math.floor(e.rating))}</div>`);break;case"button":const s=t.buttonStyle?.backgroundColor||"#111",l=t.buttonStyle?.color||"#fff";p+=`\n <button class="selwise-card-button" \n ${Kn}="${Vn}" \n ${Jn}="${i}"\n style="width:100%;margin-top:auto;padding:8px;background:${s};color:${l};border:none;border-radius:4px;cursor:pointer;">\n ${o.label||t.buttonText||"Add to Cart"}\n </button>`}});const h=u.some(e=>"button"===e.type&&(e.visible||e.enabled));if(t.showButton&&!h){const e=t.buttonStyle?.backgroundColor||"#111",n=t.buttonStyle?.color||"#fff";p+=`\n <button class="selwise-card-button" \n ${Kn}="${Vn}" \n ${Jn}="${i}"\n style="width:100%;margin-top:8px;padding:8px;background:${e};color:${n};border:none;border-radius:4px;cursor:pointer;">\n ${t.buttonText||"Add to Cart"}\n </button>`}const g=`\n <div class="selwise-card-content" style="padding:12px;flex:1;display:flex;flex-direction:column;">\n ${p}\n </div>\n `;let m="";return m="left"===r||"top"===r?d+g:"right"===r||"bottom"===r?g+d:d+g,`\n <div class="selwise-card-inner" style="display:flex;flex-direction:${s};background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 2px 4px rgba(0,0,0,0.05);height:100%;">\n ${m}\n </div>\n `}(e,t,n):function(e,t){const n=e.originalPrice&&e.originalPrice>e.price,i=n?Math.round((e.originalPrice-e.price)/e.originalPrice*100):0;let o="";return e.isNew&&(o+='<span class="selwise-badge selwise-badge-new">New</span>'),n&&(o+=`<span class="selwise-badge selwise-badge-sale">-${i}%</span>`),e.isBestseller&&(o+='<span class="selwise-badge selwise-badge-bestseller">Bestseller</span>'),`\n <div class="selwise-card-inner">\n <div class="selwise-card-image">\n ${o?`<div class="selwise-badges">${o}</div>`:""}\n <img src="${e.imageUrl}" alt="${Qn(e.title)}" loading="lazy" />\n </div>\n <div class="selwise-card-content">\n <h3 class="selwise-card-title">${Qn(e.title)}</h3>\n <div class="selwise-card-price-row">\n ${n?`<span class="selwise-price-original">${t.formatPrice(e.originalPrice)}</span>`:""}\n <span class="selwise-price-current">${t.formatPrice(e.price)}</span>\n </div>\n </div>\n </div>\n `}(e,n)}function Qn(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):""}function Xn(e,t,n,i){if(!t.customJs?.trim())return;const o=()=>{try{const o=document.createElement("script");o.setAttribute("data-selwise-card-js","true");const r={product:n,container:e,widgetId:i.widgetId,template:t.id};o.textContent=`(function() {\n const product = ${JSON.stringify(n)};\n const container = document.currentScript.parentElement;\n const context = ${JSON.stringify(r)};\n ${t.customJs}\n }).call(window);`,e.appendChild(o)}catch(e){console.error("[Selwise] Card script execution error:",e)}};switch(t.jsTiming||"immediate"){case"immediate":o();break;case"domReady":"loading"===document.readyState?document.addEventListener("DOMContentLoaded",o):o();break;case"customEvent":t.jsEventName&&document.addEventListener(t.jsEventName,o,{once:!0})}}const Zn=new Map;function ei(e,t,n){const{config:i,selectedCategory:o,formatPrice:r,formatCategoryName:a}=t,s=i,l=s.styles||{};if(0===e.hits.length)return"";let c="",d=e.categories||[];if(!d.length&&e.hits.length){const t=new Map;e.hits.forEach(e=>{if(e.categories){const n=e.categories.split(">").map(e=>e.trim()),i=n[0];t.set(i,(t.get(i)||0)+1)}}),d=Array.from(t.entries()).map(([e,t])=>({name:e,count:t}))}return"sidebar"===s.categoryDisplayMode&&d.length&&(c+=function(e,t,n,i,o){const r=i.styles||{};let a=`<div class="ws-search-layout-sidebar" style="display:flex;gap:16px;">\n <div class="ws-search-category-sidebar" style="\n width:${r.categorySidebarWidth||"180px"};\n flex-shrink:0;\n background:${r.sidebarBg||"#f9fafb"};\n border-radius:${r.categoryRadius||"8px"};\n padding:${r.categoryPadding||"12px"};\n ">\n <div class="ws-category-title" style="font-weight:600;font-size:13px;margin-bottom:8px;color:${r.textColor||"#374151"};">${r.textCategories||"Categories"}</div>\n <button class="ws-search-cat-item ${n?"":"active"}" data-cat="" style="\n display:flex;justify-content:space-between;align-items:center;width:100%;\n padding:8px 12px;margin-bottom:4px;border:none;border-radius:6px;cursor:pointer;\n font-size:13px;transition:all 0.15s;text-align:left;\n background:${n?"transparent":r.categoryActiveBg||r.accentColor||"#6366f1"};\n color:${n?r.textColor||"#374151":r.categoryActiveText||"#fff"};\n ">\n <span>${r.textAll||"All"}</span>\n ${i.categoryShowCount?`<span style="opacity:0.7;font-size:11px;">${t}</span>`:""}\n </button>`;return e.slice(0,i.categoryMaxVisible).forEach(e=>{a+=`\n <button class="ws-search-cat-item ${n===e.name?"active":""}" data-cat="${Dn(e.name)}" style="\n display:flex;justify-content:space-between;align-items:center;width:100%;\n padding:8px 12px;margin-bottom:4px;border:none;border-radius:6px;cursor:pointer;\n font-size:13px;transition:all 0.15s;text-align:left;\n background:${n===e.name?r.categoryActiveBg||r.accentColor||"#6366f1":"transparent"};\n color:${n===e.name?r.categoryActiveText||"#fff":r.textColor||"#374151"};\n ">\n <span>${Dn(o(e.name))}</span>\n ${i.categoryShowCount?`<span style="opacity:0.7;font-size:11px;">${e.count}</span>`:""}\n </button>`}),a+='</div>\n <div class="ws-search-results-area" style="flex:1;min-width:0;">',a}(d,e.total,o,s,a)),"chips"===s.categoryDisplayMode&&d.length&&(c+=function(e,t,n,i){const o=n.styles||{};let r=`<div class="ws-search-categories">\n <button class="ws-search-cat-chip ${t?"":"active"}" data-cat="">${o.textAll||"All"}</button>`;return e.slice(0,n.categoryMaxVisible).forEach(e=>{r+=`\n <button class="ws-search-cat-chip ${t===e.name?"active":""}" data-cat="${Dn(e.name)}">\n ${Dn(i(e.name))}${n.categoryShowCount?` (${e.count})`:""}\n </button>`}),r+="</div>",r}(d,o,s,a)),"dropdown"===s.categoryDisplayMode&&d.length&&(c+=function(e,t,n,i){const o=i.styles||{};let r=`<div class="ws-search-category-dropdown" style="padding:8px 12px;border-bottom:1px solid ${o.borderColor||"#e5e7eb"};">\n <select class="ws-search-cat-select" style="\n width:${o.dropdownWidth||"100%"};\n padding:8px 12px;\n border:1px solid ${o.borderColor||"#d1d5db"};\n border-radius:${o.inputRadius||"6px"};\n background:${o.dropdownBg||o.inputBg||"#fff"};\n color:${o.textColor||"#374151"};\n font-size:14px;\n cursor:pointer;\n outline:none;\n ">\n <option value="">${o.textAll||"All"} ${o.textCategories||"Categories"} (${t})</option>`;return e.slice(0,i.categoryMaxVisible).forEach(e=>{r+=`\n <option value="${Dn(e.name)}" ${n===e.name?"selected":""}>\n ${Dn(e.name)}${i.categoryShowCount?` (${e.count})`:""}\n </option>`}),r+="</select></div>",r}(d,e.total,o,s)),c+='<div class="ws-search-items">',c+=e.hits.map((e,t)=>function(e,t,n,i,o){if(t.productCard)return function(e,t,n,i,o){const r=t.productCard,a=function(e){return{id:e.id,itemCode:e.itemCode,title:e.title,description:e.description,imageUrl:e.imageUrl||"",url:e.url||"#",price:e.price,originalPrice:e.originalPrice,discountRate:e.discountRate,inStock:e.inStock,categories:e.categories,brand:e.brand,rating:e.rating,reviewCount:e.reviewCount,isNew:e.isNew,isBestseller:e.isBestseller,isSale:e.originalPrice&&e.originalPrice>e.price}}(e),s={id:r.id,template:r.template,fields:r.fields||[],layoutType:r.layoutType,imagePosition:r.imagePosition,imageSize:r.imageSize,showBadges:r.showBadges,showButton:r.showButton,buttonText:r.buttonText,buttonStyle:r.buttonStyle,hoverEffect:r.hoverEffect,customCSS:r.customCSS,customHTML:r.customHTML,customJs:r.customJs,jsTiming:r.jsTiming||"immediate",jsEventName:r.jsEventName},l=Yn(a,s,{source:"search",formatPrice:i.formatPrice});return o&&s.customJs&&(Zn.has(o)||Zn.set(o,[]),Zn.get(o).push({template:s,unifiedProduct:a,productItemCode:e.itemCode||e.id})),`\n <div class="ws-search-item${n?" focused":""}" data-product-id="${e.itemCode||e.id}" data-selwise-card-container="${o||""}" style="display: block; cursor: pointer;">\n ${l}\n </div>\n `}(e,t,n,i,o);const r=t.styles||{},a="small"===t.imageSize?"40px":"large"===t.imageSize?"72px":"56px",s=t.highlightMatch&&e.highlights?.title?.[0]?e.highlights.title[0]:i.escapeHtml(e.title),l=e.imageUrl||"",c=e.itemCode||e.id,d=function(e,t){if(!e.boostReason)return"";const n=t.styles||{},i=n.boostBadgeBg||"#3b82f6",o=n.boostBadgeText||"#ffffff";if("pinned"===e.boostReason){const t=e.pinPosition||1;return`<span class="ws-boost-badge" style="\n display:inline-flex;\n align-items:center;\n gap:2px;\n padding:2px 6px;\n border-radius:4px;\n font-size:10px;\n font-weight:600;\n text-transform:uppercase;\n background:${i};\n color:${o};\n margin-left:6px;\n " title="Pinned to position ${t}">\n <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">\n <path d="M16 12V4H17V2H7V4H8V12L6 14V16H11.2V22H12.8V16H18V14L16 12Z"/>\n </svg>\n #${t}\n </span>`}return"boosted"===e.boostReason?`<span class="ws-boost-badge" style="\n display:inline-flex;\n align-items:center;\n gap:2px;\n padding:2px 6px;\n border-radius:4px;\n font-size:10px;\n font-weight:600;\n text-transform:uppercase;\n background:${i};\n color:${o};\n margin-left:6px;\n " title="Boosted by search rules">\n <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">\n <path d="M13 2L3 14H12L11 22L21 10H12L13 2Z"/>\n </svg>\n Boosted\n </span>`:""}(e,t),u=!1!==t.addToCartEnabled&&t.cartPlatform&&"none"!==t.cartPlatform?`<button class="product-card-button"\n ${Kn}="${Vn}"\n ${Jn}="${c}"\n onclick="event.stopPropagation();">\n Add to Cart\n </button>`:"";return`\n <a href="${e.url||"#"}" class="ws-search-item${n?" focused":""}" data-product-id="${c}"${e.boostReason?` data-boost-reason="${e.boostReason}"`:""}>\n ${t.showImages&&l?`\n <div class="ws-search-img-wrap" style="width:${"grid"!==t.resultLayout?a:"100%"};height:${"grid"!==t.resultLayout?a:r.imageHeight||"auto"};">\n <img src="${l}" alt="${i.escapeHtml(e.title)}" class="ws-search-img" style="width:100%;height:100%;" loading="lazy" onerror="this.style.display='none'" />\n ${r.imageOverlay?'<div class="ws-search-img-overlay"></div>':""}\n ${r.showOverlay?`\n <div class="ws-search-text-overlay pos-${r.overlayPosition||"bottom"}">\n <span class="ws-search-name" style="color:#fff;font-size:12px;">${s}${d}</span>\n ${t.showPrices?`<span class="ws-search-price" style="color:#fff;font-size:11px;">${i.formatPrice(e.price)}</span>`:""}\n </div>\n `:""}\n </div>\n `:""}\n <div class="ws-search-content">\n <p class="ws-search-name">${s}${d}</p>\n ${t.showDescription&&e.description?`<p class="ws-search-desc">${i.escapeHtml(e.description)}</p>`:""}\n ${t.showPrices?`\n <p>\n <span class="ws-search-price">${i.formatPrice(e.price)}</span>\n ${t.showOldPrice&&e.originalPrice&&e.originalPrice>e.price?`<span class="ws-search-old-price">${i.formatPrice(e.originalPrice)}</span>`:""}\n ${t.showDiscount&&e.discountRate?`<span class="ws-search-discount">-${Math.round(e.discountRate)}%</span>`:""}\n </p>\n `:""}\n ${t.showCategory&&e.categories?`<p class="ws-search-category">${i.escapeHtml(i.formatCategoryName(e.categories))}</p>`:""}\n ${t.showStock?`<span class="ws-search-stock ${e.inStock?"in-stock":"out-of-stock"}">${e.inStock?r.textInStock||"In Stock":r.textOutOfStock||"Out of Stock"}</span>`:""}\n ${u}\n </div>\n </a>\n `}(e,i,0===t,{formatPrice:r,escapeHtml:Dn,formatCategoryName:a},n)).join(""),c+="</div>",c+=`<div class="ws-search-footer">${Dn((l.textFooter||"{total} products found in {time}ms").replace("{total}",String(e.total)).replace("{time}",String(e.took)))}</div>`,"sidebar"===s.categoryDisplayMode&&d.length&&(c+="</div></div>"),c}class ti{constructor(e,t,n,i){this.config=null,this.suggestions=null,this.container=null,this.input=null,this.resultsContainer=null,this.debounceTimer=null,this.cache=new Map,this.cacheMaxAge=6e4,this.isOpen=!1,this.focusedIndex=-1,this.selectedCategory=null,this.overlayElement=null,this.searchOpenTime=null,this.lastQuery="",this.lastResultCount=0,this.abortController=null,this.boundHandleDocumentClick=null,this.boundHandleDocumentKeydown=null,this.boundHandleHotkey=null,this.boundHandleClearClick=null,this.clearButtonEl=null,this.spaObserver=null,this.isDestroyed=!1,this.getOrCreateVisitorId=Ct,this.getStoredSiteUserId=kt,this.generateEventId=It,this.apiUrl=e,this.siteKey=t,this.sessionId=vt(),this.experimentManager=n,this.segmentManager=i}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.boundHandleDocumentClick&&(document.removeEventListener("click",this.boundHandleDocumentClick),this.boundHandleDocumentClick=null),this.boundHandleDocumentKeydown&&(document.removeEventListener("keydown",this.boundHandleDocumentKeydown),this.boundHandleDocumentKeydown=null),this.boundHandleHotkey&&(document.removeEventListener("keydown",this.boundHandleHotkey),this.boundHandleHotkey=null),this.boundHandleClearClick&&this.clearButtonEl&&this.clearButtonEl.removeEventListener("click",this.boundHandleClearClick),this.boundHandleClearClick=null,this.clearButtonEl=null,this.spaObserver&&(this.spaObserver.disconnect(),this.spaObserver=null),this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.overlayElement&&this.overlayElement.parentNode&&this.overlayElement.parentNode.removeChild(this.overlayElement),this.cache.clear(),this.container=null,this.input=null,this.resultsContainer=null,this.overlayElement=null,this.config=null,this.suggestions=null,G("WidgetSearch","Module destroyed and cleaned up"))}getAPIConfig(){return{apiUrl:this.apiUrl,siteKey:this.siteKey}}async init(){try{if(this.config=await async function(e,t){try{const n=await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/search-config`);if(!n.ok)return null;let i=await n.json();if(t){const e=t.getAssignmentByTargetType("search_config");if("different_module"===e?.experimentMode&&void 0!==e?.moduleData)return W("WidgetSearch","Search excluded by experiment (different_module mode - variant available)"),null;if(e&&"different_module"!==e.experimentMode){const n=Wt(e);n&&(W("WidgetSearch","Applying experiment override:",e.variantName),i=qt(i,n),t.trackImpression(e.experimentId))}}W("WidgetSearch","Config loaded:",i);const o=(0,zn.validateSearchConfig)({position:i.position,floatingPosition:i.floatingPosition,categoryDisplayMode:i.categoryDisplayMode,resultLayout:i.resultLayout,imageSize:i.imageSize,imagePosition:i.imagePosition,animationType:i.animationType,stylesJson:i.styles,suggestionStylesJson:i.suggestionStyles});return o.valid?(i.styles=(0,zn.sanitizeSearchStyles)(i.styles),i.suggestionStyles&&(i.suggestionStyles=(0,zn.sanitizeSuggestionStyles)(i.suggestionStyles)),i):(G("WidgetSearch","Invalid search config received:",o.message),null)}catch{return null}}(this.getAPIConfig(),this.experimentManager),!this.config?.enabled)return void G("WidgetSearch","Search module disabled");if(this.config.isTestMode){if("undefined"==typeof localStorage||"true"!==localStorage.getItem(h))return void G("WidgetSearch",`Search is in test mode. Run localStorage.setItem('${h}', 'true') to view.`);G("WidgetSearch","Test mode enabled, showing search widget")}if(this.segmentManager&&this.config.segmentTargetingMode&&this.config.segmentIds&&!await this.segmentManager.shouldShow(this.config.segmentTargetingMode,this.config.segmentIds))return void G("WidgetSearch","Search module hidden due to segment targeting");this.suggestions=await async function(e){try{const t=await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/search/suggestions`);if(!t.ok)return null;const n=await t.json();return n&&n.styles&&(n.styles=(0,zn.sanitizeSuggestionStyles)(n.styles)),W("WidgetSearch","Suggestions loaded:",n),n}catch(e){return G("WidgetSearch","Failed to load suggestions:",e),null}}(this.getAPIConfig()),function(e,t){if(document.getElementById("ws-search-styles"))return;const n=document.createElement("style");n.id="ws-search-styles",n.textContent=function(e,t){const n=e,i=n.styles||{},o=t,r={small:"40px",medium:"56px",large:"72px"}[n.imageSize]||"56px";return`\n /* Base Wrapper */\n .ws-search-wrapper {\n position: relative;\n font-family: ${i.fontFamily||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'};\n z-index: 999999;\n box-sizing: border-box;\n }\n .ws-search-wrapper * { box-sizing: border-box; }\n .ws-search-wrapper svg {\n display: inline-block;\n vertical-align: middle;\n overflow: visible;\n }\n\n /* Input */\n .ws-search-input-wrap { position: relative; }\n .ws-search-input {\n width: 100%;\n padding: 12px 16px 12px ${!1!==i.inputIcon?"44px":"16px"};\n border-width: ${i.inputBorderWidth||"2px"};\n border-style: solid;\n border-color: ${i.inputBorder||"#e5e7eb"};\n border-radius: ${i.inputRadius||"8px"};\n font-size: ${"large"===i.inputSize?"16px":"xlarge"===i.inputSize?"18px":"14px"};\n color: ${i.textColor||"#1f2937"};\n background: ${i.inputBg||"#f9fafb"};\n outline: none;\n transition: all 0.2s ease;\n }\n .ws-search-input.no-icon { padding-left: 16px; }\n \n .ws-search-input:focus {\n border-color: ${i.inputFocus||i.accentColor||"#6366f1"};\n background: ${i.backgroundColor||"#ffffff"};\n box-shadow: 0 0 0 3px ${i.inputFocus||i.accentColor||"#6366f1"}20;\n }\n .ws-search-input::placeholder { color: #9ca3af; }\n\n .ws-search-icon {\n position: absolute;\n left: 14px;\n top: 50%;\n transform: translateY(-50%);\n width: 20px;\n height: 20px;\n color: ${i.accentColor||"#9ca3af"};\n pointer-events: none;\n display: ${!1!==i.inputIcon?"block":"none"};\n }\n\n .ws-search-clear {\n position: absolute;\n right: 12px;\n top: 50%;\n transform: translateY(-50%);\n width: 24px;\n height: 24px;\n background: #f3f4f6;\n border: none;\n border-radius: 50%;\n cursor: pointer;\n display: none;\n align-items: center;\n justify-content: center;\n color: #6b7280;\n }\n .ws-search-clear:hover { background: #e5e7eb; color: #374151; }\n .ws-search-wrapper.has-value .ws-search-clear { display: flex; }\n\n /* Results Container */\n .ws-search-results {\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n margin-top: 8px;\n background: ${i.backgroundColor||"#ffffff"};\n border-radius: ${i.containerRadius||"12px"};\n box-shadow: ${Nn(i.containerShadow||"lg")};\n max-height: ${i.maxHeight||"400px"};\n overflow-y: auto;\n display: none;\n z-index: 1000000;\n border: ${i.containerBorder?"1px solid "+(i.borderColor||"#e5e7eb"):"none"};\n }\n .ws-search-results.open {\n display: block;\n animation: wsSearchFadeIn ${n.animationDuration}ms ease;\n }\n\n @keyframes wsSearchFadeIn {\n from { opacity: 0; transform: translateY(-8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n @keyframes wsSearchSlideIn {\n from { opacity: 0; transform: translateX(100%); }\n to { opacity: 1; transform: translateX(0); }\n }\n @keyframes wsSearchScaleIn {\n from { opacity: 0; transform: scale(0.95); }\n to { opacity: 1; transform: scale(1); }\n }\n\n /* Result Items - Base Shared */\n .ws-search-item {\n display: flex;\n align-items: center;\n cursor: pointer;\n transition: background 0.15s ease;\n text-decoration: none;\n color: inherit;\n }\n .ws-search-item:hover,\n .ws-search-item.focused {\n background: ${i.itemHoverBg||i.resultHoverBg||"#f9fafb"};\n }\n .ws-search-item:not(:last-child) {\n border-bottom: ${!1!==i.resultDivider?"1px solid "+(i.borderColor||"#f3f4f6"):"none"};\n }\n \n /* Layout: List (Standard) */\n .ws-search-results.layout-list .ws-search-item {\n gap: ${i.itemGap||"12px"};\n padding: ${i.itemPadding||"12px"} 16px;\n }\n\n /* Layout: Compact (Dense) */\n .ws-search-results.layout-compact .ws-search-item {\n gap: 8px;\n padding: 8px 12px;\n }\n .ws-search-results.layout-compact .ws-search-img {\n width: 32px;\n height: 32px;\n border-radius: ${i.imageRadius||"4px"};\n }\n .ws-search-results.layout-compact .ws-search-desc { display: none; }\n .ws-search-results.layout-compact .ws-search-price { font-size: 13px; }\n .ws-search-results.layout-compact .ws-search-name { font-size: 13px; margin: 0; }\n \n /* Layout: Large (Prominent) */\n .ws-search-results.layout-large .ws-search-item {\n gap: 16px;\n padding: 20px;\n }\n .ws-search-results.layout-large .ws-search-img {\n width: 80px;\n height: 80px;\n }\n .ws-search-results.layout-large .ws-search-name {\n font-size: 16px;\n margin-bottom: 6px;\n }\n .ws-search-results.layout-large .ws-search-desc {\n -webkit-line-clamp: 3;\n line-clamp: 3;\n }\n\n /* Grid Layout */\n .ws-search-results.layout-grid .ws-search-items {\n display: grid;\n grid-template-columns: repeat(${i.gridColumns||2}, 1fr);\n gap: ${i.gridGap||"16px"};\n padding: 12px;\n }\n .ws-search-results.layout-grid .ws-search-item {\n flex-direction: column;\n padding: ${i.itemPadding||"16px"};\n border-radius: ${i.itemRadius||"12px"};\n border: 1px solid ${i.borderColor||"#e5e7eb"};\n box-shadow: ${Nn(i.itemShadow||"sm")};\n }\n .ws-search-results.layout-grid .ws-search-item:hover {\n box-shadow: ${Nn(i.itemHoverShadow||"lg")};\n ${i.itemHoverScale?"transform: scale(1.02);":""}\n }\n\n /* Image */\n .ws-search-img {\n width: ${r};\n height: ${r};\n height: ${r};\n object-fit: ${i.imageObjectFit||"cover"};\n border-radius: ${"grid"===n.resultLayout?"0":i.imageRadius||"8px"};\n border: ${i.imageBorder?"1px solid "+(i.borderColor||"#e5e7eb"):"none"};\n aspect-ratio: ${i.cardAspect&&"auto"!==i.cardAspect?i.cardAspect:"auto"};\n background: #f3f4f6;\n flex-shrink: 0;\n }\n .ws-search-results.layout-grid .ws-search-img {\n width: 100%;\n height: ${i.imageHeight||"100px"};\n }\n\n /* Image Overlay & Text Overlay */\n .ws-search-img-wrap {\n position: relative;\n overflow: hidden;\n border-radius: ${"grid"===n.resultLayout?"0":i.imageRadius||"8px"};\n flex-shrink: 0;\n }\n .ws-search-img-overlay {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.4);\n pointer-events: none;\n }\n .ws-search-text-overlay {\n position: absolute;\n left: 0; right: 0;\n padding: 8px;\n background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);\n color: #fff;\n display: flex;\n flex-direction: column;\n justify-content: flex-end;\n }\n .ws-search-text-overlay.pos-bottom { bottom: 0; height: 50%; }\n .ws-search-text-overlay.pos-full { top: 0; bottom: 0; justify-content: flex-end; }\n .ws-search-text-overlay.pos-center { top: 0; bottom: 0; justify-content: center; align-items: center; text-align: center; }\n\n /* Content */\n .ws-search-content { flex: 1; min-width: 0; }\n .ws-search-name {\n font-weight: ${i.titleWeight||"medium"};\n font-size: ${i.titleSize||"14px"};\n color: ${i.textColor||"#1f2937"};\n margin: 0 0 4px 0;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .ws-search-name mark {\n background: ${i.highlightBg||"#fef08a"};\n color: ${i.highlightText||"inherit"};\n padding: 0 2px;\n border-radius: ${i.highlightRadius||"2px"};\n }\n .ws-search-desc {\n font-size: ${i.descSize||"12px"};\n color: #6b7280;\n margin: 0;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: ${"large"===n.resultLayout?3:2};\n -webkit-box-orient: vertical;\n font-size: ${i.descSize||"12px"};\n color: #6b7280;\n }\n .ws-search-price {\n font-weight: 600;\n font-size: ${i.priceSize||"14px"};\n color: ${i.priceColor||i.accentColor||"#059669"};\n }\n .ws-search-old-price {\n font-size: 12px;\n color: ${i.originalPriceColor||"#9ca3af"};\n text-decoration: line-through;\n margin-left: 6px;\n }\n .ws-search-discount {\n display: inline-block;\n background: ${i.discountBadgeBg||"#dc2626"};\n color: ${i.discountBadgeText||"#fff"};\n font-size: 11px;\n font-weight: 600;\n padding: 2px 6px;\n border-radius: ${i.badgeRadius||"4px"};\n margin-left: 6px;\n }\n .ws-search-category {\n font-size: 11px;\n color: #9ca3af;\n margin-top: 4px;\n }\n .ws-search-stock {\n font-size: 11px;\n padding: 2px 6px;\n border-radius: 4px;\n margin-top: 4px;\n display: inline-block;\n }\n .ws-search-stock.in-stock { background: #dcfce7; color: #166534; }\n .ws-search-stock.out-of-stock { background: #fee2e2; color: #991b1b; }\n\n /* Loading & Empty */\n .ws-search-loading, .ws-search-empty {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 32px 24px;\n color: #6b7280;\n text-align: center;\n }\n .ws-search-spinner {\n width: 24px;\n height: 24px;\n border: 2px solid #e5e7eb;\n border-top-color: ${i.accentColor||"#6366f1"};\n border-radius: 50%;\n animation: wsSearchSpin 0.8s linear infinite;\n margin-bottom: 12px;\n }\n @keyframes wsSearchSpin { to { transform: rotate(360deg); } }\n\n /* Footer */\n .ws-search-footer {\n padding: 10px 16px;\n background: #f9fafb;\n border-top: 1px solid #f3f4f6;\n font-size: 11px;\n color: #9ca3af;\n text-align: center;\n }\n\n /* Category Chips */\n .ws-search-categories {\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n padding: 12px 16px;\n border-bottom: 1px solid #f3f4f6;\n }\n .ws-search-cat-chip {\n padding: 6px 12px;\n border-radius: 9999px;\n font-size: 12px;\n font-weight: 500;\n background: #f3f4f6;\n color: #4b5563;\n border: none;\n cursor: pointer;\n transition: all 0.15s;\n }\n .ws-search-cat-chip:hover { background: #e5e7eb; }\n .ws-search-cat-chip.active {\n background: ${i.categoryActiveBg||i.accentColor||"#6366f1"};\n color: ${i.categoryActiveText||"#fff"};\n }\n .ws-search-cat-chip {\n padding: ${i.categoryPadding||"6px 12px"};\n border-radius: ${i.categoryRadius||"9999px"};\n font-size: 12px;\n font-weight: 500;\n background: ${i.inputBg||"#f3f4f6"};\n color: ${i.textColor||"#4b5563"};\n border: none;\n cursor: pointer;\n transition: all 0.15s;\n }\n\n /* Overlay (Modal/Fullscreen/Sidebar) */\n .ws-search-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0,0,0,${(i.overlayOpacity||50)/100});\n display: none;\n align-items: flex-start;\n justify-content: center;\n padding-top: 100px;\n z-index: 9999999;\n }\n .ws-search-overlay.open { display: flex; }\n .ws-search-overlay.position-fullscreen {\n padding: 0;\n align-items: stretch;\n z-index: 99999999; /* Higher for fullscreen */\n }\n .ws-search-overlay.position-sidebar {\n justify-content: flex-end;\n padding: 0;\n }\n\n /* Modal */\n .ws-search-modal {\n width: 90%;\n max-width: ${i.modalWidth||"600px"};\n max-height: ${i.modalMaxHeight||"80vh"};\n background: ${i.backgroundColor||"#fff"};\n border-radius: ${i.modalRadius||i.containerRadius||"12px"};\n box-shadow: ${i.modalShadow||"0 25px 50px -12px rgba(0,0,0,0.25)"};\n animation: wsSearchScaleIn ${n.animationDuration}ms ease;\n overflow: hidden;\n display: flex;\n flex-direction: column;\n position: relative; /* Context context */\n }\n .ws-search-modal .ws-search-results {\n position: static;\n margin: 0;\n box-shadow: none;\n border-top: 1px solid ${i.borderColor||"#e5e7eb"};\n border-radius: 0;\n flex: 1;\n }\n\n /* Inline Container for Inline Mode */\n ${"inline"===n.position?`\n ${n.selector||""} .ws-search-container {\n box-shadow: none;\n max-width: 100%;\n border-radius: ${i.inputRadius||"8px"};\n padding: ${i.inputPaddingTop||0} ${i.inputPaddingRight||0} ${i.inputPaddingBottom||0} ${i.inputPaddingLeft||0};\n margin: ${i.inputMarginTop||0} ${i.inputMarginRight||0} ${i.inputMarginBottom||0} ${i.inputMarginLeft||0};\n border-width: ${i.inputBorderWidth||"1px"};\n border-style: ${i.inputBorderStyle||"solid"};\n border-color: ${i.inputBorderColor||"transparent"};\n background: transparent;\n position: relative;\n }\n ${n.selector||""} .ws-search-results {\n width: ${i.resultsWidth||"100%"};\n ${i.resultsWidth?"right: auto;":""}\n }\n `:""}\n\n /* Fullscreen */\n .ws-search-fullscreen {\n width: 100%;\n height: 100%;\n background: ${i.backgroundColor||"#fff"};\n display: flex;\n flex-direction: column;\n animation: wsSearchFadeIn ${n.animationDuration}ms ease;\n }\n .ws-search-fullscreen .ws-search-input-wrap { padding: 24px; }\n .ws-search-fullscreen .ws-search-results {\n position: static;\n margin: 0;\n box-shadow: none;\n flex: 1;\n max-height: none;\n border-radius: 0;\n }\n\n /* Sidebar Panel */\n .ws-search-sidebar-panel {\n width: ${i.sidebarWidth||i.panelWidth||"480px"};\n max-width: 100%;\n height: 100%;\n background: ${i.backgroundColor||"#fff"};\n box-shadow: ${i.sidebarShadow||"-10px 0 40px rgba(0,0,0,0.15)"};\n animation: wsSearchSlideIn ${n.animationDuration}ms ease;\n display: flex;\n flex-direction: column;\n }\n .ws-search-sidebar-panel .ws-search-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px 20px;\n border-bottom: 1px solid ${i.borderColor||"#e5e7eb"};\n }\n .ws-search-sidebar-panel .ws-search-input-wrap { padding: 16px 20px; }\n .ws-search-sidebar-panel .ws-search-results {\n position: static;\n margin: 0;\n box-shadow: none;\n flex: 1;\n max-height: none;\n border-radius: 0;\n }\n\n /* Floating Button */\n .ws-search-floating-btn {\n position: fixed;\n width: ${i.floatingButtonSize||"56px"};\n height: ${i.floatingButtonSize||"56px"};\n background: ${i.floatingButtonBg||i.accentColor||"#6366f1"};\n border: ${i.floatingButtonBorder||"none"};\n border-radius: ${i.floatingButtonRadius||"50%"};\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: ${Nn(i.floatingButtonShadow||"lg",i.floatingButtonShadowColor)};\n padding: ${i.floatingButtonPaddingTop||0} ${i.floatingButtonPaddingRight||0} ${i.floatingButtonPaddingBottom||0} ${i.floatingButtonPaddingLeft||0};\n margin: ${i.floatingButtonMarginTop||0} ${i.floatingButtonMarginRight||0} ${i.floatingButtonMarginBottom||0} ${i.floatingButtonMarginLeft||0};\n transition: all 0.2s ease;\n z-index: 999998;\n }\n .ws-search-floating-btn.ws-embedded {\n position: static;\n transform: none !important;\n z-index: auto;\n /* Respect configured margin even if embedded, unless user explicitly sets it to 0 */\n /* But wait, embedded might need resetting. Let's just inherit the margin defined above if it's not 0 */\n }\n .ws-search-floating-btn:hover {\n transform: scale(1.05);\n box-shadow: ${Nn(i.floatingButtonHoverShadow||"xl",i.floatingButtonShadowColor)};\n }\n .ws-search-floating-btn.ws-embedded:hover {\n transform: scale(1.05);\n }\n .ws-search-floating-btn svg { width: 24px; height: 24px; color: ${i.floatingButtonIconColor||"#fff"}; }\n .ws-search-floating-btn.bottom-right { bottom: ${i.floatingButtonOffset||"24px"}; right: ${i.floatingButtonOffset||"24px"}; }\n .ws-search-floating-btn.bottom-left { bottom: ${i.floatingButtonOffset||"24px"}; left: ${i.floatingButtonOffset||"24px"}; }\n .ws-search-floating-btn.top-right { top: ${i.floatingButtonOffset||"24px"}; right: ${i.floatingButtonOffset||"24px"}; }\n .ws-search-floating-btn.top-left { top: ${i.floatingButtonOffset||"24px"}; left: ${i.floatingButtonOffset||"24px"}; }\n\n /* Close Button */\n .ws-search-close {\n width: 32px;\n height: 32px;\n background: transparent;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #6b7280;\n transition: all 0.15s;\n }\n .ws-search-close:hover { background: #f3f4f6; color: #1f2937; }\n\n /* Mobile Responsive */\n @media (max-width: 640px) {\n .ws-search-modal { max-width: 100%; width: 100%; margin: 0; border-radius: 0; }\n .ws-search-sidebar-panel { width: 100%; }\n }\n \n /* Animations */\n @keyframes ws-fade-in { from { opacity: 0; } to { opacity: 1; } }\n @keyframes ws-slide-up { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }\n @keyframes ws-scale-up { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }\n\n .ws-search-overlay.anim-fade { animation: ws-fade-in ${n.animationDuration||200}ms ease-out forwards; }\n .ws-search-overlay.anim-slide { animation: ws-slide-up ${n.animationDuration||200}ms ease-out forwards; }\n .ws-search-overlay.anim-scale { animation: ws-scale-up ${n.animationDuration||200}ms ease-out forwards; }\n \n /* Container specific animations for inline/dropdown */\n .ws-search-results.anim-fade { animation: ws-fade-in ${n.animationDuration||200}ms ease-out forwards; }\n .ws-search-results.anim-slide { animation: ws-slide-up ${n.animationDuration||200}ms ease-out forwards; }\n .ws-search-results.anim-scale { animation: ws-scale-up ${n.animationDuration||200}ms ease-out forwards; }\n\n /* ========== Suggestions Styles (Modern & Beautiful) ========== */\n .ws-suggestions {\n padding: 0 !important;\n margin: 0 !important;\n box-sizing: border-box !important;\n list-style: none !important;\n background: transparent !important;\n }\n .ws-suggestions * {\n box-sizing: border-box !important;\n list-style: none !important;\n }\n \n .ws-suggestions-section {\n padding: ${o.sectionSpacing||"16px"} 0 !important;\n border-bottom: ${!1!==o.sectionDivider?"1px solid "+(o.sectionDividerColor||i.borderColor||"#f3f4f6"):"none"} !important;\n margin: 0 !important;\n background: transparent !important;\n }\n .ws-suggestions-section:last-child { \n border-bottom: none !important;\n padding-bottom: 8px !important;\n }\n .ws-suggestions-section:first-child {\n padding-top: 8px !important;\n }\n \n .ws-suggestions-header {\n display: flex !important;\n align-items: center !important;\n justify-content: space-between !important;\n padding: 0 ${o.sectionHeaderPadding||"20px"} 12px !important;\n margin: 0 0 4px 0 !important;\n background: transparent !important;\n border: none !important;\n }\n .ws-suggestions-header span {\n font-size: ${o.sectionHeaderSize||"11px"} !important;\n font-weight: ${o.sectionHeaderWeight||"600"} !important;\n color: ${o.sectionHeaderColor||"#9ca3af"} !important;\n text-transform: uppercase !important;\n letter-spacing: 0.08em !important;\n margin: 0 !important;\n padding: 0 !important;\n line-height: 1.4 !important;\n }\n \n .ws-suggestions-clear {\n font-size: 12px !important;\n font-weight: 500 !important;\n color: ${o.recentClearColor||i.accentColor||"#6366f1"} !important;\n background: transparent !important;\n border: none !important;\n cursor: pointer !important;\n padding: 4px 10px !important;\n border-radius: 6px !important;\n text-transform: none !important;\n letter-spacing: normal !important;\n transition: all 0.15s ease !important;\n margin: 0 !important;\n line-height: 1.4 !important;\n }\n .ws-suggestions-clear:hover { \n background: ${o.recentClearColor||i.accentColor||"#6366f1"}15 !important;\n }\n \n /* Recent & Popular Search Items */\n .ws-suggestion-item {\n display: flex !important;\n align-items: center !important;\n gap: 14px !important;\n padding: 12px 20px !important;\n cursor: pointer !important;\n transition: all 0.15s ease;\n color: ${o.recentTextColor||i.textColor||"#374151"};\n text-decoration: none;\n border-radius: 0;\n margin: 0;\n box-sizing: border-box;\n }\n .ws-suggestion-item:hover { \n background: ${o.recentHoverBg||i.itemHoverBg||"#f8fafc"};\n }\n .ws-suggestion-item svg { \n width: 18px !important; \n height: 18px !important; \n min-width: 18px;\n min-height: 18px;\n max-width: 18px;\n max-height: 18px;\n color: ${o.recentIconColor||"#d1d5db"}; \n flex-shrink: 0;\n transition: color 0.15s ease;\n }\n .ws-suggestion-item:hover svg {\n color: ${o.recentIconColor||i.accentColor||"#6366f1"};\n }\n .ws-suggestion-text { \n flex: 1; \n font-size: 14px;\n font-weight: 400;\n color: ${o.recentTextColor||i.textColor||"#374151"};\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .ws-suggestion-remove {\n opacity: 0;\n padding: 6px;\n border: none;\n background: transparent;\n cursor: pointer;\n color: #9ca3af;\n border-radius: 6px;\n transition: all 0.15s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .ws-suggestion-item:hover .ws-suggestion-remove { opacity: 1; }\n .ws-suggestion-remove:hover { \n background: #fef2f2; \n color: #ef4444;\n }\n .ws-suggestion-remove svg {\n width: 14px !important;\n height: 14px !important;\n min-width: 14px;\n min-height: 14px;\n color: inherit !important;\n }\n \n /* Popular Search specific */\n .ws-popular-search-item svg {\n color: ${o.popularSearchIconColor||"#fbbf24"} !important;\n }\n .ws-popular-search-item:hover svg {\n color: ${o.popularSearchIconColor||"#f59e0b"} !important;\n }\n .ws-popular-search-item .ws-suggestion-text {\n color: ${o.popularSearchTextColor||i.textColor||"#374151"};\n }\n\n /* Popular Categories Grid - Modern Card Style */\n .ws-popular-categories {\n display: grid;\n grid-template-columns: repeat(${o.categoryColumns||"auto-fill"}, minmax(${o.categoryColumns?"1fr":"90px"}, 1fr));\n gap: ${o.categoryGap||"10px"};\n padding: 0 20px;\n }\n .ws-category-card {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 10px;\n padding: 16px 12px;\n border-radius: ${o.categoryCardRadius||"12px"};\n background: ${o.categoryCardBg||"#f8fafc"};\n border: 1px solid ${o.categoryCardBorder||"transparent"};\n cursor: pointer;\n transition: all 0.2s ease;\n text-decoration: none;\n color: inherit;\n box-shadow: ${o.categoryCardShadow||"none"};\n }\n .ws-category-card:hover {\n background: ${o.categoryCardHoverBg||"#f1f5f9"};\n border-color: ${o.categoryCardHoverBorder||i.accentColor||"#6366f1"};\n transform: translateY(-2px);\n box-shadow: 0 4px 12px rgba(0,0,0,0.08);\n }\n .ws-category-img {\n width: ${o.categoryImageSize||"48px"};\n height: ${o.categoryImageSize||"48px"};\n border-radius: ${o.categoryImageRadius||"10px"};\n object-fit: cover;\n background: ${o.categoryImageBg||"#e2e8f0"};\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .ws-category-img svg {\n width: 22px !important;\n height: 22px !important;\n color: #94a3b8;\n }\n .ws-category-name {\n font-size: ${o.categoryNameSize||"12px"};\n font-weight: 500;\n text-align: center;\n color: ${o.categoryNameColor||i.textColor||"#475569"};\n line-height: 1.3;\n max-width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n }\n\n /* Popular Products - Premium Card Style */\n .ws-popular-products {\n display: grid;\n grid-template-columns: repeat(${o.productColumns||"auto-fill"}, minmax(${o.productColumns?"1fr":"140px"}, 1fr));\n gap: ${o.productGap||"12px"};\n padding: 0 20px;\n }\n .ws-product-card {\n display: flex;\n flex-direction: column;\n border-radius: ${o.productCardRadius||"12px"};\n background: ${o.productCardBg||"#ffffff"};\n border: 1px solid ${o.productCardBorder||"#e2e8f0"};\n overflow: hidden;\n cursor: pointer;\n transition: all 0.2s ease;\n text-decoration: none;\n color: inherit;\n box-shadow: ${o.productCardShadow||"0 1px 3px rgba(0,0,0,0.04)"};\n }\n .ws-product-card:hover {\n border-color: ${o.productCardHoverBorder||i.accentColor||"#6366f1"};\n box-shadow: ${o.productCardHoverShadow||"0 8px 24px rgba(0,0,0,0.12)"};\n transform: translateY(-3px);\n }\n .ws-product-card-img {\n width: 100%;\n height: ${o.productImageHeight||"100px"};\n object-fit: cover;\n background: ${o.productImageBg||"#f8fafc"};\n }\n .ws-product-card-img svg {\n width: 28px !important;\n height: 28px !important;\n }\n .ws-product-card-info {\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .ws-product-card-name {\n font-size: ${o.productNameSize||"13px"};\n font-weight: 500;\n color: ${o.productNameColor||i.textColor||"#1e293b"};\n margin: 0;\n line-height: 1.4;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n }\n .ws-product-card-prices {\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n .ws-product-card-price {\n font-size: ${o.productPriceSize||"15px"};\n font-weight: 700;\n color: ${o.productPriceColor||i.priceColor||"#059669"};\n }\n .ws-product-card-old-price {\n font-size: 12px;\n font-weight: 400;\n color: ${o.productOldPriceColor||"#9ca3af"};\n text-decoration: line-through;\n }\n .ws-product-card-discount {\n position: absolute;\n top: 8px;\n left: 8px;\n font-size: 11px;\n font-weight: 600;\n color: #ffffff;\n background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);\n padding: 3px 8px;\n border-radius: 6px;\n box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3);\n }\n .ws-product-card-img-wrap {\n position: relative;\n overflow: hidden;\n }\n\n /* Custom CSS */\n ${i.customCss||""}\n `}(e,t),document.head.appendChild(n)}(this.config,this.getSuggestionStyles()),this.render(),this.attachEventListeners(),this.setupHotkey(),this.setupSpaNavigationWatcher(),G("WidgetSearch","Search module initialized")}catch(e){K("WidgetSearch","Failed to initialize:",e)}}getSuggestionStyles(){return this.suggestions?.styles||{}}setupSpaNavigationWatcher(){W("WidgetSearch","Setting up SPA watcher, position:",this.config?.position);const e=new WeakSet;this.spaObserver&&(this.spaObserver.disconnect(),this.spaObserver=null);const t=new MutationObserver(()=>{const t=this.config?.position;if("inline"===t&&(this.container&&!document.body.contains(this.container)&&(this.container=null,W("WidgetSearch","Inline container was removed")),!this.container&&this.config?.selector)&&document.querySelector(this.config.selector)){W("WidgetSearch","Re-rendering inline search");const e=Wn(this.config,()=>this.attachEventListeners());e&&(this.container=e.container,this.input=e.input,this.resultsContainer=e.resultsContainer,this.attachEventListeners())}if("modal"===t||"floating"===t||"sidebar"===t){const t=this.config?.triggerSelector;t&&document.querySelectorAll(t).forEach(n=>{if(!e.has(n)){e.add(n),n.addEventListener("click",e=>{e.preventDefault(),this.openOverlay()});const i=this.experimentManager?.getAssignmentByTargetType("search_config");i&&this.experimentManager?.trackEvent("search_instant_open",{experimentId:i.experimentId,variant:i.variantId,position:this.config?.position}),W("WidgetSearch","Re-attached trigger listener to:",t);const o=document.querySelector(".ws-search-floating-btn:not(.ws-embedded)");o&&(o.remove(),W("WidgetSearch","Removed fallback floating button"))}})}});t.observe(document.body,{childList:!0,subtree:!0}),this.spaObserver=t,W("WidgetSearch","SPA watcher active for all modes")}render(){if(!this.config)return;const e=e=>{!function(e,t,n){if(!e)return;let i=!1;if(e.triggerSelector){const n=document.querySelectorAll(e.triggerSelector);if(!(n.length>0))return void W("WidgetSearch","Trigger selector configured but not found, waiting for SPA watcher");i=!0,n.forEach(e=>{e.addEventListener("click",e=>{e.preventDefault(),t()})})}if(!i&&!e.triggerSelector){const i=document.createElement("button");i.innerHTML=n(),i.addEventListener("click",e=>{e.preventDefault(),t()});const o=e.styles?.floatingButtonSelector,r=e.styles?.floatingButtonInjectionMode||"append";if(o){const t=document.querySelector(o);if(t)switch(i.className="ws-search-floating-btn ws-embedded",r){case"prepend":t.insertBefore(i,t.firstChild);break;case"before":t.parentNode?.insertBefore(i,t);break;case"after":t.parentNode?.insertBefore(i,t.nextSibling);break;case"replace":t.replaceWith(i);break;default:t.appendChild(i)}else i.className=`ws-search-floating-btn ${e.floatingPosition||"bottom-right"}`,document.body.appendChild(i)}else i.className=`ws-search-floating-btn ${e.floatingPosition||"bottom-right"}`,document.body.appendChild(i)}}(this.config,e,Rn)};let t;switch(this.config.position){case"inline":t=Wn(this.config,()=>this.attachEventListeners());break;case"modal":t=Gn(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e);break;case"floating":t=function(e,t,n,i){return Gn(e,t,n,i)}(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e);break;case"sidebar":t=function(e,t,n,i,o){i(t);const r=document.createElement("div");r.className="ws-search-overlay position-sidebar",r.addEventListener("click",e=>{e.target===r&&n()});const a=document.createElement("div");a.className="ws-search-sidebar-panel";const s=e.styles||{};a.innerHTML=`\n <div class="ws-search-header">\n <span style="font-weight: 600; font-size: 16px;">${s.textSearchHeader||"Search"}</span>\n <button class="ws-search-close">${o(20)}</button>\n </div>\n `,a.querySelector(".ws-search-close")?.addEventListener("click",()=>n());const l=Hn(e,{showSearchIcon:!1,showCloseIcon:!0,getSearchIcon:Rn,getCloseIcon:Ln}),c=l.querySelector(".ws-search-input"),d=l.querySelector(".ws-search-results");return a.appendChild(l),r.appendChild(a),document.body.appendChild(r),{container:l,input:c,resultsContainer:d,overlayElement:r}}(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e,Ln);break;case"fullscreen":t=function(e,t,n,i,o){i(t);const r=document.createElement("div");r.className="ws-search-overlay position-fullscreen";const a=document.createElement("div");a.className="ws-search-fullscreen",a.innerHTML=`\n <div class="ws-search-header" style="display:flex;justify-content:flex-end;padding:16px 24px;">\n <button class="ws-search-close">${o(24)}</button>\n </div>\n `,a.querySelector(".ws-search-close")?.addEventListener("click",()=>n());const s=Hn(e,{showSearchIcon:!0,showCloseIcon:!1,getSearchIcon:Rn,getCloseIcon:Ln}),l=s.querySelector(".ws-search-input"),c=s.querySelector(".ws-search-results");return a.appendChild(s),r.appendChild(a),document.body.appendChild(r),{container:s,input:l,resultsContainer:c,overlayElement:r}}(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e,Ln);break;default:return}t&&(this.container=t.container,this.overlayElement=t.overlayElement||null,this.input=t.input,this.resultsContainer=t.resultsContainer)}attachEventListeners(){this.input&&this.resultsContainer&&(this.boundHandleDocumentClick&&(document.removeEventListener("click",this.boundHandleDocumentClick),this.boundHandleDocumentClick=null),this.boundHandleDocumentKeydown&&(document.removeEventListener("keydown",this.boundHandleDocumentKeydown),this.boundHandleDocumentKeydown=null),this.input.addEventListener("input",e=>this.handleInput(e)),this.input.addEventListener("focus",()=>this.handleFocus()),this.input.addEventListener("keydown",e=>this.handleKeydown(e)),this.boundHandleClearClick&&this.clearButtonEl&&this.clearButtonEl.removeEventListener("click",this.boundHandleClearClick),this.boundHandleClearClick=null,this.clearButtonEl=this.container?.querySelector(".ws-search-clear")||null,this.clearButtonEl&&(this.boundHandleClearClick=e=>this.clearSearch(),this.clearButtonEl.addEventListener("click",this.boundHandleClearClick)),this.boundHandleDocumentClick=e=>{this.container?.contains(e.target)||this.overlayElement?.contains(e.target)||this.closeResults()},document.addEventListener("click",this.boundHandleDocumentClick),this.boundHandleDocumentKeydown=e=>{"Escape"===e.key&&(this.closeResults(),this.closeOverlay())},document.addEventListener("keydown",this.boundHandleDocumentKeydown))}setupHotkey(){this.config?.hotkey&&(this.boundHandleHotkey=e=>{const t=this.config.hotkey.toLowerCase(),n=t.includes("ctrl")&&(e.ctrlKey||e.metaKey),i=t.replace("ctrl+","").replace("cmd+","");n&&e.key.toLowerCase()===i&&(e.preventDefault(),this.openOverlay(),setTimeout(()=>this.input?.focus(),100))},document.addEventListener("keydown",this.boundHandleHotkey))}handleInput(e){const t=e.target.value.trim();this.container?.classList.toggle("has-value",t.length>0),t.length<(this.config?.minChars||2)?0===t.length?this.renderSuggestions():this.closeResults():(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.search(t),this.config?.debounceMs||300))}handleFocus(){const e=this.input?.value?.trim()||"";e.length<(this.config?.minChars||2)?this.renderSuggestions():this.config?.searchOnFocus&&e&&this.search(e)}handleKeydown(e){if(!this.isOpen)return;const t=this.resultsContainer?.querySelectorAll(".ws-search-item");if(t?.length){switch(e.key){case"ArrowDown":e.preventDefault(),this.focusedIndex=this.focusedIndex<t.length-1?this.focusedIndex+1:0;break;case"ArrowUp":e.preventDefault(),this.focusedIndex=this.focusedIndex>0?this.focusedIndex-1:t.length-1;break;case"Enter":return e.preventDefault(),void(this.focusedIndex>=0&&t[this.focusedIndex].click());default:return}t.forEach((e,t)=>e.classList.toggle("focused",t===this.focusedIndex)),t[this.focusedIndex]?.scrollIntoView({block:"nearest"})}}async search(e){const t="*"!==e&&e.length>=(this.config?.minChars||2),n=`${e}|${this.selectedCategory||""}`,i=this.cache.get(n);if(i&&Date.now()-i.timestamp<this.cacheMaxAge)return this.renderResults(i.data),this.lastQuery=e,void(this.lastResultCount=i.data.total);this.abortController&&this.abortController.abort(),this.abortController=new AbortController,this.showLoading();try{const i=await async function(e,t,n){const i=new URL(`${e.apiUrl}/public/sites/${e.siteKey}/search`);i.searchParams.set("q",t),i.searchParams.set("limit",String(n.maxResults||10)),n.category&&i.searchParams.set("category",n.category);const o=await fetch(i.toString(),{signal:n.signal});if(!o.ok)throw new Error("Search failed");return await o.json()}(this.getAPIConfig(),e,{maxResults:this.config?.maxResults||10,category:this.selectedCategory,signal:this.abortController.signal});if(i.redirect)return G("WidgetSearch","Redirecting to:",i.redirect),this.closeResults(),this.closeOverlay(),void(window.location.href=i.redirect);this.cache.set(n,{data:i,timestamp:Date.now()}),this.renderResults(i),this.lastQuery=e,this.lastResultCount=i.total,t&&(function(e,t=5,n){if(e&&!(e.length<2))try{let i=Un(t,n);i=i.filter(t=>t.toLowerCase()!==e.toLowerCase()),i.unshift(e),i=i.slice(0,t),localStorage.setItem(`${Bn}_${n}`,JSON.stringify(i))}catch(e){console.debug("[WidgetSearch] Failed to save recent search:",e)}}(e,this.suggestions?.recentSearches?.maxCount||5,this.siteKey),async function(e,t,n,i,o,r,a){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/search/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,resultsCount:n,sessionId:i,visitorId:o,siteUserId:r,pageUrl:window.location.href,referrer:document.referrer||void 0,eventId:a})})}catch{}}(this.getAPIConfig(),e,i.total,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()),0!==i.total||i.redirect||async function(e,t,n,i,o,r){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/search/zero-results`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,sessionId:n,visitorId:i,siteUserId:o,pageUrl:window.location.href,eventId:r})})}catch{}}(this.getAPIConfig(),e,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()))}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;K("WidgetSearch","Search failed:",e),this.showEmpty("Search temporarily unavailable")}}renderResults(e){if(!this.resultsContainer||!this.config)return;if(0===e.hits.length)return void this.showEmpty(this.config.styles?.textEmpty||"No products found");const t=`search-results-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,n=ei(e,{config:this.config,selectedCategory:this.selectedCategory,formatPrice:e=>On(e,this.config?.styles),formatCategoryName:e=>this.formatCategoryName(e)},t);this.resultsContainer.innerHTML=Xe(n),this.config.productCard?.customJs&&function(e,t){const n=Zn.get(e);n&&(n.forEach(e=>{const n=t.querySelector(`[data-product-id="${e.productItemCode}"] .selwise-card-inner`);if(n&&e.template.customJs){const t={source:"search",formatPrice:e=>String(e)};Xn(n,e.template,e.unifiedProduct,t)}}),Zn.delete(e))}(t,this.resultsContainer),function(e,t){e.querySelectorAll(".ws-search-cat-chip").forEach(e=>{e.addEventListener("click",()=>{const n=e.dataset.cat||null;t(n)})}),e.querySelectorAll(".ws-search-cat-item").forEach(e=>{e.addEventListener("click",()=>{const n=e.dataset.cat||null;t(n)})});const n=e.querySelector(".ws-search-cat-select");n&&n.addEventListener("change",e=>{const n=e.target.value||null;t(n)})}(this.resultsContainer,e=>{this.selectedCategory=e,this.input?.value&&this.search(this.input.value)}),this.resultsContainer.querySelectorAll(".ws-search-item").forEach(t=>{t.addEventListener("click",n=>{const i=n.target,o=t.dataset.productId,r=e.hits.find(e=>(e.itemCode||e.id)===o),a=i.closest('[data-selwise-action="add-to-cart"]');if(a)return n.preventDefault(),n.stopPropagation(),void(r&&this.handleAddToCartClick(r));o&&Fn(this.getAPIConfig(),o,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId(),this.selectedCategory||void 0,this.lastQuery),this.config?.keepOpen||(this.closeResults(),this.closeOverlay());const s=t.querySelector("a")?.href||r?.url;s&&!a&&(window.location.href=s)})}),this.focusedIndex=0,this.openResults()}handleAddToCartClick(e){!function(e,t){const n=e.itemCode||e.id;!async function(e,t,n,i,o,r,a){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:i,visitorId:o,siteUserId:r,pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:a,name:"add_to_cart",entityType:"search",entityId:n,productItemCode:n,metadata:{productItemCode:n}}]})})}catch{}}(t.config,0,n,t.sessionId,t.getVisitorId(),t.getSiteUserId(),t.generateEventId());const i={id:n,name:e.title,price:e.price,itemCode:n};if("akinon"===t.cartPlatform){const e=t.getResultsContainer(),o=e?.querySelector(`[data-selwise-action="add-to-cart"][data-product-id="${n}"]`),r=jn(o,{loading:"Adding...",success:"Added!",error:"Error",default:"Add to Cart"});qn(i,t.cartPlatform,{buttonState:r})}else qn(i,t.cartPlatform,{customScript:t.customCartScript||void 0})}(e,{config:this.getAPIConfig(),sessionId:this.sessionId,getVisitorId:()=>this.getOrCreateVisitorId(),getSiteUserId:()=>this.getStoredSiteUserId(),generateEventId:()=>this.generateEventId(),getResultsContainer:()=>this.resultsContainer,cartPlatform:this.config?.cartPlatform||"custom",customCartScript:this.config?.customCartScript})}renderSuggestions(){if(!this.resultsContainer||!this.config||!this.suggestions)return;const e=function(e,t,n,i){t.styles;const o=e.styles||{},r=e;let a='<div class="ws-suggestions">';return r.recentSearches?.enabled&&n.length>0&&(a+=`\n <div class="ws-suggestions-section ws-recent-searches">\n <div class="ws-suggestions-header">\n <span>${o.textRecentSearches||"Recent Searches"}</span>\n <button class="ws-suggestions-clear ws-clear-recent">${o.textClearRecent||"Clear"}</button>\n </div>\n `,n.slice(0,r.recentSearches.maxCount||5).forEach(e=>{a+=`\n <div class="ws-suggestion-item ws-recent-item" data-term="${i.escapeHtml(e)}">\n <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">\n <circle cx="12" cy="12" r="10"></circle>\n <polyline points="12 6 12 12 16 14"></polyline>\n </svg>\n <span class="ws-suggestion-text">${i.escapeHtml(e)}</span>\n <button class="ws-suggestion-remove ws-remove-recent" data-term="${i.escapeHtml(e)}">\n <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">\n <line x1="18" y1="6" x2="6" y2="18"></line>\n <line x1="6" y1="6" x2="18" y2="18"></line>\n </svg>\n </button>\n </div>\n `}),a+="</div>"),r.popularSearches?.enabled&&r.popularSearches.items?.length>0&&(a+=`\n <div class="ws-suggestions-section ws-popular-searches">\n <div class="ws-suggestions-header">\n <span>${o.textPopularSearches||"Popular Searches"}</span>\n </div>\n `,r.popularSearches.items.forEach(e=>{a+=`\n <div class="ws-suggestion-item ws-popular-search-item" data-term="${i.escapeHtml(e)}">\n <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">\n <polyline points="23 6 13.5 15.5 8.5 10.5 1 18"></polyline>\n <polyline points="17 6 23 6 23 12"></polyline>\n </svg>\n <span class="ws-suggestion-text">${i.escapeHtml(e)}</span>\n </div>\n `}),a+="</div>"),r.popularCategories?.enabled&&r.popularCategories.items?.length>0&&(a+=`\n <div class="ws-suggestions-section ws-popular-categories-section">\n <div class="ws-suggestions-header">\n <span>${o.textPopularCategories||"Popular Categories"}</span>\n </div>\n <div class="ws-popular-categories">\n `,r?.popularCategories?.items?.forEach(e=>{a+=`\n <a href="#" class="ws-category-card" data-category="${i.escapeHtml(e.name)}">\n ${e?.imageUrl?`<img src="${e.imageUrl}" alt="${i.escapeHtml(e.name)}" class="ws-category-img" onerror="var fb=this.parentElement.querySelector('.ws-category-img-fallback');if(fb)fb.classList.remove('hidden');this.style.display='none'" />`:""}\n <div class="ws-category-img${e.imageUrl?" hidden ws-category-img-fallback":""}" style="display:${e.imageUrl?"none":"flex"};align-items:center;justify-content:center;">\n <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>\n </svg>\n </div>\n <span class="ws-category-name">${i.escapeHtml(i.formatCategoryName(e.name))}</span>\n </a>\n `}),a+="</div></div>"),r.popularProducts?.enabled&&r.popularProducts.items?.length>0&&(a+=`\n <div class="ws-suggestions-section ws-popular-products-section">\n <div class="ws-suggestions-header">\n <span>${o.textPopularProducts||"Popular Products"}</span>\n </div>\n <div class="ws-popular-products">\n `,r.popularProducts.items.forEach(e=>{const t=e.originalPrice&&e.originalPrice>e.price,n=t?Math.round(100*(1-e.price/e.originalPrice)):0,o=e.itemCode||e.id;a+=`\n <a href="${e.url||"#"}" class="ws-product-card" data-product-id="${o}">\n <div class="ws-product-card-img-wrap" style="position:relative;">\n ${e.imageUrl?`<img src="${e.imageUrl}" alt="${i.escapeHtml(e.title)}" class="ws-product-card-img" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />`:""}\n <div class="ws-product-card-img" style="display:${e.imageUrl?"none":"flex"};align-items:center;justify-content:center;">\n <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="#cbd5e1" stroke-width="1.5">\n <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>\n <circle cx="8.5" cy="8.5" r="1.5"></circle>\n <polyline points="21 15 16 10 5 21"></polyline>\n </svg>\n </div>\n ${t?`<span class="ws-product-card-discount">-${n}%</span>`:""}\n </div>\n <div class="ws-product-card-info">\n <p class="ws-product-card-name">${i.escapeHtml(e.title)}</p>\n <div class="ws-product-card-prices">\n <span class="ws-product-card-price">${i.formatPrice(e.price)}</span>\n ${t?`<span class="ws-product-card-old-price">${i.formatPrice(e.originalPrice)}</span>`:""}\n </div>\n </div>\n </a>\n `}),a+="</div></div>"),a+="</div>",r.recentSearches?.enabled&&n.length>0||r.popularSearches?.enabled&&r.popularSearches.items?.length>0||r.popularCategories?.enabled&&r.popularCategories.items?.length>0||r.popularProducts?.enabled&&r.popularProducts.items?.length>0?a:""}(this.suggestions,this.config,Un(5,this.siteKey),{formatPrice:e=>On(e,this.config?.styles),escapeHtml:Dn,formatCategoryName:Mn});e&&(this.resultsContainer.innerHTML=Xe(e),this.attachSuggestionListeners(),this.openResults())}attachSuggestionListeners(){this.resultsContainer&&(this.resultsContainer.querySelector(".ws-clear-recent")?.addEventListener("click",e=>{e.stopPropagation(),function(e){try{localStorage.removeItem(`${Bn}_${e}`)}catch{}}(this.siteKey),this.renderSuggestions()}),this.resultsContainer.querySelectorAll(".ws-remove-recent").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.dataset.term;n&&(function(e,t){try{let n=Un(5,t);n=n.filter(t=>t.toLowerCase()!==e.toLowerCase()),localStorage.setItem(`${Bn}_${t}`,JSON.stringify(n))}catch{}}(n,this.siteKey),this.renderSuggestions())})}),this.resultsContainer.querySelectorAll(".ws-recent-item").forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.term;t&&this.input&&(async function(e,t,n,i,o,r){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,visitorId:i,siteUserId:o,pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:r,name:"recent_search_click",entityType:"search",metadata:{query:t}}]})})}catch{}}(this.getAPIConfig(),t,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()),this.input.value=t,this.container?.classList.add("has-value"),this.search(t))})}),this.resultsContainer.querySelectorAll(".ws-popular-search-item").forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.term;t&&this.input&&(async function(e,t,n,i,o,r){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,visitorId:i,siteUserId:o,pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:r,name:"popular_search_click",entityType:"search",metadata:{query:t}}]})})}catch{}}(this.getAPIConfig(),t,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()),this.input.value=t,this.container?.classList.add("has-value"),this.search(t))})}),this.resultsContainer.querySelectorAll(".ws-category-card").forEach(e=>{e.addEventListener("click",t=>{t.preventDefault();const n=e.dataset.category;n&&this.input&&(async function(e,t,n,i,o,r){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,visitorId:i,siteUserId:o,pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:r,name:"popular_category_click",entityType:"search",metadata:{categoryName:t}}]})})}catch{}}(this.getAPIConfig(),n,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()),this.selectedCategory=n,this.input.value="",this.search("*"))})}),this.resultsContainer.querySelectorAll(".ws-product-card").forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.productId;t&&(async function(e,t,n,i,o,r){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,visitorId:i,siteUserId:o,pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:r,name:"popular_product_click",entityType:"search",entityId:t,metadata:{productItemCode:t}}]})})}catch{}}(this.getAPIConfig(),t,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()),Fn(this.getAPIConfig(),t,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()))})}))}showLoading(){if(!this.resultsContainer)return;const e=Dn(this.config?.styles?.textLoading||"Searching...");this.resultsContainer.innerHTML=Xe(`\n <div class="ws-search-loading">\n <div class="ws-search-spinner"></div>\n <span>${e}</span>\n </div>\n `),this.openResults()}showEmpty(e){if(!this.resultsContainer)return;const t=Dn(e);this.resultsContainer.innerHTML=Xe(`\n <div class="ws-search-empty">\n ${Rn("",48)}\n <p style="margin-top:12px;">${t}</p>\n </div>\n `),this.openResults()}openResults(){this.resultsContainer?.classList.add("open"),"inline"===this.config?.position&&this.config?.animationType&&"none"!==this.config.animationType&&this.resultsContainer?.classList.add(`anim-${this.config.animationType}`),this.isOpen=!0}closeResults(){this.resultsContainer?.classList.remove("open"),this.isOpen=!1,this.focusedIndex=-1}openOverlay(){this.overlayElement?.classList.add("open"),this.config?.animationType&&"none"!==this.config.animationType&&this.overlayElement?.classList.add(`anim-${this.config.animationType}`),this.searchOpenTime=Date.now(),async function(e,t,n,i,o,r){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,visitorId:i,siteUserId:o,pageUrl:window.location.href,events:[{eventId:r,name:"search_instant_open",entityType:"search",metadata:{trigger:"click"}}]})})}catch{}}(this.getAPIConfig(),0,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()),setTimeout(()=>this.input?.focus(),100)}closeOverlay(){if(this.overlayElement?.classList.remove("open"),this.searchOpenTime){const e=Date.now()-this.searchOpenTime;!async function(e,t,n,i,o,r,a,s){try{await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,visitorId:r,siteUserId:a,pageUrl:window.location.href,events:[{eventId:s,name:"search_close",entityType:"search",metadata:{query:t,resultCount:n,dwellTimeMs:i}}]})})}catch{}}(this.getAPIConfig(),this.lastQuery,this.lastResultCount,e,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()),this.searchOpenTime=null}this.closeResults(),this.clearSearch()}clearSearch(){this.input&&(this.input.value=""),this.container?.classList.remove("has-value"),this.closeResults(),this.selectedCategory=null}formatCategoryName(e){const t=(this.config?.styles||{}).categoryNaming||"full_path";if(!e)return"";if("last_part"===t){const t=e.split(">");return t[t.length-1].trim()}return"first_part"===t?e.split(">")[0].trim():e}}var ni=n(126);function ii(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oi(e){if(!ii(e))return null;if("string"!=typeof e.id||0===e.id.trim().length)return null;if("string"!=typeof e.name||0===e.name.trim().length)return null;const t={strategy:e.strategy,displayType:e.displayType,trigger:e.trigger,insertPosition:e.insertPosition,cartPlatform:e.cartPlatform,maxProducts:e.maxProducts,productsPerRow:e.productsPerRow,autoplay:e.autoplay,autoplaySpeed:e.autoplaySpeed,loop:e.loop,pauseOnHover:e.pauseOnHover,slidesPerView:e.slidesPerView,slidesPerViewTablet:e.slidesPerViewTablet,slidesPerViewMobile:e.slidesPerViewMobile,slideGap:e.slideGap,title:e.title,subtitle:e.subtitle,showOnAllPages:e.showOnAllPages,includeUrls:e.includeUrls,excludeUrls:e.excludeUrls,containerSelector:e.containerSelector,addToCartEnabled:e.addToCartEnabled,addToCartConfig:e.addToCartConfig,triggerConfig:e.triggerConfig,arrowStyles:e.arrowStyles,dotStyles:e.dotStyles,titleStyles:e.titleStyles,subtitleStyles:e.subtitleStyles,containerStyles:e.containerStyles};if(!(0,ni.validateRecommendationConfig)(t).valid)return null;const n=(0,ni.sanitizeRecommendationConfig)(t),i={showOnAllPages:n.showOnAllPages,includeUrls:n.includeUrls,excludeUrls:n.excludeUrls,containerSelector:n.containerSelector,insertPosition:n.insertPosition};return{id:e.id,name:e.name,strategy:n.strategy,displayType:n.displayType,title:n.title,subtitle:n.subtitle,maxProducts:n.maxProducts,slidesPerView:n.slidesPerView,slidesPerViewMobile:n.slidesPerViewMobile,slidesPerViewTablet:n.slidesPerViewTablet,slideGap:n.slideGap,autoplay:n.autoplay,autoplaySpeed:n.autoplaySpeed,loop:n.loop,pauseOnHover:n.pauseOnHover,arrowStyles:n.arrowStyles,dotStyles:n.dotStyles,titleStyles:n.titleStyles,subtitleStyles:n.subtitleStyles,containerStyles:n.containerStyles,containerSelector:n.containerSelector,insertPosition:n.insertPosition,addToCartEnabled:n.addToCartEnabled,cartPlatform:n.cartPlatform,addToCartConfig:n.addToCartConfig,cartButtonText:"string"==typeof n.addToCartConfig?.buttonText?n.addToCartConfig.buttonText:void 0,customCartScript:"string"==typeof e.customCartScript?e.customCartScript:"string"==typeof n.addToCartConfig?.customScript?n.addToCartConfig.customScript:void 0,customCSS:"string"==typeof e.customCSS?e.customCSS:void 0,customJS:"string"==typeof e.customJS?e.customJS:void 0,productCard:ii(e.productCard)?e.productCard:void 0,pageTargetingJson:i,segmentTargetingMode:"include"===e.segmentTargetingMode||"exclude"===e.segmentTargetingMode?e.segmentTargetingMode:"all",segmentIds:Array.isArray(e.segmentIds)?e.segmentIds.filter(e=>"string"==typeof e):[]}}const ri="data-selwise-recommendation",ai=`[${ri}="true"]`;function si(e){return!!document.getElementById(`rec-widget-${e}`)}function li(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e)}const ci=new Map;const di=new Map;function ui(e){const t=window.innerWidth;return t<640?e.slidesPerViewMobile||1:t<1024?e.slidesPerViewTablet||2:e.slidesPerView||4}function pi(e,t){const n=t.querySelector(".recommendation-slider-track");if(!n)return;const i=ui(e),o=e.slideGap||0,r=n.children;for(const e of r)e.style.width=`calc((100% - ${(i-1)*o}px) / ${i})`;const a=di.get(e.id);a&&(a.slidesPerView=i)}function hi(e,t,n){const i=di.get(e.id);if(!i)return;const o=Math.ceil(i.totalSlides/i.slidesPerView);i.currentIndex="next"===n?e.loop?(i.currentIndex+1)%o:Math.min(i.currentIndex+1,o-1):e.loop?(i.currentIndex-1+o)%o:Math.max(i.currentIndex-1,0),gi(e,t),mi(t,i.currentIndex,e)}function gi(e,t){const n=di.get(e.id);if(!n)return;const i=t.querySelector(".recommendation-slider-track");if(!i)return;const o=i.children[0];if(!o)return;const r=o.offsetWidth+(e.slideGap||0),a=n.currentIndex*r;i.style.transform=`translateX(-${a}px)`}function mi(e,t,n){e.querySelectorAll(".recommendation-dot").forEach((e,i)=>{const o=n?.dotStyles||{color:"#cccccc",activeColor:"#333333"};e.style.backgroundColor=i===t?o.activeColor:o.color})}function fi(e,t){const n=di.get(e.id);n&&(yi(e),n.autoplayInterval=setInterval(()=>{hi(e,t,"next")},e.autoplaySpeed))}function yi(e){const t=di.get(e.id);t?.autoplayInterval&&(clearInterval(t.autoplayInterval),t.autoplayInterval=void 0)}function bi(e,t,n,i,o){const r=e.itemCode||e.id;i?.("add_to_cart",t.id,r,n),o?.("add_to_cart",{itemCode:r,category:e.categories,price:e.price},n);const a={id:r,title:e.title,price:e.price,variantId:e.variantId,itemCode:r,wooProductId:e.wooProductId,magentoProductId:e.magentoProductId,prestaProductId:e.prestaProductId,attributeId:e.attributeId},s=t.cartPlatform||"custom";qn(a,s,"akinon"===s?{buttonState:jn(document.querySelector(`[data-selwise-action="add-to-cart"][data-product-id="${r}"]`),{loading:"Adding...",success:"Added!",error:"Hata",default:t.cartButtonText||"Add to Cart"})}:{customScript:t.customCartScript||("string"==typeof t.addToCartConfig?.customScript?t.addToCartConfig.customScript:void 0)})}let wi=!1;function Si(){try{{const e=vt();if(e&&"string"==typeof e)return e}}catch(e){wi||(wi=!0,console.warn("[Recommendation] Failed to resolve session ID, using fallback:",e))}return function(){const e=Math.random().toString(36).slice(2,12);return`sid_fallback_${Date.now()}_${e}`}()}async function xi(e,t,n,i){try{const o="string"==typeof n&&n.trim().length>0?n.trim():null;if("click"===e)try{sessionStorage.setItem(m,JSON.stringify({ts:Date.now(),recommendationWidgetId:t,productItemCode:o}))}catch{}await fetch(`${i.apiEndpoint}/public/sites/${i.siteKey}/recommendations/track/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({widgetId:t,eventType:e,productItemCode:o||void 0,sessionId:Si(),visitorId:Ct(),userId:kt(),pageUrl:window.location.href,eventId:It(),metadata:{referrer:document.referrer||void 0}})})}catch(e){console.error("[Recommendation] Error tracking event:",e)}}async function vi(e,t,n){try{await fetch(`${n.apiEndpoint}/public/sites/${n.siteKey}/recommendations/track/behavior`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({behaviorType:e,productItemCode:t.itemCode,productCategory:t.category,productPrice:t.price,sessionId:Si(),visitorId:Ct(),siteUserId:kt(),pageUrl:window.location.href,referrer:document.referrer||void 0,eventId:It()})})}catch(e){console.error("[Recommendation] Error tracking behavior:",e)}}async function Ci(e,t,n,i,o){try{await fetch(`${o.apiEndpoint}/public/sites/${o.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:Si(),visitorId:Ct(),siteUserId:kt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:It(),name:"slider_navigate",entityType:"recommendation",entityId:e,metadata:{direction:t,fromSlide:n,toSlide:i}}]})})}catch{}}async function ki(e,t,n){try{await fetch(`${n.apiEndpoint}/public/sites/${n.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:Si(),visitorId:Ct(),siteUserId:kt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:It(),name:"slider_swipe",entityType:"recommendation",entityId:e,metadata:{direction:t}}]})})}catch{}}const Ti=new WeakMap,Ii=new Set,Ei=new Set,_i=new Map;let Pi=!1;const Ai=Ut(),$i=ht();function Oi(){setTimeout(()=>{_i.forEach((e,t)=>{e.disconnect()}),_i.clear(),G("Recommendation","Cleaned up observers on navigation")},500)}function Di(e){const t=e?.triggerConfig,n=t?.frequencyCap;if(n&&"object"==typeof n)return n}async function Mi(e){try{!function(){if(Pi)return;Pi=!0;const e=history.pushState,t=history.replaceState;history.pushState=(...t)=>{e.apply(history,t),Oi()},history.replaceState=(...e)=>{t.apply(history,e),Oi()},window.addEventListener("popstate",()=>Oi()),window.addEventListener("hashchange",()=>Oi())}();let t=(Array.isArray(e.widgets)?e.widgets:[]).map(e=>oi(e)).filter(e=>Boolean(e));if(0===t.length){const n=await fetch(`${e.apiEndpoint}/public/sites/${e.siteKey}/recommendations?pageUrl=${encodeURIComponent(window.location.href)}`);if(!n.ok)return;const i=await n.json();t=Array.isArray(i.widgets)?i.widgets.map(e=>oi(e)).filter(e=>Boolean(e)):[]}const n=function(e){if(e.length<=1)return e.map(e=>({candidateId:`recommendation:${e.id}`,widget:e,frequencyKey:`display:recommendation:${e.id}`,frequencyCapConfig:Di(e)}));const t=e.map(e=>{const t=(e?.triggerConfig||{}).conflictResolution||{};return{...$i.applyConfig({id:`recommendation:${e.id}`,type:"recommendation",selector:e.containerSelector,placementPosition:e.insertPosition,priority:e.priority??t.priority,conflictBehavior:t.behavior,placementConfig:{conflictResolution:t}}),widget:e,frequencyKey:`display:recommendation:${e.id}`,frequencyCapConfig:Di(e)}}),n=$i.resolveAll(t),i=new Set(n.flatMap(e=>e.selected.map(e=>e.id)));return t.filter(e=>i.has(e.id)).map(e=>({candidateId:e.id,widget:e.widget,frequencyKey:e.frequencyKey,frequencyCapConfig:e.frequencyCapConfig}))}(t.filter(e=>{const t=Yt(e.pageTargetingJson,window.location.href);return t||W("Recommendation","Skipping widget due to page targeting:",e.id),t}));for(const t of n)await Ni(t.widget,e,t.frequencyKey,t.frequencyCapConfig)}catch(e){K("Recommendation","Error initializing:",e)}}async function Ni(e,t,n,i){const o=si(e.id);if(o&&!Ei.has(e.id))return Ei.add(e.id),!1;if(!o&&Ei.has(e.id)&&Ei.delete(e.id),Ei.has(e.id))return!1;const r=()=>{if(!i)return!0;const t=Ai.canShow(n,i);return!!t.allowed||(W("Recommendation",`Skipping widget due to frequency cap (${t.reason||"limit"})`,e.id),!1)};if(!e.containerSelector){if(await Ui(e,t)){if(!r())return!1;if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return!1;const o=Bi(e,t);if(!o)return!1;Ei.add(o.id);const a=await zi(o,t);return a&&i&&Ai.recordShown(n),a}return!1}if(document.querySelector(e.containerSelector)){if(await Ui(e,t)){if(!r())return!1;if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return!1;const o=Bi(e,t);if(!o)return!1;Ei.add(o.id);const a=await zi(o,t);return a&&i&&Ai.recordShown(n),a}return!1}return W("Recommendation","Container not found, setting up observer for:",e.containerSelector),function(e,t,n,i){if(_i.has(e.id))return;const o=function(e){let t=null;const n=function(...n){null!==t&&clearTimeout(t),t=setTimeout(()=>{t=null,e.apply(this,n)},150)};return n.cancel=()=>{null!==t&&(clearTimeout(t),t=null)},n}(async()=>{if(si(e.id))Ri(e.id);else if(document.querySelector(e.containerSelector)&&await Ui(e,t)){if(i&&!Ai.canShow(n,i).allowed)return void Ri(e.id);if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return void Ri(e.id);const o=Bi(e,t);if(!o)return void Ri(e.id);Ei.add(o.id),await zi(o,t)&&i&&Ai.recordShown(n),Ri(e.id),W("Recommendation","Widget rendered via observer:",o.id)}}),r=new MutationObserver((e,t)=>{o()}),a=function(e){const t=e.split(/\s+/);for(let e=0;e<t.length-1;e++){const n=t.slice(0,e+1).join(" "),i=document.querySelector(n);if(i)return i}return document.body}(e.containerSelector);r.observe(a,{childList:!0,subtree:!0}),_i.set(e.id,r),setTimeout(()=>{Ri(e.id),o.cancel()},1e4)}(e,t,n,i),!1}function Ri(e){const t=_i.get(e);t&&(t.disconnect(),_i.delete(e))}function Li(){_i.forEach((e,t)=>{e.disconnect(),G("Recommendation","Cleaned up observer for:",t)}),_i.clear(),document.querySelectorAll(ai).forEach(e=>{e.remove()}),Ei.forEach(e=>{const t=document.getElementById(`rec-widget-${e}`);t&&t.remove()}),Ei.clear(),Ii.clear(),G("Recommendation","Module cleanup complete")}function Bi(e,t){if(!t.experimentManager)return e;const n=t.experimentManager.getVariantModuleForTarget(e.id);if(n&&n.moduleData){const e=n.moduleData,t=e.data||e;if(t&&t.id)return W("Recommendation","Rendering variant module instead of original:",t.id),t._experimentAssignment=n,t}const i=t.experimentManager.getVariant(e.id)||t.experimentManager.getAssignmentByTargetId(e.id);if(i){const t=Wt(i);if(t){W("Recommendation","Applying config override:",i.variantName);const n=qt(e,t);if(Object.assign(e,n),t.content&&"object"==typeof t.content){const n=t.content;void 0!==n.title&&(e.title=n.title,e.titleStyles&&(e.titleStyles.enabled=!0)),void 0!==n.subtitle?(e.subtitle=n.subtitle,e.subtitleStyles&&(e.subtitleStyles.enabled=!0)):void 0!==n.text?(e.subtitle=n.text,e.subtitleStyles&&(e.subtitleStyles.enabled=!0)):void 0!==n.description&&(e.subtitle=n.description,e.subtitleStyles&&(e.subtitleStyles.enabled=!0))}t.styles&&"object"==typeof t.styles&&(e.containerStyles=qt(e.containerStyles||{},t.styles)),t.displayType&&(e.displayType=t.displayType)}e._experimentAssignment=i}return e}async function Ui(e,t){if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return W("Recommendation","Skipping widget (excluded by experiment):",e.id),!1;if(e.containerSelector){const t=document.querySelector(e.containerSelector);if(W("Recommendation","Container check:",e.containerSelector,"-> Found:",!!t),!t)return!1}return!!Yt(e.pageTargetingJson,window.location.href)&&(!(t.segmentManager&&e.segmentTargetingMode&&e.segmentIds&&!await t.segmentManager.shouldShow(e.segmentTargetingMode,e.segmentIds))||(W("Recommendation","Skipping widget due to segment targeting:",e.id),!1))}async function zi(e,t){try{const n=function(e){if(e.currentProductId)return e.currentProductId;if(e.detectCurrentProduct){const t=e.detectCurrentProduct();if(t)return t}const t=['meta[property="og:product:id"]','meta[property="product:id"]','meta[name="product-id"]','meta[name="product_id"]','meta[name="sku"]'];for(const e of t){const t=document.querySelector(e);if(t?.content)return t.content}const n=["[data-product-id]","[data-product-sku]","[data-item-code]","[data-sku]"];for(const e of n){const t=document.querySelector(e);if(t){const e=t.getAttribute("data-product-id")||t.getAttribute("data-product-sku")||t.getAttribute("data-item-code")||t.getAttribute("data-sku");if(e)return e}}const i=document.querySelector('script[type="application/ld+json"]');if(i)try{const e=JSON.parse(i.textContent||"{}");if("Product"===e["@type"]&&e.sku)return e.sku;if("Product"===e["@type"]&&e.productID)return e.productID}catch{}return null}(t);let i="";try{i=Si()}catch{i=`sid_fallback_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}const o=await fetch(`${t.apiEndpoint}/public/sites/${t.siteKey}/recommendations/${e.id}/products`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentProductId:n,pageUrl:window.location.href,sessionId:i,visitorId:window.selwise_vid,userId:window.selwise_suid})});if(!o.ok)return!1;const r=await o.json(),a=r.products||[];if(r.productCard&&(e.productCard=r.productCard),0===a.length)return!1;const s=function(e,t,n){const i=document.createElement("div");i.className="recommendation-widget",i.id=`rec-widget-${e.id}`,i.setAttribute("data-widget-id",e.id),i.setAttribute(ri,"true");const o=e.containerStyles;if(i.style.cssText=`\n background-color: ${o?.backgroundColor};\n padding: ${o?.padding};\n border-radius: ${o?.borderRadius}px;\n max-width: ${o?.maxWidth};\n margin: ${o?.margin};\n box-sizing: border-box;\n `,e.titleStyles?.enabled&&e.title){const t=document.createElement("h2");t.className="recommendation-title",t.textContent=e.title;const n=e.titleStyles;t.style.cssText=`\n font-size: ${n.fontSize||24}px;\n font-weight: ${n.fontWeight||"bold"};\n color: ${n.color||"#111111"};\n text-align: ${n.textAlign||"left"};\n margin-bottom: ${n.marginBottom||16}px;\n margin-top: 0;\n `,i.appendChild(t)}if(e.subtitleStyles?.enabled&&e.subtitle){const t=document.createElement("p");t.className="recommendation-subtitle",t.textContent=e.subtitle;const n=e.subtitleStyles;t.style.cssText=`\n font-size: ${n.fontSize||14}px;\n font-weight: ${n.fontWeight||"normal"};\n color: ${n.color||"#666666"};\n text-align: ${n.textAlign||"left"};\n margin-bottom: ${n.marginBottom||24}px;\n margin-top: 0;\n `,i.appendChild(t)}const r=function(e,t,n){const i=e.productCard?.customJs?`recommendation-${e.id}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`:"",o=t=>function(e,t,n,i,o,r,a){const s=document.createElement("div");s.className="recommendation-card",s.setAttribute("data-product-id",e.itemCode||e.id),t.productCard?s.innerHTML=function(e,t,n){const i=function(e){return{id:e.id,itemCode:e.itemCode,sku:e.sku,title:e.title,description:e.description,shortDescription:e.shortDescription,imageUrl:e.imageUrl,url:e.url,price:e.price,originalPrice:e.originalPrice,discountRate:e.discountRate,inStock:e.inStock,stock:e.stock,categories:e.categories,brand:e.brand,productType:e.productType,categoryHierarchy:e.categoryHierarchy,isNew:e.isNew,isSale:e.isSale??(e.originalPrice&&e.originalPrice>e.price),isBestseller:e.isBestseller,rating:e.rating,reviewCount:e.reviewCount,variantId:e.variantId,wooProductId:e.wooProductId,magentoProductId:e.magentoProductId,prestaProductId:e.prestaProductId,attributeId:e.attributeId}}(e),o={id:t.id,template:t.template,fields:t.fields||[],layoutType:t.layoutType,imagePosition:t.imagePosition,imageSize:t.imageSize,showBadges:t.showBadges,showButton:t.showButton,buttonText:t.buttonText,buttonStyle:t.buttonStyle,hoverEffect:t.hoverEffect,customCSS:t.customCSS,customHTML:t.customHTML,customJs:t.customJs,jsTiming:t.jsTiming||"immediate",jsEventName:t.jsEventName},r={source:"recommendation",formatPrice:li};return n&&o.customJs&&(ci.has(n)||ci.set(n,[]),ci.get(n).push({template:o,unifiedProduct:i,productItemCode:e.itemCode||e.id})),Yn(i,o,r)}(e,t.productCard,a):s.innerHTML=Ze(function(e,t){const n=e.originalPrice&&e.originalPrice>e.price,i=n?Math.round((e.originalPrice-e.price)/e.originalPrice*100):0;let o="";e.isNew&&(o+='<span class="recommendation-badge recommendation-badge-new">New</span>'),n&&(o+=`<span class="recommendation-badge recommendation-badge-sale">-${i}%</span>`),e.isBestseller&&(o+='<span class="recommendation-badge recommendation-badge-bestseller">Bestseller</span>');let r="";if(t.addToCartEnabled){const n=e.itemCode||e.id;r=`\n <button class="recommendation-add-to-cart" \n ${Kn}="${Vn}"\n ${Jn}="${n}">\n ${t.cartButtonText||"Add to Cart"}\n </button>\n `}return`\n <div class="recommendation-card-inner">\n <div class="recommendation-card-image">\n ${o?`<div class="recommendation-badges">${o}</div>`:""}\n <img src="${e.imageUrl}" alt="${e.title}" loading="lazy" />\n </div>\n <div class="recommendation-card-content">\n <h3 class="recommendation-card-title">${e.title}</h3>\n <div class="recommendation-card-price">\n ${n?`<span class="recommendation-price-original">${li(e.originalPrice)}</span>`:""}\n <span class="recommendation-price-current">${li(e.price)}</span>\n </div>\n ${r}\n </div>\n </div>\n <style>\n .recommendation-card-inner {\n background: white;\n border-radius: 8px;\n overflow: hidden;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n transition: transform 0.2s ease, box-shadow 0.2s ease;\n cursor: pointer;\n }\n .recommendation-card-inner:hover {\n transform: translateY(-4px);\n box-shadow: 0 8px 24px rgba(0,0,0,0.15);\n }\n .recommendation-card-image {\n position: relative;\n padding-top: 100%;\n }\n .recommendation-card-image img {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n .recommendation-badges {\n position: absolute;\n top: 8px;\n left: 8px;\n z-index: 1;\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n .recommendation-badge {\n padding: 4px 8px;\n font-size: 12px;\n font-weight: 600;\n border-radius: 4px;\n text-transform: uppercase;\n }\n .recommendation-badge-new {\n background: #22c55e;\n color: white;\n }\n .recommendation-badge-sale {\n background: #ef4444;\n color: white;\n }\n .recommendation-badge-bestseller {\n background: #f59e0b;\n color: white;\n }\n .recommendation-card-content {\n padding: 12px;\n }\n .recommendation-card-title {\n font-size: 14px;\n font-weight: 500;\n color: #111;\n margin: 0 0 8px;\n line-height: 1.4;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n }\n .recommendation-card-price {\n display: flex;\n align-items: center;\n gap: 8px;\n }\n .recommendation-price-original {\n text-decoration: line-through;\n color: #999;\n font-size: 13px;\n }\n .recommendation-price-current {\n font-weight: 600;\n color: #111;\n font-size: 16px;\n }\n .recommendation-add-to-cart {\n width: 100%;\n margin-top: 12px;\n padding: 10px;\n background: #111;\n color: white;\n border: none;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.2s ease;\n }\n .recommendation-add-to-cart:hover {\n background: #333;\n }\n </style>\n `}(e,t));const l=t.productCard?.customHTML&&(t.productCard.customHTML.includes("<a ")||t.productCard.customHTML.includes("<a'"));return s.addEventListener("click",a=>{const s=a.target;return s.closest(`[${Kn}="${Vn}"]`)?(a.preventDefault(),void i(e,t,n,o,r)):l?void(s.closest("a")&&o("click",t.id,e.itemCode||e.id,n)):(o("click",t.id,e.itemCode||e.id,n),r&&r("view",{itemCode:e.itemCode||e.id,category:e.categories,price:e.price},n),void(window.location.href=e.url))}),s}(t,e,n,bi,xi,vi,i);let r;switch(e.displayType){case"slider":case"carousel":r=function(e,t,n,i){const o=document.createElement("div");o.className="recommendation-slider-wrapper",o.style.cssText="position: relative;";const r=document.createElement("div");r.className="recommendation-slider-track";const a=e.slideGap||16;r.style.cssText=`\n display: flex;\n transition: transform 0.3s ease-out;\n gap: ${a}px;\n `;const s=document.createElement("div");if(s.className="recommendation-slider-viewport",s.style.cssText="overflow: hidden;",t.forEach(t=>{const o=i(t,e,n);o.style.flexShrink="0",o.style.width=`calc((100% - ${((e.slidesPerView||4)-1)*(e.slideGap||16)}px) / ${e.slidesPerView||4})`,r.appendChild(o)}),s.appendChild(r),o.appendChild(s),e.arrowStyles?.enabled){const t=function(e){const t=e.arrowStyles,n=e=>{const n=document.createElement("button");n.className=`recommendation-arrow recommendation-arrow-${e}`,n.setAttribute("data-direction",e);let i="50%";"square"===t.style&&(i="0"),"rounded"===t.style&&(i="8px"),"minimal"===t.style&&(i="0");const o="outside"===t.position?"prev"===e?`left: ${t.offset}px;`:`right: ${t.offset}px;`:"prev"===e?`left: ${Math.abs(t.offset)}px;`:`right: ${Math.abs(t.offset)}px;`;n.style.cssText=`\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n ${o}\n width: ${t.size}px;\n height: ${t.size}px;\n background-color: ${t.backgroundColor};\n color: ${t.color};\n border: ${t.borderWidth}px solid ${t.borderColor};\n border-radius: ${i};\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10;\n transition: all 0.2s ease;\n `;const r=t.iconSize;return n.innerHTML="prev"===e?`<svg width="${r}" height="${r}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"></polyline></svg>`:`<svg width="${r}" height="${r}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"></polyline></svg>`,n.addEventListener("mouseenter",()=>{n.style.backgroundColor=t.hoverBackgroundColor,n.style.color=t.hoverColor}),n.addEventListener("mouseleave",()=>{n.style.backgroundColor=t.backgroundColor,n.style.color=t.color}),n};return{prev:n("prev"),next:n("next")}}(e);o.appendChild(t.prev),o.appendChild(t.next)}if(e.dotStyles?.enabled){const n=function(e,t){const n=e.dotStyles,i=Math.ceil(t/e.slidesPerView),o=document.createElement("div");o.className="recommendation-dots",o.style.cssText=`\n display: flex;\n justify-content: center;\n gap: ${n.gap}px;\n margin-top: ${n.offset}px;\n `;for(let e=0;e<i;e++){const t=document.createElement("button");t.className="recommendation-dot",t.setAttribute("data-index",e.toString());let i=n.size,r=n.size,a="50%";"square"===n.style&&(a="0"),"line"===n.style&&(i=3*n.size,r=n.size/2,a="2px"),"dash"===n.style&&(i=2*n.size,r=3,a="1px"),t.style.cssText=`\n width: ${i}px;\n height: ${r}px;\n background-color: ${0===e?n.activeColor:n.color};\n border: none;\n border-radius: ${a};\n cursor: pointer;\n transition: background-color 0.2s ease;\n padding: 0;\n `,o.appendChild(t)}return o}(e,t.length);o.appendChild(n)}return o}(e,t,n,o);break;case"grid":default:r=function(e,t,n,i){const o=document.createElement("div");return o.className="recommendation-grid",o.style.cssText=`\n display: grid;\n grid-template-columns: repeat(${e.slidesPerView}, 1fr);\n gap: ${e.slideGap}px;\n `,t.forEach(t=>{const r=i(t,e,n);o.appendChild(r)}),o}(e,t,n,o);break;case"list":r=function(e,t,n,i){const o=document.createElement("div");return o.className="recommendation-list",o.style.cssText=`\n display: flex;\n flex-direction: column;\n gap: ${e.slideGap}px;\n `,t.forEach(t=>{const r=i(t,e,n);r.style.flexDirection="row",o.appendChild(r)}),o}(e,t,n,o);break;case"masonry":r=function(e,t,n,i){const o=document.createElement("div");return o.className="recommendation-masonry",o.style.cssText=`\n column-count: ${e.slidesPerView};\n column-gap: ${e.slideGap}px;\n `,t.forEach(t=>{const r=i(t,e,n);r.style.breakInside="avoid",r.style.marginBottom=`${e.slideGap}px`,o.appendChild(r)}),o}(e,t,n,o)}return i&&e.productCard?.customJs&&function(e,t){const n=ci.get(e);n&&(n.forEach(e=>{const n=t.querySelector(`[data-product-id="${e.productItemCode}"] .selwise-card-inner`);if(n&&e.template.customJs){const t={source:"recommendation",formatPrice:li};Xn(n,e.template,e.unifiedProduct,t)}}),ci.delete(e))}(i,r),r}(e,t,n);if(i.appendChild(r),e.customCSS){const t=document.createElement("style");t.textContent=et(e.customCSS),i.appendChild(t)}if(e.productCard&&e.productCard.customCSS){const t=document.createElement("style");t.textContent=et(e.productCard.customCSS),i.appendChild(t)}return i}(e,a,t);if(function(e,t){const n=e.id?document.getElementById(e.id):null;n&&n!==e&&n.remove();let i=null;if(t.containerSelector&&(i=document.querySelector(t.containerSelector)),i)switch(t.insertPosition){case"before":i.parentNode?i.parentNode.insertBefore(e,i):document.body.appendChild(e);break;case"after":i.parentNode?i.parentNode.insertBefore(e,i.nextSibling):document.body.appendChild(e);break;case"prepend":i.insertBefore(e,i.firstChild);break;case"replace":i.innerHTML="",i.appendChild(e);break;default:i.appendChild(e)}else document.body.appendChild(e)}(s,e),async function(e,t){try{await fetch(`${t.apiEndpoint}/public/sites/${t.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:Si(),visitorId:Ct(),siteUserId:kt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:It(),name:"widget_impression",entityType:"recommendation",entityId:e,metadata:{timestamp:Date.now()}}]})})}catch(e){console.error("[Recommendation] Error tracking widget impression:",e)}}(e.id,t).catch(()=>{}),e._experimentAssignment&&t.experimentManager&&t.experimentManager.trackImpression(e._experimentAssignment.experimentId),"slider"!==e.displayType&&"carousel"!==e.displayType||function(e,t,n,i,o){const r=t.querySelector(".recommendation-slider-track");if(!r)return;const a=ui(e),s={currentIndex:0,totalSlides:r.children.length,slidesPerView:a,touchStartX:0,touchEndX:0};di.set(e.id,s),pi(e,t);const l=t.querySelector(".recommendation-arrow-prev"),c=t.querySelector(".recommendation-arrow-next");l?.addEventListener("click",()=>{const o=s.currentIndex;hi(e,t,"prev"),i?.(e.id,"prev",o,s.currentIndex,n)}),c?.addEventListener("click",()=>{const o=s.currentIndex;hi(e,t,"next"),i?.(e.id,"next",o,s.currentIndex,n)}),t.querySelectorAll(".recommendation-dot").forEach(n=>{n.addEventListener("click",i=>{i.preventDefault();const o=parseInt(n.getAttribute("data-index")||"0");!function(e,t,n){const i=di.get(e.id);i&&(i.currentIndex=n,gi(e,t),mi(t,n,e))}(e,t,o)})});const d=t.querySelector(".recommendation-slider-viewport");d?.addEventListener("touchstart",e=>{const t=e.touches[0];s.touchStartX=t.clientX},{passive:!0}),d?.addEventListener("touchend",i=>{const r=i.changedTouches[0];s.touchEndX=r.clientX;const a=s.touchStartX-s.touchEndX;if(Math.abs(a)>50){const t=a>0?"left":"right";o?.(e.id,t,n)}!function(e,t){const n=di.get(e.id);if(!n)return;const i=n.touchStartX-n.touchEndX;i>50?hi(e,t,"next"):i<-50&&hi(e,t,"prev")}(e,t)},{passive:!0}),e.autoplay&&(fi(e,t),e.pauseOnHover&&(t.addEventListener("mouseenter",()=>{yi(e)}),t.addEventListener("mouseleave",()=>{fi(e,t)}))),window.addEventListener("resize",()=>{pi(e,t),gi(e,t)})}(e,s,t,Ci,ki),function(e,t,n){const i=Ti.get(e);i&&i.disconnect();const o=e.querySelectorAll(".recommendation-card"),r=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting&&e.intersectionRatio>=.5){const i=e.target,r=i.dataset.productId,a=`${t}_${r}`;if(r&&!Ii.has(a)){Ii.add(a);const e=Array.from(o).indexOf(i);fetch(`${n.apiEndpoint}/public/sites/${n.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:Si(),visitorId:Ct(),siteUserId:kt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:It(),name:"product_impression",entityType:"recommendation",entityId:t,productItemCode:r,metadata:{productItemCode:r,position:e}}]})}).catch(()=>{})}}})},{threshold:.5});Ti.set(e,r),o.forEach(e=>r.observe(e))}(s,e.id,t),e._experimentAssignment&&t.experimentManager&&s.addEventListener("click",n=>{const i=n.target;if(i.closest(".recommendation-card")||i.closest('[data-selwise-action="add-to-cart"]')||i.closest("a")||i.closest("button")){const n=e._experimentAssignment;t.experimentManager?.trackConversion(n.experimentId)}}),e.customJS)try{J("Recommendation","Executing custom JS for widget:",e.id),new Function("widgetElement","products","widgetConfig",e.customJS)(s,a,e)}catch(e){K("Recommendation","Custom JS error:",e)}return!0}catch(e){return K("Recommendation","Error rendering widget:",e),!1}}const Fi={loadSearchModule:async()=>({SearchModule:ti}),loadRecommendationModule:async()=>({initRecommendations:Mi,cleanup:Li})},qi={canShow:()=>({allowed:!0}),recordShown:()=>{},cleanup:()=>{}};class ji{constructor(e={}){this.trackerInstance=null,this.experiments=null,this.segments=null,this.dataLayerManager=null,this.dataLayerEnabled=!1,this.searchModule=null,this.recommendationsCleanup=null,this.recommendationsInitialized=!1,this.campaigns=[],this.widgets=[],this.recommendationWidgets=[],this.isDestroyed=!1,this.renderedEntities=new Set,this.frequencyCapManagerInstance=null,this.conflictResolver=ht(),this.originalPushState=null,this.originalReplaceState=null,this.popStateListener=null,this.pendingTimeouts=new Set,this.spaCleanupSetup=!1,this.config={siteKey:"",apiUrl:yt(),exposeGlobal:!1},this.renderer=new dt,this.moduleLoaders={...Fi,...e}}get tracker(){return this.trackerInstance||(this.trackerInstance=new Mt(this.config.apiUrl||yt(),this.config.siteKey)),this.trackerInstance}set tracker(e){this.trackerInstance=e}get frequencyCapManager(){return this.isBrowserEnvironment()?(this.frequencyCapManagerInstance||(this.frequencyCapManagerInstance=Ut()),this.frequencyCapManagerInstance):qi}isBrowserEnvironment(){return"undefined"!=typeof window&&"undefined"!=typeof document}bindGlobalInstance(){if(this.isBrowserEnvironment())try{window.Selwise=this}catch{}}clearGlobalInstanceBinding(){if(this.isBrowserEnvironment())try{const e=window;if(e.Selwise!==this)return;delete e.Selwise}catch{try{window.Selwise===this&&(window.Selwise=void 0)}catch{}}}get siteKey(){return this.config.siteKey||""}detectMissingFeatures(){const e=[];return"undefined"==typeof fetch&&e.push("fetch"),"undefined"==typeof Promise&&e.push("Promise"),"undefined"==typeof IntersectionObserver&&e.push("IntersectionObserver"),"undefined"!=typeof Map&&"undefined"!=typeof Set||e.push("Map/Set"),"undefined"==typeof MutationObserver&&e.push("MutationObserver"),"undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams||e.push("URL/URLSearchParams"),e}get apiUrl(){return this.config.apiUrl||""}get trackingConfig(){return this._trackingConfig||null}cleanupRenderedEntityRoots(){this.renderedEntities.clear(),E.forEach((e,t)=>{$(t)}),document.querySelectorAll(I).forEach(e=>{e.remove()}),document.querySelectorAll("[data-widget-id]").forEach(e=>{const t=e;"true"!==t.getAttribute("data-selwise-recommendation")&&t.remove()})}cleanupRenderedEntityById(e,t){!function(e,t){document.querySelectorAll(I).forEach(n=>{const i=n.getAttribute(k)===e,o=!t||n.getAttribute(T)===t;i&&o&&n.remove()})}(e,t),document.querySelectorAll("[data-widget-id]").forEach(t=>{const n=t;n.dataset.widgetId===e&&"true"!==n.getAttribute("data-selwise-recommendation")&&n.remove()})}setupSPACleanup(){this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),this.popStateListener=()=>{this.onNavigate()},window.addEventListener("popstate",this.popStateListener),history.pushState=(...e)=>{const t=window.location.href;this.originalPushState(...e),t!==window.location.href&&this.onNavigate()},history.replaceState=(...e)=>{const t=window.location.href;this.originalReplaceState(...e),t!==window.location.href&&this.onNavigate()}}onNavigate(){const e=window.location.href;G("Selwise","SPA navigation detected:",e,"- cleaning up..."),this.pendingTimeouts.forEach(e=>clearTimeout(e)),this.pendingTimeouts.clear(),this.searchModule?.destroy&&(this.searchModule.destroy(),this.searchModule=null),this.recommendationsCleanup&&(this.recommendationsCleanup(),this.recommendationsCleanup=null),this.recommendationsInitialized=!1,this.cleanupRenderedEntityRoots(),this.trackerInstance?.cleanup(),this.dataLayerManager&&(this.dataLayerManager.destroy(),this.dataLayerManager=null,this.dataLayerEnabled=!1);const t=window.setTimeout(()=>{this.pendingTimeouts.delete(t),this.initDataLayer()},50);this.pendingTimeouts.add(t),document.querySelectorAll("script[data-selwise-script]").forEach(e=>e.remove()),document.querySelectorAll("style[data-selwise-script-css]").forEach(e=>e.remove()),document.querySelectorAll("script[data-selwise-custom-js]").forEach(e=>e.remove()),document.querySelectorAll("style[data-selwise-custom-css]").forEach(e=>e.remove()),document.querySelectorAll("script[data-selwise-card-js]").forEach(e=>e.remove());const n=window.setTimeout(()=>{this.pendingTimeouts.delete(n),this.initSearch(),this.initRecommendations(),this.renderEntitiesWithPolicies().catch(e=>{G("Selwise","Failed to render entities after navigation:",e)})},100);this.pendingTimeouts.add(n)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.pendingTimeouts.forEach(e=>clearTimeout(e)),this.pendingTimeouts.clear(),this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popStateListener&&(window.removeEventListener("popstate",this.popStateListener),this.popStateListener=null),this.spaCleanupSetup=!1,this.searchModule?.destroy&&this.searchModule.destroy(),this.searchModule=null,this.recommendationsCleanup&&this.recommendationsCleanup(),this.recommendationsCleanup=null,this.recommendationsInitialized=!1,this.dataLayerManager&&(this.dataLayerManager.destroy(),this.dataLayerEnabled=!1),this.dataLayerManager=null,this.trackerInstance&&(this.trackerInstance.flush(),this.trackerInstance.cleanup(),this.tracker=null),this.isBrowserEnvironment()&&this.cleanupRenderedEntityRoots(),this.clearGlobalInstanceBinding(),G("Selwise","Instance destroyed"))}async init(e){if(!this.isBrowserEnvironment())return void J("Selwise","init() must be called in a browser environment");this.isDestroyed=!1;const t=this.detectMissingFeatures();if(t.length>0&&J("Selwise","Browser missing required features:",t.join(", "),"- Widget may not function correctly"),this.config={...this.config,...e},this.trackerInstance&&(this.trackerInstance.flush(),this.trackerInstance.cleanup()),this.tracker=new Mt(this.config.apiUrl,this.config.siteKey),this.config.exposeGlobal?(this.bindGlobalInstance(),this.tracker.setupConsentCallback()):this.clearGlobalInstanceBinding(),this.spaCleanupSetup||(this.setupSPACleanup(),this.spaCleanupSetup=!0),this.config.siteKey){(async function(){const e=document.currentScript;if(!e)return void console.debug("[Selwise] No script tag found for Sentry configuration");const t=e.getAttribute("data-sentry-dsn");if(!t)return void console.debug("[Selwise] No Sentry DSN found in script tag attributes");if(!Zt(t))return void console.warn("[Selwise] Sentry DSN validation failed - not initializing");const n=window.SelwiseConfig;return async function(e){if(e.dsn)if(Zt(e.dsn))try{await async function(){if(!en)return tn||(tn=new Promise((e,t)=>{if(window.Sentry)return en=!0,void e();const n=document.createElement("script");n.async=!0,n.src="https://browser.sentry-cdn.com/8.32.0/bundle.min.js",n.crossOrigin="anonymous",n.onload=()=>{en=!0,e()},n.onerror=()=>{console.warn("[Selwise] Failed to load Sentry from CDN"),t(new Error("Sentry CDN load failed"))},document.head.appendChild(n)}),tn)}();const t=window.Sentry;if(!t)return void console.warn("[Selwise] Sentry loaded but not available on window");if(t.getClient())return void console.debug("[Selwise] Sentry already initialized");t.init({dsn:e.dsn,environment:e.environment||"production",release:e.release,tracesSampleRate:e.tracesSampleRate||0,beforeBreadcrumb:nn,beforeSend:on,integrations:[],maxBreadcrumbs:10,attachStacktrace:!0,sampleRate:1});const n=function(){const e=window.SelwiseConfig;if(e?.siteKey)return e.siteKey;const t=document.currentScript;return t&&t.getAttribute("data-site-key")||void 0}();t.setUser({id:n||"unknown"}),t.setContext("widget",{widgetType:"Selwise Client",siteKey:n||"unknown"}),console.debug("[Selwise] Sentry initialized")}catch(e){console.debug("[Selwise] Failed to initialize Sentry:",e)}else console.warn("[Selwise] Sentry: DSN validation failed - not initializing");else console.debug("[Selwise] Sentry: No DSN provided, skipping initialization")}({dsn:t,environment:e.getAttribute("data-sentry-environment")||n?.sentryEnvironment||void 0,release:e.getAttribute("data-sentry-release")||n?.sentryRelease||void 0})})().catch(()=>{});try{this.experiments=new Gt(this.config.siteKey,this.tracker.getVisitorId(),this.config.apiUrl),await this.experiments.init(),this.segments=new Qt(this.config.apiUrl,this.config.siteKey,this.tracker.getVisitorId(),this.tracker.getSessionId(),this.tracker.getSiteUserId(),this.tracker.getSiteUserProfileId());const[e,t,n]=await Promise.allSettled([this.loadSiteConfig().catch(e=>(K("Selwise","Failed to load site config:",e),null)),this.loadScripts().catch(e=>(K("Selwise","Failed to load scripts:",e),null)),fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/integrations`).catch(()=>null)]);if("fulfilled"===n.status&&n.value&&n.value.ok){const e=await n.value.json(),t={};for(const n of e.integrations||[]){const e=n.reverseEventMapping||{};n.enabled&&e&&Object.assign(t,e)}Object.keys(t).length>0&&(this.config.reverseEventMapping=t,W("Selwise","Reverse event mapping loaded:",t))}if("fulfilled"===e.status&&e.value){const{campaigns:t,widgets:n,recommendations:i,tracking:o}=e.value;if(this.campaigns=t||[],this.widgets=n||[],this.recommendationWidgets=i||[],o){if(this._trackingConfig=o,o.subscriptionRequired)return J("Selwise","Subscription required:",o.subscriptionMessage),void this.handleSubscriptionInactive(o.subscriptionMessage);const e=o.flushInterval?1e3*o.flushInterval:void 0;this.tracker.setBatcherConfig({enabled:o.batchingEnabled,batchSize:o.batchSize,flushInterval:e,enablePersistence:o.offlinePersistence,enableSendBeacon:o.sendBeaconOnUnload,maxRetries:o.maxRetries,maxQueueSize:o.maxQueueSize,maxStorageEvents:o.maxStorageEvents,debugMode:o.debugMode}),j(o.debugMode||!1),await this.tracker.initialize(),this.config.dataLayerConfig=o.dataLayerConfig,o.debugMode&&W("Selwise","Tracking config loaded from batch endpoint:",o)}W("Selwise","Loaded site config from batch endpoint:",{campaigns:this.campaigns.length,widgets:this.widgets.length,recommendations:this.recommendationWidgets.length}),this.initDataLayer()}else J("Selwise","Batch endpoint failed, falling back to individual endpoints"),this.recommendationWidgets=[],await this.loadTrackingConfig(),this.initDataLayer(),await this.loadCampaignsAndWidgets();"requestIdleCallback"in window?requestIdleCallback(()=>{this.renderEntitiesWithPolicies()},{timeout:100}):setTimeout(()=>{this.renderEntitiesWithPolicies()},0),"requestIdleCallback"in window?requestIdleCallback(()=>this.initSearch(),{timeout:200}):setTimeout(()=>this.initSearch(),50),"requestIdleCallback"in window?requestIdleCallback(()=>this.initRecommendations(),{timeout:300}):setTimeout(()=>this.initRecommendations(),100)}catch(e){G("Selwise","Failed to load data",e),e instanceof Error&&function(e){const t=window.Sentry;t&&t.getClient()?t.captureException(e,{extra:{context:"init"}}):console.debug("[Selwise] Sentry not initialized, error not captured:",e)}(e)}}else J("Selwise","No site key provided")}async loadTrackingConfig(){if(this.config.siteKey&&this.config.apiUrl)try{const[e,t]=await Promise.allSettled([fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/tracking-config`),fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/integrations`)]);if("fulfilled"===e.status&&e.value.ok){const t=await e.value.json();if(this._trackingConfig=t,t.subscriptionRequired)return J("Selwise","Subscription required:",t.subscriptionMessage),void this.handleSubscriptionInactive(t.subscriptionMessage);const n=t.flushInterval?1e3*t.flushInterval:void 0;this.tracker.setBatcherConfig({enabled:t.batchingEnabled,batchSize:t.batchSize,flushInterval:n,enablePersistence:t.offlinePersistence,enableSendBeacon:t.sendBeaconOnUnload,maxRetries:t.maxRetries,maxQueueSize:t.maxQueueSize,maxStorageEvents:t.maxStorageEvents,debugMode:t.debugMode}),j(t.debugMode||!1),await this.tracker.initialize(),t.debugMode&&W("Selwise","Tracking config loaded:",t),this.config.dataLayerConfig=t.dataLayerConfig}else if("fulfilled"===e.status&&403===e.value.status){const t=await e.value.json().catch(()=>({}));return J("Selwise","Subscription required (HTTP 403):",t.message||"Subscription inactive"),void this.handleSubscriptionInactive(t.message||"Subscription required")}if("fulfilled"===t.status&&t.value.ok){const e=await t.value.json(),n={};for(const t of e.integrations||[]){const e=t.reverseEventMapping||{};t.enabled&&e&&Object.assign(n,e)}Object.keys(n).length>0&&(this.config.reverseEventMapping=n,W("Selwise","Reverse event mapping loaded:",n))}}catch(e){G("Selwise","Failed to load tracking config, using defaults")}}async loadSiteConfig(){if(!this.config.siteKey||!this.config.apiUrl)return null;try{const e=await fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/config`,{method:"GET"});if(!e.ok){if(403===e.status){const t=await e.json().catch(()=>({}));J("Selwise","Subscription required:",t.message||"Subscription inactive"),this.handleSubscriptionInactive(t.message||"Subscription required")}return null}return await e.json()}catch(e){return G("Selwise","Failed to load batch config, falling back to individual endpoints"),null}}async loadCampaignsAndWidgets(){const e=this.loadCampaigns().catch(e=>(K("Selwise","Failed to load campaigns:",e),null)),t=this.loadWidgets().catch(e=>(K("Selwise","Failed to load widgets:",e),null));await Promise.allSettled([e,t])}initDataLayer(){if(!this.config.siteKey)return;const e=this.config.dataLayerConfig||{},t=this.config.reverseEventMapping||{};this.dataLayerEnabled=e.enabled??!0,this.dataLayerManager=new $n(this.tracker,this.config.siteKey,yt(this.config.apiUrl),{enabled:e.enabled??!0,variableName:e.variableName??"selwiseLayer",pageDetection:e.pageDetection??"auto",autoPageTracking:e.autoPageTracking??!0,cartAbandonmentTimeout:e.cartAbandonmentTimeout??30,pageTypePatterns:e.pageTypePatterns??void 0,debugMode:e.debugMode??!1,cookieConsent:e.cookieConsent,trackingModules:e.trackingModules,bufferSize:e.bufferSize,flushInterval:e.flushInterval,reverseEventMapping:Object.keys(t).length>0?t:void 0,externalDataLayerName:"dataLayer",attachToGlobalApi:Boolean(this.config.exposeGlobal)}),this.dataLayerEnabled?(this.dataLayerManager.init(),W("Selwise","Data layer manager initialized and started")):W("Selwise","Data layer manager created but NOT enabled (disabled in dashboard settings)"),e.debugMode&&W("Selwise","Data layer initialized with config:",e)}getVariant(e){return this.experiments?.getVariant(e)}getExperimentVariant(e){return this.experiments?this.experiments.getAssignedVariant(e):null}getActiveExperiments(){return this.experiments?this.experiments.getAllAssignments():[]}async trackOrder(e){return this.tracker.trackOrder(e)}async identify(e,t){if(!e)return{success:!1,merged:!1};const n=await this.tracker.identify(e,t);return this.segments&&this.segments.updateUserIdentifiers(this.tracker.getSiteUserId(),this.tracker.getSiteUserProfileId()),n}async setTraits(e){return this.tracker.setTraits(e)}track(e,t){return this.tracker.track(e,t)}getSiteUserId(){return this.tracker.getSiteUserId()}getVisitorId(){return this.tracker.getVisitorId()}getSessionId(){return this.tracker.getSessionId()}getJourneyId(){return this.tracker.getJourneyId()}getJourneyState(){return this.tracker.getJourneyState()}endJourney(){this.tracker.endJourney()}pushDataLayer(e){this.dataLayerManager&&this.dataLayerEnabled?this.dataLayerManager.push(e):J("Selwise","Data layer is not initialized; pushDataLayer was ignored")}getDataLayer(){return this.dataLayerManager&&this.dataLayerEnabled?this.dataLayerManager.getLayerState(500):[]}getConsentState(){return this.dataLayerManager&&this.dataLayerEnabled?this.dataLayerManager.getConsentState():null}grantConsent(e){this.dataLayerManager&&this.dataLayerEnabled?this.dataLayerManager.grantConsent(e):J("Selwise","Data layer is not initialized; grantConsent was ignored")}revokeConsent(e){this.dataLayerManager&&this.dataLayerEnabled?this.dataLayerManager.revokeConsent(e):J("Selwise","Data layer is not initialized; revokeConsent was ignored")}async initSearch(){try{const{SearchModule:e}=await this.moduleLoaders.loadSearchModule();this.searchModule=new e(this.config.apiUrl,this.config.siteKey,this.experiments??void 0,this.segments??void 0),await this.searchModule.init()}catch(e){G("Selwise","Search module initialization failed",e)}}async initRecommendations(){if(!this.recommendationsInitialized)try{const{initRecommendations:e,cleanup:t}=await this.moduleLoaders.loadRecommendationModule();await e({siteKey:this.config.siteKey,apiEndpoint:this.config.apiUrl,experimentManager:this.experiments??void 0,segmentManager:this.segments??void 0,widgets:this.recommendationWidgets}),this.recommendationsInitialized=!0,this.recommendationsCleanup=t,W("Selwise","Recommendations module initialized")}catch(e){G("Selwise","Recommendations module initialization failed",e)}}async loadCampaigns(){const e=await fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/campaigns`,{method:"GET"});if(!e.ok){if(403===e.status){const t=await e.json().catch(()=>({}));J("Selwise","Subscription required for campaigns:",t.message||"Subscription inactive"),this.handleSubscriptionInactive(t.message||"Subscription required")}throw new Error("Failed to fetch campaigns")}const t=await e.json();this.campaigns=t.campaigns||[]}async loadWidgets(){const e=await fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/widgets`,{method:"GET"});if(!e.ok){if(403===e.status){const t=await e.json().catch(()=>({}));J("Selwise","Subscription required for widgets:",t.message||"Subscription inactive"),this.handleSubscriptionInactive(t.message||"Subscription required")}return}const t=await e.json();this.widgets=t.widgets||[]}async loadScripts(){const e=window.location.pathname;try{const t=await fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/scripts?path=${encodeURIComponent(e)}`,{method:"GET"});if(!t.ok)return void G("Selwise","Failed to fetch scripts");const n=(await t.json()).scripts||[];W("Selwise","Loading custom scripts:",n.length),n.forEach(e=>{try{if(e.css){const t=document.createElement("style");t.setAttribute("data-selwise-script-css",e.id),t.textContent=e.css,document.head.appendChild(t),W("Selwise",`Injected script CSS: ${e.name}`)}const t=document.createElement("script");t.setAttribute("data-selwise-script",e.id),t.textContent=e.code,document.body.appendChild(t),W("Selwise",`Injected script: ${e.name}`),this.tracker.track("script_injected",{entityType:"script",entityId:e.id,metadata:{name:e.name}})}catch(t){K("Selwise",`Failed to execute script: ${e.name}`),G("Selwise","Script execution error details:",t),t instanceof SyntaxError&&J("Selwise","Script syntax error. Please check for invalid characters or escapes.");try{this.tracker.track("script_error",{entityType:"script",entityId:e.id,metadata:{name:e.name,message:t?.message}})}catch{}}})}catch(e){G("Selwise","Failed to load scripts",e)}}shouldRenderForCurrentPage(e,t){const n=Yt(e.pageTargetingJson,window.location.href);return n||W("Selwise",`Skipping ${t} due to page targeting: ${e.id}`),n}buildDisplayCandidates(){return[...this.campaigns.map(e=>({entity:e,type:"campaign"})),...this.widgets.map(e=>({entity:e,type:"widget"}))].filter(({entity:e,type:t})=>this.shouldRenderForCurrentPage(e,t)).map(({entity:e,type:t})=>{const n=e.placementConfigJson||{},i=n.selector,o=n.position||n.insertPosition,r=n.conflictResolution||{},a=this.conflictResolver.applyConfig({id:`${t}:${e.id}`,type:t,selector:i,placementPosition:o,priority:e.priority??r.priority,conflictBehavior:r.behavior,placementConfigJson:n});return{id:a.id,type:t,priority:a.priority,conflictBehavior:a.conflictBehavior,selector:a.selector,placementPosition:a.placementPosition,placementConfigJson:n,sourceId:e.id,sourceEntity:e,frequencyCapConfig:n.frequencyCap}})}async renderEntitiesWithPolicies(){const e=this.buildDisplayCandidates();if(W("Selwise","Rendering entities with policies:",e.length),this.renderedEntities.clear(),this.frequencyCapManager.cleanup(),0===e.length)return;const t=this.conflictResolver.resolveAll(e),n=new Set(t.flatMap(e=>e.selected.map(e=>e.id)));for(const t of e){if(!n.has(t.id))continue;const e=`display:${t.id}`;if(t.frequencyCapConfig){const n=this.frequencyCapManager.canShow(e,t.frequencyCapConfig);if(!n.allowed){W("Selwise",`Skipping ${t.type} due to frequency cap (${n.reason||"limit"}):`,t.sourceId);continue}}await this.renderEntity(t.sourceEntity,t.type)&&t.frequencyCapConfig&&this.frequencyCapManager.recordShown(e)}}async renderEntity(e,t,n=!1){const i="true"===St().getItem(h),o="campaign"===t?"campaign":"widget";if(this.renderedEntities.has(e.id))return W("Selwise",`Skipping already rendered ${o}: ${e.id}`),!1;if(e.isTestMode&&!i)return J("Selwise",`Skipping test mode ${o}: ${e.id}${"campaign"===t?" (Run localStorage.setItem('selwise_test_mode', 'true') to view)":""}`),!1;if(!this.shouldRenderForCurrentPage(e,t))return!1;const r=n?null:this.experiments?.getVariantModuleForTarget(e.id);if(r&&r.moduleData)return W("Selwise",`Rendering variant module for ${o}: ${e.id} -> variant: ${r.moduleData.id}`),await this.renderVariantModule(r.moduleData,r.experimentId,r.variantId,r.targetType||t),!1;if(this.experiments&&!this.experiments.shouldRenderTarget(e.id))return W("Selwise",`Skipping ${o} (excluded by experiment): ${e.id}`),!1;if(this.segments&&e.segmentTargetingMode&&e.segmentIds&&!await this.segments.shouldShow(e.segmentTargetingMode,e.segmentIds))return W("Selwise",`Skipping ${o} due to segment targeting: ${e.id}`),!1;if(!e.contentJson||0===Object.keys(e.contentJson).length)return J("Selwise",`Skipping empty ${o}: ${e.id}`),!1;let a=jt(e.contentJson||{}),s=e.stylesJson||{},l=e.placementConfigJson||{};const c=this.experiments?.getVariant(e.id)||this.experiments?.getAssignmentByTargetId(e.id);if(c){const e=Wt(c);e?.content&&"object"==typeof e.content&&(a=qt(a,jt(e.content))),e?.styles&&"object"==typeof e.styles&&(s=qt(s,e.styles)),e?.placement&&"object"==typeof e.placement&&(l=qt(l,e.placement))}const d={id:e.id,type:e.type,placementConfigJson:l,__entityType:t},u={id:e.id,contentJson:a,stylesJson:s};this.cleanupRenderedEntityById(e.id,t);const p=this.renderer.render(d,u);return!!p&&(this.renderedEntities.add(e.id),this.tracker.track("impression",{entityType:"campaign"===t?"campaign":"widget",entityId:e.id}),c&&this.experiments?.trackImpression(c.experimentId),p.addEventListener("click",n=>{const i=n.target;if("A"===i.tagName||"BUTTON"===i.tagName){const n=i.textContent?.toLowerCase()||"",o=/add to cart|buy now|purchase|add to bag|sepete ekle|satın al|buy now/i.test(n);this.tracker.track("click",{entityType:"campaign"===t?"campaign":"widget",entityId:e.id}),"campaign"===t&&o&&this.tracker.track("add_to_cart",{entityType:"campaign",entityId:e.id,metadata:{buttonText:i.textContent}}),c&&this.experiments?.trackConversion(c.experimentId)}}),!0)}async renderVariantModule(e,t,n,i){let o,r;switch(e.data?(o=e.data,r=e.targetType||i||"widget"):(o=e,r=i||"widget"),this.experiments&&this.experiments.trackImpression(t),this.tracker.track("impression",{entityType:r,entityId:o.id,metadata:{experimentId:t,variantId:n,isVariantModule:!0}}),r){case"widget":await this.renderEntity(o,"widget",!0);break;case"campaign":await this.renderEntity(o,"campaign",!0);break;case"recommendation":W("Selwise","Variant recommendation module will be rendered by recommendations module");break;case"search_config":W("Selwise","Variant search config will be applied by search module");break;default:J("Selwise",`Unknown target type for variant module: ${r}`)}}handleSubscriptionInactive(e){if(this.enabled=!1,this.subscriptionInactive=!0,this.subscriptionMessage=e,"undefined"!=typeof window){const t=new CustomEvent("selwise:subscription-inactive",{detail:{message:e}});window.dispatchEvent(t)}J("Selwise","Subscription inactive. Widget will not display. Message: "+e)}}export{ji as Selwise,ji as default,yt as resolveApiUrl};