(function () {
  const notifList = [{"name":"#19984","createdAt":"2025-12-14T17:03:47Z","lineItems":{"edges":[{"node":{"title":"特級白蝦仁1kg｜批次不同可能出現有尾或無尾情況｜純天然捕撈｜高蛋白低脂肪｜肉質鮮嫩｜無添加劑｜適合煎、炒、燉、燒烤等多種烹飪方式｜冷凍新鮮加工｜健康美味選擇[3777822540301]","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/3A9577CD-9C30-4B52-AF61-F46AC24BC2C7.jpg?v=1746893718"},"product":{"id":"gid://shopify/Product/9330811306270","handle":"白蝦仁"}}}]},"customer":{"firstName":"kwok kuen","addresses":[{"city":"hong kong","country":"Hong Kong"}]}},{"name":"#19983","createdAt":"2025-12-14T16:52:54Z","lineItems":{"edges":[{"node":{"title":"「特價🉐」南非🇿🇦煙燻味慢煮鴕鳥肉｜250克｜高蛋白低脂肪｜橙色包裝🍊","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-2058.jpg?v=1756914055"},"product":{"id":"gid://shopify/Product/9844228456734","handle":"南非-煙燻味慢煮鴕鳥肉-250克-高蛋白低脂肪-橙色包裝🍊"}}}]},"customer":{"firstName":"Kwan","addresses":[{"city":"葵涌","country":"Hong Kong"},{"city":"Kwai Chung","country":"Hong Kong"},{"city":"葵涌","country":"Hong Kong"}]}},{"name":"#19982","createdAt":"2025-12-14T16:47:23Z","lineItems":{"edges":[{"node":{"title":"「平絕全港」CP 檸檬🍋味熟雞胸900克｜即食雞胸｜健身減肥｜美容瘦身｜即開即食｜方便｜一包9塊","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/160EF65B-1329-4271-8AF5-92700B390F2B.jpg?v=1746894680"},"product":{"id":"gid://shopify/Product/9740551946526","handle":"泰國-cp-檸檬"}}}]},"customer":{"firstName":"sandy","addresses":[{"city":"屯門","country":"Hong Kong"},{"city":"屯門","country":"Hong Kong"}]}},{"name":"#19981","createdAt":"2025-12-14T16:46:14Z","lineItems":{"edges":[{"node":{"title":"阿根廷大廠COTO 100%純天然牛尾切粒3.6cm｜偏瘦｜100%原切牛肉｜100%無添加｜適合燉煮｜紅酒燴牛尾｜方便[3483044939637]","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-3265.jpg?v=1762952440"},"product":{"id":"gid://shopify/Product/9416086552862","handle":"牛尾"}}}]},"customer":{"firstName":"XIONGFEI","addresses":[{"city":"Pok Fu Lam","country":"Hong Kong"},{"city":"Mid-Levels Central","country":"Hong Kong"}]}},{"name":"#19980","createdAt":"2025-12-14T16:39:29Z","lineItems":{"edges":[{"node":{"title":"英國🇬🇧肥牛皇1mm｜100%無激素｜香港加工｜約60/40肥瘦｜👍類似吉⭕️家口感、牛肉飯","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-2936.jpg?v=1761741783"},"product":{"id":"gid://shopify/Product/9330766053662","handle":"hotpot-king-2lb"}}}]},"customer":{"firstName":"Evelyn","addresses":[{"city":"薄扶林","country":"Hong Kong"},{"city":"薄扶林","country":"Hong Kong"}]}},{"name":"#19979","createdAt":"2025-12-14T16:08:45Z","lineItems":{"edges":[{"node":{"title":"櫻桃谷鴨胸｜1份3塊｜有皮｜好吃😋｜沒有調味｜生鴨胸","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-6259.jpg?v=1755909299"},"product":{"id":"gid://shopify/Product/9768237498654","handle":"櫻桃谷鴨胸-3塊-有皮-好吃😋"}}}]},"customer":{"firstName":"Suki","addresses":[{"city":"沙田","country":"Hong Kong"},{"city":"大圍","country":"Hong Kong"},{"city":"沙田","country":"Hong Kong"}]}},{"name":"#19978","createdAt":"2025-12-14T16:01:36Z","lineItems":{"edges":[{"node":{"title":"ROCKY CHICKEN 瘦熟雞胸500克｜奧爾良口味｜適合健身人士，方便｜獨立包裝｜一包5塊｜平替CP雞胸口味較淡｜「橙色袋」","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/1ECDFBDC-F67C-40B4-8287-47E310E535C8.jpg?v=1755909450"},"product":{"id":"gid://shopify/Product/9784502812958","handle":"rocky-chicken-瘦熟雞胸500克"}}}]},"customer":{"firstName":"ka yiu","addresses":[{"city":"香港","country":"Hong Kong"}]}},{"name":"#19977","createdAt":"2025-12-14T15:52:23Z","lineItems":{"edges":[{"node":{"title":"特價SPECIAL 雞胸肉 約 1KG ｜高蛋白低脂肪 適合減肥｜雞胸磚1分為2","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-5309.jpg?v=1746894840"},"product":{"id":"gid://shopify/Product/9684369178910","handle":"雞胸肉"}}}]},"customer":{"firstName":"蔡先生","addresses":[{"city":"沙田","country":"Hong Kong"}]}},{"name":"#19976","createdAt":"2025-12-14T15:42:06Z","lineItems":{"edges":[{"node":{"title":"「平絕全港」泰國皇家農場ROYAL FARM雞扒1公斤｜雞比扒｜精選部位｜100%純天然｜無防腐劑｜無激素｜無抗生素 (boneless thigh / boneless dumbstick）","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-5541.jpg?v=1746893879"},"product":{"id":"gid://shopify/Product/9414299222302","handle":"泰國皇家農場雞扒"}}}]},"customer":{"firstName":"Kimmy","addresses":[{"city":"元朗","country":"Hong Kong"},{"city":"洪水橋","country":"Hong Kong"}]}},{"name":"#19975","createdAt":"2025-12-14T15:27:06Z","lineItems":{"edges":[{"node":{"title":"美國IBP/EXCEL/NATIONAL ｜BEEF ANGUS安格斯｜雪花牛肩胛脊肉｜牛板腱｜肩胛板腱CHOICE精選級黑標｜產地直送｜高蛋白｜適合生酮飲食[3506014058429]","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-5290.jpg?v=1746893586"},"product":{"id":"gid://shopify/Product/9330747998494","handle":"product-2"}}}]},"customer":{"firstName":null,"addresses":[{"city":"hong kong","country":"Hong Kong"}]}},{"name":"#19974","createdAt":"2025-12-14T15:06:30Z","lineItems":{"edges":[{"node":{"title":"「冬日新產品特價🉐」澳洲和牛m4/5 火鍋片｜業務用1磅裝｜好吃口感好｜⚠️肩胛部位有肥的","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-2944.jpg?v=1761793096"},"product":{"id":"gid://shopify/Product/9905110876446","handle":"冬日新產品-澳洲和牛m4-5-火鍋片-業務用1磅裝-好吃口感好"}}}]},"customer":{"firstName":"Jamie","addresses":[{"city":"HK","country":"Hong Kong"}]}},{"name":"#19973","createdAt":"2025-12-14T14:50:08Z","lineItems":{"edges":[{"node":{"title":"「健身神器新產品」去皮鴨胸柳｜業務重 1kg｜低脂肪 高蛋白｜不用天天吃雞胸","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-3443.jpg?v=1764314008"},"product":{"id":"gid://shopify/Product/9937843945758","handle":"健身神器新產品-去皮鴨胸柳-業務重-1kg-低脂肪-高蛋白-不用天天吃雞胸"}}}]},"customer":{"firstName":"Wai Yab","addresses":[{"city":"N.T.","country":"Hong Kong"},{"city":"1 Tune On Lane, Tuen Mun","country":"Hong Kong"},{"city":"N.T.","country":"Hong Kong"},{"city":"1 Tune On Lane, Tuen Mun","country":"Hong Kong"}]}},{"name":"#19972","createdAt":"2025-12-14T14:35:51Z","lineItems":{"edges":[{"node":{"title":"「平絕全港」CP 奧爾良味熟雞胸900克｜即食雞胸｜健身減肥｜美容瘦身｜即開即食｜方便｜一包9塊","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/CD3E0751-842A-49C7-A188-56EE29E1B21C.png?v=1746894636"},"product":{"id":"gid://shopify/Product/9728671580446","handle":"cp雞胸奧爾良"}}}]},"customer":{"firstName":"Brian","addresses":[{"city":"Chai Wan","country":"Hong Kong"},{"city":"Chai Wan","country":"Hong Kong"}]}},{"name":"#19971","createdAt":"2025-12-14T14:30:11Z","lineItems":{"edges":[{"node":{"title":"「香港🇭🇰製造」0脂肪純蛋白液｜蛋青液｜1KG｜10.9g蛋白｜高蛋白低脂肪｜適合健身減脂朋友｜高效減脂｜⚠️特制急凍產品，解凍後使用⚠️｜","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-1977.jpg?v=1756352861"},"product":{"id":"gid://shopify/Product/9840301211934","handle":"香港製造-純蛋白液-蛋青液-1kg-高蛋白低脂肪-適合健身減脂朋友-高效減脂-⚠️特制急凍產品-解凍後使用⚠️-星期六出貨"}}}]},"customer":{"firstName":"Ka Tim","addresses":[{"city":"觀塘","country":"Hong Kong"},{"city":"觀塘","country":"Hong Kong"},{"city":"觀塘","country":"Hong Kong"},{"city":"觀塘","country":"Hong Kong"},{"city":"觀塘","country":"Hong Kong"}]}},{"name":"#19970","createdAt":"2025-12-14T14:18:38Z","lineItems":{"edges":[{"node":{"title":"越南🇻🇳迷你蝦仁1KG（蝦皇牌logo）｜炒飯煮麵精品｜減肥健身低卡路里","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-5262.jpg?v=1746894257"},"product":{"id":"gid://shopify/Product/9638353043742","handle":"越南-迷你蝦仁1kg-無冰衣-不縮水-炒飯煮麵精品"}}}]},"customer":{"firstName":"Kazaf","addresses":[{"city":"","country":"Hong Kong"},{"city":"何文田","country":"Hong Kong"}]}},{"name":"#19969","createdAt":"2025-12-14T14:17:59Z","lineItems":{"edges":[{"node":{"title":"特級白蝦仁1kg｜批次不同可能出現有尾或無尾情況｜純天然捕撈｜高蛋白低脂肪｜肉質鮮嫩｜無添加劑｜適合煎、炒、燉、燒烤等多種烹飪方式｜冷凍新鮮加工｜健康美味選擇[3777822540301]","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/3A9577CD-9C30-4B52-AF61-F46AC24BC2C7.jpg?v=1746893718"},"product":{"id":"gid://shopify/Product/9330811306270","handle":"白蝦仁"}}}]},"customer":{"firstName":"Wing Ho","addresses":[{"city":"將軍澳 坑口","country":"Hong Kong"},{"city":"Ming Tak Estate","country":"Hong Kong"},{"city":"Tseung Kwan O","country":"Hong Kong"}]}},{"name":"#19968","createdAt":"2025-12-14T14:10:46Z","lineItems":{"edges":[{"node":{"title":"港式蜜汁叉燒熟雞胸Champrotein™｜「新產品推廣」｜獨立包裝｜100gx9包｜業務裝900g｜採用CP原材料｜健身減脂肪新選擇｜紅色🌹","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-3741.jpg?v=1765450464"},"product":{"id":"gid://shopify/Product/9944749900062","handle":"新產品推廣-champrotein™-港式蜜汁叉燒熟雞胸-獨立包裝-業務裝900g-採用cp原材料-健身減脂肪新選擇"}}}]},"customer":{"firstName":null,"addresses":[{"city":"香港","country":"Hong Kong"}]}},{"name":"#19967","createdAt":"2025-12-14T13:51:50Z","lineItems":{"edges":[{"node":{"title":"美國IBP/EXCEL/NATIONAL ｜BEEF ANGUS安格斯｜雪花牛肩胛脊肉｜牛板腱｜肩胛板腱CHOICE精選級黑標｜產地直送｜高蛋白｜適合生酮飲食[3506014058429]","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-5290.jpg?v=1746893586"},"product":{"id":"gid://shopify/Product/9330747998494","handle":"product-2"}}}]},"customer":{"firstName":"Joey","addresses":[{"city":"","country":"Hong Kong"},{"city":"柴灣","country":"Hong Kong"},{"city":"柴灣","country":"Hong Kong"},{"city":"柴灣","country":"Hong Kong"},{"city":"柴灣","country":"Hong Kong"},{"city":"柴灣","country":"Hong Kong"},{"city":"柴灣","country":"Hong Kong"},{"city":"柴灣","country":"Hong Kong"}]}},{"name":"#19966","createdAt":"2025-12-14T13:33:41Z","lineItems":{"edges":[{"node":{"title":"「米飯替代神器」毛豆仁1KG｜植物蛋白低卡路里｜合適健身減脂｜與米飯混合煮｜增加飽腹感","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-7529.jpg?v=1755909525"},"product":{"id":"gid://shopify/Product/9793976336670","handle":"米飯替代神器-毛豆仁1kg-植物蛋白低卡路里-合適健身減肥-與米飯混合煮-增加飽腹感"}}}]},"customer":{"firstName":"sze","addresses":[{"city":"Hongkong","country":"Hong Kong"},{"city":"Hongkong","country":"Hong Kong"},{"city":"元朗","country":"Hong Kong"},{"city":"元朗","country":"Hong Kong"}]}},{"name":"#19965","createdAt":"2025-12-14T12:38:58Z","lineItems":{"edges":[{"node":{"title":"新疆孜然燒烤熟雞胸Champrotein™ |「新產品推廣」| 獨立包裝｜100gx9包｜業務裝900g｜採用CP原材料｜健身減脂肪新選擇｜紫色💜","image":{"url":"https://cdn.shopify.com/s/files/1/0677/4754/5374/files/IMG-3742.jpg?v=1765450444"},"product":{"id":"gid://shopify/Product/9944758124830","handle":"新產品推廣-champrotein™-新疆孜然燒烤熟雞胸-獨立包裝-業務裝900g-採用cp原材料-健身減脂肪新選擇"}}}]},"customer":{"firstName":"Samson","addresses":[{"city":".","country":"Hong Kong"},{"city":"葵青","country":"Hong Kong"}]}}];
  const visitorCounter = {"isEnabled":true,"minVisitorsToShow":1,"maxVisitorsToShow":50,"messageTemplate":"現在有{count}人查看此產品","displayDuration":30};
  const seasonalTheme = {
  isEnabled: false,
  currentTheme: 'halloween',
  startDate: '10-15',
  endDate: '11-01'
}; 
  const triggerRules = {
  exitIntent: { isEnabled: true },
  scrollDepth: { isEnabled: false, percentage: 50 },
  timeOnPage: { isEnabled: true, seconds: 30 },
  inactivity: { isEnabled: false, seconds: 60 }
};
  const crossSell = {
  isEnabled: false,
  suggestType: 'complementary',
  maxSuggestions: 3,
  message: 'Complete your purchase with {product}'
};
  const countdownTimer ={
  isEnabled: false,
  duration: 24,
  style: 'simple',
  position: 'after',
  text: 'Offer ends in {time}'
};
  const timeTranslations = {"about":"About","second":"second","seconds":"seconds","minute":"minute","minutes":"minutes","hour":"hour","hours":"hours","day":"day","days":"days","month":"month","months":"months","year":"year","years":"years","ago":"ago","numeralLocale":"en"};

  if (Object.keys(notifList).length === 0) {
    return;
  }

  function getActiveThemeStyles() {
    // If seasonal themes not enabled, return null
    if (!seasonalTheme?.isEnabled) return null;

    const now = new Date();
    const currentMonth = now.getMonth() + 1;
    const currentDay = now.getDate();

    // Parse theme dates
    const [startMonth, startDay] = seasonalTheme.startDate.split('-').map(Number);
    const [endMonth, endDay] = seasonalTheme.endDate.split('-').map(Number);

    // Helper function to convert month and day to a comparable number
  const dateToNumber = (month, day) => month * 100 + day;

  const currentDate = dateToNumber(currentMonth, currentDay);
  const startDate = dateToNumber(startMonth, startDay);
  const endDate = dateToNumber(endMonth, endDay);

  let isInSeason;
  if (startDate <= endDate) {
    // Normal date range within same year
    isInSeason = currentDate >= startDate && currentDate <= endDate;
  } else {
    // Date range spans across years (like Dec 26 - Jan 20)
    isInSeason = currentDate >= startDate || currentDate <= endDate;
  }

  if (!isInSeason) return null;

    // Return the seasonal theme styles
    switch(seasonalTheme.currentTheme) {
      case 'christmas':
        return {
          bgColor: "#FC5C65",
          bgImage: "https://sales-popup.gropulse.com/assets/images/christmas.png",
          textColor: "#ffffff",
          timeTextColor: "#ffffff",
          productNameTextColor: "#ffffff",
          closeButtonColor: "#ffffff",
        };
      case 'halloween':
        return {
          bgColor: '#A55EEA',
          bgImage: 'https://sales-popup.gropulse.com/assets/images/halloween.png',
          textColor: "#ffffff",
          timeTextColor: "#f3eded",
          productNameTextColor: "#f3eded",
          closeButtonColor: "#ffffff",
        };
      case 'blackFriday':
        return {
          bgColor: '#A55EEA',
          bgImage: 'https://sales-popup.gropulse.com/assets/images/black-friday.png',
          textColor: "#ffffff",
          timeTextColor: "#f3eded",
          productNameTextColor: "#f3eded",
          closeButtonColor: "#ffffff",
        };
      case 'cyberMonday':
        return {
          bgColor: '#4B7BEC',
          bgImage: 'https://sales-popup.gropulse.com/assets/images/cyber-monday.png',
          textColor: "#ffffff",
          timeTextColor: "#f3eded",
          productNameTextColor: "#f3eded",
          closeButtonColor: "#ffffff",
        };
      case 'valentines':
        return {
          bgColor: "#FFE4E1",
          bgImage: "none",
          textColor: "#FF69B4",
          timeTextColor: "#FF1493",
          productNameTextColor: "#FF69B4",
          closeButtonColor: "#FF1493",
        };
      case 'newYear':
        return {
          bgColor: "#2C3E50",
          bgImage: "none",
          textColor: "#ffffff",
          timeTextColor: "#F1C40F",
          productNameTextColor: "#E74C3C",
          closeButtonColor: "#ffffff",
        };
      default:
        return null;
    }
  }

  const styleElement = document.createElement("style");
  const bgImage = 'linear-gradient(270deg, #FC9E8B 0%, #FE1C4F 100%)';
  const isGradient = bgImage.search("linear-gradient") !== -1 || bgImage.search("radial-gradient") !== -1;

  const animation = {
  isEnabled: false,
  entryAnimation: 'slide',
  exitAnimation: 'slide',
  duration: 400,
  delay: 0,
  easing: 'ease'
};
  const dimension = {
  isEnabled: false,
  width: '385',
  widthUnit: 'px',
  height: '',
  heightUnit: 'px',
  useSameForMobile: true,
  mobileWidth: 300,
  mobileWidthUnit: 'px'
};

  const activeTheme = getActiveThemeStyles();

  styleElement.innerHTML = `
  :root {
    --quantum-sn-notif-bg-color: ${activeTheme ? activeTheme.bgColor : '#FC9E8B'};
    --quantum-sn-notif-bg-image: ${activeTheme ? "url('"+activeTheme.bgImage+"')": (isGradient ? 'linear-gradient(270deg, #FC9E8B 0%, #FE1C4F 100%)' : (bgImage !== "none" ? 'url(https://sales-popup.gropulse.comlinear-gradient(270deg, #FC9E8B 0%, #FE1C4F 100%))' : "none"))};
    --quantum-sn-notif-close-button-color: ${activeTheme ? activeTheme.closeButtonColor : '#ffffff'};
    --quantum-sn-notif-order-time-text-color: ${activeTheme ? activeTheme.timeTextColor : '#ffffff'};
    --quantum-sn-notif-position-top: ${'bottomLeft' === 'topLeft' || 'bottomLeft' === 'topRight' || 'bottomLeft' === 'centerTop' ? `2px` : 'auto'};
    --quantum-sn-notif-position-right: ${'bottomLeft' === 'topRight' || 'bottomLeft' === 'bottomRight' ? `30px` : 'auto'};
    --quantum-sn-notif-position-bottom: ${'bottomLeft' === 'bottomLeft' || 'bottomLeft' === 'bottomRight' || 'bottomLeft' === 'centerBottom' ? `30px` : 'auto'};
    --quantum-sn-notif-position-left: ${'bottomLeft' === 'topLeft' || 'bottomLeft' === 'bottomLeft' ? `30px` : 'auto'};
    --quantum-sn-notif-product-name-text-color: ${activeTheme ? activeTheme.productNameTextColor : '#f3eded'};
    --quantum-sn-notif-text-color: ${activeTheme ? activeTheme.textColor : '#ffffff'};
    --notification-transform-distance: 200px;
    --animation-duration: ${animation.isEnabled ? `${animation.duration}ms` : '1s'};
    --animation-delay: ${animation.isEnabled ? `${animation.delay}ms` : '0s'};
    --animation-easing: ${animation.isEnabled ? animation.easing : 'ease-in-out'};
    --notification-width: ${dimension.isEnabled ? `${dimension.width}${dimension.widthUnit}` : '385px'};
    --notification-height: ${dimension.isEnabled && dimension.height !== 'auto' ? `${dimension.height}${dimension.heightUnit}` : 'auto'};
    --notification-mobile-width: ${dimension.isEnabled && !dimension.useSameForMobile ? `${dimension.mobileWidth}${dimension.mobileWidthUnit}` : 'calc(100% - 20px)'};
  }
  
  .quantum-sn-notification-wrapper {
    font-size: 13px;
    line-height: 1.3;
    position: fixed;
    z-index: 99999999;
    top: var(--quantum-sn-notif-position-top);
    right: var(--quantum-sn-notif-position-right);
    bottom: var(--quantum-sn-notif-position-bottom);
    left: var(--quantum-sn-notif-position-left);
    width: var(--notification-width);
    height: var(--notification-height);
    ${!dimension.isEnabled ? 'max-width: 100%;' : ''}
    padding: 15px 25px 15px 20px;
    transition: all var(--animation-duration) var(--animation-easing);
    transform: ${'bottomLeft' === 'topLeft' || 'bottomLeft' === 'topRight' || 'bottomLeft' === 'centerTop' 
      ? 'translateY(calc(-100% - var(--notification-transform-distance)))' 
      : 'translateY(calc(100% + var(--notification-transform-distance)))'};
    color: var(--quantum-sn-notif-text-color);
    border-radius: 8px;
    background-color: var(--quantum-sn-notif-bg-color);
    background-image: var(--quantum-sn-notif-bg-image);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.14);
    ${dimension.isEnabled ? 'overflow-y: auto;' : ''}
  }
  
  .quantum-sn-notification-wrapper span.order-product-name {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 6px;
  }
  
  .quantum-sn-notification-wrapper span.order-product-name a {
    text-decoration: none;
    color: var(--quantum-sn-notif-product-name-text-color);
    border-bottom: 1px solid transparent;
  }
  
  .quantum-sn-notification-wrapper span.order-product-name > span {
    font-weight: normal;
    color: var(--quantum-sn-notif-text-color);
  }
  
  .quantum-sn-notification-wrapper span.order-time {
    margin-top: auto;
    color: var(--quantum-sn-notif-order-time-text-color);
  }
  
  .quantum-sn-notification-content {
    display: flex;
    align-items: flex-start;
    max-width: 350px;
  }
  
  .quantum-sn-notification-content__close-btn {
    position: absolute;
    top: 7px;
    right: 7px;
    width: 14px;
    min-width: 14px;
    height: 14px;
    min-height: 14px;
    padding: 0;
    cursor: pointer;
    border: none;
    background: none;
  }
  
  .quantum-sn-notification-content__close-btn svg {
    fill: var(--quantum-sn-notif-close-button-color);
  }
  
  .quantum-sn-notification-content__image {
    flex: 0 0 70px;
    margin-right: 20px;
    width: 70px;
    height: 70px;
  }
  
  .quantum-sn-notification-content__text {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
  }
  
  .quantum-sn-notification-content__text > span {
    display: block;
  }
  
  .quantum-sn-notification-content__image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border: 1px solid #eceaea;
    border-radius: 4px;
  }
  
  .quantum-sn-show {
    transform: translateY(0);
  }

  /* Visitor counter styles */
  .quantum-sn-visitor-counter {
    background: rgba(255, 255, 255, 0.9);
    padding: 8px 12px;
    margin-bottom: 12px;
    border-radius: 6px;
    font-size: 13px;
    line-height: 1.3;
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--quantum-sn-notif-text-color);
  }

  .quantum-sn-visitor-counter svg {
    width: 16px;
    height: 16px;
    fill: currentColor;
  }

  @media (max-width: 768px) {
    .quantum-sn-notification-wrapper {
      line-height: 1.5;
      width: var(--notification-mobile-width);
      top: ${'top' === 'top' ? `2px` : 'auto'};
      bottom: ${'top' === 'bottom' ? `30px` : 'auto'};
      left: 50%;
      transform: translate(-50%, ${
        'top' === 'top' 
          ? 'calc(-100% - var(--notification-transform-distance))'
          : 'calc(100% + var(--notification-transform-distance))'
      });
      right: auto;
    }

    .quantum-sn-show {
      transform: translate(-50%, 0);
    }

    .quantum-sn-notification-wrapper span.order-product-name {
      font-size: 12px;
    }
  }
    .quantum-sn-stock-alert {
    font-size: 13px;
    line-height: 1.3;
    padding: 8px 12px;
    margin: 6px 0;
    background: rgba(255, 236, 236, 0.9);
    border-radius: 6px;
    color: #d82c0d;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .quantum-sn-stock-alert.critical {
    background: rgba(216, 44, 13, 0.1);
    color: #d82c0d;
    font-weight: 500;
  }

  .quantum-sn-stock-alert::before {
    content: "⚠️";
    font-size: 14px;
  }

  /* Animation classes */
  .animation-slide-in {
    animation: slideIn var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-slide-out {
    animation: slideOut var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-fade-in {
    animation: fadeIn var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-fade-out {
    animation: fadeOut var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-bounce-in {
    animation: bounceIn var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-bounce-out {
    animation: bounceOut var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-scale-in {
    animation: scaleIn var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-scale-out {
    animation: scaleOut var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  /* Animation keyframes */
  @keyframes slideIn {
    from {
      transform: translateY(200px);
      opacity: 0;
    }
    to {
      transform: translateY(0);
      opacity: 1;
    }
  }

  @keyframes slideOut {
    from {
      transform: translateY(0);
      opacity: 1;
    }
    to {
      transform: translateY(200px);
      opacity: 0;
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @keyframes fadeOut {
    from {
      opacity: 1;
    }
    to {
      opacity: 0;
    }
  }

  @keyframes bounceIn {
    0% {
      transform: scale(0.3);
      opacity: 0;
    }
    50% {
      transform: scale(1.05);
      opacity: 0.8;
    }
    70% {
      transform: scale(0.9);
      opacity: 0.9;
    }
    100% {
      transform: scale(1);
      opacity: 1;
    }
  }

  @keyframes bounceOut {
    0% {
      transform: scale(1);
      opacity: 1;
    }
    20% {
      transform: scale(1.1);
      opacity: 0.8;
    }
    100% {
      transform: scale(0.3);
      opacity: 0;
    }
  }

  @keyframes scaleIn {
    from {
      transform: scale(0);
      opacity: 0;
    }
    to {
      transform: scale(1);
      opacity: 1;
    }
  }

  @keyframes scaleOut {
    from {
      transform: scale(1);
      opacity: 1;
    }
    to {
      transform: scale(0);
      opacity: 0;
    }
  }

  @media (max-width: 768px) {
  .quantum-sn-notification-wrapper {
    /* Your existing mobile styles... */
  }

  .animation-slide-in {
    animation: slideInMobile var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  .animation-slide-out {
    animation: slideOutMobile var(--animation-duration) var(--animation-easing) var(--animation-delay) forwards;
  }

  @keyframes slideInMobile {
    from {
      transform: translate(-50%, 200px);
      opacity: 0;
    }
    to {
      transform: translate(-50%, 0);
      opacity: 1;
    }
  }

  @keyframes slideOutMobile {
    from {
      transform: translate(-50%, 0);
      opacity: 1;
    }
    to {
      transform: translate(-50%, 200px);
      opacity: 0;
    }
  }
}

 .quantum-sn-notification-wrapper::-webkit-scrollbar {
    width: 6px;
  }

  .quantum-sn-notification-wrapper::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 3px;
  }

  .quantum-sn-notification-wrapper::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }

  .quantum-sn-notification-wrapper::-webkit-scrollbar-thumb:hover {
    background: rgba(0, 0, 0, 0.3);
  }
  `;

  document.head.appendChild(styleElement);

  const customCSS = ``; 
  if (customCSS && customCSS.trim() !== '') {
    const customStyleElement = document.createElement("style");
    customStyleElement.innerHTML = customCSS;
    document.head.appendChild(customStyleElement);
  }

  const timeDifference = (current, previous) => {
    const msPerMinute = 60 * 1000;
    const msPerHour = msPerMinute * 60;
    const msPerDay = msPerHour * 24;
    const msPerMonth = msPerDay * 30;
    const msPerYear = msPerDay * 365;

    const elapsed = current - previous;

    // Helper function to format numbers based on locale
    const formatNum = (num) => {
      try {
        return new Intl.NumberFormat(timeTranslations?.numeralLocale || "en").format(num);
      } catch {
        return String(num);
      }
    };

    // Use translations with fallback defaults
    // For "ago": use ?? to respect empty strings (user-cleared values)
    const t = {
      second: timeTranslations?.second || "second",
      seconds: timeTranslations?.seconds || "seconds",
      minute: timeTranslations?.minute || "minute",
      minutes: timeTranslations?.minutes || "minutes",
      hour: timeTranslations?.hour || "hour",
      hours: timeTranslations?.hours || "hours",
      day: timeTranslations?.day || "day",
      days: timeTranslations?.days || "days",
      month: timeTranslations?.month || "month",
      months: timeTranslations?.months || "months",
      year: timeTranslations?.year || "year",
      years: timeTranslations?.years || "years",
      ago: timeTranslations?.ago ?? "",
    };

    if (elapsed < msPerMinute) {
      const timeInSecond = Math.round(elapsed / 1000);
      return `${formatNum(timeInSecond)} ${timeInSecond === 1 ? t.second : t.seconds} ${t.ago}`;
    } else if (elapsed < msPerHour) {
      const timeInMinute = Math.round(elapsed / msPerMinute);
      return `${formatNum(timeInMinute)} ${timeInMinute === 1 ? t.minute : t.minutes} ${t.ago}`;
    } else if (elapsed < msPerDay) {
      const timeInHour = Math.round(elapsed / msPerHour);
      return `${formatNum(timeInHour)} ${timeInHour === 1 ? t.hour : t.hours} ${t.ago}`;
    } else if (elapsed < msPerMonth) {
      const timeInDay = Math.round(elapsed / msPerDay);
      return `${formatNum(timeInDay)} ${timeInDay === 1 ? t.day : t.days} ${t.ago}`;
    } else if (elapsed < msPerYear) {
      const timeInMonth = Math.round(elapsed / msPerMonth);
      return `${formatNum(timeInMonth)} ${timeInMonth === 1 ? t.month : t.months} ${t.ago}`;
    } else {
      const timeInYear = Math.round(elapsed / msPerYear);
      return `${formatNum(timeInYear)} ${timeInYear === 1 ? t.year : t.years} ${t.ago}`;
    }
  };

  function createVisitorCounter(count) {
    if (!visitorCounter.isEnabled) {
      return '';
    }

    const message = visitorCounter.messageTemplate.replace('{count}', count);
    
    return `
      <div style="color: #000000" class="quantum-sn-visitor-counter">
        <svg viewBox="0 0 20 20">
          <path d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"/>
        </svg>
        <span>${message}</span>
      </div>
    `;
  }

  function getSessionId() {
    let sessionId = localStorage.getItem('quantum_visitor_sid');
    if (!sessionId) {
      sessionId = 'sid_' + Math.random().toString(36).substr(2, 9);
      localStorage.setItem('quantum_visitor_sid', sessionId);
    }
    return sessionId;
  }

  async function trackVisitor() {
    if (!visitorCounter.isEnabled) return null;
    
    try {
      const response = await fetch('https://sales-popup.gropulse.com/visitors/track', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          shop: Shopify.shop,
          sessionId: getSessionId(),
          deviceType: screen.width < 768 ? 'mobile' : 'desktop',
          currentPage: window.location.pathname
        }),
      });
  
      const data = await response.json();
      return data.visitorCount;
    } catch (error) {
      console.error('Error tracking visitor:', error);
      return null;
    }
  }

  const notificationWrapperElement = document.createElement("div");
  notificationWrapperElement.classList.add("quantum-sn-notification-wrapper");

  const closeBtnMarkup = true === true ? `<button class="quantum-sn-notification-content__close-btn">
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="12"
      height="12"
      fill="currentColor"
      class="bi bi-x-circle"
      viewBox="0 0 16 16"
    >
      <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
      <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
    </svg>
  </button>` : "";

  notificationWrapperElement.innerHTML = `
    ${closeBtnMarkup}
    <div class="quantum-sn-notification-content-wrapper"></div>
  `;

  document.body.appendChild(notificationWrapperElement);

  const notifElem = document.querySelector(".quantum-sn-notification-content-wrapper");
  const closeBtn = document.querySelector(".quantum-sn-notification-content__close-btn");

  let initialDelayTimeoutId;
  let intervalTimeoutId;
  let displayTimeTimeoutId;

  const deactivateNotifications = () => {
    clearTimeout(initialDelayTimeoutId);
    clearTimeout(intervalTimeoutId);
    clearTimeout(displayTimeTimeoutId);
    if (animation.isEnabled) {
      notificationWrapperElement.className = `quantum-sn-notification-wrapper animation-${animation.exitAnimation}-out`;
      setTimeout(() => {
        notificationWrapperElement.classList.remove("quantum-sn-show");
      }, animation.duration + animation.delay);
    } else {
      notificationWrapperElement.classList.remove("quantum-sn-show");
    }
  };

  closeBtn?.addEventListener("click", deactivateNotifications);

  async function trackAnalytics(type, data = {}) {
    try {
      await fetch('https://sales-popup.gropulse.com/analytics/track', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          type,
          shop: Shopify.shop,
          deviceType: screen.width < 768 ? 'mobile' : 'desktop',
          ...data
        })
      });
    } catch (error) {
      console.error('Analytics tracking error:', error);
    }
  };


  function getNotificationHeight() {
    const notification = document.querySelector('.quantum-sn-notification-wrapper');
    if (!notification) return 200; // Default fallback height
    const height = notification.offsetHeight;
    return height + 50; // Adding extra padding
  }

  const stockScarcity = {
  isEnabled: false,
  threshold: 10,
  criticalThreshold: 5,
  lowStockMessage: 'Only {count} items left in stock!',
  criticalStockMessage: 'Hurry! Only {count} left!',
  position: 'after'
};

  async function createStockAlert(productId) {
    if (!stockScarcity.isEnabled) return '';
    // Get stock level from Shopify product variant
    async function getProductStock(productId) {
      const storageKey = `product_stock_${productId}`;
      const cachedData = sessionStorage.getItem(storageKey);
      
      if (cachedData !== null) {
        const { stock, timestamp } = JSON.parse(cachedData);
        const currentTime = new Date().getTime();
        // Cache expires after 5 minutes
        if (currentTime - timestamp < 5 * 60 * 1000) {
          return stock;
        }
      }

      try {
        const response = await fetch(`https://sales-popup.gropulse.com/product?shop=${Shopify.shop}&productId=${productId}`);
        const {product} = await response.json();

        const totalStock = product.variants.edges.reduce((sum, { node }) => 
          sum + (node.inventoryQuantity || 0), 0
        );

        const cacheData = {
          stock: totalStock,
          timestamp: new Date().getTime()
        };
        sessionStorage.setItem(storageKey, JSON.stringify(cacheData));
        return totalStock;
      } catch (error) {
        console.error('Error fetching product stock:', error);
        return null;
      }
    }
  
    const stockCount = await getProductStock(productId);
    if (stockCount === null || stockCount > stockScarcity.threshold) return '';
  
    const isCritical = stockCount <= stockScarcity.criticalThreshold;
    const message = isCritical 
      ? stockScarcity.criticalStockMessage 
      : stockScarcity.lowStockMessage;
  
    return `
      <div class="quantum-sn-stock-alert ${isCritical ? 'critical' : ''}">
        ${message.replace('{count}', stockCount)}
      </div>
    `;
  }

  async function getRecommendedProducts(productId) {
    if (!crossSell.isEnabled) return null;
  
    try {
      const response = await fetch(
        `${window.Shopify.routes.root}recommendations/products.json?` + 
        `product_id=${productId}&` +
        `limit=${crossSell.maxSuggestions}&` +
        `intent=${crossSell.suggestType}`
      );
      const {products} = await response.json();
      return products;
    } catch (error) {
      console.error('Error fetching recommended products:', error);
      return null;
    }
  }
  
  let i = 0;
  window.gpIsViewCounted = window.gpIsViewCounted || false;
  const showNotif = async () => {
    const notif = notifList[i++ % notifList.length];
    const productId = notif?.lineItems?.edges[0]?.node?.product?.id;

    let recommendedProduct = null;
    if (crossSell.isEnabled && Math.random() < 0.3) {
      const recommendations = await getRecommendedProducts(productId.split("/").pop());
      if (recommendations && recommendations.length > 0) {
        recommendedProduct = recommendations[Math.floor(Math.random() * recommendations.length)];
      }
    }

    if(!window.gpIsViewCounted){
      await trackAnalytics('view', {
        productId: notif?.lineItems?.edges[0]?.node?.product?.id
      });
      window.gpIsViewCounted = true
    }

   
    
    let visitorCount = null;
    if (visitorCounter.isEnabled) {
      visitorCount = await trackVisitor();
    }

    let stockAlert = '';
    if (stockScarcity.isEnabled) {
      stockAlert = await createStockAlert(productId);
    }

    const customerName = notif?.customer?.firstName;
    const customerCity = notif?.customer?.addresses[0]?.city;
    const customerCountry = notif?.customer?.addresses[0]?.country;
    const productName = notif?.lineItems?.edges[0]?.node?.title;
    const productImage = notif?.lineItems?.edges[0]?.node?.image?.url;
    const productUrl = notif?.lineItems?.edges[0]?.node?.product?.handle;
    const orderTime = notif?.createdAt;

    const modifiedNotificationContent = `{{customer city}} 的客人購買了 {{product name}}❤️❤️❤️`.replace(
      /{{customer name}}/g,
      `${true || !customerName ? "Someone" : customerName}`
    )
    .replace(/{{customer city}}/g, customerCity ? customerCity : "unknown city")
    .replace(/{{customer country}}/g, `${customerCountry ? customerCountry : "unknown country"}`)
    .replace(
      /{{product name}}/g,
      `<span class="order-product-name"><a href="https://${Shopify.shop}/products/${productUrl}">${productName}</a></span>`
    );

    notifElem.innerHTML = recommendedProduct ? `
    ${createVisitorCounter(visitorCount)}
    <div class="quantum-sn-notification-content">
      <div class="quantum-sn-notification-content__image">
        <a href="/products/${recommendedProduct.handle}">
          <img src="${recommendedProduct.featured_image}" alt="${recommendedProduct.title}" />
        </a>
      </div>
      <div class="quantum-sn-notification-content__text">
        <div style="margin-bottom: 6px">
          ${crossSell.message.replace('{product}', `<span class="order-product-name"><a href="/products/${recommendedProduct.handle}">${recommendedProduct.title}</a></span>`)}
        </div>
      </div>
    </div>`
    : `${createVisitorCounter(visitorCount)}
      <div class="quantum-sn-notification-content">
        ${productImage ? (`<div class="quantum-sn-notification-content__image">
          <a href='/products/${productUrl}'>
            <img src=${productImage} alt=${productName} />
          </a>
        </div>`) : ""}
        <div class="quantum-sn-notification-content__text">
          ${stockScarcity.isEnabled && stockScarcity.position === 'before' ? stockAlert : ''}
          <div style="margin-bottom: 6px">
            ${modifiedNotificationContent}
          </div>
          ${stockScarcity.isEnabled && stockScarcity.position === 'after' ? stockAlert : ''}
          <span class="order-time">${timeTranslations?.about ?? ""} ${timeDifference(
            new Date(),
            new Date(orderTime)
          )}</span>
        </div>
      </div>
      `;


      if (countdownTimer.isEnabled) {
        // Create a unique timer ID for this product
        const timerKey = `quantum_timer_${notif?.lineItems?.edges[0]?.node?.product?.id}`;
        let endTime = localStorage.getItem(timerKey);
        
        if (!endTime) {
          endTime = Date.now() + (countdownTimer.duration * 60 * 60 * 1000); // Convert hours to milliseconds
          localStorage.setItem(timerKey, endTime);
        }
    
        const timeLeft = Math.max(0, endTime - Date.now());
        const hours = Math.floor(timeLeft / (60 * 60 * 1000));
        const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000));
        const seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
    
        let timeString;
        if (countdownTimer.style === 'digital') {
          timeString = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        } else {
          timeString = `${hours}h ${minutes}m ${seconds}s`;
        }
    
        const timerMessage = countdownTimer.text.replace('{time}', timeString);
        
        // Insert timer based on position
        const notifContent = notifElem.querySelector('.quantum-sn-notification-content__text');
        const timerElement = document.createElement('div');
        timerElement.className = 'quantum-sn-timer';

        const updateTimer = () => {
          const timeLeft = Math.max(0, endTime - Date.now());
          const hours = Math.floor(timeLeft / (60 * 60 * 1000));
          const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000));
          const seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);

          if (timeLeft === 0) {
            clearInterval(timerInterval);
            // Optionally hide or update the timer when it reaches zero
            timerElement.style.display = 'none';
            return;
          }

          let timeString;
          if (countdownTimer.style === 'digital') {
            timeString = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
          } else {
            timeString = `${hours}h ${minutes}m ${seconds}s`;
          }

          const timerMessage = countdownTimer.text.replace('{time}', timeString);
          timerElement.innerHTML = timerMessage;
        };

        // Initial update
        updateTimer();
        
        // Update timer every second
        const timerInterval = setInterval(updateTimer, 1000);
    
        if (countdownTimer.position === 'before') {
          notifContent.insertBefore(timerElement, notifContent.firstChild);
        } else if (countdownTimer.position === 'after') {
          notifContent.appendChild(timerElement);
        } else {
          notifContent.parentNode.insertBefore(timerElement, notifContent.nextSibling);
        }
      };

    const height = getNotificationHeight();
    notificationWrapperElement.style.setProperty('--notification-transform-distance', `${height}px`);

    notificationWrapperElement.classList.add("quantum-sn-show");

    
    if (animation.isEnabled) {
      notificationWrapperElement.className = `quantum-sn-notification-wrapper animation-${animation.entryAnimation}-in`;
    } else {
      notificationWrapperElement.className = "quantum-sn-notification-wrapper quantum-sn-show";
    }
  

    displayTimeTimeoutId = setTimeout(() => {
      if (animation.isEnabled) {
        // Apply exit animation
        notificationWrapperElement.className = `quantum-sn-notification-wrapper animation-${animation.exitAnimation}-out`;
        
        // Wait for animation to complete before hiding
        setTimeout(() => {
          notificationWrapperElement.classList.remove("quantum-sn-show");
          intervalTimeoutId = setTimeout(showNotif, (+110*1000));
        }, animation.duration + animation.delay);
      } else {
        // Use default behavior
        notificationWrapperElement.classList.remove("quantum-sn-show");
        intervalTimeoutId = setTimeout(showNotif, (+110*1000));
      }
    }, (+8*1000));


      // Add click tracking to product links
  const productLinks = document.querySelectorAll('.order-product-name a');
  productLinks.forEach(link => {
    link.addEventListener('click', () => {
      trackAnalytics('click', {
        productId: notif?.lineItems?.edges[0]?.node?.product?.id
      });
    });
  });

  // Add close button tracking
  const closeButton = document.querySelector('.quantum-sn-notification-content__close-btn');
  if (closeButton) {
    closeButton.addEventListener('click', () => {
      trackAnalytics('close');
    });
  }
  };

  const selectedDevices = 'desktop,mobile'.split(",");
  const selectedPages = 'all'.split(",");
  const selectedTemplates = ''.split(",");


  async function checkGeoTargeting() {
    const geoTargeting = { isEnabled: false, mode: 'all', countries: [] };
    
    if (!geoTargeting.isEnabled) return true;
  
    try {
      // Get user's country from session storage if available
      let userCountry = sessionStorage.getItem('quantum_user_country');
  
      if (!userCountry) {
        // Fetch user's country using IP geolocation
        const response = await fetch('https://get.geojs.io/v1/ip/geo.json');
        const data = await response.json();
        userCountry = data.country_code;
        
        // Cache the result
        sessionStorage.setItem('quantum_user_country', userCountry);
      }
  
      // Check if notification should be shown based on targeting mode
      if (geoTargeting.mode === 'all') return true;
      
      const isCountryInList = geoTargeting.countries.includes(userCountry);
      return geoTargeting.mode === 'include' ? isCountryInList : !isCountryInList;
    } catch (error) {
      console.error('Error checking geo-targeting:', error);
      return true; // Show notification if geo-targeting check fails
    }
  }

      const displayBasedOnDevice = async () => {
        const shouldDisplayForLocation = await checkGeoTargeting();
        if (!shouldDisplayForLocation) return;

        let shouldDisplay = false;
        
        // show notifications on mobile devices
        if(selectedDevices.length === 1 && selectedDevices[0] === "mobile"){
          if(screen.width < 640) shouldDisplay = true;
        } 
        // show notifications on desktop devices
        if(selectedDevices.length === 1 && selectedDevices[0] === "desktop"){
          if(screen.width > 640) shouldDisplay = true;
        } 
        // always show notifications
        if(selectedDevices.length === 2){
          shouldDisplay = true;
        }

        // If device check passes, set up triggers
        if (shouldDisplay) {
          // Exit intent tracking
          if (triggerRules.exitIntent.isEnabled) {
            let mouseY = 0;
            document.addEventListener('mousemove', function(e) {
              mouseY = e.clientY;
            });
            
            document.addEventListener('mouseleave', function(e) {
              if (mouseY < 100 && e.clientY <= 0) {  // Exit intent detected
                showNotif();
              }
            });
          }

          // Scroll depth tracking
          if (triggerRules.scrollDepth.isEnabled) {
            window.addEventListener('scroll', function() {
              const scrollPercent = (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100;
              if (scrollPercent >= triggerRules.scrollDepth.percentage) {
                showNotif();
              }
            });
          }

          // Time on page tracking
          if (triggerRules.timeOnPage.isEnabled) {
            setTimeout(showNotif, triggerRules.timeOnPage.seconds * 1000);
          }

          // Inactivity tracking
          if (triggerRules.inactivity.isEnabled) {
            let inactivityTimer;
            
            function resetInactivityTimer() {
              clearTimeout(inactivityTimer);
              inactivityTimer = setTimeout(showNotif, triggerRules.inactivity.seconds * 1000);
            }

            ['mousemove', 'keypress', 'scroll', 'click'].forEach(event => {
              document.addEventListener(event, resetInactivityTimer);
            });
            
            resetInactivityTimer();
          }

          // If no custom triggers are enabled, use default delay
          if (!triggerRules.exitIntent.isEnabled && 
              !triggerRules.scrollDepth.isEnabled && 
              !triggerRules.timeOnPage.isEnabled && 
              !triggerRules.inactivity.isEnabled) {
            initialDelayTimeoutId = setTimeout(showNotif, (+30*1000));
          }
        }
    };

  // Display logic based on pages
  if(selectedPages[0] === 'all') {
    displayBasedOnDevice();
  }

  if(selectedPages[0] === 'custom') {
    const currentPath = location.pathname.split("/")[1];
    const pathMap = {
      '': 'index',
      'collections': 'collection',
      'products': 'product',
      'cart': 'cart',
      'blogs': 'blog',
      'pages': 'page',
      'search': 'search'
    };
    
    if (selectedTemplates.includes(pathMap[currentPath] || '')) {
      displayBasedOnDevice();
    }
  }
})();