;(() => {
  const style=document.createElement('style');
  style.textContent='body.product-index #main-content, body.product-index-search #main-content,main:has(salla-loyalty-program){min-height:100vh} .container--products-list salla-products-list{display:block;min-height:55vh} .details-slider .swiper:has(.magnify-wrapper){aspect-ratio:1;overflow:hidden} .details-slider .swiper-wrapper:has(>.magnify-wrapper){display:flex;align-items:start} .details-slider .magnify-wrapper{flex:0 0 100%;min-width:0} salla-loyalty-program{display:block;min-height:100vh} salla-loyalty-hero,.s-loyalty-program-hero-background{display:block;min-height:320px} .container--products-list:before{content:none}';
  document.head.append(style);
  function header(){const cart=document.querySelector('#mainnav salla-cart-summary'),top=document.querySelector('header.store-header .top-navbar');const search=top?.querySelector('.header-search'),address=top?.querySelector('button.btn--rounded-gray[onclick]');if(!cart||!address||!search)return false;const group=cart.parentElement;group.classList.add('am-header-actions');search.classList.add('am-header-search');address.classList.add('am-header-address');group.prepend(search,address);document.body.classList.add('am-header-utilities-ready');return true;}
  if(!header() && document.readyState==='loading'){const observe=new MutationObserver(()=>{if(header())observe.disconnect()});observe.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener('DOMContentLoaded',()=>observe.disconnect(),{once:true});}
})();
;(() => {
  const css = document.createElement('style');
  css.textContent = 'html{scrollbar-gutter:stable}#mainnav :is(.s-cart-summary-total,[data-am-value],.s-cart-summary-count),.s-product-card-price{font-variant-numeric:tabular-nums}#main-content .s-product-card-entry:not(.s-product-card-horizontal) .s-product-card-image,#am-category-products .s-product-card-image{aspect-ratio:1}#main-content .s-product-card-entry .s-product-card-image img{display:block}#main-content :is(input,select,textarea){max-inline-size:100%}';
  document.head.append(css);
  // Reserve the last rendered dimensions only when reloading the same layout.
  const key = 'am-layout-reload-v1';
  const width = innerWidth;
  const route = location.pathname + location.search;
  const targets = [
    'header.store-header','#mainnav .inner','#am-shop','#am-service-requests','#am-water-savings',
    '#main-content > section[component-id]','#am-category-products > [data-am-shelf]',
    '.am-cart-address-summary','footer.store-footer','.container--product-details .details-slider','.container--products-list','.s-loyalty-program-hero-background','salla-loyalty-program','.am07-list-hero'
  ];
  function selector(el, base) {
    for (const attr of ['data-am-shelf','component-id']) {
      const value=el.getAttribute(attr);
      if (value && /^\d+$/.test(value)) return base+'['+attr+'="'+value+'"]';
    }
    return base;
  }
  let saved;
  try {saved=JSON.parse(sessionStorage.getItem(key));} catch {}
  const hold=document.createElement('style');
  if(performance.getEntriesByType('navigation')[0]?.type==='reload' && saved?.route===route && saved.width===width && saved.sizes){
    const rules=[];
    for(const [sel,h] of Object.entries(saved.sizes)) {
      const plain=sel.replace(/\[(?:component-id|data-am-shelf)="\d+"\]$/,'');
      if(targets.includes(plain) && Number.isFinite(h) && h>0 && h<3500)rules.push(sel+'{min-height:'+h+'px!important;box-sizing:border-box}');
    }
    const heroHeight=saved.sizes['.am07-list-hero'];
    if(Number.isFinite(heroHeight)&&heroHeight>0&&heroHeight<1000)rules.push('main:not(:has(.am07-list-hero)) .container--products-list{margin-block-start:calc('+heroHeight+'px + 2rem)!important}');
    hold.textContent=rules.join('');document.head.append(hold);
    for(const event of ['pointerdown','keydown','resize'])window.addEventListener(event,()=>hold.remove(),{once:true,passive:true});
    const release=()=>Promise.resolve(document.fonts?.ready).then(()=>requestAnimationFrame(()=>requestAnimationFrame(()=>setTimeout(()=>hold.remove(),1200))));
    if(document.readyState==='complete')release();else window.addEventListener('load',release,{once:true});
  }
  window.addEventListener('pagehide',()=>{
    if(document.readyState!=='complete'||innerWidth!==width)return;
    const sizes={};for(const base of targets)for(const el of document.querySelectorAll(base)){
      const h=Math.round(el.getBoundingClientRect().height);if(h>0 && h<3500)sizes[selector(el,base)]=h;
    }
    try{sessionStorage.setItem(key,JSON.stringify({route,width,sizes}));}catch{}
  });
})();
;(() => { const load = () => { if (document.querySelector('script[data-almoalej-shopping]')) return; const s = document.createElement('script'); s.dataset.almoalejShopping = '1'; s.src = 'https://almoalej-shopping.almoalej-services.workers.dev/assistant.js'; document.body.append(s); }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', load, {once:true}); else load(); })();
/* Restore the reading position only when reloading this history entry. */
(function(){
 const reloading=performance.getEntriesByType('navigation')[0]?.type==='reload';
 const key='amReloadPosition:'+ (window.navigation?.currentEntry?.key || location.pathname);
 let armed=!reloading;
 function marker(el){return el?.closest('.s-product-card-entry[id],section[component-id]')}
 function remember(){
  if(!armed)return;
  const line=Math.min(150,innerHeight/3),el=marker(document.elementFromPoint(innerWidth/2,line));
  const selector=el?.matches('.s-product-card-entry')?'.s-product-card-entry[id="'+CSS.escape(el.id)+'"]':el?'section[component-id="'+CSS.escape(el.getAttribute('component-id'))+'"]':null;
  try{sessionStorage.setItem(key,JSON.stringify({path:location.pathname+location.search+location.hash,y:scrollY,selector,top:el?.getBoundingClientRect().top}))}catch{}
 }
 window.addEventListener('scrollend',remember,{passive:true});
 window.addEventListener('pagehide',()=>{if(document.visibilityState!=='hidden')remember()});
 window.addEventListener('load',()=>setTimeout(()=>{armed=true},1900),{once:true});
 if(!reloading)return;
 let pos;try{pos=JSON.parse(sessionStorage.getItem(key))}catch{} if(!pos||pos.path!==location.pathname+location.search+location.hash)return;
 const root=document.documentElement,style=document.createElement('style');
 style.textContent='html{scroll-behavior:auto!important}html body{visibility:hidden!important}';
 (document.head||root).append(style);
 let done=false,frame=0,last='',steady=0;
 function reveal(){if(done)return;done=true;cancelAnimationFrame(frame);style.remove();armed=true}
 const limit=setTimeout(()=>{place();reveal()},1800);
 function finish(){clearTimeout(limit);reveal()}
 for(const type of ['pointerdown','wheel','touchstart','keydown','pagehide'])window.addEventListener(type,finish,{once:true,passive:true});
 function target(){const el=pos.selector&&document.querySelector(pos.selector);return pos.y<2?0:el&&el.offsetHeight?Math.max(0,el.getBoundingClientRect().top+scrollY-pos.top):pos.y}
 function place(){if(!done)window.scrollTo({top:target(),behavior:'instant'})}
 function check(){if(done)return;const sig=Math.round(target())+':'+document.documentElement.scrollHeight;steady=sig===last?steady+1:0;last=sig;
 if(steady>=4&&document.readyState==='complete'&&(!document.body.classList.contains('index')||document.getElementById('am-shop'))){place();finish();return}frame=requestAnimationFrame(check)}
 frame=requestAnimationFrame(check);
})();
/* Capture the native header context before asynchronous cart components start. */
(function (global) {
  'use strict';
  let current = null, receivedContext = false;
  document.addEventListener('headerContextUpdate', event => {
    const detail = event.detail;
    receivedContext = true;
    current = detail?.type === 'address' && typeof detail.city === 'string' && detail.city.trim()
      ? { known: true, city: detail.city.trim(), countryCode: String(detail.country_code || '').toUpperCase() }
      : null;
  });
  function get() {
    if (receivedContext) return current;
    const scope = global.salla?.config?.get?.('store.scope');
    const location = global.salla?.config?.get?.('store.shipping.delivery_location');
    // This is Salla's Saudi country ID, verified against the native country picker.
    // Unknown countries remain unconfirmed rather than being assumed Saudi.
    if (scope?.allocation?.type !== 'address' || String(location?.country_id) !== '1473353380' || typeof location?.city_name !== 'string' || !location.city_name.trim()) return null;
    return { known: true, city: location.city_name.trim(), countryCode: 'SA' };
  }
  global.AlmoalejNativeDeliveryContext = { get };
})(window);


/* Almoalej draft navigation. Runs only when the new draft service component exists. */
(function(){
 const selector=id=>'section[component-id="'+id+'"]';
 const targets={'am-shop':'935235511','am-offers':'652080513','am-devices':'2031253909','am-filters':'25939608','am-services':'1853988552','am-about':'877447485'};
 function rootOf(section){return section&&Array.from(section.querySelectorAll('*')).map(el=>el.shadowRoot).find(Boolean)}
 function jump(){const id=location.hash.slice(1);if(id.startsWith('am-'))document.getElementById(id)?.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'})}
 let bound=false,attempts=0;
 function mount(){
  const services=document.querySelector(selector('1853988552'));if(!services)return;
  Object.entries(targets).forEach(([id,component])=>{const el=document.querySelector(selector(component));if(el)el.id=id});
  const footer=document.querySelector('footer');if(footer)footer.id='am-contact';
  const heroRoot=rootOf(document.querySelector(selector('398096929')));
  const primary=heroRoot?.querySelector('.s-block-simple-section__button');
  if(primary)primary.setAttribute('href','#am-shop');
  document.querySelectorAll('a[href*="#am-"]').forEach(a=>{if(a.hasAttribute('download')||(a.target&&a.target!=='_self'))return;const target=new URL(a.href,location.href);if(target.origin===location.origin&&target.pathname.replace(/\/$/,'')===location.pathname.replace(/\/$/,'')&&target.search===location.search&&document.getElementById(target.hash.slice(1)))a.setAttribute('href',target.hash)});
  [['652080513','146247215'],['2031253909','463435319'],['344871967','1969591600'],['25939608','564944693']].forEach(([component,category])=>{const section=document.querySelector(selector(component));const h=section?.querySelector('h2');if(h&&!section.querySelector('.am-view-all')){const a=document.createElement('a');a.className='am-view-all';a.href='https://salla.sa/almoalej.com/-/c'+category;a.textContent='عرض الكل ←';h.before(a)}});
  if(!services.querySelector('.am-service-request')){const box=document.createElement('div');box.className='am-service-request';box.style.cssText='text-align:center;padding:0 20px 40px';const a=document.createElement('a');a.href='https://wa.me/966533557999?text='+encodeURIComponent('أرغب بطلب خدمة أو استشارة من المعالج.\nالمدينة:\nنوع الجهاز أو الاحتياج:');a.textContent='اطلب خدمة أو استشارة';a.style.cssText='display:inline-flex;align-items:center;justify-content:center;min-height:48px;padding:12px 24px;border-radius:8px;background:#0756d9;color:white;font-weight:700;text-decoration:none';box.append(a);services.append(box)}
  if(!bound){bound=true;window.addEventListener('hashchange',jump);document.addEventListener('click',event=>{const a=event.composedPath().find(el=>el instanceof HTMLAnchorElement);if(!a||event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey||a.hasAttribute('download')||(a.target&&a.target!=='_self'))return;const url=new URL(a.href,location.href);if(url.origin!==location.origin||url.pathname.replace(/\/$/,'')!==location.pathname.replace(/\/$/,'')||url.search!==location.search)return;const hash=url.hash;const target=hash&&hash.startsWith('#am-')&&document.getElementById(hash.slice(1));if(!target)return;event.preventDefault();event.stopPropagation();history.replaceState(null,'',hash);const move=()=>window.scrollTo({top:target.getBoundingClientRect().top+window.scrollY-110,behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'instant':'smooth'});if(document.body.classList.contains('menu-opened')){setTimeout(()=>{document.querySelector('button.close-mobile-menu')?.click();setTimeout(move,100)},50)}else move();},true);/* Initial section links are positioned by alignInitialAnchor. */}
 }
 function start(){mount();const timer=setInterval(()=>{mount();if(++attempts>=40)clearInterval(timer)},250)}
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Almoalej light motion: one entrance per element; content stays visible. */
(function(){
 function start(){
  if(document.body.classList.contains('cart')||performance.getEntriesByType('navigation')[0]?.type==='reload')return;
  if(getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return;
  if(document.documentElement.hasAttribute('data-am-motion'))return;
  document.documentElement.setAttribute('data-am-motion','ready');
  const reduced=matchMedia('(prefers-reduced-motion: reduce)');
  if(!('IntersectionObserver' in window)||!Element.prototype.animate)return;
  const seen=new WeakSet(),active=new Set();let order=0,queued=false;
  const observer=new IntersectionObserver(entries=>{entries.forEach(entry=>{
   if(!entry.isIntersecting)return;observer.unobserve(entry.target);if(reduced.matches)return;
   const animation=entry.target.animate([{opacity:.72,transform:'translate3d(0,8px,0)'},{opacity:1,transform:'translate3d(0,0,0)'}],{duration:320,delay:(order++%4)*20,easing:'cubic-bezier(.22,.61,.36,1)',fill:'none'});
   animation.id='am-soft-enter';active.add(animation);
   animation.onfinish=()=>{active.delete(animation);entry.target.setAttribute('data-am-entered','true');};animation.oncancel=()=>active.delete(animation);
  });},{threshold:.06,rootMargin:'0px 0px -8px 0px'});
  function scan(){document.querySelectorAll('.index #main-content>section:not(:has(.s-product-card-entry,.slide--cat-entry)), .index #main-content .slide--cat-entry, .s-product-card-entry, body.product-single article.am-native-product-description, .product-index .am07-list-hero, .product-index-search .am07-list-hero, .am-info-view:not([hidden]) .am-info-hero').forEach(el=>{if(seen.has(el)||getComputedStyle(el).display==='none')return;seen.add(el);observer.observe(el);});}
  function cancelActive(){active.forEach(animation=>animation.cancel());}
  reduced.addEventListener('change',()=>{if(reduced.matches)cancelActive();});window.addEventListener('pagehide',cancelActive);
  scan();const main=document.getElementById('main-content');if(main)new MutationObserver(()=>{if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;scan();});}).observe(main,{childList:true,subtree:true});
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Draft cart: the decrement control becomes native removal at quantity one. */
(function(){
 function start(){
  if(!document.body.classList.contains('cart')||getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return;
  const main=document.getElementById('main-content');if(!main||main.dataset.amDeleteReady)return;main.dataset.amDeleteReady='true';
  const style=document.createElement('style');style.textContent=`.cart .cart-item.am-quantity-delete>.absolute{display:none!important}.cart .cart-item.am-quantity-delete>div:first-of-type>div:first-child{padding-inline-end:0!important}.cart .am-delete-at-one{color:#dc2626!important;background:#fff1f2!important;opacity:1!important;cursor:pointer!important}.cart .am-delete-at-one:hover{background:#ffe4e6!important;color:#b91c1c!important}.cart .am-delete-at-one>span{display:none!important}.cart .am-delete-at-one:after{content:'';display:block;width:17px;height:17px;margin:auto;background:currentColor;mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cg fill='none' stroke='black' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3 6h18M9 6V4h6v2M5 6l1 14h12l1-14M10 10v6M14 10v6'/%3E%3C/g%3E%3C/svg%3E") center/contain no-repeat}.cart .am-delete-at-one:focus-visible{outline:2px solid #dc2626!important;outline-offset:3px}`;document.head.append(style);
  function sync(){main.querySelectorAll('.cart-item').forEach(item=>{const quantity=item.querySelector('salla-quantity-input'),input=quantity?.querySelector('input'),minus=quantity?.querySelector('.s-quantity-input-decrease-button'),remove=item.querySelector('salla-button.btn--delete button');if(!input||!minus||!remove)return;const one=Number(input.value)<=1;if(!item.classList.contains('am-quantity-delete'))item.classList.add('am-quantity-delete');minus.classList.toggle('am-delete-at-one',one);const label=one?'حذف المنتج من السلة':'إنقاص الكمية';if(minus.getAttribute('aria-label')!==label)minus.setAttribute('aria-label',label);if(minus.title!==label)minus.title=label;});}
  document.addEventListener('click',event=>{const minus=event.target.closest?.('.cart-item .s-quantity-input-decrease-button');if(!minus)return;const item=minus.closest('.cart-item'),input=item.querySelector('salla-quantity-input input'),remove=item.querySelector('salla-button.btn--delete button');if(!input||Number(input.value)>1||!remove)return;event.preventDefault();event.stopImmediatePropagation();remove.click();},true);
  let queued=false;function schedule(){if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;sync()});}
  main.addEventListener('input',schedule);main.addEventListener('change',schedule);main.addEventListener('click',schedule);
  new MutationObserver(schedule).observe(main,{childList:true,subtree:true,attributes:true,attributeFilter:['value']});sync();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
/* Six linked offer banners. Image slots intentionally empty until supplied. */
(function(){
 const banners=[{"title":"عرض الفخامة","url":"https://almoalej.com/عرض-الفخامة-جهاز-نانو-تكنولوجي-مع-برادة-ذاتية/p1808009306","desktopImage":"https://cdn.files.salla.network/other/609952933/f56fd124-6cb0-4c12-966c-a0bb7ca17652-original.png","mobileImage":"https://cdn.files.salla.network/homepage/609952933/2480d4ea-2f9d-4770-a767-a29618d436b9-original.png"},{"title":"العرض الكبير","url":"https://almoalej.com/العرض-الكبير-كلاسيك-بيور-مع-برادة-ذاتية-وجامبو-ثلاثي/p543722590","desktopImage":"https://cdn.files.salla.network/other/609952933/ec89400f-bf75-4705-95cc-ea11e5332a7f-original.png","mobileImage":"https://cdn.files.salla.network/other/609952933/6d863e1d-6206-464f-8337-cabb679148af-original.png"},{"title":"عرض الكلاسيك","url":"https://almoalej.com/عرض-الكلاسيك/p1916119903","desktopImage":"https://cdn.files.salla.network/other/609952933/0ed85b4d-dee2-4c49-86d1-af1ec7e02bcb-original.png","mobileImage":"https://cdn.files.salla.network/other/609952933/f4f6e706-69e8-494d-bd7c-fa8deb07b14a-original.png"},{"title":"عرض الكلاسيك بلس","url":"https://almoalej.com/عرض-الكلاسيك-بلس/p77942364","desktopImage":"https://cdn.files.salla.network/other/609952933/03febf23-2c6e-45fa-a5bc-9f8f35b9a917-original.png","mobileImage":"https://cdn.files.salla.network/homepage/609952933/fc4c43c5-95a9-440b-87ae-493d45fa71a9-original.png"},{"title":"باقة الصيانة سنتين ونصف","url":"https://almoalej.com/باقة-صيانة-سنتين-ونصف-5-زيارات/p1593553312","desktopImage":"https://cdn.files.salla.network/other/609952933/0251130d-c157-48a6-9528-679f94f12040-original.png","mobileImage":"https://cdn.files.salla.network/homepage/609952933/dfc5651d-1b2e-4ba1-9cd4-3fb401b8e16a-original.png"},{"title":"باقة الصيانة 5 سنوات","url":"https://almoalej.com/باقة-صيانة-5-سنوات-10-زيارات/p1418337955","desktopImage":"https://cdn.files.salla.network/other/609952933/7ae93753-d511-41d3-94c4-0fb4e91756ba-original.png","mobileImage":"https://cdn.files.salla.network/homepage/609952933/5694e1b6-b071-42fe-a138-8292c68bf58a-original.png"}];
 let attempts=0;
 function mount(){
  if(getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return false;
  const section=document.querySelector('section[component-id="280736763"]');const root=section&&Array.from(section.querySelectorAll('*')).map(el=>el.shadowRoot).find(Boolean);if(!root)return false;if(root.querySelector('.am-banner-carousel'))return true;
  const style=document.createElement('style');style.textContent='.container{display:none!important}:host{display:block!important;min-height:0!important}.am-banner-carousel{position:relative;width:100%;color:white;font-family:Tajawal,Tahoma,Arial;direction:rtl;box-sizing:border-box}.am-banner-slide[hidden]{display:none!important}.am-banner-slide{display:flex;align-items:center;justify-content:center;min-height:clamp(360px,25vw,480px);text-decoration:none;color:white!important;background:#0756d9;position:relative;box-sizing:border-box;text-align:center;padding:50px 80px 85px}.am-banner-copy h2{font-size:clamp(30px,3vw,46px);line-height:1.5;margin:12px 0 26px;color:white;font-weight:800}.am-banner-kicker{font-size:16px;color:#e7f6ff}.am-banner-cta{display:inline-flex;align-items:center;justify-content:center;border-radius:9px;background:white;color:#0756d9;min-height:48px;padding:10px 28px;font-weight:700;font-size:18px;box-sizing:border-box}.am-banner-picture{position:absolute;inset:0;width:100%;height:100%;display:block}.am-banner-picture img{display:block;width:100%;height:100%;object-fit:contain}.am-banner-slide:has(.am-banner-picture){padding:0;aspect-ratio:4/1}.am-banner-nav{position:absolute;bottom:22px;inset-inline:20px;display:flex;justify-content:center;align-items:center;gap:14px}.am-banner-nav button{display:inline-flex;align-items:center;justify-content:center;cursor:pointer;border:1px solid #ffffff80;background:#ffffff18;color:white;border-radius:50%;width:42px;height:42px;font-size:22px}.am-banner-dots{display:flex;gap:2px}.am-banner-dots button{width:28px;height:32px;background:transparent;border:0;padding:8px}.am-banner-dots button:after{content:"";width:8px;height:8px;background:#ffffff66;border-radius:50%}.am-banner-dots button[aria-current="true"]:after{background:white;width:18px;border-radius:6px}.am-banner-nav button:focus-visible,.am-banner-slide:focus-visible{outline:3px solid white;outline-offset:-5px}.am-banner-status{position:absolute;inset-inline-end:26px;bottom:29px;font-size:14px;color:#e7f6ff}@media(max-width:767px){.am-banner-slide{min-height:320px;padding:36px 22px 86px}.am-banner-copy h2{font-size:28px;margin:10px 0 20px}.am-banner-kicker{font-size:14px}.am-banner-cta{font-size:16px}.am-banner-nav{bottom:15px;gap:8px;inset-inline:8px}.am-banner-status{display:none}.am-banner-slide:has(.am-banner-picture){aspect-ratio:39/32}}';style.textContent+=".am-banner-carousel{display:grid!important}.am-banner-slide{grid-area:1/1!important;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .65s cubic-bezier(.22,.61,.36,1),visibility 0s linear .65s}.am-banner-slide.am-banner-active{opacity:1;visibility:visible;pointer-events:auto;transition:opacity .65s cubic-bezier(.22,.61,.36,1),visibility 0s linear 0s}.am-banner-nav,.am-banner-status{z-index:3}@media(prefers-reduced-motion:reduce){.am-banner-slide{transition:none!important}}";style.textContent+=".am-banner-slide:has(.am-banner-picture){min-height:0!important;aspect-ratio:4/1!important;padding:0!important}.am-banner-nav{position:relative!important;grid-area:2/1!important;inset:auto!important;bottom:auto!important;min-height:58px;box-sizing:border-box;padding:8px 16px;margin:0;background:#0756d9}.am-banner-status{bottom:19px!important;direction:ltr}.am-banner-picture img{object-fit:contain!important}@media(max-width:767px){.am-banner-slide:has(.am-banner-picture){min-height:0!important;aspect-ratio:39/32!important}.am-banner-nav{min-height:58px;padding:8px 10px}}";style.textContent+=".am-banner-carousel{grid-template-rows:auto!important;overflow:hidden;background:transparent!important}.am-banner-slide:has(.am-banner-picture){width:100%!important;min-height:0!important;aspect-ratio:4/1!important}.am-banner-picture,.am-banner-picture img{display:block!important;width:100%!important;height:100%!important}.am-banner-picture img{object-fit:contain!important;object-position:center!important}.am-banner-nav{position:absolute!important;grid-area:auto!important;inset:0!important;transform:none!important;min-height:0!important;height:100%!important;width:100%!important;padding:0!important;background:transparent!important;display:block!important;pointer-events:none}.am-banner-nav>button{position:absolute!important;top:50%!important;bottom:auto!important;pointer-events:auto;background:#082b5970!important;border-color:#ffffffaa!important;box-shadow:0 2px 8px #0002;backdrop-filter:blur(5px);transform:translateY(-50%)}.am-banner-nav>button:first-child{right:12px!important;left:auto!important}.am-banner-nav>button:nth-of-type(2){left:12px!important;right:auto!important}.am-banner-nav>button:last-child{top:auto!important;bottom:8px!important;left:12px!important;right:auto!important;transform:none!important;width:32px!important;height:32px!important;font-size:16px!important}.am-banner-dots{position:absolute!important;bottom:8px!important;left:50%!important;transform:translateX(-50%);pointer-events:auto;background:#082b5970;border-radius:24px;padding:0 4px;backdrop-filter:blur(5px)}.am-banner-status{display:none!important}@media(max-width:767px){.am-banner-slide:has(.am-banner-picture){aspect-ratio:39/32!important}.am-banner-nav>button{width:34px!important;height:34px!important;font-size:20px!important}.am-banner-nav>button:first-child{right:6px!important}.am-banner-nav>button:nth-of-type(2){left:6px!important}.am-banner-dots{bottom:5px!important;padding:0 2px}.am-banner-dots button{width:20px;height:24px;padding:6px}.am-banner-dots button:after{width:6px;height:6px}.am-banner-dots button[aria-current=\"true\"]:after{width:12px}.am-banner-nav>button:last-child{bottom:5px!important;left:6px!important;width:26px!important;height:26px!important;font-size:14px!important}}";style.textContent+="@media(min-width:768px){.am-banner-slide:has(.am-banner-picture){aspect-ratio:3/1!important;background:#edfaff!important;overflow:hidden}.am-banner-slide:has(.am-banner-picture):before{content:\"\";position:absolute;inset:-24px;background-image:var(--am-banner-art);background-size:cover;background-position:center;filter:blur(20px);opacity:1;pointer-events:none}.am-banner-picture{z-index:1}.am-banner-picture img{object-fit:contain!important}}";root.append(style);
  const carousel=document.createElement('div');carousel.className='am-banner-carousel';carousel.setAttribute('role','region');carousel.setAttribute('aria-roledescription','عارض شرائح');carousel.setAttribute('aria-label','عروض الأجهزة وباقات الصيانة');let current=0;
  const slides=banners.map((item,index)=>{const a=document.createElement('a');a.className='am-banner-slide';
const previewPage=new URL(location.href);
const bannerTarget=new URL(item.url,previewPage.href);
const storePrefix='/almoalej.com';
const inStorePreview=previewPage.pathname===storePrefix||previewPage.pathname.startsWith(storePrefix+'/');
if(previewPage.hostname==='salla.sa'&&inStorePreview&&previewPage.searchParams.has('preview')&&['almoalej.com','salla.sa'].includes(bannerTarget.hostname)){
 bannerTarget.protocol=previewPage.protocol;bannerTarget.host=previewPage.host;
 if(bannerTarget.pathname!==storePrefix&&!bannerTarget.pathname.startsWith(storePrefix+'/'))bannerTarget.pathname=storePrefix+bannerTarget.pathname;
 bannerTarget.searchParams.set('preview',previewPage.searchParams.get('preview'));a.href=bannerTarget.href;
}else{a.href=item.url;}
a.setAttribute('aria-label',item.title);a.dataset.bannerIndex=index;a.hidden=index!==0;if(item.desktopImage)a.style.setProperty('--am-banner-art','url("'+item.desktopImage+'")');
   if(item.desktopImage){const picture=document.createElement('picture');picture.className='am-banner-picture';if(item.mobileImage){const source=document.createElement('source');source.media='(max-width:767px)';source.srcset=item.mobileImage;picture.append(source)}const img=document.createElement('img');img.src=item.desktopImage;img.alt=item.title;picture.append(img);a.append(picture)}else{const copy=document.createElement('div');copy.className='am-banner-copy';const kicker=document.createElement('div');kicker.className='am-banner-kicker';kicker.textContent=index<4?'عروض الأجهزة والباقات':'باقات الصيانة';const title=document.createElement('h2');title.textContent=item.title;const cta=document.createElement('span');cta.className='am-banner-cta';cta.textContent=index<4?'استعرض العرض':'استعرض الباقة';copy.append(kicker,title,cta);a.append(copy)}carousel.append(a);return a;});
  const nav=document.createElement('div');nav.className='am-banner-nav';const prev=document.createElement('button');prev.type='button';prev.textContent='→';prev.setAttribute('aria-label','البانر السابق');const next=document.createElement('button');next.type='button';next.textContent='←';next.setAttribute('aria-label','البانر التالي');const dots=document.createElement('div');dots.className='am-banner-dots';const status=document.createElement('span');status.className='am-banner-status';status.setAttribute('aria-live','polite');
  const dotButtons=banners.map((item,index)=>{const b=document.createElement('button');b.type='button';b.setAttribute('aria-label','عرض بانر '+item.title);b.addEventListener('click',()=>show(index));dots.append(b);return b});
  function show(index){current=(index+banners.length)%banners.length;slides.forEach((el,i)=>{const active=i===current;el.hidden=false;el.classList.toggle('am-banner-active',active);el.setAttribute('aria-hidden',String(!active));el.inert=!active;el.tabIndex=active?0:-1});dotButtons.forEach((el,i)=>el.setAttribute('aria-current',String(i===current)));status.textContent=(current+1)+' / '+banners.length;}
  prev.addEventListener('click',()=>show(current-1));next.addEventListener('click',()=>show(current+1));nav.append(prev,dots,next);carousel.append(nav,status);root.append(carousel);show(0);
  let autoplayTimer=null,paused=false,hovered=false;
  const pause=document.createElement('button');pause.type='button';pause.textContent='Ⅱ';pause.setAttribute('aria-label','إيقاف التبديل التلقائي');pause.setAttribute('aria-pressed','false');nav.append(pause);
  carousel.dataset.autoplayInterval='5000';status.setAttribute('aria-live','off');
  function restartAutoplay(){clearInterval(autoplayTimer);autoplayTimer=null;if(paused||hovered||document.hidden||carousel.contains(root.activeElement))return;autoplayTimer=setInterval(()=>{if(!carousel.isConnected){clearInterval(autoplayTimer);return;}show(current+1)},5000);}
  pause.addEventListener('click',()=>{paused=!paused;pause.textContent=paused?'▶':'Ⅱ';pause.setAttribute('aria-pressed',String(paused));pause.setAttribute('aria-label',paused?'تشغيل التبديل التلقائي':'إيقاف التبديل التلقائي');restartAutoplay()});
  nav.addEventListener('click',restartAutoplay);carousel.addEventListener('pointerenter',event=>{if(event.pointerType==='mouse'){hovered=true;restartAutoplay()}});carousel.addEventListener('pointerleave',event=>{if(event.pointerType==='mouse'){hovered=false;restartAutoplay()}});carousel.addEventListener('focusin',restartAutoplay);carousel.addEventListener('focusout',()=>setTimeout(restartAutoplay,0));document.addEventListener('visibilitychange',restartAutoplay);
  carousel.style.touchAction='pan-y pinch-zoom';let swipeGesture=null,suppressClickUntil=0;
  carousel.addEventListener('pointerdown',event=>{if(event.pointerType==='mouse'||!event.isPrimary||event.target.closest('.am-banner-nav'))return;swipeGesture={id:event.pointerId,x:event.clientX,y:event.clientY};clearInterval(autoplayTimer);autoplayTimer=null;},{passive:true});
  carousel.addEventListener('pointermove',event=>{if(!swipeGesture||event.pointerId!==swipeGesture.id)return;const dx=event.clientX-swipeGesture.x,dy=event.clientY-swipeGesture.y;if(Math.abs(dy)>12&&Math.abs(dy)>Math.abs(dx)){swipeGesture=null;restartAutoplay();return;}if(Math.abs(dx)>12&&Math.abs(dx)>Math.abs(dy))event.preventDefault();},{passive:false});
  carousel.addEventListener('pointerup',event=>{if(!swipeGesture||event.pointerId!==swipeGesture.id)return;const dx=event.clientX-swipeGesture.x,dy=event.clientY-swipeGesture.y;swipeGesture=null;if(Math.abs(dx)>=45&&Math.abs(dx)>Math.abs(dy)*1.25){suppressClickUntil=Date.now()+800;show(current+(dx>0?1:-1));carousel.dataset.lastSwipe=dx>0?'right':'left';}restartAutoplay();},{passive:true});
  carousel.addEventListener('pointercancel',()=>{swipeGesture=null;restartAutoplay()},{passive:true});
  carousel.addEventListener('click',event=>{if(Date.now()<suppressClickUntil&&!event.target.closest('.am-banner-nav')){event.preventDefault();event.stopImmediatePropagation();}},true);
  carousel.dataset.swipeEnabled='true';
restartAutoplay();return true;
 }
 function start(){if(mount())return;const timer=setInterval(()=>{if(mount()||++attempts>=40)clearInterval(timer)},250)}
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Almoalej draft shopping tools. Product facts are supplied from reviewed store pages. */
(function(){
  const catalogue = [{"id":"1775024552","image":"https://cdn.files.salla.network/other/609952933/9b28ae68-e24a-48cd-8a26-1894aa1a26c7-original.webp","price":"٤٩٩","title":"جهاز تحلية المعالج – 7 مراحل","url":"https://almoalej.com/%D8%AC%D9%87%D8%A7%D8%B2-%D8%AA%D8%AD%D9%84%D9%8A%D8%A9-%D8%A7%D9%84%D9%85%D8%B9%D8%A7%D9%84%D8%AC-7-%D9%85%D8%B1%D8%A7%D8%AD%D9%84/p1775024552","description":"جهاز تحلية المعالج – 7 مراحل. يضم فلاتر قطنية وكربونية، وغشاء ممبرين، وفلتر بوست كاربون، وفلتر مينرال، وفلتر ألكالاين، مع خزان وحنفية. يُرجى مراجعة متطلبات التركيب والتوصيلات قبل الطلب.","kind":"device"},{"id":"1808009306","image":"https://cdn.files.salla.network/other/609952933/b1980c7c-9080-4559-9de1-5f958e7ed829-standard.webp","price":"١٢٤٩","title":"عرض الفخامة – جهاز نانو تكنولوجي مع برادة ذاتية","url":"https://almoalej.com/%D8%B9%D8%B1%D8%B6-%D8%A7%D9%84%D9%81%D8%AE%D8%A7%D9%85%D8%A9-%D8%AC%D9%87%D8%A7%D8%B2-%D9%86%D8%A7%D9%86%D9%88-%D8%AA%D9%83%D9%86%D9%88%D9%84%D9%88%D8%AC%D9%8A-%D9%85%D8%B9-%D8%A8%D8%B1%D8%A7%D8%AF%D8%A9-%D8%B0%D8%A7%D8%AA%D9%8A%D8%A9/p1808009306","description":"عرض يجمع جهاز نانو تكنولوجي مع برادة مياه ذاتية التعبئة، ويشمل الخزان والحنفية. اختر شكل الجهاز، مربعًا أو مستطيلًا، ولون واجهته ولون البرادة من الخيارات المصورة. تظهر كل تركيبة في صورتها المخصصة.","kind":"offer"},{"id":"543722590","image":"https://cdn.files.salla.network/other/609952933/ee4be794-a27c-4e15-bd4a-7f1b1d41c9c9-standard.webp","price":"١٧٩٩","title":"العرض الكبير – كلاسيك بيور مع برادة ذاتية وجامبو ثلاثي","url":"https://almoalej.com/%D8%A7%D9%84%D8%B9%D8%B1%D8%B6-%D8%A7%D9%84%D9%83%D8%A8%D9%8A%D8%B1-%D9%83%D9%84%D8%A7%D8%B3%D9%8A%D9%83-%D8%A8%D9%8A%D9%88%D8%B1-%D9%85%D8%B9-%D8%A8%D8%B1%D8%A7%D8%AF%D8%A9-%D8%B0%D8%A7%D8%AA%D9%8A%D8%A9-%D9%88%D8%AC%D8%A7%D9%85%D8%A8%D9%88-%D8%AB%D9%84%D8%A7%D8%AB%D9%8A/p543722590","description":"عرض يجمع جهاز تحلية كلاسيك بيور بسبع مراحل، مع خزان وحنفية، وبرادة مياه ذاتية التعبئة، وهاوس جامبو ثلاثي 20 بوصة. تتوفر البرادة بالأبيض والأسود والفضي حسب الاختيار المرتبط بصورته.","kind":"offer"},{"id":"1916119903","image":"https://cdn.files.salla.network/other/609952933/3b8fafb1-e869-4e9e-ad0d-0363a89667f4-standard.webp","price":"٨٤٩","title":"عرض الكلاسيك","url":"https://almoalej.com/%D8%B9%D8%B1%D8%B6-%D8%A7%D9%84%D9%83%D9%84%D8%A7%D8%B3%D9%8A%D9%83/p1916119903","description":"عرض يجمع جهاز تحلية بسبع مراحل مع برادة عادية وقارورة. اختر هذه التجميعة عند الرغبة في شراء المكونات الثلاثة معًا.","kind":"offer"},{"id":"77942364","image":"https://cdn.files.salla.network/other/609952933/d7cb417a-dc0b-486f-8efe-b909852b3d0a-standard.webp","price":"٩٤٩","title":"عرض الكلاسيك بلس","url":"https://almoalej.com/%D8%B9%D8%B1%D8%B6-%D8%A7%D9%84%D9%83%D9%84%D8%A7%D8%B3%D9%8A%D9%83-%D8%A8%D9%84%D8%B3/p77942364","description":"عرض يجمع جهاز تحلية كلاسيك بيور بسبع مراحل مع برادة ذاتية التعبئة. يجمع هذا الخيار الجهاز والبرادة ضمن بند واحد لتسهيل اختيار التجميعة المطلوبة.","kind":"offer"},{"id":"1108966318","image":"https://cdn.files.salla.network/other/609952933/d70a8d7b-0adb-4ff1-9d77-798f8a966b47-original.webp","price":"٤٩٩","title":"جهاز تحلية كلاسيك بيور – 7 مراحل","url":"https://almoalej.com/%D8%AC%D9%87%D8%A7%D8%B2-%D8%AA%D8%AD%D9%84%D9%8A%D8%A9-%D9%83%D9%84%D8%A7%D8%B3%D9%8A%D9%83-%D8%A8%D9%8A%D9%88%D8%B1-7-%D9%85%D8%B1%D8%A7%D8%AD%D9%84/p1108966318","description":"جهاز تحلية كلاسيك بيور – 7 مراحل. يضم فلاتر قطنية وكربونية، وغشاء ممبرين، وفلتر بوست كاربون، وفلتر مينرال، وفلتر ألكالاين، مع خزان وحنفية. يُرجى مراجعة متطلبات التركيب والتوصيلات قبل الطلب.","kind":"device"},{"id":"1000986793","image":"https://cdn.files.salla.network/other/609952933/2ee9158d-3ba1-4f21-9196-fcda8668f5e0-original.webp","price":"٥٩٩","title":"جهاز تحلية كلاسيك بيور ستاند – 7 مراحل","url":"https://almoalej.com/%D8%AC%D9%87%D8%A7%D8%B2-%D8%AA%D8%AD%D9%84%D9%8A%D8%A9-%D9%83%D9%84%D8%A7%D8%B3%D9%8A%D9%83-%D8%A8%D9%8A%D9%88%D8%B1-%D8%B3%D8%AA%D8%A7%D9%86%D8%AF-7-%D9%85%D8%B1%D8%A7%D8%AD%D9%84/p1000986793","description":"جهاز تحلية كلاسيك بيور ستاند – 7 مراحل. يضم فلاتر قطنية وكربونية، وغشاء ممبرين، وفلتر بوست كاربون، وفلتر مينرال، وفلتر ألكالاين، مع خزان وحنفية. يُرجى مراجعة متطلبات التركيب والتوصيلات قبل الطلب.","kind":"device"},{"id":"825763252","image":"https://cdn.files.salla.network/other/609952933/c77ddbf7-2110-4cd8-b67b-d64807f22b15-standard.webp","price":"٤٩٩","title":"جهاز تحلية بلاك هورس – 7 مراحل","url":"https://almoalej.com/%D8%AC%D9%87%D8%A7%D8%B2-%D8%AA%D8%AD%D9%84%D9%8A%D8%A9-%D8%A8%D9%84%D8%A7%D9%83-%D9%87%D9%88%D8%B1%D8%B3-7-%D9%85%D8%B1%D8%A7%D8%AD%D9%84/p825763252","description":"جهاز تحلية بلاك هورس – 7 مراحل. يضم فلاتر قطنية وكربونية، وغشاء ممبرين، وفلتر بوست كاربون، وفلتر مينرال، وفلتر ألكالاين، مع خزان وحنفية. يُرجى مراجعة متطلبات التركيب والتوصيلات قبل الطلب.","kind":"device"},{"id":"1558340534","image":"https://cdn.files.salla.network/other/609952933/fc6ab9c0-5702-4232-a9f2-74273029a902-original.webp","price":"٦٤٩","title":"جهاز تحلية بلاك ستار ستاند – 7 مراحل","url":"https://almoalej.com/%D8%AC%D9%87%D8%A7%D8%B2-%D8%AA%D8%AD%D9%84%D9%8A%D8%A9-%D8%A8%D9%84%D8%A7%D9%83-%D8%B3%D8%AA%D8%A7%D8%B1-%D8%B3%D8%AA%D8%A7%D9%86%D8%AF-7-%D9%85%D8%B1%D8%A7%D8%AD%D9%84/p1558340534","description":"جهاز تحلية بلاك ستار ستاند – 7 مراحل. يضم فلاتر قطنية وكربونية، وغشاء ممبرين، وفلتر بوست كاربون، وفلتر مينرال، وفلتر ألكالاين، مع خزان وحنفية. يُرجى مراجعة متطلبات التركيب والتوصيلات قبل الطلب.","kind":"device"},{"id":"1031859859","image":"https://cdn.files.salla.network/other/609952933/b4ab4d02-486d-43b2-99dd-03e4c8f6a450-original.webp","price":"١١٫٥","title":"فلتر قطني 10 بوصة","url":"https://almoalej.com/%D9%81%D9%84%D8%AA%D8%B1-%D9%82%D8%B7%D9%86%D9%8A-10-%D8%A8%D9%88%D8%B5%D8%A9/p1031859859","description":"فلتر قطني 10 انش من مجموعة الفلاتر في متجر المعالج. طابق نوع الفلتر ومقاسه مع متطلبات جهازك قبل اختيار البديل.","kind":"filter","size":"10","filterType":"قطني"},{"id":"1498033309","image":"https://cdn.files.salla.network/other/609952933/9c932fcb-5920-4b84-868a-059053b9865d-original.webp","price":"٢٣","title":"فلتر كربون حبيبي UDF – 10 بوصات","url":"https://almoalej.com/%D9%81%D9%84%D8%AA%D8%B1-%D9%83%D8%B1%D8%A8%D9%88%D9%86-%D8%AD%D8%A8%D9%8A%D8%A8%D9%8A-udf-10-%D8%A8%D9%88%D8%B5%D8%A7%D8%AA/p1498033309","description":"فلتر حبيبات كربون نشط مقاس10 إنش، ضمن فلاتر المعالج. يُختار البديل بعد مطابقة المقاس والتوصيلات مع جهاز المياه.","kind":"filter","size":"10","filterType":"حبيبي"},{"id":"258805148","image":"https://cdn.files.salla.network/other/609952933/28de6f4f-7840-4661-9066-cef743b2f416-original.webp","price":"٢٩","title":"فلتر كربوني صلب 10 بوصة","url":"https://almoalej.com/%D9%81%D9%84%D8%AA%D8%B1-%D9%83%D8%B1%D8%A8%D9%88%D9%86%D9%8A-%D8%B5%D9%84%D8%A8-10-%D8%A8%D9%88%D8%B5%D8%A9/p258805148","description":"فلتر كربوني صلب 10 انش من مجموعة الفلاتر في متجر المعالج. طابق نوع الفلتر ومقاسه مع متطلبات جهازك قبل اختيار البديل.","kind":"filter","size":"10","filterType":"صلب"},{"id":"1173894118","image":"https://cdn.files.salla.network/other/609952933/7bb1e18b-1d9e-4a0c-b485-13d32f30662d-original.webp","price":"٤٩","title":"فلتر قطني 12 بوصة - PP","url":"https://almoalej.com/%D9%81%D9%84%D8%AA%D8%B1-%D9%82%D8%B7%D9%86%D9%8A-12-%D8%A8%D9%88%D8%B5%D8%A9-pp/p1173894118","description":"فلتر برادة قطني 12 انش من مجموعة الفلاتر في متجر المعالج. طابق نوع الفلتر ومقاسه مع متطلبات جهازك قبل اختيار البديل.","kind":"filter","size":"12","filterType":"قطني"}];
  const installationCities=['الأحساء','الدمام','الرياض','تبوك'];
  const coverage='شحن لجميع مدن المملكة، وتركيب في الأحساء والدمام والرياض وتبوك.';
  const normalize=s=>String(s||'').replace(/[أإآ]/g,'ا').replace(/ى/g,'ي').replace(/ة/g,'ه').replace(/\s+/g,' ').trim();
  const canInstall=city=>['الاحساء','الدمام','الرياض','تبوك'].includes(normalize(city));
  const number=s=>Number(String(s||'').replace(/[٠-٩]/g,c=>'٠١٢٣٤٥٦٧٨٩'.indexOf(c)).replace(/[۰-۹]/g,c=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(c)).replace('٫','.').replace(/[^\d.]/g,''));
  const el=(tag,cls,text)=>{const e=document.createElement(tag);if(cls)e.className=cls;if(text!==undefined)e.textContent=text;return e};
  const wa=text=>'https://wa.me/966533557999?text='+encodeURIComponent(text);
  function track(action,extra={}){const event={event:'am_shopping_tool',tool_action:action,...extra};document.dispatchEvent(new CustomEvent('almoalej:analytics',{detail:event}));if(Array.isArray(window.dataLayer))window.dataLayer.push(event);}
  function productLink(p){const url=new URL(p.url);if(new URLSearchParams(location.search).has('preview')){url.searchParams.set('preview','1');if(location.hostname==='salla.sa'){url.hostname='salla.sa';url.pathname='/almoalej.com'+url.pathname;}}return url.href;}
  function tags(p){if(p.id==='1808009306')return ['ذاتية','نانو'];if(p.id==='543722590')return ['ذاتية','جامبو'];if(p.id==='1916119903')return ['عادية'];if(p.id==='77942364')return ['ذاتية'];return ['جهاز'];}
  function livePrice(p){const card=document.querySelector('.s-product-card-entry[id="'+p.id+'"]');const price=card?.querySelector('.s-product-card-sale-price h4,.s-product-card-price');const text=price?.textContent.trim();return text&&/[0-9٠-٩۰-۹]/.test(text)?text:null;}
  function priceLabel(p){const price=livePrice(p);return price===null?'السعر في صفحة المنتج':price+' ر.س';}
  function link(text,href,cls='am-tool-link'){const a=el('a',cls,text);a.href=href;return a;}
  function button(text,fn,cls='am-tool-button'){const b=el('button',cls,text);b.type='button';b.addEventListener('click',fn);return b;}
  function field(label,control){const wrap=el('label','am-tool-field');wrap.append(el('span','',label),control);return wrap;}
  function select(values){const s=el('select');values.forEach(([value,title])=>{const o=el('option','',title);o.value=value;s.append(o)});return s;}
  function input(type,placeholder){const i=el('input');i.type=type;if(placeholder)i.placeholder=placeholder;return i;}
  function start(){
    if(getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return;
    if(document.getElementById('am-shopping-tools-dialog'))return;
    const main=document.getElementById('main-content');if(!main)return;
    const style=el('style');style.textContent=".am-shopping-hub{margin:34px 0 6px;padding:32px;border:1px solid #d8e7f4;border-radius:22px;background:linear-gradient(125deg,#f1faff,#fff);text-align:right;color:#082b59}.am-shopping-hub h2{font-size:30px!important;font-weight:800;margin:6px 0!important}.am-tool-eyebrow{font-size:13px;font-weight:700;color:#0756d9}.am-tool-muted{color:#52677f;line-height:1.9;font-size:16px}.am-hub-actions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin:24px 0}.am-hub-card{display:flex;flex-direction:column;align-items:flex-start;text-align:right;gap:12px;min-height:218px;padding:24px;background:#fff;border:1px solid #d1e3f2;border-radius:16px;color:#082b59;cursor:pointer;transition:transform .2s,box-shadow .2s}.am-hub-card:hover{transform:translateY(-3px);box-shadow:0 10px 28px #082b5910}.am-hub-card strong{font-size:20px;font-weight:800}.am-hub-card>span:not(.am-hub-number):not(.am-hub-arrow){font-size:15px;color:#52677f;line-height:1.8}.am-hub-number{display:grid;place-items:center;width:38px;height:38px;border-radius:12px;color:#0756d9;background:#edf7ff;font-weight:800}.am-hub-arrow{margin-top:auto;color:#0756d9;font-weight:700}.am-hub-links{display:flex;flex-wrap:wrap;align-items:center;gap:12px}.am-tool-button,.am-tool-secondary{display:inline-flex;align-items:center;justify-content:center;min-height:46px;padding:10px 20px;border-radius:10px;font:700 16px/1.6 Tajawal,Tahoma,Arial;cursor:pointer;text-decoration:none;border:1px solid #0756d9;box-sizing:border-box}.am-tool-button{background:#0756d9;color:#fff!important}.am-tool-secondary{background:#fff;color:#0756d9}.am-tool-text-button,.am-card-compare{min-height:44px;color:#0756d9;background:none;border:0;font:700 15px/1.6 Tajawal,Tahoma,Arial;text-decoration:underline;text-underline-offset:5px;cursor:pointer}.am-card-compare{width:100%;font-size:14px;text-decoration:none;border-top:1px solid #e6eef6;margin-top:6px}.am-tools-dialog{width:min(1120px,calc(100vw - 40px));max-height:90dvh;padding:0;border:1px solid #d7e4ef;border-radius:22px;color:#082b59;background:white;box-shadow:0 30px 100px #082b5930;font-family:Tajawal,Tahoma,Arial;overflow:auto}.am-tools-dialog::backdrop{background:#061b3a99;backdrop-filter:blur(3px)}.am-tools-head{position:sticky;top:0;z-index:5;display:flex;align-items:center;justify-content:space-between;gap:20px;padding:20px 26px;background:#fff;border-bottom:1px solid #e2edf6}.am-tools-head h2{font-size:24px;line-height:1.5;font-weight:800;margin:0}.am-tool-close{min-width:58px;min-height:44px;border:1px solid #d4e1ec;border-radius:10px;background:#f6faff;color:#082b59;font-weight:700;cursor:pointer}.am-tools-tabs{display:flex;gap:8px;padding:16px 26px;border-bottom:1px solid #e2edf6;overflow-x:auto}.am-tools-tab{min-height:44px;white-space:nowrap;border:1px solid #d7e5f1;border-radius:22px;padding:8px 18px;background:#fff;color:#426080;font-weight:700;cursor:pointer}.am-tools-tab[aria-selected=true]{color:#fff;background:#0756d9;border-color:#0756d9}.am-tools-body{padding:26px}.am-tools-body h3{font-size:23px;font-weight:800;line-height:1.6;margin:0 0 12px}.am-tool-form{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;margin:20px 0}.am-tool-form>.am-tool-button{align-self:end}.am-tool-field{display:flex;flex-direction:column;gap:8px;font-size:15px;color:#244563;font-weight:600;min-width:0}.am-tool-field input,.am-tool-field select{min-height:48px;border:1px solid #bfd2e3;border-radius:10px;background:#fff;padding:10px 12px;color:#082b59;font:400 16px/1.6 Tajawal,Tahoma,Arial;width:100%;box-sizing:border-box}.am-tool-field:has(input[type=checkbox]){flex-direction:row-reverse;align-items:center;justify-content:flex-end;gap:10px}.am-tool-field input[type=checkbox]{width:20px;min-height:20px;height:20px;accent-color:#0756d9;flex:none}.am-tool-note{padding:14px 16px;border:1px solid #d8e8f5;border-radius:12px;background:#f4faff;color:#355773;font-size:15px;line-height:1.9;margin:16px 0}.am-tool-results{margin-top:24px}.am-tool-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin:18px 0}.am-tool-product{min-width:0;border:1px solid #d9e5f0;border-radius:16px;padding:18px;display:flex;flex-direction:column;gap:10px;background:#fff}.am-tool-product img{width:100%;height:160px;object-fit:contain}.am-tool-product h3{font-size:17px;min-height:55px;margin:0}.am-tool-product p{margin:0}.am-tool-price{color:#0756d9;font-size:24px;font-weight:800;margin-top:auto!important}.am-tool-link{display:inline-block;color:#0756d9;font-weight:700;text-decoration:underline;text-underline-offset:4px;line-height:1.8;padding-block:8px}.am-tool-help{padding:22px;border:1px solid #d8e8f5;border-radius:16px;margin-top:24px}.am-tool-help input{max-width:480px}.am-compare-options{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:20px 0}.am-compare-options>label{padding:12px;border:1px solid #d5e5f2;border-radius:12px;cursor:pointer}.am-compare-scroll{overflow:auto;border:1px solid #d7e5f1;border-radius:14px}.am-compare-table{border-collapse:collapse;width:100%;min-width:620px;text-align:right;line-height:1.9;font-size:15px}.am-compare-table caption{padding:14px;font-weight:800}.am-compare-table th,.am-compare-table td{border:1px solid #e0eaf4;padding:16px;vertical-align:top;min-width:140px}.am-compare-table thead th{background:#eef8ff;color:#082b59}.am-compare-table tbody th{background:#f8fbfe;font-weight:700}.am-tools-body ul{padding-inline-start:24px;line-height:2}.am-product-guide{padding:22px;margin:24px 0;border:1px solid #d8e7f4;background:#fbfdff;border-radius:18px;color:#082b59}.am-product-guide h2{font-size:23px;font-weight:800;margin:0 0 12px}.am-product-guide details{border-bottom:1px solid #dce8f3;padding:12px 0;line-height:1.9}.am-product-guide summary{min-height:40px;font-weight:700;cursor:pointer}.am-product-guide .am-hub-links{margin-top:18px}.am-shopping-hub button:focus-visible,.am-tools-dialog :focus-visible,.am-product-guide :focus-visible{outline:3px solid #0756d9;outline-offset:3px}.am-tools-dialog input:invalid:not(:placeholder-shown){box-shadow:none}@media(max-width:767px){.am-shopping-hub{padding:20px;margin-top:24px}.am-shopping-hub h2{font-size:25px!important}.am-hub-actions{grid-template-columns:1fr;gap:12px}.am-hub-card{padding:18px;min-height:170px}.am-hub-card strong{font-size:19px}.am-tools-dialog{width:calc(100vw - 16px);max-height:94dvh;border-radius:16px}.am-tools-head{padding:14px 16px}.am-tools-head h2{font-size:20px}.am-tools-tabs{padding:12px;gap:6px}.am-tools-tab{padding:8px 13px;font-size:14px}.am-tools-body{padding:18px}.am-tool-form{grid-template-columns:1fr}.am-tool-grid{grid-template-columns:1fr}.am-tool-product img{height:190px}.am-compare-options{grid-template-columns:1fr}.am-product-guide{padding:16px}.am-hub-links{gap:8px}.am-tool-button,.am-tool-secondary{font-size:15px}.am-tool-muted{font-size:15px}}@media(prefers-reduced-motion:reduce){.am-hub-card{transition:none;transform:none!important}}\n";document.head.append(style);
    let currentTab='choose',opener=null,selected=new Set(),group='offers';
    const dialog=el('dialog','am-tools-dialog');dialog.id='am-shopping-tools-dialog';dialog.dir='rtl';dialog.setAttribute('aria-labelledby','am-tools-dialog-title');
    const header=el('div','am-tools-head'),heading=el('h2','','اختيار أوضح، وطلب أسهل');heading.id='am-tools-dialog-title';header.append(heading,button('إغلاق',()=>dialog.close(),'am-tool-close'));
    const tabs=el('div','am-tools-tabs');tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','أدوات التسوق');const body=el('div','am-tools-body');body.id='am-tools-panel';body.setAttribute('role','tabpanel');
    const tabDefs=[['choose','اختيار الجهاز'],['compare','المقارنة'],['filter','اختيار الفلتر'],['install','التركيب والشحن'],['remind','تذكير الصيانة']];
    tabDefs.forEach(([id,title])=>{const b=button(title,()=>render(id),'am-tools-tab');b.dataset.tab=id;b.id='am-tool-tab-'+id;b.setAttribute('role','tab');b.setAttribute('aria-controls',body.id);tabs.append(b)});
    tabs.addEventListener('keydown',event=>{if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;event.preventDefault();const buttons=Array.from(tabs.children);let n=buttons.indexOf(document.activeElement);n=event.key==='Home'?0:event.key==='End'?buttons.length-1:(n+(event.key==='ArrowLeft'?1:-1)+buttons.length)%buttons.length;render(buttons[n].dataset.tab);buttons[n].focus()});
    dialog.append(header,tabs,body);document.body.append(dialog);dialog.addEventListener('click',e=>{if(e.target===dialog&&e.offsetX<0)dialog.close()});dialog.addEventListener('close',()=>opener?.focus());
    function open(tab,source){opener=source||document.activeElement;render(tab);if(!dialog.open)dialog.showModal();track('open',{tool:tab});}
    function render(tab){currentTab=tab;if(tab==='remind')tabs.style.setProperty('display','none','important');else tabs.style.removeProperty('display');tabs.querySelectorAll('button').forEach(b=>{b.setAttribute('aria-selected',String(b.dataset.tab===tab));b.tabIndex=b.dataset.tab===tab?0:-1});body.setAttribute('aria-labelledby','am-tool-tab-'+tab);body.replaceChildren();({choose:chooseView,compare:compareView,filter:filterView,install:installView,remind:remindView})[tab]();}
    function notice(text){return el('p','am-tool-note',text)}
    function productCard(p,reason){const c=el('article','am-tool-product');const img=el('img');img.src=p.image;img.alt=p.title;img.loading='lazy';c.append(img,el('h3','',p.title));if(reason)c.append(el('p','am-tool-muted',reason));c.append(el('p','am-tool-price',priceLabel(p)),link('تفاصيل المنتج وخياراته',productLink(p),'am-tool-button'));const b=button(selected.has(p.id)?'مضاف للمقارنة':'أضف للمقارنة',()=>{if(selected.has(p.id)){selected.delete(p.id)}else if(selected.size<3){selected.add(p.id)}else{b.textContent='الحد الأقصى 3 منتجات';return;}b.textContent=selected.has(p.id)?'مضاف للمقارنة':'أضف للمقارنة';b.setAttribute('aria-pressed',String(selected.has(p.id)));track('compare_select',{product_id:p.id})},'am-tool-secondary');b.setAttribute('aria-pressed',String(selected.has(p.id)));if(p.kind!=='filter')c.append(b);return c;}
    function chooseView(){body.append(el('h3','','ما التجميعة التي تبحث عنها؟'),el('p','am-tool-muted','نرشّح حسب المكونات والميزانية. لتقييم جودة المياه والسعة المطلوبة، تواصل مع فريقنا.'));
      const form=el('form','am-tool-form'),need=select([['all','أريد استعراض الخيارات'],['جهاز','جهاز تحلية فقط'],['عادية','جهاز مع برادة عادية وقارورة'],['ذاتية','جهاز مع برادة ذاتية التعبئة'],['جامبو','تجميعة تشمل جامبو ثلاثي']]),budget=input('number','مثال: 1500'),city=input('text','اكتب مدينتك');budget.min='0';budget.step='1';city.autocomplete='address-level2';form.append(field('الاحتياج',need),field('الميزانية القصوى — اختياري، قبل التركيب والشحن',budget),field('المدينة — لتوضيح الخدمة',city));const submit=el('button','am-tool-button','اعرض الخيارات المناسبة');submit.type='submit';form.append(submit);const results=el('div','am-tool-results');results.setAttribute('aria-live','polite');body.append(form,results);
      form.addEventListener('submit',event=>{event.preventDefault();results.replaceChildren();const products=catalogue.filter(p=>!p.kind||p.kind!=='filter').filter(p=>need.value==='all'||tags(p).includes(need.value)).filter(p=>{if(!budget.value)return true;const price=livePrice(p);return price!==null&&number(price)<=Number(budget.value)});if(city.value.trim())results.append(notice(canInstall(city.value)?'مدينتك ضمن مدن التركيب. راجع خدمة التركيب والمدينة والأجرة للمنتجات المؤهلة في السلة.':'الشحن متاح لمدينتك. خدمة التركيب لدينا في الأحساء والدمام والرياض وتبوك فقط.'));results.append(notice('راجع السعر ومواصفات المنتج في صفحته، وخيارات الخدمة والإجمالي في السلة. تظهر رسوم الشحن عند إتمام الطلب. عند تحديد الميزانية تظهر المنتجات ذات السعر المتاح فقط.'));if(!products.length){results.append(el('p','','لا توجد نتيجة ضمن هذه الميزانية والمكونات. جرّب ميزانية أخرى أو استشر الفريق.'));}else{const grid=el('div','am-tool-grid');products.forEach(p=>grid.append(productCard(p,need.value==='all'?'راجع محتويات المنتج للمفاضلة.':'يتضمن المكونات التي اخترتها.')));results.append(el('h3','',products.length+' خيارات للمراجعة'),grid,button('قارن المنتجات المختارة',()=>render('compare'),'am-tool-secondary'));}track('device_results',{result_count:products.length,need:need.value});});}
    function compareView(){body.append(el('h3','','قارن المكونات قبل اختيار العرض'));const switcher=select([['offers','العروض والتجميعات'],['devices','الأجهزة المنفردة']]);switcher.value=group;switcher.addEventListener('change',()=>{group=switcher.value;selected.clear();render('compare')});body.append(field('مجموعة المقارنة',switcher),notice('اختر منتجين أو ثلاثة. مواصفات السعة والضمان لا تُستنتج من عدد المراحل؛ راجع تفاصيل المنتج أو اسأل الفريق.'));
      const options=el('div','am-compare-options'),items=catalogue.filter(p=>group==='offers'?p.kind==='offer':p.kind==='device');items.forEach(p=>{const check=input('checkbox');check.checked=selected.has(p.id);check.addEventListener('change',()=>{if(check.checked&&selected.size>=3){check.checked=false;limit.textContent='يمكن مقارنة 3 منتجات بحد أقصى.';return;}if(check.checked)selected.add(p.id);else selected.delete(p.id);tableView();track('compare_select',{product_id:p.id})});const label=field(p.title,check);options.append(label)});const limit=el('p','am-tool-note');limit.setAttribute('role','status');const target=el('div');body.append(options,limit,target);function tableView(){target.replaceChildren();const chosen=items.filter(p=>selected.has(p.id));if(chosen.length<2){target.append(notice('اختر منتجين على الأقل لعرض المقارنة.'));return;}const wrap=el('div','am-compare-scroll'),table=el('table','am-compare-table'),caption=el('caption','','مقارنة المنتجات المختارة');table.append(caption);const thead=el('thead'),headRow=el('tr');headRow.append(el('th','','المقارنة'));chosen.forEach(p=>headRow.append(el('th','',p.title)));thead.append(headRow);table.append(thead);const tbody=el('tbody');const rows=[['سعر المنتج',p=>priceLabel(p)],['المكونات والمواصفات',p=>link('راجع وصف المنتج الحالي',productLink(p))],['الخدمة الاختيارية',p=>link('راجع خيارات الخدمة المتاحة لهذا المنتج',productLink(p))],['بقية مدن المملكة',()=> 'شحن فقط'],['تفاصيل الطلب',p=>link('الخيارات والمواصفات',productLink(p))]];rows.forEach(([title,value])=>{const row=el('tr'),th=el('th','',title);th.scope='row';row.append(th);chosen.forEach(p=>{const td=el('td'),v=value(p);td.append(typeof v==='string'?document.createTextNode(v):v);row.append(td)});tbody.append(row)});table.append(tbody);wrap.append(table);target.append(wrap);track('compare_view',{product_ids:chosen.map(p=>p.id).join(',')});}tableView();}
    function filterView(){body.append(el('h3','','ابحث عن الفلتر بالمقاس والنوع'),notice('تطابق النوع والمقاس لا يكفي وحده: طابق التوصيلات ورقم القطعة قبل الطلب. لم يتم تأكيد توافق موديلات الأجهزة آليًا.'));
      const form=el('form','am-tool-form'),size=select([['10','10 بوصات'],['12','12 بوصة']]),type=select([['all','جميع الأنواع المتاحة'],['قطني','قطني PP'],['حبيبي','كربون حبيبي UDF'],['صلب','كربون صلب']]);form.append(field('المقاس المكتوب على الفلتر',size),field('نوع الفلتر',type));const submit=el('button','am-tool-button','اعرض الفلاتر');submit.type='submit';form.append(submit);const results=el('div','am-tool-results');results.setAttribute('aria-live','polite');body.append(form,results);form.addEventListener('submit',event=>{event.preventDefault();results.replaceChildren();const found=catalogue.filter(p=>p.kind==='filter'&&p.size===size.value&&(type.value==='all'||p.filterType===type.value));if(!found.length)results.append(notice('لا توجد نتيجة مؤكدة ضمن هذه المجموعة. أرسل صورة الفلتر أو رقم القطعة لفريقنا.'));const grid=el('div','am-tool-grid');found.forEach(p=>grid.append(productCard(p,'مطابق للنوع والمقاس المختارين؛ تحقّق من التوصيلات.')));results.append(grid);track('filter_results',{size:size.value,filter_type:type.value,result_count:found.length});});const help=el('div','am-tool-help'),model=input('text','موديل الجهاز أو رقم القطعة');help.append(el('h3','','لا تعرف المقاس أو الموديل؟'),field('اكتب الموديل إن توفر',model));const contact=link('تحقّق من التوافق مع الفريق',wa('أرغب بالتحقق من توافق فلتر مع جهازي. سأرسل صورة الجهاز والفلتر ورقم القطعة.'));model.addEventListener('input',()=>contact.href=wa('أرغب بالتحقق من توافق فلتر. موديل الجهاز أو رقم القطعة: '+model.value+'\nسأرفق الصور في المحادثة.'));help.append(contact);body.append(help);}
    function installView(){body.append(el('h3','','الشحن والتركيب حسب مدينتك'),el('p','am-tool-muted',coverage));const city=input('text','اكتب المدينة');const list=el('datalist');list.id='am-install-cities';installationCities.forEach(name=>{const option=el('option');option.value=name;list.append(option)});city.setAttribute('list',list.id);city.autocomplete='address-level2';const result=el('div','am-tool-note');result.setAttribute('aria-live','polite');const check=button('تحقّق من الخدمة',()=>{if(!city.value.trim()){result.textContent='اكتب مدينتك أولًا.';city.focus();return;}result.textContent=canInstall(city.value)?'التركيب متاح في '+city.value+'. راجع خدمة التركيب أو الاستبدال والمدينة والأجرة في السلة للمنتجات المؤهلة، ويُنسّق الموعد مع الفريق.':'الشحن متاح إلى '+city.value+'. مدينتك خارج نطاق تركيبنا الحالي؛ اختر بدون تركيب.';track('coverage_check',{installation:canInstall(city.value)})});body.append(field('المدينة',city),list,check,result);const ul=el('ul');['راجع مساحة الجهاز والخزان ومقاس المنتج.','تحقّق من مصدر المياه والصرف والتوصيلات اللازمة مع الفريق.','اختر مواصفات المنتج المتاحة، ثم راجع خدمة التركيب والمدينة في السلة.','تكلفة الشحن تُعرض حسب بيانات الطلب عند إتمام الشراء.'].forEach(text=>ul.append(el('li','',text)));body.append(el('h3','','قبل طلب الجهاز'),ul,link('نسّق تفاصيل التركيب',wa('أرغب بتنسيق تركيب جهاز تحلية.\nالمدينة:\nاسم الجهاز أو رابط المنتج:\nحالة التوصيلات والمساحة المتاحة:')));}
    function remindView(){body.append(el('h3','','تذكير الصيانة في تقويمك'),notice('اختر موعدًا بناءً على دليل الجهاز أو توصية الفني. لا نفترض فترة موحّدة لتغيير الفلاتر. حدّد التاريخ، ثم اضغط «إضافة إلى تقويمي» واحفظ الموعد في تطبيقك.'));const form=el('form','am-tool-form'),model=input('text','اسم الجهاز أو نوع الفلتر'),date=input('date');date.required=true;const today=new Date();date.min=[today.getFullYear(),String(today.getMonth()+1).padStart(2,'0'),String(today.getDate()).padStart(2,'0')].join('-');form.append(field('الجهاز أو الفلتر — اختياري',model),field('موعد التذكير',date));const submit=el('button','am-tool-button','إضافة إلى تقويمي');submit.type='submit';form.append(submit);const status=el('p','am-tool-note');status.setAttribute('role','status');body.append(form,status);function androidCalendarLinks(date,title){const start=Date.parse(date+'T00:00:00Z');const end=start+86400000;const endDate=new Date(end).toISOString().slice(0,10);const dates=(date+'/'+endDate).replaceAll('-','');const web='https://calendar.google.com/calendar/render?action=TEMPLATE&dates='+dates+'&text='+encodeURIComponent(title);const native='intent://com.android.calendar/events#Intent;scheme=content;action=android.intent.action.INSERT;type=vnd.android.cursor.dir/event;S.title='+encodeURIComponent(title)+';l.beginTime='+start+';l.endTime='+end+';B.allDay=true;S.browser_fallback_url='+encodeURIComponent(web)+';end';return {native,web}};let lastUrl;form.addEventListener('submit',async event=>{event.preventDefault();const day=date.value.replaceAll('-','');const escape=s=>s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/,/g,'\\,').replace(/;/g,'\\;');const ics=['BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//Almoalej//Maintenance//AR','CALSCALE:GREGORIAN','BEGIN:VEVENT','UID:am-'+Date.now()+'@almoalej.com','DTSTAMP:'+new Date().toISOString().replace(/[-:]/g,'').replace(/\.\d{3}/,''),'DTSTART;VALUE=DATE:'+day,'SUMMARY:'+escape('مراجعة صيانة '+(model.value||'جهاز المياه')),'DESCRIPTION:'+escape('راجع دليل الجهاز ونسّق احتياج الصيانة مع المعالج. https://wa.me/966533557999'),'END:VEVENT','END:VCALENDAR'].join('\r\n');const ios=/iPhone|iPad|iPod/i.test(navigator.userAgent)||(navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1);const android=/Android/i.test(navigator.userAgentData?.platform||navigator.userAgent);if(android){const urls=androidCalendarLinks(date.value,'مراجعة صيانة '+(model.value.trim()||'جهاز المياه'));const fallback=el('a','am-tool-text-button','فتح الموعد في تقويم Google');fallback.href=urls.web;status.replaceChildren(fallback);window.location.assign(urls.native);return}const file=new File([ics],'maintenance.ics',{type:'text/calendar'});if(lastUrl)URL.revokeObjectURL(lastUrl);lastUrl=URL.createObjectURL(file);const direct=el('a','am-tool-text-button','فتح موعد الصيانة');direct.href=lastUrl;if(ios){direct.target='_blank';direct.rel='noopener'}else if(!android){direct.download=file.name}status.replaceChildren(direct);if(ios&&navigator.canShare?.({files:[file]})){try{await navigator.share({files:[file]});return}catch(error){if(error.name==='AbortError')return;status.prepend('تعذرت المشاركة. ');return}}direct.click()});body.append(link('استعرض باقات الصيانة','https://almoalej.com/-/c1520217384'));}
    function mountHomepage(){const tasks=document.querySelector('section[component-id="1204252081"]');if(!tasks||tasks.querySelector('.am-shopping-hub'))return;const box=el('div','am-shopping-hub');box.append(el('span','am-tool-eyebrow','قرار شراء أسهل'),el('h2','','اختر بثقة، وقارن بوضوح'),el('p','am-tool-muted',coverage));const actions=el('div','am-hub-actions');[['choose','ساعدني أختار جهازًا','حدّد المكونات والميزانية واعرض الخيارات.'],['compare','قارن الأجهزة والعروض','مقارنة واضحة للمكونات والأسعار.'],['filter','فلتر يناسب احتياجك','ابحث بالنوع والمقاس وتحقّق من التوصيلات.']].forEach(([tab,title,desc],i)=>{const b=button('',()=>open(tab,b),'am-hub-card');b.dataset.shopTool=tab;const badge=el('span','am-hub-number');badge.setAttribute('aria-hidden','true');const paths={"choose":"<circle cx=\"16\" cy=\"16\" r=\"12.25\" fill=\"currentColor\" fill-opacity=\".10\"/><path d=\"M16 4v2m0 20v2M4 16h2m20 0h2\"/><path d=\"m22 10-3.8 8.2L10 22l3.8-8.2Z\" fill=\"currentColor\" fill-opacity=\".18\"/><path d=\"m22 10-8.2 3.8 4.4 4.4Z\" fill=\"currentColor\" stroke=\"none\"/>","compare":"<path d=\"M16 6v20M5 10l11-3 11 3M10.5 27h11\"/><circle cx=\"16\" cy=\"6\" r=\"2\" fill=\"currentColor\" stroke=\"none\"/><path d=\"m7 10-4 9h8l-4-9Zm18 0-4 9h8l-4-9Z\"/><path d=\"M3 19h8a4 4 0 0 1-8 0Zm18 0h8a4 4 0 0 1-8 0Z\" fill=\"currentColor\" stroke=\"none\"/>","filter":"<path d=\"M3 7h4m18 0h4\"/><rect x=\"7\" y=\"4\" width=\"18\" height=\"6\" rx=\"2\" fill=\"currentColor\" fill-opacity=\".20\"/><path d=\"M9 10v12a6 6 0 0 0 6 6h2a6 6 0 0 0 6-6V10Z\" fill=\"currentColor\" fill-opacity=\".10\"/><path d=\"M16 13c-1.3 2.1-3.7 4.7-3.7 7a3.7 3.7 0 0 0 7.4 0c0-2.3-2.4-4.9-3.7-7Z\" fill=\"currentColor\" stroke=\"none\"/>"};badge.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" focusable="false">'+paths[tab]+'</svg>';b.append(badge,el('strong','',title),el('span','',desc),el('span','am-hub-arrow','ابدأ ←'));actions.append(b)});box.append(actions);const footer=document.querySelector('footer.store-footer');if(footer){const row=el('div','container am-shipping-map-row');row.dir='rtl';const action=button('الشحن والتركيب حسب المدينة',()=>open('install'),'am-tool-text-button');row.append(action);footer.before(row);const style=el('style');style.textContent='.am-shipping-map-row{display:flex;justify-content:flex-end;padding-block:12px}.am-shipping-map-row>button{width:min(350px,100%);min-height:44px;border:1px solid #ff8666;border-radius:12px;background:#fff;color:#102f49;font:inherit;font-weight:700;cursor:pointer}@media(max-width:1023px){.am-shipping-map-row{justify-content:flex-start}}';row.append(style);}tasks.querySelector('.container').append(box);}
    document.addEventListener('click',event=>{if(event.target.closest?.('#am-service-requests button[data-am-request="reminder"]'))open('remind')});
    function mountCards(){document.querySelectorAll('.index .s-product-card-entry').forEach(card=>{let p=catalogue.find(p=>p.id===card.id&&p.kind!=='filter');if(!p&&card.closest('[component-id="344871967"]')){const a=card.querySelector('h3 a');if(!a||!card.id)return;p={id:card.id,title:a.textContent.trim(),url:a.href,kind:'device',image:card.querySelector('img')?.src||'',description:'',price:card.querySelector('.s-product-card-sale-price h4,.s-product-card-price')?.textContent.trim()||''};catalogue.push(p)}if(!p||card.querySelector('.am-card-compare'))return;const b=button('قارن هذا المنتج',()=>{if(selected.size>=3&&!selected.has(p.id))selected.clear();selected.add(p.id);group=p.kind==='offer'?'offers':'devices';open('compare',b)},'am-card-compare');card.querySelector('.s-product-card-content')?.append(b)});}
    function rootOf(id){const s=document.querySelector('section[component-id="'+id+'"]');return s&&Array.from(s.querySelectorAll('*')).map(e=>e.shadowRoot).find(Boolean)}
    function fixCoverage(){const hero=rootOf('398096929');const subtitle=hero?.querySelector('.s-block-simple-section__subtitle');if(subtitle)subtitle.textContent='أجهزة التحلية والفلاتر وخدمات الصيانة. '+coverage+' نساعدك في اختيار الحل المناسب لاحتياجك.';const about=rootOf('877447485')?.querySelector('.s-block-simple-section__subtitle');if(about)about.textContent='المعالج لوحدات تحلية المياه يجمع الأجهزة والفلاتر وقطع الغيار مع خدمات الصيانة. '+coverage;const services=rootOf('1853988552');const lead=services?.querySelector('.section-subtitle');if(lead)lead.textContent='من اختيار الجهاز إلى التركيب والصيانة. '+coverage;const descriptions=services?.querySelectorAll('.service-description');if(descriptions?.[0])descriptions[0].textContent='التركيب في الأحساء والدمام والرياض وتبوك، حسب خيار المنتج وتنسيق الموعد مع الفريق.';const footer=document.querySelector('footer');if(footer)Array.from(footer.querySelectorAll('p,div')).filter(e=>e.children.length===0&&e.textContent.includes('المعالج لوحدات تحلية المياه. حلول مياه')).forEach(e=>e.textContent='المعالج لوحدات تحلية المياه. '+coverage);const note=document.querySelector('section[component-id="678832534"] .s-product-card-content-subtitle');if(note&&!note.dataset.amCoverage){note.append(document.createTextNode(' — التركيب في الأحساء والدمام والرياض وتبوك.'));note.dataset.amCoverage='true';}}

    mountHomepage();mountCards();fixCoverage();let attempts=0;const interval=setInterval(()=>{mountHomepage();mountCards();fixCoverage();if(++attempts>=20)clearInterval(interval)},500);
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Draft: installation option requires an explicitly selected service city. */
(function(){
 function start(){
  if(getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return;
  const cities=['الأحساء','الدمام','الرياض','تبوك'],bindings=new Map();let queued=false;
  const style=document.createElement('style');style.textContent='.am-install-city-box{margin:0 0 18px;padding:18px;border:1px solid #cfe1f3;border-radius:12px;background:#f4faff;color:#082b59}.am-install-city-box label{display:block;font-weight:700;margin-bottom:8px}.am-install-city-box select{width:100%;min-height:48px;background:#fff;border:1px solid #bdcfe3;border-radius:8px;padding:10px;color:#082b59}.am-install-city-box p{margin:10px 0 0;font-size:14px;line-height:1.8}.am-install-city-box[data-available="true"]{border-color:#0756d9}.am-install-city-box select:focus-visible{outline:2px solid #0756d9;outline-offset:2px}';document.head.append(style);
  function installOptions(select){return Array.from(select.options).filter(o=>/^مع\s*(?:ال)?تركيب/.test(o.textContent.trim()))}
  function sync(select,binding){
   const allowed=cities.includes(binding.city.value),options=installOptions(select);let reset=false;
   options.forEach(o=>{o.disabled=!allowed;if(!allowed&&o.selected)reset=true});
   if(reset){const without=Array.from(select.options).find(o=>/بدون\s*(?:ال)?تركيب/.test(o.textContent));select.value=without?.value||'';select.dispatchEvent(new Event('change',{bubbles:true}));}
   binding.box.dataset.available=String(allowed);
   const message=allowed?'التركيب متاح في '+binding.city.value+'؛ يمكنك الآن اختيار «مع التركيب» بالسعر الموضح أدناه.':binding.city.value==='shipping'?'التركيب غير متاح لهذه المدينة. الطلب للشحن فقط، وتُضاف رسوم الشحن عند إتمام الطلب حسب المدينة وطريقة الشحن.':'اختر مدينة من مدن التركيب لتفعيل «مع التركيب». يمكنك الطلب بدون تركيب لبقية مدن المملكة.';
   if(binding.note.textContent!==message)binding.note.textContent=message;
  }
  function mount(){
   document.querySelectorAll('form.product-form select').forEach(select=>{
    if(!installOptions(select).length||!Array.from(select.options).some(o=>/بدون\s*(?:ال)?تركيب/.test(o.textContent)))return;
    if(bindings.has(select)){const binding=bindings.get(select),host=select.closest('salla-product-options');if(host?.contains(binding.box))host.before(binding.box);sync(select,binding);return;}
    const box=document.createElement('div');box.className='am-install-city-box';
    const label=document.createElement('label'),city=document.createElement('select'),note=document.createElement('p');
    city.id='am-order-city-'+bindings.size;label.htmlFor=city.id;label.textContent='مدينة التركيب';note.id=city.id+'-note';note.setAttribute('role','status');note.setAttribute('aria-live','polite');city.setAttribute('aria-describedby',note.id);
    [['','اختر المدينة أولًا'],...cities.map(c=>[c,c]),['shipping','مدينة أخرى — شحن فقط']].forEach(([value,text])=>{const o=document.createElement('option');o.value=value;o.textContent=text;city.append(o)});
    box.append(label,city,note);(select.closest('salla-product-options')||select.parentElement).before(box);
    const binding={box,city,note};bindings.set(select,binding);select.setAttribute('aria-describedby',note.id);
    city.addEventListener('change',()=>sync(select,binding));select.addEventListener('change',()=>sync(select,binding));sync(select,binding);
   });
   for(const [select] of bindings)if(!select.isConnected)bindings.delete(select);
  }
  function guard(event){
   const form=event.target.closest?.('form');if(event.type==='click'&&!event.target.closest?.('salla-add-product-button,button[type="submit"],input[type="submit"]'))return;
   for(const [select,binding] of bindings){if(form&&!form.contains(select))continue;if(installOptions(select).some(o=>o.selected)&&!cities.includes(binding.city.value)){event.preventDefault();event.stopImmediatePropagation();sync(select,binding);binding.city.focus();return;}}
  }
  document.addEventListener('submit',guard,true);document.addEventListener('click',guard,true);
  new MutationObserver(()=>{if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;mount()})}).observe(document.body,{childList:true,subtree:true});mount();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
/* Persist installation city in Salla's native item notes, not browser storage. */
(function(){
 function start(){
  if(getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return;
  const cities=['الأحساء','الدمام','الرياض','تبوك'];
  const strip=text=>String(text||'').split('\n').filter(line=>!line.startsWith('مدينة التركيب:')).join('\n').trim();
  function sync(){document.querySelectorAll('form.product-form').forEach(form=>{
   const city=form.querySelector('.am-install-city-box select');if(!city)return;
   const installation=Array.from(form.querySelectorAll('select')).find(s=>Array.from(s.options).some(o=>/^مع\s*(?:ال)?تركيب/.test(o.textContent.trim())));
   const withInstallation=installation&&/^مع\s*(?:ال)?تركيب/.test(installation.selectedOptions[0]?.textContent.trim()||'');
   let notes=form.querySelector('[name="notes"]');if(!notes){notes=document.createElement('input');notes.type='hidden';notes.name='notes';notes.dataset.amCityNotes='true';form.append(notes)}
   const base=strip(notes.value),line=withInstallation&&cities.includes(city.value)?'مدينة التركيب: '+city.value:'';
   notes.value=[base,line].filter(Boolean).join('\n');notes.disabled=!notes.value&&notes.dataset.amCityNotes==='true';
   const box=form.querySelector('.am-install-city-box');let summary=box.querySelector('.am-install-city-saved');if(!summary){summary=document.createElement('p');summary.className='am-install-city-saved';box.append(summary)}
   const message=line?'ستُرفق '+line+' مع ملاحظات المنتج في الطلب.':'';if(summary.textContent!==message)summary.textContent=message;summary.hidden=!line;
  })}
  document.addEventListener('change',sync);document.addEventListener('input',e=>{if(e.target.matches?.('[name="notes"]'))sync()});
  document.addEventListener('click',e=>{if(e.target.closest?.('salla-add-product-button'))sync()},true);
  let queued=false;new MutationObserver(()=>{if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;sync()})}).observe(document.body,{childList:true,subtree:true});sync();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();


/* Installation cities: native option changes and verified per-line notes. No price overrides. */
(function(){
 function start(){
  if(!document.body.classList.contains('cart')||getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return;
  const cities=['الأحساء','الدمام','الرياض','تبوك'],lines=new Map();
  const outside='التركيب غير متاح لهذه المدينة. الطلب للشحن فقط، وتُضاف رسوم الشحن عند إتمام الطلب حسب المدينة وطريقة الشحن.';
  const shipping='بدون تركيب — تُضاف رسوم الشحن عند إتمام الطلب حسب المدينة وطريقة الشحن.';
  let busy=false,again=false,revision=0,retries=0,refreshTimer;
  const isWith=select=>/^مع\s*(?:ال)?تركيب/.test(select?.selectedOptions[0]?.textContent.trim()||'');
  const findInstallation=card=>Array.from(card?.querySelectorAll('select')||[]).find(select=>Array.from(select.options).some(option=>/^مع\s*(?:ال)?تركيب/.test(option.textContent.trim()))&&Array.from(select.options).some(option=>/بدون\s*(?:ال)?تركيب/.test(option.textContent)));
  const cardFor=id=>document.querySelector('[data-testid="store-cart-item-'+id+'"]');
  const idFor=card=>card?.getAttribute('data-testid')?.replace('store-cart-item-','')||'';
  const cityFrom=notes=>String(notes||'').split('\n').find(line=>/^مدينة التركيب: (الأحساء|الدمام|الرياض|تبوك)$/.test(line))?.slice('مدينة التركيب: '.length)||'';
  function notesField(form){let notes=form.querySelector('[name="notes"]');if(!notes){notes=document.createElement('input');notes.type='hidden';notes.name='notes';form.append(notes)}notes.disabled=false;return notes}
  function writeNotes(form,city){const notes=notesField(form),base=String(notes.value||'').split('\n').filter(line=>!line.startsWith('مدينة التركيب:')).join('\n').trim();notes.value=[base,city?'مدينة التركيب: '+city:''].filter(Boolean).join('\n');return notes}
  function lock(select,city){Array.from(select.options).filter(option=>/^مع\s*(?:ال)?تركيب/.test(option.textContent.trim())).forEach(option=>option.disabled=!cities.includes(city));}
  function show(card,state){const city=card?.querySelector('.am-cart-city-choice'),status=card?.querySelector('.am-cart-city-status'),installation=findInstallation(card);if(!city||!status||!installation)return;
   const withInstallation=isWith(installation),valid=cities.includes(city.value),verified=!state.pending&&!state.failed&&state.confirmedOption===installation.value&&(!withInstallation||valid&&state.confirmedCity===city.value);
   card.dataset.amCitySaved=verified?'true':'false';card.dataset.amCityState=state.failed?'failed':state.pending?'pending':verified?'saved':'required';card.dataset.amCityConfirmed=verified?state.confirmedCity:'';
   const notice=city.value==='shipping'?outside:!withInstallation?shipping:!valid?'حدد مدينة التركيب قبل إتمام الطلب.':'مدينة التركيب: '+city.value;
   const detail=state.failed?'تعذّر تأكيد حفظ الخيارات والمدينة. أعد المحاولة قبل إتمام الطلب.':state.pending?'جارٍ حفظ الخيارات والمدينة والتحقق منها في سلة…':verified&&withInstallation?'تم تأكيد حفظ مدينة التركيب في سلة.':'';
   const text=[notice,detail].filter(Boolean).join(' ');if(status.textContent!==text)status.textContent=text;city.setCustomValidity(withInstallation&&!valid?'اختر مدينة متاحة للتركيب.':'');
   const retry=card.querySelector('.am-cart-city-retry');if(retry)retry.hidden=!state.failed;lock(installation,city.value);
  }
  function schedule(delay=200){clearTimeout(refreshTimer);refreshTimer=setTimeout(refresh,delay)}
  function nativeQuantity(form){const input=form.querySelector('salla-quantity-input input')||form.querySelector('input[name="quantity"]');const quantity=Number(input?.value);return Number.isInteger(quantity)&&quantity>0?quantity:null}
  function fail(state){if(!state.dirty)return;state.pending=false;state.failed=true;show(cardFor(state.id),state)}
  function begin(card,state){const form=card.closest('form'),city=card.querySelector('.am-cart-city-choice'),installation=findInstallation(card);if(!form||!city||!installation)return;
   revision++;state.generation++;state.rawCity=city.value;state.desiredCity=isWith(installation)&&cities.includes(city.value)?city.value:'';state.desiredOption=installation.value;state.desiredQuantity=nativeQuantity(form);state.readAttempts=0;state.pending=true;state.failed=false;state.dirty=true;state.acknowledged=false;state.confirmedCity='';state.confirmedOption='';writeNotes(form,state.desiredCity);show(card,state);
   const generation=state.generation;clearTimeout(state.timeout);state.timeout=setTimeout(()=>{if(lines.get(state.id)===state&&state.generation===generation&&state.pending)fail(state)},12000);
   schedule(400);
  }
  document.addEventListener('change',event=>{const form=event.target.closest?.('form'),card=form?.querySelector('.cart-item'),state=lines.get(idFor(card)),city=card?.querySelector('.am-cart-city-choice'),installation=findInstallation(card);if(!state||!city||!installation)return;
   const allowed=cities.includes(city.value);lock(installation,city.value);
   if(!allowed&&isWith(installation)){const without=Array.from(installation.options).find(option=>/بدون\s*(?:ال)?تركيب/.test(option.textContent));if(without&&installation.value!==without.value){installation.value=without.value;writeNotes(form,'');event.stopImmediatePropagation();installation.dispatchEvent(new Event('change',{bubbles:true}));return;}}
   begin(card,state);
  },true);
  function nativeChoice(item,select){
   const optionId=select.name?.match(/^options\[(\d+)\]/)?.[1],options=item.options;if(!optionId||!options)return null;
   let option=Array.isArray(options)?options.find(value=>String(value.id??value.option_id)===optionId):options[optionId];if(option==null)return null;
   if(typeof option==='string'||typeof option==='number')return String(option);
   const direct=option.value_id??option.option_value_id??option.detail_id;if(direct!=null)return String(direct);
   const details=option.details||option.values||[],selected=Array.isArray(details)?details.find(value=>value.is_selected===true||value.selected===true):null;if(selected?.id!=null)return String(selected.id);
   const value=option.value;if(typeof value==='string'||typeof value==='number'){const matched=Array.from(select.options).find(entry=>entry.value===String(value)||entry.textContent.trim()===String(value).trim());if(matched)return matched.value;}
   return null;
  }
  function mount(card,state){let box=card.querySelector('.am-cart-city');if(box)return box;
   box=document.createElement('div');box.className='am-cart-city';box.style.cssText='padding:12px 16px;margin:12px 0;border:1px solid #cfe1f3;border-radius:10px;background:#f1faff;color:#082b59;font-weight:700';
   const label=document.createElement('label'),city=document.createElement('select'),status=document.createElement('p'),retry=document.createElement('button');city.id='am-cart-city-'+state.id;label.htmlFor=city.id;label.textContent='مدينة التركيب';city.className='am-cart-city-choice';city.style.cssText='width:100%;min-height:44px;margin-top:8px;background:white;border:1px solid #cfe1f3;border-radius:8px;padding:8px';status.className='am-cart-city-status';status.style.cssText='font-size:13px;line-height:1.8;margin-top:8px';status.setAttribute('aria-live','polite');
   [['','اختر المدينة'],...cities.map(value=>[value,value]),['shipping','مدينة أخرى — شحن فقط']].forEach(([value,text])=>{const option=document.createElement('option');option.value=value;option.textContent=text;city.append(option)});
   retry.type='button';retry.className='am-cart-city-retry';retry.textContent='إعادة محاولة حفظ الخيارات والمدينة';retry.hidden=true;retry.style.cssText='margin-top:10px;padding:10px;border:1px solid #bfd2e6;border-radius:8px;background:white;color:#0756d9';retry.addEventListener('click',()=>findInstallation(card)?.dispatchEvent(new Event('change',{bubbles:true})));
   box.append(label,city,status,retry);card.querySelector('h1')?.after(box);box.dataset.source='salla-item-notes';return box;
  }
  async function refresh(){if(busy){again=true;return}if(!window.salla?.cart?.details)return;busy=true;const readRevision=revision;
   try{const response=await salla.cart.details();if(readRevision!==revision){again=true;return}const data=response?.data?.data||response?.data||response,items=data?.items||data?.cart?.items||[],active=new Set();document.documentElement.dataset.amCityReadback=String(items.length);
    for(const item of items){const id=String(item.id);active.add(id);const card=cardFor(id),form=card?.closest('form'),installation=findInstallation(card);if(!card||!form){if(retries++<12)schedule(500);continue}if(!installation){const host=card.querySelector('salla-product-options');if(host){let awaiting=!host.children.length;try{awaiting=awaiting||JSON.parse(host.getAttribute('options')||'[]').some(option=>(option.details||[]).some(detail=>/^مع\s*(?:ال)?تركيب/.test(detail.name))&&(option.details||[]).some(detail=>/بدون\s*(?:ال)?تركيب/.test(detail.name)))}catch(error){}if(awaiting&&retries++<12)schedule(500)}continue}const savedCity=cityFrom(item.notes),serverOption=nativeChoice(item,installation);let state=lines.get(id);
     if(!state){state={id,rawCity:savedCity,desiredCity:savedCity,desiredOption:installation.value,confirmedCity:savedCity,confirmedOption:installation.value,dirty:false,pending:false,failed:false,acknowledged:true,generation:0};lines.set(id,state)}
     const box=mount(card,state),city=box.querySelector('select'),notes=notesField(form);
     if(state.dirty){const optionMatches=serverOption===null?state.acknowledged:serverOption===state.desiredOption,quantityMatches=state.desiredQuantity===null||item.quantity==null||Number(item.quantity)===state.desiredQuantity;if(savedCity===state.desiredCity&&optionMatches&&quantityMatches){state.confirmedCity=savedCity;state.confirmedOption=state.desiredOption;state.dirty=false;state.pending=false;state.failed=false;clearTimeout(state.timeout);notes.value=item.notes||'';}else{writeNotes(form,state.desiredCity);if(state.pending&&state.readAttempts++<12)schedule(600);}
     }else{state.desiredCity=savedCity;state.rawCity=savedCity||state.rawCity;state.desiredOption=serverOption??installation.value;state.confirmedCity=savedCity;state.confirmedOption=serverOption??installation.value;notes.value=item.notes||'';}
     const desired=state.dirty?state.rawCity:(savedCity||state.rawCity);if(city.value!==desired)city.value=desired;show(card,state);
    }
    for(const [id,state] of lines)if(!active.has(id)&&!cardFor(id)){clearTimeout(state.timeout);lines.delete(id)}
   }catch(error){document.documentElement.dataset.amCityReadback='unavailable';for(const state of lines.values())if(state.pending)fail(state)}finally{busy=false;if(again){again=false;schedule(150)}}
  }
  function eventItemId(response,itemId){const candidate=String(itemId||response?.data?.item_id||response?.item_id||'');return lines.has(candidate)?candidate:''}
  function updated(response,itemId){const id=eventItemId(response,itemId);for(const [lineId,state] of lines){if(id&&id!==lineId||!state.dirty)continue;state.acknowledged=true;}schedule(200)}
  function failed(response,itemId){const id=eventItemId(response,itemId);for(const [lineId,state] of lines)if((!id||id===lineId)&&state.dirty)fail(state);schedule(250)}
  document.addEventListener('click',event=>{const button=event.target.closest?.('button');if(!button||button.textContent.trim()!=='إتمام الطلب')return;
   for(const card of document.querySelectorAll('.cart-item')){const installation=findInstallation(card);if(!installation)continue;const city=card.querySelector('.am-cart-city-choice'),state=lines.get(idFor(card)),withInstallation=isWith(installation),valid=city&&cities.includes(city.value),verified=state&&!state.pending&&!state.failed&&state.confirmedOption===installation.value&&(!withInstallation||valid&&state.confirmedCity===city.value);
    if(!verified){event.preventDefault();event.stopImmediatePropagation();if(state)show(card,state);if(city){city.reportValidity();city.focus()}else{let note=card.querySelector('.am-cart-city-load-error');if(!note){note=document.createElement('p');note.className='am-cart-city-load-error';note.textContent='انتظر تحميل مدينة التركيب وخيارات المنتج أو حدّث السلة قبل إتمام الطلب.';card.append(note)}}schedule(100);return;}
   }
  },true);
  if(window.salla?.onReady)salla.onReady(()=>{refresh();salla.event.on('cart::updated',updated);salla.event.on('cart::item.updated',updated);salla.event.on('cart::item.updated.failed',failed)});else refresh();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Product information and dedicated draft information views. Facts reviewed 15 Nov 2026. */
(function(){
 const warranty='ضمان القطع الكهربائية سنتان لجميع المنتجات.';
 const coverage='شحن لجميع مدن المملكة، وتركيب في الأحساء والدمام والرياض وتبوك.';
 const e=(tag,cls,text)=>{const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n};
 const a=(text,href,cls)=>{const n=e('a',cls,text);n.href=href;return n};
 const wa=text=>'https://wa.me/966533557999?text='+encodeURIComponent(text);
 function homeUrl(hash=''){const u=new URL(location.href);u.pathname=location.hostname==='salla.sa'?'/almoalej.com/':'/';u.hash=hash;return u.href}
 function icon(type){const s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttribute('viewBox','0 0 24 24');s.setAttribute('fill','none');s.setAttribute('stroke','currentColor');s.setAttribute('stroke-width','1.6');s.setAttribute('stroke-linecap','round');s.setAttribute('stroke-linejoin','round');s.setAttribute('aria-hidden','true');const p=document.createElementNS(s.namespaceURI,'path');p.setAttribute('d',type==='shield'?'M12 3 4 6v6c0 5 8 9 8 9s8-4 8-9V6l-8-3Z M8 12l3 3 5-6':'M3 6h12v11H3z M15 10h3l3 4v3h-6 M6 17a2 2 0 1 0 0 4 2 2 0 0 0 0-4 M18 17a2 2 0 1 0 0 4 2 2 0 0 0 0-4');s.append(p);return s}
 function start(){
  if(getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1')return;
  if(document.documentElement.dataset.amDetailsReady)return;document.documentElement.dataset.amDetailsReady='true';
  const style=e('style');style.textContent=".am-pdp-intro{margin:18px 0 24px;color:#082b59;text-align:right}.am-pdp-intro p{font-size:18px;line-height:1.9;margin:0 0 14px}.am-pdp-trust{display:flex;gap:8px;flex-wrap:wrap}.am-pdp-trust span{display:inline-flex;align-items:center;gap:8px;padding:9px 12px;background:#f0f8ff;border:1px solid #d5e5f3;border-radius:9px;color:#0c477a;font-size:13px;font-weight:700}.am-pdp-trust svg{width:19px;height:19px;flex-shrink:0}.am-pdp-details{margin:28px 0 0;padding:0!important;overflow:hidden;border:1px solid #d6e5f1!important;border-radius:16px!important;background:#fff!important;color:#082b59;text-align:right}.am-pdp-details .am-detail-head{padding:22px;background:#f0f8ff;border-bottom:1px solid #dce9f3}.am-pdp-details h2{font-size:23px!important;font-weight:800;margin:0 0 8px!important}.am-detail-eyebrow{display:block;color:#0756d9;font-size:12px;font-weight:700;margin-bottom:8px}.am-detail-head p{font-size:15px;line-height:1.9;margin:0;color:#52677f}.am-detail-section{padding:22px;border-bottom:1px solid #e5edf5}.am-detail-section h3{font-size:19px;font-weight:800;margin:0 0 14px}.am-content-list{list-style:none;margin:0;padding:0;display:grid;gap:10px}.am-content-list li{display:flex;align-items:flex-start;gap:10px;color:#314f6e;font-size:15px;line-height:1.8}.am-content-check{width:22px;height:22px;flex-shrink:0;background:#eaf4ff;color:#0756d9;border-radius:50%;display:grid;place-items:center;font-size:13px;margin-top:2px}.am-spec-list{margin:0;display:grid;grid-template-columns:minmax(90px,.7fr) 1.4fr}.am-spec-list dt,.am-spec-list dd{padding:12px 0;border-bottom:1px solid #eaf0f6;font-size:14px;line-height:1.8;margin:0}.am-spec-list dt{color:#5c7187}.am-spec-list dd{color:#082b59;font-weight:700}.am-before-order{margin:0;padding-inline-start:22px;display:grid;gap:12px;color:#314f6e;font-size:15px;line-height:1.9}.am-detail-section p{font-size:15px;line-height:1.9;color:#52677f;margin:0 0 12px}.am-detail-section a{font-size:15px;font-weight:700;color:#0756d9;text-decoration:underline;text-underline-offset:4px}.am-pdp-details details{margin:0!important;padding:18px 22px!important;border:0!important;border-bottom:1px solid #e5edf5!important}.am-pdp-details summary{font-size:16px;font-weight:800;cursor:pointer;min-height:30px}.am-pdp-details details>div{padding-top:14px}.am-pdp-details .am-hub-links{padding:20px 22px;gap:9px}.am-pdp-details .am-hub-links button{font-size:14px;padding:9px 13px}.am-product-policy-links{display:flex;gap:18px;flex-wrap:wrap;margin:18px 0;padding:14px 0;border-top:1px solid #e1eaf4}.am-product-policy-links a{color:#0756d9;font-weight:700;font-size:14px;min-height:30px;text-decoration:underline;text-underline-offset:4px}.am-policy-footer-links{display:flex;gap:16px;flex-wrap:wrap;margin-top:20px}.am-policy-footer-links a{display:inline-block;color:inherit!important;border-bottom:1px solid currentColor;line-height:2;font-size:14px;font-weight:700}.am-info-view{max-width:1280px;margin:0 auto;padding:28px 20px 64px;color:#082b59;direction:rtl}.am-info-breadcrumb{display:flex;align-items:center;gap:10px;margin-bottom:24px;font-size:14px;color:#647a91}.am-info-breadcrumb a{color:#0756d9}.am-info-hero{padding:46px 44px;background:linear-gradient(115deg,#edfaff,#f6faff);border:1px solid #d4e7f5;border-radius:22px;margin-bottom:26px;display:grid;grid-template-columns:1.7fr .7fr;align-items:center;gap:30px}.am-info-hero h1{font-size:38px!important;line-height:1.5;font-weight:800;margin:8px 0 16px!important;color:#082b59}.am-info-hero p{font-size:18px;line-height:1.9;color:#52677f;max-width:760px;margin:0}.am-info-emblem{justify-self:center;display:grid;place-items:center;width:158px;height:158px;border-radius:38px;background:white;border:1px solid #d6e8f5;box-shadow:0 14px 38px #0a3f7110}.am-info-emblem svg{width:72px;height:72px;color:#0756d9}.am-info-number{font-size:64px;font-weight:800;color:#0756d9;line-height:1}.am-info-emblem small{display:block;font-size:16px;font-weight:700}.am-info-layout{display:grid;grid-template-columns:minmax(0,1.8fr) minmax(270px,.8fr);gap:24px;align-items:start}.am-info-card{padding:30px;border:1px solid #d9e6f2;background:#fff;border-radius:16px;margin-bottom:20px}.am-info-card h2{font-size:24px;font-weight:800;line-height:1.6;margin:0 0 18px}.am-info-card h3{font-size:18px;font-weight:800;margin:0 0 10px}.am-info-card p,.am-info-card li{font-size:16px;line-height:1.95;color:#52677f}.am-info-card p{margin:0 0 14px}.am-info-card p:last-child{margin-bottom:0}.am-info-card ol,.am-info-card ul{margin:0;padding-inline-start:22px;display:grid;gap:12px}.am-info-accent{background:#f2f9ff}.am-info-cities{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:20px 0}.am-info-cities span{border:1px solid #cfe1f3;background:#f4faff;border-radius:10px;padding:16px 8px;color:#0756d9;text-align:center;font-weight:700}.am-info-button{display:flex;align-items:center;justify-content:center;min-height:48px;border:1px solid #0756d9;background:#0756d9;color:#fff!important;border-radius:10px;padding:10px 18px;font-weight:700;font-size:16px;text-decoration:none;margin-top:14px}.am-info-button.secondary{background:white;color:#0756d9!important}.am-info-note{padding:16px;border-inline-start:3px solid #0756d9;background:#f1f8ff;border-radius:8px;font-size:15px;line-height:1.9;color:#365674}.am-info-view details{padding:16px 0;border-bottom:1px solid #e1eaf4}.am-info-view summary{font-size:17px;font-weight:700;cursor:pointer}.am-info-view details p{margin-top:12px}.am-info-links{display:flex;gap:16px;flex-wrap:wrap;margin-top:20px}.am-info-links a{color:#0756d9;font-weight:700;text-decoration:underline;text-underline-offset:4px}.am-info-active #main-content>*:not(.am-info-view){display:none!important}.am-info-view[hidden]{display:none!important}.am-info-active #main-content{padding-top:0!important}.am-info-active .sticky-product-bar,.am-info-active .s-product-sticky-bar,.am-info-active .s-sticky-product-bar{display:none!important}@media(max-width:767px){.am-pdp-intro p{font-size:16px}.am-pdp-trust{gap:7px}.am-pdp-trust span{font-size:12px;padding:8px 10px}.am-pdp-details h2{font-size:21px!important}.am-detail-section,.am-pdp-details .am-detail-head{padding:18px}.am-pdp-details details{padding:16px 18px!important}.am-pdp-details .am-hub-links{padding:18px;display:grid;grid-template-columns:1fr}.am-pdp-details .am-hub-links button{width:100%}.am-info-view{padding:20px 16px 36px}.am-info-hero{grid-template-columns:1fr;padding:28px 22px;gap:22px;border-radius:16px}.am-info-hero h1{font-size:29px!important}.am-info-hero p{font-size:16px}.am-info-emblem{grid-row:1;width:98px;height:98px;border-radius:25px;justify-self:start}.am-info-emblem svg{width:50px;height:50px}.am-info-number{font-size:42px}.am-info-emblem small{font-size:13px}.am-info-layout{grid-template-columns:1fr;gap:0}.am-info-card{padding:22px 20px}.am-info-card h2{font-size:22px}.am-info-card p,.am-info-card li{font-size:15px}.am-info-cities{grid-template-columns:repeat(2,minmax(0,1fr))}.am-info-breadcrumb{margin-bottom:18px}}\n\r\n.am-info-view:focus{outline:none}\r\n";style.textContent+="body.product-single #main-content article.am-native-product-description {\n  box-sizing: border-box;\n  direction: rtl;\n  text-align: right;\n  color: #082b59;\n  background: #fff;\n  border: 1px solid #d8e5f3;\n  border-radius: 18px;\n  padding: clamp(18px, 2.5vw, 30px);\n  margin-block: 24px;\n  max-width: 100%;\n  min-width: 0;\n  font-size: 16px;\n  line-height: 1.95;\n  overflow-wrap: anywhere;\n}\nbody.product-single #main-content article.am-native-product-description :where(h2,h3,h4) {\n  color: #082b59;\n  font-weight: 800;\n  line-height: 1.65;\n  margin-block: 26px 12px;\n}\nbody.product-single #main-content article.am-native-product-description h3 {\n  font-size: clamp(19px, 1.45vw, 23px);\n  border-inline-start: 3px solid #0756d9;\n  padding-inline-start: 12px;\n}\nbody.product-single #main-content article.am-native-product-description > :first-child {\n  margin-block-start: 0;\n}\nbody.product-single #main-content article.am-native-product-description > p:first-of-type {\n  font-size: 17px;\n  color: #24476f;\n  background: #f1f7ff;\n  border-radius: 12px;\n  padding: 15px 18px;\n  margin-block: 0 22px;\n}\nbody.product-single #main-content article.am-native-product-description p {\n  margin-block: 10px 15px;\n}\nbody.product-single #main-content article.am-native-product-description :where(ul,ol) {\n  margin-block: 12px 20px;\n  padding-inline-start: 24px;\n  padding-inline-end: 0;\n}\nbody.product-single #main-content article.am-native-product-description ul {\n  list-style: disc outside;\n}\nbody.product-single #main-content article.am-native-product-description ol {\n  list-style: decimal outside;\n}\nbody.product-single #main-content article.am-native-product-description li {\n  padding-inline-start: 3px;\n  margin-block: 7px;\n}\nbody.product-single #main-content article.am-native-product-description li::marker {\n  color: #0756d9;\n  font-weight: 700;\n}\nbody.product-single #main-content article.am-native-product-description dl {\n  display: grid;\n  grid-template-columns: minmax(110px, .55fr) minmax(0, 1fr);\n  margin-block: 14px 22px;\n  border: 1px solid #d8e5f3;\n  border-radius: 12px;\n  overflow: hidden;\n}\nbody.product-single #main-content article.am-native-product-description :where(dt,dd) {\n  margin: 0;\n  padding: 12px 15px;\n  border-bottom: 1px solid #e5edf6;\n  min-width: 0;\n}\nbody.product-single #main-content article.am-native-product-description dt {\n  background: #f1f7ff;\n  color: #082b59;\n  font-weight: 700;\n}\nbody.product-single #main-content article.am-native-product-description dd {\n  background: #fff;\n}\nbody.product-single #main-content article.am-native-product-description .am-native-table-scroll {\n  box-sizing: border-box;\n  width: 100%;\n  max-width: 100%;\n  min-width: 0;\n  overflow-x: auto;\n  overscroll-behavior-x: contain;\n  border: 1px solid #d8e5f3;\n  border-radius: 12px;\n  margin-block: 14px 22px;\n  scrollbar-width: thin;\n}\nbody.product-single #main-content article.am-native-product-description .am-native-table-scroll:focus-visible {\n  outline: 3px solid #0756d9;\n  outline-offset: 3px;\n}\nbody.product-single #main-content article.am-native-product-description table {\n  width: 100%;\n  border-collapse: collapse;\n  border-spacing: 0;\n  margin: 0;\n  color: #082b59;\n  font-size: 15px;\n  line-height: 1.8;\n}\nbody.product-single #main-content article.am-native-product-description :where(th,td) {\n  min-width: 100px;\n  padding: 12px 15px;\n  text-align: start;\n  vertical-align: top;\n  white-space: normal;\n  overflow-wrap: anywhere;\n  border-bottom: 1px solid #e5edf6;\n}\nbody.product-single #main-content article.am-native-product-description th {\n  background: #f1f7ff;\n  color: #082b59;\n  font-weight: 700;\n}\nbody.product-single #main-content article.am-native-product-description tbody tr:last-child > :where(th,td) {\n  border-bottom: 0;\n}\nbody.product-single #main-content article.am-native-product-description a {\n  color: #0756d9;\n  text-decoration: underline;\n  text-underline-offset: 3px;\n}\nbody.product-single #main-content article.am-native-product-description img {\n  max-width: 100%;\n  height: auto;\n}\n@media (max-width: 639px) {\n  body.product-single #main-content article.am-native-product-description {\n    padding: 17px 15px;\n    margin-block: 20px;\n    border-radius: 14px;\n    font-size: 16px;\n    line-height: 1.9;\n  }\n  body.product-single #main-content article.am-native-product-description h3 {\n    font-size: 20px;\n    margin-block: 24px 11px;\n    padding-inline-start: 10px;\n  }\n  body.product-single #main-content article.am-native-product-description > p:first-of-type {\n    font-size: 16px;\n    padding: 13px 12px;\n  }\n  body.product-single #main-content article.am-native-product-description dl {\n    grid-template-columns: minmax(0, 1fr);\n  }\n  body.product-single #main-content article.am-native-product-description dt {\n    padding-block: 9px;\n    border-bottom: 0;\n  }\n  body.product-single #main-content article.am-native-product-description dd {\n    padding-block: 10px 13px;\n  }\n  body.product-single #main-content article.am-native-product-description :where(th,td) {\n    padding: 10px 12px;\n    font-size: 14px;\n  }\n}\n";document.head.append(style);
  const main=document.getElementById('main-content');if(!main)return;
  const info=e('section','am-info-view');info.hidden=true;info.tabIndex=-1;info.setAttribute('aria-label','معلومات الضمان والشحن');main.append(info);
  let previousTitle=document.title;
  function addTrust(container){const trust=e('div','am-pdp-trust');[['shield','ضمان القطع الكهربائية سنتان'],['truck','شحن لجميع المملكة']].forEach(([type,text])=>{const item=e('span');item.append(icon(type),document.createTextNode(text));trust.append(item)});container.append(trust)}
  function detailSection(title){const s=e('div','am-detail-section');s.append(e('h3','',title));return s}
  function mountProduct(){
   if(!document.body.classList.contains('product-single'))return;
   const title=main.querySelector('h1');
   const article=title?.parentElement?.querySelector('article:not(.am-tool-product)');
   if(!article)return;
   article.classList.remove('am-description-summarized');
   article.classList.add('am-native-product-description');
   main.querySelectorAll('.am-product-guide,.am-pdp-intro,.am07-plan-details').forEach(node=>{if(!article.contains(node))node.remove()});
   article.querySelectorAll('table').forEach(table=>{
    if(table.parentElement?.classList.contains('am-native-table-scroll'))return;
    const wrapper=e('div','am-native-table-scroll');
    wrapper.tabIndex=0;wrapper.setAttribute('role','region');
    wrapper.setAttribute('aria-label',table.querySelector('caption')?.textContent.trim()||'جدول معلومات المنتج');
    table.before(wrapper);wrapper.append(table);
   });
  }
  function card(title,text,cls=''){const c=e('section','am-info-card '+cls);c.append(e('h2','',title));if(text)c.append(e('p','',text));return c}
  function infoPage(kind){
   const isWarranty=kind==='warranty',heading=isWarranty?'الضمان وخدمة ما بعد البيع':'الشحن والتركيب';info.replaceChildren();
   const crumbs=e('nav','am-info-breadcrumb');crumbs.setAttribute('aria-label','مسار الصفحة');crumbs.append(a('الرئيسية',homeUrl()),e('span','','/'),e('span','',heading));info.append(crumbs);
   const hero=e('header','am-info-hero'),copy=e('div');copy.append(e('span','am-detail-eyebrow','المعالج لوحدات تحلية المياه'),e('h1','',heading),e('p','',isWarranty?warranty:coverage));const emblem=e('div','am-info-emblem');if(isWarranty){const n=e('div');n.style.textAlign='center';n.append(e('div','am-info-number','٢'),e('small','','سنتان للقطع الكهربائية'));emblem.append(n)}else emblem.append(icon('truck'));hero.append(copy,emblem);info.append(hero);
   const layout=e('div','am-info-layout'),content=e('div'),side=e('aside');layout.append(content,side);info.append(layout);
   if(isWarranty){
    content.append(card('تغطية الضمان',warranty));
    const help=card('كيف تتواصل معنا بخصوص منتجك؟');const ol=e('ol');['جهّز رقم الطلب إن توفر، واسم المنتج أو موديله.','وضّح المشكلة، وأرفق صورًا أو مقطعًا يوضحها عند التواصل.','تواصل مع فريق المعالج لمراجعة طلبك وتوضيح الخطوة المناسبة.'].forEach(t=>ol.append(e('li','',t)));help.append(ol);content.append(help);
    const questions=card('أسئلة عن الضمان');[['ما مدة الضمان؟',warranty],['لدي استفسار عن قطعة محددة، كيف أتحقق؟','أرسل اسم المنتج وصورة القطعة لفريق المعالج للاستفسار عن تغطيتها.'],['كيف أطلب خدمة لمنتج اشتريته؟','تواصل معنا مع رقم الطلب ووصف المشكلة لتسهيل مراجعة طلب الخدمة.']].forEach(([q,t])=>{const d=e('details');d.append(e('summary','',q),e('p','',t));questions.append(d)});content.append(questions);
   }else{
    content.append(card('الشحن لجميع مدن المملكة','يمكن طلب منتجات المعالج للشحن إلى جميع مدن المملكة، بما فيها المدن الواقعة خارج نطاق التركيب.'));
    const cities=card('المدن المتاح فيها التركيب','يتوفر خيار «مع التركيب» بعد اختيار إحدى المدن التالية:');const grid=e('div','am-info-cities');['الأحساء','الدمام','الرياض','تبوك'].forEach(t=>grid.append(e('span','',t)));cities.append(grid,e('div','am-info-note','بقية مدن المملكة متاح لها الشحن فقط. اختر «بدون تركيب» عند الطلب.'));content.append(cities);
    const costs=card('تكلفة الخدمة وتفاصيل التوصيل');costs.append(e('p','','تظهر أجرة التركيب أو الاستبدال للمنتجات المؤهلة في السلة، وتُحسب لكل قطعة حسب فئة أجرتها. يشمل اختيار الخدمة جميع القطع المؤهلة ضمن فئة الأجرة نفسها.'),e('p','','للاستفسار عن رسوم الشحن ومدة التوصيل إلى مدينتك، تواصل مع الفريق وحدّد المنتجات المطلوبة والمدينة.'));content.append(costs);
    const steps=card('قبل تأكيد طلب التركيب');const ol=e('ol');['اختر مواصفات المنتج وأضفه إلى السلة.','راجع خدمة التركيب ومدينتها والأجرة والإجمالي في السلة، ثم تأكد من عنوان التوصيل.','تواصل مع الفريق لتنسيق تفاصيل الخدمة في موقعك.'].forEach(t=>ol.append(e('li','',t)));steps.append(ol);content.append(steps);
   }
   const contact=card('نساعدك في الخطوة التالية',isWarranty?'أرسل استفسارك عن المنتج أو طلب الخدمة لفريق المعالج.':'اذكر مدينتك والمنتج المطلوب ليراجع الفريق تفاصيل الشحن أو التركيب.','am-info-accent');contact.append(a(isWarranty?'تواصل بخصوص الضمان':'استفسر عن الشحن والتركيب',wa(isWarranty?'أرغب بالاستفسار عن ضمان منتج من المعالج.\nاسم المنتج:\nرقم الطلب إن توفر:\nوصف الاستفسار:':'أرغب بالاستفسار عن الشحن أو التركيب.\nالمدينة:\nالمنتج المطلوب:'),'am-info-button'),a('اتصل بنا: +966533557999','tel:+966533557999','am-info-button secondary'));side.append(contact);
   const other=card(isWarranty?'هل تبحث عن معلومات التوصيل؟':'ضمان القطع الكهربائية',isWarranty?'تعرّف على نطاق الشحن ومدن التركيب.':warranty);other.append(a(isWarranty?'الشحن والتركيب':'تفاصيل الضمان',homeUrl(isWarranty?'#am-shipping':'#am-warranty'),'am-info-button secondary'));side.append(other);
  }
  function route(){const kind=location.hash==='#am-warranty'?'warranty':location.hash==='#am-shipping'?'shipping':null;document.body.classList.toggle('am-info-active',!!kind);info.hidden=!kind;if(kind){infoPage(kind);document.title=(kind==='warranty'?'الضمان وخدمة ما بعد البيع':'الشحن والتركيب')+' | المعالج لوحدات تحلية المياه';window.scrollTo({top:0,behavior:'instant'});info.focus({preventScroll:true})}else document.title=previousTitle;}
  window.addEventListener('click',event=>{if(!document.body.classList.contains('am-info-active'))return;const link=event.composedPath().find(x=>x instanceof HTMLAnchorElement);if(!link)return;let url;try{url=new URL(link.href,location.href)}catch{return}if(url.origin===location.origin&&!['#am-warranty','#am-shipping'].includes(url.hash)&&url.hash.startsWith('#am-')){document.body.classList.remove('am-info-active');info.hidden=true;document.title=previousTitle;const preview=new URLSearchParams(location.search).get('preview');if(preview){url.searchParams.set('preview',preview);link.href=url.href}}},true);
  document.addEventListener('click',event=>{const link=event.composedPath().find(x=>x instanceof HTMLAnchorElement);if(!link)return;let url;try{url=new URL(link.href,location.href)}catch{return}if(!['#am-warranty','#am-shipping'].includes(url.hash))return;if(url.origin!==location.origin)return;event.preventDefault();event.stopImmediatePropagation();history.pushState(null,'',url.hash);route()},true);
  window.addEventListener('hashchange',route);window.addEventListener('popstate',route);
  function patchLegacyWarranty(){document.querySelectorAll('.am-tools-body .am-tool-note').forEach(n=>{if(n.textContent.includes('مواصفات السعة والضمان لا تُستنتج'))n.textContent='اختر منتجين أو ثلاثة. ضمان القطع الكهربائية سنتان لجميع المنتجات. للمقاسات والسعة المطلوبة، اسأل الفريق.'})}
  let queued=false;function mount(){mountProduct();patchLegacyWarranty()}
  new MutationObserver(()=>{if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;mount()})}).observe(main,{childList:true,subtree:true});mount();let count=0;const timer=setInterval(()=>{mount();if(++count>=20)clearInterval(timer)},400);route();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();


/* Phase 07: native Salla commerce UI, draft scoped. No checkout/payment overrides. */
(function(){
  const matchingProducts = {"15784432":[1391072644],"50676917":[440897920],"77942364":[1847314155,1112643817],"83651231":[891853192,157637518,1840455052],"88831962":[891853192,157637518,1840455052],"116766857":[1921824666,547858585,506918372],"122471892":[1031859859,1145614035,1460770523],"157637518":[2058223522,722946974,83651231,1676864733,88831962],"192850360":[746108227,1888188904],"223723490":[1875602366],"332856963":[1457162648],"395195812":[1391072644],"398807783":[502156477],"407782294":[1031859859,1145614035,1460770523],"440897920":[1073719279,827775456,50676917],"473868266":[1775024552],"502156477":[398807783,1004594676,1888188904],"543722590":[1847314155,1112643817],"583001739":[1746080997],"648960751":[1733494443],"689962476":[825763252],"722946974":[891853192,157637518,1840455052],"750204037":[1954274764,1178664141],"825763252":[689962476],"827775456":[440897920],"891853192":[722946974,83651231,1676864733,88831962],"895985355":[1031859859,1145614035,1460770523],"973824823":[1391072644],"1000986793":[1847314155,1112643817],"1004594676":[1775024552],"1031859859":[1781228183,407782294,1361700053,122471892,895985355,1536853962],"1066941581":[1921824666,547858585,506918372],"1073719279":[440897920],"1108966318":[1847314155,1112643817],"1112643817":[1108966318,1000986793,543722590,77942364],"1145614035":[1781228183,407782294,1361700053,122471892,895985355,1536853962],"1282004635":[1355990922],"1314989205":[1746080997],"1355990922":[1282004635],"1361700053":[1031859859,1145614035,1460770523],"1391072644":[15784432,973824823,395195812],"1421949934":[1558340534],"1457162648":[1531083407,332856963],"1460770523":[1781228183,407782294,1361700053,122471892,895985355,1536853962],"1531083407":[1457162648],"1536853962":[1031859859,1145614035,1460770523],"1558340534":[1421949934],"1676864733":[891853192,157637518,1840455052],"1700513977":[1954274764],"1733494443":[648960751],"1746080997":[1314989205,583001739],"1775024552":[1004594676,473868266],"1781228183":[1031859859,1145614035,1460770523],"1840455052":[722946974,83651231,1676864733,88831962],"1847314155":[1108966318,1000986793,543722590,77942364],"1875602366":[223723490,1888188904],"1921824666":[1066941581,116766857,2089026964],"1954274764":[1700513977],"2089026964":[1921824666,547858585,506918372]};

 const housingIds=new Set(["116766857","157637518","332856963","891853192","1066941581","1531083407","1840455052","2089026964"]);
 const stationIds=new Set(["440897920","1391072644"]);
 const boxDevices=new Set(["784892599","1249034417","2023072176","610267058","1073819068","1982074547"]);
 const boxRecommendations=[306995717,940572209,1634423973,535272111,436201817,1173894118,864588001,1638035936,1888188904];
 for(const device of boxDevices) matchingProducts[device]=boxRecommendations;
 function setupCartRecommendations(){
  if(!document.body.classList.contains('cart') || document.querySelector('#am-cart-matches')) return;
  const main=document.querySelector('main#main-content');
  if(!main || !window.salla?.cart?.details) return;
  const devices=new Set([...deviceIds,...boxDevices,...housingIds,...['750204037','192850360','502156477','1875602366','440897920','1391072644','1700513977','543722590','77942364']]);
  const box=document.createElement('section');box.className='container am07-related';box.id='am-cart-matches';box.hidden=true;main.append(box);
  let revision=0,timer,last='';
  async function update(version){
   try{
    const response=await salla.cart.details();
    if(version!==revision)return;
    const data=response?.data?.data??response?.data??response;
    const lines=data?.items??data?.cart?.items;
    if(!Array.isArray(lines))return;
    const ids=lines.map(item=>item.product_id??item.product?.id);
    if(ids.some(id=>id==null))return;
    const present=new Set(ids.map(String));
    const groups=[...present].filter(id=>devices.has(id)).map(id=>matchingProducts[id]||[]);
    const picks=new Set([...present].some(id=>deviceIds.includes(id)) ? standardPlanIds.map(String).filter(id=>!present.has(id)) : []);
    for(let rank=0;rank<Math.max(0,...groups.map(group=>group.length));rank++)for(const group of groups){
     const candidate=group[rank];if(candidate&&!present.has(String(candidate)))picks.add(String(candidate));
    }
    const selected=[...picks].slice(0,[...present].some(id=>deviceIds.includes(id)||boxDevices.has(id)||housingIds.has(id)||stationIds.has(id))?picks.size:6),signature=selected.join(',');
    if(signature!==last){box.replaceChildren();last=signature;
     if(selected.length){const slider=document.createElement('salla-products-slider');slider.setAttribute('source','selected');slider.setAttribute('limit',String(selected.length));slider.setAttribute('source-value',JSON.stringify(selected));slider.setAttribute('block-title','منتجات مرتبطة بالأجهزة في سلتك');box.append(slider)}
    }
    box.hidden=!selected.length;
   }catch{if(version===revision)box.hidden=true}
  }
  function schedule(){box.hidden=true;const version=++revision;clearTimeout(timer);timer=setTimeout(()=>update(version),100)}
  for(const name of ['cart::updated','cart::item.added','cart::item.deleted','cart::item.updated'])salla.event.on(name,schedule);
  window.addEventListener('pageshow',schedule);schedule();
 }
 function mountCartRecommendations(){if(window.salla?.onReady)salla.onReady(setupCartRecommendations);else document.addEventListener('salla::ready',setupCartRecommendations,{once:true})}
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mountCartRecommendations,{once:true});else queueMicrotask(mountCartRecommendations);

 const deviceIds=['1775024552','1108966318','1000986793','825763252','1558340534','1733494443'];
 // Standard seven-stage housings use the regular 10-inch filter family.
 const standardPlanIds=[1593553312,1418337955];
 const standardFilterIds=[1004594676,1276299864,1031859859,1498033309,258805148,1168185179,1451388253,683724961,220107431,1847314155,648960751,1421949934,689962476,1597169379,1112643817,473868266,2061769965,1888188904];
 for(const device of deviceIds){
   matchingProducts[device]=[...new Set([...standardPlanIds,...(matchingProducts[device]||[]),...standardFilterIds])];
 }
 for(const filter of standardFilterIds){
   matchingProducts[filter]=[...new Set([...deviceIds.map(Number),...(matchingProducts[filter]||[])])];
 }

 const offerIds=['1808009306','543722590','1916119903','77942364'];
 const partIds=['1031859859','1498033309','258805148','1173894118'];
 const plans={'1418337955':{term:'5 سنوات',visits:'10 زيارات',items:['10 أطقم فلاتر — 3 مراحل','5 فلاتر بوست كاربون','3 فلاتر مينرال','3 فلاتر ألكالين','فلتران ممبرين']},'1593553312':{term:'سنتان ونصف',visits:'5 زيارات',items:['5 أطقم فلاتر — 3 مراحل','فلتران بوست كاربون','فلتر مينرال','فلتر ألكالين','فلتر ممبرين']},"306995717":{"term":"سنتان","visits":"4 زيارات","items":["4 أطقم فلاتر — 3 مراحل، 12 بوصة","فلتران بوست كاربون","فلتر ممبرين 75 جالون"],"specs":[["مقاس الفلاتر","12 بوصة"],["الأجهزة المناسبة","الكومباكت بتقنية النانو والبرادات المدمجة بفلاتر داخلية"],["الممبرين","75 جالون"]],"schedule":[["طقم فلاتر 3 مراحل","كل 6 أشهر"],["بوست كاربون","كل سنة"],["الممبرين","كل سنتين"]]},"940572209":{"term":"4 سنوات","visits":"8 زيارات","items":["8 أطقم فلاتر — 3 مراحل، 12 بوصة","4 فلاتر بوست كاربون","فلتران ممبرين 75 جالون"],"specs":[["مقاس الفلاتر","12 بوصة"],["الأجهزة المناسبة","الكومباكت بتقنية النانو والبرادات المدمجة بفلاتر داخلية"],["الممبرين","75 جالون"]],"schedule":[["طقم فلاتر 3 مراحل","كل 6 أشهر"],["بوست كاربون","كل سنة"],["الممبرين","كل سنتين"]]},"15784432":{"family":"station-200","capacity":200,"years":2,"term":"سنتان","visits":"4 زيارات"},"973824823":{"family":"station-200","capacity":200,"years":4,"term":"4 سنوات","visits":"8 زيارات"},"1073719279":{"family":"station-400","capacity":400,"years":2,"term":"سنتان","visits":"4 زيارات"},"827775456":{"family":"station-400","capacity":400,"years":4,"term":"4 سنوات","visits":"8 زيارات"}};
 const cities=['الأحساء','الدمام','الرياض','تبوك'];
 const e=(tag,cls,text)=>{const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n};
 const a=(text,href,cls)=>{const n=e('a',cls,text);n.href=href;return n};
 const button=(text,fn)=>{const b=e('button','',text);b.type='button';b.addEventListener('click',fn);return b};
 function draftUrl(path){const u=new URL(path,location.origin);if(location.hostname==='salla.sa'&&!u.pathname.startsWith('/almoalej.com'))u.pathname='/almoalej.com'+(u.pathname.startsWith('/')?u.pathname:'/'+u.pathname);const preview=new URLSearchParams(location.search).get('preview');if(preview)u.searchParams.set('preview',preview);return u.href}
 function cleanPhotoName(s){return String(s||'').replace(/\.(webp|png|jpe?g)$/i,'').replace(/\s+webp$/i,'').replace(/-/g,' ').trim()}
 function nativeOptions(form){try{return JSON.parse(form.querySelector('salla-product-options')?.getAttribute('options')||'[]')}catch{return []}}
 function containsInstall(options){return options.some(o=>(o.details||[]).some(d=>/^مع\s*(?:ال)?تركيب/.test(d.name))&&(o.details||[]).some(d=>/بدون\s*(?:ال)?تركيب/.test(d.name)))}
 function lineNotes(text,city,key){const base=String(text||'').split('\n').filter(l=>!l.startsWith(key+':')).join('\n').trim();return [base,city?key+': '+city:''].filter(Boolean).join('\n')}
 function start(){
  if(getComputedStyle(document.documentElement).getPropertyValue('--am-motion-enabled').trim()!=='1'||document.body.classList.contains('am-commerce07'))return;
  if(!document.getElementById('main-content'))return;document.body.classList.add('am-commerce07');
  const style=e('style');style.textContent="/* Phase 07: native Salla commerce surfaces. Applied only by the draft module. */\nbody.am-commerce07{--am07-blue:#0756d9;--am07-ink:#082b59;--am07-muted:#526b84;--am07-line:#d9e6f2;--am07-tint:#f2f8ff;--am07-shadow:0 12px 30px #082b590c}\nbody.am-commerce07 .am07-type-note,body.am-commerce07 .am07-help{padding:15px 18px;border:1px solid var(--am07-line);border-radius:12px;background:var(--am07-tint);color:var(--am07-muted);font-size:15px;line-height:1.9;text-align:right;margin:15px 0}\nbody.am-commerce07 .am07-type-note strong,body.am-commerce07 .am07-help strong{color:var(--am07-ink)}\nbody.am-commerce07 .am07-type-note a,body.am-commerce07 .am07-help a{color:var(--am07-blue);font-weight:700;text-decoration:underline;text-underline-offset:4px}\nbody.am-commerce07 .am07-type-badge{display:inline-flex;align-items:center;min-height:29px;padding:4px 10px;border:1px solid #d8e8f7;background:#f1f8ff;border-radius:7px;color:#195280;font-size:12px;line-height:1.5;font-weight:700;margin-bottom:10px}\nbody.am-commerce07 .am07-selection-summary{margin:12px 0;padding:13px 16px;border-inline-start:3px solid var(--am07-blue);border-radius:8px;background:#f0f7ff;color:var(--am07-ink);font-size:14px;line-height:1.9;overflow-wrap:anywhere}\nbody.am-commerce07 .am07-price-box{display:flex;align-items:center;flex-wrap:wrap;gap:9px 14px;padding:19px 20px;border:1px solid #d4e5f5;border-radius:14px;background:linear-gradient(115deg,#f2f9ff,#fff);margin:16px 0;color:var(--am07-ink)}\nbody.am-commerce07 .am07-price-box h2.total-price{font-size:30px!important;line-height:1.4;font-weight:800;color:var(--am07-ink)!important;letter-spacing:0;white-space:normal}\nbody.am-commerce07 .am07-price-box .before-price,body.am-commerce07 .am07-price-box .line-through{font-size:15px;color:#73879b;text-decoration-thickness:1px}\nbody.am-commerce07 .am07-price-box .am07-price-caption{flex-basis:100%;font-size:13px;color:var(--am07-muted);line-height:1.8}\nbody.am-commerce07.product-single form.product-form select,body.am-commerce07.product-single form.product-form input:not([type=radio]):not([type=checkbox]):not([type=hidden]),body.am-commerce07.product-single form.product-form textarea{font-size:16px;min-height:46px;border-radius:9px}\nbody.am-commerce07.product-single form.product-form select{border-color:#bfd2e6;color:var(--am07-ink);background-color:#fff}\nbody.am-commerce07.product-single .s-product-options-option-container{padding:18px;border:1px solid var(--am07-line);border-radius:14px;background:#fff;margin-bottom:18px}\nbody.am-commerce07.product-single .s-product-options-option-label{display:block;margin-bottom:13px;color:var(--am07-ink);font-size:16px;line-height:1.7}\nbody.am-commerce07.product-single .s-product-options-option-label small{color:var(--am07-muted);font-weight:400}\nbody.am-commerce07.product-single .s-product-options-thumbnails-wrapper{display:grid!important;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px!important;width:100%}\nbody.am-commerce07.product-single .s-product-options-thumbnails-wrapper>div{min-width:0;width:auto!important;display:flex;flex-direction:column;align-items:stretch;gap:7px;padding:7px;border:1px solid #e1eaf3;border-radius:10px;background:#fff;transition:border-color .18s,box-shadow .18s}\nbody.am-commerce07.product-single .s-product-options-thumbnails-wrapper>div:has(input:checked){border-color:var(--am07-blue);box-shadow:0 0 0 1px var(--am07-blue);background:#f5faff}\nbody.am-commerce07.product-single .s-product-options-thumbnails-wrapper label{width:100%!important;height:auto!important;min-height:64px;aspect-ratio:1/1;max-width:none!important;display:flex;align-items:center;justify-content:center;border-radius:7px;overflow:hidden;background:#fff;cursor:pointer}\nbody.am-commerce07.product-single .s-product-options-thumbnails-wrapper label img{width:100%!important;height:100%!important;object-fit:contain!important;padding:4px;background:white}\nbody.am-commerce07.product-single .s-product-options-thumbnails-wrapper p{font-size:12px;line-height:1.7;text-align:center;color:var(--am07-ink);margin:0;overflow-wrap:anywhere}\nbody.am-commerce07.product-single .s-product-options-thumbnails-wrapper input:focus-visible+label{outline:3px solid #7db6ff;outline-offset:2px}\nbody.am-commerce07.product-single salla-slider.details-slider{border:1px solid #deE9f3;border-radius:18px!important;overflow:hidden;background:#fff;box-shadow:var(--am07-shadow)}\nbody.am-commerce07.product-single salla-slider.details-slider .swiper-slide img{object-fit:contain!important;object-position:center!important;background:#fff!important}\nbody.am-commerce07.product-single salla-slider.details-slider .slide--one-fourth{border:1px solid #dfe9f3;border-radius:10px;overflow:hidden;background:#fff;cursor:pointer}\nbody.am-commerce07.product-single salla-slider.details-slider .slide--one-fourth img{padding:5px;border-radius:8px!important}\nbody.am-commerce07.product-single salla-slider.details-slider .swiper-slide-thumb-active{border:2px solid var(--am07-blue)!important;box-shadow:0 0 0 2px #0756d915}\nbody.am-commerce07.product-single salla-slider.details-slider .s-slider-prev,body.am-commerce07.product-single salla-slider.details-slider .s-slider-next{min-width:44px;min-height:44px;border:1px solid #d7e3ef;border-radius:50%;color:var(--am07-ink);background:#fffffff0;box-shadow:0 3px 10px #082b5910}\nbody.am-commerce07 .am07-gallery-tools{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;padding:12px 3px;margin:3px 0 18px;color:var(--am07-muted);font-size:13px}\nbody.am-commerce07 .am07-gallery-tools button{display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:44px;padding:9px 15px;border:1px solid #cadaec;background:#fff;color:var(--am07-blue);border-radius:9px;font:700 14px/1.5 Tajawal,Tahoma,Arial;cursor:pointer}\nbody.am-commerce07 .am07-gallery-tools button:hover{background:#f2f8ff;border-color:#0756d9}\nbody.am-commerce07 .am07-gallery-tools [role=status]{line-height:1.8}\nbody.am-commerce07 .am07-lightbox{width:min(1100px,calc(100vw - 32px));max-width:none;max-height:94dvh;margin:auto;padding:0;border:1px solid #dbe6f1;border-radius:18px;background:#fff;color:var(--am07-ink);overflow:auto;box-shadow:0 28px 100px #02142d50;direction:rtl}\nbody.am-commerce07 .am07-lightbox::backdrop{background:#051b35cc;backdrop-filter:blur(5px)}\nbody.am-commerce07 .am07-lightbox header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:15px 20px;border-bottom:1px solid #e3ebf3;background:#f8fbff}\nbody.am-commerce07 .am07-lightbox header h2{font-size:18px;line-height:1.6;font-weight:700;margin:0}\nbody.am-commerce07 .am07-lightbox button{display:inline-flex;align-items:center;justify-content:center;min-width:44px;min-height:44px;padding:8px 14px;border:1px solid #cddded;background:#fff;border-radius:9px;color:var(--am07-blue);font:700 15px/1.4 Tajawal,Tahoma,Arial;cursor:pointer;flex-shrink:0}\nbody.am-commerce07 .am07-lightbox>img{display:block;width:100%;height:min(68dvh,760px);object-fit:contain;padding:12px;background:white}\nbody.am-commerce07 .am07-lightbox footer,body.am-commerce07 .am07-lightbox nav{display:flex;align-items:center;justify-content:center;gap:16px;flex-wrap:wrap;padding:12px 20px;border-top:1px solid #e3ebf3;background:#f8fbff;color:var(--am07-muted);font-size:14px;line-height:1.8}\nbody.am-commerce07 .am07-lightbox button:focus-visible,body.am-commerce07 .am07-gallery-tools button:focus-visible{outline:3px solid #70a9f7;outline-offset:3px}\nbody.am-commerce07.product-single form.product-form salla-add-product-button .s-button-element.s-button-btn{min-height:50px;border-radius:10px;font-size:16px;font-weight:800;line-height:1.6}\nbody.am-commerce07.product-single form.product-form salla-add-product-button .s-button-text{white-space:normal!important;text-overflow:clip!important;overflow:visible!important;word-break:normal;line-height:1.6}\nbody.am-commerce07.product-single form.product-form salla-add-product-button .s-button-text>span{white-space:normal!important}\nbody.am-commerce07.product-single .sticky-product-bar__btn{min-width:0}\nbody.am-commerce07.product-single .sticky-product-bar__btn .s-add-product-button-main{gap:8px}\nbody.am-commerce07.product-single .sticky-product-bar__btn .s-add-product-button-main>*{min-width:0}\nbody.am-commerce07.product-single .sticky-product-bar__quantity .s-quantity-input-button{min-width:44px;min-height:44px}\nbody.am-commerce07 .am07-service-fields{display:grid;grid-template-columns:1fr;gap:16px;padding:20px;margin:18px 0;border:1px solid var(--am07-line);border-radius:14px;background:#f5faff}\nbody.am-commerce07 .am07-service-fields label{display:grid;gap:8px;font-size:15px;font-weight:700;color:var(--am07-ink);line-height:1.8}\nbody.am-commerce07 .am07-service-fields input,body.am-commerce07 .am07-service-fields textarea{width:100%;min-height:48px;padding:11px 13px;border:1px solid #bfd2e6;border-radius:9px;background:#fff;font:400 16px/1.7 Tajawal,Tahoma,Arial;color:var(--am07-ink);box-sizing:border-box}\nbody.am-commerce07 .am07-service-fields textarea{min-height:92px;resize:vertical}\nbody.am-commerce07 .am07-service-fields p{font-size:14px;line-height:1.9;color:var(--am07-muted);margin:0}\nbody.am-commerce07 .am07-service-fields input:focus,body.am-commerce07 .am07-service-fields textarea:focus{outline:2px solid #75aff6;outline-offset:2px}\nbody.am-commerce07 .am07-related-empty{padding:24px;margin:18px 0;border:1px dashed #c9ddec;border-radius:14px;color:var(--am07-muted);background:#f8fbff;text-align:center;font-size:15px;line-height:1.9}\nbody.am-commerce07:is(.product-index,.product-index-search) .am07-list-hero{max-width:1280px;width:calc(100% - 40px);margin:0 auto 22px!important;padding:28px 30px;border:1px solid #d3e5f5;border-radius:18px;background:linear-gradient(115deg,#edf9ff,#f7faff);color:var(--am07-ink);text-align:right;box-sizing:border-box}\nbody.am-commerce07:is(.product-index,.product-index-search) .am07-list-hero>span{display:block;font-size:12px;font-weight:800;color:var(--am07-blue);margin-bottom:7px}\nbody.am-commerce07:is(.product-index,.product-index-search) .am07-list-hero h1{font-size:30px!important;font-weight:800;line-height:1.6;margin:0 0 12px!important;color:var(--am07-ink)}\nbody.am-commerce07:is(.product-index,.product-index-search) .am07-list-hero p{font-size:16px;line-height:1.9;color:var(--am07-muted);margin:0;max-width:850px}\nbody.am-commerce07 .am07-list-tools{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;margin:18px 0 0}\nbody.am-commerce07 .am07-list-tools form,body.am-commerce07 .am07-list-tools form.search{display:flex;gap:8px;align-items:center;flex:1 1 360px;max-width:620px;min-width:0}\nbody.am-commerce07 .am07-list-tools input{min-width:0;flex:1 1 auto;min-height:48px;padding:11px 15px;border:1px solid #bdd1e6;border-radius:10px;background:#fff;color:var(--am07-ink);font:400 16px/1.5 Tajawal,Tahoma,Arial;box-sizing:border-box}\nbody.am-commerce07 .am07-list-tools button{flex:0 0 auto;min-height:48px;padding:10px 22px;border:1px solid var(--am07-blue);border-radius:10px;background:var(--am07-blue);color:#fff;font:700 16px/1.5 Tajawal,Tahoma,Arial;cursor:pointer}\nbody.am-commerce07 .am07-list-tools input:focus-visible{outline:2px solid #75aff6;outline-offset:2px}\nbody.am-commerce07 .am07-tags{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:16px}\nbody.am-commerce07 .am07-tags a{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:8px 14px;border:1px solid #cadff0;border-radius:24px;background:#fff;color:#1c568b;font-size:14px;font-weight:700;text-decoration:none;line-height:1.6}\nbody.am-commerce07 .am07-tags a:hover{border-color:var(--am07-blue);color:var(--am07-blue);background:#edf6ff}\nbody.am-commerce07:is(.product-index,.product-index-search) .container--products-list{gap:24px;align-items:flex-start}\nbody.am-commerce07:is(.product-index,.product-index-search) salla-filters#filters-menu{border:1px solid #d7e5f2;border-radius:14px;background:#fff;padding:18px;width:250px;box-sizing:border-box}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-filters-widget-container{border-bottom:1px solid #e1eaf3;padding-bottom:16px;margin-bottom:16px}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-filters-widget-container:last-child{border-bottom:0;margin-bottom:0;padding-bottom:0}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-filters-widget-title{font-size:17px;color:var(--am07-ink);font-weight:800;margin-bottom:12px}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-filters-label{min-height:44px;display:flex;align-items:center;gap:9px;font-size:14px;color:#355572;line-height:1.7;padding:5px 0;cursor:pointer}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-filters-checkbox,body.am-commerce07:is(.product-index,.product-index-search) .s-filters-radio{width:19px;height:19px;flex-shrink:0;accent-color:var(--am07-blue)}\nbody.am-commerce07:is(.product-index,.product-index-search) select#product-filter{min-height:46px;padding:9px 14px!important;border:1px solid #c7daeb;border-radius:9px;background:#fff;color:var(--am07-ink);font-size:15px;line-height:1.7;max-width:100%}\nbody.am-commerce07:is(.product-index,.product-index-search) salla-products-list{min-width:0}\nbody.am-commerce07:is(.product-index,.product-index-search) salla-products-list .s-products-list-wrapper{display:grid!important;grid-template-columns:repeat(3,minmax(0,1fr))!important;gap:18px!important;align-items:stretch}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-entry,body.am-commerce07.product-single salla-products-slider .s-product-card-entry{border:1px solid #dbe6f1;border-radius:14px!important;overflow:hidden;background:#fff;box-shadow:0 4px 14px #082b5904;transition:border-color .2s,box-shadow .2s,transform .2s;min-width:0;height:100%}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-entry:hover,body.am-commerce07.product-single salla-products-slider .s-product-card-entry:hover{border-color:#98bce9;box-shadow:0 10px 25px #082b5910;transform:translateY(-2px)}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-image,body.am-commerce07.product-single salla-products-slider .s-product-card-image{height:auto!important;aspect-ratio:1/1;background:#fff;padding:12px;box-sizing:border-box}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-image>a,body.am-commerce07.product-single salla-products-slider .s-product-card-image>a{height:100%;width:100%;display:block}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-image img,body.am-commerce07.product-single salla-products-slider .s-product-card-image img{width:100%!important;height:100%!important;object-fit:contain!important;background:#fff!important;border-radius:8px}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content,body.am-commerce07.product-single salla-products-slider .s-product-card-content{padding:16px!important;gap:10px;min-width:0;display:flex;flex-direction:column;flex:1}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content-title,body.am-commerce07.product-single salla-products-slider .s-product-card-content-title{font-size:16px!important;line-height:1.8!important;font-weight:700;min-height:58px;color:var(--am07-ink);margin:0}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content-title a,body.am-commerce07.product-single salla-products-slider .s-product-card-content-title a{color:var(--am07-ink);overflow-wrap:anywhere}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-sale-price h4,body.am-commerce07:is(.product-index,.product-index-search) .s-product-card-price,body.am-commerce07.product-single salla-products-slider .s-product-card-sale-price h4,body.am-commerce07.product-single salla-products-slider .s-product-card-price{font-size:21px!important;font-weight:800;color:var(--am07-ink)!important;line-height:1.5}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-sale-price>span,body.am-commerce07.product-single salla-products-slider .s-product-card-sale-price>span{color:#7c8fa1;font-size:13px}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content-footer,body.am-commerce07.product-single salla-products-slider .s-product-card-content-footer{margin-top:auto;padding-top:6px}\nbody.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content-footer .s-button-element,body.am-commerce07.product-single salla-products-slider .s-product-card-content-footer .s-button-element{min-height:46px;border-radius:9px;font-size:14px;font-weight:700;white-space:normal}\nbody.am-commerce07 .am07-card-link{width:100%;display:flex;align-items:center;justify-content:center;min-height:46px;padding:10px 13px;border:1px solid var(--am07-blue);border-radius:9px;background:#fff;color:var(--am07-blue)!important;font-size:14px;font-weight:700;line-height:1.6;text-decoration:none;box-sizing:border-box;text-align:center}\nbody.am-commerce07 .am07-card-link:hover{background:var(--am07-blue);color:white!important}\nbody.am-commerce07 .am07-card-link:focus-visible,body.am-commerce07 .am07-tags a:focus-visible,body.am-commerce07 .am07-list-tools button:focus-visible{outline:3px solid #75aff6;outline-offset:3px}\nbody.am-commerce07 .am07-card-meta{font-size:12px;line-height:1.8;color:var(--am07-muted);margin:0 0 4px}\nbody.am-commerce07.cart .cart-item{border:1px solid #d7e5f1;border-radius:17px!important;box-shadow:0 8px 24px #082b5906;background:#fff}\nbody.am-commerce07.cart .cart-item h1{font-size:18px!important;font-weight:800;line-height:1.8;color:var(--am07-ink)}\nbody.am-commerce07.cart .cart-item h1 a{color:var(--am07-ink)}\nbody.am-commerce07.cart .cart-item select{min-height:46px;font-size:16px;border-color:#bfd2e5;border-radius:9px;color:var(--am07-ink);background:#fff}\nbody.am-commerce07.cart .cart-item .am-cart-city{border-radius:12px!important;background:#f1f8ff!important;border-color:#cbdff2!important}\nbody.am-commerce07.cart .cart-item .s-quantity-input-button{min-width:44px;min-height:44px}\nbody.am-commerce07.cart .cart-item .s-quantity-input-input{min-width:42px;font-size:16px}\nbody.am-commerce07.cart .am07-cart-note{font-size:14px;line-height:1.9;color:var(--am07-muted);padding:12px 15px;background:#f6faff;border:1px solid #dbe8f3;border-radius:10px;margin:14px 0}\nbody.am-commerce07.cart .am07-cart-continue{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:9px 15px;border:1px solid #c5d9ed;border-radius:9px;background:white;color:var(--am07-blue);font-size:14px;font-weight:700;text-decoration:none;margin:10px 0}\n@media(min-width:768px) and (max-width:1100px){body.am-commerce07:is(.product-index,.product-index-search) salla-products-list .s-products-list-wrapper{grid-template-columns:repeat(2,minmax(0,1fr))!important}body.am-commerce07:is(.product-index,.product-index-search) salla-filters#filters-menu{width:220px;padding:14px}body.am-commerce07:is(.product-index,.product-index-search) .container--products-list{gap:18px}}\n@media(max-width:767px){\n body.am-commerce07 .am07-type-note,body.am-commerce07 .am07-help{padding:13px 14px;font-size:14px}\n body.am-commerce07 .am07-price-box{padding:15px 16px;gap:7px 12px}\n body.am-commerce07 .am07-price-box h2.total-price{font-size:28px!important}\n body.am-commerce07.product-single .s-product-options-option-container{padding:14px;border-radius:12px;margin-bottom:16px}\n body.am-commerce07.product-single .s-product-options-thumbnails-wrapper{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px!important}\n body.am-commerce07.product-single .s-product-options-thumbnails-wrapper label{aspect-ratio:1.1/1;min-height:70px}\n body.am-commerce07.product-single .s-product-options-thumbnails-wrapper p{font-size:12px;line-height:1.7}\n body.am-commerce07.product-single salla-slider.details-slider{border-radius:13px!important}\n body.am-commerce07 .am07-gallery-tools{padding:10px 0;gap:8px;font-size:12px}\n body.am-commerce07 .am07-gallery-tools button{font-size:13px;padding:8px 12px}\n body.am-commerce07 .am07-lightbox{width:calc(100vw - 16px);max-height:94dvh;border-radius:13px}\n body.am-commerce07 .am07-lightbox header{padding:12px;gap:10px}\n body.am-commerce07 .am07-lightbox header h2{font-size:15px}\n body.am-commerce07 .am07-lightbox>img{height:62dvh;padding:5px}\n body.am-commerce07 .am07-lightbox footer,body.am-commerce07 .am07-lightbox nav{padding:10px 12px;gap:12px;font-size:13px}\n body.am-commerce07.product-single .sticky-product-bar__btn .s-button-element{font-size:14px!important;padding:10px 12px!important;min-height:46px!important;line-height:1.5}\n body.am-commerce07.product-single .sticky-product-bar__btn .s-button-text{white-space:normal!important;font-size:14px!important;line-height:1.55!important;overflow:visible!important;text-overflow:clip!important}\n body.am-commerce07.product-single .sticky-product-bar__btn .s-add-product-button-main{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px}\n body.am-commerce07.product-single .sticky-product-bar__btn .s-add-product-button-main salla-button,body.am-commerce07.product-single .sticky-product-bar__btn .s-add-product-button-main salla-mini-checkout-widget{width:100%!important;min-width:0}\n body.am-commerce07 .am07-service-fields{padding:16px;gap:14px}\n body.am-commerce07:is(.product-index,.product-index-search) .am07-list-hero{width:calc(100% - 32px);padding:22px 18px;margin-bottom:18px!important;border-radius:14px}\n body.am-commerce07:is(.product-index,.product-index-search) .am07-list-hero h1{font-size:25px!important;line-height:1.6}\n body.am-commerce07:is(.product-index,.product-index-search) .am07-list-hero p{font-size:14px;line-height:1.9}\n body.am-commerce07 .am07-list-tools{gap:10px;margin-top:15px}\n body.am-commerce07 .am07-list-tools form{flex-basis:100%;width:100%;gap:7px}\n body.am-commerce07 .am07-list-tools input{font-size:16px;padding:10px 11px}\n body.am-commerce07 .am07-list-tools button{font-size:14px;padding:10px 15px}\n body.am-commerce07 .am07-tags{gap:7px;margin-top:13px}\n body.am-commerce07 .am07-tags a{font-size:12px;min-height:44px;padding:8px 11px}\n body.am-commerce07:is(.product-index,.product-index-search) .container--products-list{gap:16px}\n body.am-commerce07:is(.product-index,.product-index-search) salla-filters#filters-menu{width:100%;padding:16px;border-radius:14px}\n body.am-commerce07:is(.product-index,.product-index-search) select#product-filter{font-size:14px;min-height:44px}\n body.am-commerce07:is(.product-index,.product-index-search) salla-products-list .s-products-list-wrapper{grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:12px!important}\n body.am-commerce07:is(.product-index,.product-index-search) .s-product-card-image,body.am-commerce07.product-single salla-products-slider .s-product-card-image{padding:7px}\n body.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content,body.am-commerce07.product-single salla-products-slider .s-product-card-content{padding:11px!important;gap:8px}\n body.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content-title,body.am-commerce07.product-single salla-products-slider .s-product-card-content-title{font-size:14px!important;line-height:1.8!important;min-height:76px}\n body.am-commerce07:is(.product-index,.product-index-search) .s-product-card-sale-price h4,body.am-commerce07:is(.product-index,.product-index-search) .s-product-card-price,body.am-commerce07.product-single salla-products-slider .s-product-card-sale-price h4,body.am-commerce07.product-single salla-products-slider .s-product-card-price{font-size:19px!important}\n body.am-commerce07:is(.product-index,.product-index-search) .s-product-card-content-footer .s-button-element,body.am-commerce07.product-single salla-products-slider .s-product-card-content-footer .s-button-element,body.am-commerce07 .am07-card-link{font-size:13px;min-height:46px;padding:9px 7px}\n body.am-commerce07 .am07-type-badge{font-size:11px;padding:4px 7px;min-height:27px;margin-bottom:6px}\n body.am-commerce07.cart .cart-item{border-radius:14px!important}\n body.am-commerce07.cart .cart-item h1{font-size:16px!important;line-height:1.85}\n body.am-commerce07.cart .cart-item .am-cart-city{padding:12px!important}\n body.am-commerce07.cart .cart-item .s-quantity-input-button{min-width:44px;min-height:44px}\n}\n@media(prefers-reduced-motion:reduce){body.am-commerce07 .s-product-card-entry,body.am-commerce07 .s-product-options-thumbnails-wrapper>div{transition:none!important;transform:none!important}}\n\nbody.am-commerce07 .am07-lightbox>img{touch-action:pan-y pinch-zoom}\nbody.am-commerce07 .am07-photo-caption{direction:ltr;unicode-bidi:isolate}\n\r\nbody.am-commerce07 .am07-price-box.hidden{display:none!important}body.am-commerce07 .am07-service-fields select{width:100%;min-height:48px;padding:10px;border:1px solid #bfd2e6;border-radius:9px;background:white;color:#082b59;font-size:16px}body.am-commerce07 .am07-filter-reset{width:100%;min-height:44px;border:1px solid #cfe0ef;border-radius:8px;background:white;color:#0756d9;font-weight:700;margin-bottom:14px}\r\nbody.am-commerce07 salla-add-product-button.am07-configurable-add{display:none!important}\r\n";document.head.append(style);
  const main=document.getElementById('main-content'),id=location.pathname.match(/\/p(\d+)/)?.[1];
  let scheduled=false;function schedule(){if(scheduled)return;scheduled=true;requestAnimationFrame(()=>{scheduled=false;mount()})}
  function preservePreview(){if(!new URLSearchParams(location.search).has('preview'))return;document.querySelectorAll('a[href]').forEach(link=>{let u;try{u=new URL(link.href,location.href)}catch{return}if(!['almoalej.com','salla.sa'].includes(u.hostname))return;if(u.hostname==='salla.sa'&&!u.pathname.startsWith('/almoalej.com'))return;if(!/(\/p\d+|\/c\d+|\/search|\/cart|^\/$|^\/almoalej.com\/?$)/.test(u.pathname))return;if(u.hostname==='almoalej.com'){u.hostname=location.hostname;if(location.hostname==='salla.sa')u.pathname='/almoalej.com'+u.pathname}u.searchParams.set('preview',new URLSearchParams(location.search).get('preview'));if(link.href!==u.href)link.href=u.href})}
  function classify(form){const options=nativeOptions(form),type=form.querySelector('salla-add-product-button')?.getAttribute('product-type');return plans[id]?'maintenance':type==='booking'?'booking':containsInstall(options)?'installation':partIds.includes(id)?'part':options.length?'options':type==='service'?'service':'simple'}
  function field(label,control){const n=e('label');n.append(e('span','',label),control);return n}
  function citySelect(label){const select=e('select');select.setAttribute('aria-label',label);[['','اختر المدينة'],...cities.map(c=>[c,c]),['outside','مدينة أخرى — الباقة غير متاحة']].forEach(([value,text])=>{const o=e('option','',text);o.value=value;select.append(o)});return select}
  function syncServiceNotes(form){const field=form.querySelector('.am07-service-city');if(!field)return;let notes=form.querySelector('[name="notes"]');if(!notes){notes=e('input');notes.type='hidden';notes.name='notes';form.append(notes)}const valid=cities.includes(field.value);notes.disabled=false;notes.value=lineNotes(notes.value,valid?field.value:'','مدينة الخدمة');const status=form.querySelector('.am07-service-status');const text=valid?'مدينة زيارات الصيانة: '+field.value+'. سعر الباقة حسب المنتج، دون رسم تركيب إضافي.':field.value==='outside'?'الباقة غير متاحة لهذه المدينة. تتوفر الزيارات في الأحساء والدمام والرياض وتبوك.':'اختر مدينة الخدمة قبل إضافة الباقة.';if(status.textContent!==text)status.textContent=text;field.setCustomValidity(valid?'':'اختر إحدى مدن الخدمة المتاحة.');}
  function serviceForm(form){if(!plans[id]||form.querySelector('.am07-service-fields'))return;const box=e('section','am07-service-fields'),city=citySelect('مدينة زيارات الصيانة');city.classList.add('am07-service-city');city.required=true;box.append(e('h3','','أين تريد زيارات الصيانة؟'),field('مدينة زيارات الصيانة',city));const status=e('p','am07-service-status');status.setAttribute('role','status');box.append(status);const nativeButton=form.querySelector('salla-add-product-button');(nativeButton.closest('.sticky-product-bar')||nativeButton).before(box);city.addEventListener('change',()=>syncServiceNotes(form));syncServiceNotes(form)}


  function product(){const form=document.querySelector('form.product-form');if(!form)return;const kind=classify(form);form.dataset.am07Kind=kind;document.body.dataset.am07Kind=kind;
   const typeText={maintenance:'باقة فلاتر وزيارات — راجع المدة والمحتويات ومدن الخدمة.',installation:'حدد الخيارات ومدينة التركيب. الإضافة للتركيب متاحة فقط عندما تكون ضمن خيارات هذا المنتج.',part:'قطعة بديلة — طابق المقاس والتوصيلات قبل الطلب.',options:'اختر من الخيارات الأصلية المتاحة؛ تختلف الصورة والسعر حسب الاختيار.',booking:'اختر الموعد من نظام الحجز المتاح لهذا المنتج.',service:'راجع تفاصيل الخدمة وخياراتها قبل الطلب.',simple:'راجع تفاصيل المنتج والكمية قبل إضافته للسلة.'}[kind];let typeNote=form.querySelector('.am07-type-note');if(!typeNote){typeNote=e('p','am07-type-note');form.prepend(typeNote)}if(typeNote.textContent!==typeText)typeNote.textContent=typeText;
   form.querySelectorAll('h2.total-price').forEach(price=>price.parentElement.classList.add('am07-price-box'));
   if(!form.querySelector('.am07-selection-summary')){const summary=e('div','am07-selection-summary');summary.setAttribute('aria-live','polite');const b=form.querySelector('salla-add-product-button');if(b)(b.closest('.sticky-product-bar')||b).before(summary);form.addEventListener('change',()=>{selection(form);syncServiceNotes(form)});}
   selection(form);serviceForm(form);gallery();related();
  }
  function selection(form){const summary=form.querySelector('.am07-selection-summary');if(!summary)return;const selections=[];form.querySelectorAll('salla-product-options select').forEach(s=>{if(s.value)selections.push(s.selectedOptions[0].textContent.trim())});form.querySelectorAll('salla-product-options input[type="radio"]:checked,salla-product-options input[type="checkbox"]:checked').forEach(input=>{const label=document.querySelector('label[for="'+CSS.escape(input.id)+'"]');const name=label?.querySelector('img')?.alt||label?.parentElement.querySelector('p')?.textContent||label?.textContent;if(name)selections.push(name.trim())});const text=selections.length?'اختياراتك: '+selections.join(' · '):'راجع تفاصيل المنتج والكمية، ثم أضفه إلى السلة.';if(summary.textContent!==text)summary.textContent=text;}
  let lightbox=null,photos=[],imageIndex=0,photoOpener;
  function gallery(){
   const slider=main.querySelector('salla-slider.details-slider'),stage=slider?.querySelector('.s-slider-container');
   if(!stage||slider.querySelector('.am07-gallery-tools'))return;
   try{photos=JSON.parse(slider.getAttribute('data-images')||'[]').filter(p=>p.url)}catch{return}
   if(!photos.length)return;
   if(!document.getElementById('am07-gallery-overlay-style')){
    const overlayStyle=e('style');overlayStyle.id='am07-gallery-overlay-style';
    overlayStyle.textContent=`
body.am-commerce07.product-single .am07-gallery-stage{position:relative}
body.am-commerce07.product-single .am07-gallery-stage .swiper-slide img{cursor:zoom-in}
body.am-commerce07 .am07-gallery-tools.am07-gallery-overlay{position:absolute;inset-block-start:12px;inset-inline-start:12px;inset-block-end:auto;inset-inline-end:auto;z-index:5;display:block;width:44px;height:44px;min-height:0;padding:0;margin:0;pointer-events:none}
body.am-commerce07 .am07-gallery-tools.am07-gallery-overlay button{display:flex;align-items:center;justify-content:center;width:44px;height:44px;min-width:44px;min-height:44px;padding:0;margin:0;border:1px solid #d2e1ef;border-radius:50%;background:#fffffff2;color:var(--am07-blue);box-shadow:0 3px 12px #082b591a;pointer-events:auto;cursor:zoom-in;touch-action:manipulation}
body.am-commerce07 .am07-gallery-tools.am07-gallery-overlay button:hover{background:#f0f7ff;border-color:var(--am07-blue)}
body.am-commerce07 .am07-gallery-tools.am07-gallery-overlay button:focus-visible{outline:3px solid #70a9f7;outline-offset:3px}
body.am-commerce07 .am07-gallery-tools.am07-gallery-overlay svg{display:block;width:22px;height:22px;flex:none;pointer-events:none}
`;
    document.head.append(overlayStyle);
   }
   const tools=e('div','am07-gallery-tools am07-gallery-overlay');
   const zoom=button('',event=>{
    event.stopPropagation();
    const active=slider.querySelector('.s-slider-container .swiper-slide-active img');
    const source=active?.currentSrc||active?.src;
    imageIndex=Math.max(0,photos.findIndex(p=>p.url===source));
    photoOpener=zoom;buildLightbox();showImage();lightbox.showModal();
   });
   zoom.setAttribute('aria-label','تكبير الصورة');zoom.setAttribute('title','تكبير الصورة');zoom.setAttribute('aria-haspopup','dialog');
   zoom.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4.5 4.5M10.5 7.5v6M7.5 10.5h6"/></svg>';
   zoom.addEventListener('pointerdown',event=>event.stopPropagation());
   tools.append(zoom);stage.classList.add('am07-gallery-stage');stage.append(tools);
   // A still, single-pointer click opens the existing viewer; swipes keep native behavior.
   let photoPress=null;
   const photoAt=target=>target instanceof Element?target.closest('.swiper-slide-active img'):null;
   const moved=event=>photoPress&&Math.hypot(event.clientX-photoPress.x,event.clientY-photoPress.y)>10;
   stage.addEventListener('pointerdown',event=>{
    if(event.button!==0&&event.pointerType!=='touch')return;
    if(photoPress&&!photoPress.ended&&photoPress.id!==event.pointerId){photoPress.cancelled=true;return}
    photoPress={id:event.pointerId,x:event.clientX,y:event.clientY,image:photoAt(event.target),moved:false,cancelled:event.isPrimary===false,ended:false};
   },true);
   stage.addEventListener('pointermove',event=>{if(photoPress?.id===event.pointerId&&moved(event))photoPress.moved=true},true);
   stage.addEventListener('pointerleave',event=>{if(event.target===stage&&photoPress&&!photoPress.ended)photoPress.cancelled=true},true);
   document.addEventListener('pointerdown',event=>{if(photoPress&&!photoPress.ended&&event.pointerId!==photoPress.id)photoPress.cancelled=true},true);
   document.addEventListener('pointerup',event=>{if(photoPress?.id===event.pointerId){photoPress.moved=photoPress.moved||moved(event);photoPress.ended=true}},true);
   document.addEventListener('pointercancel',event=>{if(photoPress?.id===event.pointerId){photoPress.cancelled=true;photoPress.ended=true}},true);
   stage.addEventListener('click',event=>{
    const image=photoAt(event.target);
    if(!image||!stage.contains(image)||event.target.closest('button,.am07-gallery-tools'))return;
    // The native main slide is a link; route it to the same viewer as the icon.
    event.preventDefault();event.stopPropagation();
    if(!photoPress?.ended||photoPress.image!==image||photoPress.moved||photoPress.cancelled)return;
    photoPress=null;zoom.click();
   },true);

   slider.querySelectorAll('.s-slider-container .swiper-slide img').forEach(img=>{img.style.objectFit='contain'});
  }
  
function buildLightbox(){if(lightbox)return;lightbox=e('dialog','am07-lightbox');lightbox.setAttribute('aria-label','معرض صور المنتج');const header=e('header');header.append(e('strong','','صور المنتج'),button('إغلاق',()=>lightbox.close()));const img=e('img');img.alt='';const footer=e('footer');const caption=e('p','am07-photo-caption');caption.setAttribute('aria-live','polite');footer.append(button('الصورة السابقة',()=>{imageIndex=(imageIndex-1+photos.length)%photos.length;showImage()}),caption,button('الصورة التالية',()=>{imageIndex=(imageIndex+1)%photos.length;showImage()}));lightbox.append(header,img,footer);document.body.append(lightbox);lightbox.addEventListener('close',()=>photoOpener?.focus());lightbox.addEventListener('keydown',event=>{if(!['ArrowLeft','ArrowRight'].includes(event.key))return;event.preventDefault();imageIndex=(imageIndex+(event.key==='ArrowLeft'?1:-1)+photos.length)%photos.length;showImage()});let pointer=null;lightbox.addEventListener('pointerdown',ev=>{if(ev.pointerType==='touch')pointer={x:ev.clientX,y:ev.clientY}});lightbox.addEventListener('pointerup',ev=>{if(!pointer)return;const dx=ev.clientX-pointer.x,dy=ev.clientY-pointer.y;pointer=null;if(Math.abs(dx)>50&&Math.abs(dx)>Math.abs(dy)*1.3){imageIndex=(imageIndex+(dx>0?1:-1)+photos.length)%photos.length;showImage()}})}
  function showImage(){const p=photos[imageIndex],img=lightbox.querySelector('img');img.src=p.url;img.alt=cleanPhotoName(p.alt)||main.querySelector('h1')?.textContent||'صورة المنتج';lightbox.querySelector('.am07-photo-caption').textContent=(imageIndex+1)+' / '+photos.length;}

  function related(){
   const picks=matchingProducts[id];
   if(picks){
    if(main.querySelector('[data-am-matching-products]')) return;
    const section=e('section','container am07-related');
    section.dataset.amMatchingProducts=id;
    const slider=e('salla-products-slider');
    slider.setAttribute('source','selected');
    const displayed=housingIds.has(String(id))||boxDevices.has(String(id))||deviceIds.includes(String(id))||standardFilterIds.includes(Number(id))?picks:picks.slice(0,4);
    slider.setAttribute('limit',String(displayed.length));
    slider.setAttribute('source-value',JSON.stringify(displayed.map(String)));
    slider.setAttribute('block-title','منتجات مرتبطة بهذا المنتج');
    section.append(slider);
    const details=main.querySelector('.container--product-details');
    if(details) details.after(section); else main.append(section);
    return;
   }
   let el=main.querySelector('salla-products-slider[source="related"],.am07-related salla-products-slider');if(!el){let ids=plans[id]?Object.keys(plans):offerIds.includes(id)?offerIds:partIds.includes(id)?partIds:deviceIds.includes(id)?deviceIds:[];ids=ids.filter(pid=>pid!==id).slice(0,4);const box=e('section','container am07-related');el=e('salla-products-slider');el.setAttribute('source',ids.length?'selected':'related');el.setAttribute('source-value',ids.length?JSON.stringify(ids):id);el.setAttribute('block-title','منتجات قد تهمك أيضًا');box.append(el);main.append(box)}if(!el.previousElementSibling?.classList.contains('am07-help')){const note=e('p','am07-help','منتجات قد تهمك أيضًا — راجع المواصفات والتوافق قبل اختيار أي قطعة بديلة.');el.before(note)}if(el.querySelector('.s-product-card-entry'))el.querySelector('.am07-related-empty')?.remove();}
  /* Direct add from cards and native option selection. */
  const am07QuickStyle=e('style');am07QuickStyle.id='am07-quickadd-style';am07QuickStyle.textContent="/* Native Salla options and purchase controls remain visible and unchanged. */\nbody.am-commerce07 dialog.am07-quickadd {\n  box-sizing: border-box;\n  position: fixed;\n  inset: 0;\n  width: min(600px, calc(100vw - 32px));\n  max-width: 600px;\n  height: fit-content;\n  max-height: calc(100vh - 32px);\n  max-height: calc(100dvh - 32px);\n  margin: auto;\n  padding: 0;\n  overflow-x: hidden;\n  overflow-y: auto;\n  overscroll-behavior: contain;\n  border: 1px solid #d9e6f2;\n  border-radius: 18px;\n  background: #fff;\n  color: #082b59;\n  box-shadow: 0 24px 80px #082b5933;\n  font-family: inherit;\n  direction: rtl;\n  text-align: right;\n  scrollbar-gutter: stable;\n}\n\nbody.am-commerce07 dialog.am07-quickadd *,\nbody.am-commerce07 dialog.am07-quickadd *::before,\nbody.am-commerce07 dialog.am07-quickadd *::after {\n  box-sizing: border-box;\n}\n\nbody.am-commerce07 dialog.am07-quickadd::backdrop {\n  background: #082b5973;\n  backdrop-filter: blur(4px);\n}\n\nbody.am-commerce07 dialog.am07-quickadd[open] {\n  animation: am07QuickAddIn 180ms ease-out;\n}\n\nbody.am-commerce07 .am07-quickadd-header {\n  position: sticky;\n  top: 0;\n  z-index: 2;\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 14px;\n  padding: 18px 22px;\n  border-bottom: 1px solid #e2edf6;\n  background: #fff;\n}\n\nbody.am-commerce07 #am07-quickadd-title {\n  min-width: 0;\n  margin: 0;\n  color: #082b59;\n  font-size: 20px;\n  font-weight: 800;\n  line-height: 1.65;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07 .am07-quickadd-close {\n  display: inline-flex;\n  flex: 0 0 44px;\n  align-items: center;\n  justify-content: center;\n  width: 44px;\n  height: 44px;\n  min-width: 44px;\n  min-height: 44px;\n  padding: 0;\n  border: 1px solid #d9e6f2;\n  border-radius: 12px;\n  background: #f4f8fd;\n  color: #082b59;\n  font: inherit;\n  font-size: 25px;\n  line-height: 1;\n  cursor: pointer;\n  transition: color 160ms ease, background-color 160ms ease, border-color 160ms ease;\n}\n\nbody.am-commerce07 .am07-quickadd-close:hover {\n  border-color: #b6cdef;\n  background: #eaf2ff;\n  color: #0756d9;\n}\n\nbody.am-commerce07 .am07-quickadd-form {\n  display: grid;\n  min-width: 0;\n  gap: 18px;\n  margin: 0;\n  padding: 20px 22px 22px;\n}\n\nbody.am-commerce07 .am07-quickadd-price {\n  margin: 0;\n  padding: 14px 16px;\n  border: 1px solid #d9e6f2;\n  border-radius: 12px;\n  background: #f2f8ff;\n  color: #082b59;\n  font-size: 25px;\n  font-weight: 800;\n  line-height: 1.6;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07 .am07-quickadd-note,\nbody.am-commerce07 .am07-quickadd-city p {\n  margin: 0;\n  color: #526b84;\n  font-size: 14px;\n  line-height: 1.9;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07 .am07-quickadd-status {\n  margin: 0;\n  padding: 10px 12px;\n  border-inline-start: 3px solid #0756d9;\n  border-radius: 8px;\n  background: #f2f8ff;\n  color: #082b59;\n  font-size: 14px;\n  line-height: 1.85;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07 .am07-quickadd-status:empty {\n  display: none;\n}\n\nbody.am-commerce07 .am07-quickadd-options {\n  display: grid;\n  min-width: 0;\n  gap: 16px;\n}\n\nbody.am-commerce07 .am07-quickadd-options .s-product-options-option {\n  display: block;\n}\n\nbody.am-commerce07 .am07-quickadd-options .s-product-options-option-label,\nbody.am-commerce07 .am07-quickadd-options .s-product-options-option-content {\n  display: block;\n  width: 100%;\n  max-width: 100%;\n}\n\nbody.am-commerce07 .am07-quickadd-options .s-product-options-option-label {\n  margin-bottom: 14px;\n}\n\nbody.am-commerce07 .am07-quickadd-options salla-product-options {\n  display: block;\n  min-width: 0;\n  max-width: 100%;\n}\n\nbody.am-commerce07 .am07-quickadd-options :is(select, textarea, input:not([type=\"radio\"]):not([type=\"checkbox\"]):not([type=\"hidden\"])) {\n  min-height: 44px;\n  max-width: 100%;\n  font-size: 16px;\n}\n\nbody.am-commerce07 .am07-quickadd-city {\n  display: grid;\n  min-width: 0;\n  gap: 9px;\n  padding: 15px;\n  border: 1px solid #d9e6f2;\n  border-radius: 12px;\n  background: #f7fbff;\n}\n\nbody.am-commerce07 .am07-quickadd-city label {\n  color: #082b59;\n  font-size: 15px;\n  font-weight: 700;\n  line-height: 1.7;\n}\n\nbody.am-commerce07 .am07-quickadd-city select {\n  width: 100%;\n  min-width: 0;\n  max-width: 100%;\n  min-height: 48px;\n  margin: 0;\n  padding: 10px 12px;\n  border: 1px solid #bfd2e6;\n  border-radius: 9px;\n  background: #fff;\n  color: #082b59;\n  font: inherit;\n  font-size: 16px;\n  line-height: 1.6;\n}\n\nbody.am-commerce07 .am07-quickadd-actions {\n  display: grid;\n  min-width: 0;\n  gap: 12px;\n  padding-top: 4px;\n  position: sticky;\n  bottom: -22px;\n  z-index: 2;\n  padding-block: 14px;\n  background: #fff;\n  border-top: 1px solid #e2edf6;\n}\n\nbody.am-commerce07 .am07-quickadd-submit {\n  width: 100%;\n  min-height: 48px;\n  padding: 12px 16px;\n  border: 1px solid #0756d9;\n  border-radius: 10px;\n  background: #0756d9;\n  color: #fff;\n  font: inherit;\n  font-size: 16px;\n  font-weight: 700;\n  line-height: 1.6;\n  cursor: pointer;\n}\n\nbody.am-commerce07 .am07-quickadd-submit:disabled {\n  opacity: .65;\n  cursor: wait;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  body.am-commerce07 .am07-quickadd-submit:not(:disabled):hover {\n    box-shadow: 0 5px 14px #0756d92b;\n  }\n}\n\nbody.am-commerce07 .am07-quickadd-actions salla-add-product-button {\n  display: block;\n  min-width: 0;\n  max-width: 100%;\n}\n\nbody.am-commerce07 .am07-quickadd-actions salla-add-product-button .s-button-element {\n  min-height: 48px;\n  white-space: normal;\n  line-height: 1.6;\n}\n\nbody.am-commerce07 .am07-quickadd-actions salla-add-product-button .s-button-text {\n  white-space: normal;\n  overflow: visible;\n  text-overflow: clip;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07 .am07-quickadd-details {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  min-height: 44px;\n  padding: 10px 16px;\n  border: 1px solid #c4d7f2;\n  border-radius: 10px;\n  background: #fff;\n  color: #0756d9;\n  font-size: 14px;\n  font-weight: 700;\n  line-height: 1.75;\n  text-align: center;\n  text-decoration: none;\n  cursor: pointer;\n  transition: color 160ms ease, background-color 160ms ease, border-color 160ms ease;\n}\n\nbody.am-commerce07 .am07-quickadd-details:hover {\n  border-color: #0756d9;\n  background: #f2f7ff;\n}\n\nbody.am-commerce07 .am07-card-link.am07-quickadd-trigger {\n  cursor: pointer;\n}\n\nbody.am-commerce07 dialog.am07-quickadd :is(button, input, select, textarea, a):focus-visible,\nbody.am-commerce07 .am07-card-link.am07-quickadd-trigger:focus-visible {\n  outline: 3px solid #0756d9;\n  outline-offset: 3px;\n}\n\n@media (max-width: 480px) {\n  body.am-commerce07 .am07-quickadd-header {\n    gap: 10px;\n    padding: 14px 16px;\n  }\n\n  body.am-commerce07 #am07-quickadd-title {\n    font-size: 18px;\n  }\n\n  body.am-commerce07 .am07-quickadd-form {\n    gap: 15px;\n    padding: 16px;\n  }\n\n  body.am-commerce07 .am07-quickadd-price {\n    padding: 12px 14px;\n    font-size: 23px;\n  }\n\n  body.am-commerce07 .am07-quickadd-city {\n    padding: 12px;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  body.am-commerce07 dialog.am07-quickadd[open] {\n    animation: none;\n  }\n\n  body.am-commerce07 .am07-quickadd-close,\n  body.am-commerce07 .am07-quickadd-details {\n    transition: none;\n  }\n}\n\n@keyframes am07QuickAddIn {\n  from { opacity: 0; transform: translateY(6px); }\n  to { opacity: 1; transform: translateY(0); }\n}\n";document.head.append(am07QuickStyle);
/* Insert in the existing Phase 07 closure; replace its cardRules().
 * Single owner: HTML submit button -> Salla.form.submit, never native Add + SDK.
 * Docs: https://docs.salla.dev/twilight/react/sdk/forms
 * https://docs.salla.dev/twilight/react/web-components/salla-product-options
 */
let am07QuickAddActive = null;
function openQuickAdd(card,pid,type,status) {
  pid=String(pid||'');
  const source=Array.from(card.querySelectorAll('salla-add-product-button')).find(node=>String(node.getAttribute('product-id'))===pid);
  if(!/^\d+$/.test(pid)||!source)return;
  const target=card.querySelector('a[href*="/p"]'),trigger=card.querySelector('.am07-quickadd-trigger')||document.activeElement;
  if(['booking','group_products','donating','financial_support'].includes(type)||typeof HTMLDialogElement==='undefined') {if(target)location.assign(target.href);return;}
  // Native options match product-id across the page: do not create a duplicate.
  const existing=Array.from(document.querySelectorAll('salla-product-options')).find(node=>String(node.getAttribute('product-id'))===pid&&!node.closest('.am07-quickadd'));
  if(existing){if(existing.getClientRects().length){existing.scrollIntoView({block:'center',behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'instant':'smooth'});existing.querySelector('select,input,button,textarea')?.focus({preventScroll:true});}else if(target)location.assign(target.href);return;}
  if(am07QuickAddActive)am07QuickAddActive.close();
  const dialog=e('dialog','am07-quickadd'),header=e('header','am07-quickadd-header');dialog.id='am07-quickadd';
  const heading=e('h2','',card.querySelector('.s-product-card-content-title a,.s-product-card-content-title')?.textContent.trim()||'إضافة المنتج إلى السلة');
  heading.id='am07-quickadd-title';dialog.setAttribute('aria-labelledby',heading.id);dialog.setAttribute('dir','rtl');
  const close=button('×',()=>dialog.close());close.className='am07-quickadd-close';close.setAttribute('aria-label','إغلاق خيارات المنتج');header.append(heading,close);
  const form=e('form','am07-quickadd-form');form.method='post';form.enctype='multipart/form-data';form.dataset.productType=type;form.dataset.productStatus=status;
  const hidden=(name,value)=>{const input=e('input');input.type='hidden';input.name=name;input.value=value;form.append(input);return input;};
  hidden('id',pid);hidden('quantity','1');const notes=hidden('notes','');
  const price=card.querySelector('.s-product-card-sale-price h4,.s-product-card-price');
  if(price?.textContent.trim()){const priceBox=e('div','am07-quickadd-price');priceBox.append(price.cloneNode(true));form.append(priceBox);}
  form.append(e('p','am07-quickadd-note','السعر المعروض من بطاقة المنتج. راجع خياراته؛ يُحسب المبلغ النهائي من سلة حسب الخيارات المختارة.'));
  const message=e('p','am07-quickadd-status','جارٍ تحميل خيارات المنتج…');message.setAttribute('role','status');message.setAttribute('aria-live','polite');
  const options=e('salla-product-options','am07-quickadd-options');options.setAttribute('product-id',pid);options.setAttribute('unique-key','am07-quick-'+pid+'-'+Date.now());
  const actions=e('div','am07-quickadd-actions'),submit=e('button','am07-quickadd-submit','أضف إلى السلة');submit.type='submit';submit.disabled=true;actions.append(submit);
  if(target)actions.append(a('تفاصيل المنتج كاملة',target.href,'am07-quickadd-details'));
  form.append(message,options,actions);dialog.append(header,form);
  const state={closed:false,ready:false,pending:false,apiLoaded:false,expectsOptions:false,city:null,cityStatus:null};
  try{state.expectsOptions=String(card.product?.id)===pid&&card.product.has_options===true;}catch{}
  const setMessage=text=>{if(message.textContent!==text)message.textContent=text;};
  const writeCityNote=(label,city)=>{const prefix=label+':',base=notes.value.split('\n').filter(line=>!line.startsWith(prefix));notes.value=[...base,city?prefix+' '+city:''].filter(Boolean).join('\n');};
  const pairs=()=>Array.from(options.querySelectorAll('select')).filter(select=>Array.from(select.options).some(option=>/^مع\s*(?:ال)?تركيب/.test(option.textContent.trim()))&&Array.from(select.options).some(option=>/بدون\s*(?:ال)?تركيب/.test(option.textContent)));
  function addCity(isPlan){
    if(state.city)return;
    const box=e('section','am07-quickadd-city'),label=e('label'),city=e('select'),note=e('p');
    city.id='am07-quick-city-'+pid;label.htmlFor=city.id;label.textContent=isPlan?'مدينة زيارات الصيانة':'مدينة التركيب';
    [['','اختر المدينة'],...cities.map(city=>[city,city]),[isPlan?'outside':'shipping',isPlan?'مدينة أخرى — الباقة غير متاحة':'مدينة أخرى — شحن فقط']].forEach(([value,text])=>{const item=e('option','',text);item.value=value;city.append(item);});
    city.required=isPlan;note.id=city.id+'-note';city.setAttribute('aria-describedby',note.id);box.append(label,city,note);options.before(box);
    state.city=city;state.cityStatus=note;city.addEventListener('change',syncCity);
  }
  function syncCity(){
    const isPlan=!!plans[pid],selects=pairs();if(!isPlan&&!selects.length)return;addCity(isPlan);
    const city=state.city,valid=cities.includes(city.value);
    if(isPlan){
      writeCityNote('مدينة الخدمة',valid?city.value:'');city.setCustomValidity(valid?'':'اختر إحدى مدن الخدمة المتاحة.');
      const text=valid?'مدينة زيارات الصيانة: '+city.value+'.':city.value==='outside'?'الزيارات متاحة في الأحساء والدمام والرياض وتبوك فقط.':'اختر مدينة الخدمة قبل إضافة الباقة.';
      if(state.cityStatus.textContent!==text)state.cityStatus.textContent=text;return;
    }
    let withInstallation=false;
    selects.forEach(select=>{
      Array.from(select.options).filter(option=>/^مع\s*(?:ال)?تركيب/.test(option.textContent.trim())).forEach(option=>{option.disabled=!valid;});
      if(!valid&&/^مع\s*(?:ال)?تركيب/.test(select.selectedOptions[0]?.textContent.trim()||'')){
        const without=Array.from(select.options).find(option=>/بدون\s*(?:ال)?تركيب/.test(option.textContent));select.value=without?.value||'';select.dispatchEvent(new Event('change',{bubbles:true}));
      }
      withInstallation=withInstallation||/^مع\s*(?:ال)?تركيب/.test(select.selectedOptions[0]?.textContent.trim()||'');
    });
    writeCityNote('مدينة التركيب',withInstallation&&valid?city.value:'');city.setCustomValidity(withInstallation&&!valid?'اختر إحدى مدن التركيب المتاحة.':'');
    const text=valid?'التركيب متاح في '+city.value+' عند اختيار «مع التركيب» من خيارات هذا المنتج.':city.value==='shipping'?'لهذه المدينة يتوفر الشحن فقط؛ رسوم الشحن حسب المدينة والطريقة عند إتمام الطلب.':'اختر مدينة من مدن التركيب لتفعيل الخيار الأصلي «مع التركيب»، أو اطلب بدون تركيب.';
    if(state.cityStatus.textContent!==text)state.cityStatus.textContent=text;
  }
  function refreshReady(){if(!state.apiLoaded||state.closed)return;state.ready=!state.expectsOptions||!!options.querySelector('input:not([type="hidden"]),select,textarea,salla-file-upload,salla-booking-field');submit.disabled=!state.ready||state.pending||status!=='sale';setMessage(!state.ready?'جارٍ تحميل خيارات المنتج…':status==='sale'?'راجع الخيارات ثم أضف المنتج إلى السلة.':'هذا المنتج غير متاح للإضافة حاليًا. راجع تفاصيل المنتج.');}
  const observer=new MutationObserver(()=>{syncCity();if(!state.pending)refreshReady();});
  function added(response,productId){if(!state.closed&&state.pending&&String(productId)===pid)dialog.close();}
  salla.event?.on('cart::item.added',added);
  function cleanup(){if(state.closed)return;state.closed=true;observer.disconnect();salla.event?.off('cart::item.added',added);window.removeEventListener('pagehide',leave);form.replaceChildren();dialog.remove();if(am07QuickAddActive===dialog)am07QuickAddActive=null;if(trigger?.isConnected)trigger.focus({preventScroll:true});}
  function leave(){if(dialog.open)dialog.close();else cleanup();}
  dialog.addEventListener('close',cleanup,{once:true});window.addEventListener('pagehide',leave,{once:true});
  form.addEventListener('change',syncCity);
  form.addEventListener('submit',event=>{
    event.preventDefault();
    if(state.closed||state.pending||!state.ready||status!=='sale')return;
    syncCity();if(!form.reportValidity())return;
    if(!window.salla?.form?.submit){setMessage('تعذّر تهيئة الإضافة. افتح تفاصيل المنتج أو أعد المحاولة.');return;}
    state.pending=true;submit.disabled=true;form.setAttribute('aria-busy','true');setMessage('جارٍ إضافة المنتج إلى السلة…');
    // Exactly one request path. Call synchronously while this event is active.
    let result;try{result=salla.form.submit('cart.addItem',event);}catch(error){result=Promise.reject(error);}
    Promise.resolve(result).then(()=>{if(!state.closed)dialog.close();}).catch(()=>{if(state.closed)return;state.pending=false;submit.disabled=false;form.removeAttribute('aria-busy');setMessage('تعذّرت الإضافة. راجع الخيارات ورسالة سلة ثم أعد المحاولة.');});
  });
  document.body.append(dialog);am07QuickAddActive=dialog;
  try{dialog.showModal();}catch(error){cleanup();if(target)location.assign(target.href);return;}
  close.focus({preventScroll:true});observer.observe(options,{childList:true,subtree:true});syncCity();
  Promise.resolve(customElements.whenDefined('salla-product-options')).then(async()=>{
    if(state.closed)return;if(typeof options.componentOnReady==='function')await options.componentOnReady();if(state.closed)return;
    if(typeof options.getOptionsData!=='function'||typeof options.validateAndScroll!=='function')throw new Error('Options API unavailable');
    const loadedOptions=await options.getOptionsData();if(state.closed)return;if(loadedOptions?.length)state.expectsOptions=true;syncCity();state.apiLoaded=true;refreshReady();
  }).catch(()=>{if(!state.closed)setMessage('تعذّر تحميل الخيارات. افتح تفاصيل المنتج للمحاولة من صفحته.');});
}

function cardRules(){
  document.querySelectorAll('.s-product-card-entry').forEach(card=>{
    const add=card.querySelector('salla-add-product-button'),pid=String(add?.getAttribute('product-id')||'');if(!add||!/^\d+$/.test(pid))return;
    const type=add.getAttribute('product-type')||'product',status=add.getAttribute('product-status')||'sale';
    let meta=null;try{if(String(card.product?.id)===pid)meta=card.product;}catch{}
    const plan=!!plans[pid],knownConfig=deviceIds.includes(pid)||offerIds.includes(pid),special=['booking','group_products','donating','financial_support'].includes(type)||!!meta?.has_custom_form,direct=!plan&&meta?.has_options===false&&type==='product'&&!meta.has_custom_form&&!meta.can_upload_file;
    // Unavailable products retain native availability/notify controls.
    if(direct||status!=='sale'){
      add.hidden=false;add.classList.remove('am07-configurable-add');card.querySelectorAll('.am07-card-link').forEach(link=>link.remove());
    }else if(special){
      add.hidden=true;add.classList.add('am07-configurable-add');card.querySelectorAll('.am07-quickadd-trigger').forEach(node=>node.remove());
      const target=card.querySelector('a[href*="/p"]');if(target&&!card.querySelector('.am07-card-link'))add.after(a(type==='booking'?'اختر موعد الحجز':'خيارات المنتج',target.href,'am07-card-link'));
    }else{
      add.hidden=true;add.classList.add('am07-configurable-add');let trigger=card.querySelector('.am07-quickadd-trigger');
      card.querySelectorAll('.am07-card-link:not(.am07-quickadd-trigger)').forEach(link=>link.remove());
      if(!trigger){
        trigger=button(['1808009306','543722590','77942364'].includes(pid)?(pid==='1808009306'?'اختر الشكل واللون':'اختر اللون'):'اختر خيارات المنتج',()=>{const current=card.querySelector('salla-add-product-button'),currentId=String(current?.getAttribute('product-id')||'');if(current&&/^\d+$/.test(currentId))openQuickAdd(card,currentId,current.getAttribute('product-type')||'product',current.getAttribute('product-status')||'sale');});
        trigger.className='am07-card-link am07-quickadd-trigger';trigger.setAttribute('aria-haspopup','dialog');add.after(trigger);
      }
      const name=card.querySelector('.s-product-card-content-title')?.textContent.trim(),action=['1808009306','543722590','77942364'].includes(pid)?(pid==='1808009306'?'اختر الشكل واللون':'اختر اللون'):'اختر خيارات المنتج',label=name?action+': '+name:action;if(trigger.getAttribute('aria-label')!==label)trigger.setAttribute('aria-label',label);
    }
    const content=card.querySelector('.s-product-card-content-main');if(content&&!content.querySelector('.am07-type-badge')){const text=plan?'باقة صيانة':(knownConfig||card.closest('[component-id="344871967"]'))?'جهاز أو تجميعة':partIds.includes(pid)?'فلتر بديل':null;if(text)content.prepend(e('span','am07-type-badge',text));}
  });
}

  function listing(){if(!document.body.classList.contains('product-index')&&!document.body.classList.contains('product-index-search'))return;const list=main.querySelector('salla-products-list');if(!list)return;
   if(!main.querySelector('.am07-list-hero')){const search=document.body.classList.contains('product-index-search'),q=new URLSearchParams(location.search).get('q')||'',crumbs=Array.from(main.querySelectorAll('.s-breadcrumb-item')).map(e=>e.textContent.trim()),name=crumbs[crumbs.length-1]||'تسوق منتجات المعالج';const hero=e('section','am07-list-hero');hero.append(e('span','am-detail-eyebrow','متجر المعالج'),e('h1','',search?'نتائج البحث':name),e('p','',search?'نتائج البحث عن «'+q+'». استخدم الفرز والتصفية لتضييق الخيارات.':'تصفح المنتجات، ثم راجع تفاصيل المنتج وخياراته قبل الشراء.'));const tools=e('div','am07-list-tools'),form=e('form','search'),input=e('input');input.type='search';input.value=q;input.required=true;input.minLength=2;input.placeholder='ابحث عن جهاز، فلتر أو قطعة غيار';input.setAttribute('aria-label','البحث في منتجات المعالج');const submit=e('button','','بحث');submit.type='submit';form.append(input,submit);form.addEventListener('submit',event=>{event.preventDefault();const value=input.value.trim();if(value.length<2){input.setCustomValidity('اكتب حرفين على الأقل.');input.reportValidity();return;}input.setCustomValidity('');const u=new URL(draftUrl('/search'));u.searchParams.set('q',value);location.href=u.href});input.addEventListener('input',()=>input.setCustomValidity(''));tools.append(form);hero.append(tools);const tags=e('nav','am07-tags');tags.setAttribute('aria-label','اقتراحات بحث');['كلاسيك بيور','فلتر قطني','باقة صيانة','قطع غيار'].forEach(text=>{const u=new URL(draftUrl('/search'));u.searchParams.set('q',text);tags.append(a(text,u.href))});hero.append(tags);const container=main.querySelector('.container--products-list');container.before(hero);}
   const filter=main.querySelector('salla-filters');if(filter&&!filter.querySelector('.am07-filter-reset')){const reset=button('مسح التصفية',()=>{if(typeof filter.resetFilters==='function')filter.resetFilters()});reset.className='am07-filter-reset';filter.prepend(reset)}
   const close=main.querySelector('button.close-filters');if(close)close.setAttribute('aria-label','إغلاق التصفية');
   const opener=main.querySelector('.filters-trigger');if(opener)opener.setAttribute('aria-label','فتح التصفية');
  }
  function search(){document.querySelectorAll('salla-search input[type="search"]').forEach(input=>{input.placeholder='ابحث عن جهاز، فلتر أو قطعة غيار';input.setAttribute('aria-label','البحث في المتجر')})}
  function policies(){const view=main.querySelector('.am-info-view');if(!view||view.hidden||view.querySelector('h1')?.textContent!=='الشحن والتركيب'||view.querySelector('.am07-service-coverage'))return;const content=view.querySelector('.am-info-layout>div');if(content){const card=e('section','am-info-card am07-service-coverage');card.append(e('h2','','نطاق باقات الصيانة'),e('p','','تتوفر زيارات باقات الصيانة في الأحساء والدمام والرياض وتبوك. الباقات غير متاحة لبقية مدن المملكة.'));content.append(card)}}
  let cartBusy=false,cartPending=false,cartRetries=0,cartRevision=0;
  const serviceLines=new Map();
  function serviceItemId(card){return card?.getAttribute('data-testid')?.replace('store-cart-item-','')||''}
  function serviceCard(itemId){return main.querySelector('[data-testid="store-cart-item-'+itemId+'"]')}
  function serviceStatus(card,state){const city=card?.querySelector('.am07-service-city'),status=card?.querySelector('.am07-service-status');if(!city||!status)return;
   const valid=cities.includes(city.value),verified=valid&&!state.pending&&!state.failed&&state.confirmedCity===city.value;
   card.dataset.am07ServiceSaved=verified?'true':'false';card.dataset.am07ServiceCity=verified?state.confirmedCity:'';card.dataset.am07ServiceState=state.failed?'failed':state.pending?'pending':verified?'saved':'required';
   const text=!valid?(city.value==='outside'?'الباقة متاحة في الأحساء والدمام والرياض وتبوك فقط.':'اختر مدينة الخدمة قبل إتمام الطلب.'):state.failed?'تعذّر تأكيد حفظ مدينة الخدمة. أعد المحاولة قبل إتمام الطلب.':state.pending?'جارٍ حفظ مدينة الخدمة والتحقق منها في سلة…':verified?'تم حفظ مدينة زيارات الصيانة: '+state.confirmedCity:'لم يتم تأكيد حفظ مدينة الخدمة بعد.';
   if(status.textContent!==text)status.textContent=text;city.setCustomValidity(valid?'':'اختر مدينة الخدمة المتاحة.');const retry=card.querySelector('.am07-service-retry');if(retry)retry.hidden=!state.failed;
  }
  document.addEventListener('change',event=>{if(!document.body.classList.contains('cart'))return;const form=event.target.closest?.('form');if(!form)return;cartRevision++;const card=form.querySelector('.cart-item'),city=card?.querySelector('.am07-service-city'),itemId=serviceItemId(card),state=serviceLines.get(itemId);if(!city||!state)return;
   state.rawCity=city.value;state.desiredCity=cities.includes(city.value)?city.value:'';state.dirty=true;state.pending=true;state.failed=false;state.confirmedCity='';let notes=form.querySelector('[name="notes"]');if(notes){notes.disabled=false;notes.value=lineNotes(notes.value,state.desiredCity,'مدينة الخدمة')}serviceStatus(card,state);
  },true);
  function cart(){if(!document.body.classList.contains('cart'))return;if(!main.querySelector('.am07-cart-intro')){const h=main.querySelector('h1');if(h){const note=e('p','am07-help am07-cart-intro','راجع الكمية ومواصفات المنتجات والخدمة. اختيار التركيب يشمل جميع القطع المؤهلة ضمن فئة الأجرة نفسها. تأكد من المدينة والإجمالي؛ مدينة الخدمة لا تغني عن عنوان التوصيل.');h.after(note)}}if(cartBusy){cartPending=true;return}if(!window.salla?.cart?.details)return;cartBusy=true;const revision=cartRevision;
   salla.cart.details().then(response=>{if(revision!==cartRevision){cartPending=true;return}const data=response?.data?.data||response?.data||response,activeIds=new Set();for(const item of data?.items||data?.cart?.items||[]){if(!plans[String(item.product_id)])continue;const itemId=String(item.id);activeIds.add(itemId);const card=serviceCard(itemId),form=card?.closest('form');if(!form){if(cartRetries++<12)setTimeout(cart,500);continue}
    const saved=String(item.notes||'').split('\n').find(l=>l.startsWith('مدينة الخدمة: '))?.slice('مدينة الخدمة: '.length),savedCity=cities.includes(saved)?saved:'';let state=serviceLines.get(itemId);if(!state){state={desiredCity:savedCity,rawCity:savedCity,confirmedCity:savedCity,dirty:false,pending:false,failed:false};serviceLines.set(itemId,state)}
    let notes=form.querySelector('[name="notes"]');if(!notes){notes=e('input');notes.type='hidden';notes.name='notes';form.append(notes)}notes.disabled=false;
    let box=card.querySelector('.am07-service-fields');if(!box){box=e('div','am07-service-fields');const city=citySelect('مدينة زيارات الصيانة');city.classList.add('am07-service-city');city.required=true;const status=e('p','am07-service-status');status.setAttribute('aria-live','polite');const retry=button('إعادة محاولة حفظ المدينة',()=>city.dispatchEvent(new Event('change',{bubbles:true})));retry.className='am07-service-retry';retry.hidden=true;box.append(field('مدينة زيارات الصيانة',city),status,retry);card.querySelector('h1')?.after(box)}
    const select=box.querySelector('select');
    if(state.dirty){if(savedCity===state.desiredCity){state.confirmedCity=savedCity;state.pending=false;state.failed=false;state.dirty=false;notes.value=item.notes||''}else{notes.value=lineNotes(notes.value,state.desiredCity,'مدينة الخدمة')}}else{state.desiredCity=savedCity;state.rawCity=savedCity||state.rawCity;state.confirmedCity=savedCity;notes.value=item.notes||''}
    const desired=state.dirty?state.rawCity:(savedCity||state.rawCity);if(select.value!==desired)select.value=desired;serviceStatus(card,state);
   }for(const itemId of serviceLines.keys())if(!activeIds.has(itemId))serviceLines.delete(itemId);
   }).catch(()=>{for(const [itemId,state] of serviceLines){if(!state.pending)continue;state.pending=false;state.failed=true;serviceStatus(serviceCard(itemId),state)}}).finally(()=>{cartBusy=false;if(cartPending){cartPending=false;setTimeout(cart,150)}});
  }
  function serviceUpdateFailed(response,itemId){const candidate=String(itemId||response?.data?.item_id||''),explicit=serviceLines.has(candidate)?candidate:'';for(const [lineId,state] of serviceLines){if((explicit&&explicit!==lineId)||!state.dirty)continue;state.pending=false;state.failed=true;serviceStatus(serviceCard(lineId),state)}cartQueued=false;setTimeout(cartOnce,250)}
  let cartQueued=false;function cartOnce(){if(cartQueued)return;cartQueued=true;cart();}
  document.addEventListener('click',event=>{const form=event.target.closest?.('form.product-form');if(form&&plans[id]&&event.target.closest?.('salla-add-product-button,salla-mini-checkout-widget,salla-quick-buy')){syncServiceNotes(form);const city=form.querySelector('.am07-service-city');if(!city||!cities.includes(city.value)){event.preventDefault();event.stopImmediatePropagation();city?.reportValidity();city?.focus();return;}}const target=event.target.closest?.('button');if(document.body.classList.contains('cart')&&target?.textContent.trim()==='إتمام الطلب'){for(const card of main.querySelectorAll('.cart-item')){const pid=card.querySelector('a[href*="/p"]')?.href.match(/\/p(\d+)/)?.[1];if(!plans[pid])continue;const city=card.querySelector('.am07-service-city'),state=serviceLines.get(serviceItemId(card)),verified=city&&cities.includes(city.value)&&state&&!state.pending&&!state.failed&&state.confirmedCity===city.value;if(!verified){event.preventDefault();event.stopImmediatePropagation();if(city){if(state)serviceStatus(card,state);city.reportValidity();city.focus();if(!state?.failed)cart()}else{if(!card.querySelector('.am07-service-load-error'))card.append(e('p','am07-help am07-service-load-error','انتظر تحميل مدينة الخدمة أو حدّث السلة قبل إتمام الطلب.'));cart()}return;}} }},true);
  document.addEventListener('submit',event=>{const form=event.target;if(form.matches('form.product-form')&&plans[id]){syncServiceNotes(form);const city=form.querySelector('.am07-service-city');if(!city||!cities.includes(city.value)){event.preventDefault();event.stopImmediatePropagation();city?.reportValidity();}}},true);
  function mount(){preservePreview();search();product();cardRules();listing();policies();cartOnce()}
  new MutationObserver(schedule).observe(main,{childList:true,subtree:true});mount();let n=0;const retry=setInterval(()=>{mount();if(++n>=20)clearInterval(retry)},500);
  if(window.salla?.onReady)salla.onReady(()=>{if(document.body.classList.contains('cart')){cart();const refresh=()=>{cartQueued=false;setTimeout(cartOnce,250)};salla.event.on('cart::updated',refresh);salla.event.on('cart::item.updated',refresh);salla.event.on('cart::item.updated.failed',serviceUpdateFailed)}});
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
/* Cart summary: name native installation option totals clearly. */
(function(){
 function start(){
  if(!document.body.classList.contains('cart'))return;
  let queued=false;
  function sync(){document.querySelectorAll('salla-cart-summary-card .s-cart-summary-card-line > span').forEach(label=>{if(label.textContent.trim()==='مجموع خيارات الطلب')label.textContent='رسوم التركيب'});}
  function schedule(){if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;sync()});}
  new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true,characterData:true});
  sync();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Match native cart installation choices to the confirmed delivery city. */
(function(){
 function start(){
  if(!document.body.classList.contains('cart'))return;
  const main=document.getElementById('main-content');if(!main)return;
  const originalDisabled=new WeakMap();let queued=false,busy=false,failed=false,ready=false,unknownReady=false;
  let cityHint=null,lastView='',lastContext='',generation=0;
  const normalize=value=>String(value||'').normalize('NFKC').replace(/[\u064B-\u065F\u0670\u0640]/g,'').replace(/[أإآٱ]/g,'ا').toLowerCase().replace(/[\s-]+/g,'').trim();
  const groups=[['الأحساء',['الأحساء','الاحساء','الهفوف','المبرز','Al Ahsa','Al Hofuf','Hofuf','Al Mubarraz','Mubarraz']],['الدمام',['الدمام','Dammam','Ad Dammam']],['الرياض',['الرياض','Riyadh','Ar Riyadh']],['تبوك',['تبوك','Tabuk','Tabouk']]];
  function cityGroup(city){return groups.find(([,names])=>names.some(name=>normalize(name)===normalize(city)))?.[0]||'';}
  function context(){
   const view=document.querySelector('.s-bullet-delivery-cart-view'),title=view?.querySelector('.s-bullet-delivery-cart-view-title')?.textContent.trim()||'',subtitle=view?.querySelector('.s-bullet-delivery-cart-view-subtitle')?.textContent.trim()||'';
   const signature=title+'|'+subtitle;
   if(signature!==lastView){lastView=signature;if(subtitle)cityHint=null;}
   if(cityHint)return cityHint;
   if(title==='توصيل'&&subtitle){const parts=subtitle.split(/[،,]/).map(s=>s.trim());if(parts.length>=2){const country=parts[0].replace(/^(?:إلى|الى|to)\s+/i,'');return{known:true,city:parts[1],group:/^(?:السعودية|المملكة العربية السعودية|Saudi Arabia)$/i.test(country)?cityGroup(parts[1]):''};}}
   return{known:false,city:'',group:''};
  }
  function installationCity(option){const match=option.textContent.trim().match(/^مع\s+التركيب\s*[—–-]\s*(.*?)\s*[—–-]/);return match?cityGroup(match[1]):null;}
  function fields(){return Array.from(main.querySelectorAll('select[name^="options["]')).filter(select=>Array.from(select.options).some(o=>installationCity(o)!==null)&&Array.from(select.options).some(o=>/^بدون\s+تركيب(?:\s|[—–-]|$)/.test(o.textContent.trim())));}
  function without(select){return Array.from(select.options).find(o=>/^بدون\s+تركيب(?:\s|[—–-]|$)/.test(o.textContent.trim()));}
  function invalid(select,place){const option=select.selectedOptions[0],group=option&&installationCity(option);return group!==null&&group!==undefined&&(!place.known||!place.group||group!==place.group);}
  function status(place,list){
   let box=document.getElementById('am-installation-delivery-status');
   if(!list.length){box?.remove();return;}
   if(!box){box=document.createElement('div');box.id='am-installation-delivery-status';box.setAttribute('role','status');box.setAttribute('aria-live','polite');box.tabIndex=-1;box.style.cssText='margin:16px 0;padding:14px 16px;border:1px solid #cbdff2;border-radius:12px;background:#f1f8ff;color:#244563;line-height:1.9;font-size:15px';const address=main.querySelector('.s-bullet-delivery-cart-view');if(address)address.after(box);else(main.querySelector('.am07-cart-intro')||main.querySelector('h1')).after(box);}
   const pending=busy||list.some(select=>invalid(select,place));
   let text=failed?'تعذّر تأكيد تحديث رسوم التركيب. اضغط «إعادة المحاولة» قبل إتمام الطلب.':pending?'جارٍ مطابقة خدمة التركيب مع مدينة التوصيل وتحديث الإجمالي…':!place.known?'اختر مدينة التوصيل أولًا لتحديد توفر التركيب. يتوفر التركيب في الأحساء والدمام والرياض وتبوك فقط.':place.group?'التركيب متاح لمدينة التوصيل «'+place.city+'». يمكنك اختيار التركيب لهذه المدينة أو الشحن بدون تركيب.':'التوصيل إلى «'+place.city+'» متاح بالشحن بدون تركيب فقط. تُضاف رسوم الشحن عند إتمام الطلب حسب المدينة وطريقة الشحن.';
   let message=box.querySelector('p');if(!message){message=document.createElement('p');message.style.margin='0';box.append(message);}if(message.textContent!==text)message.textContent=text;
   let retry=box.querySelector('button');if(!retry){retry=document.createElement('button');retry.type='button';retry.textContent='إعادة المحاولة';retry.style.cssText='margin-top:8px;padding:8px 14px;border:1px solid #bfd2e6;border-radius:8px;background:white;color:#0756d9';retry.addEventListener('click',()=>{failed=false;schedule();});box.append(retry);}retry.hidden=!failed;
   box.dataset.state=failed?'failed':pending?'pending':'ready';
  }
  function lockOptions(select,place){for(const option of select.options){if(!originalDisabled.has(option))originalDisabled.set(option,option.disabled);const group=installationCity(option);if(group!==null){const disabled=originalDisabled.get(option)||!place.known||!place.group||group!==place.group;if(option.disabled!==disabled)option.disabled=disabled;}}}
  function schedule(){if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;sync();});}
  async function sync(){
   const place=context(),list=fields(),key=JSON.stringify(place);if(key!==lastContext){lastContext=key;generation++;failed=false;}
   list.forEach(select=>lockOptions(select,place));status(place,list);
   if(busy||failed||!ready||(!place.known&&!unknownReady))return;
   const select=list.find(field=>invalid(field,place));if(!select)return;
   const option=without(select),form=select.closest('form');if(!option||!form){failed=true;status(place,list);return;}
   busy=true;const revision=generation;status(place,list);
   const wasDisabled=select.disabled;select.disabled=true;
   try{
    const data=new FormData(form),choices=fields().filter(field=>field.closest('form')===form).map(field=>({name:field.name,value:invalid(field,place)?without(field).value:field.value}));
    choices.forEach(choice=>data.set(choice.name,choice.value));
    await salla.cart.updateItem(data);
    if(revision===generation){choices.forEach(choice=>{const current=fields().find(field=>field.name===choice.name);if(current)current.value=choice.value;});failed=false;}
   }catch(error){if(revision===generation)failed=true;}
   finally{select.disabled=wasDisabled;busy=false;schedule();}
  }
  function blocked(){const list=fields(),place=context();return list.length&&(busy||failed||list.some(select=>invalid(select,place)));}
  document.addEventListener('change',event=>{const select=event.target;if(!fields().includes(select))return;const place=context();if(invalid(select,place)){event.preventDefault();event.stopImmediatePropagation();}else failed=false;schedule();},true);
  document.addEventListener('click',event=>{const target=event.target.closest?.('button');if(!target||(!target.closest('salla-button#s-cart-summary-card-submit')&&target.textContent.trim()!=='إتمام الطلب')||!blocked())return;event.preventDefault();event.stopImmediatePropagation();schedule();document.getElementById('am-installation-delivery-status')?.focus();},true);
  document.addEventListener('headerContextUpdate',event=>{const detail=event.detail;if(detail?.type==='address'&&typeof detail.city==='string'&&detail.city.trim()){cityHint={known:true,city:detail.city.trim(),group:String(detail.country_code||'').toUpperCase()==='SA'?cityGroup(detail.city):''};}else cityHint=null;failed=false;generation++;schedule();});
  document.addEventListener('bulletDeliveryConfirmed',()=>{failed=false;generation++;schedule();});
  new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true,characterData:true});
  setTimeout(()=>{unknownReady=true;schedule();},5000);
  let readyBound=false,readyTries=0;function bindReady(){if(readyBound||!window.salla?.onReady)return;readyBound=true;salla.onReady(()=>{ready=true;schedule();});}bindReady();
  const readyTimer=setInterval(()=>{bindReady();if(readyBound||++readyTries>=20)clearInterval(readyTimer);},500);
  schedule();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Keep this store's native catalogue links on the current storefront origin. */
(function(){
 const prefix='/almoalej.com';
 function start(){
  const hosted=location.origin==='https://salla.sa'&&(location.pathname===prefix||location.pathname.startsWith(prefix+'/'));
  if(location.origin!=='https://almoalej.com'&&!hosted)return;
  let queued=false;const observedRoots=new WeakSet();
  const initialHash=location.hash,settleUntil=performance.now()+10000;let settleActive=!(performance.getEntriesByType('navigation')[0]?.type==='reload')&&/^#am-(?:shop|offers|devices|filters|services|about|contact)$/.test(initialHash),settleTimer,lastAnchorTop=null;
  function stopInitialAlignment(){settleActive=false;clearTimeout(settleTimer);}
  function alignInitialAnchor(){
   if(!settleActive)return;if(location.hash!==initialHash||performance.now()>settleUntil){stopInitialAlignment();return;}
   const target=document.getElementById(initialHash.slice(1));if(!target)return;const top=target.getBoundingClientRect().top+window.scrollY;
   if(lastAnchorTop!==null&&Math.abs(top-lastAnchorTop)<2)return;lastAnchorTop=top;clearTimeout(settleTimer);
   settleTimer=setTimeout(()=>{if(!settleActive||location.hash!==initialHash||performance.now()>settleUntil)return;const current=document.getElementById(initialHash.slice(1));if(!current)return;const finalTop=current.getBoundingClientRect().top+window.scrollY;if(Math.abs(finalTop-top)<2)window.scrollTo({top:Math.max(0,finalTop-110),behavior:'instant'});else schedule();},350);
  }
  function ownPath(url){
   if(url.protocol!=='https:')return null;
   if(url.origin==='https://almoalej.com'||url.origin==='https://www.almoalej.com'||url.origin==='https://store.almoalej.com')return url.pathname;
   const legacyPrefix='/almaaalg-lohdat-thly-almyah';
   if(url.origin==='https://salla.sa'&&(url.pathname===legacyPrefix||url.pathname.startsWith(legacyPrefix+'/')))return url.pathname.slice(legacyPrefix.length)||'/';
   if(url.origin==='https://salla.sa'&&(url.pathname===prefix||url.pathname.startsWith(prefix+'/')))return url.pathname.slice(prefix.length)||'/';
   return null;
  }
  function supported(path){return path==='/'||/^\/(?:cart|search)\/?$/.test(path)||/^\/(?:[^/?#]+\/)*[pc]\d+\/?$/.test(path);}
  function normalizeLink(link){
   if(link.hash==='#am-about' && (link.getAttribute('aria-label')==='عن المعالج'||link.textContent.trim()==='عن المعالج')){link.href=new URL('/من-نحن/page-1985983162', 'https://almoalej.com').href;return;}
   const raw=link.getAttribute('href');if(!raw||raw.startsWith('#')||link.hasAttribute('download')||(link.target&&link.target!=='_self'))return;
   let url;try{url=new URL(raw,location.href);}catch{return;}
   const path=ownPath(url);if(path===null||!supported(path))return;
   const cleanPath=path==='/cart/'?'/cart':path;
   const destination=new URL(hosted?prefix+(cleanPath==='/'?'/':cleanPath):cleanPath,location.origin);destination.search=url.search;destination.hash=url.hash;
   const preview=new URLSearchParams(location.search);if(preview.has('preview'))destination.searchParams.set('preview',preview.get('preview'));
   if(link.href!==destination.href)link.setAttribute('href',destination.href);
  }
  function activeMenu(){
   for (const contact of document.querySelectorAll('.main-menu>li>a[aria-label="تواصل معنا"]')) {
    const item=contact.parentElement;
    if(item.previousElementSibling?.hasAttribute('data-am-rewards')) continue;
    const reward=item.cloneNode(true); reward.removeAttribute('id'); reward.setAttribute('data-am-rewards','');
    const link=reward.querySelector('a'); link.href='https://almoalej.com/loyalty'; link.setAttribute('aria-label','مكافآت المعالج'); link.querySelector('span').textContent='مكافآت المعالج'; item.before(reward);
   }
   const hash=location.hash.slice(1);let current='المتجر';
   if(/\/loyalty(?:_points)?\/?$/.test(location.pathname))current='مكافآت المعالج';else if(location.pathname.endsWith('/page-1985983162'))current='عن المعالج';else if(hash==='am-services')current='الخدمات';else if(/^(?:am-about|am-warranty|am-shipping)$/.test(hash))current='عن المعالج';else if(hash==='am-contact')current='تواصل معنا';else if(document.body.classList.contains('index')&&!/^am-(?:shop|offers|devices|filters)/.test(hash))current='الرئيسية';
   document.querySelectorAll('.main-menu>li>a[aria-label]').forEach(link=>{const label=link.getAttribute('aria-label');if(!['الرئيسية','المتجر','الخدمات','عن المعالج','مكافآت المعالج','تواصل معنا'].includes(label))return;const selected=label===current;if(link.getAttribute('data-am-current')!==String(selected))link.setAttribute('data-am-current',String(selected));if(selected){if(link.getAttribute('aria-current')!=='page')link.setAttribute('aria-current','page');}else if(link.getAttribute('aria-current')==='page')link.removeAttribute('aria-current');});
  }
  const observer=new MutationObserver(schedule);
  function roots(){const result=[document];document.querySelectorAll('section[component-id="280736763"],section[component-id="398096929"]').forEach(section=>{section.querySelectorAll('*').forEach(node=>{if(!node.shadowRoot)return;result.push(node.shadowRoot);if(!observedRoots.has(node.shadowRoot)){observedRoots.add(node.shadowRoot);observer.observe(node.shadowRoot,{childList:true,subtree:true,attributes:true,attributeFilter:['href']});}});});return result;}
  function sync(){roots().forEach(root=>root.querySelectorAll('a[href]').forEach(normalizeLink));activeMenu();alignInitialAnchor();}
  function schedule(){if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;sync();});}
  observer.observe(document.body,{childList:true,subtree:true,attributes:true,attributeFilter:['href']});
  ['pointerdown','touchstart','wheel','keydown'].forEach(type=>window.addEventListener(type,stopInitialAlignment,{once:true,passive:true}));window.addEventListener('pagehide',stopInitialAlignment,{once:true});window.addEventListener('load',schedule,{once:true});
  window.addEventListener('hashchange',schedule);window.addEventListener('popstate',schedule);window.addEventListener('pageshow',schedule);document.addEventListener('click',event=>{if(!event.defaultPrevented&&event.button===0&&!event.metaKey&&!event.ctrlKey&&!event.shiftKey&&!event.altKey){const link=event.composedPath().find(node=>node instanceof HTMLAnchorElement);if(link)normalizeLink(link);}schedule();},true);
  sync();let retries=0;const timer=setInterval(()=>{schedule();if(++retries>=16)clearInterval(timer);},500);
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Interactive motion for the twelve homepage category links only. */
(function(){
 function start(){
  if(!document.body.classList.contains('index'))return;
  const main=document.getElementById('main-content');if(!main||main.dataset.amCatInteractionReady)return;main.dataset.amCatInteractionReady='true';
  const reduced=matchMedia('(prefers-reduced-motion: reduce)'),fine=matchMedia('(hover:hover) and (pointer:fine)');
  const bound=new WeakSet(),touched=new Set();let active=null,bounds=null,point=null,frame=0,mountQueued=false;
  const canHover=()=>!reduced.matches&&fine.matches;
  function reset(card){
   if(!card||!touched.has(card))return;
   if(active===card){active=null;bounds=null;point=null;if(frame)cancelAnimationFrame(frame);frame=0;}
   card.classList.remove('am-cat-hover','am-cat-pressed');['--am-cat-rx','--am-cat-ry','--am-cat-px','--am-cat-py'].forEach(name=>card.style.removeProperty(name));touched.delete(card);
  }
  function resetAll(){Array.from(touched).forEach(reset);}
  function paint(){
   frame=0;if(!active||!bounds||!point||!canHover())return;
   const x=Math.max(0,Math.min(1,(point.x-bounds.left)/bounds.width)),y=Math.max(0,Math.min(1,(point.y-bounds.top)/bounds.height));
   active.style.setProperty('--am-cat-rx',((.5-y)*7).toFixed(2)+'deg');active.style.setProperty('--am-cat-ry',((x-.5)*8).toFixed(2)+'deg');
   active.style.setProperty('--am-cat-px',(x*100).toFixed(2)+'%');active.style.setProperty('--am-cat-py',(y*100).toFixed(2)+'%');
  }
  function move(card,event){if(active!==card||!canHover())return;point={x:event.clientX,y:event.clientY};if(!frame)frame=requestAnimationFrame(paint);}
  function mount(){
   main.querySelectorAll('section[component-id="935235511"] .slide--cat-entry').forEach(card=>{
    if(bound.has(card))return;bound.add(card);card.classList.add('am-cat-interactive');
    const light=document.createElement('span');light.className='am-cat-light';light.setAttribute('aria-hidden','true');card.append(light);
    card.addEventListener('pointerenter',event=>{if(!canHover()||event.pointerType==='touch')return;if(active&&active!==card)reset(active);bounds=card.getBoundingClientRect();if(!bounds.width||!bounds.height)return;active=card;touched.add(card);card.classList.add('am-cat-hover');move(card,event);},{passive:true});
    card.addEventListener('pointermove',event=>move(card,event),{passive:true});
    card.addEventListener('pointerleave',()=>reset(card),{passive:true});
    card.addEventListener('pointercancel',()=>reset(card),{passive:true});
    card.addEventListener('pointerdown',()=>{if(reduced.matches)return;touched.add(card);card.classList.add('am-cat-pressed');},{passive:true});
    card.addEventListener('keydown',event=>{if(event.key==='Enter'&&!reduced.matches){touched.add(card);card.classList.add('am-cat-pressed');}});
    card.addEventListener('keyup',event=>{if(event.key==='Enter')card.classList.remove('am-cat-pressed');});
    card.addEventListener('blur',()=>reset(card));
   });
  }
  function scheduleMount(){if(mountQueued)return;mountQueued=true;requestAnimationFrame(()=>{mountQueued=false;mount();});}
  window.addEventListener('pointerup',()=>{touched.forEach(card=>card.classList.remove('am-cat-pressed'));},{passive:true});
  window.addEventListener('resize',resetAll,{passive:true});window.addEventListener('scroll',resetAll,{passive:true});window.addEventListener('blur',resetAll);window.addEventListener('pagehide',resetAll);
  reduced.addEventListener('change',resetAll);fine.addEventListener('change',resetAll);
  new MutationObserver(scheduleMount).observe(main,{childList:true,subtree:true});mount();
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();


/* Keep one decorative background aligned with the existing native hero pair. */
(() => {
  'use strict';
  if (!document.body.classList.contains('index')) return;
  let main, copy, product, resizeObserver, discoveryPoll, discoveryTimer, frame = 0;
  function measure() {
    frame = 0;
    if (!main?.isConnected || !copy?.isConnected || !product?.isConnected) return;
    if (!copy.offsetHeight || !product.offsetHeight) return;
    const top = Math.min(copy.offsetTop, product.offsetTop);
    const bottom = Math.max(copy.offsetTop + copy.offsetHeight, product.offsetTop + product.offsetHeight);
    main.style.setProperty('--am-hero-background-top', top + 'px');
    main.style.setProperty('--am-hero-background-height', (bottom - top) + 'px');
  }
  function schedule() {
    if (!frame) frame = requestAnimationFrame(measure);
  }
  function makeCopyTransparent() {
    const host = Array.from(copy.querySelectorAll('*')).find(node => node.shadowRoot?.querySelector('.s-block-simple-section__title'));
    const root = host?.shadowRoot;
    if (!root) return false;
    if (!root.querySelector('style[data-am-hero-background]')) {
      const style = document.createElement('style');
      style.dataset.amHeroBackground = 'true';
      style.textContent = ':host{background:transparent!important;background-image:none!important}';
      root.append(style);
    }
    return true;
  }
  function discover() {
    main = document.querySelector('#main-content');
    copy = main?.querySelector(':scope > section[component-id="398096929"]');
    product = main?.querySelector(':scope > section[component-id="678832534"]');
    if (!main || !copy || !product || !makeCopyTransparent()) return;
    main.classList.add('am-hero-background');
    if (!resizeObserver && typeof ResizeObserver === 'function') {
      resizeObserver = new ResizeObserver(schedule);
      [main, copy, product].forEach(node => resizeObserver.observe(node));
    }
    measure();
    clearInterval(discoveryPoll);
    clearTimeout(discoveryTimer);
  }
  function start() {
    discover();
    if (!main?.classList.contains('am-hero-background')) {
      discoveryPoll = setInterval(discover, 250);
      discoveryTimer = setTimeout(() => clearInterval(discoveryPoll), 15000);
    }
    document.fonts?.ready.then(schedule);
  }
  window.addEventListener('resize', schedule, { passive: true });
  window.addEventListener('pageshow', () => { discover(); schedule(); });
  window.addEventListener('pagehide', () => {
    if (frame) cancelAnimationFrame(frame);
    frame = 0;
    clearInterval(discoveryPoll);
    clearTimeout(discoveryTimer);
    resizeObserver?.disconnect();
    resizeObserver = null;
  });
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });
  else start();
})();
/* Cart option dropdown presentation — 2026-11-19 */
(()=>{const style=document.createElement("style");style.id="am-cart-dropdown-style";style.textContent="/* Cart-only image dropdowns. Native inputs, images, labels and events remain\n   intact; JS adds am-cart-image-group only after a successful enhancement. */\nbody.am-commerce07.cart salla-product-options .am-cart-image-group {\n  display: block !important;\n  width: 100% !important;\n  min-width: 0;\n  max-width: none !important;\n  color: #082b59;\n  direction: rtl;\n  text-align: start;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group > label {\n  display: block !important;\n  width: 100% !important;\n  max-width: 100% !important;\n  margin: 0 0 8px;\n  color: #082b59;\n  font-size: 14px;\n  font-weight: 700;\n  line-height: 1.8;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07.cart .am-cart-image-heading {\n  display: flex !important;\n  align-items: center;\n  gap: 10px;\n  width: 100%;\n  min-width: 0;\n  direction: rtl;\n}\n\nbody.am-commerce07.cart .am-cart-image-toggle {\n  box-sizing: border-box;\n  display: flex;\n  flex: 1 1 0%;\n  align-items: center;\n  justify-content: space-between;\n  gap: 10px;\n  min-width: 0;\n  min-height: 48px;\n  margin: 0;\n  padding: 10px 14px;\n  border: 1px solid #c7d9e8;\n  border-radius: 10px;\n  background: #fff;\n  color: #082b59;\n  box-shadow: none;\n  font: inherit;\n  font-size: 15px;\n  font-weight: 600;\n  line-height: 1.7;\n  text-align: start;\n  cursor: pointer;\n  transition: border-color 160ms ease, box-shadow 160ms ease;\n}\n\nbody.am-commerce07.cart .am-cart-image-value {\n  flex: 1 1 auto;\n  min-width: 0;\n  white-space: normal;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07.cart .am-cart-image-toggle::after {\n  content: '';\n  flex: 0 0 8px;\n  width: 8px;\n  height: 8px;\n  margin-inline-start: 6px;\n  border-right: 2px solid #0756d9;\n  border-bottom: 2px solid #0756d9;\n  transform: translateY(-2px) rotate(45deg);\n  transition: transform 160ms ease;\n}\n\nbody.am-commerce07.cart .am-cart-image-toggle[aria-expanded='true'] {\n  border-color: #0756d9;\n}\n\nbody.am-commerce07.cart .am-cart-image-toggle[aria-expanded='true']::after {\n  transform: translateY(2px) rotate(225deg);\n}\n\nbody.am-commerce07.cart .am-cart-image-toggle:focus-visible {\n  outline: 3px solid #86b5ff;\n  outline-offset: 2px;\n  border-color: #0756d9;\n}\n\nbody.am-commerce07.cart .am-cart-image-toggle:disabled {\n  opacity: .65;\n  cursor: not-allowed;\n}\n\nbody.am-commerce07.cart img.am-cart-image-preview {\n  box-sizing: border-box;\n  display: block;\n  flex: 0 0 64px;\n  width: 64px;\n  height: 64px;\n  max-width: 64px;\n  margin: 0;\n  padding: 4px;\n  object-fit: contain;\n  border: 1px solid #d7e4f0;\n  border-radius: 10px;\n  background: #fff;\n}\n\nbody.am-commerce07.cart img.am-cart-image-preview[hidden] {\n  display: none !important;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group:not(.am-cart-image-open) > .s-product-options-option-content {\n  display: none !important;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group.am-cart-image-open > .s-product-options-option-content {\n  box-sizing: border-box;\n  display: block !important;\n  width: 100% !important;\n  min-width: 0 !important;\n  max-width: none !important;\n  margin: 10px 0 0 !important;\n  padding: 12px !important;\n  border: 1px solid #d7e4f0;\n  border-radius: 12px;\n  background: #fff;\n  max-height: min(420px, 60dvh);\n  overflow-y: auto;\n  overscroll-behavior: contain;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group .s-product-options-thumbnails-wrapper {\n  display: grid !important;\n  grid-template-columns: repeat(4, minmax(0, 1fr)) !important;\n  gap: 10px !important;\n  width: 100% !important;\n  min-width: 0 !important;\n  max-width: none !important;\n  margin: 0 !important;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group .s-product-options-thumbnails-wrapper > div {\n  min-width: 0 !important;\n  width: auto !important;\n  max-width: none !important;\n  margin: 0 !important;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group .s-product-options-thumbnails-wrapper label.go-to-slide {\n  box-sizing: border-box;\n  display: block !important;\n  width: 100% !important;\n  height: 96px !important;\n  max-width: none !important;\n  max-height: none !important;\n  border-radius: 9px !important;\n  overflow: hidden;\n  background: #fff;\n  cursor: pointer;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group .s-product-options-thumbnails-wrapper img {\n  box-sizing: border-box;\n  width: 100% !important;\n  height: 96px !important;\n  max-height: 96px !important;\n  object-fit: contain !important;\n  padding: 4px;\n  background: #fff;\n}\n\nbody.am-commerce07.cart salla-product-options .am-cart-image-group .s-product-options-thumbnails-wrapper p {\n  height: auto !important;\n  margin: 7px 0 0;\n  color: #082b59;\n  font-size: 12px;\n  line-height: 1.7;\n  text-align: center;\n  white-space: normal !important;\n  overflow-wrap: anywhere;\n}\n\n/* Retain and match the original installation select. */\nbody.am-commerce07.cart salla-product-options select.s-form-control {\n  box-sizing: border-box;\n  display: block;\n  width: 100%;\n  min-width: 0;\n  max-width: 100%;\n  min-height: 46px;\n  padding: 10px 12px;\n  border: 1px solid #c7d9e8;\n  border-radius: 10px;\n  background-color: #fff;\n  color: #082b59;\n  box-shadow: none;\n  font-family: inherit;\n  font-size: 15px;\n  line-height: 1.6;\n  direction: rtl;\n  text-align: start;\n}\n\nbody.am-commerce07.cart salla-product-options select.s-form-control:focus-visible {\n  outline: 3px solid #86b5ff;\n  outline-offset: 2px;\n  border-color: #0756d9;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  body.am-commerce07.cart .am-cart-image-toggle:hover {\n    border-color: #0756d9;\n    box-shadow: 0 3px 10px #0756d912;\n  }\n}\n\n@media (max-width: 767px) {\n  body.am-commerce07.cart .am-cart-image-toggle {\n    min-height: 48px;\n    padding: 10px 12px;\n    font-size: 16px;\n  }\n\n  body.am-commerce07.cart img.am-cart-image-preview {\n    flex-basis: 56px;\n    width: 56px;\n    height: 56px;\n    max-width: 56px;\n  }\n\n  body.am-commerce07.cart salla-product-options .am-cart-image-group .s-product-options-thumbnails-wrapper {\n    grid-template-columns: repeat(2, minmax(0, 1fr)) !important;\n  }\n\n  body.am-commerce07.cart salla-product-options select.s-form-control {\n    min-height: 48px;\n    font-size: 16px;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  body.am-commerce07.cart .am-cart-image-toggle,\n  body.am-commerce07.cart .am-cart-image-toggle::after {\n    transition: none;\n  }\n}\r\n";document.head.append(style);})();
/* Cart-only image dropdowns. All native Salla choices, fields and events remain intact. */
(()=>{
  function start(){
    if(!document.body.classList.contains('cart'))return;
    const main=document.querySelector('main');if(!main)return;
    const bindings=new WeakMap();let serial=0,scheduled=false;
    const text=node=>(node?.textContent||'').replace(/\s+/g,' ').trim();
    function labelFor(input,content){return Array.from(content.querySelectorAll('label')).find(label=>label.htmlFor===input.id);}
    function choiceName(input,content){const label=labelFor(input,content);return text(label?.parentElement?.querySelector('p'))||label?.querySelector('img')?.alt?.trim()||text(label).replace(/\bcheck\b/g,'').trim();}
    function setOpen(group,open){const state=bindings.get(group);if(!state)return;state.open=open;group.classList.toggle('am-cart-image-open',open);state.toggle.setAttribute('aria-expanded',String(open));}
    function closeChoice(group){const state=bindings.get(group),restoreFocus=state?.content.contains(document.activeElement);setOpen(group,false);if(restoreFocus)state.toggle.focus({preventScroll:true});}
    function restore(group){const state=bindings.get(group);if(state)state.heading.remove();group.querySelectorAll(':scope > .am-cart-image-heading').forEach(node=>node.remove());group.classList.remove('am-cart-image-group','am-cart-image-open');bindings.delete(group);}
    function sync(group){
      const content=group.querySelector('.s-product-options-option-content');if(!content){restore(group);return;}
      const inputs=Array.from(content.querySelectorAll('input[type="radio"],input[type="checkbox"]'));
      if(!inputs.length||content.querySelector('select,textarea,input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"])')){restore(group);return;}
      const single=inputs.every(input=>input.type==='radio');
      if(single&&(!inputs[0].name||inputs.some(input=>input.name!==inputs[0].name))){restore(group);return;}
      if(inputs.some(input=>!choiceName(input,content))){restore(group);return;}
      let state=bindings.get(group);
      if(!state||state.content!==content||!state.heading.isConnected){
        const wasOpen=state?.open||false;restore(group);
        const heading=document.createElement('div');heading.className='am-cart-image-heading';
        const toggle=document.createElement('button');toggle.type='button';toggle.className='am-cart-image-toggle';toggle.setAttribute('aria-expanded',String(wasOpen));
        const value=document.createElement('span');value.className='am-cart-image-value';toggle.append(value);
        if(!content.id)content.id='am-cart-image-options-'+(++serial);toggle.setAttribute('aria-controls',content.id);
        const preview=document.createElement('img');preview.className='am-cart-image-preview';preview.hidden=true;preview.decoding='async';
        heading.append(toggle,preview);content.before(heading);
        state={content,heading,toggle,value,preview,open:wasOpen};bindings.set(group,state);
        toggle.addEventListener('click',()=>{
          const open=!state.open;
          if(open)main.querySelectorAll('.am-cart-image-open').forEach(other=>{if(other!==group)setOpen(other,false);});
          setOpen(group,open);
        });
        group.classList.add('am-cart-image-group');setOpen(group,wasOpen);
      }
      const selected=inputs.filter(input=>input.checked),names=selected.map(input=>choiceName(input,content));
      const selection=names.join('، ')||'اختر من الصور المتاحة';if(state.value.textContent!==selection)state.value.textContent=selection;
      const title=text(group.querySelector('.s-product-options-option-label')).replace(/\s*\*\s*$/,'');
      const accessible=(title||'خيارات المنتج')+': '+selection;if(state.toggle.getAttribute('aria-label')!==accessible)state.toggle.setAttribute('aria-label',accessible);
      const source=selected.map(input=>labelFor(input,content)?.querySelector('img')).find(Boolean),src=source&&(source.currentSrc||source.getAttribute('src')||source.getAttribute('data-src'));
      if(src){if(state.preview.getAttribute('src')!==src)state.preview.src=src;const alt=source.alt||names[0];if(state.preview.alt!==alt)state.preview.alt=alt;state.preview.hidden=false;state.preview.title=selection;}else{state.preview.hidden=true;state.preview.removeAttribute('src');state.preview.alt='';}
      state.toggle.disabled=inputs.every(input=>input.matches(':disabled'));
      if(!selected.length&&inputs.some(input=>input.required&&!input.matches(':disabled')))setOpen(group,true);
    }
    function mount(){scheduled=false;main.querySelectorAll('.cart-item salla-product-options .s-product-options-option').forEach(sync);}
    function schedule(){if(scheduled)return;scheduled=true;requestAnimationFrame(mount);}
    const observer=new MutationObserver(records=>{if(records.every(record=>record.target.closest?.('.am-cart-image-heading')))return;schedule();});
    observer.observe(main,{childList:true,subtree:true,attributes:true,attributeFilter:['disabled','checked','aria-disabled']});
    main.addEventListener('change',event=>{
      const input=event.target,group=input.closest?.('.am-cart-image-group');
      if(group&&input.matches('input[type="radio"],input[type="checkbox"]')){sync(group);if(input.type==='radio')closeChoice(group);}
      schedule();
    });
    main.addEventListener('click',event=>{
      const input=event.target,group=input.closest?.('.am-cart-image-group');
      if(group&&input.matches('input[type="radio"]')&&input.checked&&!input.matches(':disabled'))requestAnimationFrame(()=>{sync(group);closeChoice(group);});
    });
    main.addEventListener('load',event=>{const image=event.target,content=image.closest?.('.s-product-options-option-content'),group=content?.closest('.am-cart-image-group');if(group&&image.tagName==='IMG')sync(group);},true);
    main.addEventListener('invalid',event=>{const group=event.target.closest?.('.am-cart-image-group');if(group)setOpen(group,true);},true);
    document.addEventListener('click',event=>{main.querySelectorAll('.am-cart-image-open').forEach(group=>{if(!group.contains(event.target))setOpen(group,false);});});
    main.addEventListener('keydown',event=>{if(event.key!=='Escape')return;const group=event.target.closest?.('.am-cart-image-open');if(group){setOpen(group,false);bindings.get(group)?.toggle.focus();event.preventDefault();}});
    window.salla?.event?.on('cart::item.updated',schedule);window.salla?.event?.on('cart::updated',schedule);mount();
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
/* Compact installation service presentation — 2026-11-19 */
(()=>{const style=document.createElement("style");style.id="am-install-compact-style";style.textContent="/* Installation presentation only. JS adds these markers after enhancement;\n   the original select, option values and submission handlers stay native. */\nbody.am-commerce07.cart .am-install-compact-host {\n  display: block;\n  width: 100%;\n  min-width: 0;\n  margin: 0 !important;\n  padding: 0 !important;\n  border: 0 !important;\n  border-radius: 0;\n  background: transparent !important;\n  box-shadow: none !important;\n}\n\nbody.am-commerce07.cart form.am-install-compact-form {\n  padding-top: 0 !important;\n}\n\nbody.am-commerce07.cart .cart-options:has(.am-install-compact-host) {\n  border: 0 !important;\n  box-shadow: none !important;\n}\n\nbody.am-commerce07.cart .am-install-compact-container {\n  box-sizing: border-box;\n  display: block !important;\n  min-width: 0 !important;\n  width: 100% !important;\n  max-width: none !important;\n  margin: 0 !important;\n  padding: 14px !important;\n  border: 1px solid #d6e5f3 !important;\n  border-radius: 14px !important;\n  background: #fff !important;\n  box-shadow: 0 4px 16px #082b5908;\n  color: #082b59;\n  direction: rtl;\n  text-align: start;\n}\n\nbody.am-commerce07.cart .am-install-compact {\n  display: block !important;\n  min-width: 0;\n  margin: 0 !important;\n  padding: 0 !important;\n  border: 0;\n  background: transparent;\n}\n\n/* Only the enhanced group's old direct label is replaced by the new header. */\nbody.am-commerce07.cart .am-install-compact > .s-product-options-option-label,\nbody.am-commerce07.cart .am-install-compact > label {\n  display: none !important;\n}\n\nbody.am-commerce07.cart .am-install-compact-header {\n  display: flex !important;\n  align-items: center;\n  justify-content: space-between;\n  gap: 10px;\n  min-width: 0;\n  width: 100%;\n}\n\nbody.am-commerce07.cart label.am-install-compact-label {\n  display: inline-flex !important;\n  flex: 1 1 0%;\n  align-items: center;\n  gap: 7px;\n  min-width: 0;\n  margin: 0 !important;\n  color: #082b59;\n  font-size: 15px;\n  font-weight: 700;\n  line-height: 1.65;\n  text-align: start;\n  cursor: pointer;\n}\n\nbody.am-commerce07.cart .am-install-compact-label > span {\n  min-width: 0;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07.cart svg.am-install-compact-icon {\n  display: block;\n  flex: 0 0 20px;\n  width: 20px;\n  height: 20px;\n  color: #0756d9;\n}\n\nbody.am-commerce07.cart .am-install-compact-fee {\n  box-sizing: border-box;\n  display: inline-block;\n  flex: 0 1 auto;\n  max-width: 48%;\n  margin: 0;\n  padding: 4px 8px;\n  border: 1px solid #dce9fb;\n  border-radius: 8px;\n  background: #f0f6ff;\n  color: #0756d9;\n  font-size: 14px;\n  font-weight: 700;\n  line-height: 1.6;\n  text-align: end;\n  white-space: normal;\n  overflow-wrap: anywhere;\n}\n\nbody.am-commerce07.cart .am-install-compact > .s-product-options-option-content {\n  display: block !important;\n  width: 100% !important;\n  min-width: 0 !important;\n  max-width: none !important;\n  margin: 10px 0 0 !important;\n  padding: 0 !important;\n}\n\nbody.am-commerce07.cart select.am-install-compact-select {\n  box-sizing: border-box;\n  display: block !important;\n  appearance: auto;\n  width: 100% !important;\n  min-width: 0 !important;\n  max-width: 100% !important;\n  min-height: 48px !important;\n  margin: 0 !important;\n  padding: 10px 12px;\n  padding-inline-end: 30px;\n  border: 1px solid #bdd2e7;\n  border-radius: 10px;\n  background-color: #fff;\n  background-image: none !important;\n  color: #082b59;\n  box-shadow: none;\n  font-family: inherit;\n  font-size: 15px;\n  font-weight: 500;\n  line-height: 1.6;\n  direction: rtl;\n  text-align: start;\n  cursor: pointer;\n  transition: border-color 160ms ease, box-shadow 160ms ease;\n}\n\nbody.am-commerce07.cart select.am-install-compact-select:focus-visible {\n  outline: 3px solid #86b5ff;\n  outline-offset: 2px;\n  border-color: #0756d9;\n  box-shadow: 0 0 0 1px #0756d9;\n}\n\nbody.am-commerce07.cart select.am-install-compact-select:disabled {\n  background-color: #f3f7fb;\n  color: #526b84;\n  cursor: not-allowed;\n}\n\nbody.am-commerce07.cart .am-install-compact-note {\n  margin: 8px 0 0;\n  color: #526b84;\n  font-size: 12px;\n  font-weight: 400;\n  line-height: 1.8;\n  white-space: normal;\n  overflow-wrap: anywhere;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  body.am-commerce07.cart select.am-install-compact-select:not(:disabled):hover {\n    border-color: #0756d9;\n  }\n}\n\n@media (max-width: 767px) {\n  body.am-commerce07.cart select.am-install-compact-select {\n    min-height: 52px !important;\n    font-size: 16px;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  body.am-commerce07.cart select.am-install-compact-select {\n    transition: none;\n  }\n}\n";document.head.append(style);})();
/* Presentation only: retain native option values, selection, required and city locks. */
(()=>{
  function start(){
    if(!document.body.classList.contains('cart'))return;
    const main=document.querySelector('main');if(!main)return;
    const bindings=new WeakMap(),texts=new WeakMap();let queued=false,serial=0;
    const money=new Intl.NumberFormat('ar-SA',{maximumFractionDigits:2});
    const digits=value=>String(value).replace(/[٠-٩]/g,c=>String('٠١٢٣٤٥٦٧٨٩'.indexOf(c))).replace(/[۰-۹]/g,c=>String('۰۱۲۳۴۵۶۷۸۹'.indexOf(c))).replace(/٫/g,'.').replace(/٬/g,'');
    const withCity=text=>String(text).trim().match(/^مع\s+التركيب\s*[—–-]\s*(الأحساء|الاحساء|الدمام|الرياض|تبوك)\s*[—–-]\s*(.+)$/);
    const without=text=>/^بدون\s+تركيب(?:\s|[—–-]|$)/.test(String(text).trim());
    function original(option){let state=texts.get(option);const current=option.textContent;if(!state||current!==state.last){state={original:current,last:current};texts.set(option,state);}return state.original;}
    function setText(option,text){const state=texts.get(option);if(option.textContent!==text)option.textContent=text;if(state)state.last=text;}
    function restore(group){
      const state=bindings.get(group);if(state){state.header.remove();state.note.remove();state.select.classList.remove('am-install-compact-select');for(const [name,value] of Object.entries(state.aria)){if(value===null)state.select.removeAttribute(name);else state.select.setAttribute(name,value);}}
      group.querySelectorAll(':scope > .am-install-compact-header,:scope > .am-install-compact-note').forEach(node=>node.remove());
      group.classList.remove('am-install-compact');group.closest('.s-product-options-option-container')?.classList.remove('am-install-compact-container');bindings.delete(group);
    }
    function dataFor(select){try{const id=select.name.match(/^options\[(\d+)\]$/)?.[1];return JSON.parse(select.closest('salla-product-options')?.getAttribute('options')||'[]').find(option=>String(option.id)===id);}catch{return null;}}
    function priceFor(option,data){const detail=data?.details?.find(detail=>String(detail.id)===option.value),amount=detail?.additional_price;if(amount!==null&&amount!==undefined&&amount!==''&&Number.isFinite(Number(amount)))return Number(amount);const match=withCity(original(option))?.[2].match(/([0-9٠-٩۰-۹]+(?:[.٫][0-9٠-٩۰-۹]+)?)\s*(?:ريال|ر\.?\s*س)/);return match?Number(digits(match[1])):null;}
    function makeHeader(group,select){
      const header=document.createElement('div');header.className='am-install-compact-header';
      const label=document.createElement('label');label.className='am-install-compact-label';if(!select.id)select.id='am-install-service-'+(++serial);label.htmlFor=select.id;label.id=select.id+'-compact-label';
      const icon=document.createElementNS('http://www.w3.org/2000/svg','svg');icon.setAttribute('viewBox','0 0 24 24');icon.setAttribute('fill','none');icon.setAttribute('stroke','currentColor');icon.setAttribute('stroke-width','1.7');icon.setAttribute('aria-hidden','true');icon.classList.add('am-install-compact-icon');
      const path=document.createElementNS('http://www.w3.org/2000/svg','path');path.setAttribute('d','m14.7 6.3 3 3m-1.3-6.2a5 5 0 0 0-6.2 6.2L3.6 16a2.4 2.4 0 1 0 3.4 3.4l6.7-6.6a5 5 0 0 0 6.2-6.2l-3.5 3.5-3-3z');path.setAttribute('stroke-linecap','round');path.setAttribute('stroke-linejoin','round');icon.append(path);
      const title=document.createElement('span');title.textContent='خدمة التركيب';label.append(icon,title);
      const fee=document.createElement('span');fee.className='am-install-compact-fee';fee.id=select.id+'-compact-fee';
      header.append(label,fee);
      const note=document.createElement('p');note.className='am-install-compact-note';note.id=select.id+'-compact-note';note.textContent='يشمل القطع المؤهلة. الشحن يُحسب عند إتمام الطلب.';
      group.querySelector('.s-product-options-option-content').before(header);group.append(note);
      const state={select,header,label,fee,note,aria:{'aria-labelledby':select.getAttribute('aria-labelledby'),'aria-describedby':select.getAttribute('aria-describedby')}};
      select.setAttribute('aria-labelledby',label.id+' '+fee.id);select.setAttribute('aria-describedby',[state.aria['aria-describedby'],note.id].filter(Boolean).join(' '));select.classList.add('am-install-compact-select');
      group.classList.add('am-install-compact');group.closest('.s-product-options-option-container')?.classList.add('am-install-compact-container');select.closest('salla-product-options')?.classList.add('am-install-compact-host');select.closest('form')?.classList.add('am-install-compact-form');bindings.set(group,state);return state;
    }
    function sync(group){
      const select=group.querySelector('.s-product-options-option-content select');if(!select){if(bindings.has(group))restore(group);return;}
      const options=Array.from(select.options);options.forEach(original);
      if(!/^options\[\d+\]$/.test(select.name)||options.some(option=>!option.hasAttribute('value'))||!options.some(option=>withCity(original(option)))||!options.some(option=>without(original(option)))){if(bindings.has(group))restore(group);return;}
      let state=bindings.get(group);if(!state||state.select!==select||!state.header.isConnected){restore(group);state=makeHeader(group,select);}
      const data=dataFor(select),prices=[];
      for(const option of options){
        const raw=original(option),match=withCity(raw);
        if(option.value===''){setText(option,'اختر الخدمة');continue;}
        if(without(raw)){setText(option,'بدون تركيب — شحن فقط');continue;}
        if(match){const fee=priceFor(option,data);if(fee!==null){prices.push(fee);setText(option,'مع التركيب — '+match[1]+' — '+money.format(fee)+' ر.س');}}
      }
      const unique=[...new Set(prices)],feeText=unique.length===1?money.format(unique[0])+' ر.س / قطعة':unique.length>1?'الأجرة حسب المدينة':'حسب الخيار';
      if(state.fee.textContent!==feeText)state.fee.textContent=feeText;
    }
    function mount(){queued=false;main.querySelectorAll('salla-product-options .s-product-options-option').forEach(sync);main.querySelectorAll('.am-install-compact-host').forEach(host=>{if(!host.querySelector('.am-install-compact'))host.classList.remove('am-install-compact-host');});main.querySelectorAll('.am-install-compact-form').forEach(form=>{if(!form.querySelector('.am-install-compact'))form.classList.remove('am-install-compact-form');});}
    function schedule(){if(queued)return;queued=true;requestAnimationFrame(mount);}
    const observer=new MutationObserver(records=>{if(records.every(record=>record.target.closest?.('.am-install-compact-header,.am-install-compact-note')))return;schedule();});
    observer.observe(main,{childList:true,subtree:true,attributes:true,attributeFilter:['disabled','options']});
    main.addEventListener('change',schedule);window.salla?.event?.on('cart::updated',schedule);mount();
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
/* DOM-only presentation helper. No Salla/cart API calls or native parent edits.
 *
 * const el = AlmoalejInstallCardUI.create({
 *   fee: 59, city: 'الرياض', supported: true, selected: false,
 *   busy: false, quantity: 2,
 *   onChange(selectedBoolean, el) { handleSelection(selectedBoolean, el); },
 *   onChooseAddress(el) { openAddressChooser(el); }
 * });
 * card.append(el); // caller chooses the insertion point
 * AlmoalejInstallCardUI.update(el, {selected:true, busy:false});
 * AlmoalejInstallCardUI.destroy(el); // removes this helper only
 *
 * supported is true / false / null, supplied by the authoritative controller.
 * No city support is inferred from labels. null or an empty city means unknown.
 * fee and quantity are actual values; missing/invalid values are not guessed.
 * message is optional controller status text. Callbacks receive user intent;
 * update never invokes callbacks. Neither control has a native form field name.
 */
(function () {
  'use strict';
  const entries = new WeakMap();
  const keys = ['fee','city','supported','selected','busy','quantity','onChange','onChooseAddress','message'];
  const money = new Intl.NumberFormat('ar-SA', {maximumFractionDigits:2});
  let sequence = 0;
  const node = (tag, className, styles) => {
    const el = document.createElement(tag);
    el.className = className;
    if (styles) Object.assign(el.style, styles);
    return el;
  };
  const number = value => {
    if (typeof value !== 'number' && !(typeof value === 'string' && value.trim())) return null;
    const result = Number(value);
    return Number.isFinite(result) && result >= 0 ? result : null;
  };
  const set = (el, value) => { if (el.textContent !== value) el.textContent = value; };
  function facts(props) {
    const city = typeof props.city === 'string' ? props.city.trim() : '';
    return {city, fee:number(props.fee), known:!!city && typeof props.supported === 'boolean', allowed:!!city && props.supported === true};
  }
  function render(entry) {
    const {props,el,label,feeText,select,withOption,note,total,status} = entry;
    const {city,fee,known,allowed} = facts(props);
    const busy = props.busy === true, selected = props.selected === true;
    el.setAttribute('aria-busy', String(busy));
    select.disabled = busy || typeof props.onChange !== 'function';
    withOption.disabled = !allowed || fee === null;
    select.value = selected ? 'with' : 'without';
    set(label,'خدمة التركيب');
    set(feeText, fee === null ? 'الأجرة غير مؤكدة' : money.format(fee)+' ريال / قطعة');
    set(note, !known ? 'لتفعيل خيار التركيب، حدّد منطقتك من زر «تعديل العنوان» أعلى السلة.' : !allowed
      ? 'التركيب غير متاح لهذه المنطقة. تُضاف رسوم الشحن حسب المنطقة عند إتمام الطلب.'
      : city+'؛ الشحن يُحسب عند إتمام الطلب.');
    const quantity = number(props.quantity);
    const showTotal = selected && fee !== null && quantity !== null && Number.isInteger(quantity) && quantity >= 1;
    total.hidden = !showTotal;
    if (showTotal) set(total,'إجمالي التركيب: '+money.format(fee*quantity)+' ريال — الكمية '+money.format(quantity));
    set(status, typeof props.message === 'string' && props.message.trim() ? props.message.trim()
      : busy ? 'جارٍ تحديث خيار التركيب…' : fee === null ? 'تعذّر تأكيد الأجرة؛ راجع الخدمة قبل إضافتها.' : '');
    status.hidden = !status.textContent;
  }
  function update(el, patch) {
    const entry = entries.get(el);
    if (!entry) throw new TypeError('Unknown installation card UI');
    if (patch && typeof patch === 'object') keys.forEach(key => {
      if (Object.prototype.hasOwnProperty.call(patch,key)) entry.props[key] = patch[key];
    });
    render(entry);
    return el;
  }
  function create(props) {
    const id = 'am-install-card-'+(++sequence);
    const el = node('section','am-install-card',{
      boxSizing:'border-box', width:'100%', minWidth:'0', margin:'12px 0 0', padding:'14px',
      border:'1px solid #d6e5f3', borderRadius:'14px', background:'#fff', color:'#082b59',
      boxShadow:'0 3px 12px #082b5908', direction:'rtl', textAlign:'start', fontFamily:'inherit'
    });
    el.setAttribute('role','group');
    el.setAttribute('aria-labelledby',id+'-label');
    const header = node('div','am-install-card-header',{display:'flex',alignItems:'center',justifyContent:'space-between',gap:'10px',minWidth:'0'});
    const label = node('label','am-install-card-label',{flex:'1 1 0%',minWidth:'0',margin:'0',fontSize:'15px',fontWeight:'700',lineHeight:'1.7',overflowWrap:'anywhere'});
    label.id=id+'-label'; label.htmlFor=id+'-select';
    const feeText = node('span','am-install-card-fee',{flex:'0 1 auto',maxWidth:'52%',padding:'4px 8px',borderRadius:'8px',background:'#f0f6ff',color:'#0756d9',fontSize:'13px',fontWeight:'700',lineHeight:'1.7',textAlign:'end',overflowWrap:'anywhere'});
    feeText.id=id+'-fee'; header.append(label,feeText);
    const select = node('select','am-install-card-select',{
      boxSizing:'border-box',display:'block',width:'100%',minWidth:'0',maxWidth:'100%',minHeight:'48px',
      margin:'10px 0 0',padding:'10px 12px',border:'1px solid #bdd2e7',borderRadius:'10px',
      background:'#fff',color:'#082b59',fontFamily:'inherit',fontSize:'16px',lineHeight:'1.6',
      direction:'rtl',textAlign:'start',appearance:'auto',outlineOffset:'3px',accentColor:'#0756d9'
    });
    select.id=id+'-select';
    const withoutOption = document.createElement('option');withoutOption.value='without';withoutOption.textContent='بدون تركيب';
    const withOption = document.createElement('option');withOption.value='with';withOption.textContent='مع التركيب';
    select.append(withoutOption,withOption);
    const note = node('p','am-install-card-note',{margin:'8px 0 0',fontSize:'12px',fontWeight:'400',lineHeight:'1.8',color:'#526b84',overflowWrap:'anywhere'});
    note.id=id+'-note';
    const total = node('p','am-install-card-total',{margin:'7px 0 0',fontSize:'13px',fontWeight:'700',lineHeight:'1.8',color:'#082b59',overflowWrap:'anywhere'});
    const status = node('p','am-install-card-status',{margin:'7px 0 0',fontSize:'12px',lineHeight:'1.8',color:'#0756d9',overflowWrap:'anywhere'});
    status.id=id+'-status';status.setAttribute('role','status');status.setAttribute('aria-live','polite');
    select.setAttribute('aria-describedby',feeText.id+' '+note.id+' '+status.id);
    const entry = {el,label,feeText,select,withOption,note,total,status,props:{supported:null,selected:false,busy:false}};
    entry.change = () => {
      const selected = select.value === 'with', {allowed,fee} = facts(entry.props);
      if (entry.props.busy === true || (selected && (!allowed || fee === null))) {render(entry);return;}
      if (typeof entry.props.onChange === 'function') entry.props.onChange(selected,el);
    };
    select.addEventListener('change',entry.change);
    el.append(header,select,note,total,status);entries.set(el,entry);update(el,props);
    return el;
  }
  function destroy(el) {
    const entry=entries.get(el);if(!entry)return;
    entry.select.removeEventListener('change',entry.change);
    entries.delete(el);el.remove();
  }
  window.AlmoalejInstallCardUI = Object.freeze({create,update,destroy});
})();

/* Independent native installation services. Defines a factory; never auto-enables.
 * Integration must first disable the old shared paid order fields natively and
 * confirm their old charges are gone. This browser guard is not server policy.
 * Public SDK only: cart.details/addItem/updateItem/deleteItem; no price writes.
 *
 * create({ enabled:true, legacyFeesConfirmedDisabled:true,
 *   servicesByFee:{ '59':{productId:'...',linkOptionId:'...',expectedUnitPrice:59} },
 *   eligibleProducts:{ 'physicalProductId':'59' }, onState(state){} }).start()
 * UI calls request(parentCartItemId, true|false); IDs must remain strings.
 */
(function (global) {
  'use strict';
  if (global.AlmoalejInstallationCore) return;
  const PREFIX = 'am-install:v1:';
  const id = value => {
    if (typeof value === 'number' && !Number.isSafeInteger(value)) throw new Error('Unsafe numeric identifier');
    const result = String(value == null ? '' : value);
    if (!/^\d+$/.test(result)) throw new Error('Invalid identifier');
    return result;
  };
  const normalize = value => String(value || '').normalize('NFKC').replace(/[\u064B-\u065F\u0670\u0640]/g, '').replace(/[أإآٱ]/g, 'ا').toLowerCase().replace(/[\s-]+/g, '').trim();
  const cities = [
    ['الأحساء', ['الأحساء', 'الاحساء', 'الهفوف', 'المبرز', 'Al Ahsa', 'Al Hofuf', 'Hofuf', 'Al Mubarraz', 'Mubarraz']],
    ['الدمام', ['الدمام', 'Dammam', 'Ad Dammam']],
    ['الرياض', ['الرياض', 'Riyadh', 'Ar Riyadh']],
    ['تبوك', ['تبوك', 'Tabuk', 'Tabouk']]
  ];
  const groupCity = value => cities.find(([, names]) => names.some(name => normalize(name) === normalize(value)))?.[0] || '';
  const numericPrice = value => {
    const amount = typeof value === 'object' && value ? value.amount : value;
    return typeof amount === 'number' && Number.isFinite(amount) ? amount : typeof amount === 'string' && /^\d+(?:\.\d+)?$/.test(amount) ? Number(amount) : null;
  };

  function create(config) {
    if (!config || config.enabled !== true || config.legacyFeesConfirmedDisabled !== true) throw new Error('Explicit enable and native legacy-fee cleanup confirmation required');
    const services = new Map(), servicesByProduct = new Map(), eligible = new Map();
    for (const [fee, entry] of Object.entries(config.servicesByFee || {})) {
      const service = { fee, productId: id(entry.productId), linkOptionId: id(entry.linkOptionId), expectedUnitPrice: entry.expectedUnitPrice };
      if (servicesByProduct.has(service.productId)) throw new Error('Each fee must have its own native service product');
      if (service.expectedUnitPrice != null && (!Number.isFinite(service.expectedUnitPrice) || service.expectedUnitPrice < 0)) throw new Error('Invalid verified service price');
      services.set(fee, service); servicesByProduct.set(service.productId, service);
    }
    for (const [productId, feeValue] of Object.entries(config.eligibleProducts || {})) {
      const fee = String(typeof feeValue === 'object' ? feeValue.fee : feeValue);
      if (!services.has(fee)) throw new Error('Eligible product has no configured native service');
      const product = id(productId);
      if (servicesByProduct.has(product)) throw new Error('A service cannot be an installation parent');
      eligible.set(product, fee);
    }
    if (!services.size || !eligible.size) throw new Error('Verified service and eligible-product mappings required');
    const legacyDefaults = new Map(Object.entries(config.legacyOptionDefaults || {}).map(([optionId, value]) => [id(optionId), id(value)]));
    const intents = new Map(), ambiguousAdds = new Set(), retiredServiceRows = new Map(), listeners = [];
    let started = false, disposed = false, running = false, dirty = false, scheduled = 0;
    let snapshot = null, revision = 0, error = null, phase = 'idle', active = null;
    let cityHint = null, lastView = null, place = { known: false, city: '', group: '' };
    let unknownTimer = 0, unknownExpired = false, nativePending = false, nativeSince = 0, nativeTimer = 0, nativeAck = false;
    let observer = null, ready = false, readyTimer = 0, startedAt = 0, reloadPending = false, legacyView = '';
    let legacyAttemptKey = null;
    let sdkEventsBound = false;
    const sdkEventCounts = Object.create(null);
    const summaryAttempts = new Set();
    let summaryStatus = null, summaryViewSignature = '';
    const sdk = () => config.sdk || global.salla;
    const cardFor = itemId => document.querySelector('[data-testid="store-cart-item-' + itemId + '"],#store-cart-item-' + itemId);
    const nativeQty = itemId => {
      const card = cardFor(itemId), field = card?.querySelector('salla-quantity-input input') || card?.querySelector('input[name="quantity"]');
      const quantity = Number(field?.value);
      return Number.isInteger(quantity) && quantity > 0 ? quantity : null;
    };
    const linkFor = parentId => PREFIX + parentId;
    const parentFrom = value => typeof value === 'string' && /^am-install:v1:(\d+)$/.test(value) ? value.slice(PREFIX.length) : null;
    const noteFor = parentId => {
      const parent = snapshot?.items.find(item => item.id === parentId);
      const name = typeof parent?.raw.product_name === 'string' ? parent.raw.product_name.replace(/\s+/g, ' ').trim() : '';
      return (name ? 'المنتج: ' + name + '\n' : '') + 'مرجع القطعة: ' + parentId + '\nمدينة التركيب: ' + place.group;
    };
    const wants = parentId => intents.get(parentId)?.wanted === true;

    function displayedNumber(element, count = false) {
      if (!element) return null;
      const text = element.textContent.replace(/[\u0660-\u0669\u06F0-\u06F9]/g, char => String(char.charCodeAt(0) - (char.charCodeAt(0) >= 0x06F0 ? 0x06F0 : 0x0660)));
      const matches = text.match(/\d[\d,\u066C]*(?:[.\u066B]\d+)?/g);
      if (!matches || matches.length !== 1) return null;
      const value = Number(matches[0].replace(/[,\u066C]/g, '').replace('\u066B', '.'));
      return Number.isFinite(value) && value >= 0 && (!count || Number.isSafeInteger(value)) ? value : null;
    }
    function summaryView() {
      if (config.refreshNativeSummary !== true) return null;
      const header = document.querySelector('salla-cart-summary[data-testid="store-header-cart"]') || document.querySelector('salla-cart-summary');
      const main = document.querySelector('salla-cart-summary-card[data-testid="store-cart-summary"]') || document.querySelector('salla-cart-summary-card');
      const headTotal = displayedNumber(header?.querySelector('.s-cart-summary-total'));
      const headCount = displayedNumber(header?.querySelector('.s-cart-summary-count'), true);
      const mainTotal = displayedNumber(main?.querySelector('.s-cart-summary-card-bar-total'));
      const mainCount = displayedNumber(main?.querySelector('.s-cart-summary-card-bar-count'), true);
      if ([headTotal, headCount, mainTotal, mainCount].some(value => value === null)) return null;
      return { mismatch: headTotal !== mainTotal || headCount !== mainCount, signature: [headTotal, headCount, mainTotal, mainCount].join('|') };
    }
    function summaryOperation() {
      if (config.refreshNativeSummary !== true || nativePending || error || reloadPending) return null;
      const view = summaryView();
      if (!view?.mismatch) return null;
      const parent = snapshot.items.find(item => eligible.has(item.productId) && nativeQty(item.id) === item.quantity);
      if (!parent) return null;
      const key = String(snapshot.cart.id || parent.id) + '|' + JSON.stringify(place) + '|' + view.signature;
      if (summaryAttempts.has(key)) return null;
      return { type: 'summaryRefresh', parent, key, viewSignature: view.signature, revision };
    }

    function legacyScan() {
      if (!legacyDefaults.size) return { fields: [], pendingHosts: false, signature: '' };
      const fields = Array.from(document.querySelectorAll('select[name^="options["]')).flatMap(select => {
        const match = select.name.match(/^options\[(\d+)\]$/);
        if (!match || !legacyDefaults.has(match[1])) return [];
        const form = select.closest('form'), recordId = String(form?.querySelector('input[name="id"]')?.value || '');
        return [{ select, form, recordId, optionId: match[1], defaultValue: legacyDefaults.get(match[1]) }];
      });
      let pendingHosts = false;
      for (const host of document.querySelectorAll('salla-product-options[options]')) {
        let options;
        try { options = JSON.parse(host.getAttribute('options')); } catch (_) { continue; }
        const declared = new Set();
        const visit = node => {
          if (!node || typeof node !== 'object') return;
          if (!Array.isArray(node) && legacyDefaults.has(String(node.id))) declared.add(String(node.id));
          for (const child of Object.values(node)) if (child && typeof child === 'object') visit(child);
        };
        visit(options);
        for (const optionId of declared) if (!host.querySelector('select[name="options[' + optionId + ']"]')) pendingHosts = true;
      }
      return { fields, pendingHosts, signature: fields.map(field => field.recordId + ':' + field.optionId + ':' + field.select.value).join('|') + '|' + pendingHosts };
    }
    function legacyOperation() {
      if (!legacyDefaults.size || reloadPending) return null;
      const scan = legacyScan(); legacyView = scan.signature;
      const elapsed = Date.now() - startedAt;
      if (elapsed < (config.legacyInitialWaitMs ?? 300)) return { type: 'legacyWait' };
      if (scan.pendingHosts) {
        if (elapsed < (config.legacyHydrationTimeoutMs ?? 5000)) return { type: 'legacyWait' };
        error = { code: 'LEGACY_FIELDS_NOT_READY', message: 'لم تتهيأ خيارات التركيب السابقة لتأكيد إزالة رسومها. أعد تحميل الصفحة قبل إضافة خدمة جديدة.' };
        return null;
      }
      const positive = scan.fields.find(field => field.select.value !== '' && field.select.value !== '0' && field.select.value !== field.defaultValue);
      if (!positive) return null;
      if (!positive.form || !/^\d+$/.test(positive.recordId)) {
        error = { code: 'LEGACY_RECORD_UNRECOGNIZED', message: 'تعذّر تحديد سجل رسوم التركيب السابق. لن تُضاف خدمة جديدة حتى تصحيح السلة.' };
        return null;
      }
      const fields = scan.fields.filter(field => field.form === positive.form);
      const key = 'am-install:legacy-reset:v1:' + positive.recordId + ':' + fields.map(field => field.optionId + '=' + field.defaultValue).sort().join(',');
      legacyAttemptKey = key;
      try {
        const storage = config.sessionStorage || global.sessionStorage;
        if (!storage) throw new Error('Session storage unavailable');
        if (storage.getItem(key)) {
          error = { code: 'LEGACY_RESET_UNCONFIRMED', message: 'بقيت رسوم التركيب السابقة بعد إعادة التحميل. اضغط إعادة التحقق لمحاولة تصفيرها مرة أخرى؛ لن تُضاف رسوم جديدة قبل التأكيد.' };
          return null;
        }
      } catch (_) {
        error = { code: 'LEGACY_STORAGE_UNAVAILABLE', message: 'تعذّر تهيئة التحقق من رسوم التركيب السابقة. أعد تحميل الصفحة؛ لن تُضاف رسوم جديدة الآن.' };
        return null;
      }
      return { type: 'legacyReset', form: positive.form, recordId: positive.recordId, fields, key };
    }

    function readPlace() {
      if (config.getContext) {
        const context = config.getContext();
        return { known: context?.known === true, city: String(context?.city || ''), group: context?.known === true && context?.countryCode === 'SA' ? groupCity(context.city) : '' };
      }
      const view = document.querySelector('.s-bullet-delivery-cart-view');
      const title = view?.querySelector('.s-bullet-delivery-cart-view-title')?.textContent.trim() || '';
      const subtitle = view?.querySelector('.s-bullet-delivery-cart-view-subtitle')?.textContent.trim() || '';
      const signature = title + '|' + subtitle;
      // A cleared address or a new pickup view must clear a previously allowed hint.
      if (lastView !== null && signature !== lastView && cityHint && signature !== cityHint.viewAtEvent) cityHint = null;
      lastView = signature;
      if (cityHint) return cityHint.context;
      if (title === 'توصيل' && subtitle) {
        const parts = subtitle.split(/[،,]/).map(part => part.trim());
        if (parts.length >= 2) {
          const country = parts[0].replace(/^(?:إلى|الى|to)\s+/i, '');
          return { known: true, city: parts[1], group: /^(?:السعودية|المملكة العربية السعودية|Saudi Arabia)$/i.test(country) ? groupCity(parts[1]) : '' };
        }
      }
      if (/^استلام/.test(title)) return { known: true, city: '', group: '' };
      const captured = global.AlmoalejNativeDeliveryContext?.get();
      if (captured?.known === true) return { known: true, city: captured.city, group: captured.countryCode === 'SA' ? groupCity(captured.city) : '' };
      return { known: false, city: '', group: '' };
    }
    function updatePlace() {
      const next = readPlace();
      if (JSON.stringify(next) === JSON.stringify(place)) return;
      place = next; revision++;
      if (!place.group && place.known) for (const intent of intents.values()) intent.wanted = false;
      // Changing city never re-enables an installation previously reset to shipping.
      if (error?.code === 'CITY_UNAVAILABLE') error = null;
    }
    function unwrap(response) {
      const data = response?.data?.data || response?.data || response;
      const cart = data?.cart || data;
      if (!cart || !Array.isArray(cart.items)) throw new Error('Unrecognized native cart response');
      const items = cart.items.map(raw => {
        const itemId = id(raw.id), productId = id(raw.product_id ?? raw.product?.id);
        const quantity = Number(raw.quantity);
        if (!Number.isInteger(quantity) || quantity < 1) throw new Error('Unrecognized native item quantity');
        const service = servicesByProduct.get(productId);
        const options = Array.isArray(raw.options) ? raw.options : [];
        const field = service && options.find(option => String(option.id) === service.linkOptionId);
        // Verified native service text-field response uses option.value. Never infer
        // ownership from product names, notes, option titles, or a guessed ID.
        const parentId = service ? parentFrom(field?.value) : null;
        return { id: itemId, productId, quantity, notes: String(raw.notes || '').replace(/\r\n?/g, '\n'), raw, options, service, parentId };
      });
      return { items, cart, fetchedAt: Date.now() };
    }
    async function read() {
      const result = unwrap(await sdk().cart.details());
      if (disposed) return result;
      snapshot = result;
      if (result.items.some(item => item.service && !item.parentId)) error = { code: 'SERVICE_LINK_UNRECOGNIZED', message: 'يوجد سطر خدمة تركيب بلا مرجع منتج صالح. أزله أو صحح ربطه قبل إتمام الطلب.' };
      for (const item of result.items) {
        if (item.parentId && !intents.has(item.parentId)) intents.set(item.parentId, { wanted: !place.known || !!place.group, revision });
        if (item.parentId) ambiguousAdds.delete(item.parentId);
      }
      return result;
    }
    function viewState() {
      const items = snapshot?.items || [], rows = [];
      for (const parent of items.filter(item => eligible.has(item.productId))) {
        const attached = items.filter(item => item.parentId === parent.id);
        const configured = services.get(eligible.get(parent.productId));
        rows.push({ parentId: parent.id, productId: parent.productId, quantity: parent.quantity, fee: configured.fee,
          wanted: wants(parent.id), serviceItemIds: attached.map(item => item.id),
          confirmed: attached.length === 1 && attached[0].productId === configured.productId && attached[0].quantity === parent.quantity && attached[0].notes === noteFor(parent.id) && !!place.group,
          pending: running || dirty || nativePending || !!active, allowed: !!place.group });
      }
      const hasWanted = [...intents.values()].some(intent => intent.wanted);
      const hasManaged = items.some(item => item.parentId);
      return { phase, revision, city: { ...place }, running, pending: running || dirty || !!scheduled || nativePending || reloadPending,
        ...(config.debug === true ? { debug: { sdkEventsBound, sdkEventCounts: { ...sdkEventCounts }, nativePending, nativeAck } } : {}),
        error: error ? { ...error } : null, rows, nativeCart: snapshot?.cart || null,
        retiredServiceRows: Array.from(retiredServiceRows.values(), row => ({ ...row })),
        ...(config.refreshNativeSummary === true ? { nativeSummaryRefresh: summaryStatus ? { ...summaryStatus } : null } : {}),
        blocked: !!error || running || dirty || !!scheduled || nativePending || reloadPending || ambiguousAdds.size > 0 || ((!place.known || !place.group) && (hasWanted || hasManaged)),
        message: error ? error.message : reloadPending ? 'تم إرسال إزالة رسوم التركيب السابقة. جارٍ إعادة تحميل السلة لتأكيد الإجمالي قبل إضافة الخدمة الجديدة…' : running || dirty || nativePending ? 'جارٍ تأكيد خدمة التركيب ورسومها من السلة…' : !place.known ? 'اختر مدينة التوصيل أولًا. التركيب متاح في الأحساء والدمام والرياض وتبوك فقط.' : !place.group ? 'التركيب غير متاح لهذه المدينة. الطلب للشحن فقط، وتُضاف رسوم الشحن عند إتمام الطلب حسب المدينة وطريقة الشحن.' : 'يمكن اختيار التركيب لكل منتج بشكل مستقل في ' + place.group + '.' };
    }
    function emit() {
      if (disposed) return;
      const state = viewState();
      document.dispatchEvent(new CustomEvent('am:installation-state', { detail: state }));
      if (config.onState) { try { config.onState(state); } catch (callbackError) { global.console?.error(callbackError); } }
    }
    function schedule(delay = 80) {
      if (disposed || !started || reloadPending) return;
      dirty = true;
      if (!scheduled && !running) scheduled = global.setTimeout(() => { scheduled = 0; void pump(); }, delay);
    }
    function dataFor(item, quantity, notes) {
      const card = cardFor(item.id), form = card?.closest('form') || card?.querySelector('form');
      const nativeId = form?.querySelector('input[name="id"]')?.value;
      const usableForm = form && String(nativeId) === item.id;
      const data = usableForm ? new FormData(form) : new FormData();
      if (!usableForm && item.options.some(option => String(option.id) !== item.service.linkOptionId)) throw new Error('Cannot preserve additional native service options without its form');
      data.set('id', item.id); data.set('quantity', String(quantity));
      data.set('options[' + item.service.linkOptionId + ']', linkFor(item.parentId));
      data.set('notes', notes);
      return data;
    }
    function nextOperation() {
      const legacy = legacyOperation();
      if (legacy || error || reloadPending) return legacy;
      const items = snapshot.items, byId = new Map(items.map(item => [item.id, item]));
      const owned = items.filter(item => item.parentId);
      const allowed = !!place.group && place.known;
      for (const serviceItem of owned) {
        const parent = byId.get(serviceItem.parentId), fee = parent && eligible.get(parent.productId);
        const expected = fee && services.get(fee);
        const unknownGrace = !place.known; // Unknown/loading is never consent to remove a saved service.
        const duplicate = owned.find(item => item.parentId === serviceItem.parentId)?.id !== serviceItem.id;
        if (!parent || !expected || expected.productId !== serviceItem.productId || duplicate || !wants(serviceItem.parentId) || (!allowed && !unknownGrace)) {
          return { type: 'delete', item: serviceItem };
        }
        if (!allowed) continue;
        if (serviceItem.service.expectedUnitPrice != null && numericPrice(serviceItem.raw.price) !== serviceItem.service.expectedUnitPrice) throw new Error('The native installation service price differs from the verified fee');
        const quantity = nativeQty(parent.id);
        if (quantity !== null && quantity !== parent.quantity) return { type: 'wait' };
        if (serviceItem.quantity !== parent.quantity || serviceItem.notes !== noteFor(parent.id)) return { type: 'update', item: serviceItem, quantity: parent.quantity, notes: noteFor(parent.id) };
      }
      if (!allowed) return summaryOperation();
      for (const parent of items.filter(item => eligible.has(item.productId) && wants(item.id))) {
        if (owned.some(item => item.parentId === parent.id)) continue;
        if (ambiguousAdds.has(parent.id)) return null;
        const quantity = nativeQty(parent.id);
        if (quantity !== null && quantity !== parent.quantity) return { type: 'wait' };
        return { type: 'add', parent, service: services.get(eligible.get(parent.productId)), notes: noteFor(parent.id) };
      }
      return summaryOperation();
    }
    function confirmed(operation) {
      if (!snapshot) return false;
      const parentId = operation.parent?.id || operation.item.parentId;
      const matches = snapshot.items.filter(item => item.parentId === parentId);
      if (operation.type === 'add') return matches.filter(item => item.productId === operation.service.productId).length === 1 && matches.some(item => item.productId === operation.service.productId && item.quantity === operation.parent.quantity && item.notes === operation.notes);
      if (operation.type === 'delete') return !snapshot.items.some(item => item.id === operation.item.id);
      return matches.some(item => item.id === operation.item.id && item.quantity === operation.quantity && item.notes === operation.notes);
    }
    function retireConfirmedService(operation) {
      if (operation.type !== 'delete' || !operation.item.service || !operation.item.parentId || !confirmed(operation)) return;
      retiredServiceRows.set(operation.item.id, {
        itemId: operation.item.id, productId: operation.item.productId,
        linkOptionId: operation.item.service.linkOptionId, parentId: operation.item.parentId,
        fee: operation.item.service.fee
      });
    }
    async function resetLegacy(operation) {
      active = { type: 'legacyReset', recordId: operation.recordId, revision };
      phase = 'pending'; emit();
      const timer = global.setTimeout(() => {
        if (disposed || !active) return;
        error = { code: 'LEGACY_RESET_PENDING', message: 'لم يصل تأكيد إزالة الرسوم السابقة بعد. انتظر أو أعد تحميل السلة قبل إتمام الطلب.' };
        phase = 'failed'; emit();
      }, config.operationTimeoutMs || 12000);
      try {
        // This is the native legacy pseudo-item's form, not a physical item ID.
        // Keep all unrelated options, hidden fields and quantities exactly as-is.
        const data = new FormData(operation.form);
        data.set('id', operation.recordId);
        for (const field of operation.fields) data.set(field.select.name, field.defaultValue);
        await sdk().cart.updateItem(data);
        if (disposed) return;
        const storage = config.sessionStorage || global.sessionStorage;
        storage.setItem(operation.key, JSON.stringify({ at: Date.now(), recordId: operation.recordId }));
        reloadPending = true; dirty = false; error = null; phase = 'reloading'; emit();
        // Only a fresh native page can confirm these pseudo-items: details()
        // omits them. Retain the complete URL, including preview parameters.
        global.location.reload();
      } catch (_) {
        error = { code: 'LEGACY_RESET_FAILED', message: 'تعذّر تأكيد إزالة رسوم التركيب السابقة. أعد التحقق قبل إضافة أي خدمة جديدة.' };
        phase = 'failed';
      } finally { global.clearTimeout(timer); active = null; }
    }
    async function refreshSummary(operation) {
      const parent = snapshot.items.find(item => item.id === operation.parent.id && eligible.has(item.productId));
      const view = summaryView();
      if (nativePending || revision !== operation.revision || !parent || nativeQty(parent.id) !== parent.quantity || !view?.mismatch || view.signature !== operation.viewSignature) { dirty = true; return; }
      summaryAttempts.add(operation.key);
      summaryStatus = { state: 'pending', signature: operation.key, parentId: parent.id };
      active = { type: 'summaryRefresh', parentId: parent.id, revision };
      const eventCount = sdkEventCounts['cart::updated'] || 0;
      const requestedRevision = revision, requestedQuantity = parent.quantity;
      phase = 'pending'; emit();
      const timer = global.setTimeout(() => {
        if (disposed || active?.type !== 'summaryRefresh') return;
        error = { code: 'SUMMARY_REFRESH_UNCONFIRMED', message: 'لم يصل تأكيد تحديث ملخص السلة بعد. أعد التحقق قبل إتمام الطلب.' };
        phase = 'failed'; emit();
      }, config.operationTimeoutMs || 12000);
      let requestFailed = false;
      try {
        // A documented quantity-only update, using the current server quantity.
        // Omitting options preserves the parent's native configuration. Never
        // write a price, use a pseudo-item ID, or reapply an old quantity later.
        await sdk().cart.updateItem({ id: parent.id, quantity: requestedQuantity });
      } catch (_) { requestFailed = true; }
      finally { global.clearTimeout(timer); active = null; }
      if (disposed) return;
      await new Promise(resolve => global.setTimeout(resolve, 300));
      await read(); updatePlace();
      const current = snapshot.items.find(item => item.id === parent.id), quantity = nativeQty(parent.id);
      if (revision !== requestedRevision || !current || current.quantity !== requestedQuantity || quantity !== null && quantity !== current.quantity) {
        summaryStatus = { state: 'superseded', signature: operation.key, parentId: parent.id };
        if (error?.code === 'SUMMARY_REFRESH_UNCONFIRMED') error = null;
        if (current && quantity !== null && quantity !== current.quantity && !nativePending) nativeChanged();
        dirty = true; return;
      }
      const refreshed = summaryView(), acknowledged = (sdkEventCounts['cart::updated'] || 0) > eventCount;
      if (!requestFailed && acknowledged && refreshed && !refreshed.mismatch) {
        summaryStatus = { state: 'confirmed', signature: operation.key, parentId: parent.id };
        if (error?.code === 'SUMMARY_REFRESH_UNCONFIRMED') error = null;
      } else {
        summaryStatus = { state: 'unconfirmed', signature: operation.key, parentId: parent.id, reason: requestFailed ? 'request-failed' : !acknowledged ? 'missing-event' : !refreshed ? 'missing-widgets' : 'widgets-mismatch' };
        // The server cart was read back and its quantity is unchanged. A stale
        // header alone must not block a valid checkout or trigger another write.
        if (error?.code === 'SUMMARY_REFRESH_UNCONFIRMED') error = null;
      }
    }
    async function perform(operation) {
      const operationRevision = revision;
      active = { type: operation.type, parentId: operation.parent?.id || operation.item.parentId, revision: operationRevision };
      phase = 'pending'; emit();
      const timer = global.setTimeout(() => {
        if (!active || disposed) return;
        error = { code: 'MUTATION_PENDING', message: 'لم يصل تأكيد السلة بعد. انتظر أو أعد تحميل الصفحة قبل إتمام الطلب.' };
        phase = 'failed'; emit();
      }, config.operationTimeoutMs || 12000);
      try {
        if (operation.type === 'add') {
          const options = { [operation.service.linkOptionId]: linkFor(operation.parent.id) };
          await sdk().cart.addItem({ id: operation.service.productId, quantity: operation.parent.quantity, options, notes: operation.notes });
        } else if (operation.type === 'delete') await sdk().cart.deleteItem(operation.item.id);
        else await sdk().cart.updateItem(dataFor(operation.item, operation.quantity, operation.notes));
        // An old request may finish after a new city/choice. Read it back but never
        // replace a newer intent or mark it saved; the next pass reconciles again.
        await read();
        // SDK resolution alone is not confirmation. A stale details response
        // must never cause the same add/update/delete to be written again.
        for (let attempt = 0; !confirmed(operation) && attempt < 3 && !disposed; attempt++) {
          await new Promise(resolve => global.setTimeout(resolve, 250));
          await read();
        }
        if (!confirmed(operation)) {
          if (operation.type === 'add') ambiguousAdds.add(operation.parent.id);
          error = { code: operation.type === 'add' ? 'ADD_UNCONFIRMED' : 'UPDATE_UNCONFIRMED', message: 'لم تؤكد السلة حفظ خدمة التركيب بعد. استخدم إعادة التحقق؛ لن تتكرر إضافة الرسوم تلقائيًا.' };
        } else {
          retireConfirmedService(operation);
          if (error?.code === 'MUTATION_PENDING') error = null;
        }
      } catch (cause) {
        let readback = false;
        try { await read(); readback = true; } catch (_) { /* Keep the previous snapshot explicitly unconfirmed. */ }
        const parentId = operation.parent?.id || operation.item.parentId;
        if (!readback || !confirmed(operation)) {
          if (operation.type === 'add') ambiguousAdds.add(parentId);
          error = { code: operation.type === 'add' ? 'ADD_UNCONFIRMED' : 'UPDATE_UNCONFIRMED', message: 'تعذّر تأكيد تحديث التركيب. استخدم إعادة التحقق؛ لن تُعاد إضافة رسوم غير مؤكدة تلقائيًا.' };
          phase = 'failed';
        } else {
          retireConfirmedService(operation);
          if (error?.code !== 'SERVICE_LINK_UNRECOGNIZED') error = null;
        }
      } finally {
        global.clearTimeout(timer); active = null;
      }
    }
    async function pump() {
      if (disposed || running || !ready) return;
      running = true; dirty = false; let waitDelay = 0; phase = 'pending'; emit();
      try {
        updatePlace();
        await read();
        updatePlace();
        const mismatchedQuantity = snapshot.items.some(item => eligible.has(item.productId) && nativeQty(item.id) !== null && nativeQty(item.id) !== item.quantity);
        if (nativePending) {
          if (!mismatchedQuantity && nativeAck && Date.now() - nativeSince >= 250) { nativePending = false; nativeAck = false; global.clearTimeout(nativeTimer); }
          else { phase = error ? 'failed' : 'pending'; dirty = true; return; }
        }
        if (error) { phase = 'failed'; return; }
        // One native mutation at a time, then a fresh authoritative cart. Bound
        // work per turn; events arriving in-flight only mark the latest state dirty.
        for (let count = 0; count < 30; count++) {
          updatePlace();
          const operation = nextOperation();
          if (!operation) break;
          if (operation.type === 'legacyWait') { dirty = true; waitDelay = 150; break; }
          if (operation.type === 'wait') { if (!nativePending) nativeChanged(); else dirty = true; return; }
          if (operation.type === 'legacyReset') await resetLegacy(operation);
          else if (operation.type === 'summaryRefresh') await refreshSummary(operation);
          else await perform(operation);
          if (error || disposed || reloadPending) break;
        }
        if (reloadPending) { dirty = false; phase = 'reloading'; return; }
        if (!error && nextOperation()) dirty = true;
        phase = error ? 'failed' : dirty ? 'pending' : 'saved';
      } catch (cause) {
        error = { code: 'READBACK_FAILED', message: 'تعذّر قراءة السلة الأصلية لتأكيد خدمة التركيب. أعد التحقق قبل إتمام الطلب.' };
        phase = 'failed';
      } finally {
        running = false; emit();
        // An acknowledgement can arrive while details() is pending. Retain that
        // wake-up and poll read-only at a bounded rate until the native quantity
        // matches or nativeTimer closes the guard with a failure. No write retry.
        if (dirty && !error && !reloadPending) schedule(waitDelay || (nativePending ? 300 : 80));
      }
    }
    function nativeChanged() {
      revision++; nativePending = true; nativeAck = false; nativeSince = Date.now();
      global.clearTimeout(nativeTimer);
      nativeTimer = global.setTimeout(() => {
        if (!nativePending || disposed) return;
        error = { code: 'NATIVE_UPDATE_UNCONFIRMED', message: 'تعذّر تأكيد تحديث المنتج في السلة. أعد التحقق قبل إتمام الطلب.' };
        phase = 'failed'; emit();
      }, config.operationTimeoutMs || 12000);
      schedule(350); emit();
    }
    function listen(target, name, handler, capture) {
      target.addEventListener(name, handler, capture); listeners.push(() => target.removeEventListener(name, handler, capture));
    }
    function bindSdkEvents() {
      const events = sdk()?.event;
      if (sdkEventsBound || !ready || typeof events?.on !== 'function') return;
      sdkEventsBound = true;
      for (const name of ['cart::updated', 'cart::item.added', 'cart::item.updated', 'cart::item.deleted']) {
        const handler = () => {
          sdkEventCounts[name] = (sdkEventCounts[name] || 0) + 1;
          if (config.debug === true) document.documentElement?.setAttribute('data-am-installation-sdk-events', JSON.stringify({ bound: true, last: name, count: sdkEventCounts[name] }));
          // Our no-op summary transaction is not an acknowledgement of a newer
          // user option/quantity request. Its native event still updates widgets.
          if (nativePending && active?.type !== 'summaryRefresh') nativeAck = true;
          schedule(300);
        };
        events.on(name, handler); listeners.push(() => events.off?.(name, handler));
      }
    }
    function checkoutTarget(event) {
      const target = event.target?.closest?.('a,button,salla-button');
      return target && (target.closest('#s-cart-summary-card-submit') || target.matches('[data-am-checkout]') || target.textContent.trim() === 'إتمام الطلب');
    }
    const api = {
      async start() {
        if (started) return api;
        if (!document.body?.classList.contains('cart')) throw new Error('Installation controller is scoped to the native cart only');
        started = true; startedAt = Date.now(); dirty = true; phase = 'pending';
        const begin = () => { if (disposed || ready) return; ready = true; bindSdkEvents(); schedule(0); };
        if (sdk()?.onReady) sdk().onReady(begin); else if (sdk()?.cart) begin();
        else readyTimer = global.setTimeout(() => { error = { code: 'SDK_NOT_READY', message: 'خدمة السلة غير جاهزة. أعد تحميل الصفحة.' }; phase = 'failed'; emit(); }, 10000);
        unknownTimer = global.setTimeout(() => { unknownExpired = true; revision++; schedule(); }, config.unknownCityGraceMs ?? 5000);
        listen(document, 'headerContextUpdate', event => {
          const detail = event.detail;
          const view = document.querySelector('.s-bullet-delivery-cart-view');
          const signature = (view?.querySelector('.s-bullet-delivery-cart-view-title')?.textContent.trim() || '') + '|' + (view?.querySelector('.s-bullet-delivery-cart-view-subtitle')?.textContent.trim() || '');
          cityHint = detail?.type === 'address' && typeof detail.city === 'string' && detail.city.trim() ? { viewAtEvent: signature, context: { known: true, city: detail.city.trim(), group: String(detail.country_code || '').toUpperCase() === 'SA' ? groupCity(detail.city) : '' } } : null;
          revision++; updatePlace(); schedule(); emit();
        });
        listen(document, 'bulletDeliveryConfirmed', () => { revision++; updatePlace(); schedule(); emit(); });
        listen(document, 'change', event => {
          if (event.target?.closest?.('[data-am-installation-control]')) return;
          if (legacyScan().fields.some(field => field.select === event.target)) { revision++; schedule(); emit(); return; }
          const card = event.target?.closest?.('[data-testid^="store-cart-item-"],.cart-item');
          if (card && event.target.matches?.('input[name="quantity"],salla-quantity-input input,select[name^="options["],input[name^="options["]')) nativeChanged();
        }, true);
        listen(document, 'click', event => {
          if (checkoutTarget(event) && viewState().blocked) { event.preventDefault(); event.stopImmediatePropagation(); emit(); config.onBlocked?.(viewState()); return; }
          const button = event.target?.closest?.('.cart-item .s-quantity-input-button,.cart-item salla-button.btn--delete button');
          if (!button) return;
          const card = button.closest('.cart-item');
          if (button.closest('salla-button.btn--delete') || button.classList.contains('am-delete-at-one')) {
            const match = String(card?.getAttribute('data-testid') || card?.id || '').match(/^store-cart-item-(\d+)$/);
            if (match && intents.has(match[1])) intents.set(match[1], { wanted: false, revision: ++revision });
          }
          nativeChanged();
        }, true);
        listen(document, 'submit', event => { if (event.target?.matches?.('[data-am-checkout-form]') && viewState().blocked) { event.preventDefault(); event.stopImmediatePropagation(); emit(); } }, true);
        // onReady may run synchronously when the SDK is already initialized.
        // Never bind against an incomplete pre-ready event object.
        bindSdkEvents();
        observer = new MutationObserver(() => {
          // Comparing the public delivery view also catches removal/replacement
          // of the whole address component, without observing our own UI state.
          const previous = JSON.stringify(place); updatePlace();
          if (previous !== JSON.stringify(place)) schedule(250);
          const scan = legacyScan();
          if (legacyView !== scan.signature) { legacyView = scan.signature; revision++; schedule(150); }
          const summary = summaryView(), signature = summary?.signature || '';
          if (summaryViewSignature !== signature) { summaryViewSignature = signature; schedule(250); }
        });
        observer.observe(document.body, { subtree: true, childList: true, characterData: true });
        emit(); return api;
      },
      request(parentCartItemId, wanted) {
        const parentId = id(parentCartItemId);
        if (typeof wanted !== 'boolean') throw new Error('Explicit installation choice required');
        updatePlace();
        const parent = snapshot?.items.find(item => item.id === parentId);
        if (!parent || !eligible.has(parent.productId)) throw new Error('Parent is not a verified eligible cart item');
        if (wanted && !place.group) throw new Error('Choose an installation-supported delivery city first');
        if (wanted && ambiguousAdds.has(parentId)) throw new Error('Previous addition is unconfirmed; refresh readback before retrying');
        intents.set(parentId, { wanted, revision: ++revision });
        if (!wanted) ambiguousAdds.delete(parentId);
        if (!active && (error?.code !== 'ADD_UNCONFIRMED' || !wanted && !ambiguousAdds.size)) error = null;
        schedule(); emit(); return api.getState();
      },
      refresh() { revision++; schedule(0); return api.getState(); },
      async retry() {
        // Read-only recovery first; an ambiguous add is never issued again here.
        if (running || active) { schedule(); return api.getState(); }
        if (error?.code === 'LEGACY_RESET_UNCONFIRMED' && legacyAttemptKey) {
          try { (config.sessionStorage || global.sessionStorage).removeItem(legacyAttemptKey); }
          catch (_) { emit(); return api.getState(); }
        }
        if (error?.code === 'SUMMARY_REFRESH_UNCONFIRMED' && summaryStatus?.signature) summaryAttempts.delete(summaryStatus.signature);
        updatePlace();
        try {
          await read();
          if (!active && !ambiguousAdds.size && !snapshot.items.some(item => item.service && !item.parentId)) { error = null; if (nativePending && !snapshot.items.some(item => eligible.has(item.productId) && nativeQty(item.id) !== null && nativeQty(item.id) !== item.quantity)) { nativePending = false; global.clearTimeout(nativeTimer); } schedule(0); }
        } catch (_) { /* Retain failure and the checkout guard. */ }
        emit(); return api.getState();
      },
      getState: () => viewState(),
      destroy() {
        disposed = true; observer?.disconnect(); listeners.splice(0).forEach(remove => remove());
        [scheduled, unknownTimer, nativeTimer, readyTimer].forEach(timer => global.clearTimeout(timer));
      }
    };
    return api;
  }
  global.AlmoalejInstallationCore = Object.freeze({ create, version: '1.0.0-draft' });
})(window);

/* Cart presentation adapter. Load card-ui.js, then core.js, then this file.
 * Explicit boot only:
 * const adapter = AlmoalejInstallationAdapter.start({
 *   enabled:true, legacyFeesConfirmedDisabled:true, testOnly:true,
 *   servicesByFee, eligibleProducts,
 *   hideVerifiedServiceCards:true,
 *   hideLegacyControls:true, legacyOptionIds:['1177925547', ...]
 * });
 * testOnly defaults to true and requires ?am_install_test (or testParam).
 * Production needs explicit testOnly:false. The legacy confirmation is an
 * operator assertion of native admin/readback verification, never a CSS fix.
 * legacyOptionIds are rendered option IDs, NOT the admin custom-field IDs.
 * UI is isolated in an open ShadowRoot by default so old broad native-select
 * guards cannot consume its controls. isolateUI:false is only for an already
 * patched legacy source that excludes [data-am-installation-control].
 *
 * Core owns all cart/address events, requests, reconciliation and checkout
 * blocking. This observer only remounts DOM from the last server-backed state.
 * destroy restores hidden native service/legacy cards; it never deletes items.
 */
(function (global) {
  'use strict';
  if (global.AlmoalejInstallationAdapter) return;
  let active = null;
  const PREFIX = 'am-install:v1:';
  const selector = '[data-testid^="store-cart-item-"],[id^="store-cart-item-"]';
  const own = '[data-am-installation-control]';
  const noteSelector = '.am07-cart-intro,.am-cart-context-note';
  const oldNote = 'اختيار التركيب يشمل جميع القطع المؤهلة ضمن فئة الأجرة نفسها.';
  const newNote = 'يمكنك اختيار التركيب لكل منتج مؤهل بشكل مستقل من بطاقته.';
  const id = value => {
    if (typeof value === 'number' && !Number.isSafeInteger(value)) return '';
    const result=String(value == null ? '' : value);
    return /^\d+$/.test(result) ? result : '';
  };
  const productId = raw => id(raw?.product_id ?? raw?.product?.id);
  const price = value => {
    const amount=value && typeof value==='object' ? value.amount : value;
    if (typeof amount==='number') return Number.isFinite(amount) && amount>=0 ? amount : null;
    return typeof amount==='string' && /^\d+(?:\.\d+)?$/.test(amount) ? Number(amount) : null;
  };
  const cardFor = itemId => document.querySelector('[data-testid="store-cart-item-'+itemId+'"],#store-cart-item-'+itemId);
  const cardId = card => (card?.getAttribute('data-testid') || card?.id || '').match(/^store-cart-item-(\d+)$/)?.[1] || '';
  const text = (node,value) => {if(node.textContent!==value)node.textContent=value;};

  function start(config) {
    if (!document.body?.classList.contains('cart') || !config || config.enabled!==true) return null;
    const testOnly=config.testOnly!==false, param=config.testParam || 'am_install_test';
    if (testOnly && !new URLSearchParams(location.search).has(param)) return null;
    if (config.legacyFeesConfirmedDisabled!==true) throw new Error('Native legacy installation fees must be verified disabled before boot');
    if (!global.AlmoalejInstallationCore?.create || !global.AlmoalejInstallCardUI?.create) throw new Error('Installation core and UI must be loaded before the adapter');
    if (active) throw new Error('An installation adapter is already running');
    const eligible=new Map(),services=new Map();
    Object.entries(config.eligibleProducts || {}).forEach(([key,value])=>eligible.set(id(key),String(value && typeof value==='object' ? value.fee : value)));
    Object.entries(config.servicesByFee || {}).forEach(([fee,value])=>services.set(String(fee),value));
    const ui=global.AlmoalejInstallCardUI,mounts=new WeakMap(),mounted=new Set(),serviceHidden=new Map(),managedServiceProofs=new Map(),legacyHidden=new Map(),noteFixes=new Map(),summaryMounts=new Map(),summaryLabels=new Map();
    let state=null,disposed=false,frame=0,controller=null,banner=null,bannerMessage=null,retry=null;
    const number=new Intl.NumberFormat('ar-SA',{maximumFractionDigits:2});
    function hide(node,records) {
      if (!records.has(node)) records.set(node,{hidden:node.hidden,aria:node.getAttribute('aria-hidden'),display:node.style.getPropertyValue('display'),priority:node.style.getPropertyPriority('display')});
      node.hidden=true;node.setAttribute('aria-hidden','true');node.style.setProperty('display','none','important');
    }
    function restore(records) {
      records.forEach((before,node)=>{
        node.hidden=before.hidden;
        if(before.aria===null)node.removeAttribute('aria-hidden');else node.setAttribute('aria-hidden',before.aria);
        if(before.display)node.style.setProperty('display',before.display,before.priority);else node.style.removeProperty('display');
      });
      records.clear();
    }
    function requestAddress() {
      const component=document.querySelector('salla-bullet-delivery');
      if(typeof component?.open==='function'){
        try{return Promise.resolve(component.open()).catch(()=>{if(bannerMessage)text(bannerMessage,'تعذّر فتح اختيار منطقة التوصيل. أعد المحاولة.');});}
        catch(error){if(bannerMessage)text(bannerMessage,'تعذّر فتح اختيار منطقة التوصيل. أعد المحاولة.');return;}
      }
      if(bannerMessage)text(bannerMessage,'تعذّر فتح اختيار منطقة التوصيل. أعد تحميل الصفحة ثم حاول مرة أخرى.');
    }
    function patchNotes(){
      document.querySelectorAll(noteSelector).forEach(paragraph=>{
        const walker=document.createTreeWalker(paragraph,NodeFilter.SHOW_TEXT);
        let node;while((node=walker.nextNode())){
          const before=node.nodeValue;
          if(!before.includes(oldNote) || before.indexOf(oldNote)!==before.lastIndexOf(oldNote))continue;
          const after=before.replace(oldNote,newNote);noteFixes.set(node,{before,after});node.nodeValue=after;
        }
      });
    }
    function removeEntry(entry){ui.destroy(entry.el);if(entry.host!==entry.el)entry.host.remove();}
    function captureManagedServiceProofs(current){
      // Capture every server-backed snapshot before rAF coalescing can erase a
      // transient pending state. No DOM node or current rendered row is needed.
      const items=current?.nativeCart?.items;if(!Array.isArray(items))return;
      const byId=new Map(items.map(item=>[id(item.id),item]).filter(([key])=>key));
      items.forEach(item=>{
        const itemId=id(item.id),pid=productId(item),quantity=Number(item.quantity);
        if(!/^\d{19}$/.test(itemId) || !Number.isInteger(quantity) || quantity<1)return;
        for(const [fee,service] of services){
          if(pid!==id(service.productId))continue;
          const actualPrice=price(item.price),expectedPrice=price(service.expectedUnitPrice);
          if(actualPrice===null || expectedPrice===null || actualPrice!==expectedPrice)return;
          const option=Array.isArray(item.options) && item.options.find(option=>id(option.id)===id(service.linkOptionId));
          const parentId=typeof option?.value==='string' ? option.value.match(/^am-install:v1:(\d{19})$/)?.[1] : '';
          if(!parentId)return;
          const parent=byId.get(parentId);
          if(parent){
            const parentQuantity=Number(parent.quantity);
            if(eligible.get(productId(parent))!==fee || !Number.isInteger(parentQuantity) || parentQuantity<1)return;
          }
          // A missing parent is an owned orphan, which core also removes. Its
          // exact native marker, configured service and verified price suffice.
          managedServiceProofs.set(itemId,{itemId,productId:pid,linkOptionId:id(service.linkOptionId),parentId,fee});
          return;
        }
      });
    }
    function captureRetiredServiceProofs(current){
      // Core records these only after native SDK readback confirms deletion.
      // This authority survives state/paint coalescing and missing SSR parents.
      if(!Array.isArray(current?.retiredServiceRows))return;
      current.retiredServiceRows.forEach(row=>{
        const itemId=id(row?.itemId),parentId=id(row?.parentId),pid=id(row?.productId),linkOptionId=id(row?.linkOptionId),fee=String(row?.fee??'');
        const service=services.get(fee);
        if(!/^\d{19}$/.test(itemId) || !/^\d{19}$/.test(parentId) || !service || pid!==id(service.productId) || linkOptionId!==id(service.linkOptionId))return;
        managedServiceProofs.set(itemId,{itemId,productId:pid,linkOptionId,parentId,fee,retired:true});
      });
    }
    function removeConfirmedServiceGhosts(current,rawById){
      // Only a completed authoritative read can retire an already verified
      // managed DOM row. Never infer deletion from a pending/error snapshot.
      if(current.phase!=='saved' || current.pending || current.running || current.error || !Array.isArray(current.nativeCart?.items))return;
      managedServiceProofs.forEach(proof=>{
        if(rawById.has(proof.itemId))return;
        const card=cardFor(proof.itemId);
        if(!card?.isConnected || !/^\d{19}$/.test(proof.itemId) || cardId(card)!==proof.itemId)return;
        const service=services.get(proof.fee);
        if(!service || id(service.productId)!==proof.productId || id(service.linkOptionId)!==proof.linkOptionId)return;
        // Remove an obsolete wrapper form only when it belongs exclusively to
        // this precise cart item. Shared forms and their fields remain intact.
        const form=card.closest('form'),input=form?.querySelector('input[type="hidden"][name="id"]');
        const formCards=form ? Array.from(form.querySelectorAll(selector)).filter(node=>cardId(node)) : [];
        if(form?.matches(selector))formCards.unshift(form);
        if(form && input?.value===proof.itemId && formCards.length===1 && formCards[0]===card)form.remove();
        else if(card.tagName!=='FORM')card.remove();
        else return;
        serviceHidden.delete(card);
        // Retain this exact item's server proof for late/reinserted SSR markup.
      });
    }
    function nestKnownNativeServiceCards(current,rawById){
      // Presentation only: native allocation may retire a service before core
      // ever reads it. A recognized SSR service card is still an auxiliary UI,
      // not a physical product or evidence of a current backend charge.
      if(current.phase!=='saved' || current.pending || current.running || current.error || !Array.isArray(current.nativeCart?.items))return;
      document.querySelectorAll('section[data-testid^="store-cart-item-"],section[id^="store-cart-item-"]').forEach(card=>{
        if(!/^\d{19}$/.test(cardId(card)))return;
        const links=Array.from(card.querySelectorAll('a[href]')).filter(link=>link.closest('h1') || !!link.querySelector('img'));
        const products=new Set();
        links.forEach(link=>{try{const match=new URL(link.getAttribute('href'),location.href).pathname.match(/\/p(\d+)(?:\/|$)/);if(match)products.add(match[1]);}catch{}});
        if(products.size!==1)return;
        const pid=products.values().next().value;
        const configured=Array.from(services).find(([,service])=>id(service.productId)===pid);
        if(!configured)return;
        const [fee,service]=configured,fieldId=id(service.linkOptionId);
        const inputs=Array.from(card.querySelectorAll('input')).filter(input=>input.name==='options['+fieldId+']');
        let values=inputs.map(input=>input.value);
        if(!inputs.length){
          values=[];
          card.querySelectorAll('salla-product-options').forEach(host=>{
            const hostProduct=id(host.getAttribute('product-id'));if(hostProduct && hostProduct!==pid)return;
            // Read both public property and serialized native attribute. An
            // unhydrated component can expose [] while its attribute has data.
            [host.options,host.getAttribute('options')].forEach(raw=>{
              let options;try{options=typeof raw==='string'?JSON.parse(raw):raw;}catch{return;}
              if(Array.isArray(options))options.filter(option=>id(option.id)===fieldId).forEach(option=>values.push(option.value));
            });
          });
        }
        if(!values.length)return;
        const parents=values.map(value=>typeof value==='string'?value.match(/^am-install:v1:(\d{19})$/)?.[1]:'');
        if(parents.some(parent=>!parent) || new Set(parents).size!==1)return;
        const parent=rawById.get(parents[0]);
        if(parent && eligible.get(productId(parent))!==fee)return;
        hide(card,serviceHidden); // No removal, pricing or native cart mutation.
      });
    }
    function clearSummary(entry){entry.line.remove();entry.note.remove();}
    function renderSummary(current,verified,serviceCount){
      const sheets=Array.from(document.querySelectorAll('.s-cart-summary-card-sheet')).filter(sheet=>Array.from(sheet.querySelectorAll('header h3')).some(title=>title.textContent.trim()==='ملخص الطلب'));
      const ready=!current.pending && !current.running && !current.error && !current.blocked && verified.length>0 && verified.length===serviceCount;
      const complete=ready && verified.every(item=>typeof item.total==='number' && Number.isFinite(item.total) && item.total>=0);
      const total=complete ? verified.reduce((sum,item)=>sum+item.total,0) : null;
      const seen=new Set();
      for(const sheet of sheets){
        const subtotal=Array.from(sheet.querySelectorAll('.s-cart-summary-card-line')).find(line=>!line.closest(own) && Array.from(line.children).some(child=>child.tagName==='SPAN' && ['مجموع المنتجات','مجموع المنتجات والخدمات'].includes(child.textContent.trim())));
        if(!subtotal)continue;
        const label=Array.from(subtotal.children).find(child=>child.tagName==='SPAN' && ['مجموع المنتجات','مجموع المنتجات والخدمات'].includes(child.textContent.trim()));
        if(serviceCount>0 && label.textContent.trim()==='مجموع المنتجات'){
          if(!summaryLabels.has(label))summaryLabels.set(label,{before:label.textContent,after:'مجموع المنتجات والخدمات'});
          text(label,'مجموع المنتجات والخدمات');
        }else if(serviceCount===0 && summaryLabels.has(label)){
          const original=summaryLabels.get(label);if(label.textContent===original.after)text(label,original.before);summaryLabels.delete(label);
        }
        let entry=summaryMounts.get(sheet);
        if(total===null || !Number.isFinite(total)){
          if(entry){clearSummary(entry);summaryMounts.delete(sheet);}continue;
        }
        if(!entry || !entry.line.isConnected || entry.subtotal!==subtotal){
          if(entry)clearSummary(entry);
          const line=document.createElement('div');line.className='s-cart-summary-card-line am-install-summary-line';line.setAttribute('data-am-installation-control','summary');
          line.style.cssText='display:flex;align-items:center;justify-content:space-between;gap:12px;color:#0756d9;font-size:14px';
          const title=document.createElement('span');title.textContent='منها رسوم التركيب';
          const amount=document.createElement('b'),value=document.createTextNode(''),currency=document.createElement('i');currency.className='sicon-sar';currency.setAttribute('aria-hidden','true');amount.append(value,currency);line.append(title,amount);
          const note=document.createElement('small');note.className='am-install-summary-count-note';note.setAttribute('data-am-installation-control','summary');
          note.style.cssText='display:block;margin:4px 0 10px;color:#526b84;font-size:12px;line-height:1.8';note.textContent='عدد العناصر يشمل خدمات التركيب المرتبطة.';
          subtotal.after(line);line.after(note);entry={line,note,amount,value,subtotal};summaryMounts.set(sheet,entry);
        }
        const formatted=number.format(total)+' ';if(entry.value.nodeValue!==formatted)entry.value.nodeValue=formatted;
        entry.amount.setAttribute('aria-label',number.format(total)+' ريال سعودي');seen.add(sheet);
      }
      summaryMounts.forEach((entry,sheet)=>{if(!sheet.isConnected || !seen.has(sheet)){clearSummary(entry);summaryMounts.delete(sheet);}});
      summaryLabels.forEach((entry,label)=>{if(!label.isConnected)summaryLabels.delete(label);});
    }
    function hasLegacyFeeControls(){
      return Array.from(document.querySelectorAll('select[name^="options["]')).some(select=>{
        const options=Array.from(select.options);
        return options.some(option=>/^مع\s+التركيب\s*[—–-]\s*.*?\s*[—–-]/.test(option.textContent.trim())) && options.some(option=>/^بدون\s+تركيب(?:\s|[—–-]|$)/.test(option.textContent.trim()));
      });
    }
    function renderBanner(current) {
      const visible=!!current.error || !!current.blocked || (current.rows || []).length>0;
      if(!visible){banner?.remove();banner=null;bannerMessage=null;retry=null;return;}
      if(!banner){
        banner=document.createElement('section');banner.id='am-per-card-installation-state';banner.tabIndex=-1;
        banner.setAttribute('data-am-installation-control','status');banner.setAttribute('role','status');banner.setAttribute('aria-live','polite');
        banner.style.cssText='margin:14px 0;padding:14px;border:1px solid #d6e5f3;border-radius:12px;background:#f2f8ff;color:#082b59;direction:rtl;line-height:1.8;font-size:14px';
        bannerMessage=document.createElement('p');bannerMessage.style.margin='0';
        retry=document.createElement('button');retry.type='button';retry.textContent='إعادة التحقق';
        retry.style.cssText='min-height:44px;margin-top:8px;padding:8px 12px;border:1px solid #bdd2e7;border-radius:8px;background:#fff;color:#0756d9;font:inherit;cursor:pointer';
        retry.addEventListener('click',()=>{void controller.retry();});banner.append(bannerMessage,retry);
      }
      if(!banner.isConnected){const delivery=document.querySelector('.s-bullet-delivery-cart-view'),host=delivery?.closest('salla-bullet-delivery') || delivery,main=document.getElementById('main-content');if(host)host.after(banner);else main?.prepend(banner);}
      text(bannerMessage,current.message || 'راجع اختيار التركيب لكل منتج قبل إتمام الطلب.');
      retry.hidden=!current.error;retry.disabled=!!current.running;
    }
    function paint() {
      frame=0;if(disposed || !state)return;
      // Local state only: native SDK events can mark pending before onState emits.
      if(controller)state=controller.getState();
      captureManagedServiceProofs(state);
      captureRetiredServiceProofs(state);
      const rawItems=Array.isArray(state.nativeCart?.items) ? state.nativeCart.items : [];
      const rawById=new Map(rawItems.map(raw=>[id(raw.id),raw]).filter(([key])=>key));
      removeConfirmedServiceGhosts(state,rawById);
      // Restore only surviving rows; confirmed-deleted ghosts were retired.
      restore(serviceHidden);restore(legacyHidden);
      const seen=new Set(),summaryServices=[];
      const serviceCount=rawItems.filter(item=>Array.from(services.values()).some(service=>productId(item)===id(service.productId))).length;
      for(const row of state.rows || []){
        const parentId=id(row.parentId),pid=id(row.productId),feeKey=eligible.get(pid),service=services.get(feeKey);
        const raw=rawById.get(parentId),card=parentId && cardFor(parentId);
        if(!card || cardId(card)!==parentId || !raw || productId(raw)!==pid || !service || !eligible.has(pid))continue;
        const quantity=Number(raw.quantity);
        if(!Number.isInteger(quantity) || quantity<1 || Number(row.quantity)!==quantity)continue;
        const linked=(row.serviceItemIds || []).map(key=>rawById.get(id(key))).filter(item=>{
          if(!item || productId(item)!==id(service.productId))return false;
          const option=Array.isArray(item.options) && item.options.find(option=>id(option.id)===id(service.linkOptionId));
          return option?.value===PREFIX+parentId;
        });
        const serverSelected=linked.length>0,actual=linked.length===1 ? linked[0] : null;
        const actualQuantity=actual && Number(actual.quantity),actualFee=actual && price(actual.price);
        const expectedFee=price(service.expectedUnitPrice),busy=!!state.pending || !!row.pending || !!state.running;
        const fee=actualFee!==null && actualFee!==undefined ? actualFee : expectedFee;
        const known=state.city?.known===true,city=String(state.city?.city || '');
        const actualQuantityValid=Number.isInteger(actualQuantity) && actualQuantity>0;
        const charged=serverSelected && actualQuantityValid ? 'خدمة التركيب المسجلة: '+number.format(actualQuantity)+' قطعة. ' : '';
        let message=state.error?.message || (busy ? charged+'جارٍ تأكيد الخدمة ورسومها من السلة…' : '');
        // The selected control and installation total already confirm the saved service.
        let entry=mounts.get(card);
        if(entry && entry.parentId!==parentId){removeEntry(entry);mounted.delete(card);mounts.delete(card);entry=null;}
        if(!entry || !entry.el.isConnected){
          if(entry)removeEntry(entry);
          const el=ui.create({});el.setAttribute('data-am-installation-control','product');
          let host=el;
          if(config.isolateUI!==false){
            host=document.createElement('div');host.className='am-install-card-host';host.setAttribute('data-am-installation-control','product');
            host.style.cssText='display:block;width:100%;min-width:0';host.attachShadow({mode:'open'}).append(el);
          }
          card.append(host);entry={el,host,parentId};mounts.set(card,entry);mounted.add(card);
        }
        ui.update(entry.el,{fee,city,supported:known ? row.allowed===true : null,selected:serverSelected,busy,
          quantity:serverSelected && Number.isInteger(actualQuantity) && actualQuantity>0 ? actualQuantity : quantity,message,
          onChooseAddress:requestAddress,onChange:selected=>{
            try{controller.request(parentId,selected);}catch(error){ui.update(entry.el,{message:error.message || 'تعذّر تحديث خيار التركيب. أعد التحقق من السلة.'});}
          }});
        seen.add(card);
        // Recognized services remain visually nested during quantity syncing.
        // Their actual charged quantity is visible in the parent's helper.
        const ownedPriceValid=!state.error && linked.length===1 && actualQuantityValid && actualFee!==null && expectedFee!==null && actualFee===expectedFee;
        if(config.hideVerifiedServiceCards===true && ownedPriceValid){
          const serviceCard=cardFor(id(actual.id));if(serviceCard && serviceCard!==card && cardId(serviceCard)===id(actual.id)){
            hide(serviceCard,serviceHidden);
          }
        }
        if(ownedPriceValid && row.confirmed===true && !busy && actualQuantity===quantity)summaryServices.push(actual);
      }
      for(const card of mounted){if(!card.isConnected || !seen.has(card)){const entry=mounts.get(card);if(entry)removeEntry(entry);mounts.delete(card);mounted.delete(card);}}
      nestKnownNativeServiceCards(state,rawById);
      if(config.hideLegacyControls===true && config.legacyFeesConfirmedDisabled===true){
        for(const value of config.legacyOptionIds || []){
          const optionId=id(value);if(!optionId)continue;
          const select=document.getElementById('option-'+optionId);
          if(!select?.matches('select') || select.name!=='options['+optionId+']')continue;
          const group=select.closest('.s-product-options-option-container') || select.closest('.s-product-options-option');
          if(group && !group.closest(own))hide(group,legacyHidden);
        }
      }
      // Exact known legacy status from the line-640 city guard. Never suppress
      // it while an old shared fee control is still present in native markup.
      if(config.legacyFeesConfirmedDisabled===true && !hasLegacyFeeControls()){
        const oldStatus=document.getElementById('am-installation-delivery-status');if(oldStatus)hide(oldStatus,legacyHidden);
      }
      patchNotes();renderBanner(state);renderSummary(state,summaryServices,serviceCount);
    }
    function schedulePaint(){if(!disposed && !frame)frame=requestAnimationFrame(paint);}
    const observer=new MutationObserver(records=>{
      const relevant=records.some(record=>{
        if(record.target instanceof Element && record.target.closest(own))return false;
        const parent=record.target instanceof Element ? record.target : record.target.parentElement;
        if(parent?.closest(noteSelector) && parent.textContent.includes(oldNote))return true;
        const nodes=[...record.addedNodes,...record.removedNodes];
        if(nodes.length && nodes.every(node=>node instanceof Element && node.matches(own)))return false;
        const observed=selector+','+noteSelector+',.s-cart-summary-card-sheet';
        return (record.target instanceof Element && !!record.target.closest(selector+',.s-cart-summary-card-sheet')) || nodes.some(node=>node instanceof Element && (node.matches(observed) || node.querySelector(observed)));
      });
      if(relevant)schedulePaint(); // No SDK read/write or controller.refresh here.
    });
    controller=global.AlmoalejInstallationCore.create({...config,onState:next=>{
      captureManagedServiceProofs(next);captureRetiredServiceProofs(next);state=next;schedulePaint();if(typeof config.onState==='function')config.onState(next);
    },onBlocked:next=>{
      captureManagedServiceProofs(next);captureRetiredServiceProofs(next);state=next;paint();banner?.focus({preventScroll:true});if(typeof config.onBlocked==='function')config.onBlocked(next);
    }});
    const adapter={controller,getState:()=>controller.getState(),refresh:()=>controller.refresh(),destroy(){
      if(disposed)return;disposed=true;observer.disconnect();if(frame)cancelAnimationFrame(frame);controller.destroy();
      restore(serviceHidden);restore(legacyHidden);for(const card of mounted){const entry=mounts.get(card);if(entry)removeEntry(entry);}mounted.clear();banner?.remove();
      managedServiceProofs.clear();
      noteFixes.forEach((before,node)=>{if(node.isConnected && node.nodeValue===before.after)node.nodeValue=before.before;});noteFixes.clear();
      summaryMounts.forEach(clearSummary);summaryMounts.clear();summaryLabels.forEach((entry,label)=>{if(label.isConnected && label.textContent===entry.after)text(label,entry.before);});summaryLabels.clear();
      if(active===adapter)active=null;
    }};
    active=adapter;observer.observe(document.getElementById('main-content') || document.body,{childList:true,subtree:true,characterData:true});
    Promise.resolve(controller.start()).catch(error=>{state={rows:[],error:{message:error.message},blocked:true,message:'تعذّر تهيئة خدمة التركيب. أعد تحميل الصفحة.'};schedulePaint();});
    return adapter;
  }
  global.AlmoalejInstallationAdapter=Object.freeze({start,version:'1.2.0-native-aux-presentation'});
})(window);

/* Explicit DOM-only factory; no auto-start, SDK, stock, native notes or prices.
 * const visibility=AlmoalejInstallationServiceVisibility.create({
 *   enabled:true, servicesByFee
 * }).start();
 * visibility.refresh(); visibility.destroy();
 * Auxiliary products remain native cart items. Cart presentation is exclusively
 * handled by the installation adapter. This is UI policy, not server security.
 */
(function(global){
  'use strict';
  if(global.AlmoalejInstallationServiceVisibility)return;
  const oldSentence='ينطبق اختيار الخدمة على جميع القطع المؤهلة ضمن فئة الأجرة نفسها في السلة.';
  const newSentence='يمكن اختيار خدمة التركيب لكل منتج مؤهل بشكل مستقل من بطاقته في السلة.';
  const own='[data-am-installation-service-notice]';
  const wrapperSelector='salla-product-card,custom-salla-product-card,.swiper-slide';
  const validId=value=>typeof value==='number'&&!Number.isSafeInteger(value)?'':/^\d+$/.test(String(value??''))?String(value):'';
  function create(config){
    const serviceIds=new Set(Object.values(config?.servicesByFee||{}).map(value=>validId(value?.productId)).filter(Boolean));
    const hidden=new Map(),replacements=new Map(),observedRoots=new WeakSet();
    let started=false,disposed=false,observer=null,frame=0,notice=null;
    function restore(node,before){
      node.hidden=before.hidden;
      if(before.aria===null)node.removeAttribute('aria-hidden');else node.setAttribute('aria-hidden',before.aria);
      if(before.display)node.style.setProperty('display',before.display,before.priority);else node.style.removeProperty('display');
    }
    function conceal(node,desired){
      desired.add(node);
      if(!hidden.has(node))hidden.set(node,{hidden:node.hidden,aria:node.getAttribute('aria-hidden'),display:node.style.getPropertyValue('display'),priority:node.style.getPropertyPriority('display')});
      node.hidden=true;node.setAttribute('aria-hidden','true');node.style.setProperty('display','none','important');
    }
    function entriesInside(node){
      const entries=new Set(node.querySelectorAll('.s-product-card-entry'));
      if(node.shadowRoot)node.shadowRoot.querySelectorAll('.s-product-card-entry').forEach(entry=>entries.add(entry));
      node.querySelectorAll('salla-product-card,custom-salla-product-card').forEach(host=>{
        host.shadowRoot?.querySelectorAll('.s-product-card-entry').forEach(entry=>entries.add(entry));
      });
      return Array.from(entries);
    }
    function watchRoots(){
      if(!observer)return;
      document.querySelectorAll('salla-product-card,custom-salla-product-card').forEach(host=>{
        const root=host.shadowRoot;if(!root || observedRoots.has(root))return;
        observer.observe(root,{childList:true,subtree:true,characterData:true,attributes:true,attributeFilter:['id','class']});observedRoots.add(root);
      });
    }
    function wrapperOwnsOnlyServices(wrapper){
      const entries=entriesInside(wrapper);
      return entries.length>0 && entries.every(entry=>serviceIds.has(entry.id));
    }
    function catalogCards(desired){
      if(document.body.classList.contains('cart'))return;
      const entries=Array.from(document.querySelectorAll('.s-product-card-entry'));
      // Known singular product-card hosts can also expose an open native root.
      document.querySelectorAll('salla-product-card,custom-salla-product-card').forEach(host=>{
        if(host.shadowRoot)entries.push(...host.shadowRoot.querySelectorAll('.s-product-card-entry'));
      });
      entries.forEach(entry=>{
        if(!serviceIds.has(entry.id) || entry.closest('.cart-item,[data-testid^="store-cart-item-"]'))return;
        conceal(entry,desired);
        let current=entry;
        for(let depth=0;depth<3;depth++){
          const root=current.getRootNode(),parent=current.parentElement || (root instanceof ShadowRoot ? root.host : null);
          if(!parent?.matches(wrapperSelector) || !wrapperOwnsOnlyServices(parent))break;
          conceal(parent,desired);current=parent;
        }
      });
    }
    function cartHref(){
      const existing=Array.from(document.querySelectorAll('a[href]')).map(link=>{
        try{return new URL(link.href,location.href);}catch{return null;}
      }).find(url=>url?.origin===location.origin && /\/cart\/?$/.test(url.pathname));
      const prefix=location.hostname==='salla.sa' && location.pathname.startsWith('/almoalej.com') ? '/almoalej.com' : '';
      const url=existing || new URL(prefix+'/cart',location.origin);
      const params=new URLSearchParams(location.search);if(params.has('preview'))url.searchParams.set('preview',params.get('preview'));
      return url.href;
    }
    function servicePage(desired){
      const pageId=location.pathname.match(/\/p(\d+)(?:\/|$)/)?.[1];
      const main=document.getElementById('main-content');
      if(!main || !serviceIds.has(pageId) || document.body.classList.contains('cart')){notice?.remove();notice=null;return;}
      let anchor=null;
      main.querySelectorAll('form').forEach(form=>{
        const input=form.querySelector('input[name="id"]');
        const purchasing=form.matches('.product-form,[data-testid="store-product-form"]') || !!form.querySelector('[data-testid="store-product-add-to-cart"],salla-add-product-button');
        if(purchasing && input && validId(input.value)===pageId){conceal(form,desired);anchor=anchor||form;}
      });
      main.querySelectorAll('[data-testid="store-product-add-to-cart"],salla-add-product-button,salla-quick-buy,salla-quick-order,salla-mini-checkout-widget').forEach(control=>{
        if(control.closest('.s-product-card-entry,.cart-item,[data-testid^="store-cart-item-"]'))return;
        const product=validId(control.getAttribute('product-id'));
        if(!product || product===pageId){conceal(control,desired);anchor=anchor||control;}
      });
      if(!notice){
        notice=document.createElement('section');notice.setAttribute('data-am-installation-service-notice','true');notice.setAttribute('aria-label','خدمة التركيب');
        notice.style.cssText='box-sizing:border-box;margin:18px 0;padding:20px;border:1px solid #cbdff2;border-radius:14px;background:#f1f8ff;color:#082b59;direction:rtl;line-height:1.9;font-family:inherit';
        const text=document.createElement('p');text.textContent='تُضاف خدمة التركيب من بطاقة المنتج داخل السلة';text.style.cssText='margin:0 0 14px;font-size:18px;font-weight:700';
        const link=document.createElement('a');link.textContent='الذهاب إلى السلة';
        link.style.cssText='box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;min-height:44px;max-width:100%;padding:10px 18px;border-radius:9px;background:#0756d9;color:#fff;font-weight:700;text-decoration:none';
        notice.append(text,link);
      }
      const link=notice.querySelector('a'),href=cartHref();if(link.href!==href)link.href=href;
      if(!notice.isConnected){if(anchor)anchor.before(notice);else main.prepend(notice);}
    }
    function descriptions(){
      document.querySelectorAll('#main-content article').forEach(article=>{
        const walker=document.createTreeWalker(article,NodeFilter.SHOW_TEXT);let node;
        while((node=walker.nextNode())){
          const before=node.nodeValue;if(!before.includes(oldSentence))continue;
          const after=before.split(oldSentence).join(newSentence);replacements.set(node,{before,after});node.nodeValue=after;
        }
      });
      replacements.forEach((value,node)=>{if(!node.isConnected)replacements.delete(node);});
    }
    function scan(){
      frame=0;if(!started || disposed)return;
      watchRoots();const desired=new Set();catalogCards(desired);servicePage(desired);descriptions();
      hidden.forEach((before,node)=>{if(!node.isConnected || !desired.has(node)){restore(node,before);hidden.delete(node);}});
    }
    function schedule(){if(started && !disposed && !frame)frame=requestAnimationFrame(scan);}
    const api={start(){
      if(started || disposed || config?.enabled!==true)return api;
      if(!serviceIds.size)throw new Error('Verified installation service IDs are required');
      started=true;scan();observer=new MutationObserver(records=>{
        if(records.some(record=>{
          if(record.type==='attributes')return record.target.matches('.s-product-card-entry,salla-product-card,custom-salla-product-card');
          const parent=record.target instanceof Element ? record.target : record.target.parentElement;
          if(parent?.closest(own))return false;
          const nodes=[...record.addedNodes,...record.removedNodes];
          return !nodes.length || !nodes.every(node=>node instanceof Element && node.matches(own));
        }))schedule();
      });
      observer.observe(document.body,{childList:true,subtree:true,characterData:true,attributes:true,attributeFilter:['id','class']});watchRoots();global.addEventListener('popstate',schedule);return api;
    },refresh:schedule,destroy(){
      if(disposed)return;disposed=true;observer?.disconnect();if(frame)cancelAnimationFrame(frame);global.removeEventListener('popstate',schedule);
      hidden.forEach((before,node)=>restore(node,before));hidden.clear();notice?.remove();notice=null;
      replacements.forEach((before,node)=>{if(node.isConnected && node.nodeValue===before.after)node.nodeValue=before.before;});replacements.clear();
    }};
    return api;
  }
  global.AlmoalejInstallationServiceVisibility=Object.freeze({create,version:'1.0.0-draft'});
})(window);

(function(){
 function start(){
  if(location.pathname.split('/').some(part=>['checkout','payment','payments'].includes(part.toLowerCase())))return;
  const config={"enabled":true,"legacyFeesConfirmedDisabled":true,"testOnly":false,"debug":false,"releaseId":"14d6c1ab227b","refreshNativeSummary":true,"servicesByFee":{"59":{"productId":"696086226","linkOptionId":"447030316","expectedUnitPrice":59},"100":{"productId":"519614875","linkOptionId":"1322966776","expectedUnitPrice":100},"200":{"productId":"373446428","linkOptionId":"1266263138","expectedUnitPrice":200},"400":{"productId":"1026510677","linkOptionId":"1650709554","expectedUnitPrice":400},"600":{"productId":"1689064447","linkOptionId":"1547285084","expectedUnitPrice":600}},"eligibleProducts":{"965839551":"59","77942364":"59","1451388253":"59","1916119903":"59","1276299864":"59","436201817":"59","1168185179":"59","395195812":"59","1634423973":"59","220107431":"59","683724961":"59","2058223522":"59","643251628":"59","1883004077":"59","535272111":"59","1775024552":"59","1000986793":"59","1733494443":"59","825763252":"59","50676917":"59","1355990922":"400","583001739":"400","2089026964":"400","1314989205":"400","586548182":"600","116766857":"400","157637518":"200","1531083407":"200","891853192":"200","2094211799":"200","411394257":"200","1320698320":"200","543722590":"200","1558340534":"59","784892599":"59","2023072176":"59","610267058":"59","1982074547":"59","1073819068":"59","502156477":"59","1875602366":"59","192850360":"59","1700513977":"59","924899258":"59","17692347":"59","750204037":"59","332856963":"59","1840455052":"59","1066941581":"59","407782294":"59","1781228183":"59","1207009680":"59","299802769":"59","1673252754":"59","1031859859":"59","258805148":"59","1498033309":"59","722946974":"59","83651231":"59","1457162648":"59","547858585":"59","1921824666":"59","1282004635":"59","506918372":"59","1746080997":"59","1173894118":"59","398807783":"59","746108227":"59","1638035936":"59","864588001":"59","223723490":"59","1597169379":"59","689962476":"59","2061769965":"59","1421949934":"59","648960751":"59","1888188904":"59","1112643817":"59","473868266":"59","1847314155":"59","1004594676":"59","365757685":"59","829899511":"59","56386032":"59","1564115185":"59","789032946":"59","2028785395":"59","1254747644":"59","1987259390":"59","1079528191":"59","1704121796":"59","931132613":"59","21238726":"59","1394684615":"59","755913152":"59","2129359041":"59","1219600322":"59","446611139":"59","1954274764":"59","1178664141":"59","271391694":"59","1644837583":"59","1071077832":"59","163346633":"59","1536853962":"59","895985355":"59","122471892":"59","1361700053":"59","1038027742":"59","262417119":"59","1501645272":"59","728656089":"59","88831962":"59","1460770523":"59","1391339356":"59","1603079366":"59","1217068773":"59","1439515426":"59","1808009306":"59","613813501":"59","304441848":"59","971544570":"59","196458235":"59","1391072644":"100","440897920":"100","1108966318":"59","1249034417":"59"},"hideVerifiedServiceCards":true,"hideLegacyControls":true,"legacyOptionIds":["1177925547","29339160","1570511627","1504552759","905624383"],"legacyOptionDefaults":{"1177925547":"1679389776","29339160":"788542874","1570511627":"1808178754","1504552759":"147961896","905624383":"1125195101"}};
  document.documentElement.dataset.amInstallationRelease=config.releaseId;
  if(!config.testOnly)window.AlmoalejInstallationServiceVisibility.create({enabled:true,servicesByFee:config.servicesByFee}).start();
  if(!document.body.classList.contains('cart'))return;
  if(config.testOnly && new URLSearchParams(location.search).has('am_install_legacy_seed'))return;
  window.AlmoalejInstallationAdapter.start(config);
 }
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();

/* Almoalej UX polish 2026-11-19. Uses native product options and order history. */
(function(){
'use strict';
if(window.__amUxPolish19)return;window.__amUxPolish19=true;
const colorIds=new Set(['1808009306','543722590','77942364']);
const style=document.createElement('style');style.id='am-ux19-style';style.textContent="\n/* Consistent uncropped packshots and touch-friendly cards. */\nbody.am-commerce07 .s-product-card-entry .s-product-card-image{aspect-ratio:1/1!important;height:auto!important;background:#fff!important;padding:12px!important;overflow:hidden!important;border-bottom:1px solid #edf2f7}\nbody.am-commerce07 .s-product-card-entry .s-product-card-image>a{display:flex!important;align-items:center;justify-content:center;width:100%;height:100%}\nbody.am-commerce07 .s-product-card-entry .s-product-card-image img{object-fit:contain!important;width:100%!important;height:100%!important;background:#fff;transform:none!important}\nbody.am-commerce07 .s-product-card-entry .s-product-card-content-title{min-height:3.6em;line-height:1.8!important}\nbody.am-commerce07 .s-product-card-entry .s-product-card-content-title a{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}\n.am-ux19-unready{display:none!important}\n.am-ux19-repeat{max-width:1240px;margin:24px auto;padding:22px 24px;background:#f3f8fc;border:1px solid #d9e6ef;border-radius:16px;display:flex;align-items:center;justify-content:space-between;gap:18px;color:#123349;direction:rtl}\n.am-ux19-repeat h2{font-size:22px;font-weight:800;margin:0 0 6px}.am-ux19-repeat p{font-size:14px;line-height:1.8;margin:0;color:#486577}.am-ux19-repeat a{background:#0756ad;color:#fff!important;border-radius:10px;padding:12px 20px;min-height:46px;display:inline-flex;align-items:center;justify-content:center;font-weight:700;white-space:nowrap;text-decoration:none}\n.am-ux19-repeat a:focus-visible,.am-ux19-repeat-link:focus-visible{outline:3px solid #137de5;outline-offset:3px}\n.am-ux19-search-note{padding:10px 14px;background:#eff7fc;color:#244b68;font-size:13px;line-height:1.8;border-radius:9px;margin:8px 0}\n.am-ux19-choice-note{font-size:13px;color:#43617b;margin:10px 0;line-height:1.8}\n.am-ux19-repeat-link{display:inline-block;padding:10px 14px;border:1px solid #0756ad;border-radius:8px;color:#0756ad;margin:6px 0;font-weight:700;min-height:44px}\n@media(max-width:767px){\nbody.am-commerce07 .am-banner-carousel{max-height:270px!important;border-radius:12px;overflow:hidden}\nbody.am-commerce07 .am-banner-slide{max-height:245px!important;min-height:0!important}\nbody.am-commerce07 .am-banner-slide img{max-height:245px!important;object-fit:contain!important;background:#fff}\nbody.am-commerce07 .am07-list-hero{padding:16px!important;margin-bottom:12px!important}\nbody.am-commerce07 .am07-list-hero h1{font-size:22px!important;margin-bottom:6px!important}\nbody.am-commerce07 .am07-list-hero p{font-size:14px!important;line-height:1.7!important}\nbody.am-commerce07 .s-product-card-entry .s-product-card-image{padding:8px!important}\nbody.am-commerce07 .s-product-card-entry .s-product-card-content{padding:10px!important}\nbody.am-commerce07 .s-product-card-entry .s-product-card-content-title{font-size:14px!important;min-height:5.4em}\nbody.am-commerce07 .s-product-card-entry .s-button-element,body.am-commerce07 .am07-card-link{min-height:46px!important;font-size:13px!important;white-space:normal!important}\nbody.am-commerce07 .am07-list-tools{gap:8px!important;margin-bottom:12px!important}\n.am-ux19-repeat{margin:16px;padding:16px;flex-direction:column;align-items:stretch;gap:12px}.am-ux19-repeat h2{font-size:20px}.am-ux19-repeat a{white-space:normal;width:100%}\nbody.am-commerce07 .s-product-card-entry{min-width:0!important}\nbody.am-commerce07.product-single .magnify-wrapper{touch-action:pan-y!important}\nbody.am-commerce07.product-single .magnify-wrapper img{transform:none!important;object-fit:contain!important}\n}\n@media(prefers-reduced-motion:reduce){.am-banner-carousel *{transition:none!important;animation:none!important}}\n";document.head.append(style);
const make=(tag,cls,text)=>{const el=document.createElement(tag);if(cls)el.className=cls;if(text)el.textContent=text;return el;};
function cards(){document.querySelectorAll('.s-product-card-entry').forEach(card=>{
 const pic=card.querySelector('.s-product-card-image img'),link=card.querySelector('a[href*="/p"]');if(!link)return;
 const id=link.href.match(/\/p(\d+)/)?.[1],title=card.querySelector('.s-product-card-content-title')?.textContent.trim()||pic?.alt||'';
 const src=pic?.getAttribute('src')||pic?.getAttribute('data-src')||'';
 const missing=!!src&&/placeholder|default-product|no-image/i.test(src);
 const test=/^اختبار|^رسوم تركيب القطعة/.test(title);
 if(card.classList.contains('am-ux19-unready')!==(missing||test))card.classList.toggle('am-ux19-unready',missing||test);
 card.querySelectorAll('.am07-quickadd-trigger').forEach(button=>{
  const text=colorIds.has(id)?(id==='1808009306'?'اختر الشكل واللون':'اختر اللون'):'اختر خيارات المنتج';
  if(button.textContent!==text)button.textContent=text;
  const label=text+': '+title;if(button.getAttribute('aria-label')!==label)button.setAttribute('aria-label',label);
 });
});}
// Synonyms are converted before the native Salla search receives the event.
const aliases=[[/حنفي[ةه]|بزبوز/g,'صنبور'],[/(^|\s)لي(?=\s|$)/g,'$1هوز'],[/شمعات|شموع/g,'فلاتر'],[/شمع[ةه]/g,'فلتر']];
let rewriting=false;
document.addEventListener('input',event=>{
 const input=event.composedPath().find(el=>el instanceof HTMLInputElement&&el.type==='search'&&!el.readOnly);if(!input||rewriting||event.isComposing)return;
 const before=input.value;let after=before;aliases.forEach(([pattern,value])=>after=after.replace(pattern,value));if(after===before)return;
 rewriting=true;input.value=after;rewriting=false;
 const panel=input.closest('.s-search-panel')||input.closest('form');if(panel){let note=panel.querySelector('.am-ux19-search-note');if(!note){note=make('p','am-ux19-search-note');note.setAttribute('role','status');note.setAttribute('aria-live','polite');panel.append(note);}note.textContent='نتائج البحث عن «'+after+'» — يشمل المسميات الشائعة مثل «'+before+'».';}
},true);
// Save only product-option values, never contact details, quantities or checkout data.
const restored=new WeakSet();let restoring=false;
function optionContext(el){const host=el.closest('salla-product-options');if(!host)return null;const pid=String(host.getAttribute('product-id')||location.pathname.match(/\/p(\d+)/)?.[1]||'');if(!/^\d+$/.test(pid))return null;return {host,pid,key:'am:product-choice:v1:'+pid};}
function optionFields(host){return Array.from(host.querySelectorAll('input[type="radio"][name^="options["],select[name^="options["]')).filter(el=>!el.disabled);}
function remember(event){if(!document.body.classList.contains('product-single')||restoring)return;const el=event.target;if(!(el instanceof HTMLInputElement||el instanceof HTMLSelectElement))return;const ctx=optionContext(el);if(!ctx)return;const values={};optionFields(ctx.host).forEach(field=>{if(field.type!=='radio'||field.checked)values[field.name]=field.value;});try{sessionStorage.setItem(ctx.key,JSON.stringify({at:Date.now(),values}));}catch{}}
document.addEventListener('change',remember,true);
function restoreChoices(){if(!document.body.classList.contains('product-single'))return;document.querySelectorAll('salla-product-options').forEach(host=>{
 if(restored.has(host))return;const fields=optionFields(host);if(!fields.length)return;const ctx=optionContext(fields[0]);if(!ctx)return;
 let saved;try{saved=JSON.parse(sessionStorage.getItem(ctx.key)||'null');}catch{}restored.add(host);if(!saved||Date.now()-saved.at>86400000)return;
 restoring=true;let applied=false;
 Object.entries(saved.values||{}).forEach(([name,value])=>{const field=fields.find(el=>el.name===name&&(el.type!=='radio'||el.value===value));if(!field)return;
 if(field.type==='radio'){if(!field.checked){field.checked=true;field.dispatchEvent(new Event('change',{bubbles:true}));applied=true;}}
 else if(Array.from(field.options).some(option=>option.value===value&&!option.disabled)&&field.value!==value){field.value=value;field.dispatchEvent(new Event('change',{bubbles:true}));applied=true;}});
 restoring=false;if(applied&&!host.nextElementSibling?.classList.contains('am-ux19-choice-note')){const note=make('p','am-ux19-choice-note','احتفظنا باختياراتك السابقة. راجع الصورة والسعر قبل الإضافة إلى السلة.');note.setAttribute('role','status');host.after(note);}
 });}
function repeatEntry(){
 if(!document.body.classList.contains('index'))return;const main=document.querySelector('main');if(!main||document.getElementById('am-repeat-order'))return;
 const box=make('section','am-ux19-repeat');box.id='am-repeat-order';box.setAttribute('aria-label','إعادة طلب الفلاتر والقطع');
 const words=make('div');words.append(make('h2','','تحتاج نفس الفلاتر مرة ثانية؟'),make('p','','افتح طلباتك السابقة للوصول إلى الفلتر أو القطعة نفسها، ثم راجع السعر والتوفر قبل الطلب.'));
 const link=make('a','','طلباتي السابقة');link.href=new URL('/account/orders',location.origin).href;box.append(words,link);
 const filters=document.getElementById('am-filters');if(filters)filters.after(box);else main.append(box);
}
function reorderLinks(){
 if(!/\/(?:account|customer)\/orders\//.test(location.pathname))return;
 document.querySelectorAll('main a[href*="/p"]').forEach(link=>{if(link.dataset.amRepeatReady)return;link.dataset.amRepeatReady='1';const row=link.closest('tr')||link.parentElement;if(!row||row.querySelector('.am-ux19-repeat-link'))return;const repeat=make('a','am-ux19-repeat-link','اطلب هذا المنتج مرة ثانية');repeat.href=link.href;repeat.setAttribute('aria-label','اطلب مرة ثانية: '+(link.textContent.trim()||'المنتج'));(row.tagName==='TR'?row.querySelector('td:last-child')||row:row).append(repeat);});
}
function shadowPolish(){const roots=[document];for(const root of roots){for(const host of root.querySelectorAll("*")){if(!host.shadowRoot)continue;roots.push(host.shadowRoot);const scope=host.shadowRoot;if(scope.querySelector(".am-banner-carousel,.s-block-simple-section__content")&&!scope.getElementById("am-ux19-shadow")){const css=make("style");css.id="am-ux19-shadow";css.textContent="@media(max-width:767px){.am-banner-carousel{height:270px!important;max-height:270px!important;aspect-ratio:auto!important}.am-banner-slide,.am-banner-picture{height:270px!important;max-height:270px!important;min-height:0!important}.am-banner-picture img{width:100%!important;height:270px!important;object-fit:contain!important;background:#fff}.s-block-simple-section{padding:20px 16px!important;min-height:0!important}.s-block-simple-section__title{font-size:25px!important;line-height:1.5!important}.s-block-simple-section__subtitle{font-size:14px!important;line-height:1.8!important;margin:10px 0!important}.s-block-simple-section__button,.am-secondary-link{min-height:44px!important;padding:10px 16px!important}}";scope.append(css);}}}}
let pending=false;
function run(){pending=false;shadowPolish();cards();restoreChoices();repeatEntry();reorderLinks();}
function schedule(){if(pending)return;pending=true;requestAnimationFrame(run);}
function start(){run();const observer=new MutationObserver(changes=>{if(changes.some(change=>change.type==='childList'&&Array.from(change.addedNodes).some(node=>node.nodeType===1&&!node.classList?.contains('am-ux19-search-note'))))schedule();});observer.observe(document.body,{childList:true,subtree:true});let warmups=0;const warmup=setInterval(()=>{schedule();if(++warmups>=12)clearInterval(warmup);},750);window.addEventListener('pageshow',schedule);document.addEventListener('visibilitychange',()=>{if(!document.hidden)schedule();});}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
/* Hide banner controls only; preserve the existing autoplay and slides. */
(function(){function hide(){const roots=[document];for(const root of roots){for(const host of root.querySelectorAll('*'))if(host.shadowRoot)roots.push(host.shadowRoot);if(root.querySelector('.am-banner-carousel')&&!root.querySelector('#am-banner-controls-hidden')){const style=document.createElement('style');style.id='am-banner-controls-hidden';style.textContent='.am-banner-carousel .am-banner-dots,.am-banner-carousel .am-banner-nav>button:last-child{display:none!important}@media(max-width:1023.98px){.am-banner-carousel .am-banner-nav{display:none!important}}@media(min-width:1024px){.am-banner-carousel .am-banner-nav{display:block!important}}';(root===document?document.head:root).append(style);}}}function start(){hide();let n=0;const timer=setInterval(()=>{hide();if(++n>=24)clearInterval(timer);},500);}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();

/* Edge-to-edge mobile banners only. */
(function(){const inside='@media(max-width:767px){:host{display:block!important;width:100%!important;max-width:none!important;margin-inline:0!important;padding-inline:0!important}.am-banner-carousel.am-banner-carousel{width:100%!important;max-width:none!important;height:auto!important;max-height:none!important;aspect-ratio:39/32!important;border-radius:0!important;margin-inline:0!important}.am-banner-slide.am-banner-slide,.am-banner-picture.am-banner-picture{width:100%!important;height:100%!important;max-height:none!important;min-height:0!important;border-radius:0!important}.am-banner-picture.am-banner-picture img{display:block!important;width:100%!important;height:100%!important;max-height:none!important;object-fit:contain!important;border-radius:0!important}}';function mount(){if(!document.getElementById('am-mobile-banner-edge')){const s=document.createElement('style');s.id='am-mobile-banner-edge';s.textContent='@media(max-width:767px){body.am-commerce07 main section.am-mobile-full-banner{width:100vw!important;max-width:none!important;margin-inline:calc(50% - 50vw)!important;padding-inline:0!important;overflow:hidden}}';document.head.append(s);}const roots=[document];for(const root of roots){for(const el of root.querySelectorAll('*'))if(el.shadowRoot)roots.push(el.shadowRoot);if(!root.querySelector('.am-banner-carousel'))continue;const host=root.host;if(host){const section=host.parentElement;section?.classList.add('am-mobile-full-banner');if(section&&matchMedia('(max-width:767px)').matches){section.style.setProperty('width','100%','important');section.style.setProperty('max-width','none','important');section.style.setProperty('margin-inline','0','important');section.style.setProperty('padding-inline','0','important');}else if(section){['width','max-width','margin-inline','padding-inline'].forEach(p=>section.style.removeProperty(p));}if(!root.getElementById('am-mobile-banner-inner')){const s=document.createElement('style');s.id='am-mobile-banner-inner';s.textContent=inside;root.append(s);}}}}function start(){mount();matchMedia('(max-width:767px)').addEventListener('change',mount);let n=0;const timer=setInterval(()=>{mount();if(++n>=24)clearInterval(timer);},500);}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* Move the help and comparison section directly after the filters. */
(function(){function arrange(){if(!document.body.classList.contains('index'))return;const help=document.querySelector('section[component-id="1204252081"]');const filters=document.querySelector('section[component-id="25939608"]');if(help&&filters&&filters.nextElementSibling!==help)filters.after(help);}function start(){arrange();let n=0;const timer=setInterval(()=>{arrange();if(++n>=24)clearInterval(timer);},500);}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* Compact home, category and search product cards on mobile; preserve full images and native actions. */
(function(){function start(){if(!document.body.matches('.index,.product-index,.product-index-search,.product-single'))return;const s=document.createElement('style');s.id='am-compact-home-cards';s.textContent=`@media(max-width:767px){
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-products-list-wrapper{gap:10px!important;align-items:stretch!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-entry{min-height:0!important;height:auto!important;align-self:stretch!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-image{padding:5px!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content{padding:9px!important;gap:6px!important;justify-content:flex-start!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-main{min-height:0!important;margin:0!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .am07-type-badge{min-height:0!important;padding:2px 6px!important;margin:0 0 4px!important;font-size:10px!important;line-height:1.6!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-title{min-height:0!important;margin:0 0 4px!important;font-size:13px!important;line-height:1.65!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-title a{display:block!important;overflow:visible!important;white-space:normal!important;-webkit-line-clamp:unset!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-subtitle{margin:0!important;font-size:11px!important;line-height:1.5!important;min-height:0!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-sub{margin:0!important;gap:4px!important;min-height:0!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-sale-price{gap:5px!important;flex-wrap:wrap!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-sale-price h4,:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-price{font-size:18px!important;line-height:1.5!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-sale-price>span{font-size:11px!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-footer{margin-top:auto!important;padding-top:2px!important;gap:6px!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-footer .s-button-element,:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .am07-card-link{min-height:44px!important;height:auto!important;padding:7px 5px!important;font-size:12px!important;line-height:1.5!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .am-card-compare{margin:0!important;padding:0!important;min-height:44px!important;height:44px!important;font-size:11px!important}

:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .am07-type-badge,:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-subtitle{display:none!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-image{height:clamp(128px,37vw,160px)!important;min-height:0!important;aspect-ratio:auto!important;padding:4px!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-image>a{display:block!important;width:100%!important;height:100%!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-image img{width:100%!important;height:100%!important;object-fit:contain!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content{padding:8px!important;gap:4px!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-title{font-size:13px!important;line-height:1.6!important;min-height:83.2px!important;margin:0!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-sub{min-height:27px!important;align-items:center!important}
}`;document.head.append(s);}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* Match mobile visual order to the help section's position after filters. */
(function(){const s=document.createElement('style');s.id='am-help-mobile-order';s.textContent='@media(max-width:767px){body.index #main-content>section[component-id="1204252081"]{order:7!important}}';document.head.append(s);})();
/* Two compact columns for related and suggested product cards on mobile. */
(function(){const s=document.createElement('style');s.id='am-related-two-columns';s.textContent=`@media(max-width:767px){
body.product-single #main-content salla-products-slider .s-slider-container{width:100%!important;max-width:100%!important;margin-inline:0!important;padding:0!important;overflow:visible!important}
body.product-single #main-content salla-products-slider .swiper-wrapper{display:grid!important;grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:10px!important;transform:none!important;width:100%!important;height:auto!important;align-items:stretch!important}
body.product-single #main-content salla-products-slider .s-products-slider-card{width:100%!important;max-width:100%!important;min-width:0!important;height:auto!important;margin:0!important;padding:0!important;transform:none!important}
body.product-single #main-content salla-products-slider .s-product-card-entry{height:100%!important;width:100%!important;box-sizing:border-box!important}
body.product-single #main-content salla-products-slider .s-slider-block__title-nav,body.product-single #main-content salla-products-slider .swiper-pagination{display:none!important}
}`;document.head.append(s);})();
/* Consistent mobile card geometry and aligned price/actions across store pages. */
(function(){const s=document.createElement('style');s.id='am-final-mobile-card-alignment';s.textContent=`@media(max-width:767px){
body.index #main-content>section.s-block.container:has(salla-products-list){width:calc(100% - 20px)!important;margin-inline:10px!important;padding-inline:0!important;box-sizing:border-box!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content{display:grid!important;grid-template-columns:minmax(0,1fr) auto!important;grid-template-rows:auto auto 44px!important;gap:4px!important;padding:8px!important;align-content:start!important;flex:1 0 auto!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-main{grid-row:1!important;grid-column:1/-1!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-title a{font-size:inherit!important;line-height:inherit!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-sub{grid-row:2!important;grid-column:1/-1!important;min-height:44px!important;align-self:center!important;margin:0!important}
body.index #main-content .s-product-card-content:has(.am-card-compare) .s-product-card-content-sub{grid-column:1!important}
body.index #main-content .am-card-compare{grid-row:2!important;grid-column:2!important;width:52px!important;min-width:0!important;font-size:10px!important;line-height:1.4!important;white-space:normal!important;align-self:center!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-footer{grid-row:3!important;grid-column:1/-1!important;margin:0!important;padding:0!important;height:44px!important;min-height:44px!important}
:is(body:is(.index,.product-index,.product-index-search) #main-content,body.product-single #main-content salla-products-slider) .s-product-card-content-footer .s-button-element{height:44px!important}
}`;document.head.append(s);})();
/* Keep the mobile document centered and prevent horizontal page drift. */
(function(){const s=document.createElement('style');s.id='am-mobile-no-page-drift';s.textContent=`@media(max-width:767px){
html{width:100%!important;max-width:100%!important;overflow-x:clip!important;overscroll-behavior-x:none}
body{width:100%!important;max-width:100%!important;margin-inline:0!important;overflow-x:clip!important;overscroll-behavior-x:none}
#app,#main-content{min-width:0!important;max-width:100%!important}
header .flex-1,header .header-search,header salla-search{min-width:0!important;max-width:100%!important}
header .header-search{width:auto!important}
header .header-search .s-search-placeholder-wrapper,header .header-search .s-search-input-wrapper,header .header-search .s-search-input{width:100%!important;min-width:0!important;max-width:100%!important;box-sizing:border-box!important}
body.index #main-content>section.am-mobile-full-banner{width:100%!important;max-width:100%!important;margin-inline:0!important}
}`;document.head.append(s);})();
/* A compact mobile cart: product details first, native controls preserved. */
(function(){function start(){if(!document.body.classList.contains('cart'))return;const style=document.createElement('style');style.id='am-mobile-cart-compact';style.textContent=`@media(max-width:767px){
body.cart header.store-header .top-navbar,body.cart header.store-header>div:first-child{display:none!important}
body.cart header.store-header #mainnav,body.cart header.store-header #mainnav .inner{height:56px!important;min-height:56px!important}
body.cart header.store-header #mainnav .container{padding-block:0!important}
body.cart header.store-header .navbar-brand img{height:40px!important;max-height:40px!important;width:auto!important;object-fit:contain!important}
body.cart header.store-header .navbar-brand{padding:0!important;display:flex!important;align-items:center!important}
body.cart #main-content>.container{width:calc(100% - 20px)!important;max-width:none!important;margin-inline:10px!important;padding-inline:0!important}
body.cart #main-content .breadcrumbs,body.cart #main-content .am07-cart-intro{display:none!important}
body.cart #main-content>.container>h1.sr-only{font-size:22px!important;line-height:1.4!important;margin:10px 0!important;padding:0!important}
body.cart #main-content>.container>h1.sr-only:after{display:none!important}
body.cart #main-content>.container>.pt-5{padding-top:0!important}
body.cart #am-per-card-installation-state{display:flex!important;align-items:center!important;gap:8px!important;margin:8px 10px!important;padding:8px 10px!important;font-size:12px!important;line-height:1.6!important}
body.cart #am-per-card-installation-state>p,body.cart .am-cart-short-prompt{flex:1!important;min-width:0!important}body.cart #am-per-card-installation-state.am-cart-short-message>p{display:none!important}
body.cart .am-cart-delivery-shortcut{flex:0 0 auto;min-height:44px;padding:6px 9px;border:1px solid #cbdff2;border-radius:8px;background:#fff;color:#0756d9;font:inherit;font-weight:700}
body.cart .cart-item{padding:12px!important;margin-bottom:12px!important;border-radius:12px!important;box-shadow:0 3px 12px #082b5906!important}
body.cart .cart-item>div:first-of-type{display:block!important;margin:0!important}
body.cart .cart-item>div:first-of-type>div:first-child{display:grid!important;grid-template-columns:80px minmax(0,1fr)!important;gap:10px!important;padding:0!important}
body.cart .cart-item>div:first-of-type>div:first-child>*{margin:0!important;min-width:0!important}
body.cart .cart-item>div:first-of-type>div:first-child>a{width:80px!important;height:80px!important}
body.cart .cart-item img{width:80px!important;height:80px!important;object-fit:contain!important;background:white!important}
body.cart .cart-item h1,body.cart .cart-item h1 a{font-size:14px!important;line-height:1.6!important;min-height:0!important;margin:0 0 5px!important;overflow-wrap:anywhere!important}
body.cart .cart-item .item-price{font-size:17px!important;font-weight:800!important;line-height:1.5!important}
body.cart .cart-item .item-original-price{font-size:12px!important}
body.cart .cart-item .item-weight-row{display:none!important}
body.cart .cart-item>div:first-of-type>div:nth-child(2){margin:8px 0 0!important;padding:0!important;border:0!important;gap:8px!important;min-height:44px!important}
body.cart .cart-item .s-quantity-input-container{height:44px!important}
body.cart .cart-item .s-quantity-input-button{min-height:44px!important;min-width:44px!important}
body.cart .cart-item .s-quantity-input-input{height:44px!important;font-size:16px!important}
body.cart .cart-item .item-total{font-size:16px!important}
body.cart salla-cart-summary-card .s-cart-summary-card-bar{padding-block:8px!important}
body.cart salla-cart-summary-card .s-cart-summary-card-action{padding-block:8px!important}
body.cart salla-cart-summary-card .s-cart-summary-card-action button{min-height:46px!important}
}`;document.head.append(style);
const small=matchMedia('(max-width:767px)'),seenSummary=new WeakSet();let queued=false;
const installationCSS=`@media(max-width:767px){.am-install-card{display:grid!important;grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:6px!important;padding:8px!important;margin:8px 0 0!important;border-radius:9px!important;box-shadow:none!important}.am-install-card-header{grid-column:1/-1!important}.am-install-card-label{font-size:13px!important}.am-install-card-fee{font-size:11px!important;padding:2px 5px!important}.am-install-card-select{grid-column:1/-1!important;grid-row:2!important;margin:0!important;min-height:44px!important;height:44px!important;padding:6px 8px!important}.am-install-card-address{grid-column:2!important;grid-row:2!important;margin:0!important;max-width:110px!important;padding:5px 7px!important;min-height:44px!important;font-size:11px!important}.am-install-card-note,.am-install-card-total,.am-install-card-status{grid-column:1/-1!important;margin:0!important;font-size:11px!important;line-height:1.5!important}}@media(max-width:359px){.am-install-card-select{grid-column:1/-1!important;grid-row:2!important}.am-install-card-address{grid-column:1/-1!important;grid-row:3!important;width:100%!important;max-width:100%!important;text-align:center!important;font-size:12px!important}.am-install-card-note{grid-row:4!important}}@media(max-width:767px){.am-install-card :is(.am-install-card-select,.am-install-card-address){box-sizing:border-box!important;width:100%!important;max-width:none!important;min-width:0!important;height:44px!important;min-height:44px!important;padding-block:4px!important;font-size:13px!important;line-height:1.35!important}}`;
function sync(){document.querySelectorAll('.am-install-card-host').forEach(host=>{const root=host.shadowRoot;if(root&&!root.getElementById('am-cart-install-compact')){const s=document.createElement('style');s.id='am-cart-install-compact';s.textContent=installationCSS;root.append(s)}});if(!small.matches)return;
const box=document.getElementById('am-per-card-installation-state'),p=box?.querySelector('p');if(box){const normal=p&&['اختر مدينة التوصيل أولًا. التركيب متاح في الأحساء والدمام والرياض وتبوك فقط.','حدّد مدينة التوصيل لعرض خيارات التركيب.'].includes(p.textContent.trim());box.classList.toggle('am-cart-short-message',!!normal);let short=box.querySelector('.am-cart-short-prompt');if(!short){short=document.createElement('span');short.className='am-cart-short-prompt';short.textContent='حدّد مدينة التوصيل لعرض خيارات التركيب.';box.prepend(short)}short.hidden=!normal;}
if(box&&!box.querySelector('.am-cart-delivery-shortcut')){const native=document.querySelector('header.store-header button.btn--rounded-gray[onclick]');if(native){const b=document.createElement('button');b.type='button';b.className='am-cart-delivery-shortcut';b.textContent='مدينة التوصيل';b.addEventListener('click',()=>native.click());box.append(b)}}
document.querySelectorAll('salla-cart-summary-card').forEach(card=>{const toggle=card.querySelector('.s-cart-summary-card-chevron');if(!toggle||seenSummary.has(card))return;seenSummary.add(card);if(toggle.getAttribute('aria-expanded')==='true')toggle.click()});}
function schedule(){if(queued)return;queued=true;requestAnimationFrame(()=>{queued=false;sync()})}sync();new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true});small.addEventListener('change',sync);let n=0;const timer=setInterval(()=>{sync();if(++n>=24)clearInterval(timer)},500);
}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* Keep native product-option controls readable in small cart cards. */
(function(){const s=document.createElement('style');s.id='am-cart-small-option-controls';s.textContent='@media(max-width:767px){body.cart #main-content .cart-item select{box-sizing:border-box!important;width:100%!important;min-width:0!important;max-width:100%!important;min-height:44px!important;font-size:16px!important}body.cart #main-content .cart-item label{overflow-wrap:anywhere}}';document.head.append(s);})();
/* Fit the full cart header row inside its compact mobile height. */
(function(){const s=document.createElement('style');s.id='am-cart-header-row-fit';s.textContent=`@media(max-width:767px){
body.cart header.store-header #mainnav .inner>.container,body.cart header.store-header #mainnav .inner>.container>div{height:56px!important;min-height:56px!important;max-height:56px!important;box-sizing:border-box!important}
body.cart header.store-header #mainnav .inner>.container>div{align-items:center!important;gap:8px!important}
body.cart header.store-header #mainnav .inner>.container>div>div{height:44px!important;min-height:0!important;margin-block:0!important;display:flex!important;align-items:center!important;padding-block:0!important}
body.cart header.store-header #mainnav .navbar-brand{margin-block:0!important;height:40px!important;min-height:0!important;max-height:40px!important}
body.cart header.store-header #mainnav .mburger{display:inline-flex!important;align-items:center!important;justify-content:center!important;width:44px!important;height:44px!important;margin:0!important;flex:0 0 44px!important}
body.cart header.store-header #mainnav salla-user-menu,body.cart header.store-header #mainnav salla-cart-summary{height:44px!important;align-self:center!important;margin-block:0!important}
body.cart header.store-header #mainnav .s-user-menu-login-btn,body.cart header.store-header #mainnav .s-cart-summary-wrapper{height:44px!important;min-height:44px!important;box-sizing:border-box!important}
}`;document.head.append(s);})();
/* Mobile cart: quantity above total on the left, and an isolated image-choice dialog. */
(function(){function start(){if(!document.body.classList.contains('cart'))return;const style=document.createElement('style');style.id='am-cart-quantity-color-layout';style.textContent=`@media(max-width:767px){
body.cart #main-content .cart-item>div:first-of-type{display:grid!important;grid-template-columns:100px minmax(0,1fr)!important;gap:8px 10px!important;align-items:start!important}
body.cart #main-content .cart-item>div:first-of-type>div:first-child{display:contents!important}
body.cart #main-content .cart-item>div:first-of-type>div:first-child>a{grid-column:1!important;grid-row:1/span 2!important;width:100px!important;height:100px!important}
body.cart #main-content .cart-item>div:first-of-type>div:first-child>a img{width:100px!important;height:100px!important;object-fit:contain!important}
body.cart #main-content .cart-item>div:first-of-type>div:first-child>div{grid-column:2!important;grid-row:1!important;min-width:0!important}
body.cart #main-content .cart-item>div:first-of-type>div:nth-child(2){grid-column:2!important;grid-row:2!important;display:flex!important;flex-direction:column!important;align-items:flex-end!important;justify-content:flex-start!important;gap:5px!important;margin:0!important;min-width:0!important}
body.cart #main-content .cart-item>div:first-of-type>div:nth-child(2)>p{margin:0!important;text-align:left!important;font-size:12px!important;white-space:normal!important}
body.cart .am-cart-image-preview{width:56px!important;height:56px!important;max-width:56px!important}
body.cart.am-cart-options-active{overflow-y:hidden!important}
html:has(body.cart.am-cart-options-active){overflow-y:hidden!important}
body.cart .am-cart-options-backdrop{position:fixed;inset:0;background:#082b5980;z-index:10000;backdrop-filter:blur(2px)}
body.cart #main-content salla-product-options .am-cart-image-group.am-cart-image-open>.s-product-options-option-content{position:fixed!important;inset:12px 10px!important;z-index:10010!important;width:auto!important;min-width:0!important;max-width:none!important;max-height:calc(100dvh - 24px)!important;height:auto!important;margin:0!important;padding:10px!important;overflow-x:hidden!important;overflow-y:auto!important;overscroll-behavior:contain!important;box-shadow:0 16px 48px #082b5940!important;border-radius:14px!important}
body.cart .am-cart-options-dialog-head{position:sticky;top:-10px;z-index:2;display:flex;align-items:center;justify-content:space-between;gap:8px;background:white;margin:-10px -10px 10px;padding:8px 10px;border-bottom:1px solid #d7e4f0}
body.cart .am-cart-options-dialog-head h2{font-size:14px!important;line-height:1.6!important;margin:0!important;flex:1;min-width:0}
body.cart .am-cart-options-close{flex:0 0 44px;width:44px;min-height:44px;border:1px solid #d7e4f0;border-radius:8px;background:#f4f8fc;color:#082b59;font-size:24px;line-height:1;cursor:pointer}
body.cart #main-content .am-cart-image-group .s-product-options-thumbnails-wrapper{grid-template-columns:repeat(2,minmax(0,1fr))!important;grid-auto-rows:auto!important;gap:12px!important;align-items:start!important}
body.cart #main-content .am-cart-image-group .s-product-options-thumbnails-wrapper>div{height:auto!important;min-height:0!important;padding:0!important;align-self:start!important}
body.cart #main-content .am-cart-image-group .s-product-options-thumbnails-wrapper p{height:auto!important;max-height:none!important;overflow:visible!important;white-space:normal!important;line-height:1.6!important;font-size:12px!important;margin:6px 0 0!important}
}`;document.head.append(style);const main=document.getElementById('main-content'),media=matchMedia('(max-width:767px)');if(!main)return;let last=null,queued=false,seq=0;
const backdrop=document.createElement('div');backdrop.className='am-cart-options-backdrop';backdrop.hidden=true;document.body.append(backdrop);
function close(group){const toggle=group?.querySelector('.am-cart-image-toggle');if(toggle?.getAttribute('aria-expanded')==='true')toggle.click();toggle?.focus({preventScroll:true})}
backdrop.addEventListener('click',()=>close(last));
function sync(){queued=false;main.querySelectorAll('.am-cart-image-group').forEach(group=>{const content=group.querySelector('.s-product-options-option-content');if(!content)return;if(!content.querySelector('.am-cart-options-dialog-head')){const head=document.createElement('div');head.className='am-cart-options-dialog-head';const title=document.createElement('h2');title.id='am-cart-colors-title-'+(++seq);title.textContent=group.querySelector('.s-product-options-option-label')?.textContent.replace(/\s*\*\s*$/,'').trim()||'خيارات المنتج';const button=document.createElement('button');button.type='button';button.className='am-cart-options-close';button.textContent='×';button.setAttribute('aria-label','إغلاق خيارات الألوان');button.addEventListener('click',()=>close(group));head.append(title,button);content.prepend(head);content.setAttribute('aria-labelledby',title.id)}if(media.matches){content.setAttribute('role','dialog');content.setAttribute('aria-modal','true')}else{content.removeAttribute('role');content.removeAttribute('aria-modal')}});const open=media.matches&&main.querySelector('.am-cart-image-open');document.body.classList.toggle('am-cart-options-active',!!open);backdrop.hidden=!open;if(open&&open!==last)open.querySelector('.am-cart-options-close')?.focus({preventScroll:true});last=open||null}
function schedule(){if(queued)return;queued=true;requestAnimationFrame(sync)}new MutationObserver(schedule).observe(main,{childList:true,subtree:true,attributes:true,attributeFilter:['class']});media.addEventListener('change',schedule);sync();
}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* Let cart product photos fill the free space beside quantity and total. */
(function(){const s=document.createElement('style');s.id='am-cart-photo-fill-space';s.textContent=`@media(max-width:767px){
body.cart #main-content .cart-item>div:first-of-type{grid-template-columns:clamp(112px,36vw,140px) minmax(0,1fr)!important}
body.cart #main-content .cart-item>div:first-of-type>div:first-child>a{position:relative!important;width:100%!important;height:auto!important;min-height:140px!important;max-height:200px!important;align-self:stretch!important;box-sizing:border-box!important}
body.cart #main-content .cart-item>div:first-of-type>div:first-child>a img{position:absolute!important;inset:0!important;width:100%!important;height:100%!important;max-width:100%!important;max-height:100%!important;object-fit:contain!important;box-sizing:border-box!important}
}`;document.head.append(s);})();
/* Square edge-to-edge mobile cart photo frames. */
(function(){const s=document.createElement('style');s.id='am-cart-square-photo';s.textContent=`@media(max-width:767px){
body.cart #main-content .cart-item>div:first-of-type>div:first-child>a{height:clamp(112px,36vw,140px)!important;min-height:0!important;max-height:none!important;aspect-ratio:1/1!important;align-self:start!important;padding:0!important;margin:0!important;border:0!important;border-radius:8px!important;overflow:hidden!important}
body.cart #main-content .cart-item>div:first-of-type>div:first-child>a img{display:block!important;width:100%!important;height:100%!important;object-fit:cover!important;object-position:center!important;padding:0!important;margin:0!important;border:0!important;border-radius:0!important}
}`;document.head.append(s);})();

/* Shared corner close control and outside dismissal for region dialogs. */
(function(){function start(){const selector='.s-bullet-delivery-modal,.s-scopes-modal';const s=document.createElement('style');s.id='am-region-close-style';s.textContent=`
:is(.s-bullet-delivery-modal,.s-scopes-modal) .s-modal-body{position:relative}
:is(.s-bullet-delivery-modal,.s-scopes-modal) .s-modal-header{position:static!important;display:block!important;margin:0!important;padding:0!important;min-height:0!important}
:is(.s-bullet-delivery-modal,.s-scopes-modal) .am-region-close{position:absolute!important;top:8px!important;left:8px!important;right:auto!important;z-index:10;display:flex!important;align-items:center;justify-content:center;width:36px!important;min-width:36px!important;height:36px!important;min-height:36px!important;max-width:36px!important;margin:0!important;padding:0!important;border:1px solid #d7e4f0;border-radius:8px;background:#f4f8fc;color:#082b59;font:inherit;font-size:24px!important;line-height:1;cursor:pointer}
:is(.s-bullet-delivery-modal,.s-scopes-modal) .am-region-close:focus-visible{outline:3px solid #86b5ff;outline-offset:2px}
.s-bullet-delivery-modal .s-bullet-delivery-title{padding-inline-end:40px!important}
`;document.head.append(s);let queued=false;const bound=new WeakSet();let opener=null;
function close(modal){modal.visible=false;modal.removeAttribute('visible');if(opener?.isConnected)opener.focus?.({preventScroll:true})}
function mount(){queued=false;document.querySelectorAll(selector).forEach(modal=>{if(!bound.has(modal)){bound.add(modal);modal.addEventListener('click',event=>{if(event.target.closest?.('.s-modal-body'))return;if(event.target.closest?.('.s-modal-overlay,.s-modal-wrapper')||event.target===modal){event.preventDefault();event.stopPropagation();close(modal)}});modal.addEventListener('keydown',event=>{if(event.key==='Escape'){event.preventDefault();close(modal)}})}const header=modal.querySelector('.s-modal-header');if(!header)return;let b=header.querySelector('.s-modal-close,.am-region-close');if(!b){b=document.createElement('button');b.type='button';b.addEventListener('click',event=>{event.preventDefault();event.stopPropagation();close(modal)});header.append(b)}b.classList.add('am-region-close');b.setAttribute('aria-label','إغلاق اختيار المنطقة');if(b.textContent!=='×')b.textContent='×';})}
document.addEventListener('click',event=>{if(!event.target.closest?.(selector))opener=event.target.closest?.('button,a')||document.activeElement},true);function schedule(){if(queued)return;queued=true;requestAnimationFrame(mount)}new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true});mount();}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* A clean mobile checkout bar without an expandable summary panel. */
(function(){const s=document.createElement('style');s.id='am-cart-checkout-bar-clear';s.textContent=`@media(max-width:767px){
body.cart salla-cart-summary-card.s-cart-summary-card--mobile{display:grid!important;grid-template-columns:minmax(0,1fr)!important;gap:8px!important;height:auto!important;min-height:0!important;max-height:none!important;padding:10px 12px calc(10px + env(safe-area-inset-bottom,0px))!important;box-sizing:border-box!important;background:#fff!important;overflow:visible!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-sheet-wrap,body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-chevron{display:none!important;visibility:hidden!important;pointer-events:none!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-bar{display:flex!important;align-items:center!important;justify-content:space-between!important;gap:8px!important;min-height:32px!important;height:auto!important;margin:0!important;padding:0!important;width:100%!important;box-sizing:border-box!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-bar-label{flex:1!important;min-width:0!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-bar-label-main{display:flex!important;align-items:center!important;flex-wrap:wrap!important;gap:5px!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-bar-count{font-size:11px!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-bar-totals{flex:0 0 auto!important;min-width:0!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-bar-total{font-size:20px!important;line-height:1.4!important;white-space:nowrap!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-action{width:100%!important;min-width:0!important;height:auto!important;margin:0!important;padding:0!important;box-sizing:border-box!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-action salla-button{display:block!important;width:100%!important;margin:0!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-action button{display:flex!important;align-items:center!important;justify-content:center!important;width:100%!important;min-height:48px!important;height:auto!important;margin:0!important;padding:10px 12px!important;font-size:16px!important;line-height:1.5!important;box-sizing:border-box!important;border-radius:10px!important}
body.cart salla-cart-summary-card.s-cart-summary-card--mobile .s-cart-summary-card-action .s-button-text{display:flex!important;align-items:center!important;justify-content:center!important;gap:6px!important;white-space:normal!important;line-height:1.5!important}
}`;document.head.append(s);})();
/* Deduplicate only upper delivery actions; keep every product-card action. */
(function(){function start(){if(!document.body.classList.contains('cart'))return;const s=document.createElement('style');s.id='am-upper-region-deduplicate';s.textContent='body.cart .am-cart-delivery-shortcut.am-upper-region-duplicate{display:none!important}';document.head.append(s);let queued=false;function visible(e){return e&&e.getBoundingClientRect().width>0&&e.getBoundingClientRect().height>0&&getComputedStyle(e).visibility!=='hidden'}function sync(){queued=false;const custom=document.querySelector('.am-cart-delivery-shortcut');if(!custom)return;const nativeView=Array.from(document.querySelectorAll('.s-bullet-delivery-cart-view')).some(e=>!e.closest('.cart-item')&&visible(e));const nativeHeader=Array.from(document.querySelectorAll('header.store-header button.btn--rounded-gray[onclick]')).some(visible);const duplicate=nativeView||nativeHeader;if(custom.classList.contains('am-upper-region-duplicate')!==duplicate)custom.classList.toggle('am-upper-region-duplicate',duplicate)}function schedule(){if(queued)return;queued=true;requestAnimationFrame(sync)}new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true,attributes:true,attributeFilter:['class','style']});window.addEventListener('resize',schedule,{passive:true});sync();}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* Use one clear label for every delivery-region opening action. */
(function(){function start(){let queued=false;const watched=new WeakSet();const names=new Set(['مدينة التوصيل','تحديد منطقة التوصيل','تغيير منطقة التوصيل','اختيار منطقة التوصيل','حدد منطقة التوصيل','تحديد العنوان','تغيير العنوان','استلام أو توصيل']);
function rename(button){const label=document.body.classList.contains('cart') && button.matches('.am-install-card-address,.am-cart-delivery-shortcut') ? 'تحديد منطقة التوصيل' : 'العنوان';const nodes=[],walker=document.createTreeWalker(button,NodeFilter.SHOW_TEXT);let n;while(n=walker.nextNode()){if(n.parentElement.closest('svg,i,[aria-hidden="true"]'))continue;if(n.textContent.trim())nodes.push(n)}if(nodes.length){if(nodes[0].textContent.trim()!==label)nodes[0].textContent=label;nodes.slice(1).forEach(t=>{if(t.textContent)t.textContent=''})}else{const span=document.createElement('span');span.textContent=label;button.append(span)}if(button.getAttribute('aria-label')!==label)button.setAttribute('aria-label',label);if(button.title!==label)button.title=label}
function sync(){queued=false;const roots=[document];for(const root of roots){root.querySelectorAll('button').forEach(b=>{const label=(b.innerText||b.textContent||'').replace(/\s+/g,' ').trim();const known=b.matches('.am-cart-delivery-shortcut,.am-install-card-address')||b.matches('header.store-header button.btn--rounded-gray[onclick*="scopes"]')||names.has(label);if(known)rename(b)});root.querySelectorAll('*').forEach(e=>{if(e.shadowRoot){roots.push(e.shadowRoot);if(!watched.has(e.shadowRoot)){watched.add(e.shadowRoot);new MutationObserver(schedule).observe(e.shadowRoot,{childList:true,subtree:true,characterData:true})}}})}}
function schedule(){if(queued)return;queued=true;requestAnimationFrame(sync)}new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true,characterData:true});sync();}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
/* Show the native confirmed delivery address beside the cart's edit action. */
(function(){function start(){if(!document.body.classList.contains('cart'))return;const main=document.getElementById('main-content');if(!main)return;const s=document.createElement('style');s.id='am-cart-selected-address-style';s.textContent=`body.cart .am-cart-address-summary{box-sizing:border-box;display:flex;align-items:center;gap:10px;margin:8px 10px 12px;padding:8px 10px;border:1px solid #d6e5f3;border-radius:12px;background:#f2f8ff;color:#082b59;direction:rtl}body.cart .am-cart-selected-address-value{flex:1;min-width:0;font-size:13px;line-height:1.7;overflow-wrap:anywhere}body.cart .am-cart-address-edit{flex:0 0 auto;min-height:44px;padding:7px 10px;border:1px solid #cbdff2;border-radius:8px;background:#fff;color:#0756d9;font:inherit;font-size:13px;font-weight:700;cursor:pointer}body.cart #am-per-card-installation-state.am-cart-short-message,body.cart #am-per-card-installation-state .am-cart-delivery-shortcut,body.cart .s-bullet-delivery-cart-view{display:none!important}@media(max-width:359px){body.cart .am-cart-address-summary{gap:7px;padding:8px}body.cart .am-cart-address-edit{font-size:12px;padding:7px 8px}}`;document.head.append(s);let confirmed='',queued=false;
const box=document.createElement('section');box.className='am-cart-address-summary';box.setAttribute('aria-label','عنوان التوصيل');const value=document.createElement('span');value.className='am-cart-selected-address-value';value.setAttribute('aria-live','polite');const edit=document.createElement('button');edit.type='button';edit.className='am-cart-address-edit';edit.textContent='تعديل العنوان';edit.setAttribute('aria-label','تعديل العنوان');edit.addEventListener('click',()=>document.querySelector('header.store-header button.btn--rounded-gray[onclick]')?.click());box.append(value,edit);main.prepend(box);
function nativeAddress(){const view=document.querySelector('.s-bullet-delivery-cart-view');const title=view?.querySelector('.s-bullet-delivery-cart-view-title')?.textContent.trim()||'';const subtitle=view?.querySelector('.s-bullet-delivery-cart-view-subtitle')?.textContent.trim()||'';return title==='توصيل'&&subtitle?subtitle:''}
function sync(){queued=false;const nativeContext=window.AlmoalejNativeDeliveryContext?.get();const text=nativeAddress()||confirmed||(nativeContext?.known?'إلى '+nativeContext.city:'لم يتم تحديد العنوان');if(value.textContent!==text)value.textContent=text;if(!box.isConnected)main.prepend(box)}function schedule(){if(queued)return;queued=true;requestAnimationFrame(sync)}
document.addEventListener('headerContextUpdate',event=>{const d=event.detail;if(d?.type==='address'&&typeof d.city==='string'&&d.city.trim()){confirmed=[d.country,d.region,d.city,d.district,d.street,d.address].filter(x=>typeof x==='string'&&x.trim()).map(x=>x.trim()).filter((x,i,a)=>a.indexOf(x)===i).join('، ')}else confirmed='';schedule()});new MutationObserver(schedule).observe(main,{childList:true,subtree:true,characterData:true});sync();}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();

/* Cart photographs follow the server-confirmed native image option. */
(function () {
  'use strict';
  const originals = new WeakMap(), failedImages = new WeakMap();
  let latest = null, queued = false;
  function selectedImage(options) {
    const groups = (Array.isArray(options) ? options : []).filter(option => ['thumbnail', 'image'].includes(option.type));
    if (groups.length !== 1) return null;
    const selected = (groups[0].details || []).filter(detail => detail.is_selected === true);
    if (selected.length !== 1 || !selected[0].image) return null;
    try {
      const url = new URL(selected[0].image);
      if (url.protocol !== 'https:' || !['cdn.files.salla.network', 'cdn.salla.sa'].includes(url.hostname)) return null;
      return { src: url.href, name: String(selected[0].name || '') };
    } catch (_) { return null; }
  }
  function paint() {
    queued = false;
    if (!document.body.classList.contains('cart')) return;
    const items = latest?.nativeCart?.items;
    document.querySelectorAll('.cart-item').forEach(card => {
      const itemId = (card.getAttribute('data-testid') || card.id || '').match(/^store-cart-item-(\d+)$/)?.[1];
      const host = card.querySelector('salla-product-options');
      const raw = Array.isArray(items) ? items.find(item => String(item.id) === itemId) : null;
      let options = raw?.options;
      if (!Array.isArray(items) && host) {
        try { options = JSON.parse(host.getAttribute('options') || '[]'); } catch (_) { return; }
      }
      const choice = selectedImage(options);
      const image = card.querySelector('a img');
      if (!choice || !image || failedImages.get(image) === choice.src) return;
      if (!originals.has(image)) originals.set(image, { src: image.getAttribute('src'), alt: image.alt });
      if (image.getAttribute('src') !== choice.src) image.setAttribute('src', choice.src);
      image.removeAttribute('srcset');
      if (image.alt !== choice.name) image.alt = choice.name;
      if (!image.dataset.amChoiceFallback) {
        image.dataset.amChoiceFallback = 'true';
        image.addEventListener('error', () => {
          const original = originals.get(image);
          failedImages.set(image, image.getAttribute('src'));
          if (original?.src && image.getAttribute('src') !== original.src) image.src = original.src;
        });
      }
    });
  }
  function schedule() {
    if (queued) return;
    queued = true;
    requestAnimationFrame(paint);
  }
  document.addEventListener('am:installation-state', event => { latest = event.detail; schedule(); });
  function start() {
    if (!document.body.classList.contains('cart')) return;
    new MutationObserver(schedule).observe(document.getElementById('main-content') || document.body, {
      childList: true, subtree: true, attributes: true, attributeFilter: ['options', 'src']
    });
    schedule();
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });
  else start();
})();


/* Presentation follows the installation controller's native cart readback. */
(function () {
  'use strict';
  const serviceIds = new Set(['696086226','519614875','373446428','1026510677','1689064447']);
  const number = new Intl.NumberFormat('ar-SA', { maximumFractionDigits: 2 });
  let state = null, frame = 0;
  function text(node, value) { if (node && node.textContent !== value) node.textContent = value; }
  function setMoney(node, value) {
    if (!node || typeof value !== 'number' || !Number.isFinite(value) || value < 0) return;
    const valueNode = Array.from(node.childNodes).find(child => child.nodeType === Node.TEXT_NODE && /[0-9٠-٩]/.test(child.nodeValue));
    const formatted = number.format(value) + ' ';
    if (valueNode && valueNode.nodeValue !== formatted) valueNode.nodeValue = formatted;
  }
  let confirmedHeader = null;
  function renderHeader() {
    if (!confirmedHeader) return;
    const host = document.querySelector('.am-header-actions salla-cart-summary');
    const badge = host?.querySelector('.s-cart-summary-count:not([data-am-value])');
    const amount = host?.querySelector('.s-cart-summary-total:not([data-am-value])');
    if (!badge || !amount) return;
    function view(source, type) {
      let output = source.parentElement.querySelector('[data-am-value="'+type+'"]');
      if (!output) {
        output = source.cloneNode(true);
        output.removeAttribute('id');
        output.style.removeProperty('display');
        output.classList.remove('am-native-pair-value');
        output.removeAttribute('aria-hidden');
        output.dataset.amValue = type;
        source.after(output);
      }
      if (source.style.display !== 'none') source.style.setProperty('display','none','important');
      if (source.getAttribute('aria-hidden') !== 'true') source.setAttribute('aria-hidden','true');
      if (!source.classList.contains('am-native-pair-value')) source.classList.add('am-native-pair-value');
      return output;
    }
    text(view(badge,'count'),number.format(confirmedHeader.count));
    const out = view(amount,'total');
    let value = out.querySelector('[data-am-confirmed-price]');
    if (!value) {
      const symbol = out.querySelector('i') || document.createElement('i');
      symbol.classList.add('sicon-sar');
      value = document.createElement('span');
      value.dataset.amConfirmedPrice = '';
      out.replaceChildren(value, symbol);
    }
    text(value, number.format(confirmedHeader.total) + ' ');
  }
  function bindHeader() {
    if (!document.body?.classList.contains('cart') || !window.salla?.event?.on) return;
    const header = document.querySelector('header.store-header');
    if (!header || header.dataset.amPairedTotals) return;
    header.dataset.amPairedTotals = '1';
    const style = document.createElement('style');
    style.textContent = 'header .am-native-pair-value:not([data-am-value]){clip-path:inset(100%)!important;position:absolute!important;pointer-events:none!important}';
    document.head.append(style);
    new MutationObserver(() => {
      if (confirmedHeader && (!header.querySelector('[data-am-value="total"]') || !header.querySelector('[data-am-value="count"]'))) renderHeader();
    }).observe(header,{subtree:true,childList:true});
    function accept(cart) {
      if (!Array.isArray(cart?.items) || !Number.isFinite(cart.total)) return;
      const count = cart.items.reduce((n,item) => n + (serviceIds.has(String(item.product_id ?? item.product?.id)) ? 0 : Number(item.quantity)),0);
      if (!Number.isSafeInteger(count) || count < 0) return;
      confirmedHeader = {count,total:cart.total};
      renderHeader();
    }
    salla.event.on('cart::updated', accept);
    function seed() {
      if (confirmedHeader) return;
      const read = selector => {
        const el = header.querySelector(selector);
        if (!el || !/[0-9٠-٩]/.test(el.textContent)) return NaN;
        return Number(el.textContent.trim().replace(/[٠-٩]/g,ch=>String(ch.charCodeAt(0)-1632)).replace(/[,٬]/g,'').replace('٫','.'));
      };
      const count = read('.s-cart-summary-count'), total = read('.s-cart-summary-total');
      if (Number.isSafeInteger(count) && Number.isFinite(total)) { confirmedHeader = {count,total}; renderHeader(); }
    }
    document.addEventListener('pointerdown',seed,{capture:true,passive:true});
    document.addEventListener('keydown',seed,true);
    document.addEventListener('am:installation-state', e => { if (!confirmedHeader && !e.detail?.pending) accept(e.detail?.nativeCart); });
  }
  document.addEventListener('theme::ready',bindHeader,{once:true});
  document.addEventListener('DOMContentLoaded',bindHeader,{once:true});
  if (window.salla?.onReady) salla.onReady(bindHeader);
  bindHeader();
  const installStyle = '@media(min-width:768px){.am-install-card{display:grid!important;grid-template-columns:minmax(0,1fr) auto!important;gap:8px 12px!important;padding:12px!important;margin:16px 0 0!important;border-radius:11px!important;box-shadow:none!important;background:#f9fcff!important}.am-install-card-header{grid-column:1/-1!important}.am-install-card-select{grid-column:1/-1!important;grid-row:2!important;min-height:46px!important;height:46px!important;margin:0!important;padding:8px 10px!important;font-size:15px!important}.am-install-card-address{grid-column:2!important;grid-row:2!important;min-height:46px!important;margin:0!important;padding:8px 14px!important}.am-install-card-note,.am-install-card-total,.am-install-card-status{grid-column:1/-1!important;margin:0!important;line-height:1.7!important;font-size:12px!important}}';
  function paint() {
    frame = 0;
    document.querySelectorAll('salla-add-product-toast').forEach(toast => {
      const id = toast.querySelector('.s-add-product-toast__name')?.getAttribute('href')?.match(/\/p(\d+)(?:[/?#]|$)/)?.[1];
      toast.classList.toggle('am-internal-service-toast', serviceIds.has(id));
    });
    if (!document.body.classList.contains('cart')) return;
    document.querySelectorAll('.am-install-card-host').forEach(host => {
      if (host.shadowRoot && !host.shadowRoot.querySelector('[data-am-desktop-install]')) {
        const style = document.createElement('style'); style.dataset.amDesktopInstall = 'true'; style.textContent = installStyle; host.shadowRoot.append(style);
      }
    });
    const status = document.getElementById('am-per-card-installation-state');
    if (status && state) status.classList.toggle('am-cart-status-critical', !!state.error || (!state.pending && !!state.blocked));
    if (!Array.isArray(state?.nativeCart?.items)) return;
    const items = state.nativeCart.items;
    const count = items.filter(item => !serviceIds.has(String(item.product_id ?? item.product?.id))).reduce((sum,item) => sum + (Number.isSafeInteger(Number(item.quantity)) && Number(item.quantity) > 0 ? Number(item.quantity) : 0), 0);
    const label = count === 0 ? '(لا توجد منتجات)' : count === 1 ? '(منتج واحد)' : count === 2 ? '(منتجان)' : '(' + number.format(count) + (count <= 10 ? ' منتجات)' : ' منتجًا)');
    document.querySelectorAll('.s-cart-summary-card-bar-count').forEach(node => text(node,label));
    if (!confirmedHeader) document.querySelectorAll('header .s-cart-summary-count').forEach(node => text(node,number.format(count)));
    if (!state.pending && !state.error) {
      document.querySelectorAll(confirmedHeader ? '.s-cart-summary-card-bar-total' : 'header .s-cart-summary-total,.s-cart-summary-card-bar-total').forEach(node => setMoney(node,state.nativeCart.total));
    }
  }
  function schedule() { if (!frame) frame = requestAnimationFrame(paint); }
  document.addEventListener('am:installation-state', event => { state = event.detail; schedule(); });
  function start() {
    new MutationObserver(records => {
      if (records.some(record => record.type === 'childList' || record.type === 'characterData' || record.attributeName === 'href')) schedule();
    }).observe(document.body,{childList:true,subtree:true,characterData:true,attributes:true,attributeFilter:['href']});
    schedule();
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded',start,{once:true}); else start();
})();


/* Keep the non-cart header badge consistent with physical products in the cart. */
(function () {
  'use strict';
  const serviceIds = new Set(['696086226','519614875','373446428','1026510677','1689064447']);
  const number = new Intl.NumberFormat('ar-SA');
  let items = null, timer = 0, frame = 0, busy = false, again = false, bound = false, disposed = false;
  let sdk = null, signature = '', revision = 0, initialRead = false;
  const subscriptions = [];
  const digits = value => Number(String(value || '').replace(/[٠-٩]/g,char => String(char.charCodeAt(0)-1632)).replace(/[٬,]/g,'').replace('٫','.').replace(/[^0-9.]/g,''));
  function paint() {
    frame = 0;
    if (disposed || document.body.classList.contains('cart') || !Array.isArray(items)) return;
    const count = items.filter(item => !serviceIds.has(String(item.product_id ?? item.product?.id))).reduce((sum,item) => sum + (Number.isSafeInteger(Number(item.quantity)) && Number(item.quantity) > 0 ? Number(item.quantity) : 0),0);
    document.querySelectorAll('header .s-cart-summary-count').forEach(node => {
      const value = number.format(count); if (node.textContent !== value) node.textContent = value;
    });
  }
  function schedulePaint() {
    if (bound && !initialRead && !disposed && digits(document.querySelector('header .s-cart-summary-count')?.textContent) > 0) {
      initialRead = true;
      signature = digits(document.querySelector('header .s-cart-summary-count')?.textContent) + '|' + digits(document.querySelector('header .s-cart-summary-total')?.textContent);
      queueRead();
    }
    if (!frame && !disposed) frame = requestAnimationFrame(paint);
  }
  function accept(response) {
    const data = response?.data?.data || response?.data || response;
    const cart = data?.cart || data;
    if (Array.isArray(cart?.items)) { items = cart.items; schedulePaint(); }
  }
  async function read() {
    timer = 0;
    if (disposed) return;
    if (busy) { again = true; return; }
    busy = true;
    const requestedRevision = revision;
    try {
      const response = await sdk.cart.details();
      if (requestedRevision === revision) accept(response); else again = true;
    } catch (_) { /* Preserve the native badge when a cart cannot be read. */ }
    finally { busy = false; if (again && !disposed) { again = false; queueRead(); } }
  }
  function queueRead() { clearTimeout(timer); if (!disposed) timer = setTimeout(read,350); }
  function updated(summary) {
    const next = String(summary?.count) + '|' + String(summary?.total);
    if (next === signature) return;
    signature = next; items = null; revision++;
    if (Number(summary?.count) === 0) { items = []; schedulePaint(); }
    else queueRead();
  }
  function changed() { items = null; revision++; queueRead(); }
  const observer = new MutationObserver(schedulePaint);
  function bind() {
    if (bound || disposed || document.body.classList.contains('cart')) return;
    sdk = window.salla;
    if (!sdk?.cart?.details || !sdk?.event?.on) return;
    bound = true;
    [['cart::updated',updated],['cart::item.added',changed],['cart::item.updated',changed],['cart::item.deleted',changed]].forEach(([name,handler]) => {
      sdk.event.on(name,handler); subscriptions.push([name,handler]);
    });
    signature = digits(document.querySelector('header .s-cart-summary-count')?.textContent) + '|' + digits(document.querySelector('header .s-cart-summary-total')?.textContent);
    if (digits(document.querySelector('header .s-cart-summary-count')?.textContent) > 0) { initialRead = true; queueRead(); }
  }
  function start() {
    if (document.body.classList.contains('cart')) return;
    disposed = false;
    const header = document.querySelector('header.store-header');
    if (header) observer.observe(header,{childList:true,subtree:true,characterData:true});
    if (window.salla?.onReady) window.salla.onReady(bind); else bind();
    document.addEventListener('theme::ready',bind,{once:true});
  }
  window.addEventListener('pagehide',() => {
    disposed = true; clearTimeout(timer); if (frame) cancelAnimationFrame(frame); frame = 0;
    observer.disconnect(); subscriptions.splice(0).forEach(([name,handler]) => sdk?.event?.off?.(name,handler)); bound = false;
  });
  window.addEventListener('pageshow',event => { if (event.persisted) start(); });
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded',start,{once:true}); else start();
})();


/* Keep the new layout consistent for returning browsers with a cached native stylesheet. */
(function(){let style=document.getElementById("am-final-polish-css");if(!style){style=document.createElement("style");style.id="am-final-polish-css";document.head.append(style);}style.textContent="/* Shared layout stability and restrained motion. */\nhtml { scrollbar-gutter: stable; }\nbody.theme-raed.cart { background-image: none !important; background-color: #edf8fc !important; }\nbody.cart #main-content { min-width: 0; }\nbody.cart .am07-cart-intro,\nbody.cart #main-content > .container > h1.sr-only::after,\nbody.cart .am-install-summary-count-note,\nbody.cart #am-per-card-installation-state,\nsalla-add-product-toast.am-internal-service-toast { display: none !important; }\nbody.cart #am-per-card-installation-state.am-cart-status-critical { display: flex !important; }\nbody.cart .cart-item { border-color: #d5e5ef !important; box-shadow: 0 4px 18px #082b5907 !important; }\nbody.cart .am-cart-address-summary { background: #f5faff !important; }\nbody.cart #am-per-card-installation-state { border-radius: 10px; font-size: 13px; line-height: 1.7; }\nbody.cart .s-cart-summary-card-bar-count { white-space: normal; }\nbody.cart .s-cart-summary-card-action button { min-height: 48px; border-radius: 10px; }\n.s-product-card-entry, .am-hub-card { transition: border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease; }\n@media (hover:hover) and (pointer:fine) {\n  .s-product-card-entry:hover { border-color: #9dbdeb; box-shadow: 0 8px 22px #082b5910; }\n  .am-hub-card:hover { transform: translateY(-2px); }\n}\n@media (min-width:768px) {\n  body.index #main-content > section[component-id=\"935235511\"] { grid-row: 3 !important; }\n  body.index #main-content > section[component-id=\"652080513\"] { grid-row: 4 !important; }\n  body.index #main-content > section[component-id=\"2031253909\"] { grid-row: 5 !important; }\n  body.index #main-content > section[component-id=\"25939608\"] { grid-row: 6 !important; }\n  body.index #main-content > section[component-id=\"1204252081\"] { grid-row: 7 !important; order: 7 !important; }\n  body.cart header.store-header .top-navbar { display: none !important; }\n  body.cart header.store-header #mainnav,\n  body.cart header.store-header #mainnav .inner { height: 66px !important; min-height: 66px !important; }\n  body.cart header.store-header #mainnav .container { padding-block: 0 !important; }\n  body.cart header.store-header .navbar-brand { display: flex !important; align-items: center; padding: 0 !important; max-width: 116px; }\n  body.cart header.store-header .navbar-brand img { width: auto !important; height: 46px !important; max-height: 46px !important; object-fit: contain; }\n  body.cart .header-btn { flex-shrink: 0; min-height: 44px; }\n  body.cart #main-content > .container { width: calc(100% - 48px) !important; max-width: 1200px !important; padding-inline: 0 !important; margin-inline: auto !important; }\n  body.cart .am-cart-address-summary { width: calc(100% - 48px); max-width: 1200px; margin: 14px auto 10px !important; padding: 10px 14px !important; }\n  body.cart #main-content .breadcrumbs { display: none !important; }\n  body.cart #main-content > .container > h1.sr-only { position: static !important; width: auto !important; height: auto !important; clip: auto !important; overflow: visible !important; white-space: normal !important; padding: 0 !important; margin: 12px 0 16px !important; font-size: 26px !important; line-height: 1.5 !important; }\n  body.cart #main-content > .container > .pt-5 { padding-top: 0 !important; gap: 22px; }\n  body.cart .cart-item { padding: 20px !important; margin-bottom: 16px !important; border-radius: 15px !important; }\n  body.cart .cart-item > div:first-of-type { display: grid !important; grid-template-columns: minmax(0,1fr) 148px; gap: 18px; align-items: start; margin: 0 !important; }\n  body.cart .cart-item > div:first-of-type > div:first-child { display: grid !important; grid-template-columns: 148px minmax(0,1fr); gap: 16px; min-width: 0; padding: 0 !important; }\n  body.cart .cart-item > div:first-of-type > div:first-child > * { min-width: 0; margin: 0 !important; }\n  body.cart .cart-item > div:first-of-type > div:first-child > a { width: 148px !important; height: 148px !important; border-radius: 10px; }\n  body.cart .cart-item > div:first-of-type > div:first-child > a > img { width: 148px !important; height: 148px !important; object-fit: contain !important; padding: 0 !important; border: 0 !important; background: white !important; }\n  body.cart .cart-item > div:first-of-type > div:nth-child(2) { display: flex !important; flex-direction: column !important; align-items: flex-end !important; gap: 12px !important; min-width: 0; margin: 0 !important; padding: 0 !important; border: 0 !important; }\n  body.cart .cart-item > div:first-of-type > div:nth-child(2) > p { padding: 0 !important; margin: 0 !important; text-align: left; }\n  body.cart .cart-item h1, body.cart .cart-item h1 a { font-size: 17px !important; line-height: 1.65 !important; overflow-wrap: anywhere; }\n  body.cart .cart-item .item-price { font-size: 20px !important; line-height: 1.6; font-weight: 800; }\n  body.cart .cart-item .item-weight-row { display: none !important; }\n  body.cart .cart-item .s-quantity-input-container { height: 44px !important; }\n  body.cart .cart-item .s-quantity-input-button { min-width: 44px !important; min-height: 44px !important; }\n  body.cart .cart-item .s-quantity-input-input { height: 44px !important; min-width: 42px; font-size: 16px !important; }\n  body.cart .cart-item salla-product-options { display: block; margin-top: 16px; min-width: 0; }\n  body.cart .am-cart-image-toggle { min-height: 46px !important; font-size: 15px !important; }\n  body.cart .s-cart-summary-card { border: 1px solid #d5e5ef; border-radius: 15px; box-shadow: 0 5px 22px #082b5908; }\n  body.cart .s-cart-summary-card-sheet-header { padding-bottom: 12px; }\n  body.cart .s-cart-summary-card-sheet-title { font-size: 21px; }\n  body.cart .s-cart-summary-card-line { gap: 12px; line-height: 1.7; }\n  body.cart .s-cart-summary-card-bar { padding-block: 16px !important; }\n}\n@media (min-width:1024px) {\n  body.cart #main-content > .container > .pt-5 { display: grid !important; grid-template-columns: minmax(0,1fr) 304px; align-items: start; }\n  body.cart #main-content > .container > .pt-5 > .main-content { grid-column: 1; grid-row: 1; width: auto !important; min-width: 0; }\n  body.cart #main-content > .container > .pt-5 > .sticky { grid-column: 2; grid-row: 1; width: auto !important; margin: 0 !important; top: 84px; }\n  body.cart #main-content > .container > .pt-5 > salla-hook { grid-column: 1/-1; }\n}\n@media (min-width:768px) and (max-width:1100px) {\n  body.cart .cart-item > div:first-of-type { grid-template-columns: minmax(0,1fr); }\n  body.cart .cart-item > div:first-of-type > div:nth-child(2) { flex-direction: row !important; justify-content: space-between; align-items: center !important; }\n}\n@media (prefers-reduced-motion:reduce) {\n  html { scroll-behavior: auto !important; }\n  .s-product-card-entry, .am-hub-card, .cart-item, .am-cart-image-toggle, .am-cart-image-toggle::after { animation: none !important; transition: none !important; transform: none !important; }\n}\n";})();

/* Footer branches map — owner-approved 2026-11-23 */
;(()=>{if(document.getElementById("am-footer-map-css"))return;const s=document.createElement("style");s.id="am-footer-map-css";s.textContent="/* Almoalej footer map. Append after the existing store CSS. */\n.am-footer-layout{display:grid!important;grid-template-columns:minmax(0,1fr) minmax(290px,350px)!important;align-items:start;gap:clamp(24px,4vw,56px);direction:rtl}\n.am-footer-original{min-width:0}.am-footer-original>.grid{width:100%}\n.am-footer-branches{box-sizing:border-box;min-width:0;width:100%;max-width:350px;justify-self:end;direction:rtl;background:#fff!important;color:#071b4d!important;border:1px solid #d4e0ec;border-radius:18px;padding:20px;box-shadow:0 12px 36px #00000012;font-family:inherit;font-size:13px;line-height:1.7}\n.am-footer-branches *{box-sizing:border-box}.am-footer-branches a{display:inline;color:#071b4d!important;text-decoration:none}.am-footer-branches a:hover{text-decoration:underline!important}.am-footer-branches a:focus-visible,.am-footer-map-hours summary:focus-visible{outline:2px solid #0756ad;outline-offset:3px;border-radius:5px}\n.am-footer-map-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.am-footer-map-heading h3{color:#071b4d!important;font-size:18px!important;line-height:1.4;margin:0!important}.am-footer-map-heading>span{font-size:11px;color:#456485}\n.am-footer-branches .am-footer-map-intro{color:#456485!important;font-size:12px;margin:8px 0 0}.am-footer-picker{position:relative;min-width:0;border:0;padding:0;margin:0}\n.am-map-sr-only,.am-footer-choice{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}\n.am-footer-map-canvas{position:relative;aspect-ratio:600/470;width:100%;margin:8px 0}.am-footer-outline{width:100%;height:100%;display:block}\n.am-footer-pin{position:absolute;transform:translate(-50%,-50%);width:58px;min-height:44px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:0;padding:3px;border-radius:9px;color:#071b4d;font-size:11px;font-weight:700;line-height:1.2;cursor:pointer;transition:background .18s,color .18s}\n.am-footer-pin svg{width:19px;height:24px;fill:#071b4d;flex-shrink:0}.am-footer-pin:hover{background:#eaf5fc}.am-footer-branch-panel{display:none;min-height:138px;background:#f3f7fb;border:1px solid #d8e4ef;border-radius:12px;padding:14px}\n.am-footer-branch-heading{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}.am-footer-branch-heading>a{font-size:15px;font-weight:700}.am-footer-branch-heading bdi{font-size:12px;font-variant-numeric:tabular-nums}\n.am-footer-branches .am-footer-branch-panel p{font-size:12px;color:#456485!important;margin:8px 0 6px;min-height:2em;line-height:1.6}\n.am-footer-map-actions{display:flex;align-items:center;gap:8px}.am-footer-map-actions>a{min-width:44px;min-height:44px;display:inline-flex;align-items:center;justify-content:center}.am-footer-map-actions svg{width:23px;height:23px}.am-footer-map-actions .am-footer-whatsapp{color:#168b50!important}.am-footer-map-actions .am-footer-map-open{margin-inline-start:auto;font-size:12px;gap:6px}\n.am-footer-map-hours{border-top:1px solid #d8e4ef;margin-top:16px;padding-top:4px}.am-footer-map-hours summary{cursor:pointer;min-height:44px;padding:10px 0;font-weight:700;font-size:12px}.am-footer-map-hours dl{margin:0}.am-footer-map-hours dl>div{display:flex;justify-content:space-between;gap:10px;padding:8px 0;border-top:1px solid #e0e9f2}.am-footer-map-hours dt,.am-footer-map-hours dd{font-size:11px;margin:0}.am-footer-map-hours dd{color:#456485}\n.am-footer-branches .am-footer-map-credit{font-size:10px;color:#667b92!important;line-height:1.8;margin:12px 0 0}.am-footer-map-credit a{text-decoration:underline!important;color:#456485!important}\n#am-footer-branch-0:checked~.am-footer-branch-panels [data-branch=\"0\"]{display:block}#am-footer-branch-0:checked~.am-footer-map-canvas label[for=\"am-footer-branch-0\"]{background:#eaf5fc;box-shadow:0 0 0 1px #bdd5e9}#am-footer-branch-0:focus-visible~.am-footer-map-canvas label[for=\"am-footer-branch-0\"]{outline:2px solid #0756ad;outline-offset:3px}\n#am-footer-branch-1:checked~.am-footer-branch-panels [data-branch=\"1\"]{display:block}#am-footer-branch-1:checked~.am-footer-map-canvas label[for=\"am-footer-branch-1\"]{background:#eaf5fc;box-shadow:0 0 0 1px #bdd5e9}#am-footer-branch-1:focus-visible~.am-footer-map-canvas label[for=\"am-footer-branch-1\"]{outline:2px solid #0756ad;outline-offset:3px}\n#am-footer-branch-2:checked~.am-footer-branch-panels [data-branch=\"2\"]{display:block}#am-footer-branch-2:checked~.am-footer-map-canvas label[for=\"am-footer-branch-2\"]{background:#eaf5fc;box-shadow:0 0 0 1px #bdd5e9}#am-footer-branch-2:focus-visible~.am-footer-map-canvas label[for=\"am-footer-branch-2\"]{outline:2px solid #0756ad;outline-offset:3px}\n#am-footer-branch-3:checked~.am-footer-branch-panels [data-branch=\"3\"]{display:block}#am-footer-branch-3:checked~.am-footer-map-canvas label[for=\"am-footer-branch-3\"]{background:#eaf5fc;box-shadow:0 0 0 1px #bdd5e9}#am-footer-branch-3:focus-visible~.am-footer-map-canvas label[for=\"am-footer-branch-3\"]{outline:2px solid #0756ad;outline-offset:3px}\n#am-footer-branch-4:checked~.am-footer-branch-panels [data-branch=\"4\"]{display:block}#am-footer-branch-4:checked~.am-footer-map-canvas label[for=\"am-footer-branch-4\"]{background:#eaf5fc;box-shadow:0 0 0 1px #bdd5e9}#am-footer-branch-4:focus-visible~.am-footer-map-canvas label[for=\"am-footer-branch-4\"]{outline:2px solid #0756ad;outline-offset:3px}\n@media(max-width:1023px){.am-footer-layout{grid-template-columns:minmax(0,1fr)!important}.am-footer-branches{justify-self:start;max-width:350px}}\n@media(max-width:479px){.am-footer-branches{max-width:100%;padding:16px}.am-footer-pin{font-size:10px}.am-footer-branch-heading{gap:3px}}\n@media(prefers-reduced-motion:reduce){.am-footer-pin{transition:none}}\n\n/* Preserve the native footer columns after grouping them beside the map. */\n.am-footer-original{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:24px;align-items:start}.am-footer-original>:first-child{grid-column:span 2;padding-inline:0!important}.am-footer-original>.am-policy-footer-links{grid-column:1/-1}\n@media(max-width:1199px){.am-footer-original{grid-template-columns:repeat(2,minmax(0,1fr))}}\n@media(max-width:639px){.am-footer-original{grid-template-columns:minmax(0,1fr)}.am-footer-original>:first-child{grid-column:auto}}\n";document.head.append(s);})();
/* Almoalej footer map; vanilla JS. Save in the draft custom-JavaScript field. */
(()=>{'use strict';if(window.almoalejFooterMap)return;const markup="<aside class=\"am-footer-branches\" dir=\"rtl\" aria-labelledby=\"am-footer-branches-title\"><div class=\"am-footer-map-heading\"><h3 id=\"am-footer-branches-title\">فروع المعالج</h3><span>5 فروع</span></div><p class=\"am-footer-map-intro\">اختر الفرع للتواصل أو عرض موقعه.</p><fieldset class=\"am-footer-picker\"><legend class=\"am-map-sr-only\">اختر الفرع</legend><input class=\"am-footer-choice\" type=\"radio\" id=\"am-footer-branch-0\" name=\"am-footer-branch\" value=\"الهفوف\" checked aria-label=\"فرع الهفوف\"><input class=\"am-footer-choice\" type=\"radio\" id=\"am-footer-branch-1\" name=\"am-footer-branch\" value=\"المبرز\" aria-label=\"فرع المبرز\"><input class=\"am-footer-choice\" type=\"radio\" id=\"am-footer-branch-2\" name=\"am-footer-branch\" value=\"الرياض\" aria-label=\"فرع الرياض\"><input class=\"am-footer-choice\" type=\"radio\" id=\"am-footer-branch-3\" name=\"am-footer-branch\" value=\"تبوك\" aria-label=\"فرع تبوك\"><input class=\"am-footer-choice\" type=\"radio\" id=\"am-footer-branch-4\" name=\"am-footer-branch\" value=\"الدمام\" aria-label=\"فرع الدمام\"><div class=\"am-footer-map-canvas\"><svg class=\"am-footer-outline\" viewBox=\"0 0 600 470\" aria-hidden=\"true\"><path d=\"M221.6,418.6L220.8,419.2L221.5,419.9L221.6,418.6ZM215.6,413.0L216.0,415.0L218.1,416.9L220.3,418.2L223.0,417.8L222.4,419.1L224.9,420.1L224.9,417.3L224.3,417.7L224.7,417.0L222.7,414.7L221.5,416.3L222.6,417.0L221.5,417.3L218.6,416.2L217.7,414.1L215.6,413.0ZM219.2,411.5L217.4,413.0L220.8,416.3L219.2,414.2L220.6,413.5L219.2,411.5ZM214.1,411.4L214.0,413.0L215.0,412.1L214.1,411.4ZM115.7,223.4L115.1,223.8L116.1,224.0L115.7,223.4ZM103.1,207.3L102.9,208.2L103.9,208.2L103.1,207.3ZM64.2,153.4L63.4,154.2L65.2,154.4L64.2,153.4ZM60.5,152.1L60.2,153.7L62.7,154.3L60.2,152.9L61.2,152.6L60.5,152.1ZM283.3,124.7L279.1,124.3L222.7,79.5L208.8,73.3L186.8,59.8L160.8,55.0L156.7,58.6L113.7,70.3L135.1,93.8L127.9,97.7L124.5,105.5L108.4,108.6L103.1,117.3L93.8,124.7L69.9,120.6L66.0,136.9L66.7,140.2L63.5,148.6L61.6,150.2L62.8,151.9L64.6,149.2L65.2,151.0L66.8,149.8L66.5,150.8L67.6,149.8L67.6,150.8L71.6,150.4L71.1,149.6L75.6,151.3L74.4,152.4L80.0,157.7L83.5,165.7L88.1,170.6L88.0,173.2L93.0,178.1L94.4,182.0L97.5,185.0L102.9,196.6L107.4,198.6L106.1,202.8L108.2,205.5L109.4,206.2L109.9,205.2L112.4,207.6L116.1,215.5L118.8,218.3L119.4,225.9L118.5,227.2L117.0,226.9L118.6,227.7L118.4,229.7L121.0,231.4L123.6,236.0L122.8,237.6L126.0,240.5L128.5,239.2L132.1,242.7L133.6,242.8L133.2,241.6L134.1,241.3L133.7,242.4L134.9,242.6L133.7,242.9L145.0,251.4L146.8,257.1L147.9,257.3L147.0,256.5L148.1,256.3L149.8,262.7L151.9,265.1L152.2,269.5L154.8,270.7L156.0,272.9L154.9,273.2L153.3,271.2L156.8,275.3L156.3,276.1L158.7,280.8L158.6,284.7L159.6,283.6L157.4,288.4L156.9,290.9L157.7,289.3L157.7,291.7L156.9,291.7L156.7,293.5L155.8,293.5L156.4,292.3L155.0,292.9L158.3,300.0L160.2,298.4L158.4,300.1L158.9,304.1L160.5,305.1L159.7,305.5L160.3,307.8L158.7,309.0L160.6,314.2L164.3,319.7L166.3,320.8L165.6,320.9L166.3,322.6L167.0,323.0L166.4,321.6L172.2,330.9L176.8,334.0L175.8,333.0L180.4,333.7L184.1,337.7L189.5,340.9L189.5,342.3L191.9,345.6L193.8,344.8L195.0,346.3L194.6,349.2L198.6,351.9L198.4,355.3L200.4,357.4L201.0,360.7L202.8,361.4L202.2,364.6L202.8,366.3L204.6,367.0L203.8,370.2L204.9,372.6L208.4,374.9L210.4,380.6L209.9,381.5L210.7,381.4L213.1,387.0L213.7,386.6L216.0,390.8L218.5,391.5L227.6,400.1L228.8,410.1L228.5,406.0L229.9,406.7L230.5,409.1L232.7,410.4L232.1,413.2L236.0,416.7L237.0,424.2L241.1,424.5L241.2,422.2L244.7,421.4L245.3,418.0L247.3,418.6L246.8,417.2L248.0,415.3L245.2,412.5L246.4,411.7L246.1,409.7L247.6,410.1L245.6,407.8L246.6,404.3L249.5,403.3L247.1,400.5L249.9,397.4L252.6,397.7L256.9,401.8L260.1,402.5L263.0,402.7L263.9,401.0L266.1,401.9L266.6,400.9L272.0,400.2L289.8,400.2L293.7,402.6L308.7,404.6L314.4,405.0L322.6,403.8L328.0,411.6L331.9,411.6L338.0,407.7L340.8,399.9L353.3,383.1L373.3,372.5L409.0,368.6L435.1,363.5L499.4,340.1L513.7,293.2L503.9,276.5L502.3,278.4L447.5,271.1L426.3,243.3L426.3,240.3L423.1,238.6L419.7,239.6L420.6,236.2L424.5,232.8L422.3,231.6L420.3,234.4L415.8,235.2L412.1,233.4L409.6,228.8L408.7,229.4L407.8,225.8L404.7,221.2L404.3,221.8L402.8,213.4L400.4,210.8L400.8,213.2L396.7,206.8L395.6,206.5L395.2,205.4L397.9,208.4L394.6,202.1L394.5,199.7L393.0,198.8L392.3,199.6L392.9,194.6L395.6,198.4L397.3,190.7L395.9,189.3L396.5,187.1L395.7,189.4L395.1,187.7L394.5,188.6L393.1,187.7L392.7,186.0L394.1,186.7L394.2,186.0L392.7,186.0L392.1,181.9L393.1,183.6L394.9,183.3L395.8,184.4L391.3,179.4L385.2,176.4L385.8,175.2L384.0,174.6L386.2,173.8L383.3,173.7L384.3,169.2L382.7,172.1L381.3,168.8L382.1,168.0L382.9,169.3L385.9,168.8L381.2,167.8L380.6,169.3L381.2,168.9L380.8,170.4L382.2,171.3L381.4,172.1L382.0,173.1L380.1,172.5L380.3,174.0L378.7,173.1L379.7,171.3L378.3,172.6L377.7,171.6L377.6,168.2L375.5,168.6L376.2,166.3L375.2,167.1L373.4,166.4L377.1,165.1L377.5,165.9L376.3,163.6L371.7,162.7L370.2,161.3L368.8,162.6L369.0,161.2L367.6,161.7L368.3,160.1L367.5,160.5L366.9,158.5L366.2,159.2L366.8,156.7L366.7,158.3L367.4,156.8L368.0,157.3L367.5,159.0L368.5,156.7L365.4,153.6L366.4,152.5L362.7,150.4L363.0,147.9L360.4,144.7L361.0,142.8L359.4,143.5L360.7,142.6L360.1,140.8L358.6,139.9L343.1,140.1L340.9,137.1L340.5,132.8L337.9,129.0L318.6,126.6L315.7,127.5L283.3,124.7Z\" fill=\"#eaf5fc\" stroke=\"#a6c3db\" stroke-width=\"1.3\"/><path d=\"M383.6,215 Q480,215 480,335\" fill=\"none\" stroke=\"#7795b5\" stroke-width=\"1\"/><circle cx=\"383.6\" cy=\"215\" r=\"4\" fill=\"#071b4d\"/><path d=\"M383.2,212.9 Q480,212.9 480,235\" fill=\"none\" stroke=\"#7795b5\" stroke-width=\"1\"/><circle cx=\"383.2\" cy=\"212.9\" r=\"4\" fill=\"#071b4d\"/><path d=\"M324.6,229.3 Q283,229.3 283,285\" fill=\"none\" stroke=\"#7795b5\" stroke-width=\"1\"/><circle cx=\"324.6\" cy=\"229.3\" r=\"4\" fill=\"#071b4d\"/><path d=\"M104.2,143 Q108,143 108,95\" fill=\"none\" stroke=\"#7795b5\" stroke-width=\"1\"/><circle cx=\"104.2\" cy=\"143\" r=\"4\" fill=\"#071b4d\"/><path d=\"M394.4,189.5 Q480,189.5 480,135\" fill=\"none\" stroke=\"#7795b5\" stroke-width=\"1\"/><circle cx=\"394.4\" cy=\"189.5\" r=\"4\" fill=\"#071b4d\"/></svg><label class=\"am-footer-pin\" for=\"am-footer-branch-0\" style=\"left:80%;top:71.27659574468085%\"><svg viewBox=\"0 0 24 30\" aria-hidden=\"true\"><path d=\"M12 29C9 24 1 18 1 11a11 11 0 0 1 22 0c0 7-8 13-11 18Z\"/><circle cx=\"12\" cy=\"11\" r=\"4\" fill=\"white\"/></svg><span>الهفوف</span></label><label class=\"am-footer-pin\" for=\"am-footer-branch-1\" style=\"left:80%;top:50%\"><svg viewBox=\"0 0 24 30\" aria-hidden=\"true\"><path d=\"M12 29C9 24 1 18 1 11a11 11 0 0 1 22 0c0 7-8 13-11 18Z\"/><circle cx=\"12\" cy=\"11\" r=\"4\" fill=\"white\"/></svg><span>المبرز</span></label><label class=\"am-footer-pin\" for=\"am-footer-branch-2\" style=\"left:47.166666666666664%;top:60.638297872340424%\"><svg viewBox=\"0 0 24 30\" aria-hidden=\"true\"><path d=\"M12 29C9 24 1 18 1 11a11 11 0 0 1 22 0c0 7-8 13-11 18Z\"/><circle cx=\"12\" cy=\"11\" r=\"4\" fill=\"white\"/></svg><span>الرياض</span></label><label class=\"am-footer-pin\" for=\"am-footer-branch-3\" style=\"left:18%;top:20.21276595744681%\"><svg viewBox=\"0 0 24 30\" aria-hidden=\"true\"><path d=\"M12 29C9 24 1 18 1 11a11 11 0 0 1 22 0c0 7-8 13-11 18Z\"/><circle cx=\"12\" cy=\"11\" r=\"4\" fill=\"white\"/></svg><span>تبوك</span></label><label class=\"am-footer-pin\" for=\"am-footer-branch-4\" style=\"left:80%;top:28.72340425531915%\"><svg viewBox=\"0 0 24 30\" aria-hidden=\"true\"><path d=\"M12 29C9 24 1 18 1 11a11 11 0 0 1 22 0c0 7-8 13-11 18Z\"/><circle cx=\"12\" cy=\"11\" r=\"4\" fill=\"white\"/></svg><span>الدمام</span></label></div><div class=\"am-footer-branch-panels\"><section class=\"am-footer-branch-panel\" data-branch=\"0\" aria-label=\"بيانات فرع الهفوف\"><div class=\"am-footer-branch-heading\"><a href=\"https://maps.app.goo.gl/yGvEQhCtpN38m46f8\" target=\"_blank\" rel=\"noopener noreferrer\">فرع الهفوف ↗</a><bdi>+966135814939</bdi></div><p>الخالدية، طريق الأمير فيصل بن فهد</p><div class=\"am-footer-map-actions\"><a href=\"tel:+966135814939\" aria-label=\"اتصال بفرع الهفوف\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.8 2.1Z\"/></svg></a><a class=\"am-footer-whatsapp\" href=\"https://wa.me/966135814939?text=%D9%85%D8%B1%D8%AD%D8%A8%D9%8B%D8%A7%20%D9%81%D8%B1%D8%B9%20%D8%A7%D9%84%D9%87%D9%81%D9%88%D9%81%D8%8C%20%D8%A3%D9%88%D8%AF%20%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D9%81%D8%B3%D8%A7%D8%B1%20%D8%B9%D9%86%20%D8%AE%D8%AF%D9%85%D8%A9.%0A%D8%A7%D9%84%D9%85%D8%AF%D9%8A%D9%86%D8%A9%3A%20%0A%D8%AA%D9%81%D8%A7%D8%B5%D9%8A%D9%84%20%D8%A7%D9%84%D8%A7%D8%AD%D8%AA%D9%8A%D8%A7%D8%AC%3A%20\" target=\"_blank\" rel=\"noopener noreferrer\" aria-label=\"واتساب فرع الهفوف\"><svg viewBox=\"0 0 448 512\" aria-hidden=\"true\" fill=\"currentColor\"><path d=\"M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z\"/></svg></a><a class=\"am-footer-map-open\" href=\"https://maps.app.goo.gl/yGvEQhCtpN38m46f8\" target=\"_blank\" rel=\"noopener noreferrer\">افتح الموقع <span aria-hidden=\"true\">↗</span></a></div></section><section class=\"am-footer-branch-panel\" data-branch=\"1\" aria-label=\"بيانات فرع المبرز\"><div class=\"am-footer-branch-heading\"><a href=\"https://maps.app.goo.gl/1NRboEmiKmiBSSua6\" target=\"_blank\" rel=\"noopener noreferrer\">فرع المبرز ↗</a><bdi>+966135317188</bdi></div><p>الشروفية، طريق مكة المكرمة</p><div class=\"am-footer-map-actions\"><a href=\"tel:+966135317188\" aria-label=\"اتصال بفرع المبرز\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.8 2.1Z\"/></svg></a><a class=\"am-footer-whatsapp\" href=\"https://wa.me/966135317188?text=%D9%85%D8%B1%D8%AD%D8%A8%D9%8B%D8%A7%20%D9%81%D8%B1%D8%B9%20%D8%A7%D9%84%D9%85%D8%A8%D8%B1%D8%B2%D8%8C%20%D8%A3%D9%88%D8%AF%20%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D9%81%D8%B3%D8%A7%D8%B1%20%D8%B9%D9%86%20%D8%AE%D8%AF%D9%85%D8%A9.%0A%D8%A7%D9%84%D9%85%D8%AF%D9%8A%D9%86%D8%A9%3A%20%0A%D8%AA%D9%81%D8%A7%D8%B5%D9%8A%D9%84%20%D8%A7%D9%84%D8%A7%D8%AD%D8%AA%D9%8A%D8%A7%D8%AC%3A%20\" target=\"_blank\" rel=\"noopener noreferrer\" aria-label=\"واتساب فرع المبرز\"><svg viewBox=\"0 0 448 512\" aria-hidden=\"true\" fill=\"currentColor\"><path d=\"M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z\"/></svg></a><a class=\"am-footer-map-open\" href=\"https://maps.app.goo.gl/1NRboEmiKmiBSSua6\" target=\"_blank\" rel=\"noopener noreferrer\">افتح الموقع <span aria-hidden=\"true\">↗</span></a></div></section><section class=\"am-footer-branch-panel\" data-branch=\"2\" aria-label=\"بيانات فرع الرياض\"><div class=\"am-footer-branch-heading\"><a href=\"https://maps.app.goo.gl/Q6y766YUvFScEH269\" target=\"_blank\" rel=\"noopener noreferrer\">فرع الرياض ↗</a><bdi>+966114538339</bdi></div><p>الرياض — الموقع على الخرائط</p><div class=\"am-footer-map-actions\"><a href=\"tel:+966114538339\" aria-label=\"اتصال بفرع الرياض\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.8 2.1Z\"/></svg></a><a class=\"am-footer-whatsapp\" href=\"https://wa.me/966114538339?text=%D9%85%D8%B1%D8%AD%D8%A8%D9%8B%D8%A7%20%D9%81%D8%B1%D8%B9%20%D8%A7%D9%84%D8%B1%D9%8A%D8%A7%D8%B6%D8%8C%20%D8%A3%D9%88%D8%AF%20%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D9%81%D8%B3%D8%A7%D8%B1%20%D8%B9%D9%86%20%D8%AE%D8%AF%D9%85%D8%A9.%0A%D8%A7%D9%84%D9%85%D8%AF%D9%8A%D9%86%D8%A9%3A%20%0A%D8%AA%D9%81%D8%A7%D8%B5%D9%8A%D9%84%20%D8%A7%D9%84%D8%A7%D8%AD%D8%AA%D9%8A%D8%A7%D8%AC%3A%20\" target=\"_blank\" rel=\"noopener noreferrer\" aria-label=\"واتساب فرع الرياض\"><svg viewBox=\"0 0 448 512\" aria-hidden=\"true\" fill=\"currentColor\"><path d=\"M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z\"/></svg></a><a class=\"am-footer-map-open\" href=\"https://maps.app.goo.gl/Q6y766YUvFScEH269\" target=\"_blank\" rel=\"noopener noreferrer\">افتح الموقع <span aria-hidden=\"true\">↗</span></a></div></section><section class=\"am-footer-branch-panel\" data-branch=\"3\" aria-label=\"بيانات فرع تبوك\"><div class=\"am-footer-branch-heading\"><a href=\"https://maps.app.goo.gl/JLwfnMEPGhtQuNZz9\" target=\"_blank\" rel=\"noopener noreferrer\">فرع تبوك ↗</a><bdi>+966553158377</bdi></div><p>تبوك، طريق الملك سعود</p><div class=\"am-footer-map-actions\"><a href=\"tel:+966553158377\" aria-label=\"اتصال بفرع تبوك\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.8 2.1Z\"/></svg></a><a class=\"am-footer-whatsapp\" href=\"https://wa.me/966553158377?text=%D9%85%D8%B1%D8%AD%D8%A8%D9%8B%D8%A7%20%D9%81%D8%B1%D8%B9%20%D8%AA%D8%A8%D9%88%D9%83%D8%8C%20%D8%A3%D9%88%D8%AF%20%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D9%81%D8%B3%D8%A7%D8%B1%20%D8%B9%D9%86%20%D8%AE%D8%AF%D9%85%D8%A9.%0A%D8%A7%D9%84%D9%85%D8%AF%D9%8A%D9%86%D8%A9%3A%20%0A%D8%AA%D9%81%D8%A7%D8%B5%D9%8A%D9%84%20%D8%A7%D9%84%D8%A7%D8%AD%D8%AA%D9%8A%D8%A7%D8%AC%3A%20\" target=\"_blank\" rel=\"noopener noreferrer\" aria-label=\"واتساب فرع تبوك\"><svg viewBox=\"0 0 448 512\" aria-hidden=\"true\" fill=\"currentColor\"><path d=\"M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z\"/></svg></a><a class=\"am-footer-map-open\" href=\"https://maps.app.goo.gl/JLwfnMEPGhtQuNZz9\" target=\"_blank\" rel=\"noopener noreferrer\">افتح الموقع <span aria-hidden=\"true\">↗</span></a></div></section><section class=\"am-footer-branch-panel\" data-branch=\"4\" aria-label=\"بيانات فرع الدمام\"><div class=\"am-footer-branch-heading\"><a href=\"https://maps.app.goo.gl/izpC6Gunvymht3C7A\" target=\"_blank\" rel=\"noopener noreferrer\">فرع الدمام ↗</a><bdi>+966508251525</bdi></div><p>مدينة العمال، شارع الأمير سعد بن عبدالعزيز</p><div class=\"am-footer-map-actions\"><a href=\"tel:+966508251525\" aria-label=\"اتصال بفرع الدمام\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.8 2.1Z\"/></svg></a><a class=\"am-footer-whatsapp\" href=\"https://wa.me/966508251525?text=%D9%85%D8%B1%D8%AD%D8%A8%D9%8B%D8%A7%20%D9%81%D8%B1%D8%B9%20%D8%A7%D9%84%D8%AF%D9%85%D8%A7%D9%85%D8%8C%20%D8%A3%D9%88%D8%AF%20%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D9%81%D8%B3%D8%A7%D8%B1%20%D8%B9%D9%86%20%D8%AE%D8%AF%D9%85%D8%A9.%0A%D8%A7%D9%84%D9%85%D8%AF%D9%8A%D9%86%D8%A9%3A%20%0A%D8%AA%D9%81%D8%A7%D8%B5%D9%8A%D9%84%20%D8%A7%D9%84%D8%A7%D8%AD%D8%AA%D9%8A%D8%A7%D8%AC%3A%20\" target=\"_blank\" rel=\"noopener noreferrer\" aria-label=\"واتساب فرع الدمام\"><svg viewBox=\"0 0 448 512\" aria-hidden=\"true\" fill=\"currentColor\"><path d=\"M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z\"/></svg></a><a class=\"am-footer-map-open\" href=\"https://maps.app.goo.gl/izpC6Gunvymht3C7A\" target=\"_blank\" rel=\"noopener noreferrer\">افتح الموقع <span aria-hidden=\"true\">↗</span></a></div></section></div></fieldset><details class=\"am-footer-map-hours\"><summary>ساعات الدوام في جميع الفروع</summary><dl><div><dt>السبت إلى الأربعاء</dt><dd>9 صباحًا – 1 ظهرًا<br>4 عصرًا – 10 مساءً</dd></div><div><dt>الخميس</dt><dd>9 صباحًا – 1 ظهرًا<br>4 عصرًا – 9 مساءً</dd></div><div><dt>الجمعة</dt><dd>مغلق</dd></div></dl></details><p class=\"am-footer-map-credit\">المواضع تقريبية؛ روابط الفروع تفتح الموقع الدقيق.<br>حدود الخريطة: <a href=\"https://www.geoboundaries.org/\" target=\"_blank\" rel=\"noopener noreferrer\">geoBoundaries</a> / <a href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\" rel=\"noopener noreferrer\">© OpenStreetMap، ODbL</a></p></aside>";
function mount(){const existing=document.querySelector('.am-footer-branches');if(existing)return true;const footer=document.querySelector('.store-footer__inner');if(!footer)return false;const container=footer.querySelector(':scope > .container');if(!container)return false;const original=document.createElement('div');original.className='am-footer-original';while(container.firstChild)original.append(container.firstChild);container.append(original);container.classList.add('am-footer-layout');container.insertAdjacentHTML('beforeend',markup);return true;}
window.almoalejFooterMap={mount};if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mount,{once:true});else mount();document.addEventListener('salla:page-loaded',mount);window.addEventListener('pageshow',mount);
})();
/* Store categories: an accessible drawer beside the cart. */
(()=>{
  'use strict';
  if(window.amCategoryDrawer)return;
  const css=`
body.am-categories-ready #mainnav custom-main-menu:has(a[href*="/c"]),body.am-categories-ready [data-testid="store-header-mobile-toggle"]{display:none!important}
#am-categories-trigger{display:inline-flex!important;align-items:center;justify-content:center;gap:0;flex:none;height:44px;width:44px;min-width:44px;padding:0;margin-inline-start:10px;border:1px solid #d5e6f2;border-radius:12px;background:#f5fbff;color:#0c3760;cursor:pointer;font-family:inherit;font-size:14px;font-weight:700;white-space:nowrap}
#am-categories-trigger svg{width:22px;height:22px;flex:none}#am-categories-trigger:hover{background:#e1f1fc}#am-categories-trigger:focus-visible{outline:2px solid #075be0;outline-offset:3px}

#mainnav #am-header-category-item{display:none!important;}
@media(min-width:1024px){#mainnav #am-header-category-item{display:inline-flex!important;align-items:center;}#am-header-category-item>button{background:transparent;color:white;font:inherit;font-weight:700;padding:8px;cursor:pointer;}#am-header-category-item>button::after{content:'⌄';margin-inline-start:6px;} }
#am-header-category-list{position:fixed;inset:auto;margin:0;width:256px;max-height:min(65vh,480px);overflow-y:auto;overscroll-behavior:contain;direction:rtl;background:white;border:1px solid #d1e3ec;border-radius:14px;padding:6px;box-shadow:0 10px 28px #102e5033;}#am-header-category-list:not(:popover-open){display:none!important;}#am-header-category-list a{display:block!important;padding:9px 12px;color:#102e50!important;line-height:1.5;text-decoration:none;border-radius:8px;}#am-header-category-list a:is(:hover,:focus-visible){background:#e9f6fb;}

.am-drawer-address{display:none;}
@media(max-width:767px){
html body header.store-header #mainnav .items-stretch:has(>.am-header-actions){position:relative!important;align-items:center!important;}
html body header.store-header #mainnav .items-stretch>.items-center:has(.navbar-brand){position:absolute!important;left:50%!important;top:50%!important;transform:translate(-50%,-50%)!important;width:max-content!important;z-index:2;}
html body header.store-header #mainnav .am-header-actions{display:grid!important;direction:rtl;grid-template-columns:44px 44px minmax(0,1fr) 44px 44px!important;align-items:center!important;justify-items:center!important;gap:2px!important;width:100%!important;flex:1 1 auto!important;}
html body header.store-header #mainnav .am-header-actions>#am-categories-trigger{grid-area:1/1!important;}
html body header.store-header #mainnav .am-header-actions>.am-header-search{grid-area:1/2!important;}
html body header.store-header #mainnav .am-header-actions>:is(salla-user-menu,.header-btn:has(.sicon-user)){grid-area:1/4!important;}
html body header.store-header #mainnav .am-header-actions>salla-cart-summary{grid-area:1/5!important;}
html body header.store-header #mainnav .am-header-actions>.am-header-address{display:none!important;}
html body header.store-header #mainnav .am-header-actions .am-header-search :is(.s-search-input,.s-search-input-wrapper),html body header.store-header #mainnav .am-header-actions salla-user-menu .s-user-menu-trigger,html body header.store-header #mainnav .am-header-actions salla-cart-summary .s-cart-summary-wrapper{background:transparent!important;border:0!important;box-shadow:none!important;}
html body header.store-header #mainnav .am-header-search .s-search-icon svg,html body header.store-header #mainnav .s-cart-summary-wrapper .sicon-shopping-bag{color:white!important;}
html body header.store-header #mainnav .am-header-search .s-search-icon svg path{fill:white!important;}
#am-categories-dialog .am-drawer-address{display:block;margin:8px 12px 12px;padding:10px 14px;text-align:start;color:#123b60;border:1px solid #d5e4ef;border-radius:10px;background:white;font-weight:700;flex:none;}
}
@media(max-width:767px){html body header.store-header #mainnav#mainnav#mainnav .am-header-actions :is(.s-search-input,.s-search-input-wrapper,.s-user-menu-trigger,.s-cart-summary-wrapper,#s-cart-icon){background:transparent!important;box-shadow:none!important;border-color:transparent!important;}}
#am-categories-dialog{position:fixed;inset:0 auto 0 0;width:min(360px,calc(100vw - 32px));max-width:360px;height:100dvh;max-height:100dvh;margin:0;padding:0;border:0;border-radius:0 20px 20px 0;background:#f5fbff;color:#123b60;box-shadow:12px 0 50px #07315122;direction:rtl;overflow:hidden}
#am-categories-dialog[open]{display:flex;flex-direction:column;animation:am-category-enter .2s ease-out}#am-categories-dialog::backdrop{background:#071d3b70;backdrop-filter:blur(2px)}
.am-categories-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:22px 20px 18px;border-bottom:1px solid #d9e8f2;flex:none}
#am-categories-title{margin:0;font-size:20px;line-height:1.5;color:#123b60}.am-categories-close{display:grid;place-items:center;flex:none;width:36px;height:36px;padding:0;border:1px solid #d5e4ef;border-radius:10px;background:white;color:#123b60;cursor:pointer}.am-categories-close svg{width:18px;height:18px}
.am-categories-links{overflow-y:auto;overscroll-behavior:contain;min-height:0;padding:12px;scrollbar-width:thin}.am-categories-links a{display:flex!important;align-items:center;justify-content:space-between;gap:12px;min-height:49px;padding:12px 14px;margin-bottom:5px;background:white;border:1px solid #e0ecf4;border-radius:11px;color:#123b60!important;text-decoration:none!important;font-size:15px;font-weight:600;line-height:1.6}.am-categories-links a::after{content:'‹';font-size:23px;line-height:1;color:#688ca9}.am-categories-links a:hover,.am-categories-links a[aria-current="page"]{background:#e4f2ff;border-color:#afcee8}.am-categories-links a:focus-visible,.am-categories-close:focus-visible{outline:2px solid #075be0;outline-offset:-3px}
.am-categories-pages{display:none}@media(max-width:1023px){.am-categories-pages{display:block;border-top:1px solid #d9e8f2;padding-top:12px;margin-top:14px}.am-categories-pages a{background:transparent;border-color:transparent;font-size:14px}}
@media(max-width:639px){#am-categories-trigger{padding:0;width:40px;min-width:40px;height:40px;margin-inline-start:6px;border-radius:10px}#am-categories-trigger>span{display:none}.am-categories-heading{padding:18px 16px}.am-categories-links{padding:10px}}
@keyframes am-category-enter{from{transform:translateX(-24px);opacity:0}to{transform:translateX(0);opacity:1}}@media(prefers-reduced-motion:reduce){#am-categories-dialog[open]{animation:none}#am-categories-dialog::backdrop{backdrop-filter:none}}

#am-categories-dialog .am-categories-heading{box-sizing:border-box;height:var(--bar-height,82px);padding:0 16px;background:#102e50;border:0;}
#am-categories-dialog .am-drawer-brand{height:var(--brand-height,64px);max-height:100%;width:auto;object-fit:contain;}
#am-categories-dialog #am-categories-title{padding:16px 18px 4px;flex:none;}
#am-categories-dialog .am-categories-close{background:transparent;color:white;border-color:#ffffff55;}
@media(prefers-reduced-motion:no-preference){
#am-categories-dialog{transform:translateX(-100%);opacity:0;transition:transform .32s cubic-bezier(.22,.7,.22,1),opacity .24s ease,display .32s allow-discrete,overlay .32s allow-discrete;}
#am-categories-dialog[open]{animation:none;transform:translateX(0);opacity:1;}
#am-categories-dialog::backdrop{opacity:0;transition:opacity .24s ease,display .32s allow-discrete,overlay .32s allow-discrete;}
#am-categories-dialog[open]::backdrop{opacity:1;}
@starting-style{#am-categories-dialog[open]{transform:translateX(-100%);opacity:0;}#am-categories-dialog[open]::backdrop{opacity:0;}}
}
`;
  const verifiedCategories=[['أجهزة التحلية','463435319'],['عروض الأجهزة','146247215'],['عروض الفلاتر','598060327'],['أجهزة النانو تيكنولوجي','1969591600'],['باقات الصيانة','1520217384'],['الفلاتر','564944693'],['الصيانة وقطع الغيار','1297587511'],['البرادات وصانعات الثلج','1796286755'],['الكافيهات والمطاعم','1157515308'],['فلاتر التصفية المركزية','288346930'],['فلاتر التصفية الصغيرة','1195553841'],['فلاتر الشاور','1472671796']];
  let drawerOpener;
  function openCategories(event){
    event.stopPropagation();
    if(dialog.open || !refresh())return;
    drawerOpener=event.currentTarget;
    const mark=document.querySelector('#mainnav .navbar-brand img');
    const bar=document.querySelector('#mainnav .inner');
    if(mark){const image=dialog.querySelector('.am-drawer-brand');image.src=mark.currentSrc||mark.src;dialog.style.setProperty('--brand-height',mark.getBoundingClientRect().height+'px');}
    if(bar)dialog.style.setProperty('--bar-height',bar.getBoundingClientRect().height+'px');
    previousOverflow=document.body.style.overflow;
    dialog.showModal();document.body.style.overflow='hidden';
    drawerOpener.setAttribute('aria-expanded','true');
  }
  function mountHeaderCategories(){
    const menu=document.querySelector('#mainnav custom-main-menu .main-menu');
    if(!menu||menu.querySelector('#am-header-category-item'))return;
    const item=document.createElement('li');item.id='am-header-category-item';
    const button=document.createElement('button');button.type='button';button.textContent='الأقسام';button.setAttribute('popovertarget','am-header-category-list');button.setAttribute('aria-expanded','false');button.setAttribute('aria-controls','am-header-category-list');
    const panel=document.createElement('nav');panel.id='am-header-category-list';panel.setAttribute('popover','auto');panel.setAttribute('aria-label','تصنيفات المنتجات');
    panel.addEventListener('beforetoggle',event=>{const open=event.newState==='open';button.setAttribute('aria-expanded',String(open));if(!open)return;panel.replaceChildren(...links().map(entry=>{const link=document.createElement('a');link.href=entry.href;link.textContent=entry.name;return link}));const rect=button.getBoundingClientRect();panel.style.top=Math.round(rect.bottom+8)+'px';panel.style.left=Math.max(8,Math.min(innerWidth-264,rect.right-256))+'px';});
    document.getElementById(panel.id)?.remove();item.append(button);menu.append(item);document.body.append(panel);
  }
  function mountEmptyCart(){
    const link=document.querySelector('[data-testid="store-cart-empty"] a[data-testid="store-cart-back-home"]');
    if(!link)return;
    if(link.hash!=='#am-shop')link.hash='am-shop';
    if(link.textContent!=='تسوّق بالأقسام')link.textContent='تسوّق بالأقسام';
  }
  let trigger,dialog,list,previousOverflow='',signature='';
  function links(){
    const result=[],seen=new Set();
    document.querySelectorAll('section[component-id="935235511"] a[href]').forEach(a=>{
      let u;try{u=new URL(a.href,location.href)}catch{return}
      if(!/\/c\d+(?:\/)?$/.test(u.pathname)||!a.textContent.trim())return;
      const id=u.pathname.match(/\/c(\d+)/)[1];if(seen.has(id))return;seen.add(id);
      if(new URL(location.href).searchParams.get('preview')==='true')u.searchParams.set('preview','true');
      result.push({name:a.textContent.trim(),href:u.href,id});
    });
    if(!result.length)verifiedCategories.forEach(([name,id])=>{const prefix=location.hostname==='salla.sa'?'/almoalej.com':'';const u=new URL(prefix+'/-/c'+id,location.origin);if(new URL(location.href).searchParams.get('preview')==='true')u.searchParams.set('preview','true');result.push({name,id,href:u.href})});
    return result;
  }
  const desktopDrawer=matchMedia('(min-width:1024px)');
  const serviceSelectors={periodic:'#am-service-requests [data-am-request=periodic]',urgent:'#am-service-requests [data-am-request=urgent]',complaint:'#am-service-requests [data-am-request=complaint]',compare:'.am-hub-card[data-shop-tool=compare]'};
  function followServiceHash(){
    const action=location.hash.replace('#store-service-','');if(!Object.hasOwn(serviceSelectors,action))return;
    function launch(){const button=document.querySelector(serviceSelectors[action]);if(!button)return false;history.replaceState(history.state,'',location.pathname+location.search);button.click();return true;}
    if(launch())return;const observer=new MutationObserver(()=>{if(launch())observer.disconnect()});observer.observe(document.body,{childList:true,subtree:true});setTimeout(()=>observer.disconnect(),15000);
  }
  window.addEventListener('hashchange',followServiceHash);if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',followServiceHash,{once:true});else followServiceHash();
  function refreshServices(destination){
    const home=document.querySelector('#mainnav .navbar-brand')?.href||'/';const service=id=>new URL('#store-service-'+id,home).href;
    const entries=[['طلب صيانة دورية',service('periodic'),'periodic'],['طلب صيانة عاجلة',service('urgent'),'urgent'],['البلاغات والشكاوى',service('complaint'),'complaint'],['مقارنة الأجهزة والعروض',service('compare'),'compare'],['فروع المعالج',document.querySelector('#am-footer-branches-title')?'#am-footer-branches-title':new URL('#am-footer-branches-title',home).href],['شراء كهدية لأحبابك','/قسم-الهدايا/page-663889449'],['قائمة المفضلة',document.querySelector('header a[href*="/account/wishlist"]')?.href||'/account/wishlist'],['سلة التسوق',document.querySelector('#mainnav .s-cart-summary-wrapper')?.href||'/cart'],['طلباتي',document.querySelector('a[href*="/account/orders"]')?.href||'/account/orders'],['الأسئلة الشائعة',document.querySelector('#am-important-info a[href*="1341070287"]')?.href||'/الأسئلة-الشائعة/page-1341070287']];
    const key=JSON.stringify(entries);if(destination.dataset.servicesKey===key && destination.firstElementChild)return true;destination.dataset.servicesKey=key;destination.replaceChildren();for(const [name,href,action] of entries){const a=document.createElement('a');a.href=href;a.textContent=name;if(action)a.addEventListener('click',e=>{const target=document.querySelector(serviceSelectors[action]);if(!target||e.ctrlKey||e.metaKey||e.shiftKey)return;e.preventDefault();dialog.addEventListener('close',()=>target.click(),{once:true});});destination.append(a)}
    const business=document.createElement('a');business.textContent='قطاع الأعمال';business.setAttribute('role','link');business.setAttribute('aria-disabled','true');business.title='سيُتاح الرابط قريبًا';business.style.cursor='default';destination.append(business);return true;
  }
  function refresh(){
    const name=desktopDrawer.matches?'روابط المتجر':'الأقسام';const title=dialog.querySelector('#am-categories-title');if(title.textContent!==name)title.textContent=name;list.setAttribute('aria-label',name);if(trigger)trigger.setAttribute('aria-label','فتح قائمة '+name);if(desktopDrawer.matches){signature="";return refreshServices(list)}
    delete list.dataset.servicesKey;refreshServices(dialog.querySelector(".am-mobile-service-links"));
    const entries=links();if(!entries.length)return false;
    const next=JSON.stringify(entries);if(next!==signature){
      signature=next;list.replaceChildren();
      entries.forEach(entry=>{const a=document.createElement('a');a.textContent=entry.name;a.href=entry.href;a.dataset.categoryId=entry.id;
        if(new RegExp('/c'+entry.id+'/?$').test(location.pathname))a.setAttribute('aria-current','page');list.append(a);});
      const pages=document.createElement('div');pages.className='am-categories-pages';pages.setAttribute('aria-label','روابط المتجر');
      const home=new URL(location.hostname==='salla.sa'?'/almoalej.com/':'/',location.origin);if(new URL(location.href).searchParams.get('preview')==='true')home.searchParams.set('preview','true');
      [['الرئيسية',''],['المتجر','am-shop'],['الخدمات','am-services'],['عن المعالج','am-about'],['تواصل معنا','am-contact']].forEach(([name,hash])=>{const a=document.createElement('a');const u=new URL(home);u.hash=hash;a.href=hash==='am-about'?new URL('/من-نحن/page-1985983162','https://almoalej.com').href:u.href;a.textContent=name;pages.append(a)});const rewards=document.createElement('a');rewards.href='https://almoalej.com/loyalty';rewards.textContent='مكافآت المعالج';pages.append(rewards);list.append(pages);
    }
    return true;
  }
  function close(){if(dialog?.open)dialog.close()}
  function mount(){
    const cart=document.querySelector('#mainnav salla-cart-summary');if(!cart)return false;
    if(!dialog){
      const style=document.createElement('style');style.id='am-categories-css';style.textContent=css+`#am-categories-dialog .am-mobile-service-title,#am-categories-dialog .am-mobile-service-links{display:none}@media(max-width:1023px){#am-categories-dialog[open]{overflow-y:auto;overscroll-behavior:contain}#am-categories-dialog .am-categories-links{flex:none;overflow:visible}#am-categories-dialog .am-mobile-service-links,#am-categories-dialog .am-mobile-service-title{display:block}#am-categories-dialog .am-mobile-service-title{padding:4px 16px;margin:0;font-size:17px;font-weight:700}#am-categories-dialog .am-categories-heading{flex:none}}`;document.head.append(style);
      dialog=document.createElement('dialog');dialog.id='am-categories-dialog';dialog.setAttribute('aria-labelledby','am-categories-title');
      const heading=document.createElement('div');heading.className='am-categories-heading';
      const title=document.createElement('h2');title.id='am-categories-title';title.textContent='الأقسام';
      const exit=document.createElement('button');exit.type='button';exit.className='am-categories-close';exit.setAttribute('aria-label','إغلاق قائمة الأقسام');exit.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg>';exit.addEventListener('click',close);
      const brand=document.createElement('img');brand.className='am-drawer-brand';brand.alt='المعالج لوحدات تحلية المياه';heading.append(brand,exit);list=document.createElement('nav');list.className='am-categories-links';list.setAttribute('aria-label','أقسام المتجر');const addressAction=document.createElement('button');addressAction.type='button';addressAction.className='am-drawer-address';addressAction.textContent='عنوان التوصيل';addressAction.addEventListener('click',()=>{const original=document.querySelector('#mainnav .am-header-address');if(original){dialog.addEventListener('close',()=>original.click(),{once:true});close();}});const mobileServices=document.createElement('nav');mobileServices.className='am-categories-links am-mobile-service-links';mobileServices.setAttribute('aria-label','روابط المتجر');mobileServices.addEventListener('click',e=>{if(e.target.closest('a[href]'))close()});const serviceTitle=document.createElement('h3');serviceTitle.className='am-mobile-service-title';serviceTitle.textContent='روابط المتجر';dialog.append(heading,title,list,addressAction,serviceTitle,mobileServices);document.body.append(dialog);
      dialog.addEventListener('click',e=>{if(e.target===dialog){const r=dialog.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)close()}});
      list.addEventListener('click',e=>{if(e.target.closest('a[href]'))close()});
      dialog.addEventListener('close',()=>{document.body.style.overflow=previousOverflow;drawerOpener?.setAttribute('aria-expanded','false');(drawerOpener?.isConnected ? drawerOpener : trigger)?.focus({preventScroll:true})});
    }
    if(!trigger||!trigger.isConnected){
      trigger=document.createElement('button');trigger.type='button';trigger.id='am-categories-trigger';trigger.setAttribute('aria-label','فتح قائمة الأقسام');trigger.setAttribute('aria-controls',dialog.id);trigger.setAttribute('aria-haspopup','dialog');trigger.setAttribute('aria-expanded','false');
      trigger.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h16"/></svg>';
      trigger.addEventListener('click',openCategories);
      cart.after(trigger);
    }
    mountHeaderCategories();mountEmptyCart();if(refresh())document.body.classList.add('am-categories-ready');
    return true;
  }
  function start(){mount();const cartMain=document.body.classList.contains('cart')&&document.querySelector('main');if(cartMain)new MutationObserver(mountEmptyCart).observe(cartMain,{childList:true,subtree:true});const header=document.querySelector('header')||document.querySelector('#mainnav');if(header){let scheduled=false;new MutationObserver(()=>{if(scheduled)return;scheduled=true;requestAnimationFrame(()=>{scheduled=false;mount()})}).observe(header,{childList:true,subtree:true})}}
  desktopDrawer.addEventListener('change',mount);window.amCategoryDrawer={mount,close};
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
  window.addEventListener('pagehide',close);document.addEventListener('salla:page-loaded',mount);
})();
/* Hide duplicate category shortcuts in the upper utility bar. */
(()=>{const style=document.createElement("style");style.id="am-topnav-categories-hidden";style.textContent=".top-navbar [data-testid=store-header-topnav]{display:none!important}";document.head.append(style)})();
/* Move the existing search and address controls beside the account and cart. */
(()=>{
 'use strict';if(window.amHeaderUtilities)return;
 const css=`
body.am-header-utilities-ready header.store-header .top-navbar{display:none!important}
body.am-header-utilities-ready header.store-header #mainnav a.mburger[data-testid="store-header-mobile-toggle"]{display:none!important}
#mainnav .am-header-actions{display:flex!important;align-items:center!important;flex:none;gap:8px;margin-block:8px!important;min-width:0}
#mainnav .am-header-actions>salla-cart-summary,#mainnav .am-header-actions>salla-user-menu,#mainnav .am-header-actions>#am-categories-trigger{margin:0!important;flex:none}
#mainnav .am-header-search{display:block!important;flex:none!important;width:40px!important;max-width:40px!important;margin:0!important;padding:0!important}
#mainnav .am-header-search salla-search{display:block;width:100%!important}
#mainnav .am-header-search :is(.s-search-placeholder-wrapper,.s-search-input-wrapper){width:100%!important;min-width:0!important;margin:0!important}
#mainnav .am-header-search .s-search-input{height:40px!important;min-height:40px!important;padding:0!important;border:1px solid #d5e6f2!important;border-radius:11px!important;color:transparent!important;cursor:pointer;background:#f5fbff!important}
#mainnav .am-header-search .s-search-input::placeholder{color:transparent!important}
#mainnav .am-header-search .s-search-icon-wrap{inset-inline-start:0!important;inset-inline-end:0!important;display:flex;justify-content:center;pointer-events:none;z-index:2}
#mainnav .am-header-search .s-search-icon{position:relative;z-index:3;color:#123b60!important}#mainnav .am-header-search .s-search-icon svg{fill:#123b60!important;width:18px;height:18px}
#mainnav .am-header-address{display:inline-flex!important;justify-content:center;align-items:center;flex:none;width:40px!important;min-width:40px!important;height:40px!important;min-height:40px!important;padding:0!important;margin:0!important;border:1px solid #d5e6f2;border-radius:11px;background:#f5fbff;color:#123b60;font-size:0!important;box-sizing:border-box}
#mainnav .am-header-address i{font-size:20px!important;line-height:1;margin:0!important}
#mainnav .am-header-address:focus-visible{outline:2px solid #075be0;outline-offset:3px}
@media(min-width:1440px){#mainnav .am-header-search{width:180px!important;max-width:180px!important}#mainnav .am-header-search .s-search-input{padding-inline:34px 10px!important;color:#123b60!important;font-size:12px!important}#mainnav .am-header-search .s-search-input::placeholder{color:#6a849c!important}#mainnav .am-header-search .s-search-icon-wrap{inset-inline-start:10px!important;inset-inline-end:auto!important}#mainnav .am-header-address{width:auto!important;min-width:85px!important;padding-inline:10px!important;font-size:13px!important;gap:6px}}
@media(max-width:639px){#mainnav .am-header-actions{gap:4px!important;margin-block:6px!important}#mainnav .am-header-actions>salla-cart-summary{width:40px!important;min-width:40px!important}#mainnav .am-header-actions .s-cart-summary-content{display:none!important}#mainnav .am-header-actions .s-cart-summary-wrapper{width:40px!important;min-width:40px!important;padding:0!important;justify-content:center}#mainnav .am-header-actions>salla-user-menu{max-width:40px!important;min-width:40px!important}#mainnav .am-header-actions .s-user-menu-trigger{min-width:40px!important;width:40px!important;padding:0!important}}
`;
 function mount(){
  const cart=document.querySelector('#mainnav salla-cart-summary');if(!cart)return;
  const group=cart.parentElement;const top=document.querySelector('header.store-header .top-navbar');
  const search=document.querySelector('#mainnav .am-header-search')||top?.querySelector('.header-search');
  const address=document.querySelector('#mainnav .am-header-address')||top?.querySelector('button.btn--rounded-gray[onclick]');
  if(!search||!address)return;
  group.classList.add('am-header-actions');search.classList.add('am-header-search');address.classList.add('am-header-address');
  if(search.parentElement!==group)group.prepend(search);
  if(address.parentElement!==group)search.after(address);
  document.body.classList.add('am-header-utilities-ready');
 }
 function start(){const style=document.createElement('style');style.id='am-header-utilities-css';style.textContent=css;document.head.append(style);mount();const header=document.querySelector('header.store-header');if(header){let pending=false;new MutationObserver(()=>{if(pending)return;pending=true;requestAnimationFrame(()=>{pending=false;mount()})}).observe(header,{subtree:true,childList:true})}}
 window.amHeaderUtilities={mount};if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();document.addEventListener('salla:page-loaded',mount);
})();
/* Hide only Shop and More from the storefront header navigation. */
(()=>{
 const css=document.createElement('style');css.id='am-header-shop-more-hidden';css.textContent='header.store-header #mobile-menu li[id="690705362"],header.store-header .am-header-extra-hidden{display:none!important}';document.head.append(css);
 function mount(){const header=document.querySelector('header.store-header');if(!header)return;header.querySelectorAll('nav a,nav button').forEach(el=>{const label=(el.getAttribute('aria-label')||el.textContent||'').trim();if(label==='المتجر'||label==='المزيد'){const item=el.closest('li');(item||el).classList.add('am-header-extra-hidden')}})}
 function start(){mount();const h=document.querySelector('header.store-header');if(h){let pending=false;new MutationObserver(()=>{if(pending)return;pending=true;requestAnimationFrame(()=>{pending=false;mount()})}).observe(h,{childList:true,subtree:true})}}
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();document.addEventListener('salla:page-loaded',mount);
})();
/* Clear purchase feedback and a readable cart breakdown, using native totals. */
(()=>{
 'use strict';
 const services=new Set(['696086226','519614875','373446428','1026510677','1689064447']);
 const css=`
 .am-purchase-feedback{position:fixed;z-index:10000;inset-inline-end:20px;top:90px;width:min(380px,calc(100vw - 24px));box-sizing:border-box;background:#fff;border:1px solid #cddfed;border-radius:16px;padding:16px;box-shadow:0 14px 50px #082b5926;color:#123b60;direction:rtl}
 .am-purchase-feedback[hidden]{display:none!important}.am-purchase-feedback header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;font-weight:700}.am-purchase-feedback button{font:inherit;cursor:pointer}.am-feedback-close{width:36px;height:36px;border:0;border-radius:9px;background:#f0f7fc;color:#123b60;font-size:24px!important}.am-feedback-product{display:flex;gap:12px;align-items:center}.am-feedback-product img{width:72px;height:72px;object-fit:contain;flex:none;border:1px solid #e7eff6;border-radius:10px}.am-feedback-product strong{font-size:14px;line-height:1.7;overflow-wrap:anywhere}.am-feedback-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:14px}.am-feedback-actions a,.am-feedback-actions button{display:flex;align-items:center;justify-content:center;text-align:center;min-height:44px;border-radius:10px;padding:7px;background:#eef6ff;border:1px solid #d0e1f1;color:#0756d9;font:inherit;font-size:14px;font-weight:700;text-decoration:none}.am-feedback-actions a{background:#0756d9;color:white;border-color:#0756d9}
 body.am-purchase-feedback-open salla-add-product-toast{display:none!important}
 .am-purchase-breakdown{display:none}.am-purchase-note{font-size:12px;line-height:1.7;color:#61788b;margin:10px 0 0}.am-continue-shopping{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:8px 12px;border:1px solid #cddfed;border-radius:10px;color:#0756d9;background:#fff;font-size:14px;font-weight:700;text-decoration:none;margin-block:4px 12px}
 @media(max-width:767px){.am-purchase-feedback{top:70px;inset-inline-end:12px;padding:13px}.am-purchase-breakdown{display:block;margin:0 0 14px;padding:14px;border:1px solid #d5e5ef;border-radius:14px;background:#fff;color:#123b60;box-sizing:border-box}.am-purchase-breakdown h2{font-size:16px;font-weight:700;margin:0 0 10px}.am-purchase-line{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-block:5px;font-size:13px;line-height:1.6}.am-purchase-line b{white-space:nowrap}.am-purchase-line.am-purchase-install{color:#0756d9}.am-purchase-line i{margin-inline-start:3px}.am-purchase-breakdown .am-purchase-note{margin-top:8px;padding-top:8px;border-top:1px solid #e9eff5}.am-continue-shopping{margin-top:0}body.cart .cart-item h1{overflow-wrap:anywhere}}
 @media(prefers-reduced-motion:no-preference){.am-purchase-feedback{animation:am-purchase-enter .18s ease-out}@keyframes am-purchase-enter{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:translateY(0)}}}
 `;
 let last=null,panel=null,returnFocus=null,frame=0;
 const setText=(el,value)=>{if(el.textContent!==value)el.textContent=value};
 function hide(){if(panel)panel.hidden=true;document.body.classList.remove('am-purchase-feedback-open')}
 function cartUrl(){return document.querySelector('header salla-cart-summary a[href]')?.href||new URL('cart',document.querySelector('header .navbar-brand')?.href||location.origin+'/').href}
 let addAddressObserver, addAddressTimer;
 function endAddAddressWatch(){
  addAddressObserver?.disconnect(); clearTimeout(addAddressTimer);
  document.documentElement.classList.remove('am-adding-without-address');
 }
 function watchAddAddress(){
  endAddAddressWatch();
  const selector='salla-modal.s-bullet-delivery-modal[visible]';
  if(document.querySelector(selector))return;
  document.documentElement.classList.add('am-adding-without-address');
  addAddressObserver=new MutationObserver(()=>{
   const modal=document.querySelector(selector);
   if(modal){modal.visible=false;modal.removeAttribute('visible')}
  });
  addAddressObserver.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['visible']});
  addAddressTimer=setTimeout(endAddAddressWatch,20000);
 }
 function remember(event){
  const button=event.target.closest('button');if(!button||!/أضف إلى السلة/.test(button.textContent)){endAddAddressWatch();return;}
  watchAddAddress();
  const card=button.closest('.s-product-card-entry');const a=card?.querySelector('a[href*="/p"]');
  const id=(a?.href||location.pathname).match(/\/p(\d+)(?:[/?#]|$)/)?.[1];if(!id||services.has(id))return;
  const name=card?.querySelector('h3,h2')?.textContent.trim()||document.querySelector('main h1')?.textContent.trim();
  const choices=Array.from(document.querySelectorAll('main salla-product-options input:checked')).map(e=>e.parentElement.querySelector('label img')?.alt||e.parentElement.querySelector('label')?.textContent.trim()).filter(Boolean);
  const selected=document.querySelector('main salla-product-options input:checked')?.parentElement.querySelector('label img');
  const img=card?.querySelector('img')||selected||document.querySelector('main salla-slider img');
  if(name)last={id,name:name+(choices.length?" — "+choices.join("، "):""),image:img?.currentSrc||img?.src||'',time:Date.now(),button};
 }
 function added(response,productId){
  if(!last||String(productId)!==last.id||services.has(String(productId))||Date.now()-last.time>20000)return;
  if(!panel){panel=document.createElement('section');panel.className='am-purchase-feedback';panel.setAttribute('role','region');panel.setAttribute('aria-label','تأكيد الإضافة للسلة');panel.innerHTML='<header><span role="status" aria-live="polite">تمت الإضافة إلى السلة</span><button type="button" class="am-feedback-close" aria-label="إغلاق تأكيد الإضافة">×</button></header><div class="am-feedback-product"><img alt=""><strong></strong></div><div class="am-feedback-actions"><a>إتمام الطلب</a><button type="button">متابعة التسوق</button></div>';document.body.append(panel);panel.querySelector('.am-feedback-close').addEventListener('click',()=>{hide();returnFocus?.focus({preventScroll:true})});panel.querySelector('.am-feedback-actions button').addEventListener('click',()=>{hide();returnFocus?.focus({preventScroll:true})});}
  returnFocus=last.button;setText(panel.querySelector('strong'),last.name);const img=panel.querySelector('img');img.hidden=!last.image;if(last.image)img.src=last.image;img.alt=last.name;panel.querySelector('a').href=cartUrl();panel.hidden=false;document.body.classList.add('am-purchase-feedback-open');last=null;
 }
 function paint(){frame=0;if(!document.body.classList.contains('cart'))return;
  const main=document.querySelector('#main-content');const products=main?.querySelector('.cart-item')?.parentElement?.parentElement;
  const native=document.querySelector('salla-cart-summary-card');if(!products||!native)return;
  let box=document.getElementById('am-purchase-breakdown');if(!box){box=document.createElement('section');box.id='am-purchase-breakdown';box.className='am-purchase-breakdown';box.setAttribute('aria-label','تفصيل مبلغ السلة');box.innerHTML='<h2>ملخص الطلب</h2><div class="am-purchase-lines"></div><p class="am-purchase-note">رسوم الشحن تظهر في الخطوة التالية حسب العنوان وطريقة التوصيل.</p>';products.append(box);}
  const rows=Array.from(native.querySelectorAll('.s-cart-summary-card-line')).filter(e=>e.querySelector('b'));
  const values=rows.map(e=>({label:e.querySelector('span')?.textContent.trim()||'',amount:e.querySelector('b')?.textContent.trim()||'',installation:e.classList.contains('am-install-summary-line')}));
  const signature=JSON.stringify(values);if(box.dataset.signature!==signature){box.dataset.signature=signature;const lines=box.querySelector('.am-purchase-lines');lines.replaceChildren();values.forEach(row=>{const line=document.createElement('div');line.className='am-purchase-line'+(row.installation?' am-purchase-install':'');const label=document.createElement('span'),amount=document.createElement('b');label.textContent=row.label;amount.textContent=row.amount+" ريال";line.append(label,amount);lines.append(line)})}
  box.hidden=!values.length;
  let back=products.querySelector('.am-continue-shopping');if(!back){back=document.createElement('a');back.className='am-continue-shopping';back.textContent='متابعة التسوق';back.href=document.querySelector('header .navbar-brand')?.href||location.origin+'/';products.append(back)}
  const sheet=native.querySelector('.s-cart-summary-card-sheet');if(sheet&&!sheet.querySelector('.am-purchase-note')){const note=document.createElement('p');note.className='am-purchase-note';note.textContent='رسوم الشحن تظهر في الخطوة التالية حسب العنوان وطريقة التوصيل.';sheet.append(note)}
 }
 function schedule(){if(!frame)frame=requestAnimationFrame(paint)}
 function start(){if(document.getElementById('am-purchase-flow-css'))return;const style=document.createElement('style');style.id='am-purchase-flow-css';style.textContent=css+' .am-adding-without-address .s-bullet-delivery-modal{visibility:hidden!important}';document.head.append(style);document.addEventListener('click',remember,true);document.addEventListener('keydown',e=>{if(e.key==='Escape')hide()});window.addEventListener('pagehide',hide);document.addEventListener('am:installation-state',schedule);if(document.body.classList.contains('cart'))new MutationObserver(records=>{if(records.some(r=>!(r.target instanceof Element&&r.target.closest('#am-purchase-breakdown,.am-continue-shopping'))))schedule()}).observe(document.querySelector('#main-content')?.parentElement||document.body,{childList:true,subtree:true,characterData:true});paint();if(window.salla?.onReady)salla.onReady(()=>salla.event.on('cart::item.added',added));}
 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
(function(){function addImportantLinks(){const menu=document.querySelector('footer [data-testid="store-footer-menu"]');if(!menu||document.getElementById('am-important-info'))return;const nav=document.createElement('nav');nav.id='am-important-info';nav.className='s-menu-footer-list';nav.setAttribute('aria-label','معلومات المتجر');for(const [text,url] of [["الأسئلة الشائعة","https://almoalej.com/%D8%A7%D9%84%D8%A3%D8%B3%D8%A6%D9%84%D8%A9-%D8%A7%D9%84%D8%B4%D8%A7%D8%A6%D8%B9%D8%A9/page-1341070287"],["سياسة الإلغاء والاسترجاع والاستبدال","https://almoalej.com/%D8%B3%D9%8A%D8%A7%D8%B3%D8%A9-%D8%A7%D9%84%D8%A5%D9%84%D8%BA%D8%A7%D8%A1-%D9%88%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%B1%D8%AC%D8%A7%D8%B9-%D9%88%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%A8%D8%AF%D8%A7%D9%84/page-1528351806"],["الضمان والصيانة","https://almoalej.com/%D8%B3%D9%8A%D8%A7%D8%B3%D8%A9-%D8%A7%D9%84%D8%B6%D9%85%D8%A7%D9%86-%D9%88%D8%A7%D9%84%D8%B5%D9%8A%D8%A7%D9%86%D8%A9/page-503531275"],["سياسة الشحن والتركيب","/سياسة-الشحن-والتركيب/page-1744223971"],["سياسة الخصوصية","/سياسة-الخصوصية/page-128929985"],["سياسة المكافآت والولاء","/سياسة-المكافآت-والولاء/page-822778099"],["الشهادة الضريبية","/شهادة-التسجيل-في-ضريبة-القيمة-المضافة/page-1931898834"]]){const a=document.createElement('a');a.className='s-menu-footer-item';a.href=url;a.textContent=text;nav.append(a)}menu.before(nav)}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',addImportantLinks,{once:true});else addImportantLinks();})();
/* Almoalej FAQ page */
(function(){
 if(!/\/page-1341070287\/?$/.test(location.pathname))return;
 function mount(){
 const area=document.querySelector('main .content--single-page'),entry=area?.querySelector('.content-entry'),title=area?.querySelector('h1');if(!entry||!title||area.id==='am-help-center')return;
 const groups=[["اختيار الجهاز وطلبه","الموديل والسعر وخيارات التركيب",[["وين يتركّب الجهاز، ووش اللي بيكون ظاهر في المطبخ؟","يعتمد مكان التركيب على تصميم الموديل والمساحة المتاحة. أرسل للفرع اسم الجهاز وصورة المكان إذا ودك تتأكد من موضع الوحدة والخزان والصنبور قبل الطلب."],["أبي جهاز تحلية للبيت، كيف أطلبه؟","من «تسوّق بالأقسام» افتح أجهزة التحلية أو عروض الأجهزة. اختر المنتج وخياراته، وأضفه للسلة. حدّد عنوانك وراجع خيار التركيب والمجموع قبل إتمام الطلب."],["كيف أقارن تكلفة جهازين أو عرضين؟","قارن محتويات كل عرض أولًا، مثل وجود برادة أو فلاتر إضافية. بعدها راجع سعر الجهاز ورسوم التركيب لعنوانك في السلة، ورسوم الشحن عند إتمام الطلب."],["إذا أبي ماء بارد، وش أختار؟","ابحث عن عرض يذكر البرادة ضمن محتوياته أو عن موديل يذكر التبريد في مواصفاته. اسم جهاز التحلية وحده ما يوضح إذا كان يبرّد الماء."],["كيف أتحقق من بلد صناعة الموديل؟","راجع بلد المنشأ في مواصفات الموديل أو على ملصقه. إذا ما كان مذكورًا، أرسل رابط المنتج للفرع واطلب التأكيد قبل الشراء."]]],["أداء الجهاز وجودة الماء","الإنتاج والخزان والاستهلاك",[["كيف أعرف إذا إنتاج الجهاز يكفي استهلاك بيتي؟","ابحث عن معدل إنتاج الماء في مواصفات الموديل وقارنه باستهلاكك اليومي. سعة الخزان توضّح كمية الماء المخزّنة، أما معدل الإنتاج فيوضّح كمية الماء التي يستطيع الجهاز تحليتها خلال مدة محددة."],["كم أنتظر عشان يمتلئ الخزان بعد تفريغه؟","المدة تعتمد على سعة الخزان ومعدل إنتاج الجهاز وظروف التشغيل. لمعرفة المدة المتوقعة لجهازك، أعطِ الفرع رقم الموديل وسعة الخزان."],["وش القراءة المتوقعة للأملاح بعد التحلية؟","تختلف القراءة بحسب ماء التغذية والموديل. إذا تغيّرت عن المعتاد، سجّل قراءة الماء قبل الجهاز وبعده وشاركها مع الصيانة مع رقم الموديل."],["هل قراءة الأملاح وحدها تكفي للحكم على ماء الشرب؟","قراءة الأملاح تقيس جانبًا واحدًا من جودة الماء. إذا شكّيت في صلاحيته للشرب، استخدم مصدرًا موثوقًا إلى أن تتأكد من السبب وتُفحص جودة الماء عند الحاجة."],["كيف أقدّر استهلاك الجهاز للماء والكهرباء؟","راجع القدرة الكهربائية ومواصفات استهلاك الماء في دليل الموديل. عند المقارنة بين جهازين، اطلب بيانات كل موديل على حدة لأن الاستهلاك يتأثر بطريقة التشغيل."]]],["التركيب والصيانة","التغطية والفروع ومشكلات التشغيل",[["هل أقدر أطلب فني يركّب الجهاز في حيي؟","حدّد المدينة والحي من «العنوان»، ثم افتح السلة. إذا كانت خدمة التركيب متاحة للجهاز في عنوانك، يظهر خيارها ورسومها في بطاقة المنتج."],["كيف أتواصل مع أقرب فرع للمعالج؟","من خريطة الفروع أسفل المتجر اختر الفرع المناسب. تقدر تفتح موقعه على الخريطة، أو تتصل به، أو تراسله عبر واتساب."],["مين بيركب جهازي، وكيف أتأكد من خبرته بالموديل؟","عند تنسيق الزيارة، أعطِ الفرع اسم الموديل واسأله عن بيانات الفني وخبرته بتركيب هذا النوع. الفرع هو جهة التأكيد لتفاصيل الفريق المكلّف بزيارتك."],["كيف أعرف الفلاتر المناسبة وتكلفة تغييرها؟","طابق نوع الفلتر ومقاسه مع جهازك، ثم راجع سعره في قسم الفلاتر. إذا تبي زيارة صيانة، راجع محتويات الباقة وعدد زياراتها لتعرف ما يشمله السعر."],["لقيت ماء تحت الجهاز، وش أسوي؟","أوقف استخدام الجهاز. إذا كان محبس تغذيته في مكان آمن وجاف، أغلقه. تجنّب لمس أي توصيل كهربائي مبتل وتواصل مع الصيانة لتحديد مصدر التسرّب."],["تغيّر طعم الماء أو ريحته، كيف أتصرف؟","توقّف عن شربه مؤقتًا واستخدم مصدرًا آخر موثوقًا. عند التواصل مع الصيانة، وضّح متى بدأ التغيّر ومتى غُيّرت الفلاتر آخر مرة."],["ليش صار تدفّق الماء ضعيف أو انقطع؟","لاحظ هل الضعف في صنبور التحلية وحده أم في بقية صنابير المنزل، وهل بدأ بعد استخدام كمية كبيرة من الخزان. شارك هذه التفاصيل مع الصيانة إذا استمر الضعف."]]]];
 const css=document.createElement('style');css.textContent=`#am-help-center{width:100%;max-width:1080px;margin:24px auto 48px;padding:0;background:transparent;color:#123b60;direction:rtl}#am-help-center .faq-intro{display:flex;align-items:center;justify-content:space-between;gap:20px;background:#e8f6fb;border:1px solid #c8e5f1;border-radius:20px;padding:clamp(20px,4vw,46px);overflow:hidden}#am-help-center h1{font-size:clamp(28px,4vw,44px);line-height:1.3;color:#073d63;margin:0 0 12px}#am-help-center p{margin:0;color:#34566f;line-height:1.8}#am-help-center .faq-intro img{width:min(25%,180px);aspect-ratio:1;object-fit:contain;mix-blend-mode:multiply}#am-help-center .faq-topics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin:18px 0 30px}#am-help-center .faq-topics a{display:grid;grid-template-columns:1fr auto;align-content:center;gap:4px 12px;padding:18px;border:1px solid #cbdfea;border-radius:14px;background:white;text-decoration:none;color:#0c4364}#am-help-center .faq-topics small{grid-column:1;font-size:14px;color:#486477}#am-help-center .faq-topics b{grid-column:2;grid-row:1/3;align-self:center;color:#0756ad}#am-help-center section{scroll-margin-top:100px;margin:24px 0}#am-help-center h2{font-size:22px;margin:0 0 10px;color:#103c60}#am-help-center details{background:white;border:1px solid #d2e3ed;border-radius:12px;margin-bottom:8px}#am-help-center summary{display:flex;align-items:center;justify-content:space-between;gap:16px;cursor:pointer;padding:16px;font-weight:700;list-style:none}#am-help-center summary::-webkit-details-marker{display:none}#am-help-center summary:after{content:'+';color:#0756ad}#am-help-center details[open] summary:after{content:'−'}#am-help-center details p{padding:0 16px 16px}#am-help-center :is(a,summary):focus-visible{outline:3px solid #0760bd;outline-offset:2px}@media(max-width:650px){#am-help-center .faq-topics{grid-template-columns:1fr;gap:7px;margin:12px 0 20px}#am-help-center .faq-topics a{padding:12px 16px}#am-help-center .faq-intro{gap:8px}#am-help-center .faq-intro img{width:22%}}body #am-help-center .faq-intro img{filter:none}body #am-help-center .faq-intro>div{position:relative;z-index:1}#am-help-center .faq-intro::after{content:'';position:absolute;pointer-events:none;inset:-35% auto -35% 0;width:30%;background:linear-gradient(104deg,transparent 12%,rgba(212,235,251,.05) 30%,rgba(247,252,255,.24) 48%,rgba(209,234,248,.06) 64%,transparent 84%);transform:translateX(-150%) skewX(-12deg);animation:am-faq-shine 1.9s ease-in-out .25s 1 both}@keyframes am-faq-shine{to{transform:translateX(450%) skewX(-12deg)}}@media(prefers-reduced-motion:reduce){#am-help-center .faq-intro::after{animation:none;transform:translateX(38%) skewX(-12deg);opacity:.38}}`;document.head.append(css);
 const make=(tag,text)=>{const el=document.createElement(tag);if(text)el.textContent=text;return el};area.id='am-help-center';const hero=make('header'),copy=make('div');hero.className='faq-intro';title.before(hero);copy.style.marginInline='auto';copy.style.textAlign='center';copy.append(title,make('p','اختر موضوعًا للوصول إلى إجابات عن جهازك وطلبك وخدمة التركيب.'));const img=make('img');img.alt='';img.width=2172;img.height=724;img.src='https://cdn.salla.sa/PDdngK/products/kZmzUXPb2K0fbs1809r724QEOmgYAW8M0l2Mvddg.png';hero.append(copy,img);
 const nav=make('nav');nav.className='faq-topics';nav.setAttribute('aria-label','موضوعات الأسئلة الشائعة');const content=document.createDocumentFragment();content.append(nav);groups.forEach(([label,desc,questions],index)=>{const section=make('section');section.id='faq-topic-'+(index+1);section.append(make('h2',label));const a=make('a');a.href='#'+section.id;const arrow=make('b','↓');arrow.setAttribute('aria-hidden','true');a.append(make('strong',label),make('small',desc),arrow);nav.append(a);questions.forEach(([q,answer])=>{const illustrated=q==='وين يتركّب الجهاز، ووش اللي بيكون ظاهر في المطبخ؟';
 const d=make(illustrated?'article':'details'),heading=make(illustrated?'h3':'summary',q),body=make('p',answer);d.append(heading,body);
 if(illustrated){d.style.cssText='background:white;border:1px solid #d2e3ed;border-radius:12px;margin-bottom:8px';heading.style.cssText='font-size:18px;font-weight:700;margin:16px';body.style.cssText='margin:0 16px 14px';
  const figure=make('figure'),link=make('a'),pic=make('img'),caption=make('figcaption','رسم توضيحي لجهاز بخمس مراحل. يختلف ترتيب المكوّنات حسب الموديل.');
  figure.style.cssText='margin:0 16px 18px;max-width:680px';link.href='https://cdn.salla.sa/PDdngK/products/F96trDxkGcc6dd42tCl2y4rosawk3F0Hy9jqyF68.png';link.target='_blank';link.rel='noopener';link.style.cssText='display:block;color:#0756ad;font-weight:700';link.setAttribute('aria-label','تكبير رسم مسارات المياه في نافذة جديدة');pic.src=link.href;pic.loading='lazy';pic.alt='مسارات الماء بين حوض المطبخ وجهاز التحلية والخزان وصنبور الشرب، مع ترقيم مراحل التنقية الخمس';pic.style.cssText='width:100%;height:auto;display:block;border-radius:10px';link.append(pic,make('span','تكبير الرسم ↗'));caption.style.cssText='font-size:14px;line-height:1.7;color:#456477;margin-top:4px';figure.append(link,caption);d.append(figure);
 }section.append(d)});content.append(section)});entry.replaceChildren(content);
 }if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mount,{once:true});else mount();})();
/* Periodic maintenance request on the homepage */
(function () {
  const trigger = '[data-am-request=periodic], #am-periodic-request, section[component-id="1204252081"] .swiper-slide:nth-child(1) a';
  function setUpUrgentCard(){const section=document.querySelector('section[component-id="1204252081"]');if(!section)return false;const card=Array.from(section.querySelectorAll('a.slide--cat-entry')).find(a=>a.querySelector('h2')?.textContent.trim()==='أبحث عن فلتر');if(!card)return false;card.id='am-urgent-request';card.href='https://wa.me/966533557999?text='+encodeURIComponent('أرغب بطلب صيانة عاجلة');card.querySelector('h2').textContent='صيانة عاجلة';card.setAttribute('aria-haspopup','dialog');const style=document.createElement('style');style.textContent='section[component-id="1204252081"] #am-urgent-request::before{content:"وضّح العطل وأرسل طلبك لفريق الصيانة."!important}section[component-id="1204252081"] #am-urgent-request::after{content:"اطلب صيانة عاجلة"!important}';document.head.append(style);return true}
  if(!setUpUrgentCard() && (location.pathname==='/' || location.pathname==='/ar')){const observer=new MutationObserver(()=>{if(setUpUrgentCard())observer.disconnect()});observer.observe(document.documentElement,{childList:true,subtree:true});window.addEventListener('pagehide',()=>observer.disconnect(),{once:true})}
  function complaintSetup(){const section=document.querySelector('section[component-id="1204252081"]');const link=section&&Array.from(section.querySelectorAll('a.slide--cat-entry')).find(a=>a.querySelector('h2')?.textContent.trim()==='أحتاج صيانة');if(!link)return false;link.id='am-complaints';link.querySelector('h2').textContent='البلاغات والشكاوى';link.href='https://wa.me/966533557999?text='+encodeURIComponent('أرغب في تقديم بلاغ أو شكوى');link.setAttribute('aria-haspopup','dialog');const css=document.createElement('style');css.textContent='#am-complaints#am-complaints::before{content:"عندك بلاغ أو شكوى؟ اكتب التفاصيل لفريق المعالج."!important}#am-complaints#am-complaints::after{content:"قدّم بلاغًا أو شكوى"!important}';document.head.append(css);return true}
  if(!complaintSetup() && /^\/(?:ar\/?)?$/.test(location.pathname)){const observer=new MutationObserver(()=>{if(complaintSetup())observer.disconnect()});observer.observe(document.documentElement,{subtree:true,childList:true})}
  function configureComplaint(d){const form=d.querySelector('form');for(const name of ['city','otherCity','district'])form.elements[name].closest('label').remove();const kind=form.elements.kind;kind.replaceChildren(new Option('-- اختر نوع الطلب --',''),new Option('بلاغ'),new Option('شكوى'));const notes=form.elements.notes;notes.closest('label').firstChild.textContent='تفاصيل البلاغ أو الشكوى *';notes.required=true;notes.placeholder='اكتب ما حدث هنا…';notes.oninput=()=>notes.setCustomValidity('');d.setAttribute('aria-label','البلاغات والشكاوى');const phone=form.elements.phone;phone.id='am-complaint-phone';phone.closest('label').htmlFor=phone.id}
  let complaintDialog;
  let dialog;
  function build(complaint=false) {
    const style = document.createElement('style');
    style.textContent = "html:has(#am-periodic-dialog[open]),body:has(#am-periodic-dialog[open]){overflow:hidden!important;overscroll-behavior:none!important}#am-periodic-dialog{overscroll-behavior:contain}#am-periodic-dialog{direction:rtl;margin:auto;width:min(1080px,94vw);max-width:96vw;max-height:96dvh;overflow:auto;padding:28px 20px 18px;border:0;border-radius:10px;background:white;box-shadow:0 3px 18px #0001;color:#0873a6;text-align:right;box-sizing:border-box}#am-periodic-dialog::backdrop{background:#f8f8f8f7}#am-periodic-dialog .dismiss{position:absolute;left:8px;top:2px;padding:0 8px;color:#557080;font-size:20px}#am-periodic-dialog form{display:grid;gap:12px}#am-periodic-dialog label{display:grid;gap:6px;font:inherit;font-size:16px}#am-periodic-dialog [hidden]{display:none}#am-periodic-dialog input,#am-periodic-dialog select,#am-periodic-dialog textarea,#am-periodic-dialog .tel{box-sizing:border-box;width:100%;height:50px;margin:0;padding:0 14px;border:1px solid #999;border-radius:9px;background:white;color:#183249;font:inherit}#am-periodic-dialog select{appearance:auto}#am-periodic-dialog textarea{height:88px;padding:12px;resize:vertical;border-color:#ddd}#am-periodic-dialog .tel{display:flex;align-items:center;direction:ltr;padding:0;overflow:hidden;border-color:#283541}#am-periodic-dialog .tel span{display:flex;align-items:center;white-space:nowrap;padding:0 12px;border-right:1px solid #dae1e5;height:100%}#am-periodic-dialog .tel input{min-width:0;border:0;height:100%;text-align:left;direction:ltr}#am-periodic-dialog .tel:focus-within{outline:2px solid #1473af}#am-periodic-dialog button[type=submit]{justify-self:start;border-radius:8px;padding:12px 24px;background:#0756d9;color:white} @media(max-width:600px){#am-periodic-dialog{padding:27px 13px 14px}#am-periodic-dialog form{gap:10px}#am-periodic-dialog input,#am-periodic-dialog select,#am-periodic-dialog .tel{height:46px}}";
    if(complaint)style.textContent=style.textContent.replaceAll('#am-periodic-dialog','#am-complaint-dialog');
    document.head.append(style);
    const d=document.createElement('dialog');d.id=complaint?'am-complaint-dialog':'am-periodic-dialog';d.setAttribute('aria-label','طلب صيانة دورية');
    d.innerHTML="<button class=\"dismiss\" type=\"button\" aria-label=\"إغلاق\">×</button><form><label>الاسم ثلاثي *<input name=\"fullName\" required autocomplete=\"name\" maxlength=\"100\" pattern=\"\\s*\\S+(?:\\s+\\S+){2,}\\s*\" title=\"اكتب اسمك الثلاثي\"></label><label>المدينة *<select name=\"city\" required><option value=\"\">اختر مدينتك</option><option>الأحساء</option><option>الدمام</option><option>الرياض</option><option>تبوك</option><option value=\"other\">منطقة أخرى</option></select></label><label hidden>اسم المنطقة أو المدينة *<input name=\"otherCity\" maxlength=\"80\" pattern=\".*\\S.*\" required disabled aria-describedby=\"am-coverage-note\"><small id=\"am-coverage-note\">سيتأكد الفريق من إمكانية الزيارة في منطقتك.</small></label><label>الحي *<input name=\"district\" required maxlength=\"80\" pattern=\".*\\S.*\"></label><label for=\"am-service-phone\">الجوال: (مثل 050XXXXXXX) *<span class=\"tel\"><span>+966 🇸🇦</span><input id=\"am-service-phone\" name=\"phone\" type=\"tel\" required autocomplete=\"tel-national\" inputmode=\"tel\" placeholder=\"5XXXXXXXX\"></span></label><label>نوع الطلب *<select name=\"kind\" required><option value=\"\">-- اختر طلبك --</option><option>تغيير فلاتر</option><option>صيانة دورية</option><option>فك وتركيب</option><option>تركيب فقط</option><option>معاينة فقط</option><option>طلب قطعة</option></select></label><label>ملاحظات<textarea name=\"notes\" maxlength=\"1000\" placeholder=\"اكتب هنا....\"></textarea></label><button type=\"submit\">متابعة على واتساب</button></form>";
    const city = d.querySelector('[name="city"]');
    const otherCity = d.querySelector('[name="otherCity"]');
    city.addEventListener('change', () => {
      const custom = city.value === 'other';
      otherCity.disabled = !custom;
      otherCity.closest('label').hidden = !custom;
      if (custom) otherCity.focus();
    });
    d.querySelector('.dismiss').onclick=()=>d.close();
    d.addEventListener('click',event=>{if(event.target===d){const r=d.getBoundingClientRect();if(event.clientX<r.left||event.clientX>r.right||event.clientY<r.top||event.clientY>r.bottom)d.close()}});
    const phone=d.querySelector('[name="phone"]');phone.oninput=()=>phone.setCustomValidity('');
    d.querySelector('form').onsubmit=function handle(event){event.preventDefault();const fields=event.currentTarget.elements;const national=fields.phone.value.trim().replace(/[٠-٩]/g,c=>String(c.charCodeAt(0)-1632)).replace(/[۰-۹]/g,c=>String(c.charCodeAt(0)-1776)).replace(/[\s-]/g,'').replace(/^(?:\+966|00966|966|0)/,'');if(!/^5\d{8}$/.test(national)){fields.phone.setCustomValidity('أدخل رقم جوال سعوديًا يبدأ بـ 05 ويتكوّن من 10 أرقام.');fields.phone.reportValidity();return}if(complaint&&!fields.notes.value.trim()){fields.notes.setCustomValidity('اكتب تفاصيل البلاغ أو الشكوى');fields.notes.reportValidity();return}const lines=complaint?['البلاغات والشكاوى','نوع الطلب: '+fields.kind.value,'الاسم: '+fields.fullName.value.trim(),'الجوال: +966'+national]:['طلب خدمة من المعالج','الاسم: '+fields.fullName.value.trim(),'المدينة: '+(fields.city.value==='other'?fields.otherCity.value:fields.city.value).trim(),'الحي: '+fields.district.value.trim(),'الجوال: +966'+national,'نوع الطلب: '+fields.kind.value];if(fields.notes.value.trim())lines.push('ملاحظات: '+fields.notes.value.trim());const url=new URL('https://wa.me/966533557999');url.searchParams.set('text',lines.join('\n'));window.open(url.href,'_blank','noopener,noreferrer')};
    if(complaint)configureComplaint(d);document.body.append(d);return d;
  }
  document.addEventListener('click',event=>{if(event.target.closest('#am-complaints,[data-am-request=complaint]')&&!event.ctrlKey&&!event.metaKey&&!event.shiftKey&&window.HTMLDialogElement){event.preventDefault();complaintDialog=complaintDialog||build(true);if(!complaintDialog.open)complaintDialog.showModal();return}const urgent=!!event.target.closest("#am-urgent-request,[data-am-request=urgent]");if((!urgent&&!event.target.closest(trigger))||event.ctrlKey||event.metaKey||event.shiftKey||!window.HTMLDialogElement)return;event.preventDefault();dialog=dialog||build();const kind=dialog.querySelector('[name="kind"]');let option=kind.querySelector('[data-urgent]');if(urgent){if(!option){option=new Option('صيانة عاجلة','صيانة عاجلة');option.dataset.urgent='1';kind.add(option)}kind.value=option.value}else if(option){if(kind.value===option.value)kind.value='';option.remove()}dialog.setAttribute('aria-label',urgent?'صيانة عاجلة':'طلب صيانة دورية');if(!dialog.open)dialog.showModal()});
})();
;(function(){if(!document.body.classList.contains("index"))return;function placeRequests(){const intro=document.querySelector('section[component-id="398096929"]');if(!intro)return false;const strip=document.createElement('div');strip.id='am-service-requests';strip.setAttribute('dir','rtl');strip.innerHTML='<h2>كيف نساعدك اليوم؟</h2><div class="am-requests-grid"></div>';const cards=[['maintenance','طلب صيانة','اختر صيانة دورية أو عاجلة لجهازك.','طلب صيانة'],['reminder','تذكير الصيانة','اختر موعد الصيانة القادم وأضف تذكيرًا إلى تقويمك.','جهّز تذكير الصيانة'],['complaint','البلاغات والشكاوى','عندك بلاغ أو شكوى؟ اكتب التفاصيل لفريق المعالج.','قدّم بلاغًا أو شكوى']];for(const [type,title,description,label] of cards){const card=document.createElement('article');card.innerHTML='<h3></h3><p></p><button type="button" aria-haspopup="dialog"></button>';card.children[0].textContent=title;card.children[1].textContent=description;card.children[2].textContent=label;card.children[2].dataset.amRequest=type;strip.lastElementChild.append(card)}for(const type of ['periodic','urgent']){const shortcut=document.createElement('button');shortcut.type='button';shortcut.hidden=true;shortcut.dataset.amRequest=type;strip.append(shortcut);}const style=document.createElement('style');style.textContent=`#am-service-requests article>button[data-am-request]{box-sizing:border-box;width:min(100%,180px)!important;min-height:48px!important;display:inline-flex;align-items:center;justify-content:center;text-align:center}section[component-id="398096929"]:has(#am-service-requests){height:auto!important;min-height:0!important;max-height:none!important;padding:0!important;background:none!important;display:block!important}section[component-id="398096929"]:has(#am-service-requests)::before,section[component-id="398096929"]:has(#am-service-requests)::after,section[component-id="1204252081"] salla-slider{display:none!important}#am-service-requests{max-width:1324px;margin:auto;padding:28px 22px;color:#102f58;text-align:right}#am-service-requests h2{text-align:center;font-size:26px;font-weight:700;margin:0 0 18px}.am-requests-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px}.am-requests-grid article{background:white;border:1px solid #cedff2;border-radius:12px;padding:24px;display:flex;flex-direction:column;align-items:flex-start;gap:14px}.am-requests-grid h3{font-size:21px;font-weight:700}.am-requests-grid p{color:#526981;line-height:1.8;margin-bottom:12px}.am-requests-grid button{margin-top:auto;background:#0656d9;border-radius:8px;color:white;font-weight:700;padding:10px 16px}@media(max-width:700px){#am-service-requests{padding:20px 12px}.am-requests-grid{grid-template-columns:1fr;gap:10px}.am-requests-grid article{padding:16px;gap:8px}.am-requests-grid p{margin:0}}`;document.head.append(style);style.textContent+='@media(min-width:701px){#am-service-requests .am-requests-grid{grid-template-columns:repeat(3,minmax(0,1fr))!important}} .am-maintenance-kind{direction:rtl;text-align:start;margin:auto;padding:24px;width:min(390px,calc(100% - 32px));border:1px solid #d8e4eb;border-radius:16px;background:white;color:#102f48;font-family:inherit}.am-maintenance-kind::backdrop{background:#102f4870}.am-maintenance-kind h3{font-size:21px;font-weight:700}.am-maintenance-kind p{margin:8px 0 16px}.am-kind-options{display:flex;gap:10px}.am-kind-options button{flex:1;min-height:46px;border:1px solid #ff896a;border-radius:9px;background:#fff3ee;color:#102f48;font-weight:700}.am-kind-options button:hover,.am-kind-options button:focus-visible{background:#ffc4b2}.am-kind-close{margin-block-start:16px;min-height:40px;color:#184564}';intro.replaceChildren(strip);return true}
if(!placeRequests()){const observer=new MutationObserver(()=>{if(placeRequests())observer.disconnect()});observer.observe(document.body,{childList:true,subtree:true})}})();
;(function mountSocialProfiles(){const accounts=[['TikTok','https://www.tiktok.com/@al_moalej?_r=1&_t=ZS-9AoixrO7H9x', '<path fill="none" stroke="currentColor" stroke-width="1.35" stroke-linejoin="round" d="M14 2h3c.3 3 2.1 4.8 5 5v3c-2-.1-3.7-.8-5-1.8v7.6a6.5 6.5 0 1 1-6.8-6.5v3.2a3.3 3.3 0 1 0 3.8 3.3z"/>'],['Instagram','https://www.instagram.com/almoalejest', '<g fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/></g><circle fill="currentColor" cx="17.5" cy="6.6" r="1.2"/>'],['Snapchat','https://www.snapchat.com/add/al_moalej?share_id=LnWT5uQSus8&locale=en-US', '<path fill="none" stroke="currentColor" stroke-width="1.35" stroke-linejoin="round" d="M12 2.6c-4.2 0-5.6 3.3-5.1 7.5-1.1.2-2.2-1-2.7.1-.3 1 1.6 1.5 2.4 2-.4 2.4-2.2 4.1-4.6 4.9.4 1.1 1.8 1.1 2.6 1.4l.6 1.5c1.1-.2 2-.5 2.9 0 1.4.8 2.4 1.5 3.9 1.5s2.5-.7 3.9-1.5c.9-.5 1.8-.2 2.9 0l.6-1.5c.8-.3 2.2-.3 2.6-1.4-2.4-.8-4.2-2.5-4.6-4.9.8-.5 2.7-1 2.4-2-.5-1.1-1.6.1-2.7-.1.5-4.2-.9-7.5-5.1-7.5z"/>'],['YouTube','https://youtube.com/@al_moalejest?si=1WI-sfm2ehfU5qj0', '<rect x="1" y="4.2" width="22" height="15.6" rx="4.5" fill="none" stroke="currentColor" stroke-width="1.8"/><path fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="1.5" d="m10 8 6 4-6 4z"/>']];function place(){const contacts=document.querySelector('footer salla-contacts');if(!contacts||!contacts.parentElement)return false;if(contacts.parentElement.querySelector('#am-social-profiles'))return true;const nav=document.createElement('nav');nav.id='am-social-profiles';nav.lang='ar';nav.setAttribute('aria-label','حسابات المعالج على منصات التواصل');nav.style.cssText='display:grid;gap:5px;margin-block-start:20px;direction:rtl;text-align:right';const heading=document.createElement('h4');heading.textContent='تابعنا على:';heading.style.cssText='color:#fff;font-size:17px;font-weight:700;line-height:1.65;margin:0 0 6px';nav.append(heading);for(const [name,url,glyph] of accounts){const a=document.createElement('a');a.lang='en';a.href=url;a.target='_blank';a.rel='noopener noreferrer';a.setAttribute('aria-label',name);a.title=name;a.style.cssText='display:flex;align-items:center;gap:10px;min-height:44px;font-size:16px;font-weight:600;line-height:1.5';const icon=document.createElement('span');icon.style.cssText='display:grid;place-items:center;width:40px;height:40px;flex:none';icon.innerHTML='<svg aria-hidden="true" width="23" height="23" viewBox="0 0 24 24" style="color:white">'+glyph+'</svg>';a.append(icon,document.createTextNode(name));nav.append(a)}contacts.after(nav);return true}if(!place()){const obs=new MutationObserver(()=>{if(place())obs.disconnect()});obs.observe(document.documentElement,{childList:true,subtree:true})}})();
;(() => {
  const placeVatNumber = () => {
    const badge = Array.from(document.querySelectorAll('footer .s-trust-badges-content')).find(el => el.querySelector('.s-trust-badges-label')?.textContent.trim() === 'السجل التجاري');
    if (!badge) return false;
    if (badge.querySelector('[data-am-vat]')) return true;
    const group = document.createElement('div');
    group.setAttribute('data-am-vat', '');
    group.style.marginBlockStart = '10px';
    const label = document.createElement('p');
    label.className = 's-trust-badges-label';
    label.textContent = 'الرقم الضريبي';
    const number = document.createElement('b');
    number.className = 's-trust-badges-number';
    number.dir = 'ltr';
    number.textContent = '300384718600003';
    group.append(label, number);
    badge.append(group);
    return true;
  };
  if (!placeVatNumber()) {
    const observer = new MutationObserver(() => { if (placeVatNumber()) observer.disconnect(); });
    observer.observe(document.documentElement, {childList:true, subtree:true});
  }
})();
;(() => {
  function placeCompanyLogo() {
    const vat = document.querySelector('footer [data-am-vat]');
    if (!vat) return false;
    if (vat.querySelector('[data-am-company-logo]')) return true;
    const logo = document.createElement('img');
    logo.setAttribute('data-am-company-logo','');
    logo.alt = 'شعار المعالج لوحدات تحلية المياه';
    logo.src = 'https://cdn.files.salla.network/other/609952933/6d2b5ec2-8ba3-4bcb-b25d-9d66b72c007c-original.webp';
    logo.width = 100;
    logo.height = 96;
    logo.style.cssText = 'display:block;object-fit:contain;width:100px;height:96px;max-width:100%;box-sizing:border-box;padding:6px;margin-block-start:12px;background:white;border-radius:10px';
    vat.append(logo);
    return true;
  }
  if (!placeCompanyLogo()) {
    const observer = new MutationObserver(() => { if (placeCompanyLogo()) observer.disconnect(); });
    observer.observe(document.documentElement,{childList:true,subtree:true});
  }
})();
;(() => {
  function positionFooterLogo() {
    const logo = document.querySelector('footer [data-am-company-logo]');
    const titleLink = document.querySelector('footer a:has(> h3)');
    if (!logo || !titleLink) return false;
    logo.style.marginBlock = '0 14px';
    logo.style.marginInline = '0 auto';
    titleLink.before(logo);
    return true;
  }
  if (!positionFooterLogo()) {
    const observer = new MutationObserver(() => { if (positionFooterLogo()) observer.disconnect(); });
    observer.observe(document.documentElement, {childList:true,subtree:true});
  }
})();
/* Merchant identity below the payment methods */
(()=>{
  function showMerchantIdentity(){
    const footer=document.querySelector('footer.store-footer');
    if(!footer||footer.querySelector('.am-merchant-signature'))return;
    const signature=document.createElement('div');signature.className='am-merchant-signature';signature.dir='rtl';signature.style.cssText='padding:12px 16px 16px;text-align:center;color:white;background:#102e50;border-top:1px solid #ffffff26;font:inherit;line-height:1.9;font-size:13px';
    signature.innerHTML='<p style="margin:0;font-weight:700"><span>مؤسسة المعالج للتجارة</span> · <span style="display:inline-block">السجل التجاري <bdi>7006362508</bdi></span> · <span style="display:inline-block">الرقم الضريبي <bdi>300384718600003</bdi></span></p><p style="margin:2px 0 0">© '+new Date().getFullYear()+' جميع الحقوق محفوظة لمؤسسة المعالج للتجارة</p>';
    footer.append(signature);
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',showMerchantIdentity,{once:true});else showMerchantIdentity();
  document.addEventListener('salla:page-loaded',showMerchantIdentity);
})();
/* Almoalej single-page gift form */
(function installGiftPage(markup){if(!/\/page-663889449\/?$/.test(location.pathname))return;const formId='am-gift-order';function mount(){const host=document.querySelector('#main-content .content-entry');if(!host||document.getElementById(formId))return;const form=document.createElement('form');form.id=formId;form.method='post';form.innerHTML=markup;host.replaceChildren(form)}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mount,{once:true});else mount();let revision=0;document.addEventListener('change',async e=>{const f=e.target.closest('#'+formId);if(!f)return;const select=f.elements.namedItem('id'),status=f.querySelector('[role=status]');if(e.target.name==='kind'){const rev=++revision;f.querySelector("[type=submit]").disabled=true;select.replaceChildren(new Option('اختر المنتج',''));if(!e.target.value)return;status.textContent='جارٍ تحميل المنتجات…';try{const seen=new Set();let page=1;while(true){const r=await salla.product.fetch({source:'categories',source_value:[Number(e.target.value)],page,per_page:50});if(rev!==revision)return;const products=Array.isArray(r.data)?r.data:r.data?.data||[];let added=0;for(const p of products){if(seen.has(p.id))continue;seen.add(p.id);added++;const o=new Option(p.name,String(p.id));o.disabled=!!p.is_out_of_stock;o.dataset.url=new URL("/p"+p.id,location.origin).href;if(p.url){const canonical=new URL(p.url,location.origin);if(canonical.origin===location.origin)o.dataset.url=canonical.href}select.add(o)}if(!added||page>=Number(r.pagination?.totalPages||r.pagination?.total_pages||1))break;page++}status.textContent=seen.size?'':'لا توجد منتجات في هذا التصنيف الآن.'}catch{if(rev===revision)status.textContent='تعذر تحميل المنتجات. أعد اختيار التصنيف.'}}else if(e.target===select){f.querySelector('[type=submit]').disabled=!select.value}},true);document.addEventListener('submit',e=>{const f=e.target;if(f.getAttribute('id')!==formId)return;e.preventDefault();const option=f.elements.namedItem('id').selectedOptions[0];if(option?.dataset.url)location.assign(option.dataset.url+'#am-product-gift')},true)})("<style>#am-gift-order{direction:rtl;margin:18px 0;padding:clamp(16px,3vw,28px);border:1px solid #bed6e1;border-radius:18px;background:#f4fafc;color:#123250}#am-gift-order fieldset{padding:0;border:0;margin:16px 0;min-width:0}#am-gift-order legend{font-size:1.1rem;font-weight:700;margin-bottom:8px}#am-gift-order .gift-fields{display:grid;gap:10px;grid-template-columns:repeat(auto-fit,minmax(min(100%,175px),1fr))}#am-gift-order label{display:grid;gap:4px;font-size:.94rem}#am-gift-order :is(input,select,textarea){width:100%;background:white;color:#123250;border:1px solid #aac4d0;border-radius:8px;padding:9px;font:inherit}#am-gift-order button{background:#123b60;color:white;border-radius:9px;padding:10px 20px;margin-top:12px}#am-gift-order small{display:block;margin:8px 0}#am-gift-order [role=status]{margin-top:9px}</style><h2>تفاصيل هديتك</h2><fieldset><legend>اختيار الهدية</legend><div class=\"gift-fields\"><label>نوع الهدية<select name=\"kind\" required><option value=\"\">اختر النوع</option><option value=\"146247215\">عروض الأجهزة مع البرادات</option><option value=\"463435319\">أجهزة التحلية</option><option value=\"1969591600\">أجهزة تحلية النانو</option><option value=\"1796286755\">البرادات</option><option value=\"564944693\">الفلاتر</option><option value=\"598060327\">عروض الفلاتر</option><option value=\"288346930\">فلاتر التصفية المركزية</option><option value=\"1195553841\">فلاتر التصفية الصغيرة</option><option value=\"1472671796\">فلاتر الشاور</option></select></label><label>المنتج<select name=\"id\" required><option value=\"\">اختر المنتج</option></select></label></div></fieldset><small>اختر اللون أو الشكل المتاح في صفحة المنتج، ثم اضغط «أرسل كهدية» لاختيار البطاقة وإدخال بيانات المتلقي.</small><button type=\"submit\" disabled>متابعة إلى المنتج للإهداء</button><div role=\"status\" aria-live=\"polite\"></div>");
if(location.hash==='#am-product-gift'){ const focusGift=()=>{const widget=document.querySelector('salla-gifting'); if(widget){const options=document.querySelector('salla-product-options');(options||widget).scrollIntoView({block:'center'});return true;}return false;};window.addEventListener('load',focusGift,{once:true}); }
;(() => {
  function start() {
    const row = document.querySelector('header.store-header #mainnav .inner');
    if (!row) return;
    const controls = '.main-menu > li > a[data-am-current], #am-header-category-item button, #am-categories-trigger';
    const category = /\/c\d+\/?$/.test(location.pathname);
    const hover = matchMedia('(hover:hover) and (pointer:fine)');
    let frame = 0;
    function paint() {
      frame = 0;
      const images = [], sizes = [], offsets = [];
      const left = row.getBoundingClientRect().left + row.clientLeft;
      for (const tab of row.querySelectorAll(controls)) {
        const selected = tab.matches('[data-am-current="true"], [aria-current="page"], [aria-expanded="true"], :active, :focus-visible') || (hover.matches && tab.matches(':hover')) || (category && tab.matches('#am-header-category-item button'));
        if (!selected || !tab.offsetWidth) continue;
        const rect = tab.getBoundingClientRect();
        const x = Math.max(0, rect.left - left);
        const width = Math.min(row.clientWidth, rect.right - left) - x;
        if (width <= 0) continue;
        const line = Math.round(width * .68);
        images.push('linear-gradient(#8adfff,#8adfff)', 'linear-gradient(#214763,#214763)');
        sizes.push(line+'px 3px',width+'px 100%');
        offsets.push((x+(width-line)/2)+'px bottom',x+'px top');
      }
      row.style.setProperty('--am-row-images',images.join(',') || 'none');
      row.style.setProperty('--am-row-sizes',sizes.join(',') || 'auto');
      row.style.setProperty('--am-row-offsets',offsets.join(',') || '0 0');
      if (!row.classList.contains('am-row-tabs')) row.classList.add('am-row-tabs');
    }
    function schedule() { if (!frame) frame = requestAnimationFrame(paint); }
    for (const type of ['pointerover','pointerout','pointerdown','pointerup','pointercancel','focusin','focusout']) row.addEventListener(type,schedule);
    new ResizeObserver(schedule).observe(row);
    new MutationObserver(schedule).observe(row,{subtree:true, childList:true, attributes:true, attributeFilter:['class','aria-current','aria-expanded','data-am-current']});
    window.addEventListener('resize',schedule,{passive:true});
    document.fonts?.ready.then(schedule);
    paint();
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded',start,{once:true}); else start();
})();

/* Display Western digits in storefront text, including dynamically rendered prices. */
;(() => {
  const digits = /[٠-٩۰-۹]/g;
  const normalize = text => text.replace(digits, digit => String(digit.charCodeAt(0) % 16));
  const ignored = 'script,style,template,noscript,textarea,[contenteditable]:not([contenteditable="false"])';
  const attrs = ['aria-label','aria-valuetext','aria-description','alt','title','placeholder','label'];
  const roots = new WeakSet();
  function isIgnored(el) { return !el || !!el.closest(ignored); }
  function textNode(node) {
    if (isIgnored(node.parentElement)) return;
    const next = normalize(node.data);
    if (next !== node.data) node.data = next;
  }
  function attribute(el, name) {
    const value = el.getAttribute(name);
    if (!value) return;
    const next = normalize(value);
    if (next !== value) el.setAttribute(name,next);
  }
  function element(el) {
    for (const name of attrs) if (el.hasAttribute(name)) attribute(el,name);
    if (el.shadowRoot) watch(el.shadowRoot);
  }
  function scan(node) {
    if (node.nodeType === 3) { textNode(node); return; }
    if (node.nodeType !== 1 && node.nodeType !== 11) return;
    if (node.nodeType === 1) { if (isIgnored(node)) return; element(node); }
    const walk = document.createTreeWalker(node, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {acceptNode: child => child.nodeType === 1 && child.matches(ignored) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT});
    for (let child = walk.nextNode(); child; child = walk.nextNode()) {
      if (child.nodeType === 3) textNode(child); else element(child);
    }
  }
  function watch(root) {
    if (roots.has(root)) return;
    roots.add(root);
    new MutationObserver(records => {
      for (const record of records) {
        if (record.type === 'attributes') { if (!isIgnored(record.target)) attribute(record.target,record.attributeName); }
        else if (record.type === 'characterData') textNode(record.target);
        else for (const child of record.addedNodes) scan(child);
      }
    }).observe(root,{subtree:true,childList:true,characterData:true,attributes:true,attributeFilter:attrs});
    scan(root);
  }
  if (document.body) watch(document.body); else document.addEventListener('DOMContentLoaded',() => watch(document.body),{once:true});
})();
/* Keep the storefront profile in the customer navigation. */
;(() => {
  const selector = 'a.s-user-menu-dropdown-item-link[href*="accounts.salla.com"]';
  function update(link) {
    const url = new URL(link.href);
    if (url.hostname !== 'accounts.salla.com' || !/^\/(?:[a-z]{2}\/)?profile\/?$/.test(url.pathname)) return;
    link.setAttribute('href', '/account/profile');
    link.removeAttribute('target');
  }
  function scan(node) {
    if (node.nodeType !== 1) return;
    if (node.matches(selector)) update(node);
    node.querySelectorAll(selector).forEach(update);
  }
  scan(document.documentElement);
  new MutationObserver(records => {
    for (const record of records) {
      if (record.type === 'attributes') { if (record.target.matches(selector)) update(record.target); }
      else record.addedNodes.forEach(scan);
    }
  }).observe(document.documentElement, {subtree:true, childList:true, attributes:true, attributeFilter:['href']});
})();

;window.addEventListener('click', function openStoreProfile(event) {
  const link = event.composedPath().find(node => node instanceof HTMLAnchorElement && node.matches('a.s-user-menu-dropdown-item-link'));
  if (!link || link.origin !== location.origin || link.pathname !== '/account/profile') return;
  event.stopImmediatePropagation();
  if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || event.button !== 0) return;
  event.preventDefault();
  location.assign(link.href);
}, true);

;(() => {
  if (location.pathname.replace(/\/$/, '') !== '/account/profile') return;
  function setupOptionalFields() {
    const form = document.querySelector('.form--user-profile');
    if (!form) return;
    function updateFields() {
      for (const field of form.querySelectorAll('[name="birthday"], [name="gender"]')) {
        field.removeAttribute('required');
        field.removeAttribute('aria-required');
      }
      for (const label of form.querySelectorAll('label')) {
        if (/^(تاريخ الميلاد|الجنس)$/.test(label.textContent.trim())) label.append(' (اختياري)');
      }
    }
    updateFields();
    new MutationObserver(updateFields).observe(form, {subtree: true, childList: true, attributes: true, attributeFilter: ['required']});
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', setupOptionalFields, {once: true});
  else setupOptionalFields();
})();

;(() => {
  if (location.pathname.replace(/\/$/, '') !== '/account/profile') return;
  document.addEventListener('formdata', event => {
    if (!event.target.matches('.form--user-profile')) return;
    for (const key of ['birthday', 'gender']) {
      if (event.formData.get(key) === '') event.formData.delete(key);
    }
  }, true);
})();
;(() => {
 const phone='+966533557999';
 const legacy=/(?:\+?966|0)\s*(?:13\s*581\s*(?:4939|2481)|56\s*264\s*7239)/g;
 const observed=new WeakSet();
 function update(a){
  if(a.closest('.am-footer-branches,.am-footer-branch-panel,[class*="branch-map"],[id*="branch-map"]')) return;
  const raw=a.getAttribute('href')||'';
  if(!/^(?:tel:|https?:\/\/(?:wa\.me\/|api\.whatsapp\.com\/send))/i.test(raw))return;
  const url=new URL(raw,location.href);const dest=url.protocol==='tel:'?url.pathname:url.hostname==='wa.me'?url.pathname.slice(1):url.searchParams.get('phone');
  if(!['966135814939','0135814939','966562647239','0562647239','966135812481','0135812481','966533557999','0533557999'].includes((dest||'').replace(/[^0-9]/g,'')))return;
  if(url.protocol==='tel:')url.pathname=phone;else if(url.hostname==='wa.me')url.pathname=phone.slice(1);else url.searchParams.set('phone',phone.slice(1));
  const target=url.protocol==='tel:'?'tel:'+phone:url.href;if(target!==raw)a.setAttribute('href',target);
  const replace=s=>s.replace(legacy,phone).replace(/(?<![+0-9])(?:0533557999|966533557999)(?![0-9])/g,phone);
  for(const attr of ['aria-label','title']){const v=a.getAttribute(attr);if(v&&v!==replace(v))a.setAttribute(attr,replace(v));}
  const walker=document.createTreeWalker(a,NodeFilter.SHOW_TEXT);let node;while(node=walker.nextNode()){const v=replace(node.data);if(v!==node.data)node.data=v;}
 }
 function scan(el){if(el.matches?.('a[href]'))update(el);el.querySelectorAll?.('a[href^="tel:"],a[href*="wa.me/"],a[href*="api.whatsapp.com/send"]').forEach(update);for(const host of el.querySelectorAll?.('salla-contacts,[component-id]>:first-child')||[])if(host.shadowRoot)watch(host.shadowRoot);if(el.shadowRoot)watch(el.shadowRoot);}
 function watch(root){if(observed.has(root))return;observed.add(root);scan(root);new MutationObserver(records=>{for(const r of records){if(r.type==='attributes')update(r.target);else{const a=r.target.closest?.('a[href]');if(a)update(a);for(const n of r.addedNodes)if(n.nodeType===1)scan(n);}}}).observe(root,{childList:true,subtree:true,attributes:true,attributeFilter:['href']});}
 if(document.body)watch(document.body);else document.addEventListener('DOMContentLoaded',()=>watch(document.body),{once:true});
})();
;(() => {
  function insertReturnLink(menu) {
    for (const orderLink of menu.querySelectorAll('li > a[href$="/account/orders"]')) {
      const row = orderLink.parentElement;
      if (row.parentElement.querySelector('.am-return-menu-item')) continue;
      const item = document.createElement('li');
      item.className = 's-user-menu-dropdown-item am-return-menu-item';
      const link = document.createElement('a');
      link.href = '/طلب-استرجاع-أو-استبدال/page-834161675';
      link.className = 's-user-menu-dropdown-item-link';
      link.innerHTML = '<i class="s-user-menu-dropdown-item-prefix" aria-hidden="true"><svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 10h10a5 5 0 0 1 0 10h-3M4 10l5-5M4 10l5 5"/></svg></i><span class="s-user-menu-dropdown-item-title">الاسترجاع والاستبدال</span>';
      item.append(link);
      row.after(item);
    }
  }
  function init() {
    document.querySelectorAll('salla-user-menu').forEach(menu => {
      insertReturnLink(menu);
      new MutationObserver(() => insertReturnLink(menu)).observe(menu,{childList:true,subtree:true});
    });
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, {once:true});
  else init();
})();
;(() => {
  const routes = { maintenance: 'maintenance.html', periodic: 'maintenance.html?kind=periodic', urgent: 'maintenance.html?kind=urgent', complaint: 'complaint.html' };
  window.addEventListener('click', event => {
    const button = event.target.closest?.('#am-service-requests button[data-am-request]');
    const kind = button && routes[button.dataset.amRequest];
    if (!kind) return;
    event.preventDefault();
    event.stopImmediatePropagation();
    try { sessionStorage.setItem('am-form-back', JSON.stringify({y: scrollY, url: location.href})); } catch {}
    location.assign('https://returns.almoalej.com/' + kind);
  }, true);
})();
;(() => {
  const field = 'amFormOrigin';
  function remember(event) {
    if (event.type === 'keydown' && !['Enter', ' '].includes(event.key)) return;
    const node = event.composedPath().find(el => el.matches?.('#am-service-requests [data-am-request="periodic"], #am-service-requests [data-am-request="urgent"], a[href*="page-834161675"], a[href*="/maintenance.html"]'));
    if (!node || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
    try {sessionStorage.setItem('am-form-back', JSON.stringify({y: scrollY, url: location.href}));} catch {} 
  }
  for (const type of ['pointerdown','keydown','click']) window.addEventListener(type, remember, true);
  function restore() {
    let pos; try {pos=JSON.parse(sessionStorage.getItem('am-form-back'));} catch {} 
    if (!pos || pos.url !== location.href) return;
    sessionStorage.removeItem('am-form-back');
    const controller = new AbortController();
    for (const type of ['wheel','touchstart','pointerdown','keydown','pagehide']) window.addEventListener(type, () => controller.abort(), {once:true, passive:true, signal:controller.signal});
    const end=performance.now()+1600;
    function place() {
      if (controller.signal.aborted) return;
      if (Math.abs(scrollY-pos.y)>1) window.scrollTo({top:pos.y,behavior:'instant'});
      if(performance.now()<end) requestAnimationFrame(place); else controller.abort();
    }
    requestAnimationFrame(place);
  }
  window.addEventListener('pageshow', e => {if(e.persisted || performance.getEntriesByType('navigation')[0]?.type==='back_forward') restore();});
  restore();
  window.addEventListener('message', event => {
    const frame = document.querySelector('.am-returns-mobile iframe');
    if (!frame || event.origin!=='https://returns.almoalej.com' || event.source!==frame.contentWindow || event.data!=='am-close-service-form') return;
    if (document.referrer && new URL(document.referrer).origin===location.origin && history.length>1) history.back();
    else location.assign('/#am-service-requests');
  });
})();
;(() => {
  const id = location.pathname.match(/\/p(\d+)\/?$/)?.[1];
  if (!id) return;
  function installDeviceLinks() {
    const title = document.querySelector('main h1');
    const name = title?.textContent.trim();
    if (!name || !/جهاز تحلية|برادة|محطة تحلية|هاوس|صانعة ثلج|جهاز نانو/.test(name) || /باقة صيانة|فلتر استبدال/.test(name)) return;
    const photo = document.querySelector('meta[property="og:image"]')?.content;
    function destination(kind) {
      const url = new URL('https://returns.almoalej.com/maintenance.html');
      url.searchParams.set('kind', kind);
      url.searchParams.set('product_id', id);
      url.searchParams.set('product_name', name);
      if (photo) url.searchParams.set('product_image', photo);
      return url.href;
    }
    if (document.getElementById('am-device-service-links')) return;
    const row = document.createElement('nav');
    row.id = 'am-device-service-links';
    row.setAttribute('aria-label','صيانة هذا الجهاز');
    row.style.cssText='display:flex;flex-wrap:wrap;gap:8px;margin:8px 0 16px';
    for (const [kind,label] of [['periodic','صيانة دورية لهذا الجهاز'],['urgent','صيانة عاجلة لهذا الجهاز']]) {
      const link = document.createElement('a');
      link.href = destination(kind);
      link.textContent = label;
      link.style.cssText='padding:8px 12px;border:1px solid #c9dfda;border-radius:8px;color:#123450;font-weight:700;background:white';
      row.append(link);
    }
    title.after(row);
    window.addEventListener('click', event => {
      const link = event.target.closest?.('a[href]');
      const kind = link?.hash.match(/^#store-service-(urgent|periodic)$/)?.[1];
      if (!kind || link.origin !== location.origin) return;
      event.preventDefault(); event.stopImmediatePropagation(); location.assign(destination(kind));
    },true);
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded',installDeviceLinks,{once:true});
  else installDeviceLinks();
})();
;(() => {
  if (location.pathname !== '/account/orders' || !new URLSearchParams(location.search).has('maintenance-devices')) return;
  const script = document.createElement('script');
  script.src = 'https://returns.almoalej.com/purchased-devices.js?v=1';
  document.head.append(script);
})();
;(() => { const script = document.createElement("script"); script.src = "https://returns.almoalej.com/customer-maintenance.js?v=2"; document.head.append(script); })();
;(() => {
  'use strict';
  const preview = location.protocol === 'file:' || location.hostname === 'localhost';
  if ((!preview && !['almoalej.com','www.almoalej.com','store.almoalej.com'].includes(location.hostname)) || document.getElementById('almoalej-shop-guide')) return;
  const entries = [["746108227","فلتر استبدال لجهاز الجيك - 4 في 1","فلتر استبدال لجهاز الجيك بتصميم 4 في 1، بهيكل أبيض وأطراف زرقاء.",null],["827775456","باقة صيانة محطة تحلية 400 جالون لمدة 4 سنوات – 8 زيارات","",2499],["1073719279","باقة صيانة محطة تحلية 400 جالون لمدة سنتين – 4 زيارات","",1399],["973824823","باقة صيانة محطة تحلية 200 جالون لمدة 4 سنوات – 8 زيارات","",1999],["15784432","باقة صيانة محطة تحلية 200 جالون لمدة سنتين – 4 زيارات","",1099],["306995717","باقة صيانة فلاتر كومباكت نانو 12 بوصة – سنتان، 4 زيارات","",585],["940572209","باقة صيانة فلاتر كومباكت نانو 12 بوصة – 4 سنوات، 8 زيارات","",1320],["1439515426","وصلة حساوي زاوية بسن خارجي","",15],["1217068773","وصلة حساوي مستقيمة بسن داخلي","",15],["1056767614","جهاز قياس حموضة المياه pH – أصفر","مقياس (PH) ضمن أدوات القياس المتوفرة لدى متجر المعالج",59],["1603079366","فلتر شاور بمروحة زرقاء","فلتر شاور من مجموعة المعالج، بمروحة زرقاء داخل رأس شفاف ومقبض بلمسة فضية لامعة",59],["1391339356","فلتر شاور بمروحة ذهبية","يُحسّن تدفق الماء ويمنحك تجربة استحمام مريحة مع مروحة ذهبية أنيقة",59],["1460770523","ربلة لهاوس فلاتر 10 بوصات","قطعة غيار أصلية من ربلة هاوس مقاس 10 انش لاستبدال القطع التالفة في الأجهزة",3],["88831962","ربلة لهاوس فلاتر جامبو 20 بوصة – سوداء","توفر لك ربلة هاوس جامبو حماية فعالة من التسريب والتآكل في الأجهزة المختلفة",5],["728656089","صنبور مياه (بزبوز) ملكي – كروم","صنبور مياه معدني بتصميم أنيق وعصري يناسب جميع أنواع الأجهزة",59],["1501645272","هوز توصيل مياه 1/4 بوصة – 5 أمتار","أنبوب هوز مرن ومقاوم للتآكل، مثالي لتوصيل المياه في الأجهزة المنزلية",10],["262417119","صنبور مياه (بزبوز) كروم بتفاصيل ذهبية","صنبور مياه بتصميم منحني، بلون كروم لامع مع تفاصيل ذهبية، كما يظهر في صور المنتج",59],["1038027742","هوز توصيل مياه 3/8 بوصة – 5 أمتار","أنبوب هوز مرن ومقاوم للتآكل، مثالي لتوصيل المياه في الأجهزة المنزلية",15],["1676864733","مفتاح لهاوس فلاتر جامبو 20 بوصة","أداة مفتاح هاوس جامبو مقاس 20 انش مصممة خصيصاً لصيانة الفلاتر",29],["370527708","جهاز قياس حموضة المياه pH – أحمر","مقياس (PH) ضمن أدوات القياس المتوفرة لدى متجر المعالج",59],["1145614035","مفتاح لهاوس فلاتر 10 بوصات","أداة مساعدة لفتح وإغلاق هاوسات الفلاتر بسهولة",23],["1784909778","جهاز قياس الأملاح الذائبة في المياه TDS","مقياس أملاح (TDS) ضمن أدوات القياس المتوفرة لدى متجر المعالج",59],["411394257","ريزين تبادل أيوني INDION 225 Na – 25 لتر","رزن إنديون للتبادل الأيوني الكاتيوني الحمضي القوي (SAC) مصمم خصيصاً لمنظومات تليين المياه",399],["1320698320","خزان ملح لتليين المياه – 60 لتر","خزان ملح سعة 60 لتر مخصص لمنظومات تليين المياه",699],["2094211799","رأس تحكم أوتوماتيكي لخزان معالجة المياه – أسود","جهاز تحكم إلكتروني أوتوماتيكي لإدارة وتشغيل خزان معالجة المياه بكفاءة",1989],["586548182","خزان معالجة مياه FRP (فزل) – 12 × 52 بوصة","خزان فايبر جلاسFRP بمقاس12×52 إنش: قطر12 إنش وارتفاع52 إنش",749],["1361700053","هاوس فلتر مياه 10 بوصات – شفاف بغطاء أبيض","فلتر مياه هاوس شفاف مقاس 10 انش، مناسب لتجهيز وتنظيف الفلاتر",59],["122471892","هاوس فلتر مياه 10 بوصات – أسود","فلتر هاوس أسود اللون بتصميم عملي ومدمج مع الأجهزة",59],["895985355","هاوس فلتر مياه 10 بوصات – أزرق","فلتر هاوس أزرق اللون مخصص لتنقية المياه في أجهزة المعالجة",59],["1536853962","هاوس فلتر مياه 10 بوصات – أبيض","قطعة غيار أصلية من هاوس، مقاس 10 انش، مناسبة لتجهيزات المعالج",59],["163346633","هاوس ممبرين للتحلية – أبيض","هاوس ممبرين أبيض مع توصيلات جانبية، يُستخدم كقطعة غيار في أنظمة التناضح العكسي",59],["1071077832","خزان مياه – 22 جالون","خزان مياه سعة 22 جالون مصمم لتخزين المياه بكفاءة",549],["1644837583","خزان مياه للتحلية – 5 جالونات","خزان مياه عاكس للضغط (Pressure Vessel) بسعة 5 جالون لزيادة كفاءة أنظمة التناضح العكسي",149],["271391694","خزان مياه للتحلية – 11 جالون","خزان مياه بسعة 11 جالون لتخزين المياه بكفاءة في منزلك أو محل العمل",399],["1178664141","غطاء برادة مياه مع عوامة","غطاء برادة ضمن مستلزمات الصيانة وقطع الغيار في متجر المعالج",59],["1954274764","قارورة تعبئة للبرادة مع عوامة – أزرق شفاف","قطعة غيار أساسية للبرادات لضمان تعبئة المياه بكفاءة",59],["446611139","محبس تغذية مياه 1/4 بوصة","صمام تحكم دقيق في تدفق المياه ضمن أنظمة التحلية",15],["1219600322","سدادة خزان ستيل","سدة خزان ستيل ضمن مستلزمات الصيانة وقطع الغيار في متجر المعالج",15],["2129359041","وصلة ستانلس ستيل – نصف بوصة","وصله ستانلس ستيل عالية الجودة لمختلف التطبيقات الصناعية والمنزلية",15],["755913152","وصلة خلاط ستيل","وصلة خلاط ستيل ضمن مستلزمات الصيانة وقطع الغيار في متجر المعالج",23],["1394684615","صمام مياه سولينويد 24 فولت DC – 5 واط","صمام مياه كهربائي من سنولايد يعمل بـ 24 فولت (DC24V) ليعمل بكفاءة مع الأجهزة المنزلية",35],["21238726","صمام مياه سولينويد دائري – 24 فولت","صمام سنولايد كهربائي يعمل بـ 24 فولت، مثالي لاستخدامات الصيانة وقطع الغيار",35],["931132613","صمام سولينويد JIA YI JY-3 – 220 فولت","صمام سولينويد للتحكم الكهربائي في مسار الماء بدقة عالية",179],["1704121796","محبس خزان بلاستيك 3/4 – مخرج 3/8","محبس تنك ضمن مستلزمات الصيانة وقطع الغيار في متجر المعالج",25],["196458235","محبس خلط بتحكم يدوي","قطعة معدنية مصممة للتحكم في تدفق السوائل أو الغازات داخل الأنظمة الصناعية",23],["971544570","محبس خزان بلاستيك 3/4 – مخرج 1/4","محبس تنك ضمن مستلزمات الصيانة وقطع الغيار في متجر المعالج",25],["304441848","صمام إغلاق تلقائي رباعي ASOV للتحلية","يُغلق الخزان التلقائي عند امتلائه لمنع التسرب أو الهدر",23],["1079528191","قطعة فلو تصريف – مقاس 3/8","قطعة غيار بيضاء بتصميم أنيق لسهولة التركيب والصيانة",23],["1987259390","لو برشر (Low Pressure)","قطعة لو برشر ضمن قطع غيار أجهزة المياه في متجر المعالج",23],["613813501","هاي برشر (High Pressure)","قطعة هاي برشر ضمن قطع غيار أجهزة المياه في متجر المعالج",23],["1254747644","محول طاقة كلاسيك بيور 36 فولت – 1.2 أمبير","محول طاقة CLASSIC PURE بمدخل 220 فولت وخرج 36 فولت، 1",89],["2028785395","محول طاقة كلاسيك بيور 24 فولت – 1.2 أمبير","يوفر لك جهد خرج ثابت 24 فولت تيار مستمر (DC) مع تيار أقصى 1",59],["789032946","مضخة كلاسيك بيور – 36 فولت","مضخة غشاء من Classic Pure لأنظمة معالجة المياه، بجهد DC 36 فولت",159],["1564115185","مضخة كلاسيك بيور – 24 فولت","مضخة غشاء من Classic Pure لأنظمة معالجة المياه، بجهد DC 24 فولت",139],["56386032","وحدة UV لتعقيم المياه – 12 واط","وحدة تعقيم مياه إلكترونية كاملة من الترا فايلوت لتطهير المياه بفعالية",149],["829899511","ممبرين تحلية مياه – 300 جالون","فلتر عكسي أوزموسيس أمريكي سعة 300 جالون لإزالة الشوائب والملوثات من الماء",199],["365757685","ممبرين تحلية مياه – 100 جالون","فلتر تنقية مياه أمريكي من مجموعة الفلاتر في متجر المعالج",149],["1004594676","فلتر بوست كاربون T33 – US Water System","يوفر هذا الفلتر نهائياً طعم الماء الطبيعي ويحسّن من نكهته قبل الشرب",69],["1847314155","فلتر GAC كلاسيك بيور – أبيض","فلتر مياه أبيض من نوع GAC لتنقية المياه وإزالة الشوائب والكلور",59],["473868266","فلتر قلوي (ألكالاين) pH","يُعدّ فلتر الكلاين (PH) المرحلة المخصصة لضبط قلوية الماء ضمن منظومة الفلاتر",79],["1112643817","فلتر مينرال 4 × 1 – كلاسيك بيور","يضيف المعادن النافعة مثل الكالسيوم والمغنيسيوم إلى الماء ليعيد توازنه الطبيعي",79],["1888188904","ممبرين تحلية مياه Nittotic – 75 جالون","ممبرين نيتوليك لتحلية المياه، مصنف 75 جالون وفق بيانات المنتج",139],["648960751","فلتر GAC كلاسيك بيور أكوا سمارت – برتقالي","فلتر غشاء كربون نشط (GAC) من Classic Pure Aqua Smart لتنقية المياه",59],["1421949934","فلتر GAC كلاسيك بيور بلاك ستار – أزرق","فلتر تنقية مياه TAIWANESE GAC فلترة متقدمة لتنقية المياه",59],["2061769965","فلتر إنفراريد","فلتر سيراميك حيوي من نوع Bio-ceramic لتحسين جودة مياه الشرب",79],["689962476","فلتر GAC كلاسيك بيور بلاك هورس – أحمر","فلتر مياه احترافي من Classic Pure Black Horse مصنوع في تايوان",59],["1597169379","فلتر كربون حبيبي GAC كلاسيك بيور – أخضر","فلتر مينرال من CLASSIC PURE بهيكل أخضر، وفقًا لملصق MINERAL FILTER الظاهر على المنتج",59],["223723490","فلتر استبدال لجهاز الدايركت - 4 في 1","فلتر استبدال مخصص لجهاز الدايركت، يتكون من ستة مكونات: فلتر قطني بدقة 5 ميكرون، وأيونات الفضة، وحبيبات الكربون النشط، وفلتر…",99],["864588001","فلتر كربون حبيبي 12 بوصة - UDF","فلتر حبيبات كربون نشط مقاس12 إنش للبرادات",49],["1638035936","فلتر كربوني 12 بوصة - CTO","فلتر برادة كربوني 12 انش من مجموعة الفلاتر في متجر المعالج",49],["398807783","فلتر استبدال للجهاز الدائري – 4 في 1","فلتر استبدال مخصص للجهاز الدائري، يُستخدم بديلًا للفلتر الموجود داخل الجهاز",99],["1173894118","فلتر قطني 12 بوصة - PP","فلتر برادة قطني 12 انش من مجموعة الفلاتر في متجر المعالج",49],["1746080997","فلتر قطني 40 بوصة","فلتر قطنى 40 انش من مجموعة الفلاتر في متجر المعالج",49],["506918372","فلتر كربوني صلب 20 بوصة","فلتر كربوني صلب 20 انش من مجموعة الفلاتر في متجر المعالج",49],["1282004635","فلتر قطني 30 بوصة","فلتر قطني 30 انش من مجموعة الفلاتر في متجر المعالج",39],["1921824666","فلتر قطني 20 بوصة","فلتر قطني 20 انش من مجموعة الفلاتر في متجر المعالج",59],["547858585","فلتر كربون حبيبي UDF – 20 بوصة","فلتر حبيبات كربون نشط مقاس20 إنش، ضمن فلاتر المعالج",49],["1457162648","فلتر قطني جامبو 10 بوصة","فلتر قطني جامبو 10 انش من مجموعة الفلاتر في متجر المعالج",23],["83651231","فلتر بلوك جامبو 20 بوصة","فلتر بلوك جامبو 20 انش من مجموعة الفلاتر في متجر المعالج",69],["722946974","فلتر قطني جامبو 20 بوصة","فلتر قطني جامبو 20 انش من مجموعة الفلاتر في متجر المعالج",59],["1498033309","فلتر كربون حبيبي UDF – 10 بوصات","فلتر حبيبات كربون نشط مقاس10 إنش، ضمن فلاتر المعالج",23],["258805148","فلتر كربوني صلب 10 بوصة","فلتر كربوني صلب 10 انش من مجموعة الفلاتر في متجر المعالج",29],["1031859859","فلتر قطني 10 بوصة","فلتر قطني 10 انش من مجموعة الفلاتر في متجر المعالج",11.5],["1673252754","فلتر شاور مضيء","فلتر شاور مضيء من مجموعة المعالج",59],["299802769","فلتر شاور بمروحة فضية","فلتر شاور بمروحة من مجموعة المعالج",59],["1207009680","هاوس شوائب نانو","هاوس شوائب نانو، ضمن تجهيزات فلاتر التصفية الصغيرة في متجر المعالج",99],["1781228183","هاوس ثلاثي 10 بوصات – توصيل 1 بوصة","هاوس ثلاثي 10 انش 1 بوصة، ضمن تجهيزات فلاتر التصفية الصغيرة في متجر المعالج",199],["407782294","هاوس مفرد 10 بوصات – توصيل 1 بوصة","هاوس مفرد 10 انش 1 بوصة، ضمن تجهيزات فلاتر التصفية الصغيرة في متجر المعالج",99],["1314989205","هاوس فايبر 40 بوصة","هاوس فايبر 40 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",2199],["2089026964","هاوس فايبر 20 بوصة","هاوس فايبر 20 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",1499],["583001739","هاوس استيل 40 بوصة","هاوس استيل 40 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",2399],["1355990922","هاوس استيل 30 بوصة","هاوس استيل 30 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",2199],["116766857","هاوس استيل 20 بوصة","هاوس استيل 20 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",1699],["891853192","هاوس ثنائي جامبو 20 بوصة","هاوس ثنائي جامبو 20 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",649],["1531083407","هاوس ثلاثي جامبو 10 بوصة","هاوس ثلاثي جامبو 10 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",649],["157637518","هاوس ثلاثي جامبو 20 بوصة","هاوس ثلاثي جامبو 20 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",949],["1066941581","هاوس مفرد 20 بوصة","هاوس مفرد 20 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",149],["1840455052","هاوس مفرد جامبو 20 بوصة","هاوس مفرد جامبو 20 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",199],["332856963","هاوس مفرد جامبو 10 بوصة","هاوس مفرد جامبو 10 انش، ضمن تجهيزات فلاتر التصفية المركزية في متجر المعالج",149],["440897920","محطة تحلية 400 جالون – بدون خزان","جهاز تحلية بفئة 400 جالون، بإصدار بدون خزان، ضمن حلول المعالج للكافيهات والمطاعم",1849],["750204037","برادة مدمجة بصانعة ثلج","برادة مدمجة بصانعة ثلج، تجمع الوظيفتين في جهاز واحد",899],["1391072644","محطة تحلية 200 جالون – بدون خزان","جهاز تحلية بفئة 200 جالون، بإصدار بدون خزان، ضمن حلول المعالج للكافيهات والمطاعم",1399],["17692347","برادة مياه ذاتية التعبئة – فضي","برادة بنظام تعبئة ذاتية، ضمن خيارات البرادات في متجر المعالج",499],["924899258","برادة مياه ذاتية التعبئة – أسود","برادة بنظام تعبئة ذاتية، ضمن خيارات البرادات في متجر المعالج",499],["1700513977","برادة مياه نصفية – القارورة غير مشمولة","برادة بتبريد كمبرسور، بهيكل بلاستيكي وتغليف داخلي من الستانلس ستيل",299],["192850360","جهاز تحلية بجيك محمول","جهاز تحلية بتقنية النانو بإنتاجية 75 جالونًا يوميًا، مزود بفلتر 1×4 مكوّن من أربع طبقات، وخزان داخلي سعة 2 لتر وجيك محمول سعة 1",499],["965839551","برادة مياه ذاتية التعبئة – أبيض","برادة بنظام تعبئة ذاتية، ضمن خيارات البرادات في متجر المعالج",499],["1875602366","جهاز تحلية دايركت – 300 جالون بدون خزان","جهاز تحلية مياه بتقنية النانو من فئة 300 جالون، بست مراحل ترشيح ضمن فلتر مدمج وبدون خزان مياه",1599],["502156477","جهاز تحلية مياه دائري مع خزان","جهاز تحلية مياه منزلي بتصميم دائري وتقنية النانو، بفئة 75 جالونًا وسبع مراحل ترشيح ضمن فلتر مدمج",1099],["1073819068","جهاز تحلية بوكس مستطيل – واجهة رمادية","جهاز تحلية منزلي بخمس مراحل وبتصميم بوكس مستطيل، بفئة إنتاجية 75 جالون يوميًا",949],["1982074547","جهاز تحلية بوكس مستطيل – واجهة سوداء","جهاز تحلية منزلي بخمس مراحل وبتصميم بوكس مستطيل، بفئة إنتاجية 75 جالون يوميًا",949],["610267058","جهاز تحلية بوكس مستطيل – واجهة بيضاء","جهاز تحلية منزلي بخمس مراحل وبتصميم بوكس مستطيل، بفئة إنتاجية 75 جالون يوميًا",949],["1249034417","جهاز تحلية بوكس مربع – واجهة رمادية","جهاز تحلية منزلي بخمس مراحل وبتصميم بوكس مربع، بفئة إنتاجية 75 جالون يوميًا وخزان فايبر جلاس سعة 5 جالونات وحنفية ستانلس ستيل",949],["2023072176","جهاز تحلية بوكس مربع – واجهة سوداء","جهاز تحلية منزلي بخمس مراحل وبتصميم بوكس مربع، بفئة إنتاجية 75 جالون يوميًا وخزان فايبر جلاس سعة 5 جالونات وحنفية ستانلس ستيل",949],["784892599","جهاز تحلية بوكس مربع – واجهة بيضاء","جهاز تحلية منزلي بخمس مراحل وبتصميم بوكس مربع، بفئة إنتاجية 75 جالون يوميًا وخزان فايبر جلاس سعة 5 جالونات وحنفية ستانلس ستيل",949],["1558340534","جهاز تحلية بلاك ستار ستاند – 7 مراحل","جهاز بلاك ستار من مجموعة أجهزة التحلية المنزلية في متجر المعالج",649],["50676917","طقم فلاتر 20 بوصة – 400 جالون، 8 مراحل","مكون من طقم فلاتر 20 انش (3 مراحل) + فلتر بوست كاربون  + عدد 4 فلتر ممبرين 100 جالون ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",549],["825763252","جهاز تحلية بلاك هورس – 7 مراحل","جهاز بلاك هورس من مجموعة أجهزة التحلية المنزلية في متجر المعالج",499],["1733494443","جهاز تحلية أكوا سمارت – 7 مراحل","جهاز اكوا سمارت من مجموعة أجهزة التحلية المنزلية في متجر المعالج",499],["1000986793","جهاز تحلية كلاسيك بيور ستاند – 7 مراحل","جهاز كلاسيك بيور أستاند من مجموعة أجهزة التحلية المنزلية في متجر المعالج",599],["1775024552","جهاز تحلية المعالج – 7 مراحل","جهاز كلاسيك بيور من مجموعة أجهزة التحلية المنزلية في متجر المعالج",499],["535272111","طقم فلاتر برادة 12 بوصة – 4 مراحل","مكون من طقم فلاتر 12 انش (3 مراحل) + فلتر بوست كاربون ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",149],["1108966318","جهاز تحلية كلاسيك بيور – 7 مراحل","جهاز كلاسيك بيور من مجموعة أجهزة التحلية المنزلية في متجر المعالج",499],["1883004077","طقم فلاتر 20 بوصة – 3 مراحل","طقم فلاتر 20 انش (3 مراحل)، ضمن أطقم الفلاتر المتوفرة لدى المعالج",119],["643251628","طقم فلاتر 20 بوصة – 4 مراحل","مكون من طقم فلاتر 20 انش (3 مراحل) + فلتر بوست كاربون ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",219],["1418337955","باقة صيانة 5 سنوات – 10 زيارات","باقة صيانة لمدة 5 سنوات ، تشمل 10 زيارات بمعدل زيارة كل ستة أشهر",1320],["2058223522","طقم فلاتر جامبو 20 بوصة – 3 مراحل","طقم فلاتر جامبو 20 انش (3 مراحل)، ضمن أطقم الفلاتر المتوفرة لدى المعالج",149],["683724961","طقم فلاتر 10 بوصات – 6 مراحل","مكون من طقم فلاتر 10 انش (3 مراحل) + فلتر بوست كاربون + فلتر مينرال + فلتر ألكالين ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",199],["1593553312","باقة صيانة سنتين ونصف – 5 زيارات","باقة صيانة لمدة سنتين ونصف، تشمل خمس زيارات بمعدل زيارة كل ستة أشهر",585],["220107431","طقم فلاتر 10 بوصات – 7 مراحل","مكون من طقم فلاتر 10 انش (3 مراحل) + فلتر بوست كاربون + فلتر مينرال + فلتر ألكالين  + فلتر ممبرين، ضمن أطقم الفلاتر المتوفرة لدى المعالج",249],["1634423973","طقم فلاتر برادة 12 بوصة – 3 مراحل","طقم فلاتر برادة 12 انش (3 مراحل)، ضمن أطقم الفلاتر المتوفرة لدى المعالج",99],["395195812","طقم فلاتر 20 بوصة – 200 جالون، 6 مراحل","مكون من طقم فلاتر 20 انش (3 مراحل) + فلتر بوست كاربون  + عدد 2 فلتر ممبرين 100 جالون ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",399],["1168185179","طقم فلاتر 10 بوصات – 4 مراحل","مكون من طقم فلاتر 10 انش (3 مراحل) + فلتر بوست كاربون ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",99],["1808009306","عرض الفخامة – جهاز نانو تكنولوجي مع برادة ذاتية","تجميعة جهاز نانو تيكنولوجي مع برادة ذاتية التعبئة، ضمن عروض أجهزة المعالج",1249],["436201817","طقم فلاتر برادة 12 بوصة – 5 مراحل","مكون من طقم فلاتر 12 انش (3 مراحل) + فلتر بوست كاربون + فلتر مينرال ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",199],["1276299864","طقم فلاتر 10 بوصات – 3 مراحل","طقم فلاتر 10 انش (3 مراحل)، ضمن أطقم الفلاتر المتوفرة لدى المعالج",59],["1916119903","عرض الكلاسيك – جهاز تحلية مع برادة عادية وقارورة","عرض يجمع جهاز تحلية بسبع مراحل مع برادة عادية وقارورة",849],["543722590","العرض الكبير – كلاسيك بيور مع برادة ذاتية وجامبو ثلاثي","تجميعة تضم جهاز تحلية كلاسيك بيور بسبع مراحل، وبرادة ذاتية التعبئة، وهاوس جامبو",1799],["1451388253","طقم فلاتر 10 بوصات – 5 مراحل","مكون من طقم فلاتر 10 انش (3 مراحل) + فلتر بوست كاربون + فلتر مينرال ، ضمن أطقم الفلاتر المتوفرة لدى المعالج",149],["77942364","عرض الكلاسيك بلس – كلاسيك بيور ستاند مع برادة ذاتية التعبئة","عرض يجمع جهاز تحلية كلاسيك بيور بسبع مراحل مع برادة ذاتية التعبئة",949]];
  const normalize = text => String(text).normalize('NFKC').toLowerCase()
    .replace(/[٠-٩۰-۹]/g,c => String(c.charCodeAt(0)%16)).replace(/[ً-ْـ]/g,'')
    .replace(/[إأآ]/g,'ا').replace(/ة/g,'ه').replace(/ى/g,'ي')
    .replace(/انش|انج/g,'بوصه').replace(/ممبران/g,'ممبرين').replace(/فلاتر/g,'فلتر').replace(/اجهزه/g,'جهاز')
    .replace(/[^\p{L}\p{N} ]/gu,' ').trim();
  const tokens = text => normalize(text).split(/\s+/).map(w=>w.replace(/^ل(?=جهاز|فلتر|محطه)/,'').replace(/^لل(?=.{2})/,'').replace(/^ال(?=.{2})/,'')).filter(Boolean);
  const rows = entries.map(([id,name,description,price])=>({id,name,description,price,title:new Set(tokens(name)),words:new Set(tokens(name+' '+description))}));
  const frequencies = new Map();
  for(const row of rows) for(const term of row.words) frequencies.set(term,(frequencies.get(term)||0)+1);
  let waiting=false, previous=[], pending='', lastCategory='';
  const host=document.createElement('div');
  host.id='almoalej-shop-guide';document.body.append(host);
  const root=host.attachShadow({mode:'open'});
  root.innerHTML=`<style>
  :host{direction:rtl;font-family:inherit;color:#122e49}*{box-sizing:border-box}
  button,input,a{font:inherit}button{cursor:pointer}button:focus-visible,a:focus-visible,input:focus-visible{outline:3px solid #129ea2;outline-offset:2px}
  dialog{position:fixed;inset:0 0 0 auto;margin:0;direction:rtl;color:#122e49;border:0;border-left:1px solid #d3e4e8;border-radius:18px 0 0 18px;padding:0;width:min(440px,calc(100vw - 20px));max-width:100vw;height:100vh;height:100dvh;max-height:100dvh;box-shadow:-10px 0 40px #112d4926}dialog main{min-height:0;overscroll-behavior:contain}dialog header,dialog form{flex-shrink:0}dialog form{padding-bottom:max(12px,env(safe-area-inset-bottom))}@media(prefers-reduced-motion:no-preference){dialog[open]{animation:amDrawerIn .2s ease-out}@keyframes amDrawerIn{from{transform:translateX(100%)}to{transform:translateX(0)}}}
  dialog[open]{display:flex;flex-direction:column}dialog::backdrop{background:#102a4450}
  header{background:#102f4c;color:white;display:flex;align-items:center;justify-content:space-between;padding:18px 20px}header b{font-size:1.22rem}header button{background:transparent;color:white;font-size:24px;border:0;width:40px;height:40px}
  main{flex:1;overflow:auto;padding:16px;background:#f6fafa}p{line-height:1.65;margin:4px 0 10px}.user{background:#deeeee;padding:8px 12px;border-radius:12px;width:fit-content;margin-inline-start:auto}
  .choice,a{border:1px solid #c2d8da;background:white;color:#075962;border-radius:12px;padding:8px 12px;display:inline-block;margin:3px;text-decoration:none}
  article{background:white;border:1px solid #d4e3e5;border-radius:12px;padding:10px;margin:8px 0}article p{font-size:.9rem}article a{margin:0}form{display:flex;padding:12px;gap:8px;border-top:1px solid #d4e3e5}input{min-width:0;flex:1;border:1px solid #adbfc5;border-radius:10px;padding:10px}
  .send,.launcher{background:#07636a;color:white;border:0;border-radius:12px;padding:10px 16px;font-weight:bold}.launcher{position:fixed;bottom:max(76px,env(safe-area-inset-bottom));left:14px;z-index:9990;box-shadow:0 3px 14px #173f4e33}.send:disabled{opacity:.6}
  </style><button class="launcher" type="button">مساعد التسوّق</button><dialog aria-label="مساعد تسوّق المعالج"><header><b>مساعد تسوّق المعالج</b><button aria-label="إغلاق">×</button></header><main role="log" aria-live="polite"></main><form><input aria-label="سؤالك عن المنتجات" maxlength="300" autocomplete="off" placeholder="وش تدور عليه؟"><button class="send">إرسال</button></form></dialog>`;
  const panel=root.querySelector('dialog'), log=root.querySelector('main'), input=root.querySelector('input'), launcher=root.querySelector('.launcher');
  function message(text,cls=''){const p=document.createElement('p');p.textContent=text;p.className=cls;log.append(p);log.scrollTop=log.scrollHeight;}
  function choices(items){const group=document.createElement('div');for(const item of items){const b=document.createElement('button');b.type='button';b.className='choice';b.textContent=item;b.onclick=()=>{if(!waiting)reply(item)};group.append(b)} log.append(group);log.scrollTop=log.scrollHeight;}
  const examples={
    devices:['جهاز للمطبخ','تحليه مياه الشرب للبيت','احتاج انقي موية المنزل','اشرب من الحنفية','جهاز منزلي للعائلة'],
    coolers:['ابي ماء بارد وحار','تبريد الماء للمكتب','براده مع قاروره','براده تعبي نفسها'],
    stations:['انتاج كبير للمطعم','محطه تحليه تجاريه','احتاج تنقيه كميات كبيره للمقهى'],
    plans:['اشتراك زيارات دوريه','باقه صيانه سنويه','صيانة دورية وتغيير فلاتر'],
    filters:['شمعة بديلة','تغيير الفلاتر','احتاج فلتر بديل','تبديل شمعات الجهاز']
  };
  const intentModel=Object.entries(examples).map(([kind,phrases])=>{
    const words=new Map();
    for(const phrase of phrases)for(const t of new Set(tokens(phrase)))words.set(t,(words.get(t)||0)+1);
    return {kind,words};
  });
  function category(text){
    if(/باقه|باقات/.test(text))return 'plans';
    if(/فلتر|ممبرين/.test(text))return 'filters';
    if(/محطه|محطات/.test(text))return 'stations';
    if(/براده|برادات/.test(text))return 'coolers';
    if(/جهاز|بوكس|كلاسيك|تحليه للبيت/.test(text))return 'devices';
    const scores=intentModel.map(({kind,words})=>({kind,score:tokens(text).reduce((s,t)=>s+(words.get(t)||0)/Math.max(1,intentModel.filter(m=>m.words.has(t)).length),0)})).sort((a,b)=>b.score-a.score);
    return scores[0].score>=1 && scores[0].score>scores[1].score?scores[0].kind:'';
  }
  const prefixes={devices:/^جهاز (?!قياس)/,filters:/^(فلتر|طقم|ممبرين|عرض فلاتر|عرض فلتر|شمعة)/,plans:/^باقة/,stations:/^محطة/,coolers:/^برادة/};
  async function current(hits){
    if(preview)return hits;
    const response=await window.salla.product.fetch({source:'selected',source_value:hits.map(p=>Number(p.id)),limit:hits.length});
    const data=response?.data?.data??response?.data;
    if(!Array.isArray(data))throw Error('catalog unavailable');
    return hits.flatMap(row=>{
      const p=data.find(v=>String(v.id)===String(row.id));
      if(!p || p.is_available===false || p.is_out_of_stock===true || p.status==='out')return [];
      const price=p.price?.amount??p.price;
      return [{...row,name:p.name||row.name,price: typeof price==='number' || (typeof price==='string' && /^\d+(\.\d+)?$/.test(price)) ? Number(price):null}];
    });
  }
  function card(row){
    const el=document.createElement('article'),title=document.createElement('strong'),note=document.createElement('p'),link=document.createElement('a');
    title.textContent=row.name;
    note.textContent=row.description.split(/[.؛\n]/)[0];
    link.href='https://almoalej.com/-/p'+row.id;link.target='_blank';link.rel='noopener noreferrer';link.textContent='عرض المنتج'+(row.price!=null?' · '+row.price+' ر.س':'');
    el.append(title,note,link);log.append(el);
  }
  async function reply(raw){
    if(waiting||!raw.trim())return;
    waiting=true;root.querySelector('.send').disabled=true;input.value='';message(raw,'user');
    try{
      let question=normalize(raw);
      if(/قارن|مقارنه|الفرق بينهم/.test(question)&&previous.length>=2){message('هذي مواصفات أول خيارين من نتائجك');const [a,b]=previous;[a,b].forEach(card);if(a.price!=null && b.price!=null){const difference=Math.abs(a.price-b.price);message(difference?'فرق السعر '+difference+' ر.س، والأقل سعرًا '+(a.price<b.price?a.name:b.name):'الخياران بنفس السعر.')}return}
      if(pending && !category(question))question=pending+' '+question;
      pending='';
      const budget=question.match(/(?:تحت|اقل من|بحدود|حدود|ميزانيتي|ميزانيه|بحد اقصي)\s*(\d+)|(?:^|\s)(\d+)\s*ريال/);
      const ceiling=budget?Number(budget[1]||budget[2]):null;
      if(budget)question=question.replace(budget[0],' ');
      const kind=category(question)||lastCategory;
      if(kind==='filters' && !/\d|جيك|دايركت|دائري|جامبو|بوكس|ممبرين|قطني|كربون/.test(question)){
        pending='فلتر';message('وش اسم جهازك أو مقاس الفلتر المكتوب عليه؟');choices(['جيك','دايركت','دائري','10 بوصة','12 بوصة']);return;
      }
      const terms=[...new Set(tokens(question))];
      const numbers=terms.filter(t=>/^\d+$/.test(t));
      const specific=terms.filter(t=>['جيك','دايركت','دائري','جامبو','مربع','مستطيل','ممبرين','ابيض','اسود','رمادي'].includes(t));
      const scored=rows.filter(row=>(!kind||prefixes[kind].test(row.name))&&numbers.every(t=>row.title.has(t))&&specific.every(t=>row.title.has(t)))
        .map(row=>({row,score:terms.reduce((sum,t)=>sum+(row.words.has(t)?Math.log(1+rows.length/(frequencies.get(t)||1))*(row.title.has(t)?4:1):0),0)}))
        .filter(x=>x.score>0 || kind).sort((a,b)=>b.score-a.score);
      lastCategory=kind;previous=[];
      if(!scored.length){message('ما لقيت تطابق واضح. اكتب اسم المنتج أو الموديل مثل ما هو على الجهاز.');return}
      let matches=[];
      for(let i=0;i<scored.length && matches.length<3;i+=10){
        const batch=await current(scored.slice(i,i+10).map(x=>x.row));
        matches.push(...batch.filter(row=>ceiling===null||(row.price!=null&&row.price<=ceiling)));
      }
      previous=matches.slice(0,3);
      if(!previous.length){message('ما ظهرت خيارات متاحة لهذا الوصف. جرّب موديل أو مقاس آخر.');return}
      message('هذي أقرب المنتجات لوصفك');previous.forEach(card);
      if(previous.length>1)choices(['قارن أول خيارين']);
    }catch{message('تعذّر تحميل المنتجات من المتجر الآن. جرّب مرة ثانية.')}
    finally{waiting=false;root.querySelector('.send').disabled=false;log.scrollTop=log.scrollHeight;input.focus()}
  }
  launcher.onclick=()=>{panel.showModal();input.focus()};root.querySelector('header button').onclick=()=>panel.close();
  panel.onclose=()=>launcher.focus();root.querySelector('form').onsubmit=e=>{e.preventDefault();reply(input.value.trim())};
  message('حيّاك! وش تحتاج لجهازك؟ اكتب سؤالك أو اختر من تحت.');choices(['أبي جهاز تحلية للبيت','أحتاج فلتر','محطة 400 جالون']);
  if(preview)launcher.click();
})();
;(() => {
  function watchCart() {
    const header = document.querySelector('header.store-header');
    if (!header) return;
    function sync() {
      const cart = header.querySelector('salla-cart-summary');
      const count = cart?.querySelector('.s-cart-summary-count')?.textContent || '';
      if (cart) cart.toggleAttribute('data-has-items', /[1-9١-٩۱-۹]/.test(count));
    }
    sync();
    new MutationObserver(sync).observe(header, {subtree:true, childList:true, characterData:true});
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watchCart, {once:true});
  else watchCart();
})();
;(()=>{const attach=()=>{const cart=document.querySelector('#mainnav salla-cart-summary');if(!cart||cart.dataset.purchasePulseReady)return;cart.dataset.purchasePulseReady='1';const read=()=>{const text=cart.querySelector('.s-cart-summary-count')?.textContent.trim();return text?Number(text.replace(/[٠-٩]/g,c=>String('٠١٢٣٤٥٦٧٨٩'.indexOf(c)))):NaN};let previous=read(),armed=0;document.addEventListener('click',e=>{if(e.target.closest?.('salla-add-product-button,.am07-quickadd-trigger, salla-product-card button, .s-product-card-entry button'))armed=Date.now()},true);new MutationObserver(()=>{const next=read();if(!Number.isFinite(next))return;if(Number.isFinite(previous)&&next>previous&&Date.now()-armed<30000){const link=cart.querySelector('.s-cart-summary-wrapper');link?.classList.add('am-purchase-pulse');setTimeout(()=>link?.classList.remove('am-purchase-pulse'),850);armed=0}previous=next}).observe(cart,{childList:true,subtree:true,characterData:true})};if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',attach,{once:true});else attach();window.addEventListener('load',attach,{once:true})})();
;(()=>{const policy="ضمان القطع الكهربائية لمدة سنتين. ونقدّم خدمة صيانة مجانية لمدة 5 سنوات تشمل أجور اليد، وإصلاح التهريبات والأعطال التي لا تتطلب تغيير قطع غيار.";function showPolicy(){if(document.body.classList.contains('product-index')&&/\/(?:c463435319|c1969591600)\/?$/.test(location.pathname)){const title=document.querySelector('#page-main-title');if(title&&!document.getElementById('am-device-warranty')){const p=document.createElement('p');p.id='am-device-warranty';p.textContent=policy;p.style.cssText='margin:.65rem 0 1rem;padding:.8rem 1rem;background:#f2f7fa;border-inline-start:3px solid #fa896a;border-radius:8px;color:#14344f;line-height:1.8';(document.querySelector('.am07-list-hero')||title.parentElement).append(p)}}if(!document.body.classList.contains('product-single'))return;const desc=document.querySelector('.am-native-product-description')||document.querySelector('.article--main');if(!desc)return;const h=[...desc.querySelectorAll('h2,h3,h4')].find(el=>el.textContent.includes('الضمان'));const p=h?.nextElementSibling;if(p&&p.tagName==='P'&&p.textContent.includes('ضمان القطع الكهربائية في الجهاز سنتان.')){for(const n of p.childNodes){if(n.nodeType===3&&n.textContent.includes('ضمان القطع الكهربائية في الجهاز سنتان.'))n.textContent=n.textContent.replace('ضمان القطع الكهربائية في الجهاز سنتان.',policy)}return}const name=document.querySelector('main h1')?.textContent.trim()||'';if(!/^(جهاز تحلية|جهاز التحلية|جهاز نانو|جهاز دايركت|جهاز الجيك|جهاز المعالج)/.test(name)||desc.textContent.includes(policy))return;const para=document.createElement('p');para.textContent=policy;if(h)h.after(para);else{const head=document.createElement('h3');head.textContent='الضمان والصيانة';desc.append(head,para)}}function start(){showPolicy();const root=document.querySelector('main');if(root)new MutationObserver(showPolicy).observe(root,{childList:true,subtree:true})}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start()})();

;(()=>{
const mobile=window.matchMedia('(max-width:767px)');
function setup(){const slider=document.querySelector('#am-shop salla-slider'),track=slider?.querySelector('.swiper-wrapper'),view=track?.parentElement;if(!track?.children.length||slider.dataset.mobileCategorySetup)return;slider.dataset.mobileCategorySetup='1';
const style=document.createElement('style');style.textContent=`
#am-shop .am-mobile-category-arrows{display:none}
@media(max-width:767px){body#app #am-shop #main-links-4{display:block!important;position:relative!important}body#app #am-shop #main-links-4 .swiper{width:100%!important;max-width:none!important;margin-inline:auto!important;display:block!important;overflow:hidden!important;touch-action:pan-y!important}body#app #am-shop #main-links-4 .swiper-wrapper{--row:76px;--gap:8px;display:grid!important;grid-template-columns:minmax(0,1fr)!important;grid-template-rows:none!important;grid-auto-rows:var(--row)!important;grid-auto-flow:row!important;gap:var(--gap)!important;height:calc(4 * var(--row) + 3 * var(--gap))!important;width:100%!important;box-sizing:border-box!important;margin:0!important;padding:0!important;overflow-x:hidden!important;overflow-y:auto!important;transform:none!important;scroll-snap-type:y mandatory;scrollbar-width:none;touch-action:pan-y!important}#am-shop .swiper-wrapper::-webkit-scrollbar{display:none}body#app #am-shop #main-links-4 .swiper-slide{width:100%!important;height:var(--row)!important;margin:0!important;grid-column:auto!important;grid-row:auto!important;scroll-snap-align:start}body#app #am-shop #main-links-4 .slide--cat-entry{box-sizing:border-box!important;min-height:0!important;height:100%!important;display:flex!important;flex-direction:row!important;justify-content:center!important;align-items:center!important;gap:10px!important;padding:4px 10px!important}body#app #am-shop #main-links-4 .slide--cat-entry>*{margin:0!important}body#app #am-shop #main-links-4 .s-slider-block__title-left{display:none!important}#am-shop .am-mobile-category-arrows{display:none!important}#am-shop .am-mobile-category-arrows button{position:absolute;top:var(--category-mid);transform:translateY(-50%);z-index:2;width:30px;height:44px;display:grid;place-items:center;border:1px solid #ff896a;border-radius:11px;background:white;color:#132f48;box-shadow:0 2px 8px #132f4812;transition:opacity .25s,background-color .25s}#am-shop .am-mobile-category-arrows button:first-child{right:0}#am-shop .am-mobile-category-arrows button:last-child{left:0}#am-shop .am-mobile-category-arrows button:disabled{opacity:.35}#am-shop .am-mobile-category-arrows button:focus-visible{outline:2px solid #132f48}#am-shop .am-mobile-category-arrows svg{width:18px;height:18px} }
@media(min-width:768px){
 body#app #am-shop #main-links-4 .swiper{display:block!important;overflow:hidden!important;width:100%!important;touch-action:pan-x pan-y!important}
 body#app #am-shop #main-links-4 .swiper-wrapper{--n:6;--g:14px;display:grid!important;grid-template-columns:none!important;grid-template-rows:auto!important;grid-auto-flow:column!important;grid-auto-columns:calc((100% - (var(--n) - 1)*var(--g))/var(--n))!important;gap:var(--g)!important;transform:none!important;width:100%!important;max-width:100%!important;box-sizing:border-box!important;overflow-x:auto!important;overflow-y:hidden!important;padding:6px 0 10px!important;scroll-snap-type:x mandatory;scrollbar-width:none;direction:rtl;touch-action:pan-x pan-y!important}
 body#app #am-shop #main-links-4 .swiper-wrapper::-webkit-scrollbar{display:none}body#app #am-shop #main-links-4 .swiper-slide{width:100%!important;min-width:0!important;margin:0!important;scroll-snap-align:start;pointer-events:auto!important}body#app #am-shop #main-links-4 .s-slider-block__title{display:flex!important;align-items:center;justify-content:space-between!important}body#app #am-shop #main-links-4 .s-slider-block__title-left{display:none!important}.am-mobile-category-arrows{display:flex;gap:6px;direction:rtl}.am-mobile-category-arrows button{width:40px;height:40px;display:grid;place-items:center;border:1px solid #ff896a;border-radius:12px;color:#132f48;background:white;font:26px/1 Arial;cursor:pointer}.am-mobile-category-arrows button:disabled{opacity:.35;cursor:default}.am-mobile-category-arrows button:focus-visible{outline:2px solid #132f48;outline-offset:2px}@media(max-width:767px){body#app #am-shop #main-links-4 .swiper-wrapper{--n:4}}@media(max-width:600px){body#app #am-shop #main-links-4 .swiper-wrapper{--n:2;--g:10px}}
 
body#app #am-shop #main-links-4{display:block!important;position:relative!important;--rail:42px}body#app #am-shop #main-links-4 .swiper{width:calc(100% - 2 * var(--rail))!important;margin-inline:auto!important}body#app #am-shop #main-links-4 .am-mobile-category-arrows{display:contents}body#app #am-shop #main-links-4 .s-slider-block__title{position:static!important}body#app #am-shop .am-mobile-category-arrows button{position:absolute;top:var(--category-mid);transform:translateY(-50%);z-index:2;width:36px;height:40px;background:#fff;border:1px solid #ff896a;box-shadow:0 2px 8px #132f4812;transition:background-color .24s ease,opacity .24s ease,box-shadow .24s ease}#am-shop .am-mobile-category-arrows button:first-child{right:0}#am-shop .am-mobile-category-arrows button:last-child{left:0}#am-shop .am-mobile-category-arrows svg{width:19px;height:19px;transition:transform .28s ease}#am-shop .am-mobile-category-arrows button:enabled:hover{background:#fff2ed;box-shadow:0 3px 10px #132f4820}#am-shop .am-mobile-category-arrows button:first-child:enabled:hover svg{transform:translateX(2px)}#am-shop .am-mobile-category-arrows button:last-child:enabled:hover svg{transform:translateX(-2px)}@media(max-width:600px){body#app #am-shop #main-links-4{--rail:32px}body#app #am-shop .am-mobile-category-arrows button{width:29px;height:44px}}@media(prefers-reduced-motion:reduce){#am-shop .am-mobile-category-arrows button,#am-shop .am-mobile-category-arrows svg{transition:none!important}}
 #am-shop .am-mobile-category-arrows{display:contents!important}}
`;document.head.append(style);const nav=document.createElement('div');nav.className='am-mobile-category-arrows';const buttons=[-1,1].map(step=>{const b=document.createElement('button');b.type='button';b.setAttribute('aria-label',step<0?'القسم السابق':'القسم التالي');b.innerHTML='<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="'+(step<0?'m9 5 7 7-7 7':'m15 5-7 7 7 7')+'"/></svg>';b.onclick=()=>{if(!mobile.matches){const cards=Array.from(track.children),right=track.getBoundingClientRect().right,index=cards.reduce((best,c,i)=>Math.abs(c.getBoundingClientRect().right-right)<Math.abs(cards[best].getBoundingClientRect().right-right)?i:best,0),target=cards[Math.max(0,Math.min(cards.length-1,index+step))];track.scrollBy({left:target.getBoundingClientRect().right-right,behavior:matchMedia('(prefers-reduced-motion:reduce)').matches?'instant':'smooth'});return}const gap=track.children[1].getBoundingClientRect().top-track.children[0].getBoundingClientRect().top;track.scrollTo({top:(Math.round(track.scrollTop/gap)+step)*gap,behavior:matchMedia('(prefers-reduced-motion:reduce)').matches?'instant':'smooth'})};nav.append(b);return b});slider.append(nav);function sync(){slider.style.setProperty('--category-mid',(view.getBoundingClientRect().top-slider.getBoundingClientRect().top+view.clientHeight/2)+'px');buttons[0].disabled=Math.abs(track.scrollLeft)<2;buttons[1].disabled=Math.abs(track.scrollLeft)+track.clientWidth>=track.scrollWidth-2}function adapt(){if(view.swiper){view.swiper.disable()}sync()}track.addEventListener('scroll',sync,{passive:true});mobile.addEventListener('change',adapt);new ResizeObserver(adapt).observe(view);adapt();return true}function start(){if(location.pathname!=='/')return;if(setup())return;const o=new MutationObserver(()=>{if(setup())o.disconnect()});o.observe(document.body,{childList:true,subtree:true})}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start);else start()})();
;(() => {
  if(location.pathname !== '/') return;
  const scope = 'body#app #am-shop #main-links-4';
  const style = document.createElement('style');
  style.textContent = '@media(min-width:768px){'+scope+' .swiper{width:100%!important;box-sizing:border-box!important;padding-inline:48px!important;position:relative!important}'+scope+' .swiper .am-mobile-category-arrows button{top:50%!important;transform:translateY(-50%)!important}'+scope+' .swiper-wrapper{scroll-behavior:smooth}}@media(prefers-reduced-motion:reduce){'+scope+' .swiper-wrapper{scroll-behavior:auto!important}}';
  document.head.append(style);
  document.addEventListener('click', event => {
    const button = event.target.closest?.('#am-shop .am-mobile-category-arrows button');
    if (!button || button.disabled || !matchMedia('(min-width:768px) and (prefers-reduced-motion:no-preference)').matches) return;
    const track = button.closest('.swiper')?.querySelector('.swiper-wrapper');
    if (!track) return;
    const bounds = track.getBoundingClientRect();
    const next = button === button.parentElement.lastElementChild;
    const entering = [...track.children].filter(card => next ? card.getBoundingClientRect().right <= bounds.left + 2 : card.getBoundingClientRect().left >= bounds.right - 2);
    const card = next ? entering[0] : entering.at(-1);
    card?.firstElementChild?.animate([{opacity:.72,transform:'scale(.97)'},{opacity:1,transform:'scale(1)'}],{duration:520,easing:'cubic-bezier(.22,1,.36,1)'});
  },true);
})();
;document.addEventListener('click',function(event){
  const btn=event.target.closest?.('#am-shop .am-mobile-category-arrows button');
  if(!btn || btn.disabled || btn.closest('.swiper') || !matchMedia('(min-width:768px) and (prefers-reduced-motion:no-preference)').matches)return;
  const track=btn.closest('#main-links-4')?.querySelector('.swiper-wrapper');
  if(!track)return;
  const next=btn===btn.parentElement.lastElementChild, bounds=track.getBoundingClientRect();
  const outside=Array.from(track.children).filter(c=>next?c.getBoundingClientRect().right<=bounds.left+2:c.getBoundingClientRect().left>=bounds.right-2);
  const incoming=next?outside[0]:outside.at(-1);
  incoming?.firstElementChild?.animate([{opacity:.72,transform:'scale(.97)'},{opacity:1,transform:'scale(1)'}],{duration:520,easing:'cubic-bezier(.22,1,.36,1)'});
},true);
;(() => {
  if (location.pathname !== '/') return;
  const trackSelector = '#am-shop #main-links-4 .swiper-wrapper';
  document.addEventListener('wheel', event => {
    if (event.ctrlKey || !event.cancelable || !event.target.closest?.(trackSelector)) return;
    if (event.shiftKey || (event.deltaX && Math.abs(event.deltaX) >= Math.abs(event.deltaY))) event.preventDefault();
  }, {passive:false});
})();
;(() => {
  if (location.pathname !== '/') return;
  const selector = '#am-shop #main-links-4 .swiper-wrapper';
  let drag, blocked;
  const style = document.createElement('style');
  style.textContent = '@media(min-width:768px) and (any-pointer:fine){'+selector+' a{cursor:grab;user-select:none;-webkit-user-drag:none}'+selector+'[data-mouse-dragging]{scroll-snap-type:none!important;scroll-behavior:auto!important}'+selector+'[data-mouse-dragging] *{cursor:grabbing!important;user-select:none}}';
  document.head.append(style);
  document.addEventListener('pointerdown', e => {
    if(e.pointerType !== 'mouse' || e.button !== 0 || !matchMedia('(min-width:768px)').matches) return;
    blocked = null;
    const track = e.target.closest?.(selector);
    if(track) drag = {track, id:e.pointerId, x:e.clientX, start:track.scrollLeft, active:false};
  },true);
  document.addEventListener('dragstart', e => {if(drag && drag.track.contains(e.target)) e.preventDefault()},true);
  document.addEventListener('pointermove', e => {
    if(!drag || e.pointerId !== drag.id) return;
    const dx = e.clientX - drag.x;
    if(!drag.active){
      if(Math.abs(dx)<6) return;
      drag.active=true;
      drag.track.setAttribute('data-mouse-dragging','');
      drag.track.setPointerCapture(e.pointerId);
    }
    drag.track.scrollLeft = drag.start - dx;
    e.preventDefault();
  },true);
  function finish(){
    if(!drag) return;
    const {track,id,active} = drag; drag=null;
    if(!active) return;
    blocked=track;
    const right=track.getBoundingClientRect().right;
    const nearest=Array.from(track.children).reduce((a,b)=>Math.abs(a.getBoundingClientRect().right-right)<Math.abs(b.getBoundingClientRect().right-right)?a:b);
    const target=track.scrollLeft+nearest.getBoundingClientRect().right-right;
    track.removeAttribute('data-mouse-dragging');
    if(track.hasPointerCapture(id)) track.releasePointerCapture(id);
    track.scrollTo({left:target,behavior:matchMedia('(prefers-reduced-motion:reduce)').matches?'instant':'smooth'});
    setTimeout(()=>{if(blocked===track)blocked=null},350);
  }
  for(const type of ['pointerup','pointercancel','lostpointercapture']) document.addEventListener(type,e=>{if(e.pointerId===drag?.id)finish()},true);
  window.addEventListener('blur',finish);
  document.addEventListener('click',e=>{if(blocked && e.detail && blocked.contains(e.target)){e.preventDefault();e.stopImmediatePropagation();blocked=null}},true);
})();
;(() => {
  if(location.pathname !== '/') return;
  const root = '#am-shop #main-links-4';
  const reduced = matchMedia('(prefers-reduced-motion: reduce)');
  const style = document.createElement('style');
  style.dataset.amCategoryMotion = '1';
  style.textContent = [
    '@media(prefers-reduced-motion:no-preference){',
    root+' .slide--cat-entry{transition:translate .32s cubic-bezier(.2,.75,.25,1),box-shadow .32s ease}',
    '@media(hover:hover) and (pointer:fine){'+root+' .slide--cat-entry:hover{translate:0 -2px;box-shadow:0 4px 8px #122e461c}'+root+' [data-mouse-dragging] .slide--cat-entry:hover{translate:0 0}}',
    '}'
  ].join('');
  document.head.append(style);
  function bind(){
    const track=document.querySelector(root+' .swiper-wrapper');
    if(!track || !track.children.length) return false;
    const seen=new WeakMap(), running=new WeakMap();
    let x=track.scrollLeft,y=track.scrollTop,axis='x',sign=1,moved=false;
    track.addEventListener('scroll',()=>{
      const dx=track.scrollLeft-x,dy=track.scrollTop-y;
      if(dx||dy){axis=Math.abs(dy)>Math.abs(dx)?'y':'x';sign=Math.sign(axis==='y'?dy:dx);moved=true;}
      x=track.scrollLeft;y=track.scrollTop;
    },{passive:true});
    const observer=new IntersectionObserver(entries=>{
      for(const e of entries){
        const visible=e.intersectionRatio>=.18, before=seen.get(e.target);
        seen.set(e.target,visible);
        if(!visible || before!==false || !moved || reduced.matches)continue;
        const card=e.target.querySelector('.slide--cat-entry');
        if(!card)continue;
        running.get(card)?.cancel();
        const start=axis==='x'?(sign*12)+'px 0':'0 '+(sign*10)+'px';
        running.set(card,card.animate([{translate:start},{translate:'0 0'}],{duration:440,easing:'cubic-bezier(.18,.78,.22,1)'}));
      }
    },{root:track,threshold:[0,.18]});
    Array.from(track.children).forEach(el=>observer.observe(el));return true;
  }
  function start(){if(bind())return;const observer=new MutationObserver(()=>{if(bind())observer.disconnect()});observer.observe(document.body,{childList:true,subtree:true})}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
;(() => {
  if (location.pathname !== '/') return;
  const scope='#am-shop #main-links-4';
  const media=matchMedia('(max-width:767px)');
  const styles=document.createElement('style');
  styles.textContent='[data-am-vertical-nav]{display:none!important}@media(max-width:767px){body#app '+scope+' .s-slider-block__title{display:flex!important;flex-direction:row!important;direction:rtl;align-items:center!important;justify-content:space-between!important;gap:8px}body#app '+scope+' [data-am-vertical-nav]{margin-inline-start:auto;display:flex!important;direction:rtl;gap:6px}'+scope+' [data-am-vertical-nav] button{width:38px;height:38px;display:grid;place-items:center;border:1px solid #ff896a;border-radius:11px;background:white;color:#132f48;touch-action:manipulation}'+scope+' [data-am-vertical-nav] button:disabled{opacity:.38}'+scope+' [data-am-vertical-nav] svg{width:20px;height:20px}body#app '+scope+' .swiper{touch-action:pan-x pan-y!important}body#app '+scope+' .swiper-wrapper{--gap:8px;display:grid!important;grid-template-columns:none!important;grid-template-rows:repeat(2,auto)!important;grid-auto-rows:auto!important;grid-auto-flow:column!important;grid-auto-columns:calc((100% - var(--gap))/2)!important;gap:var(--gap)!important;height:auto!important;direction:rtl;overflow-x:auto!important;overflow-y:hidden!important;scroll-snap-type:x mandatory!important;touch-action:pan-x pan-y!important}body#app '+scope+' .swiper-wrapper>.swiper-slide{height:auto!important;aspect-ratio:1/1!important;box-sizing:border-box!important;min-width:0!important;scroll-snap-align:start!important}body#app '+scope+' .swiper-slide .slide--cat-entry{width:100%!important;height:100%!important}body#app '+scope+' .swiper-slide .slide--cat-entry{flex-direction:column!important;gap:5px!important;translate:none!important;animation:none!important;transition:none!important}body#app '+scope+' .am-cat-light{display:none!important}}';
  document.head.append(styles);
  function start(){
    let currentTrack, currentNav;
    function sync(){if(!currentNav || !currentTrack)return;const offset=Math.abs(currentTrack.scrollLeft);currentNav.children[0].disabled=offset<=1;currentNav.children[1].disabled=offset+currentTrack.clientWidth>=currentTrack.scrollWidth-2;}
    const size=new ResizeObserver(sync);
    function attach(){
      const slider=document.querySelector(scope), title=slider?.querySelector('.s-slider-block__title'), track=slider?.querySelector('.swiper-wrapper');
      if(!title || !track || !media.matches)return;
      if(currentTrack!==track){currentTrack?.removeEventListener('scroll',sync);size.disconnect();currentTrack=track;track.addEventListener('scroll',sync,{passive:true});size.observe(track)}
      if(!currentNav || !title.contains(currentNav)){
        currentNav?.remove();currentNav=document.createElement('div');currentNav.dataset.amVerticalNav='';
        for(const step of [-1,1]){const b=document.createElement('button');b.type='button';b.setAttribute('aria-label',step<0?'الأقسام السابقة':'الأقسام التالية');b.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="'+(step<0?'M9 5l7 7-7 7':'M15 5l-7 7 7 7')+'"/></svg>';b.onclick=()=>{const t=currentTrack,items=t.children;if(items.length<3)return;const w=items[0].getBoundingClientRect().width+parseFloat(getComputedStyle(t).columnGap);if(w>0)t.scrollTo({left:-(Math.round(Math.abs(t.scrollLeft)/w)+step)*w,behavior:matchMedia('(prefers-reduced-motion:reduce)').matches?'instant':'smooth'})};currentNav.append(b)}title.append(currentNav);
      }sync();
    }
    new MutationObserver(attach).observe(document.body,{childList:true,subtree:true});media.addEventListener('change',attach);attach();
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
;(() => {
  const sequence=["c146247215","c1520217384","c463435319","c1969591600","c1796286755","c1157515308","c288346930","c1195553841","c598060327","c564944693","c1472671796","c1297587511"];
  const rank=new Map(sequence.map((id,index)=>[id,index]));
  const groups='#main-links-4 .swiper-wrapper, #am-header-category-list, #am-categories-dialog .am-categories-links:not(.am-mobile-service-links)';
  function arrange(group){
    const cards=group.matches('.swiper-wrapper');
    const entries=Array.from(group.children).map(node=>{const link=cards?node.querySelector('a[href]'):node;return {node,index:rank.get(link?.getAttribute('href')?.split(/[?#]/)[0].split('/').filter(Boolean).at(-1))}}).filter(e=>e.index!==undefined);
    if(!entries.length||entries.some(e=>e.index===undefined))return;
    const sorted=entries.slice().sort((a,b)=>a.index-b.index);
    sorted.forEach(({node},i)=>{if(group.children[i]!==node)group.insertBefore(node,group.children[i]);if(cards){const label=(i+1)+' / '+sorted.length;if(node.getAttribute('aria-label')!==label)node.setAttribute('aria-label',label);node.style.setProperty('--am-cat-row',String(1+Math.floor(i%4/2)));node.style.setProperty('--am-cat-column',String(1+2*Math.floor(i/4)+i%2));}});
  }
  function start(){document.querySelectorAll(groups).forEach(arrange);new MutationObserver(records=>{const pending=new Set();for(const record of records){const parent=record.target.closest?.(groups);if(parent)pending.add(parent);for(const n of record.addedNodes){if(n.nodeType!==1)continue;if(n.matches(groups))pending.add(n);n.querySelectorAll(groups).forEach(g=>pending.add(g));}}pending.forEach(arrange)}).observe(document.body,{childList:true,subtree:true});}
  const style=document.createElement('style');style.textContent='@media(max-width:767px){body#app #am-shop #main-links-4 .swiper-wrapper>.swiper-slide{grid-row:var(--am-cat-row,auto)!important;grid-column:var(--am-cat-column,auto)!important}}';document.head.append(style);
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
;(() => {
  if(location.pathname !== '/') return;
  const categories=[["146247215","عروض الأجهزة"],["1520217384","باقات الصيانة"],["463435319","أجهزة التحلية"],["1969591600","أجهزة النانو تيكنولوجي"],["1796286755","البرادات وصانعات الثلج"],["1157515308","الكافيهات والمطاعم"],["288346930","فلاتر التصفية المركزية"],["1195553841","فلاتر التصفية الصغيرة"],["598060327","عروض الفلاتر"],["564944693","الفلاتر"],["1472671796","فلاتر الشاور"],["1297587511","الصيانة وقطع الغيار"]];
  function mount(){
    const first=document.querySelector('section[component-id="652080513"]');
    if(!first || !first.querySelector('salla-products-list'))return false;
    if(document.getElementById('am-category-products'))return true;
    const parent=first.parentElement;
    const existing=new Map();
    for(const list of parent.querySelectorAll(':scope > section salla-products-list[source="categories"]')){
      const ids=JSON.parse(list.getAttribute('source-value')||'[]');if(ids.length)existing.set(String(ids[0]),list.closest('section'));
    }
    const rack=document.createElement('div');rack.id='am-category-products';
    const style=document.createElement('style');style.textContent='#main-content>#am-category-products{grid-column:1/-1;grid-row:4;order:5;min-width:0;width:100%} #am-category-products>section{width:calc(100% - 32px);max-width:1280px;margin:0 auto;padding:32px 0} #am-category-products .s-products-list-wrapper{display:grid!important;grid-template-columns:repeat(4,minmax(0,1fr))!important;gap:18px!important} #am-category-products .s-products-list-wrapper>custom-salla-product-card:nth-of-type(n+5){display:none!important}@media(max-width:767px){#am-category-products>section{width:calc(100% - 20px);padding:24px 0}#am-category-products .s-products-list-wrapper{grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:10px!important}}';document.head.append(style);
    style.textContent+="#am-category-products [data-am-shelf]{position:relative;box-sizing:border-box}#am-category-products [data-am-shelf] .s-products-list-wrapper{direction:rtl;display:grid!important;grid-template-columns:none!important;grid-auto-flow:column!important;grid-template-rows:auto!important;grid-auto-columns:calc((100% - 54px)/4)!important;overflow-x:auto!important;scroll-snap-type:x mandatory;scrollbar-width:none}#am-category-products .s-products-list-wrapper::-webkit-scrollbar{display:none}#am-category-products [data-am-shelf] .s-products-list-wrapper>custom-salla-product-card:nth-of-type(n){display:flex!important;scroll-snap-align:start}#am-category-products .am-product-arrows{display:contents}#am-category-products .am-product-arrows[hidden]{display:none}#am-category-products .am-product-arrows button{position:absolute;top:52%;z-index:2;width:36px;height:40px;display:grid;place-items:center;border:1px solid #ff896a;border-radius:11px;background:white;color:#132f48;box-shadow:0 2px 8px #132f4812}#am-category-products .am-product-arrows button:first-child{right:0}#am-category-products .am-product-arrows button:last-child{left:0}#am-category-products .am-product-arrows button:disabled{opacity:.35}@media(min-width:768px){#am-category-products>section[data-am-shelf]{padding-inline:42px}}@media(max-width:767px){#am-category-products [data-am-shelf] .s-products-list-wrapper{grid-auto-columns:calc((100% - 10px)/2)!important}#am-category-products .am-product-arrows{display:flex;direction:rtl;gap:8px;justify-content:flex-end;margin-top:8px}#am-category-products .am-product-arrows[hidden]{display:none}#am-category-products .am-product-arrows button{position:static;width:40px;height:40px}}";
    first.before(rack);
    for(const [id,title] of categories){
      let section=existing.get(id);
      if(!section){section=first.cloneNode(false);section.removeAttribute('component-id');section.removeAttribute('id');const heading=first.querySelector('.s-block__title').cloneNode(true);heading.querySelector('.am-product-arrows')?.remove();heading.querySelector('h2').textContent=title;const link=heading.querySelector('.am-view-all')||document.createElement('a');link.className='am-view-all';link.href='/-/c'+id;link.textContent='عرض الكل ←';if(!link.parentElement)heading.querySelector('h2').before(link);section.append(heading);}
      section.dataset.amShelf=id;
      const original=section.querySelector('salla-products-list');
      const chosen={'598060327':[1276299864,1883004077,2058223522,1634423973],'1969591600':[1249034417,1982074547,1875602366,192850360],'288346930':[157637518,1531083407,583001739,1314989205],'1297587511':[1954274764,1784909778,1564115185,271391694]}[id];
      const list=original?.cloneNode(false)||document.createElement('salla-products-list');
      list.classList.add('horizontal-products');list.setAttribute('source','categories');list.setAttribute('source-value',JSON.stringify([Number(id)]));list.setAttribute('limit','100');list.setAttribute('horizontal-cards','');
      if(original)original.remove();
      const placeholder=document.createElement('div');placeholder.style.minHeight='clamp(320px,40vw,520px)';section.append(placeholder);
      if('IntersectionObserver' in window){const loadList=new IntersectionObserver(entries=>{if(entries.some(entry=>entry.isIntersecting)){loadList.disconnect();placeholder.replaceWith(list);}},{rootMargin:'1000px 0px'});loadList.observe(placeholder);}else placeholder.replaceWith(list);
      if(chosen)style.textContent+=chosen.map((pid,index)=>'#am-category-products [data-am-shelf="'+id+'"] custom-salla-product-card[id="'+pid+'"]{order:'+(index-chosen.length)+'!important}').join('');
      const nav=document.createElement('div');nav.className='am-product-arrows';nav.hidden=true;
      const buttons=[-1,1].map(step=>{const b=document.createElement('button');b.type='button';b.setAttribute('aria-label',(step<0?'المنتج السابق':'المنتج التالي')+' في '+title);b.innerHTML='<svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="'+(step<0?'M9 5l7 7-7 7':'M15 5l-7 7 7 7')+'"/></svg>';nav.append(b);return b});
      section.querySelector('.s-block__title').append(nav);
      let track;
      function sync(){const limit=track?track.scrollWidth-track.clientWidth:0;nav.hidden=limit<3;const offset=Math.abs(track?.scrollLeft||0);buttons[0].disabled=offset<2;buttons[1].disabled=offset>=limit-2;}
      const resize=new ResizeObserver(sync);
      function connect(){const next=list.querySelector('.s-products-list-wrapper');if(next!==track){track?.removeEventListener('scroll',sync);resize.disconnect();track=next;if(track){resize.observe(track);track.addEventListener('scroll',sync,{passive:true});}}sync();}
      for(const [index,b] of buttons.entries())b.onclick=()=>{const card=track?.querySelector('custom-salla-product-card');if(!card)return;const stride=card.getBoundingClientRect().width+(parseFloat(getComputedStyle(track).columnGap)||0);track.scrollBy({left:(index?-1:1)*stride,behavior:matchMedia('(prefers-reduced-motion:reduce)').matches?'instant':'smooth'});};
      let pending=false;new MutationObserver(()=>{if(!pending){pending=true;requestAnimationFrame(()=>{pending=false;connect()})}}).observe(list,{childList:true,subtree:true});connect();
      rack.append(section);
    }
    return true;
  }
  function start(){if(mount())return;const watch=new MutationObserver(()=>{if(mount())watch.disconnect()});watch.observe(document.body,{childList:true,subtree:true})}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
})();
;(() => {
 if(location.pathname!=='/')return;
 const css=document.createElement('style');css.textContent=`
 #am-category-products{display:flex;flex-direction:column;align-items:center}
 #am-category-products>:not([data-am-shelf]){order:2}
 #am-category-products [data-am-shelf] .s-block__title{display:block;margin-bottom:24px}
 #am-category-products [data-am-shelf] .right-side{width:100%;display:flex;align-items:center;justify-content:space-between;gap:14px}
 #am-category-products [data-am-shelf] .right-side h2{font-size:clamp(20px,2vw,30px);line-height:1.7;font-weight:700;flex:1}
 #am-category-products .am-view-all{order:1;flex:none}
 #am-category-products [data-am-shelf] custom-salla-product-card{display:flex!important;flex-direction:column!important;border-radius:20px!important;width:100%;min-width:0;height:100%;overflow:hidden}
 #am-category-products [data-am-shelf] .s-product-card-image{width:100%!important;height:auto!important;max-height:none!important;aspect-ratio:1;flex:0 0 auto!important}
 #am-category-products [data-am-shelf] .s-product-card-image a,#am-category-products [data-am-shelf] .s-product-card-image img{display:block;width:100%!important;height:100%!important;object-fit:contain}
 #am-category-products [data-am-shelf] .s-product-card-content{display:flex;flex-direction:column;width:100%!important;min-width:0;flex:1 1 auto!important;padding:20px;text-align:right;box-sizing:border-box}
 #am-category-products [data-am-shelf] .s-product-card-content-title{font-size:18px;min-height:0;text-align:right}
 #am-category-products [data-am-shelf] .s-product-card-content-footer{margin-top:8px}
 @media(max-width:767px){#am-category-products [data-am-shelf] .right-side{padding:0}#am-category-products [data-am-shelf] .s-product-card-content{padding:10px}#am-category-products [data-am-shelf] .s-product-card-content-title{font-size:15px}}
 `;document.head.append(css);
})();
;(()=>{const style=document.createElement("style");style.textContent="body#app #mainnav .am-header-actions{--am-control-height:44px}@media(max-width:767px){body#app #mainnav .am-header-actions{--am-control-height:40px}} body#app #mainnav .am-header-actions :is(.am-header-search,.am-header-address,.s-user-menu-login-btn,.s-user-menu-trigger,.s-cart-summary-wrapper,#am-categories-trigger):is(*,#am-categories-trigger){box-sizing:border-box!important;height:var(--am-control-height)!important;min-height:var(--am-control-height)!important;max-height:var(--am-control-height)!important;block-size:var(--am-control-height)!important;min-block-size:var(--am-control-height)!important;max-block-size:var(--am-control-height)!important;padding-block:0!important;align-self:center!important}body#app #mainnav .am-header-actions #am-categories-trigger,body#app #mainnav .am-header-actions .am-header-search:not(:hover):not(:focus-within):is(*,#am-categories-trigger){width:var(--am-control-height)!important;min-width:var(--am-control-height)!important}\nbody#app header #mainnav .am-header-actions.am-header-actions{display:flex!important;flex-wrap:nowrap!important;align-items:center!important;gap:4px!important}body#app header #mainnav .am-header-actions.am-header-actions>*{margin-inline:0!important;align-self:center!important}body#app header #mainnav .am-header-actions.am-header-actions>:is(salla-cart-summary,salla-user-menu){height:var(--am-control-height)!important;min-height:var(--am-control-height)!important;max-height:var(--am-control-height)!important;display:inline-flex!important;align-items:center!important}body#app header #mainnav .am-header-actions.am-header-actions>.am-header-search:not(:hover):not(:focus-within){flex-basis:var(--am-control-height)!important}@media(max-width:767px){html body#app#app header.store-header #mainnav#mainnav .am-header-actions.am-header-actions{display:grid!important;column-gap:4px!important}html body#app#app header.store-header #mainnav#mainnav .am-header-actions>.am-header-search{justify-self:end!important}}@layer amHeaderBorder{html body#app#app header #mainnav#mainnav .am-header-actions :is(.am-header-search,.am-header-address,.s-user-menu-login-btn,.s-user-menu-trigger,.s-cart-summary-wrapper,#am-categories-trigger){border-width:2px!important;box-sizing:border-box!important}}@layer amHeaderDesktopWidth{@media(min-width:1024px){.am-header-actions{--am-control-height:48px!important}.am-header-actions>:is(#am-categories-trigger,.am-header-search:not(:hover):not(:focus-within)){width:52px!important;min-width:52px!important;max-width:52px!important;flex-basis:52px!important}.am-header-actions>.am-header-address{min-width:48px!important;padding-inline:14px!important}.am-header-actions :is(.s-user-menu-trigger,.s-user-menu-login-btn){padding-left:16px!important}.am-header-actions>salla-cart-summary,.am-header-actions .s-cart-summary-wrapper{min-width:154px!important}}}@layer amMobileAccount{@media(max-width:767px){.am-header-actions salla-user-menu :is(.s-user-menu-trigger,.s-user-menu-login-btn){width:100%!important;min-width:0!important;max-width:100%!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;direction:rtl!important;gap:3px!important;padding:0 2px!important;border:2px solid #ff805c!important;border-radius:12px!important;background-color:transparent!important}.am-header-actions salla-user-menu :is(.s-user-menu-trigger,.s-user-menu-login-btn)::after{content:\"\"!important;position:static!important;order:0!important;flex:0 0 18px!important;width:18px!important;height:18px!important;transform:none!important;background:var(--am-user-art) center/contain no-repeat!important}.am-header-actions salla-user-menu :is(.s-user-menu-trigger,.s-user-menu-login-btn)::before{content:\"حسابي\"!important;position:static!important;order:1!important;font-size:12px!important;line-height:1.25!important;white-space:nowrap!important}.am-header-actions salla-user-menu :is(.s-user-menu-trigger,.s-user-menu-login-btn)>:is(img,svg,span,i,div){display:none!important}}}";document.head.append(style)})();
;(()=>{const style=document.createElement("style");style.id="am-header-icon-centering";style.textContent="@layer amHeaderDesktopWidth{html body#app#app header.store-header #mainnav#mainnav .am-header-actions .am-header-search .s-search-icon,html body#app#app header.store-header #mainnav#mainnav .am-header-actions .am-header-search .s-search-icon-wrap{display:grid!important;place-items:center!important;line-height:1!important} html body#app#app header.store-header #mainnav#mainnav .am-header-actions .am-header-search .s-search-icon svg{display:block!important;margin:auto!important;position:static!important;transform:none!important} html body#app#app header.store-header #mainnav#mainnav .am-header-actions .am-header-search:not(:hover):not(:focus-within) :is(.s-search-placeholder-wrapper,.s-search-input-wrapper,.s-search-input){width:100%!important;min-width:0!important;max-width:100%!important;height:100%!important} html body#app#app header.store-header #mainnav#mainnav .am-header-actions .am-header-search:not(:hover):not(:focus-within) .s-search-icon-wrap{inset:0!important;width:100%!important;height:100%!important;transform:none!important} @media(min-width:1024px){html body#app#app header.store-header #mainnav#mainnav .am-header-actions>.am-header-address{width:auto!important;max-width:none!important;flex:0 0 auto!important;gap:5px!important} html body#app#app header.store-header #mainnav#mainnav .am-header-actions>.am-header-address i{margin:0!important} html body#app#app header.store-header #mainnav#mainnav .am-header-actions salla-user-menu :is(.s-user-menu-trigger,.s-user-menu-login-btn){display:inline-flex!important;align-items:center!important;justify-content:center!important;direction:rtl!important;padding-inline:10px!important;gap:5px!important} html body#app#app header.store-header #mainnav#mainnav .am-header-actions salla-user-menu :is(.s-user-menu-trigger,.s-user-menu-login-btn)::after{position:static!important;order:-1!important;transform:none!important;flex-shrink:0!important}}}";document.head.append(style)})();
;(()=>{const style=document.createElement("style");style.textContent="@media(max-width:767px){#mainnav .am-header-actions salla-user-menu :is(.s-user-menu-wrapper,.s-user-menu-trigger-slot){display:flex!important;align-items:center!important;width:100%!important;min-width:0!important;height:100%!important;box-sizing:border-box!important}}";document.head.append(style)})();
;(()=>{const style=document.createElement("style");style.textContent="@layer amMobileAccount{@media(max-width:767px){html body#app header #mainnav .am-header-actions salla-user-menu :is(.s-user-menu-wrapper,.s-user-menu-trigger-slot){flex:1 1 100%!important;width:100%!important;max-width:100%!important}}}";document.head.append(style)})();
;(()=>{const style=document.createElement("style");style.textContent="@layer amMobileAccount{@media(max-width:767px){#mainnav .am-header-actions salla-cart-summary:not([data-has-items]) .s-cart-summary-wrapper{display:flex!important;flex-direction:column!important;justify-content:center!important;align-items:center!important;gap:1px!important;padding:1px 2px!important} #mainnav .am-header-actions salla-cart-summary:not([data-has-items]) #s-cart-icon,#mainnav .am-header-actions salla-cart-summary:not([data-has-items]) .header-btn__icon{height:16px!important;width:16px!important;min-height:0!important;line-height:16px!important;font-size:15px!important} #mainnav .am-header-actions salla-cart-summary:not([data-has-items]) .s-cart-summary-content,#mainnav .am-header-actions salla-cart-summary:not([data-has-items]) .s-cart-summary-total{display:flex!important;align-items:center!important;justify-content:center!important;position:static!important;gap:2px!important;margin:0!important;padding:0!important;line-height:12px!important;font-size:11px!important;white-space:nowrap!important;color:#102f4d!important} #mainnav .am-header-actions salla-cart-summary:not([data-has-items]) .s-cart-summary-content::before{display:none!important}}}";document.head.append(style)})();
;(()=>{const style=document.createElement("style");style.textContent="@layer amMobileAccount{@media(max-width:767px){#mainnav .am-header-actions salla-cart-summary:not([data-has-items]) .s-cart-summary-wrapper{position:relative!important} #mainnav .am-header-actions salla-cart-summary:not([data-has-items]) .s-cart-summary-content{position:absolute!important;inset: auto 0 4px!important;height:14px!important;transform:none!important} #mainnav .am-header-actions salla-cart-summary:not([data-has-items]) #s-cart-icon{position:absolute!important;inset:2px 0 auto!important;margin-inline:auto!important;transform:none!important}}}";document.head.append(style)})();
;(()=>{const style=document.createElement("style");style.id="am-stable-scroll";style.textContent="html{scroll-behavior:auto!important}html body#app header.store-header{position:sticky!important;top:0!important;z-index:40}html body#app header.store-header #mainnav#mainnav,html body#app header.store-header #mainnav#mainnav>.inner{position:relative!important;top:auto!important;inset-block-start:auto!important;transform:none!important;translate:none!important;transition:none!important;animation:none!important}html body#app :is(.s-product-card-entry,.s-product-card-image img,.am-hub-card,.slide--cat-entry,.am-cat-interactive),html body#app #main-content #am-shop .slide--cat-entry{transform:none!important;translate:none!important;scale:none!important;rotate:none!important;animation:none!important;transition:none!important}html body#app .am-cat-light{display:none!important}";document.head.append(style)})();
;(() => {
  if (location.pathname.replace(/\/$/, '') !== '/cart') return;
  function install() {
    const events = window.salla?.event?.cart;
    if (!events || typeof events.onUpdated !== 'function' || events.onUpdated.amEmptyCart) return;
    const register = events.onUpdated;
    function onUpdated(listener, ...rest) {
      if (typeof listener !== 'function' || !/\.updateCartPageInfo\(/.test(String(listener))) return register.call(this, listener, ...rest);
      return register.call(this, function (cart, ...args) {
        const items = document.querySelector('#main-content .main-content');
        if (cart?.count !== 0 || !items) return listener.call(this, cart, ...args);
        if (items.querySelector('[data-testid="store-cart-empty"]')) return;
        const empty = document.createElement('div');
        empty.className = 'no-content-placeholder';
        empty.dataset.testid = 'store-cart-empty';
        empty.setAttribute('role','status');
        empty.innerHTML = '<i class="sicon-shopping-bag icon" aria-hidden="true"></i><p>سلتك فارغة</p><a data-testid="store-cart-back-home" class="btn btn--outline-primary btn--rounded-full" href="/">العودة إلى الرئيسية</a>';
        setTimeout(() => {
          if (!items.isConnected || items.querySelector('[data-testid="store-cart-empty"]')) return;
          items.parentElement.replaceChildren(items);
          items.replaceChildren(empty);
        }, 0);
      }, ...rest);
    }
    onUpdated.amEmptyCart = true;
    events.onUpdated = onUpdated;
  }
  install();
  window.addEventListener('theme::ready', install, {capture:true,once:true});
  document.addEventListener('DOMContentLoaded', install, {once:true});
})();
;(() => {
  if (!/^\/cart\/?$/.test(location.pathname)) return;
  const style = document.createElement('style');
  style.textContent = '.swal2-container:has(.swal2-toast.am-quiet-cart-update){display:none!important}';
  document.head.append(style);
  function update(popup) {
    const title = popup.querySelector('.swal2-title')?.textContent.trim();
    popup.classList.toggle('am-quiet-cart-update', popup.matches('.swal2-toast.swal2-icon-success') && title === 'تم تحديث البيانات بنجاح');
  }
  function start() {
    document.querySelectorAll('.swal2-popup').forEach(update);
    new MutationObserver(records => {
      const changed = new Set();
      for (const record of records) {
        const target = record.target.nodeType === 1 ? record.target : record.target.parentElement;
        const parent = target?.closest('.swal2-popup');
        if (parent) changed.add(parent);
        for (const node of record.addedNodes) {
          if (node.nodeType !== 1) continue;
          if (node.matches('.swal2-popup')) changed.add(node);
          else node.querySelectorAll('.swal2-popup').forEach(p => changed.add(p));
        }
      }
      changed.forEach(update);
    }).observe(document.body,{childList:true,subtree:true,characterData:true,attributes:true,attributeFilter:['class']});
  }
  if(document.body) start(); else document.addEventListener('DOMContentLoaded',start,{once:true});
})();
;(()=>{const s=document.createElement("style");s.id="am-product-action-layout";s.textContent="body#app .s-product-card-content .s-product-card-content-footer{display:flex!important;align-items:stretch!important;gap:8px!important;width:100%!important;box-sizing:border-box!important;margin-inline:0!important;padding-inline:0!important}body#app .s-product-card-content .s-product-card-content-footer>salla-add-product-button,body#app .s-product-card-content .s-product-card-content-footer>.am07-card-link{flex:1 1 0%!important;min-width:0!important;margin:0!important}body#app .s-product-card-content .s-product-card-content-footer>salla-button.s-product-card-wishlist-btn{flex:0 0 44px!important;width:44px!important;align-self:stretch!important;margin:0!important}body#app .s-product-card-content .s-product-card-content-footer button.s-button-element,body#app .s-product-card-content .s-product-card-content-footer>.am07-card-link,body#app .s-product-card-content>.am-buy-now{box-sizing:border-box!important;width:100%!important;min-width:0!important;height:44px!important;min-height:44px!important;border-radius:9px!important;display:flex!important;align-items:center!important;justify-content:center!important;text-align:center!important;margin-inline:0!important;line-height:1.2!important;padding:2px 6px!important;white-space:normal!important}body#app .s-product-card-content>.am-buy-now{grid-column:1/-1!important;margin-top:8px!important}body#app .s-product-card-content .s-product-card-content-footer>salla-button.s-product-card-wishlist-btn button{padding:0!important;margin:0!important}body#app .s-product-card-content .s-product-card-content-footer .s-button-text{white-space:normal!important;line-height:1.2!important}";document.head.append(s)})();