@selwise/widget 1.0.4 → 1.0.5

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 +1,2 @@
1
1
  /*! For license information please see index.cjs.LICENSE.txt */
2
- (()=>{"use strict";var e={48(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 c(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 l(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"}),c({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"}]},l()],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"}),l()],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"}}}),c({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","ideasoft","ikas","ticimax","tsoft","wix","bigcommerce","opencart","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=u,t.validateFrequencyCapPayload=function(e){if(null==e)return{valid:!0};if(!d(e))return{valid:!1,message:"invalid frequency cap payload"};const t=Object.keys(e).filter(e=>!c.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&&u(e.minInterval)?{valid:!0}:{valid:!1,message:"invalid frequency cap minInterval"}},t.validateDataLayerConfig=function(e){if(!d(e))return{valid:!1,message:"invalid data layer config payload"};if(void 0!==e.externalDataLayerName&&("string"!=typeof e.externalDataLayerName||0===e.externalDataLayerName.trim().length))return{valid:!1,message:"invalid external data layer name"};if(void 0!==e.useExternalDataLayer&&"boolean"!=typeof e.useExternalDataLayer)return{valid:!1,message:"invalid use external data layer flag"};if(void 0!==e.platform&&("string"!=typeof e.platform||!l.has(e.platform)))return{valid:!1,message:"invalid data layer platform"};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(!d(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(!d(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(!d(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(!d(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=d(e.trackingModules)?e.trackingModules:{};for(const e of Object.keys(t)){const i=n[e];d(i)&&"boolean"==typeof i.enabled&&(t[e]={enabled:i.enabled,...d(i.config)?{config:i.config}:{}})}const o={...i.COOKIE_CONSENT_DEFAULTS,...d(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:d(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),c=new Set(["perSession","perDay","perWeek","total","minInterval"]),l=new Set(i.DATA_LAYER_PLATFORMS);function d(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function u(e){return s.has(e)}},496(e,t){Object.defineProperty(t,"__esModule",{value:!0})},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(496),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 ISO code"},{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.DATA_LAYER_PLATFORMS=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.DATA_LAYER_PLATFORMS=["auto","generic","ideasoft","ikas","ticimax","tsoft","akinon","shopify","woocommerce","magento","wix","bigcommerce","opencart","prestashop","custom","none"],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:{},c={};if("string"==typeof r.selector&&r.selector.trim().length>0&&(c.selector=r.selector.trim()),"string"==typeof r.insertPosition&&o.has(r.insertPosition)&&(c.insertPosition=r.insertPosition),n?.placementOptions?.length){const e=new Set(n.placementOptions);"string"==typeof r.position&&e.has(r.position)?c.position=r.position:"selector"!==n.placementType&&(c.position=n.placementOptions[0])}const l=s(e,r);return c.placementType=l,a(r.conflictResolution)&&(c.conflictResolution=r.conflictResolution),a(r.frequencyCap)&&(c.frequencyCap=r.frequencyCap),c};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&&c.has(e.position)?void 0===e.floatingPosition||"string"==typeof e.floatingPosition&&l.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"]),c=new Set(i.SEARCH_POSITIONS.map(e=>e.value)),l=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]:{},c=new Set(n.fields.map(e=>e.key));for(const[e,t]of Object.entries(s))c.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),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};n.r(i),n.d(i,{Selwise:()=>to,default:()=>to,resolveApiUrl:()=>bt});let o=!1;var r=n(529);const a="selwise_sid",s="selwise_vid",c="selwise_suid",l="selwise_supid",d="selwise_journey_id",u="selwise_journey_created",p="selwise_correlation_id",h="selwise_correlation_created",g="selwise_test_mode",m="selwise_last_touch",f="selwise_last_touch_reco",y="selwise_last_touch_search",b="selwise_experiments",w="selwise_consent",S="selwise_interacted_",x="selwise_merged_vids",v="selwise_user_traits",C={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"]},k="data-selwise-root",T="data-selwise-entity-id",I="data-selwise-entity-type",E=`[${k}="true"]`,_=new Map;function P(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 A(e){return{normal:"400",medium:"500",semibold:"600",bold:"700"}[e||"normal"]||"400"}function $(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(k,"true"),e.setAttribute(T,t.id),e.setAttribute(I,i)}function O(e){const t=_.get(e);t&&(t.observer&&t.observer.disconnect(),null!==t.timeoutId&&clearTimeout(t.timeoutId),_.delete(e))}function D(e,t,n=6e3){O(e);const i=()=>{try{const n=t();return n&&O(e),n}catch(t){return console.error("[Selwise] Deferred renderer failed:",t),O(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(()=>{O(e)},n);_.set(e,{observer:o,timeoutId:r})}function L(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 N(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 M(e){try{return!!localStorage.getItem(`${S}${e}`)}catch{return!1}}function R(e){try{localStorage.setItem(`${S}${e}`,"true")}catch{}}function B(e){if(!e)return"#";const t=e.trim();return t&&/^(https?:|mailto:|tel:|\/|#)/i.test(t)?t:"#"}function U(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 z(e,t,n,i=6e3){const o=t.placementConfigJson||{},r=(a=o)?"string"!=typeof a.selector?"":a.selector.trim():"";var a;if(!r)return O(n),console.warn(`[Selwise] Selector is required for widget type "${t.type}": ${t.id}`),!1;const s={...o,selector:r};return N(e,s)?(O(n),!0):(D(n,()=>N(e,s),i),!1)}let q=!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=A(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 j=!1;function H(e){j=e}function W(){if("undefined"==typeof localStorage)return!1;try{return j||"true"===localStorage.getItem("selwise_test_mode")||"true"===localStorage.getItem("selwise_debug")}catch{return j}}const K=(e,...t)=>{W()&&console.log(`[${e}]`,...t)},G=(e,...t)=>{W()&&console.debug(`[${e}]`,...t)},J=(e,...t)=>{console.error(`[${e}]`,...t)},V=(e,...t)=>{console.warn(`[${e}]`,...t)};function Y(e,t){try{const n=`${w}_${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 Q(e,t){const n=window.Selwise?.siteKey;if(!n)return null;const i=function(e){try{const t=`${w}_${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||{};K("CookieConsent","campaign payload:",{content:o,styles:r});const a=r,s=window.Selwise?.trackingConfig?.cookieConsent||{},c=e.configJson||{},l={granularEnabled:a.granularEnabled??s.granularEnabled??c.granularEnabled??!1,requiredCategories:(d=a.requiredCategories??s.requiredCategories??c.requiredCategories??"necessary",Array.isArray(d)?d:"string"==typeof d?d.split(",").map(e=>e.trim()).filter(Boolean):["necessary"]),timeoutMs:a.timeoutMs??s.timeoutMs??c.timeoutMs??0};var d;const u=l.granularEnabled??!1,p=new Set(l.requiredCategories||["necessary"]),h=l.timeoutMs||0;K("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:b="Decline",customizeButtonText:S="Customize",subtext:x,linkText:v,linkUrl:C,policyLinkText:k,policyLinkUrl:T}=o,{backgroundColor:I="#1a1a1a",textColor:E="#ffffff",buttonColor:_,buttonTextColor:A,declineButtonColor:O,declineButtonTextColor:D,customizeButtonColor:L,customizeButtonTextColor:N,padding:M="16px",borderRadius:R="8px",shadow:U="lg",border:z="none",maxWidth:q,showDeclineButton:F=!0,showCustomizeButton:j=!0,showCloseButton:H=!1,autoHideAfterMs:W=0,linkColor:G="#60a5fa",headlineFontSize:J,headlineFontWeight:V,textFontSize:Q,buttonFontSize:X,buttonFontWeight:Z}=r,ee=m||"We use cookies",te=f||x||"",ne=e.placementConfigJson?.position||"bottom",ie=_||E,oe=A||I,re=O||"transparent",ae=D||E,se=O?"none":`1px solid ${E}`,ce=L||"transparent",le=N||E,de=v||k||"",ue=B(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: ${M};\n border-radius: ${R};\n box-shadow: ${P(U)};\n ${z&&"none"!==z?`border: ${z};`:""}\n ${q&&"bottom"===ne?`max-width: ${q}; 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: ${q||"500px"};\n width: ${q?"auto":"90%"};\n z-index: 2147483647;\n `:"bottom-left"===ne?`\n position: fixed;\n bottom: 20px;\n left: 20px;\n max-width: ${q||"400px"};\n z-index: 2147483647;\n `:"bottom-right"===ne?`\n position: fixed;\n bottom: 20px;\n right: 20px;\n max-width: ${q||"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 `,$(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(V||"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(V||"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(G)}; 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 ${F?`\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(b)}\n </button>\n `:""}\n ${u&&j?`\n <button class="selwise-bar-btn selwise-customize" style="background: ${pe(ce)}; color: ${pe(le)}; border: ${pe("transparent"===ce?`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 Y(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(),Y(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 Y(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}};Y(n,e),he.remove(),ve("timeout",e),xe()},h)),W>0&&(be=window.setTimeout(()=>{Se||(Se=!0,he.remove(),xe())},W)),document.body.appendChild(he),he}const{entries:X,setPrototypeOf:Z,isFrozen:ee,getPrototypeOf:te,getOwnPropertyDescriptor:ne}=Object;let{freeze:ie,seal:oe,create:re}=Object,{apply:ae,construct:se}="undefined"!=typeof Reflect&&Reflect;ie||(ie=function(e){return e}),oe||(oe=function(e){return e}),ae||(ae=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)}),se||(se=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 ce=Ce(Array.prototype.forEach),le=Ce(Array.prototype.lastIndexOf),de=Ce(Array.prototype.pop),ue=Ce(Array.prototype.push),pe=Ce(Array.prototype.splice),he=Ce(String.prototype.toLowerCase),ge=Ce(String.prototype.toString),me=Ce(String.prototype.match),fe=Ce(String.prototype.replace),ye=Ce(String.prototype.indexOf),be=Ce(String.prototype.trim),we=Ce(Object.prototype.hasOwnProperty),Se=Ce(RegExp.prototype.test),xe=(ve=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return se(ve,t)});var ve;function Ce(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 ae(e,t,i)}}function ke(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:he;Z&&Z(e,null);let i=t.length;for(;i--;){let o=t[i];if("string"==typeof o){const e=n(o);e!==o&&(ee(t)||(t[i]=e),o=e)}e[o]=!0}return e}function Te(e){for(let t=0;t<e.length;t++)we(e,t)||(e[t]=null);return e}function Ie(e){const t=re(null);for(const[n,i]of X(e))we(e,n)&&(Array.isArray(i)?t[n]=Te(i):i&&"object"==typeof i&&i.constructor===Object?t[n]=Ie(i):t[n]=i);return t}function Ee(e,t){for(;null!==e;){const n=ne(e,t);if(n){if(n.get)return Ce(n.get);if("function"==typeof n.value)return Ce(n.value)}e=te(e)}return function(){return null}}const _e=ie(["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"]),Pe=ie(["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"]),Ae=ie(["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"]),$e=ie(["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"]),Oe=ie(["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"]),De=ie(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Le=ie(["#text"]),Ne=ie(["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"]),Me=ie(["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=ie(["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"]),Be=ie(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Ue=oe(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ze=oe(/<%[\w\W]*|[\w\W]*%>/gm),qe=oe(/\$\{[\w\W]*/gm),Fe=oe(/^data-[\-\w.\u00B7-\uFFFF]+$/),je=oe(/^aria-[\-\w]+$/),He=oe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),We=oe(/^(?:\w+script|data):/i),Ke=oe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ge=oe(/^html$/i),Je=oe(/^[a-z][.\w]*(-[.\w]+)+$/i);var Ve=Object.freeze({__proto__:null,ARIA_ATTR:je,ATTR_WHITESPACE:Ke,CUSTOM_ELEMENT:Je,DATA_ATTR:Fe,DOCTYPE_NAME:Ge,ERB_EXPR:ze,IS_ALLOWED_URI:He,IS_SCRIPT_OR_DATA:We,MUSTACHE_EXPR:Ue,TMPLIT_EXPR:qe});const Ye=function(){return"undefined"==typeof window?null:window};var Qe=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Ye();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:c,Element:l,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:h,trustedTypes:g}=t,m=l.prototype,f=Ee(m,"cloneNode"),y=Ee(m,"remove"),b=Ee(m,"nextSibling"),w=Ee(m,"childNodes"),S=Ee(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 X&&"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:L,ATTR_WHITESPACE:N,CUSTOM_ELEMENT:M}=Ve;let{IS_ALLOWED_URI:R}=Ve,B=null;const U=ke({},[..._e,...Pe,...Ae,...Oe,...Le]);let z=null;const q=ke({},[...Ne,...Me,...Re,...Be]);let F=Object.seal(re(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(re(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let K=!0,G=!0,J=!1,V=!0,Y=!1,Q=!0,Z=!1,ee=!1,te=!1,ne=!1,oe=!1,ae=!1,se=!0,ve=!1,Ce=!0,Te=!1,Ue={},ze=null;const qe=ke({},["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 Fe=null;const je=ke({},["audio","video","img","source","image","track"]);let We=null;const Ke=ke({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Je="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=ke({},[Je,Qe,Xe],ge);let it=ke({},["mi","mo","mn","ms","mtext"]),ot=ke({},["annotation-xml"]);const rt=ke({},["title","style","font","a","script"]);let at=null;const st=["application/xhtml+xml","text/html"];let ct=null,lt=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(!lt||lt!==e){if(e&&"object"==typeof e||(e={}),e=Ie(e),at=-1===st.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ct="application/xhtml+xml"===at?ge:he,B=we(e,"ALLOWED_TAGS")?ke({},e.ALLOWED_TAGS,ct):U,z=we(e,"ALLOWED_ATTR")?ke({},e.ALLOWED_ATTR,ct):q,tt=we(e,"ALLOWED_NAMESPACES")?ke({},e.ALLOWED_NAMESPACES,ge):nt,We=we(e,"ADD_URI_SAFE_ATTR")?ke(Ie(Ke),e.ADD_URI_SAFE_ATTR,ct):Ke,Fe=we(e,"ADD_DATA_URI_TAGS")?ke(Ie(je),e.ADD_DATA_URI_TAGS,ct):je,ze=we(e,"FORBID_CONTENTS")?ke({},e.FORBID_CONTENTS,ct):qe,j=we(e,"FORBID_TAGS")?ke({},e.FORBID_TAGS,ct):Ie({}),H=we(e,"FORBID_ATTR")?ke({},e.FORBID_ATTR,ct):Ie({}),Ue=!!we(e,"USE_PROFILES")&&e.USE_PROFILES,K=!1!==e.ALLOW_ARIA_ATTR,G=!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,Q=!1!==e.SAFE_FOR_XML,Z=e.WHOLE_DOCUMENT||!1,ne=e.RETURN_DOM||!1,oe=e.RETURN_DOM_FRAGMENT||!1,ae=e.RETURN_TRUSTED_TYPE||!1,te=e.FORCE_BODY||!1,se=!1!==e.SANITIZE_DOM,ve=e.SANITIZE_NAMED_PROPS||!1,Ce=!1!==e.KEEP_CONTENT,Te=e.IN_PLACE||!1,R=e.ALLOWED_URI_REGEXP||He,Ze=e.NAMESPACE||Xe,it=e.MATHML_TEXT_INTEGRATION_POINTS||it,ot=e.HTML_INTEGRATION_POINTS||ot,F=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(F.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(F.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(F.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Y&&(G=!1),oe&&(ne=!0),Ue&&(B=ke({},Le),z=[],!0===Ue.html&&(ke(B,_e),ke(z,Ne)),!0===Ue.svg&&(ke(B,Pe),ke(z,Me),ke(z,Be)),!0===Ue.svgFilters&&(ke(B,Ae),ke(z,Me),ke(z,Be)),!0===Ue.mathMl&&(ke(B,Oe),ke(z,Re),ke(z,Be))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?W.tagCheck=e.ADD_TAGS:(B===U&&(B=Ie(B)),ke(B,e.ADD_TAGS,ct))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?W.attributeCheck=e.ADD_ATTR:(z===q&&(z=Ie(z)),ke(z,e.ADD_ATTR,ct))),e.ADD_URI_SAFE_ATTR&&ke(We,e.ADD_URI_SAFE_ATTR,ct),e.FORBID_CONTENTS&&(ze===qe&&(ze=Ie(ze)),ke(ze,e.FORBID_CONTENTS,ct)),e.ADD_FORBID_CONTENTS&&(ze===qe&&(ze=Ie(ze)),ke(ze,e.ADD_FORBID_CONTENTS,ct)),Ce&&(B["#text"]=!0),Z&&ke(B,["html","head","body"]),B.table&&(ke(B,["tbody"]),delete j.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw xe('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw xe('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(""));ie&&ie(e),lt=e}},ht=ke({},[...Pe,...Ae,...$e]),gt=ke({},[...Oe,...De]),mt=function(e){ue(n.removed,{element:e});try{S(e).removeChild(e)}catch(t){y(e)}},ft=function(e,t){try{ue(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){ue(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ne||oe)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=me(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 c&&e instanceof c};function xt(e,t,i){ce(e,e=>{e.call(n,t,i,lt)})}const vt=function(e){let t=null;if(xt(_.beforeSanitizeElements,e,null),wt(e))return mt(e),!0;const i=ct(e.nodeName);if(xt(_.uponSanitizeElement,e,{tagName:i,allowedTags:B}),Q&&e.hasChildNodes()&&!St(e.firstElementChild)&&Se(/<[/\w!]/g,e.innerHTML)&&Se(/<[/\w!]/g,e.textContent))return mt(e),!0;if(7===e.nodeType)return mt(e),!0;if(Q&&8===e.nodeType&&Se(/<[/\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(F.tagNameCheck instanceof RegExp&&Se(F.tagNameCheck,i))return!1;if(F.tagNameCheck instanceof Function&&F.tagNameCheck(i))return!1}if(Ce&&!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 l&&!function(e){let t=S(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});const n=he(e.tagName),i=he(t.tagName);return!!tt[e.namespaceURI]&&(e.namespaceURI===Qe?t.namespaceURI===Xe?"svg"===n:t.namespaceURI===Je?"svg"===n&&("annotation-xml"===i||it[i]):Boolean(ht[n]):e.namespaceURI===Je?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===Je&&!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||!Se(/<\/no(script|embed|frames)/i,e.innerHTML)?(Y&&3===e.nodeType&&(t=e.textContent,ce([P,A,$],e=>{t=fe(t,e," ")}),e.textContent!==t&&(ue(n.removed,{element:e.cloneNode()}),e.textContent=t)),xt(_.afterSanitizeElements,e,null),!1):(mt(e),!0)},Ct=function(e,t,n){if(se&&("id"===t||"name"===t)&&(n in i||n in dt))return!1;if(G&&!H[t]&&Se(O,t));else if(K&&Se(D,t));else if(W.attributeCheck instanceof Function&&W.attributeCheck(t,e));else if(!z[t]||H[t]){if(!(kt(e)&&(F.tagNameCheck instanceof RegExp&&Se(F.tagNameCheck,e)||F.tagNameCheck instanceof Function&&F.tagNameCheck(e))&&(F.attributeNameCheck instanceof RegExp&&Se(F.attributeNameCheck,t)||F.attributeNameCheck instanceof Function&&F.attributeNameCheck(t,e))||"is"===t&&F.allowCustomizedBuiltInElements&&(F.tagNameCheck instanceof RegExp&&Se(F.tagNameCheck,n)||F.tagNameCheck instanceof Function&&F.tagNameCheck(n))))return!1}else if(We[t]);else if(Se(R,fe(n,N,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==ye(n,"data:")||!Fe[e])if(J&&!Se(L,fe(n,N,"")));else if(n)return!1;return!0},kt=function(e){return"annotation-xml"!==e&&me(e,M)},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:c}=r,l=ct(a),d=c;let u="value"===a?d:be(d);if(i.attrName=l,i.attrValue=u,i.keepAttr=!0,i.forceKeepAttr=void 0,xt(_.uponSanitizeAttribute,e,i),u=i.attrValue,!ve||"id"!==l&&"name"!==l||(ft(a,e),u="user-content-"+u),Q&&Se(/((--!?|])>)|<\/(style|title|textarea)/i,u)){ft(a,e);continue}if("attributename"===l&&me(u,"href")){ft(a,e);continue}if(i.forceKeepAttr)continue;if(!i.keepAttr){ft(a,e);continue}if(!V&&Se(/\/>/i,u)){ft(a,e);continue}Y&&ce([P,A,$],e=>{u=fe(u,e," ")});const p=ct(e.nodeName);if(Ct(p,l,u)){if(x&&"object"==typeof g&&"function"==typeof g.getAttributeType)if(s);else switch(g.getAttributeType(p,l)){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):de(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,l=null;if(et=!e,et&&(e="\x3c!--\x3e"),"string"!=typeof e&&!St(e)){if("function"!=typeof e.toString)throw xe("toString is not a function");if("string"!=typeof(e=e.toString()))throw xe("dirty is not a string, aborting")}if(!n.isSupported)return e;if(ee||pt(t),n.removed=[],"string"==typeof e&&(Te=!1),Te){if(e.nodeName){const t=ct(e.nodeName);if(!B[t]||j[t])throw xe("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)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(!ne&&!Y&&!Z&&-1===e.indexOf("<"))return x&&ae?x.createHTML(e):e;if(i=yt(e),!i)return ne?null:ae?v:""}i&&te&&mt(i.firstChild);const d=bt(Te?e:i);for(;s=d.nextNode();)vt(s),Tt(s),s.content instanceof a&&It(s.content);if(Te)return e;if(ne){if(oe)for(l=T.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(z.shadowroot||z.shadowrootmode)&&(l=E.call(o,l,!0)),l}let u=Z?i.outerHTML:i.innerHTML;return Z&&B["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Se(Ge,i.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+i.ownerDocument.doctype.name+">\n"+u),Y&&ce([P,A,$],e=>{u=fe(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(){lt=null,ee=!1},n.isValidAttribute=function(e,t,n){lt||pt({});const i=ct(e),o=ct(t);return Ct(i,o,n)},n.addHook=function(e,t){"function"==typeof t&&ue(_[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=le(_[e],t);return-1===n?void 0:pe(_[e],n,1)[0]}return de(_[e])},n.removeHooks=function(e){_[e]=[]},n.removeAllHooks=function(){_={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Xe={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 Ze(e,t){if(!e)return"";const n=t?{...Xe,...t}:Xe;return Qe.sanitize(e,n)}function et(e){return e?Qe.sanitize(e,{...Xe,ADD_TAGS:["img","picture","source"],ADD_ATTR:["loading","decoding","srcset","sizes","data-product-id","data-action"]}):""}function tt(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 nt{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){J("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 it(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 ot(e,t,n,i,o="comma"){const r=performance.now(),a=n-t;requestAnimationFrame(function n(s){const c=s-r,l=Math.min(c/i,1),d=1-Math.pow(1-l,4),u=Math.round(t+a*d);e.textContent=it(u,o),l<1&&requestAnimationFrame(n)})}async function rt(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 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:c,timePeriod:l}=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",$(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 c=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:c,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 rt(a,{},5e3);if(!s.ok)throw new Error("Failed to fetch product view count");const c=(await s.json()).count||0;if(!1!==r.animateCounter)o.forEach(e=>{ot(e,0,c,r.animationDuration||1e3,r.separator||"comma")});else{const e=it(c,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,l,c,i),s):null}function st(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:c,metricType:l}=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",$(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 rt(a,{},5e3);if(!s.ok)throw new Error("Failed to fetch cart count");const c=(await s.json()).count||0;if(!1!==r.animateCounter)o.forEach(e=>{ot(e,0,c,r.animationDuration||1e3,r.separator||"comma")});else{const e=it(c,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,l,c,i),s):null}const ct=/^[^\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 dt(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 ut{render(e,t){!function(){if(o)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),o=!0}();const n={...t,stylesJson:(i=e.type,a=t.stylesJson,(0,r.isWidgetType)(i)?(0,r.sanitizeStyles)(i,a||{}):a||{})};var i,a;switch(e.type){case"announcement_bar":return function(e,t){if(M(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",c=i.textColor||"#ffffff",l=i.buttonColor||c,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||c,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=c,S.style.padding=u,S.style.fontSize=p,S.style.fontWeight=A(h),S.style.gap="12px",g&&"none"!==g&&(S.style.borderBottom=g),$(S,e,t);const x=U({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=B(n.buttonUrl),t.className="selwise-bar-btn",t.style.background=l,t.style.color=d,t.textContent=n.buttonText,t.addEventListener("click",()=>R(e.id)),S.appendChild(t)}if(m){const e=L(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||{},o=n.title||n.headline||"",a=n.text||"",s=n.subtext||"",c=i.backgroundColor||"#f3f4f6",l=i.textColor||"#1f2937",d=i.buttonColor||l,u=i.buttonTextColor||c,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,r.resolveInlineBannerLayout)({imageMode:f,contentDirection:i.contentDirection,contentAlignment:i.contentAlignment}),I=document.createElement("div");I.className="selwise-widget selwise-inline",I.style.backgroundColor=c,I.style.color=l,I.style.padding=p,I.style.borderRadius=h,I.style.boxShadow=P(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),$(I,e,t);const E=U({imageUrl:n.imageUrl,mode:f,size:y,aspectRatio:b,objectFit:w,borderRadius:"fullWidth"===f?"0px":S,alt:""});E&&I.appendChild(E);const _=document.createElement("div");if(_.className="selwise-banner-content",_.style.flex="1",_.style.minWidth="0",_.style.display="flex",_.style.flexDirection="column",_.style.gap="4px",_.style.alignItems=C,_.style.textAlign=k,o){const e=document.createElement("h4");e.style.fontSize="16px",e.style.fontWeight="600",e.style.margin="0",e.textContent=o,_.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?" - ":""),_.appendChild(e)}let A=null;return n.buttonText&&(A=document.createElement("a"),A.href=B(n.buttonUrl),A.textContent=n.buttonText,A.style.padding="10px 20px",A.style.background=d,A.style.color=u,A.style.borderRadius="6px",A.style.textDecoration="none",A.style.fontSize="13px",A.style.fontWeight="600",A.style.whiteSpace="nowrap",A.style.display="inline-block",A.style.alignSelf=T),"row"===v&&A?(I.appendChild(_),I.appendChild(A)):(A&&(A.style.marginTop="8px",_.appendChild(A)),I.appendChild(_)),z(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:c="56px",borderRadius:l="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=B(r),f.className=`selwise-widget selwise-floating selwise-floating-${m}`,f.style.backgroundColor=a,f.style.color=s,f.style.borderRadius=String(l),f.style.boxShadow=P(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(c)]||String(c);/^\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"),$(f,e,t),document.body.appendChild(f),f}(e,n);case"exit_intent_popup":return function(e,t){if(M(e.id))return null;if(q)return null;q=!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",c=i.buttonColor||s,l=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 _="animation: selwise-scale-in 0.3s ease-out;";"none"===y?_="animation: none;":"fade"===y?_="animation: selwise-fade-in 0.3s ease-out;":"slide"===y&&(_="animation: selwise-slide-up 0.3s ease-out;");const A=document.createElement("div");A.className="selwise-widget selwise-overlay",A.style.display="none",A.style.backgroundColor=T,A.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=P(f),O.style.cssText+=_;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",()=>A.remove()),O.appendChild(D);const L=U({imageUrl:n.imageUrl,mode:b,size:w,aspectRatio:x,objectFit:v,borderRadius:"fullWidth"===b?"0px":C,alt:""});L&&(L.className="selwise-popup-img",L.style.marginBottom="20px");const N=document.createElement("div");if(N.style.flex="1",o){const e=document.createElement("div");e.className="selwise-popup-title",e.textContent=o,N.appendChild(e)}if(r){const e=document.createElement("div");e.className="selwise-popup-text",e.textContent=r,N.appendChild(e)}if(n.buttonText){const t=document.createElement("a");t.href=B(n.buttonUrl),t.className="selwise-bar-btn",t.style.display="block",t.style.textAlign="center",t.style.background=c,t.style.color=l,t.textContent=n.buttonText,t.addEventListener("click",()=>R(e.id)),N.appendChild(t)}if(!L||"left"!==S&&"right"!==S)L&&"top"===S&&O.appendChild(L),O.appendChild(N),L&&"bottom"===S&&O.appendChild(L);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",L.style.marginBottom="0",e.appendChild(L),e.appendChild(N),O.appendChild(e)}return A.appendChild(O),A.addEventListener("click",e=>{e.target===A&&A.remove()}),document.body.appendChild(A),document.addEventListener("mouseleave",e=>{e.clientY<=0&&"none"===A.style.display&&(A.style.display="flex")},{once:!0}),A}(e,n);case"slide_in":return function(e,t){if(M(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",c=i.textColor||"#1f2937",l=i.buttonColor||c,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=c,v.style.width=u,v.style.padding=p,v.style.borderRadius=h,v.style.boxShadow=P(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),$(v,e,t);const C=document.createElement("button");C.className="selwise-close",C.style.color=c,C.style.top="8px",C.style.right="8px",C.style.position="absolute",C.textContent="×",C.addEventListener("click",()=>v.remove()),v.appendChild(C);const k=U({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=B(n.buttonUrl),t.className="selwise-bar-btn",t.style.display="block",t.style.textAlign="center",t.style.background=l,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",c=i.buttonColor||s,l=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(p),S.style.overflow="hidden",S.style.textAlign=g,h&&"none"!==h&&(S.style.border=h),$(S,e,t);const x=U({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=B(n.buttonUrl),e.className="selwise-bar-btn",e.style.display="inline-block",e.style.background=c,e.style.color=l,e.textContent=n.buttonText,v.appendChild(e)}return"top"===f?(x&&S.appendChild(x),S.appendChild(v)):(S.appendChild(v),x&&S.appendChild(x)),z(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:c}=n,{backgroundColor:l="#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||l,C=document.createElement("div");C.className="selwise-widget selwise-footer",C.style.backgroundColor=l,C.style.color=d,C.style.padding=m,C.style.fontSize=f,C.style.fontWeight=A(y),C.style.boxShadow=P(w),b&&"none"!==b&&(C.style.borderTop=b),$(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=B(c),e.className="selwise-bar-btn",e.style.background=x,e.style.color=v,e.textContent=s,C.appendChild(e)}return!1!==g&&C.appendChild(L(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:c,buttonUrl:l,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)",P=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=A(S),$(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 D=document.createElement("div");D.className="selwise-countdown",D.style.background=_,D.style.color=P;const N="dot"===m?"•":"slash"===m?"/":"none"===m?"":":",M=()=>{if(!N)return;const e=document.createElement("span");e.className="selwise-countdown-sep",e.textContent=N,D.appendChild(e)};if(D.appendChild(F("days","Days",x,v)),M(),D.appendChild(F("hours","Hours",x,v)),M(),D.appendChild(F("minutes","Mins",x,v)),M(),D.appendChild(F("seconds","Secs",x,v)),O.appendChild(D),T){const e=document.createElement("span");e.className="selwise-bar-text",e.style.marginLeft="8px",e.textContent=T,O.appendChild(e)}if(c){const e=document.createElement("a");e.href=B(l),e.className="selwise-bar-btn",e.style.background=I,e.style.color=E,e.textContent=c,O.appendChild(e)}let R;if(O.appendChild(L(p,()=>{O.remove(),R&&clearInterval(R)})),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"]'),c=O.querySelector('[data-unit="hours"]'),l=O.querySelector('[data-unit="minutes"]'),d=O.querySelector('[data-unit="seconds"]');s&&(s.textContent=String(i).padStart(2,"0")),c&&(c.textContent=String(o).padStart(2,"0")),l&&(l.textContent=String(r).padStart(2,"0")),d&&(d.textContent=String(a).padStart(2,"0")),n<=0&&R&&clearInterval(R)};t(),R=window.setInterval(t,1e3)}return O}(e,n);case"cookie_consent":return Q(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 c;if(s.className="selwise-widget selwise-custom",s.style.padding=String(a.containerPadding||"0px"),s.style.backgroundColor=String(a.containerBackground||"transparent"),s.innerHTML=(c=n)?Qe.sanitize(c,{...Xe,ADD_TAGS:["style"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur"]}):"",$(s,e,t),i){const e=document.createElement("style");e.setAttribute("data-selwise-custom-css","true"),e.textContent=tt(i),s.appendChild(e)}const l=e.placementConfigJson||{};if("selector"===l.placementType||"string"==typeof l.selector){if(!z(s,e,`custom:${e.id}`))return null}else document.body.appendChild(s);if(o){const n=new nt;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=at(e,t);return i?(O(n),i):(D(n,()=>{const n=at(e,t);return Boolean(n)},7e3),null)}(e,n);case"cart_count":return function(e,t){const n=`cart-count:${e.id}`,i=st(e,t);return i?(O(n),i):(D(n,()=>{const n=st(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=P(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"),$(o,e,t),!1!==i.showCloseButton){const e=L(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 c=document.createElement("input");c.type="email",c.required=!0,c.className="selwise-newsletter-input",c.placeholder=String(n.emailPlaceholder||"you@example.com"),c.style.width="100%",c.style.padding="10px 12px",c.style.borderRadius="8px",c.style.border=`1px solid ${String(i.inputBorderColor||"#d1d5db")}`,c.style.backgroundColor=String(i.inputBackgroundColor||"#f9fafb"),c.style.color=String(i.inputTextColor||"#111827"),c.style.outline="none";const l=document.createElement("button");l.type="submit",l.className="selwise-newsletter-submit",l.textContent=String(n.buttonText||"Subscribe"),l.style.padding="10px 14px",l.style.border="none",l.style.borderRadius="8px",l.style.cursor="pointer",l.style.fontWeight="600",l.style.backgroundColor=String(i.buttonColor||"#111827"),l.style.color=String(i.buttonTextColor||"#ffffff"),s.appendChild(c),s.appendChild(l),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=c.value.trim().toLowerCase();if(!ct.test(t))return void dt(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 dt(d,"error",String(n.errorMessage||"Widget runtime is not initialized."));const o=String(n.buttonText||"Subscribe");l.disabled=!0,c.disabled=!0,l.textContent="Submitting...",dt(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."))),dt(d,r.state,r.message),"error"===r.state?(l.disabled=!1,c.disabled=!1):(l.disabled=!0,c.disabled=!0)}catch{dt(d,"error",String(n.errorMessage||"Unable to subscribe right now. Please try again.")),l.disabled=!1,c.disabled=!1}finally{l.disabled?l.textContent="Done":l.textContent=o}});const u=e.placementConfigJson||{};if("selector"===u.placementType||"string"==typeof u.selector){const t=`newsletter:${e.id}`;return z(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 pt{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 ht=null;function gt(){return ht||(ht=new pt),ht}const mt="https://api.selwise.com",ft="/api/v1";function yt(e){if(!e)return null;const t=e.trim();return t.length>0?t:null}function bt(e){const t="undefined"!=typeof process?yt(process.env?.NEXT_PUBLIC_API_URL):null,n=yt(e),i=t||n||mt;try{const e=new URL(i),t=function(e){const t=e.replace(/\/+$/,"");return t&&"/"!==t?t===ft||t.endsWith(ft)?t:`${t}${ft}`:ft}(e.pathname||"/");return`${e.origin}${t}`}catch{return`${mt}${ft}`}}const wt=new Map;let St=null;function xt(){return St||(St=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),V("Selwise","Using sessionStorage (persists until tab close)"),sessionStorage}catch(e){G("Selwise","sessionStorage unavailable:",e)}return V("Selwise","Using in-memory storage (persists until page refresh only). Visitor ID and experiments will reset on refresh."),{getItem:e=>wt.get(e)||null,setItem:(e,t)=>wt.set(e,t),removeItem:e=>wt.delete(e)}}()),St}function vt(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 V("Selwise","crypto.getRandomValues not available, using less secure fallback"),`${e}_${Date.now().toString(36)}${Math.random().toString(36).substring(2,15)}`}function Ct(){const e=xt();try{let e=sessionStorage.getItem(a);return e||(e=vt("sid"),sessionStorage.setItem(a,e)),e}catch{let t=e.getItem(a);return t||(t=vt("sid"),e.setItem(a,t)),t}}function kt(){const e=xt();let t=e.getItem(s);return t||(t=vt("vid"),e.setItem(s,t)),t}function Tt(){return xt().getItem(c)||void 0}function It(){return"true"===xt().getItem(g)}function Et(){const e=xt(),t=kt();let n=e.getItem(d);const i=e.getItem(u);if(n&&i){const o=parseInt(i,10);if(Date.now()-o<18e5){const i=`journey_${t}`;if(n.startsWith(i))return e.setItem(u,Date.now().toString()),n}}return n=`journey_${t}_${Date.now()}`,e.setItem(d,n),e.setItem(u,Date.now().toString()),n}function _t(){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 Pt=new Set(["productId","productSku","sku"]);function At(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t={};for(const[n,i]of Object.entries(e))Pt.has(n)||(t[n]=i);return t}const $t="events";class Ot{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($t)){const e=t.createObjectStore($t,{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([$t],"readwrite").objectStore($t),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([$t],"readonly").objectStore($t).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([$t],"readonly").objectStore($t).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([$t],"readwrite").objectStore($t);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([$t],"readwrite").objectStore($t).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([$t],"readonly").objectStore($t);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([$t],"readwrite").objectStore($t).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([$t],"readonly").objectStore($t).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([$t],"readwrite").objectStore($t).clear()}catch{}}isAvailable(){return!this.disabled&&this.initialized&&null!==this.db}}let Dt=null;const Lt="selwise_event_queue";class Nt{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:bt(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=(Dt||(Dt=new Ot),Dt),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&&K("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&&K("EventBatcher","Flushing",this.queue.length,"recovered events"),await this.flush())}catch(e){this.debugMode&&J("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&&K("EventBatcher","batchSize updated:",e.batchSize)),void 0!==e.flushInterval&&(this.config.flushInterval=e.flushInterval,this.debugMode&&K("EventBatcher","flushInterval updated:",e.flushInterval)),void 0!==e.enablePersistence&&(this.config.enablePersistence=e.enablePersistence,this.debugMode&&K("EventBatcher","enablePersistence updated:",e.enablePersistence)),void 0!==e.enableSendBeacon&&(this.config.enableSendBeacon=e.enableSendBeacon,this.debugMode&&K("EventBatcher","enableSendBeacon updated:",e.enableSendBeacon)),void 0!==e.maxRetries&&(this.maxRetries=e.maxRetries,this.debugMode&&K("EventBatcher","maxRetries updated:",e.maxRetries)),void 0!==e.maxQueueSize&&(this.maxQueueSize=e.maxQueueSize,this.debugMode&&K("EventBatcher","maxQueueSize updated:",e.maxQueueSize)),void 0!==e.maxStorageEvents&&(this.maxStorageEvents=e.maxStorageEvents,this.debugMode&&K("EventBatcher","maxStorageEvents updated:",e.maxStorageEvents)),void 0!==e.debugMode&&(this.debugMode=e.debugMode,K("EventBatcher","debugMode updated:",e.debugMode))}add(e){const t={...e,metadata:At(e.metadata)};if(t.eventId||(t.eventId=_t()),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=xt();let t=e.getItem(p);const n=e.getItem(h);if(t&&n){const e=parseInt(n,10);if(Date.now()-e<864e5)return t}return t=vt("corr"),e.setItem(p,t),e.setItem(h,Date.now().toString()),t}();if(t.correlationId=`${n}_${this.tabCorrelationId}`,t.parentEventId=this.lastEventId??void 0,t.journeyId=Et(),this.lastEventId=t.eventId,this.config.siteKey&&!this.checkConsentForEvent(t))return this.consentQueue.push(t),void(this.debugMode&&K("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(C);for(const e of n)if(C[e].indexOf(t)>=0){try{const t=`${w}_${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=xt().getItem(u);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:At(e.metadata),journeySequence:t[n]})),i={sessionId:this.sessionData.sessionId,visitorId:this.sessionData.visitorId,journeyId:Et(),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&&K("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:At(e.metadata),journeySequence:t[n]})),i={sessionId:this.sessionData.sessionId,visitorId:this.sessionData.visitorId,journeyId:Et(),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:Et()};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&&K("EventBatcher","Storage quota exceeded, skipping save"));const e={version:2,queue:this.queue.slice(0,this.maxStorageEvents),timestamp:Date.now()};localStorage.setItem(Lt,JSON.stringify(e)),this.debugMode&&K("EventBatcher","Saved",e.queue.length,"events to storage")}catch(e){this.debugMode&&K("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&&K("EventBatcher","Cleaned up expired journey state"))}catch{localStorage.removeItem(e)}}catch{}}loadFromStorage(){try{const e=localStorage.getItem(Lt);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:At(e.metadata)}))}localStorage.removeItem(Lt)}catch{localStorage.removeItem(Lt)}}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(Lt)}resetCorrelation(){this.lastEventId=null,this.debugMode&&K("EventBatcher","Correlation tracking reset")}getConsentQueueSize(){return this.consentQueue.length}flushConsentQueue(){if(0===this.consentQueue.length)return;this.debugMode&&K("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&&K("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&&K("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&&K("EventBatcher","Cleaned up processed events, kept last 5000")}this.consentQueue.length>100&&(this.consentQueue=this.consentQueue.slice(-50),this.debugMode&&K("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&&K("EventBatcher","Stored",e.length,"events in overflow storage")}).catch(()=>{this.metrics.eventsDropped+=e.length,this.debugMode&&V("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&&K("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:At(t.metadata)})}}}catch(e){this.debugMode&&J("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=bt(),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=Ct(),this.visitorId=kt(),this.siteUserId=Tt(),!1!==n?.enabled&&n&&(this.useAdvancedBatching=!0,this.batcher=new Nt({...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 Nt({...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=xt();e?t.setItem(c,e):t.removeItem(c)}(e)}getSessionId(){return this.sessionId}getVisitorId(){return this.visitorId}getSiteUserId(){return this.siteUserId}getJourneyId(){try{const e=localStorage.getItem(d),t=localStorage.getItem(u);if(e&&t){const n=parseInt(t,10);if(Date.now()-n<18e5)return e}return null}catch{return null}}endJourney(){try{localStorage.removeItem(d),localStorage.removeItem(u)}catch{}}getJourneyState(){try{const e=localStorage.getItem(d),t=localStorage.getItem(u);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(v)||"{}");t&&"object"==typeof t&&!Array.isArray(t)?localStorage.setItem(v,JSON.stringify({...t,...e})):localStorage.setItem(v,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(x)||"[]");if(Array.isArray(t)){const n=new Set([...t,...e]);localStorage.setItem(x,JSON.stringify([...n]))}else{const t=new Set(e);localStorage.setItem(x,JSON.stringify([...t]))}}catch(e){G("Selwise","Failed to update merged visitor IDs:",e)}}getMergedVisitorIds(){try{const e=JSON.parse(localStorage.getItem(x)||"[]");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=_t(),o=At(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(m,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(m)||"null"),t=JSON.parse(sessionStorage.getItem(f)||"null"),n=JSON.parse(sessionStorage.getItem(y)||"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(b);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=xt();e.removeItem(p),e.removeItem(h)}(),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:At(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:Et(),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=`${w}_${this.siteKey}`,t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}})}}}var Rt=n(664);const Bt=new Map;class Ut{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=>Bt.get(e)||null,setItem:(e,t)=>{Bt.set(e,t)},removeItem:e=>{Bt.delete(e)}}}()}parseInterval(e){if(!(0,Rt.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){V("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 zt=null;function qt(){return zt||(zt=new Ut),zt}function Ft(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jt(e){if(Array.isArray(e))return e.map(e=>jt(e));if(Ft(e)){const t={};for(const[n,i]of Object.entries(e))t[n]=jt(i);return t}return e}function Ht(e,t){const n=jt(e||{});if(!Ft(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]=jt(i):Ft(i)?Ft(t)?n[e]=Ht(t,i):n[e]=Ht({},i):n[e]=i}return n}function Wt(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 Kt(e){return Ft(e)&&"string"==typeof e.experimentId&&"string"==typeof e.variantId}function Gt(e){if(!e)return null;const t=e.variantConfig??e.config;if(!Ft(t))return null;let n=Ht({},t);const i="search_config"===e.targetType?"search":"recommendation"===e.targetType?"recommendation":void 0;if(i&&Ft(n[i])){const e=n[i];delete n[i],n=Ht(n,e)}return Ft(n.content)&&(n.content=Wt(n.content)),Ft(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)),Ft(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 Jt{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)Kt(n)&&(t[n.experimentId]=n)};return Array.isArray(e)?(n(e),t):Ft(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,K("Selwise","Experiments initialized:",this.assignments)}}catch(e){V("Selwise","Failed to load experiments:",e)}}loadFromStorage(){try{const e=localStorage.getItem(b);if(e){const t=JSON.parse(e);t&&"object"==typeof t&&!Array.isArray(t)?this.assignments=t:(V("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(b,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=Gt(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){V("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){V("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){V("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 Vt={showOnAllPages:!0,includeUrls:[],excludeUrls:[]};function Yt(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 Qt(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 Xt(e,t){const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{...Vt};const t=e;return{showOnAllPages:Boolean(t.showOnAllPages??Vt.showOnAllPages),includeUrls:Yt(t.includeUrls),excludeUrls:Yt(t.excludeUrls)}}(e),i=String(t||"");if(n.excludeUrls.length>0&&n.excludeUrls.some(e=>Qt(i,e)))return!1;if(!1===n.showOnAllPages){if(0===n.includeUrls.length)return!1;if(!i)return!1;if(!n.includeUrls.some(e=>Qt(i,e)))return!1}return!0}class Zt{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(K("SegmentManager","Evaluating segment targeting:",{mode:e,segmentIds:n,visitorId:this.visitorId,sessionId:this.sessionId}),"all"===e||0===n.length)return K("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(K("SegmentManager","Evaluation results:",{results:i,matchedSegments:o,mode:e}),"include"===e){const e=o.length>0;return K("SegmentManager","Include mode: "+(e?"SHOW":"HIDE")),e}if("exclude"===e){const e=0===o.length;return K("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};K("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 J("SegmentManager","API returned error:",n.status,n.statusText),this.getFallbackResults(e);const i=await n.json();K("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 J("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 en=[];function tn(e){return!(!e||"string"!=typeof e)&&en.includes(e)}let nn=!1,on=null;function rn(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 an(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(rn)),e.exception?.values)for(const t of e.exception.values)t.stacktrace?.frames&&(t.stacktrace.frames=sn(t.stacktrace.frames));return e.stacktrace?.frames&&(e.stacktrace.frames=sn(e.stacktrace.frames)),e.tags=e.tags||{},e.tags.widgetVersion="client",e.level||(e.level="error"),e}function sn(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 cn,ln,dn,un,pn,hn;!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"}(cn||(cn={})),function(e){e[e.BASKET=1]="BASKET",e[e.CUSTOMER=2]="CUSTOMER",e[e.PAYMENT=3]="PAYMENT",e[e.PURCHASE=4]="PURCHASE"}(ln||(ln={})),function(e){e.SIGNUP="signup",e.SIGNIN="signin",e.SIGNOUT="signout",e.UPDATE="update"}(dn||(dn={})),function(e){e.ADD="add",e.REMOVE="remove",e.UPDATE="update"}(un||(un={})),function(e){e.KEYWORD="keyword",e.FILTER="filter",e.PAGE="page",e.ORDER="order"}(pn||(pn={})),function(e){e.NECESSARY="necessary",e.ANALYTICS="analytics",e.MARKETING="marketing",e.PREFERENCES="preferences"}(hn||(hn={})),hn.NECESSARY;const gn="selwise_dl_state",mn="selwise_dl_cart",fn="selwise_dl_cart_time",yn="selwise_dl_last_page",bn="selwise_dl_page_views",wn="selwise_dl_session_start",Sn={HOME:cn.HOME,PRODUCT:cn.PRODUCT,CATEGORY:cn.CATEGORY,SEARCH:cn.SEARCH,CHECKOUT:cn.CHECKOUT,CART:cn.CART,ACCOUNT:cn.ACCOUNT,OTHER:cn.OTHER},xn={home:new RegExp(Rt.DEFAULT_PAGE_TYPE_PATTERNS.home,"i"),product:new RegExp(Rt.DEFAULT_PAGE_TYPE_PATTERNS.product,"i"),category:new RegExp(Rt.DEFAULT_PAGE_TYPE_PATTERNS.category,"i"),search:new RegExp(Rt.DEFAULT_PAGE_TYPE_PATTERNS.search,"i"),checkout:new RegExp(Rt.DEFAULT_PAGE_TYPE_PATTERNS.checkout,"i"),cart:new RegExp(Rt.DEFAULT_PAGE_TYPE_PATTERNS.cart,"i"),account:new RegExp(Rt.DEFAULT_PAGE_TYPE_PATTERNS.account,"i")},vn="datalayer",Cn=["auto","generic","ideasoft","ikas","ticimax","tsoft","akinon","shopify","woocommerce","magento","prestashop","wix","opencart","bigcommerce","custom","none"],kn=['body[class*="product"]','body[class*="item"]','[itemtype*="Product"]','[itemscope][itemtype*="Product"]',".product-single",".product-type-simple",".product-type-variable",".product-info-main",".ProductDetail",".product-detail","[data-product-code]","[data-itemcode]","[data-stock-code]","[data-productid]","[data-ikas-product-id]",".ak-product","body.page-type-product",".productView",'[data-hook="product-page"]',"[data-product-id]"],Tn={auto:{id:"auto",dataLayerNames:["dataLayer"],productPageSelectors:[]},generic:{id:"generic",dataLayerNames:["dataLayer"],productPageSelectors:[]},shopify:{id:"shopify",dataLayerNames:["dataLayer","ShopifyAnalytics","shopifyDataLayer"],pageTypePatterns:{product:"\\/products\\/[a-z0-9-]+",category:"\\/collections\\/[a-z0-9-]+",cart:"\\/cart",checkout:"\\/checkouts?\\/|\\/checkout",account:"\\/account",search:"\\/(search|collections\\/all\\?q=)"},productPageSelectors:[".product-template","[data-product-handle]",".shopify-section .product"]},woocommerce:{id:"woocommerce",dataLayerNames:["dataLayer","gtmDataLayer"],pageTypePatterns:{product:"\\/product\\/[a-z0-9-]+",category:"\\/product-category\\/[a-z0-9-]+",cart:"\\/cart",checkout:"\\/checkout",account:"\\/my-account",search:"\\/\\?s="},productPageSelectors:[".single-product",".woocommerce div.product",".product.type-product"]},magento:{id:"magento",dataLayerNames:["dataLayer","digitalData","adobeDataLayer"],pageTypePatterns:{product:"\\/[a-z0-9-]+\\.html$",category:"\\/catalog\\/|\\/c\\/|\\/category\\/",cart:"\\/checkout\\/cart",checkout:"\\/checkout",account:"\\/customer\\/account",search:"\\/catalogsearch\\/|\\/search\\/"},productPageSelectors:[".catalog-product-view","#product_addtocart_form",".product-info-main"]},bigcommerce:{id:"bigcommerce",dataLayerNames:["dataLayer","bcDataLayer"],pageTypePatterns:{product:"\\/products\\/[a-z0-9-]+",category:"\\/categories\\/[a-z0-9-]+",cart:"\\/cart\\.php",checkout:"\\/checkout",account:"\\/account\\.php",search:"\\/search\\.php"},productPageSelectors:["body.page-type-product","[data-product-id]",".productView"]},opencart:{id:"opencart",dataLayerNames:["dataLayer"],pageTypePatterns:{product:"route=product\\/product",category:"route=product\\/category",cart:"route=checkout\\/cart",checkout:"route=checkout\\/checkout",account:"route=account\\/",search:"route=product\\/search"},productPageSelectors:["#product",".product-thumb","[data-product-id]"]},prestashop:{id:"prestashop",dataLayerNames:["dataLayer"],pageTypePatterns:{product:"\\/[a-z]{2}\\/\\d+-",category:"\\/\\d+-",cart:"\\/cart",checkout:"\\/order",account:"\\/my-account",search:"\\/search"},productPageSelectors:["#product",".product-container",".js-product-container"]},akinon:{id:"akinon",dataLayerNames:["dataLayer","akDataLayer"],pageTypePatterns:{product:"\\/(p|urun)\\/",category:"\\/(c|kategori)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(checkout|odeme)",account:"\\/(hesabim|account)",search:"\\/(search|arama)"},productPageSelectors:["[data-product-code]","[data-itemcode]",".product-detail",".ak-product"]},ideasoft:{id:"ideasoft",dataLayerNames:["dataLayer","iDataLayer"],pageTypePatterns:{product:"\\/(urun|product)\\/",category:"\\/(kategori|category)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(odeme|checkout)",account:"\\/(uyelik|account)",search:"\\/(arama|search)"},productPageSelectors:[".ProductDetail","[data-product-id]","[data-product-code]"]},ikas:{id:"ikas",dataLayerNames:["dataLayer","ikasDataLayer"],pageTypePatterns:{product:"\\/(products?|urun)\\/",category:"\\/(categories?|kategori)\\/",cart:"\\/(cart|sepet)",checkout:"\\/(checkout|odeme)",account:"\\/(account|hesabim)",search:"\\/(search|arama)"},productPageSelectors:["[data-ikas-product-id]","[data-product-id]",".product-detail"]},ticimax:{id:"ticimax",dataLayerNames:["dataLayer","ticimaxDataLayer"],pageTypePatterns:{product:"\\/(product|urun)\\/",category:"\\/(category|kategori)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(odeme|checkout)",account:"\\/(uye|account)",search:"\\/(arama|search)"},productPageSelectors:["[data-productid]","[data-product-id]",".productDetail"]},tsoft:{id:"tsoft",dataLayerNames:["dataLayer","tSoftDataLayer"],pageTypePatterns:{product:"\\/(urun|product)\\/",category:"\\/(kategori|category)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(odeme|checkout)",account:"\\/(hesabim|account)",search:"\\/(arama|search)"},productPageSelectors:["[data-product-id]","[data-stock-code]",".product-detail"]},wix:{id:"wix",dataLayerNames:["dataLayer","wixDataLayer"],pageTypePatterns:{product:"\\/product-page\\/",category:"\\/category\\/",cart:"\\/cart",checkout:"\\/checkout",account:"\\/account",search:"\\/search"},productPageSelectors:['[data-hook="product-page"]',"[data-product-id]",".product-page"]},custom:{id:"custom",dataLayerNames:["dataLayer"],productPageSelectors:[]},none:{id:"none",dataLayerNames:["dataLayer"],productPageSelectors:[]}};function In(e){const t=function(e){const t="string"==typeof e?e.trim().toLowerCase():"auto";return Cn.includes(t)&&"auto"!==t?t:function(){const e=window,t=(window.location.hostname||"").toLowerCase(),n=(document.body?.className||"").toLowerCase(),i=Array.from(document.querySelectorAll("script[src]")).map(e=>e.src.toLowerCase()).join(" ");return e.Shopify||i.includes("cdn.shopify.com")||t.includes("myshopify.com")?"shopify":e.wc_add_to_cart_params||n.includes("woocommerce")||i.includes("woocommerce")?"woocommerce":e.checkoutConfig||n.includes("catalog-product-view")||i.includes("mage/")?"magento":e.BCData||n.includes("page-type-product")||i.includes("bigcommerce")?"bigcommerce":e.prestashop||i.includes("prestashop")?"prestashop":e.wixBiSession||i.includes("wixstatic")||t.includes("wixsite.com")?"wix":i.includes("opencart")||t.includes("opencart")?"opencart":i.includes("akinon")||e.akinonBasket||n.includes("akinon")?"akinon":i.includes("ideasoft")||t.includes("ideasoft")?"ideasoft":i.includes("ikas")||t.includes("ikas")?"ikas":i.includes("ticimax")||t.includes("ticimax")?"ticimax":i.includes("tsoft")||i.includes("t-soft")||t.includes("tsoft")?"tsoft":"generic"}()}(e);return Tn[t]||Tn.generic}class En{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||xn;for(const[n,i]of Object.entries(t))if(("string"==typeof i?new RegExp(i):i).test(e))return n;return this.detectPageTypeFromDom()||Sn.OTHER}detectPageTypeFromDom(){const e=In(this.config.config.platform),t=document.body.className.toLowerCase();if(t.includes("product")||t.includes("item"))return Sn.PRODUCT;if(t.includes("category")||t.includes("collection")||t.includes("catalog"))return Sn.CATEGORY;if(t.includes("checkout"))return Sn.CHECKOUT;if(t.includes("cart")||t.includes("basket"))return Sn.CART;if(t.includes("account")||t.includes("profile")||t.includes("my-account"))return Sn.ACCOUNT;if(document.querySelector('[itemtype*="Product"]'))return Sn.PRODUCT;for(const t of e.productPageSelectors)try{if(document.querySelector(t))return Sn.PRODUCT}catch{}return null}getPageMetadata(e){const t={dataSource:vn,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===Sn.PRODUCT){const e=this.extractProductInfoFromDom();e&&(t.productInfo=e)}if(e===Sn.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(yn,e)}catch{}}getLastPageType(){try{return sessionStorage.getItem(yn)||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:vn,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(bn)||"0",10)+1;return sessionStorage.setItem(bn,e.toString()),e}catch{return 1}}getPageViewCount(){try{return parseInt(sessionStorage.getItem(bn)||"0",10)}catch{return 0}}log(...e){K("PageTracker",...e)}destroy(){this.titleObserver&&(this.titleObserver.disconnect(),this.titleObserver=null)}}class _n{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=In(this.config.config.platform),t=Array.from(new Set([...kn,...e.productPageSelectors])),n=this.config.config.pageTypePatterns;if(n?.product){const e=window.location.pathname+window.location.search;if(n.product.test(e))return!0}for(const e of t)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], [data-product-code], [data-stock-code], [data-itemcode], [data-productid], [data-ikas-product-id]");if(!e)return null;const t=e.getAttribute("data-product-sku")||e.getAttribute("data-product-code")||e.getAttribute("data-itemcode")||e.getAttribute("data-stock-code")||e.getAttribute("data-ikas-product-id")||e.getAttribute("data-item-id")||e.getAttribute("data-productid")||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:vn,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:vn,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:vn,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),K("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:vn}}]},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(K("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:vn}}]},n=`${this.config.apiUrl}/public/sites/${this.config.siteKey}/events/batch`;K("ProductTracker","Sending dwell time to:",n),K("ProductTracker","Payload:",e),fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}).then(e=>e.json()).then(e=>K("ProductTracker","Dwell time sent successfully:",e)).catch(e=>J("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){K("ProductTracker",...e)}destroy(){this.stopDwellTimeTracking(),this.impressionObserver&&(this.impressionObserver.disconnect(),this.impressionObserver=null),this.trackedProducts.clear()}}const Pn=/^[A-Z]{3}$/;function An(e){const t=String(e||"").trim().toUpperCase();return Pn.test(t)?t:"EUR"}class $n{constructor(e){this.currentCart=null,this.checkInterval=null,this.lastTrackedCartId="",this.config=e}storeCartSnapshot(e){try{sessionStorage.setItem(mn,JSON.stringify(e)),sessionStorage.setItem(fn,Date.now().toString())}catch(e){this.log("Failed to store cart snapshot:",e)}}getStoredCartSnapshot(){try{const e=sessionStorage.getItem(mn),t=sessionStorage.getItem(fn);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(mn),sessionStorage.removeItem(fn)}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:vn,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:vn,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:vn,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:vn,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:An(e.currency),timestamp:Date.now(),url:window.location.href}:t,i=this.getBasketProductItemCodes(n.products),o={dataSource:vn,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:An(e.currency),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){K("BasketTracker",...e)}destroy(){this.stopCartMonitoring()}}class On{constructor(e){this.checkoutState=null,this.checkoutStorageKey=`${gn}_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:vn,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,c={dataSource:vn,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:c}),this.log("Tracked checkout_progress:",t,c)}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:vn,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:vn,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(mn),sessionStorage.removeItem(fn)}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){K("CheckoutTracker",...e)}destroy(){this.clearCheckoutState()}}class Dn{constructor(e){this.userState=null,this.userStorageKey=`${gn}_user`,this.config=e,this.sessionStartTime=Date.now(),this.loadUserState(),this.initSessionStart()}initSessionStart(){try{const e=sessionStorage.getItem(wn);e?this.sessionStartTime=parseInt(e,10):sessionStorage.setItem(wn,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:vn,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:vn,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:vn,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(wn,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:vn,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){K("UserTracker",...e)}destroy(){}}class Ln{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:vn,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:vn,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:vn,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:vn,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:vn,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:vn,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:vn,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){K("SearchTracker",...e)}destroy(){this.clearSearchState()}}class Nn{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(Array.isArray(t[e]))return t[e];if(t[e]&&!Array.isArray(t[e]))return this.log(`Warning: window.${e} exists but is not an array, resetting`),t[e]=[],t[e];const n=this.detectExistingDataLayerName(t);return n?(this.config.dataLayerName=n,this.log(`Detected external dataLayer source: window.${n}`),t[n]):(t[e]=[],this.log(`Initialized empty window.${e} array`),t[e])}detectExistingDataLayerName(e){const t=[...Array.isArray(this.config.preferredDataLayerNames)?this.config.preferredDataLayerNames.filter(e=>"string"==typeof e&&e.trim().length>0):[],"dataLayer","googleDataLayer","gtmDataLayer","analyticsDataLayer"];for(const n of t)if(Array.isArray(e[n]))return n;const n=Object.entries(e);for(const[e,t]of n)if(Array.isArray(t)&&0!==t.length&&t.some(e=>!!e&&(Array.isArray(e)?"event"===e[0]&&"string"==typeof e[1]:"object"==typeof e&&"string"==typeof e.event)))return e;return null}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){const n=this.normalizeDataLayerItem(e);if(!n)return;const i=n.event||null;if(!i&&("consent"===n[0]||n.gtm?.start||"gtm.js"===n.event))return;if(this.config.hasConsent&&!this.config.hasConsent())return void this.log(`Skipping mapped event due to consent: ${i}`);if(!i||this.isInternalEvent(i,n))return;const o=this.getMappedEvent(i);if(!o)return;const r=this.createEventId(n,t);if(this.processedEvents.has(r))return;this.processedEvents.add(r);const a=this.extractEventData(n);this.trackMappedEvent(o,i,a)}normalizeDataLayerItem(e){return e?Array.isArray(e)?this.parseArrayDataLayerItem(e):"object"==typeof e?e:null:null}parseArrayDataLayerItem(e){if(e.length<2)return null;const[t,n,i]=e;if("string"!=typeof t)return null;if("event"!==t)return null;if("string"!=typeof n||0===n.trim().length)return null;const o=n.trim(),r=i&&"object"==typeof i&&!Array.isArray(i)?i:{},a={event:o,...r},s=r.ecommerce&&"object"==typeof r.ecommerce?r.ecommerce:null;if(s)a.ecommerce=s;else{const e=[r.items,r.products,r.item_list].find(e=>Array.isArray(e));(e||r.currency||r.value||r.transaction_id)&&(a.ecommerce={items:Array.isArray(e)?e:void 0,currency:r.currency,value:r.value,transaction_id:r.transaction_id,coupon:r.coupon})}return a}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",dataSource:vn,originalEvent:e.event,externalDataLayerName:this.config.dataLayerName||"dataLayer",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)),"string"==typeof e.transaction_id&&(t.transactionId=e.transaction_id),"string"==typeof e.currency&&(t.currency=e.currency),"number"==typeof e.value&&(t.value=e.value),"string"==typeof e.search_term&&(t.searchTerm=e.search_term),Array.isArray(e.items)&&(t.products=e.items);for(const n of Object.keys(e))(n.startsWith("cd_")||n.startsWith("dimension"))&&(t[n]=e[n]);return t}extractEcommerceData(e){const t={};return Array.isArray(e.items)&&(t.items=e.items,t.products=e.items,t.currency=e.currency,t.value=e.value,t.transactionId=e.transaction_id||e.transactionId),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){const n=e.gtm?.uniqueEventId||e.eventId||e.transaction_id||e.transactionId||`${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return[e.event,n,t?"existing":"new"].join(":")}trackMappedEvent(e,t,n){this.log(`Mapping event: ${t} -> ${e}`);const{entityType:i,entityId:o}=this.determineEntityContext(e,n),r=this.resolveProductItemCode(n);this.config.tracker.track(e,{entityType:i,entityId:o,metadata:{...n,dataSource:vn,mappedFrom:t,productItemCode:r,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:"checkout",checkout_begin:"checkout",checkout_progress:"checkout",search:"search",search_query:"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||t.ecommerce?.products?.[0]?.item_id?i=t.ecommerce.products[0].id||t.ecommerce.products[0].item_id:t.ecommerce?.items?.[0]?.item_id||t.ecommerce?.items?.[0]?.sku?i=t.ecommerce.items[0].item_id||t.ecommerce.items[0].sku:(t.products?.[0]?.id||t.products?.[0]?.item_id||t.products?.[0]?.sku)&&(i=t.products[0].id||t.products[0].item_id||t.products[0].sku),"checkout"===n&&(i=t.ecommerce?.purchase?.actionField?.id||t.ecommerce?.transactionId||t.transactionId||i),{entityType:n,entityId:i}}resolveProductItemCode(e){const t=[e.productItemCode,e.product?.sku,e.product?.id,e.ecommerce?.items?.[0]?.item_id,e.ecommerce?.items?.[0]?.sku,e.ecommerce?.items?.[0]?.id,e.ecommerce?.products?.[0]?.item_id,e.ecommerce?.products?.[0]?.sku,e.ecommerce?.products?.[0]?.id,e.products?.[0]?.item_id,e.products?.[0]?.sku,e.products?.[0]?.id,e.vl_ecommerce?.detail?.product?.id,e.vl_ecommerce?.detail?.product?.sku,e.googleTagParams?.id,e.googleTagParams?.item_id,e.googleTagParams?.sku];for(const e of t)if("string"==typeof e&&e.trim().length>0)return e.trim()}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){K("ExternalDataLayerListener",...e)}}class Mn{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 c=this.getBasketProductItemCodes(e.products),l={dataSource:vn,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),productName:o.title,productItemCode:r,productItemCodes:c,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:l}),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){K("CartAssociationTracker",...e)}}const Rn=new Map;class Bn{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",this.platformProfile=In(i.platform);const o=this.normalizeTrackingModules(i.trackingModules),r=this.normalizePageTypePatterns(i.pageTypePatterns,this.platformProfile.pageTypePatterns);this.config={enabled:i.enabled??!0,variableName:i.variableName,platform:this.platformProfile.id,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,useExternalDataLayer:i.useExternalDataLayer??!0,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:{...Rt.TRACKING_MODULES.page,...e?.page||{}},product:{...Rt.TRACKING_MODULES.product,...e?.product||{}},basket:{...Rt.TRACKING_MODULES.basket,...e?.basket||{}},checkout:{...Rt.TRACKING_MODULES.checkout,...e?.checkout||{}},user:{...Rt.TRACKING_MODULES.user,...e?.user||{}},search:{...Rt.TRACKING_MODULES.search,...e?.search||{}}}}normalizePageTypePatterns(e,t){const n={...Object.fromEntries(Object.entries(xn).map(([e,t])=>[e,t.source]))};if(t)for(const[e,i]of Object.entries(t))"string"==typeof i&&i.trim().length>0&&(n[e]=i);if(e)for(const[t,i]of Object.entries(e))(i instanceof RegExp||"string"==typeof i&&i.trim().length>0)&&(n[t]=i);const i={};for(const[e,t]of Object.entries(n))if(t instanceof RegExp)i[e]=t;else if("string"==typeof t&&t.trim().length>0)try{i[e]=new RegExp(t,"i")}catch{this.log(`Invalid regex for page type "${e}", using default pattern`),i[e]=xn[e]||xn.home}return Object.keys(i).length>0?i:{...xn}}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){J("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()&&Rn.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 En(e),this.log("Page tracker enabled")),this.isModuleEnabled("product")&&(this.productTracker=new _n(e),this.log("Product tracker enabled")),this.isModuleEnabled("basket")&&(this.basketTracker=new $n(e),this.log("Basket tracker enabled")),this.isModuleEnabled("checkout")&&(this.checkoutTracker=new On(e),this.log("Checkout tracker enabled")),this.isModuleEnabled("user")&&(this.userTracker=new Dn(e),this.log("User tracker enabled")),this.isModuleEnabled("search")&&(this.searchTracker=new Ln(e),this.log("Search tracker enabled")),this.isModuleEnabled("basket")&&(this.cartAssociationTracker=new Mn(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(){if(!1===this.config.useExternalDataLayer)return void this.log("External dataLayer listening disabled by config");const e=this.config.reverseEventMapping,t=this.config.externalDataLayerName||this.platformProfile.dataLayerNames[0]||"dataLayer";if(e&&0!==Object.keys(e).length)try{this.externalListener=new Nn({tracker:this.tracker,reverseMapping:e,dataLayerName:t,preferredDataLayerNames:this.platformProfile.dataLayerNames,debugMode:this.config.debugMode,enabled:!0,hasConsent:()=>this.hasConsent()}),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=Rn.get(t)||0,i=Date.now();return i-n<1e3||(Rn.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:vn,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.platform&&(this.config.platform=e.platform,this.platformProfile=In(e.platform),this.config.pageTypePatterns=this.normalizePageTypePatterns(this.config.pageTypePatterns,this.platformProfile.pageTypePatterns)),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,this.platformProfile.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.useExternalDataLayer&&(this.config.useExternalDataLayer=e.useExternalDataLayer),void 0!==e.externalDataLayerName&&(this.config.externalDataLayerName=e.externalDataLayerName),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){K("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(),Rn.clear(),this.eventBuffer=[],this.isDestroyed=!0,this.isInitialized=!1,this.log("DataLayerManager destroyed")}}function Un(e,t,n){const i="string"==typeof t?n||{}:t||{},o="string"==typeof t?t:i.currencyCode||i.currency,r=parseInt(i.priceDecimals||"2",10),a=i.locale||void 0;return new Intl.NumberFormat(a,{style:"currency",currency:An(o),minimumFractionDigits:r,maximumFractionDigits:r}).format(Number(e||0))}function zn(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function qn(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 Fn(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 jn(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 Hn(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 Wn="ws_recent_searches";function Kn(e=5,t){try{const n=localStorage.getItem(`${Wn}_${t}`);if(!n)return[];const i=JSON.parse(n);return Array.isArray(i)?i.slice(0,e):[]}catch{return[]}}var Gn=n(561);async function Jn(e,t,n,i,o,r,a,s){try{sessionStorage.setItem(y,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 Vn(e){for(const t of e)try{const e=document.querySelector(t);if(e)return e}catch{}return null}async function Yn(e,t){const n=e.itemCode||e.id,i=t?.formSelectors||[],o=Vn([...t?.buttonSelectors||[],`[data-product-id="${n}"] .add-to-cart`,`[data-itemcode="${n}"] .add-to-cart`,`[data-productid="${n}"]`,`[data-stock-code="${n}"]`]);if(o)return void o.click();const r=Vn(i);if(!r)return;const a=r.querySelector('input[name="quantity"]')||r.querySelector('input[name="qty"]');a&&!a.value&&(a.value="1");const s=r.querySelector('input[name="product_id"]')||r.querySelector('input[name="productid"]')||r.querySelector('input[name="id"]');s&&!s.value&&(s.value=n),"function"==typeof r.requestSubmit?r.requestSubmit():r.submit()}function Qn(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}function Xn(e,t,n){switch(t){case"ideasoft":return function(e){return Yn(e,{formSelectors:['form[action*="Sepet"]','form[action*="cart"]'],buttonSelectors:[".btnSepeteEkle",'[onclick*="Sepete"]',".add-to-cart"]})}(e);case"ikas":return function(e){return Yn(e,{formSelectors:['form[action*="cart"]','form[action*="sepet"]'],buttonSelectors:["[data-ikas-product-id]","[data-product-id]",".add-to-cart"]})}(e);case"ticimax":return function(e){return Yn(e,{formSelectors:['form[action*="Sepet"]','form[action*="cart"]'],buttonSelectors:[".btnAddCart","[data-productid]","[data-product-id]"]})}(e);case"tsoft":return function(e){return Yn(e,{formSelectors:['form[action*="sepet"]','form[action*="cart"]'],buttonSelectors:["[data-stock-code]","[data-product-id]",".add-to-cart"]})}(e);case"wix":return async function(e){const t=window.wixStores;if(t?.cart?.addProducts&&"function"==typeof t.cart.addProducts)try{return void await t.cart.addProducts([{productId:e.id,quantity:1}])}catch(e){console.error("[Cart] Wix SDK add to cart error:",e)}await Yn(e,{formSelectors:['form[action*="cart"]','form[data-hook="product-form"]'],buttonSelectors:['[data-hook="add-to-cart"]',".add-to-cart"]})}(e);case"bigcommerce":return async function(e){const t=window.utils?.api?.cart;t?.itemAdd?await new Promise(n=>{t.itemAdd({product_id:e.id,qty:1},()=>n())}):await Yn(e,{formSelectors:['form[action*="cart.php"]',"form[data-cart-item-add]"],buttonSelectors:["[data-cart-item-add]",'[data-button-type="add-cart"]']})}(e);case"opencart":return function(e){const t=e.id;return fetch("/index.php?route=checkout/cart/add",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},body:`product_id=${encodeURIComponent(t)}&quantity=1`}).then(e=>e.json()).then(()=>{document.dispatchEvent(new CustomEvent("cart:updated"))}).catch(e=>{console.error("[Cart] OpenCart add to cart error:",e)})}(e);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_api":case"custom":return Qn(e,n?.customScript);default:return}}function Zn(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 ei(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 ti(e,t){if(!e.selector)return null;const n=()=>{const t=document.querySelector(e.selector);if(t){const n=ei(e,{showSearchIcon:!0,showCloseIcon:!0,getSearchIcon:jn,getCloseIcon:Hn}),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(),V("WidgetSearch","Selector not found after timeout:",e.selector)},1e4),null}function ni(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=ei(e,{showSearchIcon:!0,showCloseIcon:!0,getSearchIcon:jn,getCloseIcon:Hn}),s=a.querySelector(".ws-search-input"),c=a.querySelector(".ws-search-results");return r.appendChild(a),o.appendChild(r),document.body.appendChild(o),{container:a,input:s,resultsContainer:c,overlayElement:o}}const ii="data-selwise-action",oi="data-product-id",ri="add-to-cart";function ai(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,e.currency),oldPrice:e.originalPrice,formattedOldPrice:e.originalPrice?n.formatPrice(e.originalPrice,e.currency):"",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:`${ii}="${ri}" ${oi}="${o}"`};return Object.entries(r).forEach(([e,t])=>{const n=null!=t?t:"";i=i.replace(new RegExp(`\\$\\{${e}\\}`,"g"),String(n))}),et(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",c=t.imageSize||"cover";let l="";t.showBadges&&(e.isNew&&(l+='<span class="selwise-badge selwise-badge-new">New</span>'),e.isSale&&(l+='<span class="selwise-badge selwise-badge-sale">Sale</span>'),e.isBestseller&&(l+='<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="${si(e.title)}" loading="lazy" style="width:100%;height:100%;object-fit:${c};" />\n </a>\n ${l?`<div class="selwise-badges">${l}</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":""}">${si(String(r))}</div>`;break;case"price":p+=`<div class="selwise-card-price">${n.formatPrice(e.price,e.currency)}</div>`;break;case"old_price":e.originalPrice&&(p+=`<div class="selwise-card-old-price">${n.formatPrice(e.originalPrice,e.currency)}</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",c=t.buttonStyle?.color||"#fff";p+=`\n <button class="selwise-card-button" \n ${ii}="${ri}" \n ${oi}="${i}"\n style="width:100%;margin-top:auto;padding:8px;background:${s};color:${c};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 ${ii}="${ri}" \n ${oi}="${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="${si(e.title)}" loading="lazy" />\n </div>\n <div class="selwise-card-content">\n <h3 class="selwise-card-title">${si(e.title)}</h3>\n <div class="selwise-card-price-row">\n ${n?`<span class="selwise-price-original">${t.formatPrice(e.originalPrice,e.currency)}</span>`:""}\n <span class="selwise-price-current">${t.formatPrice(e.price,e.currency)}</span>\n </div>\n </div>\n </div>\n `}(e,n)}function si(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):""}function ci(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 li=new Map;function di(e,t,n){const{config:i,selectedCategory:o,formatPrice:r,formatCategoryName:a}=t,s=i,c=s.styles||{};if(0===e.hits.length)return"";let l="",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&&(l+=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="${zn(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>${zn(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&&(l+=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="${zn(e.name)}">\n ${zn(i(e.name))}${n.categoryShowCount?` (${e.count})`:""}\n </button>`}),r+="</div>",r}(d,o,s,a)),"dropdown"===s.categoryDisplayMode&&d.length&&(l+=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="${zn(e.name)}" ${n===e.name?"selected":""}>\n ${zn(e.name)}${i.categoryShowCount?` (${e.count})`:""}\n </option>`}),r+="</select></div>",r}(d,e.total,o,s)),l+='<div class="ws-search-items">',l+=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,currency:An(e.currency),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},c=ai(a,s,{source:"search",formatPrice:i.formatPrice});return o&&s.customJs&&(li.has(o)||li.set(o,[]),li.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 ${c}\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),c=e.imageUrl||"",l=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 ${ii}="${ri}"\n ${oi}="${l}"\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="${l}"${e.boostReason?` data-boost-reason="${e.boostReason}"`:""}>\n ${t.showImages&&c?`\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="${c}" 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,e.currency)}</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,e.currency)}</span>\n ${t.showOldPrice&&e.originalPrice&&e.originalPrice>e.price?`<span class="ws-search-old-price">${i.formatPrice(e.originalPrice,e.currency)}</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:zn,formatCategoryName:a},n)).join(""),l+="</div>",l+=`<div class="ws-search-footer">${zn((c.textFooter||"{total} products found in {time}ms").replace("{total}",String(e.total)).replace("{time}",String(e.took)))}</div>`,"sidebar"===s.categoryDisplayMode&&d.length&&(l+="</div></div>"),l}class ui{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=kt,this.getStoredSiteUserId=Tt,this.generateEventId=_t,this.apiUrl=e,this.siteKey=t,this.sessionId=Ct(),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 K("WidgetSearch","Search excluded by experiment (different_module mode - variant available)"),null;if(e&&"different_module"!==e.experimentMode){const n=Gt(e);n&&(K("WidgetSearch","Applying experiment override:",e.variantName),i=Ht(i,n),t.trackImpression(e.experimentId))}}K("WidgetSearch","Config loaded:",i);const o=(0,Gn.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,Gn.sanitizeSearchStyles)(i.styles),i.suggestionStyles&&(i.suggestionStyles=(0,Gn.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(!0===this.config.isTestMode||!0===this.config.testMode){if("undefined"==typeof localStorage||"true"!==localStorage.getItem(g))return void G("WidgetSearch",`Search is in test mode. Run localStorage.setItem('${g}', '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,Gn.sanitizeSuggestionStyles)(n.styles)),K("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: ${Fn(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: ${Fn(i.itemShadow||"sm")};\n }\n .ws-search-results.layout-grid .ws-search-item:hover {\n box-shadow: ${Fn(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: ${Fn(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: ${Fn(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){J("WidgetSearch","Failed to initialize:",e)}}getSuggestionStyles(){return this.suggestions?.styles||{}}setupSpaNavigationWatcher(){K("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,K("WidgetSearch","Inline container was removed")),!this.container&&this.config?.selector)&&document.querySelector(this.config.selector)){K("WidgetSearch","Re-rendering inline search");const e=ti(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}),K("WidgetSearch","Re-attached trigger listener to:",t);const o=document.querySelector(".ws-search-floating-btn:not(.ws-embedded)");o&&(o.remove(),K("WidgetSearch","Removed fallback floating button"))}})}});t.observe(document.body,{childList:!0,subtree:!0}),this.spaObserver=t,K("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 K("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,jn)};let t;switch(this.config.position){case"inline":t=ti(this.config,()=>this.attachEventListeners());break;case"modal":t=ni(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e);break;case"floating":t=function(e,t,n,i){return ni(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 c=ei(e,{showSearchIcon:!1,showCloseIcon:!0,getSearchIcon:jn,getCloseIcon:Hn}),l=c.querySelector(".ws-search-input"),d=c.querySelector(".ws-search-results");return a.appendChild(c),r.appendChild(a),document.body.appendChild(r),{container:c,input:l,resultsContainer:d,overlayElement:r}}(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e,Hn);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=ei(e,{showSearchIcon:!0,showCloseIcon:!1,getSearchIcon:jn,getCloseIcon:Hn}),c=s.querySelector(".ws-search-input"),l=s.querySelector(".ws-search-results");return a.appendChild(s),r.appendChild(a),document.body.appendChild(r),{container:s,input:c,resultsContainer:l,overlayElement:r}}(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e,Hn);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=Kn(t,n);i=i.filter(t=>t.toLowerCase()!==e.toLowerCase()),i.unshift(e),i=i.slice(0,t),localStorage.setItem(`${Wn}_${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;J("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=di(e,{config:this.config,selectedCategory:this.selectedCategory,formatPrice:(e,t)=>Un(e,t,this.config?.styles),formatCategoryName:e=>this.formatCategoryName(e)},t);this.resultsContainer.innerHTML=Ze(n),this.config.productCard?.customJs&&function(e,t){const n=li.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,t)=>`${e} ${t}`};ci(n,e.template,e.unifiedProduct,t)}}),li.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&&Jn(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=Zn(o,{loading:"Adding...",success:"Added!",error:"Error",default:"Add to Cart"});Xn(i,t.cartPlatform,{buttonState:r})}else Xn(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,e.currency)}</span>\n ${t?`<span class="ws-product-card-old-price">${i.formatPrice(e.originalPrice,e.currency)}</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,Kn(5,this.siteKey),{formatPrice:(e,t)=>Un(e,t,this.config?.styles),escapeHtml:zn,formatCategoryName:qn});e&&(this.resultsContainer.innerHTML=Ze(e),this.attachSuggestionListeners(),this.openResults())}attachSuggestionListeners(){this.resultsContainer&&(this.resultsContainer.querySelector(".ws-clear-recent")?.addEventListener("click",e=>{e.stopPropagation(),function(e){try{localStorage.removeItem(`${Wn}_${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=Kn(5,t);n=n.filter(t=>t.toLowerCase()!==e.toLowerCase()),localStorage.setItem(`${Wn}_${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()),Jn(this.getAPIConfig(),t,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()))})}))}showLoading(){if(!this.resultsContainer)return;const e=zn(this.config?.styles?.textLoading||"Searching...");this.resultsContainer.innerHTML=Ze(`\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=zn(e);this.resultsContainer.innerHTML=Ze(`\n <div class="ws-search-empty">\n ${jn("",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 pi=n(126);function hi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gi(e){if(!hi(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,pi.validateRecommendationConfig)(t).valid)return null;const n=(0,pi.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,isTestMode:"boolean"==typeof e.isTestMode?e.isTestMode:"boolean"==typeof e.testMode&&e.testMode,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:hi(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 mi="data-selwise-recommendation",fi=`[${mi}="true"]`;function yi(e){return!!document.getElementById(`rec-widget-${e}`)}function bi(e,t){return new Intl.NumberFormat(void 0,{style:"currency",currency:An(t)}).format(e)}const wi=new Map;function Si(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,currency:An(e.currency),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:bi};return n&&o.customJs&&(wi.has(n)||wi.set(n,[]),wi.get(n).push({template:o,unifiedProduct:i,productItemCode:e.itemCode||e.id})),ai(i,o,r)}(e,t.productCard,a):s.innerHTML=et(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 ${ii}="${ri}"\n ${oi}="${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">${bi(e.originalPrice,e.currency)}</span>`:""}\n <span class="recommendation-price-current">${bi(e.price,e.currency)}</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 c=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(`[${ii}="${ri}"]`)?(a.preventDefault(),void i(e,t,n,o,r)):c?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}const xi=new Map;function vi(e){const t=window.innerWidth;return t<640?e.slidesPerViewMobile||1:t<1024?e.slidesPerViewTablet||2:e.slidesPerView||4}function Ci(e,t){const n=t.querySelector(".recommendation-slider-track");if(!n)return;const i=vi(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=xi.get(e.id);a&&(a.slidesPerView=i)}function ki(e,t,n){const i=xi.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),Ti(e,t),Ii(t,i.currentIndex,e)}function Ti(e,t){const n=xi.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 Ii(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 Ei(e,t){const n=xi.get(e.id);n&&(_i(e),n.autoplayInterval=setInterval(()=>{ki(e,t,"next")},e.autoplaySpeed))}function _i(e){const t=xi.get(e.id);t?.autoplayInterval&&(clearInterval(t.autoplayInterval),t.autoplayInterval=void 0)}function Pi(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";Xn(a,s,"akinon"===s?{buttonState:Zn(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 Ai=!1;function $i(){try{{const e=Ct();if(e&&"string"==typeof e)return e}}catch(e){Ai||(Ai=!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 Oi(e,t,n,i){try{const o="string"==typeof n&&n.trim().length>0?n.trim():null;if("click"===e)try{sessionStorage.setItem(f,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:$i(),visitorId:kt(),userId:Tt(),pageUrl:window.location.href,eventId:_t(),metadata:{referrer:document.referrer||void 0}})})}catch(e){console.error("[Recommendation] Error tracking event:",e)}}async function Di(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:$i(),visitorId:kt(),siteUserId:Tt(),pageUrl:window.location.href,referrer:document.referrer||void 0,eventId:_t()})})}catch(e){console.error("[Recommendation] Error tracking behavior:",e)}}async function Li(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:$i(),visitorId:kt(),siteUserId:Tt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:_t(),name:"slider_navigate",entityType:"recommendation",entityId:e,metadata:{direction:t,fromSlide:n,toSlide:i}}]})})}catch{}}async function Ni(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:$i(),visitorId:kt(),siteUserId:Tt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:_t(),name:"slider_swipe",entityType:"recommendation",entityId:e,metadata:{direction:t}}]})})}catch{}}const Mi=new WeakMap,Ri=new Set,Bi=new Set,Ui=new Map;let zi=!1;const qi=qt(),Fi=gt();function ji(){setTimeout(()=>{Ui.forEach((e,t)=>{e.disconnect()}),Ui.clear(),G("Recommendation","Cleaned up observers on navigation")},500)}function Hi(e){return!!function(e){return!0===e.isTestMode||!0===e.testMode}(e)&&!function(){try{return"undefined"!=typeof localStorage&&"true"===localStorage.getItem(g)}catch{return!1}}()&&(K("Recommendation",`Skipping test mode widget: ${e.id}. Run localStorage.setItem('${g}', 'true') to view.`),!0)}function Wi(e){const t=e?.triggerConfig,n=t?.frequencyCap;if(n&&"object"==typeof n)return n}async function Ki(e){try{!function(){if(zi)return;zi=!0;const e=history.pushState,t=history.replaceState;history.pushState=(...t)=>{e.apply(history,t),ji()},history.replaceState=(...e)=>{t.apply(history,e),ji()},window.addEventListener("popstate",()=>ji()),window.addEventListener("hashchange",()=>ji())}();let t=(Array.isArray(e.widgets)?e.widgets:[]).map(e=>gi(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=>gi(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:Wi(e)}));const t=e.map(e=>{const t=(e?.triggerConfig||{}).conflictResolution||{};return{...Fi.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:Wi(e)}}),n=Fi.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=>!Hi(e)).filter(e=>{const t=Xt(e.pageTargetingJson,window.location.href);return t||K("Recommendation","Skipping widget due to page targeting:",e.id),t}));for(const t of n)await Gi(t.widget,e,t.frequencyKey,t.frequencyCapConfig)}catch(e){J("Recommendation","Error initializing:",e)}}async function Gi(e,t,n,i){const o=yi(e.id);if(o&&!Bi.has(e.id))return Bi.add(e.id),!1;if(!o&&Bi.has(e.id)&&Bi.delete(e.id),Bi.has(e.id))return!1;const r=()=>{if(!i)return!0;const t=qi.canShow(n,i);return!!t.allowed||(K("Recommendation",`Skipping widget due to frequency cap (${t.reason||"limit"})`,e.id),!1)};if(!e.containerSelector){if(await Qi(e,t)){if(!r())return!1;if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return!1;const o=Yi(e,t);if(!o)return!1;if(Hi(o))return!1;Bi.add(o.id);const a=await Xi(o,t);return a&&i&&qi.recordShown(n),a}return!1}if(document.querySelector(e.containerSelector)){if(await Qi(e,t)){if(!r())return!1;if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return!1;const o=Yi(e,t);if(!o)return!1;if(Hi(o))return!1;Bi.add(o.id);const a=await Xi(o,t);return a&&i&&qi.recordShown(n),a}return!1}return K("Recommendation","Container not found, setting up observer for:",e.containerSelector),function(e,t,n,i){if(Ui.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(yi(e.id))Ji(e.id);else if(document.querySelector(e.containerSelector)&&await Qi(e,t)){if(i&&!qi.canShow(n,i).allowed)return void Ji(e.id);if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return void Ji(e.id);const o=Yi(e,t);if(!o)return void Ji(e.id);if(Hi(o))return void Ji(e.id);Bi.add(o.id),await Xi(o,t)&&i&&qi.recordShown(n),Ji(e.id),K("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}),Ui.set(e.id,r),setTimeout(()=>{Ji(e.id),o.cancel()},1e4)}(e,t,n,i),!1}function Ji(e){const t=Ui.get(e);t&&(t.disconnect(),Ui.delete(e))}function Vi(){Ui.forEach((e,t)=>{e.disconnect(),G("Recommendation","Cleaned up observer for:",t)}),Ui.clear(),document.querySelectorAll(fi).forEach(e=>{e.remove()}),Bi.forEach(e=>{const t=document.getElementById(`rec-widget-${e}`);t&&t.remove()}),Bi.clear(),Ri.clear(),G("Recommendation","Module cleanup complete")}function Yi(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 K("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=Gt(i);if(t){K("Recommendation","Applying config override:",i.variantName);const n=Ht(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=Ht(e.containerStyles||{},t.styles)),t.displayType&&(e.displayType=t.displayType)}e._experimentAssignment=i}return e}async function Qi(e,t){if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return K("Recommendation","Skipping widget (excluded by experiment):",e.id),!1;if(e.containerSelector){const t=document.querySelector(e.containerSelector);if(K("Recommendation","Container check:",e.containerSelector,"-> Found:",!!t),!t)return!1}return!!Xt(e.pageTargetingJson,window.location.href)&&(!(t.segmentManager&&e.segmentTargetingMode&&e.segmentIds&&!await t.segmentManager.shouldShow(e.segmentTargetingMode,e.segmentIds))||(K("Recommendation","Skipping widget due to segment targeting:",e.id),!1))}async function Xi(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=$i()}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(mi,"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=>Si(t,e,n,Pi,Oi,Di,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=wi.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:bi};ci(n,e.template,e.unifiedProduct,t)}}),wi.delete(e))}(i,r),r}(e,t,n);if(i.appendChild(r),e.customCSS){const t=document.createElement("style");t.textContent=tt(e.customCSS),i.appendChild(t)}if(e.productCard&&e.productCard.customCSS){const t=document.createElement("style");t.textContent=tt(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:$i(),visitorId:kt(),siteUserId:Tt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:_t(),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=vi(e),s={currentIndex:0,totalSlides:r.children.length,slidesPerView:a,touchStartX:0,touchEndX:0};xi.set(e.id,s),Ci(e,t);const c=t.querySelector(".recommendation-arrow-prev"),l=t.querySelector(".recommendation-arrow-next");c?.addEventListener("click",()=>{const o=s.currentIndex;ki(e,t,"prev"),i?.(e.id,"prev",o,s.currentIndex,n)}),l?.addEventListener("click",()=>{const o=s.currentIndex;ki(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=xi.get(e.id);i&&(i.currentIndex=n,Ti(e,t),Ii(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=xi.get(e.id);if(!n)return;const i=n.touchStartX-n.touchEndX;i>50?ki(e,t,"next"):i<-50&&ki(e,t,"prev")}(e,t)},{passive:!0}),e.autoplay&&(Ei(e,t),e.pauseOnHover&&(t.addEventListener("mouseenter",()=>{_i(e)}),t.addEventListener("mouseleave",()=>{Ei(e,t)}))),window.addEventListener("resize",()=>{Ci(e,t),Ti(e,t)})}(e,s,t,Li,Ni),function(e,t,n){const i=Mi.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&&!Ri.has(a)){Ri.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:$i(),visitorId:kt(),siteUserId:Tt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:[{eventId:_t(),name:"product_impression",entityType:"recommendation",entityId:t,productItemCode:r,metadata:{productItemCode:r,position:e}}]})}).catch(()=>{})}}})},{threshold:.5});Mi.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{V("Recommendation","Executing custom JS for widget:",e.id),new Function("widgetElement","products","widgetConfig",e.customJS)(s,a,e)}catch(e){J("Recommendation","Custom JS error:",e)}return!0}catch(e){return J("Recommendation","Error rendering widget:",e),!1}}const Zi={loadSearchModule:async()=>({SearchModule:ui}),loadRecommendationModule:async()=>({initRecommendations:Ki,cleanup:Vi})},eo={canShow:()=>({allowed:!0}),recordShown:()=>{},cleanup:()=>{}};class to{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=gt(),this.originalPushState=null,this.originalReplaceState=null,this.popStateListener=null,this.pendingTimeouts=new Set,this.spaCleanupSetup=!1,this.config={siteKey:"",apiUrl:bt(),exposeGlobal:!1},this.renderer=new ut,this.moduleLoaders={...Zi,...e}}get tracker(){return this.trackerInstance||(this.trackerInstance=new Mt(this.config.apiUrl||bt(),this.config.siteKey)),this.trackerInstance}set tracker(e){this.trackerInstance=e}get frequencyCapManager(){return this.isBrowserEnvironment()?(this.frequencyCapManagerInstance||(this.frequencyCapManagerInstance=qt()),this.frequencyCapManagerInstance):eo}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(),_.forEach((e,t)=>{O(t)}),document.querySelectorAll(E).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(E).forEach(n=>{const i=n.getAttribute(T)===e,o=!t||n.getAttribute(I)===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 V("Selwise","init() must be called in a browser environment");this.isDestroyed=!1;const t=this.detectMissingFeatures();if(t.length>0&&V("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(!tn(t))return void console.warn("[Selwise] Sentry DSN validation failed - not initializing");const n=window.SelwiseConfig;return async function(e){if(e.dsn)if(tn(e.dsn))try{await async function(){if(!nn)return on||(on=new Promise((e,t)=>{if(window.Sentry)return nn=!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=()=>{nn=!0,e()},n.onerror=()=>{console.warn("[Selwise] Failed to load Sentry from CDN"),t(new Error("Sentry CDN load failed"))},document.head.appendChild(n)}),on)}();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:rn,beforeSend:an,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 Jt(this.config.siteKey,this.tracker.getVisitorId(),this.config.apiUrl),await this.experiments.init(),this.segments=new Zt(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=>(J("Selwise","Failed to load site config:",e),null)),this.loadScripts().catch(e=>(J("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();this.applyPublicIntegrationsConfig(e)}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 V("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}),H(o.debugMode||!1),await this.tracker.initialize(),this.config.dataLayerConfig=o.dataLayerConfig,o.debugMode&&K("Selwise","Tracking config loaded from batch endpoint:",o)}K("Selwise","Loaded site config from batch endpoint:",{campaigns:this.campaigns.length,widgets:this.widgets.length,recommendations:this.recommendationWidgets.length}),this.initDataLayer()}else V("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 V("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 V("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}),H(t.debugMode||!1),await this.tracker.initialize(),t.debugMode&&K("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 V("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();this.applyPublicIntegrationsConfig(e)}}catch(e){G("Selwise","Failed to load tracking config, using defaults")}}applyPublicIntegrationsConfig(e){if(!e||"object"!=typeof e)return;const t=this.mergeReverseMappings(e.integrations||[]),n=this.resolveExternalDataLayerName(e);Object.keys(t).length>0&&(this.config.reverseEventMapping=t,K("Selwise","Reverse event mapping loaded:",t)),n&&(this.config.externalDataLayerName=n,K("Selwise","External dataLayer source configured:",n)),"string"==typeof e.dataLayer?.platform&&e.dataLayer.platform.trim()&&(this.config.dataLayerPlatform=e.dataLayer.platform.trim()),"boolean"==typeof e.dataLayer?.useExternalDataLayer&&(this.config.useExternalDataLayer=e.dataLayer.useExternalDataLayer)}mergeReverseMappings(e){const t={};if(!e||0===e.length)return t;for(const n of e){if(!n?.enabled||!n.reverseEventMapping)continue;const e=n.provider||n.id||"unknown";for(const[i,o]of Object.entries(n.reverseEventMapping))if("string"==typeof o&&o.trim()){if(Object.prototype.hasOwnProperty.call(t,i)){const n=t[i];n!==o&&V("Selwise",`Reverse mapping collision for "${i}" ignored from ${e}. Keeping "${n}", skipping "${o}".`);continue}t[i]=o}}return t}resolveExternalDataLayerName(e){const t=e.dataLayer&&"string"==typeof e.dataLayer.externalDataLayerName&&e.dataLayer.externalDataLayerName.trim().length>0?e.dataLayer.externalDataLayerName.trim():null;if(t)return t;for(const t of e.integrations||[]){if(!t?.enabled)continue;const e=t.config&&"string"==typeof t.config.externalDataLayerName&&t.config.externalDataLayerName.trim().length>0?t.config.externalDataLayerName.trim():null;if(e)return e}return null}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(()=>({}));V("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=>(J("Selwise","Failed to load campaigns:",e),null)),t=this.loadWidgets().catch(e=>(J("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||{},n=this.config.externalDataLayerName||e.externalDataLayerName||"dataLayer",i=this.config.dataLayerPlatform||e.platform||"generic",o="boolean"==typeof this.config.useExternalDataLayer?this.config.useExternalDataLayer:e.useExternalDataLayer??!0;this.dataLayerEnabled=e.enabled??!0,this.dataLayerManager=new Bn(this.tracker,this.config.siteKey,bt(this.config.apiUrl),{enabled:e.enabled??!0,variableName:e.variableName??"selwiseLayer",platform:i,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,useExternalDataLayer:o,reverseEventMapping:Object.keys(t).length>0?t:void 0,externalDataLayerName:n,attachToGlobalApi:Boolean(this.config.exposeGlobal)}),this.dataLayerEnabled?(this.dataLayerManager.init(),K("Selwise","Data layer manager initialized and started")):K("Selwise","Data layer manager created but NOT enabled (disabled in dashboard settings)"),e.debugMode&&K("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):V("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):V("Selwise","Data layer is not initialized; grantConsent was ignored")}revokeConsent(e){this.dataLayerManager&&this.dataLayerEnabled?this.dataLayerManager.revokeConsent(e):V("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,K("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(()=>({}));V("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(()=>({}));V("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||[];K("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),K("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),K("Selwise",`Injected script: ${e.name}`),this.tracker.track("script_injected",{entityType:"script",entityId:e.id,metadata:{name:e.name}})}catch(t){J("Selwise",`Failed to execute script: ${e.name}`),G("Selwise","Script execution error details:",t),t instanceof SyntaxError&&V("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=Xt(e.pageTargetingJson,window.location.href);return n||K("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(K("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){K("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=It(),o="campaign"===t?"campaign":"widget",r=!0===e.isTestMode||!0===e.testMode;if(this.renderedEntities.has(e.id))return K("Selwise",`Skipping already rendered ${o}: ${e.id}`),!1;if(r&&!i)return V("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 a=n?null:this.experiments?.getVariantModuleForTarget(e.id);if(a&&a.moduleData)return K("Selwise",`Rendering variant module for ${o}: ${e.id} -> variant: ${a.moduleData.id}`),await this.renderVariantModule(a.moduleData,a.experimentId,a.variantId,a.targetType||t),!1;if(this.experiments&&!this.experiments.shouldRenderTarget(e.id))return K("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 K("Selwise",`Skipping ${o} due to segment targeting: ${e.id}`),!1;if(!e.contentJson||0===Object.keys(e.contentJson).length)return V("Selwise",`Skipping empty ${o}: ${e.id}`),!1;let s=Wt(e.contentJson||{}),c=e.stylesJson||{},l=e.placementConfigJson||{};const d=this.experiments?.getVariant(e.id)||this.experiments?.getAssignmentByTargetId(e.id);if(d){const e=Gt(d);e?.content&&"object"==typeof e.content&&(s=Ht(s,Wt(e.content))),e?.styles&&"object"==typeof e.styles&&(c=Ht(c,e.styles)),e?.placement&&"object"==typeof e.placement&&(l=Ht(l,e.placement))}const u={id:e.id,type:e.type,placementConfigJson:l,__entityType:t},p={id:e.id,contentJson:s,stylesJson:c};this.cleanupRenderedEntityById(e.id,t);const h=this.renderer.render(u,p);if(h){this.renderedEntities.add(e.id);const n="campaign"===t?"campaign":"widget";return this.tracker.track("impression",{entityType:n,entityId:e.id}),d&&this.experiments?.trackImpression(d.experimentId),h.addEventListener("click",t=>{const i=this.resolveTrackableInteractionTarget(t,h);if(!i)return;const o=this.buildClickMetadata(i),r=this.isLikelyAddToCartAction(o.buttonText||"",o.linkUrl);this.tracker.track("click",{entityType:n,entityId:e.id,metadata:o}),r&&this.tracker.track("add_to_cart",{entityType:n,entityId:e.id,metadata:o}),d&&this.experiments?.trackConversion(d.experimentId)},{capture:!0}),!0}return!1}resolveTrackableInteractionTarget(e,t){const n=this.resolveEventTargetElement(e);if(!n||!t.contains(n))return null;if(this.closestWithinRoot(n,t,'.selwise-close, [data-selwise-ignore-click="true"]'))return null;return this.closestWithinRoot(n,t,'a[href], button, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-selwise-track-click="true"]')||n}resolveEventTargetElement(e){if(e.target instanceof HTMLElement)return e.target;if("function"==typeof e.composedPath){const t=e.composedPath();for(const e of t)if(e instanceof HTMLElement)return e}return null}closestWithinRoot(e,t,n){const i=e.closest(n);return i instanceof HTMLElement&&t.contains(i)?i:null}buildClickMetadata(e){const t=e.closest("a[href]"),n=(e.textContent||(e instanceof HTMLInputElement?e.value:"")||e.getAttribute("aria-label")||e.getAttribute("title")||"").trim().replace(/\s+/g," "),i={targetTag:e.tagName.toLowerCase()};if(n.length>0&&(i.buttonText=n),t instanceof HTMLAnchorElement){const e=(t.getAttribute("href")||t.href||"").trim();e.length>0&&(i.linkUrl=e)}return i}isLikelyAddToCartAction(e,t){const n=e.toLowerCase(),i=(t||"").toLowerCase();return/add to cart|buy now|purchase|add to bag|sepete ekle|satın al|hemen al|sepete at|satın al şimdi/i.test(n)||i.length>0&&/cart|checkout|basket|sepet|odeme|payment/i.test(i)}async renderVariantModule(e,t,n,i){let o,r;if(e.data?(o=e.data,r=e.targetType||i||"widget"):(o=e,r=i||"widget"),!0!==o?.isTestMode&&!0!==o?.testMode||It())switch(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":K("Selwise","Variant recommendation module will be rendered by recommendations module");break;case"search_config":K("Selwise","Variant search config will be applied by search module");break;default:V("Selwise",`Unknown target type for variant module: ${r}`)}else V("Selwise",`Skipping test mode variant module (${r}): ${o?.id||"unknown"} (Run localStorage.setItem('selwise_test_mode', 'true') to view)`)}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)}V("Selwise","Subscription inactive. Widget will not display. Message: "+e)}}module.exports=i})();
2
+ (()=>{"use strict";var e={48(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 c(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 l(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"}),c({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"}]},l()],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"}),l()],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"}}}),c({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","ideasoft","ikas","ticimax","tsoft","wix","bigcommerce","opencart","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=u,t.validateFrequencyCapPayload=function(e){if(null==e)return{valid:!0};if(!d(e))return{valid:!1,message:"invalid frequency cap payload"};const t=Object.keys(e).filter(e=>!c.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&&u(e.minInterval)?{valid:!0}:{valid:!1,message:"invalid frequency cap minInterval"}},t.validateDataLayerConfig=function(e){if(!d(e))return{valid:!1,message:"invalid data layer config payload"};if(void 0!==e.externalDataLayerName&&("string"!=typeof e.externalDataLayerName||0===e.externalDataLayerName.trim().length))return{valid:!1,message:"invalid external data layer name"};if(void 0!==e.useExternalDataLayer&&"boolean"!=typeof e.useExternalDataLayer)return{valid:!1,message:"invalid use external data layer flag"};if(void 0!==e.platform&&("string"!=typeof e.platform||!l.has(e.platform)))return{valid:!1,message:"invalid data layer platform"};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(!d(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(!d(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(!d(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(!d(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=d(e.trackingModules)?e.trackingModules:{};for(const e of Object.keys(t)){const i=n[e];d(i)&&"boolean"==typeof i.enabled&&(t[e]={enabled:i.enabled,...d(i.config)?{config:i.config}:{}})}const o={...i.COOKIE_CONSENT_DEFAULTS,...d(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:d(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),c=new Set(["perSession","perDay","perWeek","total","minInterval"]),l=new Set(i.DATA_LAYER_PLATFORMS);function d(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function u(e){return s.has(e)}},496(e,t){Object.defineProperty(t,"__esModule",{value:!0})},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(496),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 ISO code"},{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,{id:"position_style_compat",title:"Position Style Compatibility",icon:"Move",fields:[{key:"modalWidth",label:"Modal Width",type:"text",default:""},{key:"modalMaxHeight",label:"Modal Max Height",type:"text",default:""},{key:"modalRadius",label:"Modal Radius",type:"text",default:""},{key:"modalShadow",label:"Modal Shadow",type:"text",default:""},{key:"sidebarShadow",label:"Sidebar Shadow",type:"text",default:""},{key:"floatingButtonSize",label:"Floating Button Size",type:"text",default:""},{key:"floatingButtonOffset",label:"Floating Button Offset",type:"text",default:""},{key:"floatingButtonBg",label:"Floating Button Background",type:"color",default:""},{key:"floatingButtonIconColor",label:"Floating Button Icon",type:"color",default:""},{key:"floatingButtonRadius",label:"Floating Button Radius",type:"text",default:""},{key:"floatingButtonShadow",label:"Floating Button Shadow",type:"select",options:["none","sm","md","lg","xl","2xl"],default:""},{key:"floatingButtonShadowColor",label:"Floating Button Shadow Color",type:"color",default:""},{key:"floatingButtonHoverShadow",label:"Floating Button Hover Shadow",type:"select",options:["none","sm","md","lg","xl","2xl"],default:""},{key:"floatingButtonSelector",label:"Floating Button Selector",type:"text",default:""},{key:"floatingButtonInjectionMode",label:"Floating Button Injection Mode",type:"select",options:["append","prepend","before","after","replace"],default:"append"}]},{id:"legacy_style_compat",title:"Legacy Style Compatibility",icon:"Settings",fields:[{key:"resultHoverBg",label:"Result Hover Background",type:"color",default:""},{key:"gridGap",label:"Grid Gap",type:"text",default:""},{key:"itemBg",label:"Item Background",type:"color",default:""},{key:"cardImageHeight",label:"Card Image Height",type:"text",default:""},{key:"originalPriceColor",label:"Original Price Color",type:"color",default:""},{key:"dropdownBg",label:"Dropdown Background",type:"color",default:""},{key:"footerBg",label:"Footer Background",type:"color",default:""},{key:"footerText",label:"Footer Text Color",type:"color",default:""},{key:"panelWidth",label:"Panel Width",type:"text",default:""},{key:"resultsWidth",label:"Results Width",type:"text",default:""},{key:"inputBorderStyle",label:"Input Border Style",type:"text",default:""},{key:"inputBorderColor",label:"Input Border Color",type:"color",default:""},{key:"inputPaddingTop",label:"Input Padding Top",type:"text",default:""},{key:"inputPaddingRight",label:"Input Padding Right",type:"text",default:""},{key:"inputPaddingBottom",label:"Input Padding Bottom",type:"text",default:""},{key:"inputPaddingLeft",label:"Input Padding Left",type:"text",default:""},{key:"inputMarginTop",label:"Input Margin Top",type:"text",default:""},{key:"inputMarginRight",label:"Input Margin Right",type:"text",default:""},{key:"inputMarginBottom",label:"Input Margin Bottom",type:"text",default:""},{key:"inputMarginLeft",label:"Input Margin Left",type:"text",default:""},{key:"floatingButtonBorder",label:"Floating Button Border",type:"text",default:""},{key:"floatingButtonPaddingTop",label:"Floating Button Padding Top",type:"text",default:""},{key:"floatingButtonPaddingRight",label:"Floating Button Padding Right",type:"text",default:""},{key:"floatingButtonPaddingBottom",label:"Floating Button Padding Bottom",type:"text",default:""},{key:"floatingButtonPaddingLeft",label:"Floating Button Padding Left",type:"text",default:""},{key:"floatingButtonMarginTop",label:"Floating Button Margin Top",type:"text",default:""},{key:"floatingButtonMarginRight",label:"Floating Button Margin Right",type:"text",default:""},{key:"floatingButtonMarginBottom",label:"Floating Button Margin Bottom",type:"text",default:""},{key:"floatingButtonMarginLeft",label:"Floating Button Margin Left",type:"text",default:""}]}],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.DATA_LAYER_PLATFORMS=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.DATA_LAYER_PLATFORMS=["auto","generic","ideasoft","ikas","ticimax","tsoft","akinon","shopify","woocommerce","magento","wix","bigcommerce","opencart","prestashop","custom","none"],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:{},c={};if("string"==typeof r.selector&&r.selector.trim().length>0&&(c.selector=r.selector.trim()),"string"==typeof r.insertPosition&&o.has(r.insertPosition)&&(c.insertPosition=r.insertPosition),n?.placementOptions?.length){const e=new Set(n.placementOptions);"string"==typeof r.position&&e.has(r.position)?c.position=r.position:"selector"!==n.placementType&&(c.position=n.placementOptions[0])}const l=s(e,r);return c.placementType=l,a(r.conflictResolution)&&(c.conflictResolution=r.conflictResolution),a(r.frequencyCap)&&(c.frequencyCap=r.frequencyCap),c};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&&c.has(e.position)?void 0===e.floatingPosition||"string"==typeof e.floatingPosition&&l.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"]),c=new Set(i.SEARCH_POSITIONS.map(e=>e.value)),l=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]:{},c=new Set(n.fields.map(e=>e.key));for(const[e,t]of Object.entries(s))c.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),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};n.r(i),n.d(i,{Selwise:()=>mo,default:()=>mo,resolveApiUrl:()=>bt});let o=!1;var r=n(529);const a="selwise_sid",s="selwise_vid",c="selwise_suid",l="selwise_supid",d="selwise_journey_id",u="selwise_journey_created",p="selwise_correlation_id",h="selwise_correlation_created",g="selwise_test_mode",m="selwise_last_touch",f="selwise_last_touch_reco",y="selwise_last_touch_search",b="selwise_experiments",w="selwise_consent",S="selwise_interacted_",x="selwise_merged_vids",v="selwise_user_traits",k={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",T="data-selwise-entity-id",I="data-selwise-entity-type",E=`[${C}="true"]`,_=new Map;function P(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 A(e){return{normal:"400",medium:"500",semibold:"600",bold:"700"}[e||"normal"]||"400"}function $(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(T,t.id),e.setAttribute(I,i)}function D(e){const t=_.get(e);t&&(t.observer&&t.observer.disconnect(),null!==t.timeoutId&&clearTimeout(t.timeoutId),_.delete(e))}function M(e,t,n=6e3){D(e);const i=()=>{try{const n=t();return n&&D(e),n}catch(t){return console.error("[Selwise] Deferred renderer failed:",t),D(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(()=>{D(e)},n);_.set(e,{observer:o,timeoutId:r})}function O(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 L(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(`${S}${e}`)}catch{return!1}}function R(e){try{localStorage.setItem(`${S}${e}`,"true")}catch{}}function B(e){if(!e)return"#";const t=e.trim();return t&&/^(https?:|mailto:|tel:|\/|#)/i.test(t)?t:"#"}function z(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 D(n),console.warn(`[Selwise] Selector is required for widget type "${t.type}": ${t.id}`),!1;const s={...o,selector:r};return L(e,s)?(D(n),!0):(M(n,()=>L(e,s),i),!1)}let F=!1;function q(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=A(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 j=!1;function H(e){j=e}function W(){if("undefined"==typeof localStorage)return!1;try{return j||"true"===localStorage.getItem("selwise_test_mode")||"true"===localStorage.getItem("selwise_debug")}catch{return j}}const K=(e,...t)=>{W()&&console.log(`[${e}]`,...t)},G=(e,...t)=>{W()&&console.debug(`[${e}]`,...t)},V=(e,...t)=>{console.error(`[${e}]`,...t)},J=(e,...t)=>{console.warn(`[${e}]`,...t)};function Y(e,t){try{const n=`${w}_${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 Q(e,t){const n=window.Selwise?.siteKey;if(!n)return null;const i=function(e){try{const t=`${w}_${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||{};K("CookieConsent","campaign payload:",{content:o,styles:r});const a=r,s=window.Selwise?.trackingConfig?.cookieConsent||{},c=e.configJson||{},l={granularEnabled:a.granularEnabled??s.granularEnabled??c.granularEnabled??!1,requiredCategories:(d=a.requiredCategories??s.requiredCategories??c.requiredCategories??"necessary",Array.isArray(d)?d:"string"==typeof d?d.split(",").map(e=>e.trim()).filter(Boolean):["necessary"]),timeoutMs:a.timeoutMs??s.timeoutMs??c.timeoutMs??0};var d;const u=l.granularEnabled??!1,p=new Set(l.requiredCategories||["necessary"]),h=l.timeoutMs||0;K("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:b="Decline",customizeButtonText:S="Customize",subtext:x,linkText:v,linkUrl:k,policyLinkText:C,policyLinkUrl:T}=o,{backgroundColor:I="#1a1a1a",textColor:E="#ffffff",buttonColor:_,buttonTextColor:A,declineButtonColor:D,declineButtonTextColor:M,customizeButtonColor:O,customizeButtonTextColor:L,padding:N="16px",borderRadius:R="8px",shadow:z="lg",border:U="none",maxWidth:F,showDeclineButton:q=!0,showCustomizeButton:j=!0,showCloseButton:H=!1,autoHideAfterMs:W=0,linkColor:G="#60a5fa",headlineFontSize:V,headlineFontWeight:J,textFontSize:Q,buttonFontSize:X,buttonFontWeight:Z}=r,ee=m||"We use cookies",te=f||x||"",ne=e.placementConfigJson?.position||"bottom",ie=_||E,oe=A||I,re=D||"transparent",ae=M||E,se=D?"none":`1px solid ${E}`,ce=O||"transparent",le=L||E,de=v||C||"",ue=B(String(k||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: ${N};\n border-radius: ${R};\n box-shadow: ${P(z)};\n ${U&&"none"!==U?`border: ${U};`:""}\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 `,$(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"}},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(V||"16px")}; font-weight: ${pe(J||"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(V||"16px")}; font-weight: ${pe(J||"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(G)}; 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(b)}\n </button>\n `:""}\n ${u&&j?`\n <button class="selwise-bar-btn selwise-customize" style="background: ${pe(ce)}; color: ${pe(le)}; border: ${pe("transparent"===ce?`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 Y(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(),Y(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 Y(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}};Y(n,e),he.remove(),ve("timeout",e),xe()},h)),W>0&&(be=window.setTimeout(()=>{Se||(Se=!0,he.remove(),xe())},W)),document.body.appendChild(he),he}const{entries:X,setPrototypeOf:Z,isFrozen:ee,getPrototypeOf:te,getOwnPropertyDescriptor:ne}=Object;let{freeze:ie,seal:oe,create:re}=Object,{apply:ae,construct:se}="undefined"!=typeof Reflect&&Reflect;ie||(ie=function(e){return e}),oe||(oe=function(e){return e}),ae||(ae=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)}),se||(se=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 ce=ke(Array.prototype.forEach),le=ke(Array.prototype.lastIndexOf),de=ke(Array.prototype.pop),ue=ke(Array.prototype.push),pe=ke(Array.prototype.splice),he=ke(String.prototype.toLowerCase),ge=ke(String.prototype.toString),me=ke(String.prototype.match),fe=ke(String.prototype.replace),ye=ke(String.prototype.indexOf),be=ke(String.prototype.trim),we=ke(Object.prototype.hasOwnProperty),Se=ke(RegExp.prototype.test),xe=(ve=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return se(ve,t)});var ve;function ke(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 ae(e,t,i)}}function Ce(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:he;Z&&Z(e,null);let i=t.length;for(;i--;){let o=t[i];if("string"==typeof o){const e=n(o);e!==o&&(ee(t)||(t[i]=e),o=e)}e[o]=!0}return e}function Te(e){for(let t=0;t<e.length;t++)we(e,t)||(e[t]=null);return e}function Ie(e){const t=re(null);for(const[n,i]of X(e))we(e,n)&&(Array.isArray(i)?t[n]=Te(i):i&&"object"==typeof i&&i.constructor===Object?t[n]=Ie(i):t[n]=i);return t}function Ee(e,t){for(;null!==e;){const n=ne(e,t);if(n){if(n.get)return ke(n.get);if("function"==typeof n.value)return ke(n.value)}e=te(e)}return function(){return null}}const _e=ie(["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"]),Pe=ie(["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"]),Ae=ie(["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"]),$e=ie(["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"]),De=ie(["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"]),Me=ie(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Oe=ie(["#text"]),Le=ie(["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=ie(["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=ie(["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"]),Be=ie(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ze=oe(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Ue=oe(/<%[\w\W]*|[\w\W]*%>/gm),Fe=oe(/\$\{[\w\W]*/gm),qe=oe(/^data-[\-\w.\u00B7-\uFFFF]+$/),je=oe(/^aria-[\-\w]+$/),He=oe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),We=oe(/^(?:\w+script|data):/i),Ke=oe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ge=oe(/^html$/i),Ve=oe(/^[a-z][.\w]*(-[.\w]+)+$/i);var Je=Object.freeze({__proto__:null,ARIA_ATTR:je,ATTR_WHITESPACE:Ke,CUSTOM_ELEMENT:Ve,DATA_ATTR:qe,DOCTYPE_NAME:Ge,ERB_EXPR:Ue,IS_ALLOWED_URI:He,IS_SCRIPT_OR_DATA:We,MUSTACHE_EXPR:ze,TMPLIT_EXPR:Fe});const Ye=function(){return"undefined"==typeof window?null:window};var Qe=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Ye();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:c,Element:l,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:h,trustedTypes:g}=t,m=l.prototype,f=Ee(m,"cloneNode"),y=Ee(m,"remove"),b=Ee(m,"nextSibling"),w=Ee(m,"childNodes"),S=Ee(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:k,createNodeIterator:C,createDocumentFragment:T,getElementsByTagName:I}=i,{importNode:E}=o;let _={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof X&&"function"==typeof S&&k&&void 0!==k.createHTMLDocument;const{MUSTACHE_EXPR:P,ERB_EXPR:A,TMPLIT_EXPR:$,DATA_ATTR:D,ARIA_ATTR:M,IS_SCRIPT_OR_DATA:O,ATTR_WHITESPACE:L,CUSTOM_ELEMENT:N}=Je;let{IS_ALLOWED_URI:R}=Je,B=null;const z=Ce({},[..._e,...Pe,...Ae,...De,...Oe]);let U=null;const F=Ce({},[...Le,...Ne,...Re,...Be]);let q=Object.seal(re(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(re(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let K=!0,G=!0,V=!1,J=!0,Y=!1,Q=!0,Z=!1,ee=!1,te=!1,ne=!1,oe=!1,ae=!1,se=!0,ve=!1,ke=!0,Te=!1,ze={},Ue=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 je=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"]),Ve="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({},[Ve,Qe,Xe],ge);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 ct=null,lt=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(!lt||lt!==e){if(e&&"object"==typeof e||(e={}),e=Ie(e),at=-1===st.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ct="application/xhtml+xml"===at?ge:he,B=we(e,"ALLOWED_TAGS")?Ce({},e.ALLOWED_TAGS,ct):z,U=we(e,"ALLOWED_ATTR")?Ce({},e.ALLOWED_ATTR,ct):F,tt=we(e,"ALLOWED_NAMESPACES")?Ce({},e.ALLOWED_NAMESPACES,ge):nt,We=we(e,"ADD_URI_SAFE_ATTR")?Ce(Ie(Ke),e.ADD_URI_SAFE_ATTR,ct):Ke,qe=we(e,"ADD_DATA_URI_TAGS")?Ce(Ie(je),e.ADD_DATA_URI_TAGS,ct):je,Ue=we(e,"FORBID_CONTENTS")?Ce({},e.FORBID_CONTENTS,ct):Fe,j=we(e,"FORBID_TAGS")?Ce({},e.FORBID_TAGS,ct):Ie({}),H=we(e,"FORBID_ATTR")?Ce({},e.FORBID_ATTR,ct):Ie({}),ze=!!we(e,"USE_PROFILES")&&e.USE_PROFILES,K=!1!==e.ALLOW_ARIA_ATTR,G=!1!==e.ALLOW_DATA_ATTR,V=e.ALLOW_UNKNOWN_PROTOCOLS||!1,J=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Y=e.SAFE_FOR_TEMPLATES||!1,Q=!1!==e.SAFE_FOR_XML,Z=e.WHOLE_DOCUMENT||!1,ne=e.RETURN_DOM||!1,oe=e.RETURN_DOM_FRAGMENT||!1,ae=e.RETURN_TRUSTED_TYPE||!1,te=e.FORCE_BODY||!1,se=!1!==e.SANITIZE_DOM,ve=e.SANITIZE_NAMED_PROPS||!1,ke=!1!==e.KEEP_CONTENT,Te=e.IN_PLACE||!1,R=e.ALLOWED_URI_REGEXP||He,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&&(G=!1),oe&&(ne=!0),ze&&(B=Ce({},Oe),U=[],!0===ze.html&&(Ce(B,_e),Ce(U,Le)),!0===ze.svg&&(Ce(B,Pe),Ce(U,Ne),Ce(U,Be)),!0===ze.svgFilters&&(Ce(B,Ae),Ce(U,Ne),Ce(U,Be)),!0===ze.mathMl&&(Ce(B,De),Ce(U,Re),Ce(U,Be))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?W.tagCheck=e.ADD_TAGS:(B===z&&(B=Ie(B)),Ce(B,e.ADD_TAGS,ct))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?W.attributeCheck=e.ADD_ATTR:(U===F&&(U=Ie(U)),Ce(U,e.ADD_ATTR,ct))),e.ADD_URI_SAFE_ATTR&&Ce(We,e.ADD_URI_SAFE_ATTR,ct),e.FORBID_CONTENTS&&(Ue===Fe&&(Ue=Ie(Ue)),Ce(Ue,e.FORBID_CONTENTS,ct)),e.ADD_FORBID_CONTENTS&&(Ue===Fe&&(Ue=Ie(Ue)),Ce(Ue,e.ADD_FORBID_CONTENTS,ct)),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 xe('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw xe('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(""));ie&&ie(e),lt=e}},ht=Ce({},[...Pe,...Ae,...$e]),gt=Ce({},[...De,...Me]),mt=function(e){ue(n.removed,{element:e});try{S(e).removeChild(e)}catch(t){y(e)}},ft=function(e,t){try{ue(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){ue(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ne||oe)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=me(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=k.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 C.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 c&&e instanceof c};function xt(e,t,i){ce(e,e=>{e.call(n,t,i,lt)})}const vt=function(e){let t=null;if(xt(_.beforeSanitizeElements,e,null),wt(e))return mt(e),!0;const i=ct(e.nodeName);if(xt(_.uponSanitizeElement,e,{tagName:i,allowedTags:B}),Q&&e.hasChildNodes()&&!St(e.firstElementChild)&&Se(/<[/\w!]/g,e.innerHTML)&&Se(/<[/\w!]/g,e.textContent))return mt(e),!0;if(7===e.nodeType)return mt(e),!0;if(Q&&8===e.nodeType&&Se(/<[/\w]/g,e.data))return mt(e),!0;if(!(W.tagCheck instanceof Function&&W.tagCheck(i))&&(!B[i]||j[i])){if(!j[i]&&Ct(i)){if(q.tagNameCheck instanceof RegExp&&Se(q.tagNameCheck,i))return!1;if(q.tagNameCheck instanceof Function&&q.tagNameCheck(i))return!1}if(ke&&!Ue[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 l&&!function(e){let t=S(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});const n=he(e.tagName),i=he(t.tagName);return!!tt[e.namespaceURI]&&(e.namespaceURI===Qe?t.namespaceURI===Xe?"svg"===n:t.namespaceURI===Ve?"svg"===n&&("annotation-xml"===i||it[i]):Boolean(ht[n]):e.namespaceURI===Ve?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===Ve&&!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||!Se(/<\/no(script|embed|frames)/i,e.innerHTML)?(Y&&3===e.nodeType&&(t=e.textContent,ce([P,A,$],e=>{t=fe(t,e," ")}),e.textContent!==t&&(ue(n.removed,{element:e.cloneNode()}),e.textContent=t)),xt(_.afterSanitizeElements,e,null),!1):(mt(e),!0)},kt=function(e,t,n){if(se&&("id"===t||"name"===t)&&(n in i||n in dt))return!1;if(G&&!H[t]&&Se(D,t));else if(K&&Se(M,t));else if(W.attributeCheck instanceof Function&&W.attributeCheck(t,e));else if(!U[t]||H[t]){if(!(Ct(e)&&(q.tagNameCheck instanceof RegExp&&Se(q.tagNameCheck,e)||q.tagNameCheck instanceof Function&&q.tagNameCheck(e))&&(q.attributeNameCheck instanceof RegExp&&Se(q.attributeNameCheck,t)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(t,e))||"is"===t&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&Se(q.tagNameCheck,n)||q.tagNameCheck instanceof Function&&q.tagNameCheck(n))))return!1}else if(We[t]);else if(Se(R,fe(n,L,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==ye(n,"data:")||!qe[e])if(V&&!Se(O,fe(n,L,"")));else if(n)return!1;return!0},Ct=function(e){return"annotation-xml"!==e&&me(e,N)},Tt=function(e){xt(_.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||wt(e))return;const i={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:U,forceKeepAttr:void 0};let o=t.length;for(;o--;){const r=t[o],{name:a,namespaceURI:s,value:c}=r,l=ct(a),d=c;let u="value"===a?d:be(d);if(i.attrName=l,i.attrValue=u,i.keepAttr=!0,i.forceKeepAttr=void 0,xt(_.uponSanitizeAttribute,e,i),u=i.attrValue,!ve||"id"!==l&&"name"!==l||(ft(a,e),u="user-content-"+u),Q&&Se(/((--!?|])>)|<\/(style|title|textarea)/i,u)){ft(a,e);continue}if("attributename"===l&&me(u,"href")){ft(a,e);continue}if(i.forceKeepAttr)continue;if(!i.keepAttr){ft(a,e);continue}if(!J&&Se(/\/>/i,u)){ft(a,e);continue}Y&&ce([P,A,$],e=>{u=fe(u,e," ")});const p=ct(e.nodeName);if(kt(p,l,u)){if(x&&"object"==typeof g&&"function"==typeof g.getAttributeType)if(s);else switch(g.getAttributeType(p,l)){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):de(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,l=null;if(et=!e,et&&(e="\x3c!--\x3e"),"string"!=typeof e&&!St(e)){if("function"!=typeof e.toString)throw xe("toString is not a function");if("string"!=typeof(e=e.toString()))throw xe("dirty is not a string, aborting")}if(!n.isSupported)return e;if(ee||pt(t),n.removed=[],"string"==typeof e&&(Te=!1),Te){if(e.nodeName){const t=ct(e.nodeName);if(!B[t]||j[t])throw xe("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)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(!ne&&!Y&&!Z&&-1===e.indexOf("<"))return x&&ae?x.createHTML(e):e;if(i=yt(e),!i)return ne?null:ae?v:""}i&&te&&mt(i.firstChild);const d=bt(Te?e:i);for(;s=d.nextNode();)vt(s),Tt(s),s.content instanceof a&&It(s.content);if(Te)return e;if(ne){if(oe)for(l=T.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(U.shadowroot||U.shadowrootmode)&&(l=E.call(o,l,!0)),l}let u=Z?i.outerHTML:i.innerHTML;return Z&&B["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Se(Ge,i.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+i.ownerDocument.doctype.name+">\n"+u),Y&&ce([P,A,$],e=>{u=fe(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(){lt=null,ee=!1},n.isValidAttribute=function(e,t,n){lt||pt({});const i=ct(e),o=ct(t);return kt(i,o,n)},n.addHook=function(e,t){"function"==typeof t&&ue(_[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=le(_[e],t);return-1===n?void 0:pe(_[e],n,1)[0]}return de(_[e])},n.removeHooks=function(e){_[e]=[]},n.removeAllHooks=function(){_={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Xe={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 Ze(e,t){if(!e)return"";const n=t?{...Xe,...t}:Xe;return Qe.sanitize(e,n)}function et(e){return e?Qe.sanitize(e,{...Xe,ADD_TAGS:["img","picture","source"],ADD_ATTR:["loading","decoding","srcset","sizes","data-product-id","data-action"]}):""}function tt(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 nt{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){V("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 it(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 ot(e,t,n,i,o="comma"){const r=performance.now(),a=n-t;requestAnimationFrame(function n(s){const c=s-r,l=Math.min(c/i,1),d=1-Math.pow(1-l,4),u=Math.round(t+a*d);e.textContent=it(u,o),l<1&&requestAnimationFrame(n)})}async function rt(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 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:c,timePeriod:l}=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",$(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 c=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:c,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 rt(a,{},5e3);if(!s.ok)throw new Error("Failed to fetch product view count");const c=(await s.json()).count||0;if(!1!==r.animateCounter)o.forEach(e=>{ot(e,0,c,r.animationDuration||1e3,r.separator||"comma")});else{const e=it(c,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,l,c,i),s):null}function st(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:c,metricType:l}=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",$(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 rt(a,{},5e3);if(!s.ok)throw new Error("Failed to fetch cart count");const c=(await s.json()).count||0;if(!1!==r.animateCounter)o.forEach(e=>{ot(e,0,c,r.animationDuration||1e3,r.separator||"comma")});else{const e=it(c,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,l,c,i),s):null}const ct=/^[^\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 dt(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 ut{render(e,t){!function(){if(o)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),o=!0}();const n={...t,stylesJson:(i=e.type,a=t.stylesJson,(0,r.isWidgetType)(i)?(0,r.sanitizeStyles)(i,a||{}):a||{})};var i,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",c=i.textColor||"#ffffff",l=i.buttonColor||c,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||c,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=c,S.style.padding=u,S.style.fontSize=p,S.style.fontWeight=A(h),S.style.gap="12px",g&&"none"!==g&&(S.style.borderBottom=g),$(S,e,t);const x=z({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=B(n.buttonUrl),t.className="selwise-bar-btn",t.style.background=l,t.style.color=d,t.textContent=n.buttonText,t.addEventListener("click",()=>R(e.id)),S.appendChild(t)}if(m){const e=O(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||{},o=n.title||n.headline||"",a=n.text||"",s=n.subtext||"",c=i.backgroundColor||"#f3f4f6",l=i.textColor||"#1f2937",d=i.buttonColor||l,u=i.buttonTextColor||c,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:k,textAlign:C,ctaAlignSelf:T}=(0,r.resolveInlineBannerLayout)({imageMode:f,contentDirection:i.contentDirection,contentAlignment:i.contentAlignment}),I=document.createElement("div");I.className="selwise-widget selwise-inline",I.style.backgroundColor=c,I.style.color=l,I.style.padding=p,I.style.borderRadius=h,I.style.boxShadow=P(g),I.style.display="flex",I.style.flexDirection=v,I.style.gap=x,I.style.alignItems=k,I.style.textAlign=C,m&&"none"!==m&&(I.style.border=m),$(I,e,t);const E=z({imageUrl:n.imageUrl,mode:f,size:y,aspectRatio:b,objectFit:w,borderRadius:"fullWidth"===f?"0px":S,alt:""});E&&I.appendChild(E);const _=document.createElement("div");if(_.className="selwise-banner-content",_.style.flex="1",_.style.minWidth="0",_.style.display="flex",_.style.flexDirection="column",_.style.gap="4px",_.style.alignItems=k,_.style.textAlign=C,o){const e=document.createElement("h4");e.style.fontSize="16px",e.style.fontWeight="600",e.style.margin="0",e.textContent=o,_.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?" - ":""),_.appendChild(e)}let A=null;return n.buttonText&&(A=document.createElement("a"),A.href=B(n.buttonUrl),A.textContent=n.buttonText,A.style.padding="10px 20px",A.style.background=d,A.style.color=u,A.style.borderRadius="6px",A.style.textDecoration="none",A.style.fontSize="13px",A.style.fontWeight="600",A.style.whiteSpace="nowrap",A.style.display="inline-block",A.style.alignSelf=T),"row"===v&&A?(I.appendChild(_),I.appendChild(A)):(A&&(A.style.marginTop="8px",_.appendChild(A)),I.appendChild(_)),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:c="56px",borderRadius:l="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=B(r),f.className=`selwise-widget selwise-floating selwise-floating-${m}`,f.style.backgroundColor=a,f.style.color=s,f.style.borderRadius=String(l),f.style.boxShadow=P(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(c)]||String(c);/^\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"),$(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(F)return null;F=!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",c=i.buttonColor||s,l=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",k=i.imageBorderRadius||"8px",C="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 _="animation: selwise-scale-in 0.3s ease-out;";"none"===y?_="animation: none;":"fade"===y?_="animation: selwise-fade-in 0.3s ease-out;":"slide"===y&&(_="animation: selwise-slide-up 0.3s ease-out;");const A=document.createElement("div");A.className="selwise-widget selwise-overlay",A.style.display="none",A.style.backgroundColor=T,A.style.cssText+=C,$(A,e,t);const D=document.createElement("div");D.className="selwise-popup",D.style.background=a,D.style.color=s,D.style.maxWidth=h,D.style.padding=g,D.style.borderRadius=m,D.style.boxShadow=P(f),D.style.cssText+=_;const M=document.createElement("button");M.className="selwise-close",M.style.color=s,M.style.top="12px",M.style.right="12px",M.style.position="absolute",M.textContent="×",M.addEventListener("click",()=>A.remove()),D.appendChild(M);const O=z({imageUrl:n.imageUrl,mode:b,size:w,aspectRatio:x,objectFit:v,borderRadius:"fullWidth"===b?"0px":k,alt:""});O&&(O.className="selwise-popup-img",O.style.marginBottom="20px");const L=document.createElement("div");if(L.style.flex="1",o){const e=document.createElement("div");e.className="selwise-popup-title",e.textContent=o,L.appendChild(e)}if(r){const e=document.createElement("div");e.className="selwise-popup-text",e.textContent=r,L.appendChild(e)}if(n.buttonText){const t=document.createElement("a");t.href=B(n.buttonUrl),t.className="selwise-bar-btn",t.style.display="block",t.style.textAlign="center",t.style.background=c,t.style.color=l,t.textContent=n.buttonText,t.addEventListener("click",()=>R(e.id)),L.appendChild(t)}if(!O||"left"!==S&&"right"!==S)O&&"top"===S&&D.appendChild(O),D.appendChild(L),O&&"bottom"===S&&D.appendChild(O);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",O.style.marginBottom="0",e.appendChild(O),e.appendChild(L),D.appendChild(e)}return A.appendChild(D),A.addEventListener("click",e=>{e.target===A&&A.remove()}),document.body.appendChild(A),document.addEventListener("mouseleave",e=>{e.clientY<=0&&"none"===A.style.display&&(A.style.display="flex")},{once:!0}),A}(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",c=i.textColor||"#1f2937",l=i.buttonColor||c,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=c,v.style.width=u,v.style.padding=p,v.style.borderRadius=h,v.style.boxShadow=P(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),$(v,e,t);const k=document.createElement("button");k.className="selwise-close",k.style.color=c,k.style.top="8px",k.style.right="8px",k.style.position="absolute",k.textContent="×",k.addEventListener("click",()=>v.remove()),v.appendChild(k);const C=z({imageUrl:n.imageUrl,mode:b,aspectRatio:w,objectFit:S,borderRadius:"fullWidth"===b?"0px":x,alt:""});if(C&&(C.style.marginBottom="16px",v.appendChild(C)),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=B(n.buttonUrl),t.className="selwise-bar-btn",t.style.display="block",t.style.textAlign="center",t.style.background=l,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",c=i.buttonColor||s,l=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(p),S.style.overflow="hidden",S.style.textAlign=g,h&&"none"!==h&&(S.style.border=h),$(S,e,t);const x=z({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=B(n.buttonUrl),e.className="selwise-bar-btn",e.style.display="inline-block",e.style.background=c,e.style.color=l,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:c}=n,{backgroundColor:l="#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||l,k=document.createElement("div");k.className="selwise-widget selwise-footer",k.style.backgroundColor=l,k.style.color=d,k.style.padding=m,k.style.fontSize=f,k.style.fontWeight=A(y),k.style.boxShadow=P(w),b&&"none"!==b&&(k.style.borderTop=b),$(k,e,t);const C=document.createElement("span");if(C.className="selwise-bar-text",C.textContent=`${S}${a?` - ${a}`:""}`,k.appendChild(C),s){const e=document.createElement("a");e.href=B(c),e.className="selwise-bar-btn",e.style.background=x,e.style.color=v,e.textContent=s,k.appendChild(e)}return!1!==g&&k.appendChild(O(h||d,()=>k.remove())),document.body.appendChild(k),k}(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:c,buttonUrl:l,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,k=e.placementConfigJson.position||"top",C=o||r||"",T=a||s||"",I=f||p,E=y||u,_=h||"rgba(0,0,0,0.1)",P=g||p,D=document.createElement("div");if(D.className=`selwise-widget selwise-bar selwise-bar-${k}`,D.style.backgroundColor=u,D.style.color=p,D.style.padding=b,D.style.fontSize=w,D.style.fontWeight=A(S),$(D,e,t),C){const e=document.createElement("span");e.className="selwise-bar-text",e.style.marginRight="8px",e.textContent=C,D.appendChild(e)}const M=document.createElement("div");M.className="selwise-countdown",M.style.background=_,M.style.color=P;const L="dot"===m?"•":"slash"===m?"/":"none"===m?"":":",N=()=>{if(!L)return;const e=document.createElement("span");e.className="selwise-countdown-sep",e.textContent=L,M.appendChild(e)};if(M.appendChild(q("days","Days",x,v)),N(),M.appendChild(q("hours","Hours",x,v)),N(),M.appendChild(q("minutes","Mins",x,v)),N(),M.appendChild(q("seconds","Secs",x,v)),D.appendChild(M),T){const e=document.createElement("span");e.className="selwise-bar-text",e.style.marginLeft="8px",e.textContent=T,D.appendChild(e)}if(c){const e=document.createElement("a");e.href=B(l),e.className="selwise-bar-btn",e.style.background=I,e.style.color=E,e.textContent=c,D.appendChild(e)}let R;if(D.appendChild(O(p,()=>{D.remove(),R&&clearInterval(R)})),document.body.appendChild(D),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=D.querySelector('[data-unit="days"]'),c=D.querySelector('[data-unit="hours"]'),l=D.querySelector('[data-unit="minutes"]'),d=D.querySelector('[data-unit="seconds"]');s&&(s.textContent=String(i).padStart(2,"0")),c&&(c.textContent=String(o).padStart(2,"0")),l&&(l.textContent=String(r).padStart(2,"0")),d&&(d.textContent=String(a).padStart(2,"0")),n<=0&&R&&clearInterval(R)};t(),R=window.setInterval(t,1e3)}return D}(e,n);case"cookie_consent":return Q(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 c;if(s.className="selwise-widget selwise-custom",s.style.padding=String(a.containerPadding||"0px"),s.style.backgroundColor=String(a.containerBackground||"transparent"),s.innerHTML=(c=n)?Qe.sanitize(c,{...Xe,ADD_TAGS:["style"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur"]}):"",$(s,e,t),i){const e=document.createElement("style");e.setAttribute("data-selwise-custom-css","true"),e.textContent=tt(i),s.appendChild(e)}const l=e.placementConfigJson||{};if("selector"===l.placementType||"string"==typeof l.selector){if(!U(s,e,`custom:${e.id}`))return null}else document.body.appendChild(s);if(o){const n=new nt;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=at(e,t);return i?(D(n),i):(M(n,()=>{const n=at(e,t);return Boolean(n)},7e3),null)}(e,n);case"cart_count":return function(e,t){const n=`cart-count:${e.id}`,i=st(e,t);return i?(D(n),i):(M(n,()=>{const n=st(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=P(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"),$(o,e,t),!1!==i.showCloseButton){const e=O(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 c=document.createElement("input");c.type="email",c.required=!0,c.className="selwise-newsletter-input",c.placeholder=String(n.emailPlaceholder||"you@example.com"),c.style.width="100%",c.style.padding="10px 12px",c.style.borderRadius="8px",c.style.border=`1px solid ${String(i.inputBorderColor||"#d1d5db")}`,c.style.backgroundColor=String(i.inputBackgroundColor||"#f9fafb"),c.style.color=String(i.inputTextColor||"#111827"),c.style.outline="none";const l=document.createElement("button");l.type="submit",l.className="selwise-newsletter-submit",l.textContent=String(n.buttonText||"Subscribe"),l.style.padding="10px 14px",l.style.border="none",l.style.borderRadius="8px",l.style.cursor="pointer",l.style.fontWeight="600",l.style.backgroundColor=String(i.buttonColor||"#111827"),l.style.color=String(i.buttonTextColor||"#ffffff"),s.appendChild(c),s.appendChild(l),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=c.value.trim().toLowerCase();if(!ct.test(t))return void dt(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 dt(d,"error",String(n.errorMessage||"Widget runtime is not initialized."));const o=String(n.buttonText||"Subscribe");l.disabled=!0,c.disabled=!0,l.textContent="Submitting...",dt(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."))),dt(d,r.state,r.message),"error"===r.state?(l.disabled=!1,c.disabled=!1):(l.disabled=!0,c.disabled=!0)}catch{dt(d,"error",String(n.errorMessage||"Unable to subscribe right now. Please try again.")),l.disabled=!1,c.disabled=!1}finally{l.disabled?l.textContent="Done":l.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 pt{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 ht=null;function gt(){return ht||(ht=new pt),ht}const mt="https://api.selwise.com",ft="/api/v1";function yt(e){if(!e)return null;const t=e.trim();return t.length>0?t:null}function bt(e){const t="undefined"!=typeof process?yt(process.env?.NEXT_PUBLIC_API_URL):null,n=yt(e),i=t||n||mt;try{const e=new URL(i),t=function(e){const t=e.replace(/\/+$/,"");return t&&"/"!==t?t===ft||t.endsWith(ft)?t:`${t}${ft}`:ft}(e.pathname||"/");return`${e.origin}${t}`}catch{return`${mt}${ft}`}}const wt=new Map;let St=null;function xt(){return St||(St=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=>wt.get(e)||null,setItem:(e,t)=>wt.set(e,t),removeItem:e=>wt.delete(e)}}()),St}function vt(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 kt(){const e=xt();try{let e=sessionStorage.getItem(a);return e||(e=vt("sid"),sessionStorage.setItem(a,e)),e}catch{let t=e.getItem(a);return t||(t=vt("sid"),e.setItem(a,t)),t}}function Ct(){const e=xt();let t=e.getItem(s);return t||(t=vt("vid"),e.setItem(s,t)),t}function Tt(){return xt().getItem(c)||void 0}function It(){return"true"===xt().getItem(g)}function Et(){const e=xt(),t=Ct();let n=e.getItem(d);const i=e.getItem(u);if(n&&i){const o=parseInt(i,10);if(Date.now()-o<18e5){const i=`journey_${t}`;if(n.startsWith(i))return e.setItem(u,Date.now().toString()),n}}return n=`journey_${t}_${Date.now()}`,e.setItem(d,n),e.setItem(u,Date.now().toString()),n}function _t(){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 Pt=new Set(["productId","productSku","sku"]);function At(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t={};for(const[n,i]of Object.entries(e))Pt.has(n)||(t[n]=i);return t}function $t(e){return"object"==typeof e&&null!==e}function Dt(e){if(!$t(e))return{};const t=Object.entries(e).filter(([,e])=>"boolean"==typeof e);return Object.fromEntries(t)}function Mt(e,t){if(!$t(e))return null;const n=e.granted;let i=Dt(e.categories),o=null;return"boolean"==typeof n?o=n:$t(n)&&(i=Dt(n),o=function(e){const t=Object.entries(e).filter(([e])=>"necessary"!==e);return 0!==t.length&&t.some(([,e])=>!0===e)}(i)),null===o?null:{granted:o,categories:i,timestamp:"number"==typeof e.timestamp&&Number.isFinite(e.timestamp)?e.timestamp:Date.now(),source:t}}function Ot(){const e=Date.now().toString(36);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const t=new Uint8Array(8);return crypto.getRandomValues(t),`rid_${e}_${Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}`}return`rid_${e}_${Math.random().toString(36).slice(2,10)}`}function Lt(e){try{const t=`${w}_${e}`,n=localStorage.getItem(t);if(n){const e=Mt(JSON.parse(n),"site_storage");if(e)return e}const i=localStorage.getItem(w);if(i){const e=Mt(JSON.parse(i),"global_storage");if(e)return e}}catch{}const t=window.__wcmp_consent;if("boolean"==typeof t)return{granted:t,categories:{},timestamp:Date.now(),source:"window_variable"};if("string"==typeof t){const e=t.trim().toLowerCase();if("granted"===e||"denied"===e)return{granted:"granted"===e,categories:{},timestamp:Date.now(),source:"window_variable"}}return Mt(t,"window_variable")||{granted:!1,categories:{necessary:!0,analytics:!1,marketing:!1,preferences:!1},timestamp:Date.now(),source:"default_denied"}}function Nt(e){const t={...Lt(e.siteKey),...e.consentSnapshot||{}};return{requestId:e.requestId||Ot(),sessionId:e.sessionId,visitorId:e.visitorId,siteUserId:e.siteUserId,journeyId:e.journeyId,pageUrl:e.pageUrl,referrer:e.referrer,consentSnapshot:t,events:(n=e.events,n.map(e=>{const t="string"==typeof e.eventId&&e.eventId.trim().length>0?e.eventId:_t(),n="number"==typeof e.eventTs&&Number.isFinite(e.eventTs)?e.eventTs:"number"==typeof e.timestamp&&Number.isFinite(e.timestamp)?e.timestamp:Date.now();return{...e,eventId:t,eventTs:n}}))};var n}const Rt="events";class Bt{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(Rt)){const e=t.createObjectStore(Rt,{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([Rt],"readwrite").objectStore(Rt),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([Rt],"readonly").objectStore(Rt).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(e=>{const{id:t,queuedAt:n,...i}=e;return i})}catch(e){return[]}}async getByEventId(e){if(!this.db)return null;try{const t=this.db.transaction([Rt],"readonly").objectStore(Rt).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([Rt],"readwrite").objectStore(Rt);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([Rt],"readwrite").objectStore(Rt).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([Rt],"readonly").objectStore(Rt);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([Rt],"readwrite").objectStore(Rt).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([Rt],"readonly").objectStore(Rt).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([Rt],"readwrite").objectStore(Rt).clear()}catch{}}isAvailable(){return!this.disabled&&this.initialized&&null!==this.db}}let zt=null;const Ut="selwise_event_queue";class Ft{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,duplicateEvents:0,batchesFailed:0,batchesSent:0,sendBeaconFailed:0,overflowStored:0,latencySamples:0,latencyTotalMs:0,latencyP95WeightedMs:0},this.initialized=!1,this.config={apiUrl:bt(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=(zt||(zt=new Bt),zt),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&&K("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&&K("EventBatcher","Flushing",this.queue.length,"recovered events"),await this.flush())}catch(e){this.debugMode&&V("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&&K("EventBatcher","batchSize updated:",e.batchSize)),void 0!==e.flushInterval&&(this.config.flushInterval=e.flushInterval,this.debugMode&&K("EventBatcher","flushInterval updated:",e.flushInterval)),void 0!==e.enablePersistence&&(this.config.enablePersistence=e.enablePersistence,this.debugMode&&K("EventBatcher","enablePersistence updated:",e.enablePersistence)),void 0!==e.enableSendBeacon&&(this.config.enableSendBeacon=e.enableSendBeacon,this.debugMode&&K("EventBatcher","enableSendBeacon updated:",e.enableSendBeacon)),void 0!==e.maxRetries&&(this.maxRetries=e.maxRetries,this.debugMode&&K("EventBatcher","maxRetries updated:",e.maxRetries)),void 0!==e.maxQueueSize&&(this.maxQueueSize=e.maxQueueSize,this.debugMode&&K("EventBatcher","maxQueueSize updated:",e.maxQueueSize)),void 0!==e.maxStorageEvents&&(this.maxStorageEvents=e.maxStorageEvents,this.debugMode&&K("EventBatcher","maxStorageEvents updated:",e.maxStorageEvents)),void 0!==e.debugMode&&(this.debugMode=e.debugMode,K("EventBatcher","debugMode updated:",e.debugMode))}add(e){const t={...e,metadata:At(e.metadata)};if(t.eventId||(t.eventId=_t()),this.processedEvents.has(t.eventId))return void this.metrics.duplicateEvents++;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=xt();let t=e.getItem(p);const n=e.getItem(h);if(t&&n){const e=parseInt(n,10);if(Date.now()-e<864e5)return t}return t=vt("corr"),e.setItem(p,t),e.setItem(h,Date.now().toString()),t}();if(t.correlationId=`${n}_${this.tabCorrelationId}`,t.parentEventId=this.lastEventId??void 0,t.journeyId=Et(),this.lastEventId=t.eventId,this.config.siteKey&&!this.checkConsentForEvent(t))return this.consentQueue.push(t),void(this.debugMode&&K("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(k);for(const e of n)if(k[e].indexOf(t)>=0){try{const t=`${w}_${this.config.siteKey}`,n=localStorage.getItem(t);if(n){const t=JSON.parse(n);return t.categories?.[e]??!1}}catch(e){this.debugMode&&J("EventBatcher","Failed to read consent state from storage:",e)}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.metrics.eventsDropped+=this.queue.length,this.queue=[],this.saveToStorage(),void(this.hasPendingMetrics()&&this.flushMetrics());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(),this.hasPendingMetrics()&&this.flushMetrics()}}async sendBatch(e){(function(){const e=xt().getItem(u);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:At(e.metadata),journeySequence:t[n]})),i=Nt({siteKey:this.config.siteKey,sessionId:this.sessionData.sessionId,visitorId:this.sessionData.visitorId,siteUserId:this.sessionData.siteUserId,journeyId:Et(),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.batchesSent++,this.recordLatencyMetrics(n)):(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&&K("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:At(e.metadata),journeySequence:t[n]})),i=Nt({siteKey:this.config.siteKey,sessionId:this.sessionData.sessionId,visitorId:this.sessionData.visitorId,siteUserId:this.sessionData.siteUserId,journeyId:Et(),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:Et()};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&&K("EventBatcher","Storage quota exceeded, skipping save"));const e={version:2,queue:this.queue.slice(0,this.maxStorageEvents),timestamp:Date.now()};localStorage.setItem(Ut,JSON.stringify(e)),this.debugMode&&K("EventBatcher","Saved",e.queue.length,"events to storage")}catch(e){this.debugMode&&K("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&&K("EventBatcher","Cleaned up expired journey state"))}catch{localStorage.removeItem(e)}}catch{}}loadFromStorage(){try{const e=localStorage.getItem(Ut);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:At(e.metadata)}))}localStorage.removeItem(Ut)}catch{localStorage.removeItem(Ut)}}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(Ut)}resetCorrelation(){this.lastEventId=null,this.debugMode&&K("EventBatcher","Correlation tracking reset")}getConsentQueueSize(){return this.consentQueue.length}flushConsentQueue(){if(0===this.consentQueue.length)return;this.debugMode&&K("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&&K("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&&K("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&&K("EventBatcher","Cleaned up processed events, kept last 5000")}this.consentQueue.length>100&&(this.consentQueue=this.consentQueue.slice(-50),this.debugMode&&K("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&&K("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&&K("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:At(t.metadata)})}}}catch(e){this.debugMode&&V("EventBatcher","Failed to load overflow storage:",e)}}getMetrics(){const e=this.metrics.latencySamples>0?Math.round(this.metrics.latencyTotalMs/this.metrics.latencySamples):0,t=this.metrics.latencySamples>0?Math.round(this.metrics.latencyP95WeightedMs/this.metrics.latencySamples):0;return{...this.metrics,averageLatencyMs:e,p95LatencyMs:t,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,duplicateEvents:this.metrics.duplicateEvents,batchesFailed:this.metrics.batchesFailed,batchesSent:this.metrics.batchesSent,sendBeaconFailed:this.metrics.sendBeaconFailed,overflowStored:this.metrics.overflowStored,overflowCount:e.count,latencySamples:this.metrics.latencySamples,latencyTotalMs:this.metrics.latencyTotalMs,latencyP95WeightedMs:this.metrics.latencyP95WeightedMs},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,duplicateEvents:0,batchesFailed:0,batchesSent:0,sendBeaconFailed:0,overflowStored:0,latencySamples:0,latencyTotalMs:0,latencyP95WeightedMs:0}}catch{}}recordLatencyMetrics(e){const t=Date.now(),n=e.map(e=>{const n="number"==typeof e.eventTs&&Number.isFinite(e.eventTs)?e.eventTs:e.timestamp;return Math.max(0,t-n)}).filter(e=>Number.isFinite(e));if(0===n.length)return;n.sort((e,t)=>e-t);const i=n.reduce((e,t)=>e+t,0),o=n[Math.min(n.length-1,Math.ceil(.95*n.length)-1)]||0;this.metrics.latencySamples+=n.length,this.metrics.latencyTotalMs+=i,this.metrics.latencyP95WeightedMs+=o*n.length}hasPendingMetrics(){return this.metrics.eventsDropped>0||this.metrics.duplicateEvents>0||this.metrics.batchesFailed>0||this.metrics.batchesSent>0||this.metrics.sendBeaconFailed>0||this.metrics.overflowStored>0||this.metrics.latencySamples>0||this.metrics.latencyTotalMs>0||this.metrics.latencyP95WeightedMs>0}}class qt{constructor(e=bt(),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=kt(),this.visitorId=Ct(),this.siteUserId=Tt(),!1!==n?.enabled&&n&&(this.useAdvancedBatching=!0,this.batcher=new Ft({...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 Ft({...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=xt();e?t.setItem(c,e):t.removeItem(c)}(e)}getSessionId(){return this.sessionId}getVisitorId(){return this.visitorId}getSiteUserId(){return this.siteUserId}getJourneyId(){try{const e=localStorage.getItem(d),t=localStorage.getItem(u);if(e&&t){const n=parseInt(t,10);if(Date.now()-n<18e5)return e}return null}catch{return null}}endJourney(){try{localStorage.removeItem(d),localStorage.removeItem(u)}catch{}}getJourneyState(){try{const e=localStorage.getItem(d),t=localStorage.getItem(u);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(v)||"{}");t&&"object"==typeof t&&!Array.isArray(t)?localStorage.setItem(v,JSON.stringify({...t,...e})):localStorage.setItem(v,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(x)||"[]");if(Array.isArray(t)){const n=new Set([...t,...e]);localStorage.setItem(x,JSON.stringify([...n]))}else{const t=new Set(e);localStorage.setItem(x,JSON.stringify([...t]))}}catch(e){G("Selwise","Failed to update merged visitor IDs:",e)}}getMergedVisitorIds(){try{const e=JSON.parse(localStorage.getItem(x)||"[]");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=_t(),o=At(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(m,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(m)||"null"),t=JSON.parse(sessionStorage.getItem(f)||"null"),n=JSON.parse(sessionStorage.getItem(y)||"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(b);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=xt();e.removeItem(p),e.removeItem(h)}(),this.batcher?.resetCorrelation())}catch(e){G("Tracker","Failed to send order event:",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:At(e.metadata)}));try{const t=Nt({siteKey:this.siteKey,sessionId:this.sessionId,visitorId:this.visitorId,siteUserId:this.siteUserId,journeyId:Et(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:e});await fetch(`${this.apiUrl}/public/sites/${this.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),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=`${w}_${this.siteKey}`,t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}})}}}var jt=n(664);const Ht=new Map;class Wt{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=>Ht.get(e)||null,setItem:(e,t)=>{Ht.set(e,t)},removeItem:e=>{Ht.delete(e)}}}()}parseInterval(e){if(!(0,jt.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 Kt=null;function Gt(){return Kt||(Kt=new Wt),Kt}function Vt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Jt(e){if(Array.isArray(e))return e.map(e=>Jt(e));if(Vt(e)){const t={};for(const[n,i]of Object.entries(e))t[n]=Jt(i);return t}return e}function Yt(e,t){const n=Jt(e||{});if(!Vt(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]=Jt(i):Vt(i)?Vt(t)?n[e]=Yt(t,i):n[e]=Yt({},i):n[e]=i}return n}function Qt(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 Xt(e){return Vt(e)&&"string"==typeof e.experimentId&&"string"==typeof e.variantId}function Zt(e){if(!e)return null;const t=e.variantConfig??e.config;if(!Vt(t))return null;let n=Yt({},t);const i="search_config"===e.targetType?"search":"recommendation"===e.targetType?"recommendation":void 0;if(i&&Vt(n[i])){const e=n[i];delete n[i],n=Yt(n,e)}return Vt(n.content)&&(n.content=Qt(n.content)),Vt(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)),Vt(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 en{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)Xt(n)&&(t[n.experimentId]=n)};return Array.isArray(e)?(n(e),t):Vt(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,K("Selwise","Experiments initialized:",this.assignments)}}catch(e){J("Selwise","Failed to load experiments:",e)}}loadFromStorage(){try{const e=localStorage.getItem(b);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(b,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=Zt(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 tn={showOnAllPages:!0,includeUrls:[],excludeUrls:[]};function nn(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 on(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 rn(e,t){const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{...tn};const t=e;return{showOnAllPages:Boolean(t.showOnAllPages??tn.showOnAllPages),includeUrls:nn(t.includeUrls),excludeUrls:nn(t.excludeUrls)}}(e),i=String(t||"");if(n.excludeUrls.length>0&&n.excludeUrls.some(e=>on(i,e)))return!1;if(!1===n.showOnAllPages){if(0===n.includeUrls.length)return!1;if(!i)return!1;if(!n.includeUrls.some(e=>on(i,e)))return!1}return!0}class an{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(K("SegmentManager","Evaluating segment targeting:",{mode:e,segmentIds:n,visitorId:this.visitorId,sessionId:this.sessionId}),"all"===e||0===n.length)return K("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(K("SegmentManager","Evaluation results:",{results:i,matchedSegments:o,mode:e}),"include"===e){const e=o.length>0;return K("SegmentManager","Include mode: "+(e?"SHOW":"HIDE")),e}if("exclude"===e){const e=0===o.length;return K("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};K("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 V("SegmentManager","API returned error:",n.status,n.statusText),this.getFallbackResults(e);const i=await n.json();K("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 V("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 sn=[];function cn(e){return!(!e||"string"!=typeof e)&&sn.includes(e)}let ln=!1,dn=null;function un(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 pn(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(un)),e.exception?.values)for(const t of e.exception.values)t.stacktrace?.frames&&(t.stacktrace.frames=hn(t.stacktrace.frames));return e.stacktrace?.frames&&(e.stacktrace.frames=hn(e.stacktrace.frames)),e.tags=e.tags||{},e.tags.widgetVersion="client",e.level||(e.level="error"),e}function hn(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 gn,mn,fn,yn,bn,wn;!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"}(gn||(gn={})),function(e){e[e.BASKET=1]="BASKET",e[e.CUSTOMER=2]="CUSTOMER",e[e.PAYMENT=3]="PAYMENT",e[e.PURCHASE=4]="PURCHASE"}(mn||(mn={})),function(e){e.SIGNUP="signup",e.SIGNIN="signin",e.SIGNOUT="signout",e.UPDATE="update"}(fn||(fn={})),function(e){e.ADD="add",e.REMOVE="remove",e.UPDATE="update"}(yn||(yn={})),function(e){e.KEYWORD="keyword",e.FILTER="filter",e.PAGE="page",e.ORDER="order"}(bn||(bn={})),function(e){e.NECESSARY="necessary",e.ANALYTICS="analytics",e.MARKETING="marketing",e.PREFERENCES="preferences"}(wn||(wn={})),wn.NECESSARY;const Sn="selwise_dl_state",xn="selwise_dl_cart",vn="selwise_dl_cart_time",kn="selwise_dl_last_page",Cn="selwise_dl_page_views",Tn="selwise_dl_session_start",In={HOME:gn.HOME,PRODUCT:gn.PRODUCT,CATEGORY:gn.CATEGORY,SEARCH:gn.SEARCH,CHECKOUT:gn.CHECKOUT,CART:gn.CART,ACCOUNT:gn.ACCOUNT,OTHER:gn.OTHER},En={home:new RegExp(jt.DEFAULT_PAGE_TYPE_PATTERNS.home,"i"),product:new RegExp(jt.DEFAULT_PAGE_TYPE_PATTERNS.product,"i"),category:new RegExp(jt.DEFAULT_PAGE_TYPE_PATTERNS.category,"i"),search:new RegExp(jt.DEFAULT_PAGE_TYPE_PATTERNS.search,"i"),checkout:new RegExp(jt.DEFAULT_PAGE_TYPE_PATTERNS.checkout,"i"),cart:new RegExp(jt.DEFAULT_PAGE_TYPE_PATTERNS.cart,"i"),account:new RegExp(jt.DEFAULT_PAGE_TYPE_PATTERNS.account,"i")},_n="datalayer",Pn=["auto","generic","ideasoft","ikas","ticimax","tsoft","akinon","shopify","woocommerce","magento","prestashop","wix","opencart","bigcommerce","custom","none"],An=['body[class*="product"]','body[class*="item"]','[itemtype*="Product"]','[itemscope][itemtype*="Product"]',".product-single",".product-type-simple",".product-type-variable",".product-info-main",".ProductDetail",".product-detail","[data-product-code]","[data-itemcode]","[data-stock-code]","[data-productid]","[data-ikas-product-id]",".ak-product","body.page-type-product",".productView",'[data-hook="product-page"]',"[data-product-id]"],$n={auto:{id:"auto",dataLayerNames:["dataLayer"],productPageSelectors:[]},generic:{id:"generic",dataLayerNames:["dataLayer"],productPageSelectors:[]},shopify:{id:"shopify",dataLayerNames:["dataLayer","ShopifyAnalytics","shopifyDataLayer"],pageTypePatterns:{product:"\\/products\\/[a-z0-9-]+",category:"\\/collections\\/[a-z0-9-]+",cart:"\\/cart",checkout:"\\/checkouts?\\/|\\/checkout",account:"\\/account",search:"\\/(search|collections\\/all\\?q=)"},productPageSelectors:[".product-template","[data-product-handle]",".shopify-section .product"]},woocommerce:{id:"woocommerce",dataLayerNames:["dataLayer","gtmDataLayer"],pageTypePatterns:{product:"\\/product\\/[a-z0-9-]+",category:"\\/product-category\\/[a-z0-9-]+",cart:"\\/cart",checkout:"\\/checkout",account:"\\/my-account",search:"\\/\\?s="},productPageSelectors:[".single-product",".woocommerce div.product",".product.type-product"]},magento:{id:"magento",dataLayerNames:["dataLayer","digitalData","adobeDataLayer"],pageTypePatterns:{product:"\\/[a-z0-9-]+\\.html$",category:"\\/catalog\\/|\\/c\\/|\\/category\\/",cart:"\\/checkout\\/cart",checkout:"\\/checkout",account:"\\/customer\\/account",search:"\\/catalogsearch\\/|\\/search\\/"},productPageSelectors:[".catalog-product-view","#product_addtocart_form",".product-info-main"]},bigcommerce:{id:"bigcommerce",dataLayerNames:["dataLayer","bcDataLayer"],pageTypePatterns:{product:"\\/products\\/[a-z0-9-]+",category:"\\/categories\\/[a-z0-9-]+",cart:"\\/cart\\.php",checkout:"\\/checkout",account:"\\/account\\.php",search:"\\/search\\.php"},productPageSelectors:["body.page-type-product","[data-product-id]",".productView"]},opencart:{id:"opencart",dataLayerNames:["dataLayer"],pageTypePatterns:{product:"route=product\\/product",category:"route=product\\/category",cart:"route=checkout\\/cart",checkout:"route=checkout\\/checkout",account:"route=account\\/",search:"route=product\\/search"},productPageSelectors:["#product",".product-thumb","[data-product-id]"]},prestashop:{id:"prestashop",dataLayerNames:["dataLayer"],pageTypePatterns:{product:"\\/[a-z]{2}\\/\\d+-",category:"\\/\\d+-",cart:"\\/cart",checkout:"\\/order",account:"\\/my-account",search:"\\/search"},productPageSelectors:["#product",".product-container",".js-product-container"]},akinon:{id:"akinon",dataLayerNames:["dataLayer","akDataLayer"],pageTypePatterns:{product:"\\/(p|urun)\\/",category:"\\/(c|kategori)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(checkout|odeme)",account:"\\/(hesabim|account)",search:"\\/(search|arama)"},productPageSelectors:["[data-product-code]","[data-itemcode]",".product-detail",".ak-product"]},ideasoft:{id:"ideasoft",dataLayerNames:["dataLayer","iDataLayer"],pageTypePatterns:{product:"\\/(urun|product)\\/",category:"\\/(kategori|category)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(odeme|checkout)",account:"\\/(uyelik|account)",search:"\\/(arama|search)"},productPageSelectors:[".ProductDetail","[data-product-id]","[data-product-code]"]},ikas:{id:"ikas",dataLayerNames:["dataLayer","ikasDataLayer"],pageTypePatterns:{product:"\\/(products?|urun)\\/",category:"\\/(categories?|kategori)\\/",cart:"\\/(cart|sepet)",checkout:"\\/(checkout|odeme)",account:"\\/(account|hesabim)",search:"\\/(search|arama)"},productPageSelectors:["[data-ikas-product-id]","[data-product-id]",".product-detail"]},ticimax:{id:"ticimax",dataLayerNames:["dataLayer","ticimaxDataLayer"],pageTypePatterns:{product:"\\/(product|urun)\\/",category:"\\/(category|kategori)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(odeme|checkout)",account:"\\/(uye|account)",search:"\\/(arama|search)"},productPageSelectors:["[data-productid]","[data-product-id]",".productDetail"]},tsoft:{id:"tsoft",dataLayerNames:["dataLayer","tSoftDataLayer"],pageTypePatterns:{product:"\\/(urun|product)\\/",category:"\\/(kategori|category)\\/",cart:"\\/(sepet|cart)",checkout:"\\/(odeme|checkout)",account:"\\/(hesabim|account)",search:"\\/(arama|search)"},productPageSelectors:["[data-product-id]","[data-stock-code]",".product-detail"]},wix:{id:"wix",dataLayerNames:["dataLayer","wixDataLayer"],pageTypePatterns:{product:"\\/product-page\\/",category:"\\/category\\/",cart:"\\/cart",checkout:"\\/checkout",account:"\\/account",search:"\\/search"},productPageSelectors:['[data-hook="product-page"]',"[data-product-id]",".product-page"]},custom:{id:"custom",dataLayerNames:["dataLayer"],productPageSelectors:[]},none:{id:"none",dataLayerNames:["dataLayer"],productPageSelectors:[]}};function Dn(e){const t=function(e){const t="string"==typeof e?e.trim().toLowerCase():"auto";return Pn.includes(t)&&"auto"!==t?t:function(){const e=window,t=(window.location.hostname||"").toLowerCase(),n=(document.body?.className||"").toLowerCase(),i=Array.from(document.querySelectorAll("script[src]")).map(e=>e.src.toLowerCase()).join(" ");return e.Shopify||i.includes("cdn.shopify.com")||t.includes("myshopify.com")?"shopify":e.wc_add_to_cart_params||n.includes("woocommerce")||i.includes("woocommerce")?"woocommerce":e.checkoutConfig||n.includes("catalog-product-view")||i.includes("mage/")?"magento":e.BCData||n.includes("page-type-product")||i.includes("bigcommerce")?"bigcommerce":e.prestashop||i.includes("prestashop")?"prestashop":e.wixBiSession||i.includes("wixstatic")||t.includes("wixsite.com")?"wix":i.includes("opencart")||t.includes("opencart")?"opencart":i.includes("akinon")||e.akinonBasket||n.includes("akinon")?"akinon":i.includes("ideasoft")||t.includes("ideasoft")?"ideasoft":i.includes("ikas")||t.includes("ikas")?"ikas":i.includes("ticimax")||t.includes("ticimax")?"ticimax":i.includes("tsoft")||i.includes("t-soft")||t.includes("tsoft")?"tsoft":"generic"}()}(e);return $n[t]||$n.generic}class Mn{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||En;for(const[n,i]of Object.entries(t))if(("string"==typeof i?new RegExp(i):i).test(e))return n;return this.detectPageTypeFromDom()||In.OTHER}detectPageTypeFromDom(){const e=Dn(this.config.config.platform),t=document.body.className.toLowerCase();if(t.includes("product")||t.includes("item"))return In.PRODUCT;if(t.includes("category")||t.includes("collection")||t.includes("catalog"))return In.CATEGORY;if(t.includes("checkout"))return In.CHECKOUT;if(t.includes("cart")||t.includes("basket"))return In.CART;if(t.includes("account")||t.includes("profile")||t.includes("my-account"))return In.ACCOUNT;if(document.querySelector('[itemtype*="Product"]'))return In.PRODUCT;for(const t of e.productPageSelectors)try{if(document.querySelector(t))return In.PRODUCT}catch{}return null}getPageMetadata(e){const t={dataSource:_n,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===In.PRODUCT){const e=this.extractProductInfoFromDom();e&&(t.productInfo=e)}if(e===In.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(kn,e)}catch{}}getLastPageType(){try{return sessionStorage.getItem(kn)||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:_n,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(Cn)||"0",10)+1;return sessionStorage.setItem(Cn,e.toString()),e}catch{return 1}}getPageViewCount(){try{return parseInt(sessionStorage.getItem(Cn)||"0",10)}catch{return 0}}log(...e){K("PageTracker",...e)}destroy(){this.titleObserver&&(this.titleObserver.disconnect(),this.titleObserver=null)}}class On{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=Dn(this.config.config.platform),t=Array.from(new Set([...An,...e.productPageSelectors])),n=this.config.config.pageTypePatterns;if(n?.product){const e=window.location.pathname+window.location.search;if(n.product.test(e))return!0}for(const e of t)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], [data-product-code], [data-stock-code], [data-itemcode], [data-productid], [data-ikas-product-id]");if(!e)return null;const t=e.getAttribute("data-product-sku")||e.getAttribute("data-product-code")||e.getAttribute("data-itemcode")||e.getAttribute("data-stock-code")||e.getAttribute("data-ikas-product-id")||e.getAttribute("data-item-id")||e.getAttribute("data-productid")||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:_n,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:_n,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:_n,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,o=e.getAttribute("data-product-position")?parseInt(e.getAttribute("data-product-position"),10):void 0;this.trackProductClick({sku:n,title:t,price:i,position:o}),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),K("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=Nt({siteKey:this.config.siteKey,sessionId:this.config.tracker.getSessionId(),visitorId:this.config.tracker.getVisitorId(),siteUserId:this.config.tracker.getSiteUserId?.(),pageUrl:window.location.href,events:[{name:"product_dwell_time",entityType:"product",entityId:this.lastTrackedProduct,productItemCode:this.lastTrackedProduct,metadata:{dwellTimeSeconds:t,dataSource:_n}}]}),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(K("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=Nt({siteKey:this.config.siteKey,sessionId:this.config.tracker.getSessionId(),visitorId:this.config.tracker.getVisitorId(),siteUserId:this.config.tracker.getSiteUserId?.(),pageUrl:window.location.href,events:[{name:"product_dwell_time",entityType:"product",entityId:this.lastTrackedProduct,productItemCode:this.lastTrackedProduct,metadata:{dwellTimeSeconds:t,dataSource:_n}}]}),n=`${this.config.apiUrl}/public/sites/${this.config.siteKey}/events/batch`;K("ProductTracker","Sending dwell time to:",n),K("ProductTracker","Payload:",e),fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}).then(e=>e.json()).then(e=>K("ProductTracker","Dwell time sent successfully:",e)).catch(e=>V("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){K("ProductTracker",...e)}destroy(){this.stopDwellTimeTracking(),this.impressionObserver&&(this.impressionObserver.disconnect(),this.impressionObserver=null),this.trackedProducts.clear()}}const Ln=/^[A-Z]{3}$/;function Nn(e){const t=String(e||"").trim().toUpperCase();return Ln.test(t)?t:"EUR"}class Rn{constructor(e){this.currentCart=null,this.checkInterval=null,this.lastTrackedCartId="",this.config=e}storeCartSnapshot(e){try{sessionStorage.setItem(xn,JSON.stringify(e)),sessionStorage.setItem(vn,Date.now().toString())}catch(e){this.log("Failed to store cart snapshot:",e)}}getStoredCartSnapshot(){try{const e=sessionStorage.getItem(xn),t=sessionStorage.getItem(vn);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(xn),sessionStorage.removeItem(vn)}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:_n,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:_n,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:_n,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:_n,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:Nn(e.currency),timestamp:Date.now(),url:window.location.href}:t,i=this.getBasketProductItemCodes(n.products),o={dataSource:_n,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:Nn(e.currency),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){K("BasketTracker",...e)}destroy(){this.stopCartMonitoring()}}class Bn{constructor(e){this.checkoutState=null,this.checkoutStorageKey=`${Sn}_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:_n,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,c={dataSource:_n,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:c}),this.log("Tracked checkout_progress:",t,c)}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:_n,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:_n,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(xn),sessionStorage.removeItem(vn)}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){K("CheckoutTracker",...e)}destroy(){this.clearCheckoutState()}}class zn{constructor(e){this.userState=null,this.userStorageKey=`${Sn}_user`,this.config=e,this.sessionStartTime=Date.now(),this.loadUserState(),this.initSessionStart()}initSessionStart(){try{const e=sessionStorage.getItem(Tn);e?this.sessionStartTime=parseInt(e,10):sessionStorage.setItem(Tn,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:_n,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:_n,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:_n,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(Tn,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:_n,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){K("UserTracker",...e)}destroy(){}}class Un{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:_n,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:_n,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:_n,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:_n,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:_n,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:_n,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:_n,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){K("SearchTracker",...e)}destroy(){this.clearSearchState()}}class Fn{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(Array.isArray(t[e]))return t[e];if(t[e]&&!Array.isArray(t[e]))return this.log(`Warning: window.${e} exists but is not an array, resetting`),t[e]=[],t[e];const n=this.detectExistingDataLayerName(t);return n?(this.config.dataLayerName=n,this.log(`Detected external dataLayer source: window.${n}`),t[n]):(t[e]=[],this.log(`Initialized empty window.${e} array`),t[e])}detectExistingDataLayerName(e){const t=[...Array.isArray(this.config.preferredDataLayerNames)?this.config.preferredDataLayerNames.filter(e=>"string"==typeof e&&e.trim().length>0):[],"dataLayer","googleDataLayer","gtmDataLayer","analyticsDataLayer"];for(const n of t)if(Array.isArray(e[n]))return n;const n=Object.entries(e);for(const[e,t]of n)if(Array.isArray(t)&&0!==t.length&&t.some(e=>!!e&&(Array.isArray(e)?"event"===e[0]&&"string"==typeof e[1]:"object"==typeof e&&"string"==typeof e.event)))return e;return null}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){const n=this.normalizeDataLayerItem(e);if(!n)return;const i=n.event||null;if(!i&&("consent"===n[0]||n.gtm?.start||"gtm.js"===n.event))return;if(this.config.hasConsent&&!this.config.hasConsent())return void this.log(`Skipping mapped event due to consent: ${i}`);if(!i||this.isInternalEvent(i,n))return;const o=this.getMappedEvent(i);if(!o)return;const r=this.createEventId(n,t);if(this.processedEvents.has(r))return;this.processedEvents.add(r);const a=this.extractEventData(n);this.trackMappedEvent(o,i,a)}normalizeDataLayerItem(e){return e?Array.isArray(e)?this.parseArrayDataLayerItem(e):"object"==typeof e?e:null:null}parseArrayDataLayerItem(e){if(e.length<2)return null;const[t,n,i]=e;if("string"!=typeof t)return null;if("event"!==t)return null;if("string"!=typeof n||0===n.trim().length)return null;const o=n.trim(),r=i&&"object"==typeof i&&!Array.isArray(i)?i:{},a={event:o,...r},s=r.ecommerce&&"object"==typeof r.ecommerce?r.ecommerce:null;if(s)a.ecommerce=s;else{const e=[r.items,r.products,r.item_list].find(e=>Array.isArray(e));(e||r.currency||r.value||r.transaction_id)&&(a.ecommerce={items:Array.isArray(e)?e:void 0,currency:r.currency,value:r.value,transaction_id:r.transaction_id,coupon:r.coupon})}return a}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",dataSource:_n,originalEvent:e.event,externalDataLayerName:this.config.dataLayerName||"dataLayer",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)),"string"==typeof e.transaction_id&&(t.transactionId=e.transaction_id),"string"==typeof e.currency&&(t.currency=e.currency),"number"==typeof e.value&&(t.value=e.value),"string"==typeof e.search_term&&(t.searchTerm=e.search_term),Array.isArray(e.items)&&(t.products=e.items);const n=this.pickFirstString([e.page_path,e.pagePath,e.path,e.pathname,e.url_path]);n&&(t.pagePath=n);const i=this.pickFirstString([e.page_url,e.pageUrl,e.url,e.location]);i&&(t.pageUrl=i);const o=this.pickFirstString([e.category_path,e.categoryPath,e.category_hierarchy,e.categoryHierarchy,e.page_category_path,e.pageCategoryPath,e.google_tag_params?.item_list_id,e.google_tag_params?.item_list_name]);o&&(t.categoryPath=o);const r=this.pickFirstString([e.category_name,e.categoryName,e.category,e.page_category_name,e.pageCategoryName,e.google_tag_params?.item_category,e.google_tag_params?.item_list_name]);r&&(t.categoryName=r);const a=this.normalizeCategoryList(e.categories||e.page_categories||e.category_list||e.google_tag_params?.item_category2);a.length>0&&(t.categories=a);for(const n of Object.keys(e))(n.startsWith("cd_")||n.startsWith("dimension"))&&(t[n]=e[n]);return t}extractEcommerceData(e){const t={};return Array.isArray(e.items)&&(t.items=e.items,t.products=e.items,t.currency=e.currency,t.value=e.value,t.transactionId=e.transaction_id||e.transactionId),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){const n=e.gtm?.uniqueEventId||e.eventId||e.transaction_id||e.transactionId||`${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return[e.event,n,t?"existing":"new"].join(":")}trackMappedEvent(e,t,n){this.log(`Mapping event: ${t} -> ${e}`);const{entityType:i,entityId:o}=this.determineEntityContext(e,n),r=this.resolveProductItemCode(n);this.config.tracker.track(e,{entityType:i,entityId:o,metadata:{...n,dataSource:_n,mappedFrom:t,productItemCode:r,sessionId:this.config.tracker.getSessionId(),visitorId:this.config.tracker.getVisitorId()}})}determineEntityContext(e,t){const n={page_view:"page",category_view:"category",product_view:"product",add_to_cart:"basket",remove_from_cart:"basket",purchase:"checkout",checkout_begin:"checkout",checkout_progress:"checkout",search:"search",search_query:"search",user_login:"user",user_logout:"user"}[e]||"custom";let i;return"category"===n?(i=this.resolveCategoryPath(t)||this.resolveCategoryName(t),{entityType:n,entityId:i}):(t.vl_ecommerce?.detail?.product?.id?i=t.vl_ecommerce.detail.product.id:t.ecommerce?.products?.[0]?.id||t.ecommerce?.products?.[0]?.item_id?i=t.ecommerce.products[0].id||t.ecommerce.products[0].item_id:t.ecommerce?.items?.[0]?.item_id||t.ecommerce?.items?.[0]?.sku?i=t.ecommerce.items[0].item_id||t.ecommerce.items[0].sku:(t.products?.[0]?.id||t.products?.[0]?.item_id||t.products?.[0]?.sku)&&(i=t.products[0].id||t.products[0].item_id||t.products[0].sku),"checkout"===n&&(i=t.ecommerce?.purchase?.actionField?.id||t.ecommerce?.transactionId||t.transactionId||i),{entityType:n,entityId:i})}resolveProductItemCode(e){const t=[e.productItemCode,e.product?.sku,e.product?.id,e.ecommerce?.items?.[0]?.item_id,e.ecommerce?.items?.[0]?.sku,e.ecommerce?.items?.[0]?.id,e.ecommerce?.products?.[0]?.item_id,e.ecommerce?.products?.[0]?.sku,e.ecommerce?.products?.[0]?.id,e.products?.[0]?.item_id,e.products?.[0]?.sku,e.products?.[0]?.id,e.vl_ecommerce?.detail?.product?.id,e.vl_ecommerce?.detail?.product?.sku,e.googleTagParams?.id,e.googleTagParams?.item_id,e.googleTagParams?.sku];for(const e of t)if("string"==typeof e&&e.trim().length>0)return e.trim()}resolveCategoryPath(e){const t=[e.categoryPath,e.category_path,e.categoryHierarchy,e.category_hierarchy,e.pagePath,e.path,e.pageUrl,e.url,e.googleTagParams?.item_list_id];for(const e of t){if("string"!=typeof e)continue;let t=e.trim();if(t){if(/^https?:\/\//i.test(t))try{t=new URL(t).pathname||t}catch{}if(t=t.replace(/[?#].*$/,"").trim(),this.isMeaningfulCategoryValue(t))return t}}const n=this.normalizeCategoryList(e.categories);if(n.length>0)return n.join(" > ")}resolveCategoryName(e){const t=[e.categoryName,e.category_name,e.category,e.googleTagParams?.item_category,e.ecommerce?.items?.[0]?.item_category,e.ecommerce?.products?.[0]?.category,e.products?.[0]?.item_category,e.products?.[0]?.category];for(const e of t){if("string"!=typeof e)continue;const t=e.trim();if(this.isMeaningfulCategoryValue(t))return t}const n=this.resolveCategoryPath(e);if(!n)return;const i=n.split(/[>/]/g).map(e=>e.trim()).filter(Boolean).pop();if(!i)return;const o=i.replace(/[-_]+/g," ").trim();return this.isMeaningfulCategoryValue(o)?o:void 0}pickFirstString(e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t.trim()}normalizeCategoryList(e){return(Array.isArray(e)?e:[e]).filter(e=>"string"==typeof e).map(e=>e.trim()).filter(e=>this.isMeaningfulCategoryValue(e))}isMeaningfulCategoryValue(e){const t=e.trim().toLowerCase();return t.length>0&&"unknown"!==t&&"null"!==t&&"undefined"!==t}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){K("ExternalDataLayerListener",...e)}}class qn{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 c=this.getBasketProductItemCodes(e.products),l={dataSource:_n,pageUrl:window.location.href,referrer:document.referrer,timestamp:Date.now(),productName:o.title,productItemCode:r,productItemCodes:c,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:l}),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){K("CartAssociationTracker",...e)}}const jn=new Map;class Hn{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",this.platformProfile=Dn(i.platform);const o=this.normalizeTrackingModules(i.trackingModules),r=this.normalizePageTypePatterns(i.pageTypePatterns,this.platformProfile.pageTypePatterns);this.config={enabled:i.enabled??!0,variableName:i.variableName,platform:this.platformProfile.id,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,useExternalDataLayer:i.useExternalDataLayer??!0,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:{...jt.TRACKING_MODULES.page,...e?.page||{}},product:{...jt.TRACKING_MODULES.product,...e?.product||{}},basket:{...jt.TRACKING_MODULES.basket,...e?.basket||{}},checkout:{...jt.TRACKING_MODULES.checkout,...e?.checkout||{}},user:{...jt.TRACKING_MODULES.user,...e?.user||{}},search:{...jt.TRACKING_MODULES.search,...e?.search||{}}}}normalizePageTypePatterns(e,t){const n={...Object.fromEntries(Object.entries(En).map(([e,t])=>[e,t.source]))};if(t)for(const[e,i]of Object.entries(t))"string"==typeof i&&i.trim().length>0&&(n[e]=i);if(e)for(const[t,i]of Object.entries(e))(i instanceof RegExp||"string"==typeof i&&i.trim().length>0)&&(n[t]=i);const i={};for(const[e,t]of Object.entries(n))if(t instanceof RegExp)i[e]=t;else if("string"==typeof t&&t.trim().length>0)try{i[e]=new RegExp(t,"i")}catch{this.log(`Invalid regex for page type "${e}", using default pattern`),i[e]=En[e]||En.home}return Object.keys(i).length>0?i:{...En}}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){V("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()&&jn.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 Mn(e),this.log("Page tracker enabled")),this.isModuleEnabled("product")&&(this.productTracker=new On(e),this.log("Product tracker enabled")),this.isModuleEnabled("basket")&&(this.basketTracker=new Rn(e),this.log("Basket tracker enabled")),this.isModuleEnabled("checkout")&&(this.checkoutTracker=new Bn(e),this.log("Checkout tracker enabled")),this.isModuleEnabled("user")&&(this.userTracker=new zn(e),this.log("User tracker enabled")),this.isModuleEnabled("search")&&(this.searchTracker=new Un(e),this.log("Search tracker enabled")),this.isModuleEnabled("basket")&&(this.cartAssociationTracker=new qn(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(){if(!1===this.config.useExternalDataLayer)return void this.log("External dataLayer listening disabled by config");const e=this.config.reverseEventMapping,t=this.config.externalDataLayerName||this.platformProfile.dataLayerNames[0]||"dataLayer";if(e&&0!==Object.keys(e).length)try{this.externalListener=new Fn({tracker:this.tracker,reverseMapping:e,dataLayerName:t,preferredDataLayerNames:this.platformProfile.dataLayerNames,debugMode:this.config.debugMode,enabled:!0,hasConsent:()=>this.hasConsent()}),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=jn.get(t)||0,i=Date.now();return i-n<1e3||(jn.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:_n,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.platform&&(this.config.platform=e.platform,this.platformProfile=Dn(e.platform),this.config.pageTypePatterns=this.normalizePageTypePatterns(this.config.pageTypePatterns,this.platformProfile.pageTypePatterns)),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,this.platformProfile.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.useExternalDataLayer&&(this.config.useExternalDataLayer=e.useExternalDataLayer),void 0!==e.externalDataLayerName&&(this.config.externalDataLayerName=e.externalDataLayerName),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){K("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(),jn.clear(),this.eventBuffer=[],this.isDestroyed=!0,this.isInitialized=!1,this.log("DataLayerManager destroyed")}}function Wn(e,t,n){const i="string"==typeof t?n||{}:t||{},o="string"==typeof t?t:i.currencyCode||i.currency,r=parseInt(i.priceDecimals||"2",10),a=i.locale||void 0;return new Intl.NumberFormat(a,{style:"currency",currency:Nn(o),minimumFractionDigits:r,maximumFractionDigits:r}).format(Number(e||0))}function Kn(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function Gn(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 Vn(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 Jn(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 Yn(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 Qn="ws_recent_searches";function Xn(e=5,t){try{const n=localStorage.getItem(`${Qn}_${t}`);if(!n)return[];const i=JSON.parse(n);return Array.isArray(i)?i.slice(0,e):[]}catch{return[]}}var Zn=n(561);const ei=new Set(["all","include","exclude"]);function ti(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const ni=new Set(["standard","expanded_query","redirect","disabled","service_unavailable","validation_error","error"]);async function ii(e,t,n,i,o){const r=Nt({siteKey:e.siteKey,sessionId:t,visitorId:n,siteUserId:i,pageUrl:window.location.href,referrer:document.referrer||void 0,events:o});await fetch(`${e.apiUrl}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}async function oi(e,t,n,i,o,r,a,s){try{sessionStorage.setItem(y,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 ri(e){for(const t of e)try{const e=document.querySelector(t);if(e)return e}catch{}return null}async function ai(e,t){const n=e.itemCode||e.id,i=t?.formSelectors||[],o=ri([...t?.buttonSelectors||[],`[data-product-id="${n}"] .add-to-cart`,`[data-itemcode="${n}"] .add-to-cart`,`[data-productid="${n}"]`,`[data-stock-code="${n}"]`]);if(o)return void o.click();const r=ri(i);if(!r)return;const a=r.querySelector('input[name="quantity"]')||r.querySelector('input[name="qty"]');a&&!a.value&&(a.value="1");const s=r.querySelector('input[name="product_id"]')||r.querySelector('input[name="productid"]')||r.querySelector('input[name="id"]');s&&!s.value&&(s.value=n),"function"==typeof r.requestSubmit?r.requestSubmit():r.submit()}function si(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}function ci(e,t,n){switch(t){case"ideasoft":return function(e){return ai(e,{formSelectors:['form[action*="Sepet"]','form[action*="cart"]'],buttonSelectors:[".btnSepeteEkle",'[onclick*="Sepete"]',".add-to-cart"]})}(e);case"ikas":return function(e){return ai(e,{formSelectors:['form[action*="cart"]','form[action*="sepet"]'],buttonSelectors:["[data-ikas-product-id]","[data-product-id]",".add-to-cart"]})}(e);case"ticimax":return function(e){return ai(e,{formSelectors:['form[action*="Sepet"]','form[action*="cart"]'],buttonSelectors:[".btnAddCart","[data-productid]","[data-product-id]"]})}(e);case"tsoft":return function(e){return ai(e,{formSelectors:['form[action*="sepet"]','form[action*="cart"]'],buttonSelectors:["[data-stock-code]","[data-product-id]",".add-to-cart"]})}(e);case"wix":return async function(e){const t=window.wixStores;if(t?.cart?.addProducts&&"function"==typeof t.cart.addProducts)try{return void await t.cart.addProducts([{productId:e.id,quantity:1}])}catch(e){console.error("[Cart] Wix SDK add to cart error:",e)}await ai(e,{formSelectors:['form[action*="cart"]','form[data-hook="product-form"]'],buttonSelectors:['[data-hook="add-to-cart"]',".add-to-cart"]})}(e);case"bigcommerce":return async function(e){const t=window.utils?.api?.cart;t?.itemAdd?await new Promise(n=>{t.itemAdd({product_id:e.id,qty:1},()=>n())}):await ai(e,{formSelectors:['form[action*="cart.php"]',"form[data-cart-item-add]"],buttonSelectors:["[data-cart-item-add]",'[data-button-type="add-cart"]']})}(e);case"opencart":return function(e){const t=e.id;return fetch("/index.php?route=checkout/cart/add",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},body:`product_id=${encodeURIComponent(t)}&quantity=1`}).then(e=>e.json()).then(()=>{document.dispatchEvent(new CustomEvent("cart:updated"))}).catch(e=>{console.error("[Cart] OpenCart add to cart error:",e)})}(e);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_api":case"custom":return si(e,n?.customScript);default:return}}function li(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 di(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 ui(e,t){if(!e.selector)return null;const n=()=>{const t=document.querySelector(e.selector);if(t){const n=di(e,{showSearchIcon:!0,showCloseIcon:!0,getSearchIcon:Jn,getCloseIcon:Yn}),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 pi(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=di(e,{showSearchIcon:!0,showCloseIcon:!0,getSearchIcon:Jn,getCloseIcon:Yn}),s=a.querySelector(".ws-search-input"),c=a.querySelector(".ws-search-results");return r.appendChild(a),o.appendChild(r),document.body.appendChild(o),{container:a,input:s,resultsContainer:c,overlayElement:o}}const hi="data-selwise-action",gi="data-product-id",mi="add-to-cart";function fi(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,e.currency),oldPrice:e.originalPrice,formattedOldPrice:e.originalPrice?n.formatPrice(e.originalPrice,e.currency):"",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:`${hi}="${mi}" ${gi}="${o}"`};return Object.entries(r).forEach(([e,t])=>{const n=null!=t?t:"";i=i.replace(new RegExp(`\\$\\{${e}\\}`,"g"),String(n))}),et(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",c=t.imageSize||"cover";let l="";t.showBadges&&(e.isNew&&(l+='<span class="selwise-badge selwise-badge-new">New</span>'),e.isSale&&(l+='<span class="selwise-badge selwise-badge-sale">Sale</span>'),e.isBestseller&&(l+='<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="${yi(e.title)}" loading="lazy" style="width:100%;height:100%;object-fit:${c};" />\n </a>\n ${l?`<div class="selwise-badges">${l}</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":""}">${yi(String(r))}</div>`;break;case"price":p+=`<div class="selwise-card-price">${n.formatPrice(e.price,e.currency)}</div>`;break;case"old_price":e.originalPrice&&(p+=`<div class="selwise-card-old-price">${n.formatPrice(e.originalPrice,e.currency)}</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",c=t.buttonStyle?.color||"#fff";p+=`\n <button class="selwise-card-button" \n ${hi}="${mi}" \n ${gi}="${i}"\n style="width:100%;margin-top:auto;padding:8px;background:${s};color:${c};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 ${hi}="${mi}" \n ${gi}="${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="${yi(e.title)}" loading="lazy" />\n </div>\n <div class="selwise-card-content">\n <h3 class="selwise-card-title">${yi(e.title)}</h3>\n <div class="selwise-card-price-row">\n ${n?`<span class="selwise-price-original">${t.formatPrice(e.originalPrice,e.currency)}</span>`:""}\n <span class="selwise-price-current">${t.formatPrice(e.price,e.currency)}</span>\n </div>\n </div>\n </div>\n `}(e,n)}function yi(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):""}function bi(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 wi=new Map;function Si(e,t,n){const{config:i,selectedCategory:o,formatPrice:r,formatCategoryName:a}=t,s=i,c=s.styles||{};if(0===e.hits.length)return"";let l="",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&&(l+=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="${Kn(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>${Kn(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&&(l+=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="${Kn(e.name)}">\n ${Kn(i(e.name))}${n.categoryShowCount?` (${e.count})`:""}\n </button>`}),r+="</div>",r}(d,o,s,a)),"dropdown"===s.categoryDisplayMode&&d.length&&(l+=function(e,t,n,i,o){const r=i.styles||{};let a=`<div class="ws-search-category-dropdown" style="padding:8px 12px;border-bottom:1px solid ${r.borderColor||"#e5e7eb"};">\n <select class="ws-search-cat-select" style="\n width:${r.dropdownWidth||"100%"};\n padding:8px 12px;\n border:1px solid ${r.borderColor||"#d1d5db"};\n border-radius:${r.inputRadius||"6px"};\n background:${r.dropdownBg||r.inputBg||"#fff"};\n color:${r.textColor||"#374151"};\n font-size:14px;\n cursor:pointer;\n outline:none;\n ">\n <option value="">${r.textAll||"All"} ${r.textCategories||"Categories"} (${t})</option>`;return e.slice(0,i.categoryMaxVisible).forEach(e=>{a+=`\n <option value="${Kn(e.name)}" ${n===e.name?"selected":""}>\n ${Kn(o(e.name))}${i.categoryShowCount?` (${e.count})`:""}\n </option>`}),a+="</select></div>",a}(d,e.total,o,s,a)),l+='<div class="ws-search-items">',l+=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,currency:Nn(e.currency),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},c=fi(a,s,{source:"search",formatPrice:i.formatPrice});return o&&s.customJs&&(wi.has(o)||wi.set(o,[]),wi.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 ${c}\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),c=e.imageUrl||"",l=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 ${hi}="${mi}"\n ${gi}="${l}"\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="${l}"${e.boostReason?` data-boost-reason="${e.boostReason}"`:""}>\n ${t.showImages&&c?`\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="${c}" 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,e.currency)}</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,e.currency)}</span>\n ${t.showOldPrice&&e.originalPrice&&e.originalPrice>e.price?`<span class="ws-search-old-price">${i.formatPrice(e.originalPrice,e.currency)}</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:Kn,formatCategoryName:a},n)).join(""),l+="</div>",l+=`<div class="ws-search-footer">${Kn((c.textFooter||"{total} products found in {time}ms").replace("{total}",String(e.total)).replace("{time}",String(e.took)))}</div>`,"sidebar"===s.categoryDisplayMode&&d.length&&(l+="</div></div>"),l}class xi{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=Tt,this.generateEventId=_t,this.apiUrl=e,this.siteKey=t,this.sessionId=kt(),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 K("WidgetSearch","Search excluded by experiment (different_module mode - variant available)"),null;if(e&&"different_module"!==e.experimentMode){const n=Zt(e);n&&(K("WidgetSearch","Applying experiment override:",e.variantName),i=Yt(i,n),t.trackImpression(e.experimentId))}}K("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?function(e){const t={...e},n=(0,Zn.sanitizeSuggestionStyles)(t.suggestionStyles),i=function(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}(t.segmentIds),o=t.segmentTargetingMode,r="string"==typeof o&&ei.has(o)?o:"all",a=!0===t.isTestMode||!0===t.testMode;return t.styles=(0,Zn.sanitizeSearchStyles)(t.styles),t.suggestionStyles=n,t.isTestMode=a,t.testMode=a,t.addToCartEnabled=!1!==t.addToCartEnabled,t.cartPlatform=function(e){if("string"!=typeof e)return"custom";const t=e.trim();return t.length>0?t:"custom"}(t.cartPlatform),t.addToCartConfig=t.addToCartConfig&&"object"==typeof t.addToCartConfig&&!Array.isArray(t.addToCartConfig)?t.addToCartConfig:{},t.customCartScript=function(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}(t.customCartScript),t.segmentIds=i,t.segmentTargetingMode="all"!==r&&0===i.length?"all":r,t}(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(!0===this.config.isTestMode||!0===this.config.testMode){if("undefined"==typeof localStorage||"true"!==localStorage.getItem(g))return void G("WidgetSearch",`Search is in test mode. Run localStorage.setItem('${g}', '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)),K("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: ${Vn(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: ${Vn(i.itemShadow||"sm")};\n }\n .ws-search-results.layout-grid .ws-search-item:hover {\n box-shadow: ${Vn(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: ${Vn(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: ${Vn(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){V("WidgetSearch","Failed to initialize:",e)}}getSuggestionStyles(){return this.suggestions?.styles||{}}setupSpaNavigationWatcher(){K("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,K("WidgetSearch","Inline container was removed")),!this.container&&this.config?.selector)&&document.querySelector(this.config.selector)){K("WidgetSearch","Re-rendering inline search");const e=ui(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}),K("WidgetSearch","Re-attached trigger listener to:",t);const o=document.querySelector(".ws-search-floating-btn:not(.ws-embedded)");o&&(o.remove(),K("WidgetSearch","Removed fallback floating button"))}})}});t.observe(document.body,{childList:!0,subtree:!0}),this.spaObserver=t,K("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 K("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,Jn)};let t;switch(this.config.position){case"inline":t=ui(this.config,()=>this.attachEventListeners());break;case"modal":t=pi(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e);break;case"floating":t=function(e,t,n,i){return pi(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 c=di(e,{showSearchIcon:!1,showCloseIcon:!0,getSearchIcon:Jn,getCloseIcon:Yn}),l=c.querySelector(".ws-search-input"),d=c.querySelector(".ws-search-results");return a.appendChild(c),r.appendChild(a),document.body.appendChild(r),{container:c,input:l,resultsContainer:d,overlayElement:r}}(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e,Yn);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=di(e,{showSearchIcon:!0,showCloseIcon:!1,getSearchIcon:Jn,getCloseIcon:Yn}),c=s.querySelector(".ws-search-input"),l=s.querySelector(".ws-search-results");return a.appendChild(s),r.appendChild(a),document.body.appendChild(r),{container:s,input:c,resultsContainer:l,overlayElement:r}}(this.config,()=>this.openOverlay(),()=>this.closeOverlay(),e,Yn);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 function(e){if(!ti(e))throw new Error("Invalid search response: expected object payload");if(!Array.isArray(e.hits))throw new Error("Invalid search response: hits must be an array");if("number"!=typeof e.total)throw new Error("Invalid search response: total must be a number");if("number"!=typeof e.took)throw new Error("Invalid search response: took must be a number");if("boolean"!=typeof e.enabled)throw new Error("Invalid search response: enabled must be a boolean");if("string"!=typeof e.strategy||!ni.has(e.strategy))throw new Error("Invalid search response: strategy is missing or unsupported");if(!ti(e.debugMeta))throw new Error("Invalid search response: debugMeta must be an object");if("string"!=typeof e.traceId||0===e.traceId.trim().length)throw new Error("Invalid search response: traceId is required");return{hits:e.hits,total:e.total,took:e.took,enabled:e.enabled,...Array.isArray(e.categories)?{categories:e.categories}:{},..."string"==typeof e.redirect?{redirect:e.redirect}:{},...Array.isArray(e.suggestions)?{suggestions:e.suggestions}:{},...Array.isArray(e.expandedQuery)?{expandedQuery:e.expandedQuery}:{},strategy:e.strategy,debugMeta:e.debugMeta,traceId:e.traceId}}(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=Xn(t,n);i=i.filter(t=>t.toLowerCase()!==e.toLowerCase()),i.unshift(e),i=i.slice(0,t),localStorage.setItem(`${Qn}_${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;V("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",e.suggestions);const t=`search-results-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,n=Si(e,{config:this.config,selectedCategory:this.selectedCategory,formatPrice:(e,t)=>Wn(e,t,this.config?.styles),formatCategoryName:e=>this.formatCategoryName(e)},t);this.resultsContainer.innerHTML=Ze(n),this.config.productCard?.customJs&&function(e,t){const n=wi.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,t)=>`${e} ${t}`};bi(n,e.template,e.unifiedProduct,t)}}),wi.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&&oi(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 ii(e,i,o,r,[{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=li(o,{loading:"Adding...",success:"Added!",error:"Error",default:"Add to Cart"});ci(i,t.cartPlatform,{buttonState:r})}else ci(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){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,e.currency)}</span>\n ${t?`<span class="ws-product-card-old-price">${i.formatPrice(e.originalPrice,e.currency)}</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,Xn(5,this.siteKey),{formatPrice:(e,t)=>Wn(e,t,this.config?.styles),escapeHtml:Kn,formatCategoryName:Gn});e&&(this.resultsContainer.innerHTML=Ze(e),this.attachSuggestionListeners(),this.openResults())}attachSuggestionListeners(){this.resultsContainer&&(this.resultsContainer.querySelector(".ws-clear-recent")?.addEventListener("click",e=>{e.stopPropagation(),function(e){try{localStorage.removeItem(`${Qn}_${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=Xn(5,t);n=n.filter(t=>t.toLowerCase()!==e.toLowerCase()),localStorage.setItem(`${Qn}_${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 ii(e,n,i,o,[{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 ii(e,n,i,o,[{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 ii(e,n,i,o,[{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 ii(e,n,i,o,[{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()),oi(this.getAPIConfig(),t,this.sessionId,this.getOrCreateVisitorId(),this.getStoredSiteUserId(),this.generateEventId()))})}))}showLoading(){if(!this.resultsContainer)return;const e=Kn(this.config?.styles?.textLoading||"Searching...");this.resultsContainer.innerHTML=Ze(`\n <div class="ws-search-loading">\n <div class="ws-search-spinner"></div>\n <span>${e}</span>\n </div>\n `),this.openResults()}showEmpty(e,t=[]){if(!this.resultsContainer)return;const n=Kn(e),i=t.filter(e=>e.trim().length>0).slice(0,4).map(e=>Kn(e)),o=i.length>0?`\n <div class="ws-empty-suggestions" style="margin-top:12px;">\n <p style="font-size:12px;opacity:0.8;margin-bottom:8px;">Did you mean?</p>\n <div style="display:flex;flex-wrap:wrap;gap:8px;justify-content:center;">\n ${i.map(e=>`\n <button\n type="button"\n data-suggestion-query="${e}"\n style="\n padding:6px 10px;\n border-radius:999px;\n border:1px solid rgba(148,163,184,0.45);\n background:rgba(255,255,255,0.04);\n font-size:12px;\n cursor:pointer;\n "\n >${e}</button>\n `).join("")}\n </div>\n </div>\n `:"";this.resultsContainer.innerHTML=Ze(`\n <div class="ws-search-empty">\n ${Jn("",48)}\n <p style="margin-top:12px;">${n}</p>\n ${o}\n </div>\n `),this.resultsContainer.querySelectorAll("[data-suggestion-query]").forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.suggestionQuery;t&&(this.input&&(this.input.value=t),this.search(t))})}),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 ii(e,n,i,o,[{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 ii(e,o,r,a,[{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 vi=n(126);function ki(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ci(e){if(!ki(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=(n=e.reasonCodes,Array.isArray(n)?n.map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0):null);var n;const i=function(e){if(!ki(e))return null;const{isActive:t,pageTargetingConfigured:n,segmentTargetingRequired:i,containerSelectorRequired:o,testModeOnly:r,...a}=e;if("boolean"!=typeof t||"boolean"!=typeof n||"boolean"!=typeof i||"boolean"!=typeof o||"boolean"!=typeof r)return null;const s={};for(const[e,t]of Object.entries(a)){if("boolean"!=typeof t)return null;s[e]=t}return{isActive:t,pageTargetingConfigured:n,segmentTargetingRequired:i,containerSelectorRequired:o,testModeOnly:r,...s}}(e.eligibilityFlags);if(!t||!i)return null;const o={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,vi.validateRecommendationConfig)(o).valid)return null;const r=(0,vi.sanitizeRecommendationConfig)(o),a={showOnAllPages:r.showOnAllPages,includeUrls:r.includeUrls,excludeUrls:r.excludeUrls,containerSelector:r.containerSelector,insertPosition:r.insertPosition};return{id:e.id,name:e.name,isTestMode:"boolean"==typeof e.isTestMode?e.isTestMode:"boolean"==typeof e.testMode&&e.testMode,strategy:r.strategy,displayType:r.displayType,title:r.title,subtitle:r.subtitle,maxProducts:r.maxProducts,slidesPerView:r.slidesPerView,slidesPerViewMobile:r.slidesPerViewMobile,slidesPerViewTablet:r.slidesPerViewTablet,slideGap:r.slideGap,autoplay:r.autoplay,autoplaySpeed:r.autoplaySpeed,loop:r.loop,pauseOnHover:r.pauseOnHover,arrowStyles:r.arrowStyles,dotStyles:r.dotStyles,titleStyles:r.titleStyles,subtitleStyles:r.subtitleStyles,containerStyles:r.containerStyles,containerSelector:r.containerSelector,insertPosition:r.insertPosition,addToCartEnabled:r.addToCartEnabled,cartPlatform:r.cartPlatform,addToCartConfig:r.addToCartConfig,cartButtonText:"string"==typeof r.addToCartConfig?.buttonText?r.addToCartConfig.buttonText:void 0,customCartScript:"string"==typeof e.customCartScript?e.customCartScript:"string"==typeof r.addToCartConfig?.customScript?r.addToCartConfig.customScript:void 0,customCSS:"string"==typeof e.customCSS?e.customCSS:void 0,customJS:"string"==typeof e.customJS?e.customJS:void 0,productCard:ki(e.productCard)?e.productCard:void 0,pageTargetingJson:a,segmentTargetingMode:"include"===e.segmentTargetingMode||"exclude"===e.segmentTargetingMode?e.segmentTargetingMode:"all",segmentIds:Array.isArray(e.segmentIds)?e.segmentIds.filter(e=>"string"==typeof e):[],reasonCodes:t,eligibilityFlags:i}}const Ti="data-selwise-recommendation",Ii=`[${Ti}="true"]`;function Ei(e){return!!document.getElementById(`rec-widget-${e}`)}function _i(e,t){return new Intl.NumberFormat(void 0,{style:"currency",currency:Nn(t)}).format(e)}const Pi=new Map;function Ai(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,currency:Nn(e.currency),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:_i};return n&&o.customJs&&(Pi.has(n)||Pi.set(n,[]),Pi.get(n).push({template:o,unifiedProduct:i,productItemCode:e.itemCode||e.id})),fi(i,o,r)}(e,t.productCard,a):s.innerHTML=et(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 ${hi}="${mi}"\n ${gi}="${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">${_i(e.originalPrice,e.currency)}</span>`:""}\n <span class="recommendation-price-current">${_i(e.price,e.currency)}</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 c=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(`[${hi}="${mi}"]`)?(a.preventDefault(),void i(e,t,n,o,r)):c?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}const $i=new Map;function Di(e){const t=window.innerWidth;return t<640?e.slidesPerViewMobile||1:t<1024?e.slidesPerViewTablet||2:e.slidesPerView||4}function Mi(e,t){const n=t.querySelector(".recommendation-slider-track");if(!n)return;const i=Di(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=$i.get(e.id);a&&(a.slidesPerView=i)}function Oi(e,t,n){const i=$i.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),Li(e,t),Ni(t,i.currentIndex,e)}function Li(e,t){const n=$i.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 Ni(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 Ri(e,t){const n=$i.get(e.id);n&&(Bi(e),n.autoplayInterval=setInterval(()=>{Oi(e,t,"next")},e.autoplaySpeed))}function Bi(e){const t=$i.get(e.id);t?.autoplayInterval&&(clearInterval(t.autoplayInterval),t.autoplayInterval=void 0)}function zi(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";ci(a,s,"akinon"===s?{buttonState:li(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 Ui=!1;function Fi(){try{{const e=kt();if(e&&"string"==typeof e)return e}}catch(e){Ui||(Ui=!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 qi(e,t){const n=Nt({siteKey:e.siteKey,sessionId:Fi(),visitorId:Ct(),siteUserId:Tt(),pageUrl:window.location.href,referrer:document.referrer||void 0,events:t});await fetch(`${e.apiEndpoint}/public/sites/${e.siteKey}/events/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async function ji(e,t,n,i){try{const o="string"==typeof n&&n.trim().length>0?n.trim():null;if("click"===e)try{sessionStorage.setItem(f,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:Fi(),visitorId:Ct(),userId:Tt(),pageUrl:window.location.href,eventId:_t(),metadata:{referrer:document.referrer||void 0}})})}catch(e){console.error("[Recommendation] Error tracking event:",e)}}async function Hi(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:Fi(),visitorId:Ct(),siteUserId:Tt(),pageUrl:window.location.href,referrer:document.referrer||void 0,eventId:_t()})})}catch(e){console.error("[Recommendation] Error tracking behavior:",e)}}async function Wi(e,t,n,i,o){try{await qi(o,[{eventId:_t(),name:"slider_navigate",entityType:"recommendation",entityId:e,metadata:{direction:t,fromSlide:n,toSlide:i}}])}catch{}}async function Ki(e,t,n){try{await qi(n,[{eventId:_t(),name:"slider_swipe",entityType:"recommendation",entityId:e,metadata:{direction:t}}])}catch{}}const Gi=new WeakMap,Vi=new Set,Ji=new Set,Yi=new Map;let Qi=!1;const Xi=Gt(),Zi=gt();function eo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function to(e){const t=Number(e);return Number.isFinite(t)?t:null}function no(){setTimeout(()=>{Yi.forEach(e=>{e.disconnect()}),Yi.clear(),G("Recommendation","Cleaned up observers on navigation")},500)}function io(e){return!!function(e){return!0===e.isTestMode||!0===e.testMode}(e)&&!function(){try{return"undefined"!=typeof localStorage&&"true"===localStorage.getItem(g)}catch{return!1}}()&&(K("Recommendation",`Skipping test mode widget: ${e.id}. Run localStorage.setItem('${g}', 'true') to view.`),!0)}function oo(e){const t=e?.triggerConfig,n=t?.frequencyCap;if(n&&"object"==typeof n)return n}async function ro(e){try{!function(){if(Qi)return;Qi=!0;const e=history.pushState,t=history.replaceState;history.pushState=(...t)=>{e.apply(history,t),no()},history.replaceState=(...e)=>{t.apply(history,e),no()},window.addEventListener("popstate",()=>no()),window.addEventListener("hashchange",()=>no())}();let t=(Array.isArray(e.widgets)?e.widgets:[]).map(e=>Ci(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=function(e){if(!eo(e))return null;if(!Array.isArray(e.reasonCodes))return null;const t=e.reasonCodes.map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0),n=function(e){if(!eo(e))return null;const{siteFound:t,siteVerified:n,subscriptionValidated:i,pageUrlEvaluated:o,hasEligibleWidgets:r,...a}=e;if("boolean"!=typeof t||"boolean"!=typeof n||"boolean"!=typeof i||"boolean"!=typeof o||"boolean"!=typeof r)return null;const s={};for(const[e,t]of Object.entries(a)){if("boolean"!=typeof t)return null;s[e]=t}return{siteFound:t,siteVerified:n,subscriptionValidated:i,pageUrlEvaluated:o,hasEligibleWidgets:r,...s}}(e.eligibilityFlags);return n?{widgets:Array.isArray(e.widgets)?e.widgets.map(e=>Ci(e)).filter(e=>Boolean(e)):[],reasonCodes:t,eligibilityFlags:n}:null}(await n.json());if(!i)return void J("Recommendation","Invalid recommendations contract: required reasonCodes/eligibilityFlags missing.");if(!i.eligibilityFlags.siteFound||!i.eligibilityFlags.siteVerified||!i.eligibilityFlags.subscriptionValidated)return void J("Recommendation","Server marked recommendations as ineligible:",i.reasonCodes);t=i.widgets}const n=function(e){if(e.length<=1)return e.map(e=>({candidateId:`recommendation:${e.id}`,widget:e,frequencyKey:`display:recommendation:${e.id}`,frequencyCapConfig:oo(e)}));const t=e.map(e=>{const t=(e?.triggerConfig||{}).conflictResolution||{};return{...Zi.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:oo(e)}}),n=Zi.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=>!!e.eligibilityFlags?.isActive||(K("Recommendation","Skipping inactive widget from contract:",e.id),!1)).filter(e=>!io(e)).filter(e=>{const t=rn(e.pageTargetingJson,window.location.href);return t||K("Recommendation","Skipping widget due to page targeting:",e.id),t}));for(const t of n)await ao(t.widget,e,t.frequencyKey,t.frequencyCapConfig)}catch(e){V("Recommendation","Error initializing:",e)}}async function ao(e,t,n,i){const o=Ei(e.id);if(o&&!Ji.has(e.id))return Ji.add(e.id),!1;if(!o&&Ji.has(e.id)&&Ji.delete(e.id),Ji.has(e.id))return!1;const r=()=>{if(!i)return!0;const t=Xi.canShow(n,i);return!!t.allowed||(K("Recommendation",`Skipping widget due to frequency cap (${t.reason||"limit"})`,e.id),!1)};if(!e.containerSelector){if(await uo(e,t)){if(!r())return!1;if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return!1;const o=lo(e,t);if(!o)return!1;if(io(o))return!1;Ji.add(o.id);const a=await po(o,t);return a&&i&&Xi.recordShown(n),a}return!1}if(document.querySelector(e.containerSelector)){if(await uo(e,t)){if(!r())return!1;if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return!1;const o=lo(e,t);if(!o)return!1;if(io(o))return!1;Ji.add(o.id);const a=await po(o,t);return a&&i&&Xi.recordShown(n),a}return!1}return K("Recommendation","Container not found, setting up observer for:",e.containerSelector),function(e,t,n,i){if(Yi.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(Ei(e.id))so(e.id);else if(document.querySelector(e.containerSelector)&&await uo(e,t)){if(i&&!Xi.canShow(n,i).allowed)return void so(e.id);if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return void so(e.id);const o=lo(e,t);if(!o)return void so(e.id);if(io(o))return void so(e.id);Ji.add(o.id),await po(o,t)&&i&&Xi.recordShown(n),so(e.id),K("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}),Yi.set(e.id,r),setTimeout(()=>{so(e.id),o.cancel()},1e4)}(e,t,n,i),!1}function so(e){const t=Yi.get(e);t&&(t.disconnect(),Yi.delete(e))}function co(){Yi.forEach((e,t)=>{e.disconnect(),G("Recommendation","Cleaned up observer for:",t)}),Yi.clear(),document.querySelectorAll(Ii).forEach(e=>{e.remove()}),Ji.forEach(e=>{const t=document.getElementById(`rec-widget-${e}`);t&&t.remove()}),Ji.clear(),Vi.clear(),G("Recommendation","Module cleanup complete")}function lo(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 K("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=Zt(i);if(t){K("Recommendation","Applying config override:",i.variantName);const n=Yt(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=Yt(e.containerStyles||{},t.styles)),t.displayType&&(e.displayType=t.displayType)}e._experimentAssignment=i}return e}async function uo(e,t){if(!1===e.eligibilityFlags?.isActive)return!1;if(e.eligibilityFlags?.segmentTargetingRequired&&!t.segmentManager)return K("Recommendation","Skipping segment-targeted widget because segment manager is unavailable:",e.id),!1;if(t.experimentManager&&!t.experimentManager.shouldRenderTarget(e.id))return K("Recommendation","Skipping widget (excluded by experiment):",e.id),!1;if(e.containerSelector){const t=document.querySelector(e.containerSelector);if(K("Recommendation","Container check:",e.containerSelector,"-> Found:",!!t),!t)return!1}return!!rn(e.pageTargetingJson,window.location.href)&&(!(t.segmentManager&&e.segmentTargetingMode&&e.segmentIds&&!await t.segmentManager.shouldShow(e.segmentTargetingMode,e.segmentIds))||(K("Recommendation","Skipping widget due to segment targeting:",e.id),!1))}async function po(e,t){try{const i=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 o="";try{o=Fi()}catch{o=`sid_fallback_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}const r=await fetch(`${t.apiEndpoint}/public/sites/${t.siteKey}/recommendations/${e.id}/products`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentProductId:i,pageUrl:window.location.href,sessionId:o,visitorId:window.selwise_vid,userId:window.selwise_suid})});if(!r.ok)return!1;const a=await r.json(),s=(n=a.products,Array.isArray(n)?n.filter(e=>eo(e)).map(e=>{const t=function(e){if(!eo(e))return null;if("string"!=typeof e.strategy||"string"!=typeof e.summary)return null;if(!Array.isArray(e.reasonCodes)||!Array.isArray(e.weights))return null;const t=to(e.confidence);if(null===t)return null;const n=e.reasonCodes.map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0),i=[];for(const t of e.weights){if(!eo(t)||"string"!=typeof t.signal||"string"!=typeof t.label)return null;const e=to(t.weight),n=to(t.score),o=to(t.contribution);if(null===e||null===n||null===o)return null;i.push({signal:t.signal,label:t.label,weight:e,score:n,contribution:o})}return{strategy:e.strategy,reasonCodes:n,summary:e.summary,confidence:t,weights:i}}(e.explainability);return t?{...e,explainability:t}:e}):[]);if(a.productCard&&(e.productCard=a.productCard),0===s.length)return!1;const c=s.find(e=>e.explainability)?.explainability;c&&G("Recommendation","Top explainability summary:",c.summary);const l=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(Ti,"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=>Ai(t,e,n,zi,ji,Hi,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=Pi.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:_i};bi(n,e.template,e.unifiedProduct,t)}}),Pi.delete(e))}(i,r),r}(e,t,n);if(i.appendChild(r),e.customCSS){const t=document.createElement("style");t.textContent=tt(e.customCSS),i.appendChild(t)}if(e.productCard&&e.productCard.customCSS){const t=document.createElement("style");t.textContent=tt(e.productCard.customCSS),i.appendChild(t)}return i}(e,s,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)}(l,e),async function(e,t){try{await qi(t,[{eventId:_t(),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=Di(e),s={currentIndex:0,totalSlides:r.children.length,slidesPerView:a,touchStartX:0,touchEndX:0};$i.set(e.id,s),Mi(e,t);const c=t.querySelector(".recommendation-arrow-prev"),l=t.querySelector(".recommendation-arrow-next");c?.addEventListener("click",()=>{const o=s.currentIndex;Oi(e,t,"prev"),i?.(e.id,"prev",o,s.currentIndex,n)}),l?.addEventListener("click",()=>{const o=s.currentIndex;Oi(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=$i.get(e.id);i&&(i.currentIndex=n,Li(e,t),Ni(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=$i.get(e.id);if(!n)return;const i=n.touchStartX-n.touchEndX;i>50?Oi(e,t,"next"):i<-50&&Oi(e,t,"prev")}(e,t)},{passive:!0}),e.autoplay&&(Ri(e,t),e.pauseOnHover&&(t.addEventListener("mouseenter",()=>{Bi(e)}),t.addEventListener("mouseleave",()=>{Ri(e,t)}))),window.addEventListener("resize",()=>{Mi(e,t),Li(e,t)})}(e,l,t,Wi,Ki),function(e,t,n){const i=Gi.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&&!Vi.has(a)){Vi.add(a);const e=Array.from(o).indexOf(i);qi(n,[{eventId:_t(),name:"product_impression",entityType:"recommendation",entityId:t,productItemCode:r,metadata:{productItemCode:r,position:e}}]).catch(()=>{})}}})},{threshold:.5});Gi.set(e,r),o.forEach(e=>r.observe(e))}(l,e.id,t),e._experimentAssignment&&t.experimentManager&&l.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)(l,s,e)}catch(e){V("Recommendation","Custom JS error:",e)}return!0}catch(e){return V("Recommendation","Error rendering widget:",e),!1}var n}const ho={loadSearchModule:async()=>({SearchModule:xi}),loadRecommendationModule:async()=>({initRecommendations:ro,cleanup:co})},go={canShow:()=>({allowed:!0}),recordShown:()=>{},cleanup:()=>{}};class mo{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=gt(),this.originalPushState=null,this.originalReplaceState=null,this.popStateListener=null,this.pendingTimeouts=new Set,this.spaCleanupSetup=!1,this.config={siteKey:"",apiUrl:bt(),exposeGlobal:!1},this.renderer=new ut,this.moduleLoaders={...ho,...e}}get tracker(){return this.trackerInstance||(this.trackerInstance=new qt(this.config.apiUrl||bt(),this.config.siteKey)),this.trackerInstance}set tracker(e){this.trackerInstance=e}get frequencyCapManager(){return this.isBrowserEnvironment()?(this.frequencyCapManagerInstance||(this.frequencyCapManagerInstance=Gt()),this.frequencyCapManagerInstance):go}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(),_.forEach((e,t)=>{D(t)}),document.querySelectorAll(E).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(E).forEach(n=>{const i=n.getAttribute(T)===e,o=!t||n.getAttribute(I)===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 qt(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(!cn(t))return void console.warn("[Selwise] Sentry DSN validation failed - not initializing");const n=window.SelwiseConfig;return async function(e){if(e.dsn)if(cn(e.dsn))try{await async function(){if(!ln)return dn||(dn=new Promise((e,t)=>{if(window.Sentry)return ln=!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=()=>{ln=!0,e()},n.onerror=()=>{console.warn("[Selwise] Failed to load Sentry from CDN"),t(new Error("Sentry CDN load failed"))},document.head.appendChild(n)}),dn)}();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:un,beforeSend:pn,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 en(this.config.siteKey,this.tracker.getVisitorId(),this.config.apiUrl),await this.experiments.init(),this.segments=new an(this.config.apiUrl,this.config.siteKey,this.tracker.getVisitorId(),this.tracker.getSessionId(),this.tracker.getSiteUserId(),this.tracker.getSiteUserProfileId());const[e,,t]=await Promise.allSettled([this.loadSiteConfig().catch(e=>(V("Selwise","Failed to load site config:",e),null)),this.loadScripts().catch(e=>(V("Selwise","Failed to load scripts:",e),null)),fetch(`${this.config.apiUrl}/public/sites/${this.config.siteKey}/integrations`).catch(()=>null)]);if("fulfilled"===t.status&&t.value&&t.value.ok){const e=await t.value.json();this.applyPublicIntegrationsConfig(e)}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}),H(o.debugMode||!1),await this.tracker.initialize(),this.config.dataLayerConfig=o.dataLayerConfig,o.debugMode&&K("Selwise","Tracking config loaded from batch endpoint:",o)}K("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}),H(t.debugMode||!1),await this.tracker.initialize(),t.debugMode&&K("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();this.applyPublicIntegrationsConfig(e)}}catch(e){G("Selwise","Failed to load tracking config, using defaults")}}applyPublicIntegrationsConfig(e){if(!e||"object"!=typeof e)return;const t=this.mergeReverseMappings(e.integrations||[]),n=this.resolveExternalDataLayerName(e);Object.keys(t).length>0&&(this.config.reverseEventMapping=t,K("Selwise","Reverse event mapping loaded:",t)),n&&(this.config.externalDataLayerName=n,K("Selwise","External dataLayer source configured:",n)),"string"==typeof e.dataLayer?.platform&&e.dataLayer.platform.trim()&&(this.config.dataLayerPlatform=e.dataLayer.platform.trim()),"boolean"==typeof e.dataLayer?.useExternalDataLayer&&(this.config.useExternalDataLayer=e.dataLayer.useExternalDataLayer)}mergeReverseMappings(e){const t={};if(!e||0===e.length)return t;for(const n of e){if(!n?.enabled||!n.reverseEventMapping)continue;const e=n.provider||n.id||"unknown";for(const[i,o]of Object.entries(n.reverseEventMapping))if("string"==typeof o&&o.trim()){if(Object.prototype.hasOwnProperty.call(t,i)){const n=t[i];n!==o&&J("Selwise",`Reverse mapping collision for "${i}" ignored from ${e}. Keeping "${n}", skipping "${o}".`);continue}t[i]=o}}return t}resolveExternalDataLayerName(e){const t=e.dataLayer&&"string"==typeof e.dataLayer.externalDataLayerName&&e.dataLayer.externalDataLayerName.trim().length>0?e.dataLayer.externalDataLayerName.trim():null;if(t)return t;for(const t of e.integrations||[]){if(!t?.enabled)continue;const e=t.config&&"string"==typeof t.config.externalDataLayerName&&t.config.externalDataLayerName.trim().length>0?t.config.externalDataLayerName.trim():null;if(e)return e}return null}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=>(V("Selwise","Failed to load campaigns:",e),null)),t=this.loadWidgets().catch(e=>(V("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||{},n=this.config.externalDataLayerName||e.externalDataLayerName||"dataLayer",i=this.config.dataLayerPlatform||e.platform||"generic",o="boolean"==typeof this.config.useExternalDataLayer?this.config.useExternalDataLayer:e.useExternalDataLayer??!0;this.dataLayerEnabled=e.enabled??!0,this.dataLayerManager=new Hn(this.tracker,this.config.siteKey,bt(this.config.apiUrl),{enabled:e.enabled??!0,variableName:e.variableName??"selwiseLayer",platform:i,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,useExternalDataLayer:o,reverseEventMapping:Object.keys(t).length>0?t:void 0,externalDataLayerName:n,attachToGlobalApi:Boolean(this.config.exposeGlobal)}),this.dataLayerEnabled?(this.dataLayerManager.init(),K("Selwise","Data layer manager initialized and started")):K("Selwise","Data layer manager created but NOT enabled (disabled in dashboard settings)"),e.debugMode&&K("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,K("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||[];K("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),K("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),K("Selwise",`Injected script: ${e.name}`),this.tracker.track("script_injected",{entityType:"script",entityId:e.id,metadata:{name:e.name}})}catch(t){V("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=rn(e.pageTargetingJson,window.location.href);return n||K("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(K("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){K("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=It(),o="campaign"===t?"campaign":"widget",r=!0===e.isTestMode||!0===e.testMode;if(this.renderedEntities.has(e.id))return K("Selwise",`Skipping already rendered ${o}: ${e.id}`),!1;if(r&&!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 a=n?null:this.experiments?.getVariantModuleForTarget(e.id);if(a&&a.moduleData)return K("Selwise",`Rendering variant module for ${o}: ${e.id} -> variant: ${a.moduleData.id}`),await this.renderVariantModule(a.moduleData,a.experimentId,a.variantId,a.targetType||t),!1;if(this.experiments&&!this.experiments.shouldRenderTarget(e.id))return K("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 K("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 s=Qt(e.contentJson||{}),c=e.stylesJson||{},l=e.placementConfigJson||{};const d=this.experiments?.getVariant(e.id)||this.experiments?.getAssignmentByTargetId(e.id);if(d){const e=Zt(d);e?.content&&"object"==typeof e.content&&(s=Yt(s,Qt(e.content))),e?.styles&&"object"==typeof e.styles&&(c=Yt(c,e.styles)),e?.placement&&"object"==typeof e.placement&&(l=Yt(l,e.placement))}const u={id:e.id,type:e.type,placementConfigJson:l,__entityType:t},p={id:e.id,contentJson:s,stylesJson:c};this.cleanupRenderedEntityById(e.id,t);const h=this.renderer.render(u,p);if(h){this.renderedEntities.add(e.id);const n="campaign"===t?"campaign":"widget";return this.tracker.track("impression",{entityType:n,entityId:e.id}),d&&this.experiments?.trackImpression(d.experimentId),h.addEventListener("click",t=>{const i=this.resolveTrackableInteractionTarget(t,h);if(!i)return;const o=this.buildClickMetadata(i),r=this.isLikelyAddToCartAction(o.buttonText||"",o.linkUrl);this.tracker.track("click",{entityType:n,entityId:e.id,metadata:o}),r&&this.tracker.track("add_to_cart",{entityType:n,entityId:e.id,metadata:o}),d&&this.experiments?.trackConversion(d.experimentId)},{capture:!0}),!0}return!1}resolveTrackableInteractionTarget(e,t){const n=this.resolveEventTargetElement(e);if(!n||!t.contains(n))return null;if(this.closestWithinRoot(n,t,'.selwise-close, [data-selwise-ignore-click="true"]'))return null;return this.closestWithinRoot(n,t,'a[href], button, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-selwise-track-click="true"]')||n}resolveEventTargetElement(e){if(e.target instanceof HTMLElement)return e.target;if("function"==typeof e.composedPath){const t=e.composedPath();for(const e of t)if(e instanceof HTMLElement)return e}return null}closestWithinRoot(e,t,n){const i=e.closest(n);return i instanceof HTMLElement&&t.contains(i)?i:null}buildClickMetadata(e){const t=e.closest("a[href]"),n=(e.textContent||(e instanceof HTMLInputElement?e.value:"")||e.getAttribute("aria-label")||e.getAttribute("title")||"").trim().replace(/\s+/g," "),i={targetTag:e.tagName.toLowerCase()};if(n.length>0&&(i.buttonText=n),t instanceof HTMLAnchorElement){const e=(t.getAttribute("href")||t.href||"").trim();e.length>0&&(i.linkUrl=e)}return i}isLikelyAddToCartAction(e,t){const n=e.toLowerCase(),i=(t||"").toLowerCase();return/add to cart|buy now|purchase|add to bag|sepete ekle|satın al|hemen al|sepete at|satın al şimdi/i.test(n)||i.length>0&&/cart|checkout|basket|sepet|odeme|payment/i.test(i)}async renderVariantModule(e,t,n,i){let o,r;if(e.data?(o=e.data,r=e.targetType||i||"widget"):(o=e,r=i||"widget"),!0!==o?.isTestMode&&!0!==o?.testMode||It())switch(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":K("Selwise","Variant recommendation module will be rendered by recommendations module");break;case"search_config":K("Selwise","Variant search config will be applied by search module");break;default:J("Selwise",`Unknown target type for variant module: ${r}`)}else J("Selwise",`Skipping test mode variant module (${r}): ${o?.id||"unknown"} (Run localStorage.setItem('selwise_test_mode', 'true') to view)`)}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)}}module.exports=i})();