/* VELAR — optimized JavaScript 2026-10-25. Replace ALL previous custom JavaScript. Install companion CSS first. */
(() => {
  "use strict";
  if (window.__velarPerformance20261025) return;
  window.__velarPerformance20261025 = true;
  const velarDiscovery = (() => {
    const listeners = new Set;
    const nodes = new Set;
    let observer = null;
    let queued = false;
    function flush() {
      queued = false;
      const batch = [ ...nodes ];
      nodes.clear();
      const roots = batch.filter(node => !batch.some(other => other !== node && other.contains(node)));
      const matches = new Map;
      for (const entry of listeners) {
        let found = matches.get(entry.selector);
        if (!found) {
          found = new Set;
          for (const root of roots) {
            if (root.matches(entry.selector)) found.add(root);
            root.querySelectorAll(entry.selector).forEach(node => found.add(node));
          }
          matches.set(entry.selector, found);
        }
        if (found.size) entry.notify(found);
      }
    }
    return function subscribe(selector, notify) {
      const entry = {
        selector: selector,
        notify: notify
      };
      listeners.add(entry);
      if (!observer) {
        observer = new MutationObserver(records => {
          for (const record of records) {
            for (const node of record.addedNodes) if (node.nodeType === 1) nodes.add(node);
            for (const node of record.removedNodes) if (node.nodeType === 1) nodes.add(node);
          }
          if (!nodes.size || queued) return;
          queued = true;
          requestAnimationFrame(flush);
        });
        observer.observe(document.documentElement, {
          childList: true,
          subtree: true
        });
      }
      return () => {
        listeners.delete(entry);
        if (!listeners.size) {
          observer.disconnect();
          observer = null;
          nodes.clear();
        }
      };
    };
  })();
  function watchRelevant(root, selector, callback, extra = {}, includeInside = true) {
    let queued = false;
    let stopped = false;
    const local = new Map;
    function schedule() {
      if (queued || stopped) return;
      queued = true;
      requestAnimationFrame(() => {
        queued = false;
        if (!stopped) callback();
      });
    }
    function attach(element) {
      if (!includeInside || local.has(element)) return;
      const observer = new MutationObserver(schedule);
      observer.observe(element, {
        childList: true,
        subtree: true,
        ...extra
      });
      local.set(element, observer);
    }
    if (root.nodeType === 1 && root.matches(selector)) attach(root);
    root.querySelectorAll(selector).forEach(attach);
    const unsubscribe = velarDiscovery(selector, found => {
      let changed = false;
      for (const element of found) {
        if (root.contains(element)) {
          attach(element);
          changed = true;
        } else if (local.has(element) || !element.isConnected) changed = true;
      }
      for (const [element, observer] of local) {
        if (!root.contains(element)) {
          observer.disconnect();
          local.delete(element);
          changed = true;
        }
      }
      if (changed) schedule();
    });
    return {
      disconnect() {
        stopped = true;
        unsubscribe();
        for (const observer of local.values()) observer.disconnect();
        local.clear();
      }
    };
  }
  (() => {
    if (window.__velarFaqFix) return;
    window.__velarFaqFix = true;
    const ids = new WeakMap;
    let counter = 0;
    function fixFaq() {
      document.querySelectorAll(".s-block--bundle-questions .faq-item").forEach(item => {
        const input = item.querySelector('input[type="checkbox"]');
        const label = item.querySelector("label");
        if (!input || !label) return;
        if (!ids.has(input)) {
          let id;
          do {
            id = `velar-faq-toggle-${++counter}`;
          } while (document.getElementById(id));
          ids.set(input, id);
        }
        const id = ids.get(input);
        if (input.id !== id) input.id = id;
        if (label.htmlFor !== id) label.htmlFor = id;
      });
    }
    function start() {
      fixFaq();
      watchRelevant(document.body, ".s-block--bundle-questions", fixFaq, {
        attributes: true,
        attributeFilter: [ "id", "for" ]
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarSectionNav) return;
    window.__velarSectionNav = true;
    const sections = [ {
      title: "اكتشف منتجاتنا",
      selector: 'section[component-id="1008117744"]',
      id: "velar-products"
    }, {
      title: "العروض",
      selector: 'section[component-id="2028420654"]',
      id: "velar-offers"
    }, {
      title: "حكاية فيلار",
      selector: 'section[component-id="1684567503"]',
      id: "velar-story"
    }, {
      title: "الأسئلة الشائعة",
      selector: ".s-block--faqs",
      id: "velar-questions"
    } ];
    function start() {
      const nav = document.createElement("nav");
      nav.id = "velar-section-nav";
      nav.setAttribute("aria-label", "أقسام الصفحة");
      const desktop = window.matchMedia("(min-width: 1024px)");
      function mount() {
        const mainnav = document.querySelector("#mainnav");
        const inner = mainnav?.querySelector(".inner");
        const row = inner?.querySelector(":scope > .container > .flex");
        const group = row?.firstElementChild;
        const targets = sections.map(section => document.querySelector(section.selector));
        if (!inner || !row || !group || targets.some(t => !t)) {
          nav.remove();
          mainnav?.classList.remove("velar-has-section-nav");
          return;
        }
        targets.forEach((target, index) => {
          if (target.id !== sections[index].id) target.id = sections[index].id;
        });
        if (!nav.children.length) {
          sections.forEach(section => {
            const link = document.createElement("a");
            link.href = "#" + section.id;
            link.textContent = section.title;
            nav.appendChild(link);
          });
        }
        const parent = desktop.matches ? group : inner;
        if (nav.parentElement !== parent) parent.appendChild(nav);
        if (!mainnav.classList.contains("velar-has-section-nav")) mainnav.classList.add("velar-has-section-nav");
        if (desktop.matches) {
          const logo = row.querySelector(".navbar-brand");
          const menu = row.querySelector(".mburger");
          const space = row.getBoundingClientRect().width / 2 - (logo?.getBoundingClientRect().width || 120) / 2 - (menu?.getBoundingClientRect().width || 24) - 40;
          const width = Math.max(0, Math.floor(space)) + "px";
          if (nav.style.getPropertyValue("--velar-nav-space") !== width) {
            nav.style.setProperty("--velar-nav-space", width);
          }
        }
      }
      nav.addEventListener("click", event => {
        const link = event.target.closest("a");
        if (!link || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
        const target = document.getElementById(link.getAttribute("href").slice(1));
        if (!target) return;
        event.preventDefault();
        const header = document.querySelector("#mainnav");
        const banner = document.querySelector(".s-block--header-marquee.in-header");
        const extraScroll = target.id === "velar-products" || target.id === "velar-offers" ? 40 : 0;
        const offset = (header?.getBoundingClientRect().height || 0) + (banner?.getBoundingClientRect().height || 0) + 16 - extraScroll;
        window.scrollTo({
          top: Math.max(0, window.scrollY + target.getBoundingClientRect().top - offset),
          behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth"
        });
      });
      let scheduled = false;
      function schedule() {
        if (scheduled) return;
        scheduled = true;
        requestAnimationFrame(() => {
          scheduled = false;
          mount();
        });
      }
      mount();
      window.addEventListener("resize", schedule);
      window.addEventListener("load", schedule, {
        once: true
      });
      watchRelevant(document.body, "#mainnav, section[component-id], .s-block--faqs", schedule, {}, false);
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarFixedHeader) return;
    window.__velarFixedHeader = true;
    function start() {
      const header = document.querySelector("header.store-header.kesra-store-header");
      if (!header) return;
      const spacer = document.createElement("div");
      spacer.setAttribute("aria-hidden", "true");
      spacer.style.cssText = "display:block;width:100%;flex-shrink:0;pointer-events:none;";
      header.before(spacer);
      header.classList.add("velar-fixed-header");
      let queued = false;
      function updateSpace() {
        if (queued) return;
        queued = true;
        requestAnimationFrame(() => {
          queued = false;
          const height = header.getBoundingClientRect().height;
          if (height <= 0) return;
          const value = height + "px";
          if (spacer.style.height !== value || spacer.style.getPropertyPriority("height") !== "important") {
            spacer.style.setProperty("height", value, "important");
          }
          const rounded = Math.ceil(height) + "px";
          if (document.documentElement.style.getPropertyValue("--velar-header-real-height") !== rounded) {
            document.documentElement.style.setProperty("--velar-header-real-height", rounded);
            window.dispatchEvent(new Event("velar:header-size"));
          }
        });
      }
      new ResizeObserver(updateSpace).observe(header);
      window.addEventListener("resize", updateSpace);
      updateSpace();
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarDiscoverComplete) return;
    window.__velarDiscoverComplete = true;
    function mount() {
      if (document.getElementById("velar-discover-link")) return true;
      const target = document.querySelector('section[component-id="1008117744"]');
      const arrowBox = [ ...document.querySelectorAll("div.absolute.bottom-10.animate-bounce") ].find(box => box.querySelector("svg path")?.getAttribute("d")?.trim() === "m19.5 8.25-7.5 7.5-7.5-7.5");
      if (!arrowBox || !target) return false;
      const banner = arrowBox.closest("section") || arrowBox.parentElement;
      const reference = banner.querySelector("p.text-lg.font-light");
      const svg = arrowBox.querySelector("svg");
      if (!reference || !svg) return false;
      if (!target.id) target.id = "velar-products";
      const link = document.createElement("a");
      link.id = "velar-discover-link";
      link.className = arrowBox.className;
      link.classList.remove("animate-bounce", "opacity-50");
      link.href = "#" + target.id;
      link.style.cssText = `\n      display: flex;\n      flex-direction: column;\n      align-items: center;\n      justify-content: center;\n      gap: 8px;\n      width: max-content;\n      max-width: 90%;\n      min-height: 44px;\n      padding: 4px 8px;\n      opacity: 1 !important;\n      text-decoration: none !important;\n      text-align: center;\n      cursor: pointer;\n    `;
      const text = document.createElement("span");
      text.textContent = "اكتشف عالم فيلار";
      text.style.cssText = `\n      font: inherit !important;\n      color: inherit !important;\n      letter-spacing: inherit !important;\n      white-space: nowrap;\n    `;
      svg.classList.add("animate-bounce");
      svg.style.setProperty("color", "inherit", "important");
      link.append(text, svg);
      arrowBox.replaceWith(link);
      function matchReference() {
        const source = getComputedStyle(reference);
        [ "font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "color" ].forEach(property => {
          const value = source.getPropertyValue(property);
          if (link.style.getPropertyValue(property) !== value) {
            link.style.setProperty(property, value, "important");
          }
        });
      }
      matchReference();
      window.addEventListener("resize", matchReference);
      document.fonts.ready.then(matchReference);
      new ResizeObserver(matchReference).observe(reference);
      link.addEventListener("click", event => {
        if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
        const destination = document.querySelector('section[component-id="1008117744"]');
        if (!destination) return;
        event.preventDefault();
        const header = document.querySelector("header.store-header");
        const offset = Math.max(0, header?.getBoundingClientRect().bottom || 0) + 16;
        window.scrollTo({
          top: Math.max(0, window.scrollY + destination.getBoundingClientRect().top - offset),
          behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth"
        });
      });
      return true;
    }
    function start() {
      if (mount()) return;
      const observer = watchRelevant(document.body, "section, #featured-products-style2-3, .kesra-main-banner", () => {
        if (mount()) observer.disconnect();
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarNaturalCollectionHeading) return;
    window.__velarNaturalCollectionHeading = true;
    function mount() {
      const section = document.getElementById("featured-products-style2-3");
      const container = section?.querySelector(":scope > .container");
      if (!container) return false;
      if (container.querySelector(".velar-collection-heading")) {
        return true;
      }
      const heading = document.createElement("div");
      heading.className = "velar-collection-heading";
      const title = document.createElement("h2");
      title.id = "velar-natural-collection-title";
      title.textContent = "اختيارات من فيلار.";
      const link = document.createElement("a");
      link.className = "velar-collection-link";
      link.href = "https://salla.sa/Velaroud/عود-طبيعي/c1282528204";
      const label = document.createElement("span");
      label.textContent = "عرض المجموعة";
      const arrow = document.createElement("span");
      arrow.textContent = "←";
      arrow.setAttribute("aria-hidden", "true");
      link.append(label, arrow);
      heading.append(title, link);
      container.prepend(heading);
      section.setAttribute("aria-labelledby", title.id);
      return true;
    }
    function start() {
      if (mount()) return;
      const observer = watchRelevant(document.body, "section, #featured-products-style2-3, .kesra-main-banner", () => {
        if (mount()) observer.disconnect();
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarHeroLinks) return;
    window.__velarHeroLinks = true;
    const normalize = text => text.replace(/[\u064B-\u065F\u0670]/g, "").replace(/\s+/g, " ").trim();
    const destinations = {
      "اكتشف منتجاتنا": "#featured-products-style2-3",
      "اختيارات فيلار": "#velar-natural-collection-title",
      "اختيارات من فيلار": "#velar-natural-collection-title",
      "تعرف على فيلار": "#velar-story"
    };
    function mount() {
      const buttons = document.querySelectorAll("div.flex.flex-col.gap-4.justify-center.items-center > a");
      let found = 0;
      buttons.forEach(button => {
        const selector = destinations[normalize(button.textContent)];
        if (!selector) return;
        found++;
        if (button.getAttribute("href") !== selector) button.setAttribute("href", selector);
        if (button.dataset.velarScrollBound) return;
        button.dataset.velarScrollBound = "true";
        button.addEventListener("click", event => {
          if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
          const target = document.querySelector(selector);
          if (!target) return;
          event.preventDefault();
          const header = document.querySelector("header.store-header");
          const offset = Math.max(0, header?.getBoundingClientRect().bottom || 0) + 16;
          window.scrollTo({
            top: Math.max(0, window.scrollY + target.getBoundingClientRect().top - offset),
            behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth"
          });
        });
      });
      return found >= 2;
    }
    function start() {
      if (mount()) return;
      const observer = watchRelevant(document.body, "section, #featured-products-style2-3, .kesra-main-banner", () => {
        if (mount()) observer.disconnect();
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarUnifiedFaq) return;
    window.__velarUnifiedFaq = true;
    const selector = ".s-block--faqs .faq-item > " + 'input[type="checkbox"][id^="velar-faq-toggle-"]';
    function closeOthers(active) {
      document.querySelectorAll(selector).forEach(input => {
        if (input !== active) input.checked = false;
      });
    }
    document.addEventListener("change", event => {
      const active = event.target;
      if (!(active instanceof HTMLInputElement) || !active.matches(selector) || !active.checked) return;
      closeOthers(active);
      queueMicrotask(() => {
        if (active.checked) closeOthers(active);
      });
    }, true);
    function start() {
      const opened = document.querySelector(selector + ":checked");
      if (opened) closeOthers(opened);
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarFaqSingleClickV2) return;
    window.__velarFaqSingleClickV2 = true;
    const selector = ".s-block--faqs .faq-item > " + 'input[type="checkbox"][id^="velar-faq-toggle-"]';
    function toggle(active) {
      const shouldOpen = !active.checked;
      document.querySelectorAll(selector).forEach(input => {
        input.checked = input === active && shouldOpen;
        const label = input.closest(".faq-item")?.querySelector("label");
        label?.setAttribute("aria-expanded", String(input.checked));
      });
    }
    function findInput(target) {
      if (!(target instanceof Element)) return null;
      const label = target.closest(".s-block--faqs .faq-item label");
      const item = label?.closest(".faq-item");
      return item?.querySelector('input[type="checkbox"][id^="velar-faq-toggle-"]') || (target.matches(selector) ? target : null);
    }
    window.addEventListener("click", event => {
      const input = findInput(event.target);
      if (!input) return;
      event.preventDefault();
      event.stopImmediatePropagation();
      toggle(input);
    }, true);
  })();
  (() => {
    if (window.__velarProductLayoutReviewed) return;
    window.__velarProductLayoutReviewed = true;
    const priceSnapshots = new WeakMap;
    const descriptionSnapshots = new WeakMap;
    function addClass(element, name) {
      if (!element.classList.contains(name)) element.classList.add(name);
    }
    function markHeadings(info) {
      info.querySelectorAll(".product__description article").forEach(article => {
        if (descriptionSnapshots.get(article) === article.innerHTML) return;
        const paragraphs = Array.from(article.children).filter(element => element.tagName === "P" && element.textContent.trim());
        paragraphs.forEach((paragraph, index) => {
          const text = paragraph.textContent.trim();
          const bold = paragraph.querySelector(":scope > strong:only-child, :scope > b:only-child");
          const heading = Boolean(bold && bold.textContent.trim() === text && (index === 0 || /[:：]$/.test(text)));
          if (paragraph.classList.contains("velar-description-heading") !== heading) {
            paragraph.classList.toggle("velar-description-heading", heading);
          }
        });
        descriptionSnapshots.set(article, article.innerHTML);
      });
    }
    function updateProduct(info) {
      const layout = info.parentElement;
      const photo = layout?.querySelector(":scope > .kesra-sidebar");
      const title = info.querySelector("h1");
      const price = info.querySelector(".kesra-price");
      const form = info.querySelector("form.product-form");
      if (!photo || !title || !price || !form) return;
      addClass(layout, "velar-product-v2");
      let heading = info.querySelector(":scope > .velar-product-heading");
      if (!heading) {
        heading = document.createElement("div");
        heading.className = "velar-product-heading";
        title.before(heading);
      }
      if (title.parentElement !== heading) heading.append(title);
      if (price.parentElement !== heading) heading.append(price);
      Array.from(form.children).forEach(element => {
        if (element.tagName === "SECTION" && element.querySelector(".price-wrapper")) {
          addClass(element, "velar-duplicate-price");
        }
      });
      const description = layout.querySelector(".product__description");
      if (description) {
        addClass(description, "velar-description");
        if (heading.nextElementSibling !== description) heading.after(description);
      }
      markHeadings(info);
      const options = form.querySelector("salla-product-options");
      if (options) {
        let row = form.querySelector(".velar-extra-price");
        if (!row) {
          row = document.createElement("div");
          row.className = "velar-extra-price";
          const label = document.createElement("span");
          label.textContent = "السعر";
          const value = document.createElement("div");
          value.className = "velar-extra-price__value";
          row.append(label, value);
        }
        if (options.nextElementSibling !== row) options.after(row);
        const value = row.querySelector(".velar-extra-price__value");
        const source = price.innerHTML;
        const previous = priceSnapshots.get(price);
        if (!previous || previous.source !== source || previous.value !== value || value.innerHTML !== previous.rendered) {
          const snapshot = price.cloneNode(true);
          snapshot.querySelectorAll("[id]").forEach(element => element.removeAttribute("id"));
          snapshot.querySelectorAll(".total-price").forEach(element => {
            element.classList.replace("total-price", "velar-extra-amount");
          });
          const rendered = snapshot.innerHTML;
          if (value.innerHTML !== rendered) value.innerHTML = rendered;
          priceSnapshots.set(price, {
            source: source,
            value: value,
            rendered: rendered
          });
        }
      }
      addClass(layout, "velar-product-ready");
    }
    let main = null;
    let observer = null;
    let queued = false;
    function update() {
      if (!main) return;
      main.querySelectorAll(".kesra-main-content").forEach(info => {
        try {
          updateProduct(info);
        } catch (error) {
          if (info.parentElement) addClass(info.parentElement, "velar-product-ready");
          console.warn("VELAR product layout:", error);
        }
      });
    }
    function schedule() {
      if (queued) return;
      queued = true;
      requestAnimationFrame(() => {
        queued = false;
        observer?.disconnect();
        try {
          update();
        } finally {
          observeProduct();
        }
      });
    }
    function observeProduct() {
      if (!main || !observer) return;
      observer.observe(main, {
        childList: true,
        subtree: true,
        characterData: true
      });
      main.querySelectorAll(".kesra-price").forEach(price => {
        observer.observe(price, {
          childList: true,
          subtree: true,
          characterData: true,
          attributes: true,
          attributeFilter: [ "class", "style", "hidden" ]
        });
      });
    }
    function attach() {
      const nextMain = document.getElementById("main-content");
      if (!nextMain) return false;
      if (main === nextMain) return true;
      observer?.disconnect();
      main = nextMain;
      update();
      observer = new MutationObserver(records => {
        const structure = ".kesra-main-content, .kesra-sidebar, .kesra-price, h1, form.product-form, salla-product-options, .product__description";
        if (records.some(record => {
          const el = record.target.nodeType === 1 ? record.target : record.target.parentElement;
          if (el?.closest(".velar-extra-price")) return false;
          if (el?.closest(".kesra-price, .product__description")) return true;
          return [ ...record.addedNodes, ...record.removedNodes ].some(node => node.nodeType === 1 && (node.matches(structure) || node.querySelector(structure)));
        })) schedule();
      });
      observeProduct();
      return true;
    }
    velarDiscovery("#main-content", () => attach());
    window.addEventListener("pageshow", () => {
      if (attach()) schedule();
    });
    if (!attach()) document.addEventListener("DOMContentLoaded", attach, {
      once: true
    });
  })();
  (() => {
    if (window.__velarFastCheckoutColor) return;
    window.__velarFastCheckoutColor = true;
    const css = `\n    button.s-fast-checkout-button.outline,\n    button.s-fast-checkout-button.outline:is(:hover, :focus, :active) {\n      background: #75603D !important;\n      border: 1px solid #75603D !important;\n      color: #FFFDF9 !important;\n      box-shadow: none !important;\n    }\n\n    button.s-fast-checkout-button.outline svg path {\n      fill: #FFFDF9 !important;\n    }\n\n    .s-add-product-button-mini-checkout-content,\n    .s-add-product-button-mini-checkout-content span {\n      color: #FFFDF9 !important;\n    }\n\n    .s-add-product-button-mini-checkout-content svg path {\n      fill: #FFFDF9 !important;\n    }\n  `;
    const observed = new WeakSet;
    const waitingDefinitions = new WeakSet;
    const pending = new Set;
    const widgetSelector = "salla-mini-checkout-widget, button.s-fast-checkout-button";
    let queued = false;
    function enqueue(node) {
      if (!node || ![ 1, 11 ].includes(node.nodeType)) return;
      pending.add(node);
      if (queued) return;
      queued = true;
      requestAnimationFrame(() => {
        queued = false;
        const batch = [ ...pending ];
        pending.clear();
        batch.forEach(node => {
          if (node.isConnected && !batch.some(parent => parent !== node && parent.contains(node))) {
            scan(node);
          }
        });
      });
    }
    function inject(root) {
      if (root.querySelector("style[data-velar-fast-color]")) return;
      const style = document.createElement("style");
      style.setAttribute("data-velar-fast-color", "");
      style.textContent = css;
      (root === document ? document.head : root).append(style);
    }
    function observe(root) {
      if (observed.has(root)) return;
      observed.add(root);
      new MutationObserver(records => {
        for (const record of records) {
          if (record.type === "attributes" && record.target === root) enqueue(root); else record.addedNodes.forEach(enqueue);
        }
      }).observe(root, {
        childList: true,
        subtree: true
      });
      if (root.nodeType === 1) new MutationObserver(() => enqueue(root)).observe(root, {
        attributes: true,
        attributeFilter: [ "class" ]
      });
    }
    function inspect(element) {
      if (element.shadowRoot && !observed.has(element.shadowRoot)) scan(element.shadowRoot);
      if (element.localName.includes("-") && !waitingDefinitions.has(element)) {
        waitingDefinitions.add(element);
        observe(element);
        customElements.whenDefined(element.localName).then(() => enqueue(element));
      }
      if (element.matches("button.s-fast-checkout-button")) {
        const root = element.getRootNode();
        if (root === document || root instanceof ShadowRoot) inject(root);
      }
    }
    function scan(root) {
      if (root instanceof ShadowRoot) observe(root);
      if (root.nodeType === 1) inspect(root);
      root.querySelectorAll("*").forEach(inspect);
    }
    function start() {
      inject(document);
      document.querySelectorAll(widgetSelector).forEach(scan);
      velarDiscovery(widgetSelector, widgets => {
        widgets.forEach(widget => {
          if (widget.isConnected) enqueue(widget);
        });
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else start();
  })();
  (() => {
    function fitVelarBanner() {
      const banner = document.querySelector('section.kesra-main-banner[component-id="486279619"]');
      if (!banner) return;
      const viewportHeight = window.innerHeight;
      const bannerTop = Math.max(0, banner.getBoundingClientRect().top + window.scrollY);
      if (bannerTop >= viewportHeight) return;
      const height = `${Math.floor(viewportHeight - bannerTop)}px`;
      if (banner.style.getPropertyValue("height") !== height || banner.style.getPropertyPriority("height") !== "important") {
        banner.style.setProperty("height", height, "important");
      }
    }
    let pending = false;
    const update = () => {
      if (pending) return;
      pending = true;
      requestAnimationFrame(() => {
        pending = false;
        fitVelarBanner();
      });
    };
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", update, {
        once: true
      });
    } else {
      update();
    }
    window.addEventListener("load", update, {
      once: true
    });
    window.addEventListener("resize", update);
    window.addEventListener("velar:header-size", update);
    if (document.fonts) {
      document.fonts.ready.then(update);
    }
  })();
  (() => {
    function renameVelarMenu() {
      document.querySelectorAll("header a, header span").forEach(el => {
        if (el.children.length === 0 && el.textContent.trim() === "اكتشف منتجاتنا") {
          el.textContent = "اختيارات من فيلار";
        }
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", renameVelarMenu);
    } else {
      renameVelarMenu();
    }
    window.addEventListener("load", renameVelarMenu);
  })();
  (() => {
    if (window.velarCollectionLinkFixed) return;
    window.velarCollectionLinkFixed = true;
    window.addEventListener("click", event => {
      if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
      const link = event.target instanceof Element ? event.target.closest('section[component-id="486279619"] a') : null;
      if (!link || !/^اختيارات\s+(من\s+)?فيلار$/.test(link.textContent.trim())) return;
      const target = document.getElementById("velar-natural-collection-title");
      if (!target) return;
      event.preventDefault();
      event.stopImmediatePropagation();
      window.scrollTo({
        top: Math.max(0, window.scrollY + target.getBoundingClientRect().top - 120),
        behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "instant" : "smooth"
      });
    }, true);
  })();
  (() => {
    if (window.__velarCategoryTitle) return;
    window.__velarCategoryTitle = true;
    const categoryId = path => path.match(/\/c(\d+)(?:\/|$)/)?.[1];
    function updateTitle() {
      const id = categoryId(location.pathname);
      const title = document.getElementById("page-main-title");
      if (!id || !title) return;
      const crumbs = [ ...document.querySelectorAll(".s-breadcrumb-item") ];
      const current = crumbs[crumbs.length - 1];
      let name = current && !current.querySelector("a") ? current.textContent.trim() : "";
      if (!name) {
        const link = [ ...document.querySelectorAll("#mobile-menu a[href]") ].find(a => {
          try {
            return categoryId(new URL(a.href, location.href).pathname) === id;
          } catch {
            return false;
          }
        });
        name = link?.textContent.trim() || "";
      }
      if (name && title.textContent.trim() !== name) {
        title.textContent = name;
      }
    }
    let queued = false;
    function schedule() {
      if (queued) return;
      queued = true;
      requestAnimationFrame(() => {
        queued = false;
        updateTitle();
      });
    }
    function start() {
      if (!categoryId(location.pathname)) return;
      updateTitle();
      watchRelevant(document.body, "#page-main-title, .s-breadcrumb-item, #mobile-menu", schedule, {
        characterData: true
      });
      window.addEventListener("popstate", schedule);
      window.addEventListener("pageshow", schedule);
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarManualBadges) return;
    window.__velarManualBadges = true;
    const selector = ".s-product-options-grid-mode-span";
    function updateOption(el) {
      const label = el.closest("label");
      if (!label) return;
      const text = el.textContent.trim();
      const splitAt = text.indexOf("|");
      let badge = label.querySelector(".velar-option-badge");
      if (splitAt < 0) {
        if (el.dataset.velarCleanText === text) return;
        if (badge) badge.remove();
        label.classList.remove("velar-has-badge");
        delete el.dataset.velarCleanText;
        return;
      }
      const name = text.slice(0, splitAt).trim();
      const message = text.slice(splitAt + 1).trim();
      if (!name) return;
      el.dataset.velarCleanText = name;
      el.textContent = name;
      if (!message) {
        if (badge) badge.remove();
        label.classList.remove("velar-has-badge");
        return;
      }
      if (!badge) {
        badge = document.createElement("span");
        badge.className = "velar-option-badge";
        label.appendChild(badge);
      }
      badge.textContent = message;
      label.classList.add("velar-has-badge");
    }
    function scan(node) {
      if (node.nodeType !== 1) return;
      if (node.matches(selector)) updateOption(node);
      node.querySelectorAll(selector).forEach(updateOption);
    }
    function start() {
      scan(document.body);
      watchRelevant(document.body, ".s-product-options-grid-mode", () => {
        document.querySelectorAll(".s-product-options-grid-mode").forEach(scan);
      }, {
        characterData: true
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    const radioSelector = '.s-product-options-option input[type="radio"]';
    const watchedGrids = new WeakSet;
    function watchGrid(grid) {
      if (watchedGrids.has(grid)) return;
      watchedGrids.add(grid);
      new MutationObserver(scheduleUpdate).observe(grid, {
        subtree: true,
        childList: true,
        characterData: true,
        attributes: true,
        attributeFilter: [ "disabled", "checked", "class", "required", "value" ]
      });
    }
    function updateDropdowns() {
      const grids = new Set(
        [...document.querySelectorAll(radioSelector)]
          .filter(input => {
            const title = input.closest(".s-product-options-option")
              ?.querySelector(".s-product-options-option-label b")?.textContent || "";
            const normalized = title.normalize("NFKC")
              .replace(/[\u064B-\u065F\u0670\u0640]/g, "")
              .replace(/[أإآ]/g, "ا").replace(/\s+/g, " ").trim();
            return /تغليف\s*(?:ال)?هدايا/.test(normalized);
          })
          .map(input => input.closest(".s-product-options-grid-mode"))
          .filter(Boolean)
      );
      grids.forEach(grid => {
        watchGrid(grid);
        const radios = [ ...grid.querySelectorAll(radioSelector) ];
        const container = grid.parentElement;
        let select = [ ...container.children ].find(element => element.matches("select.velar-gift-dropdown"));
        if (!select) {
          select = document.createElement("select");
          select.className = "velar-gift-dropdown";
          select.setAttribute("aria-label", "تغليف هدايا");
          container.insertBefore(select, grid);
        }
        const choices = radios.map(radio => {
          const label = radio.closest("label");
          return {
            value: radio.value,
            text: (label.querySelector(".s-product-options-grid-mode-span") || label).textContent.trim(),
            disabled: radio.disabled || label.classList.contains("s-product-options-option-stock-out")
          };
        });
        const signature = JSON.stringify(choices);
        if (select.dataset.signature !== signature) {
          const placeholder = new Option("اختر", "");
          placeholder.disabled = true;
          select.replaceChildren(placeholder, ...choices.map(choice => {
            const option = new Option(choice.text, choice.value);
            option.disabled = choice.disabled;
            return option;
          }));
          select.dataset.signature = signature;
        }
        const required = radios.some(radio => radio.required);
        const disabled = radios.every(radio => radio.disabled);
        const selected = radios.find(radio => radio.checked)?.value || "";
        if (select.required !== required) select.required = required;
        if (select.disabled !== disabled) select.disabled = disabled;
        if (select.value !== selected) select.value = selected;
        select.onchange = () => {
          const radio = radios.find(item => item.value === select.value);
          if (radio && !radio.disabled && !radio.checked) {
            radio.click();
          }
        };
        radios.forEach(radio => {
          radio.oninvalid = event => {
            event.preventDefault();
            select.focus();
            select.reportValidity();
          };
        });
        if (grid.style.getPropertyValue("display") !== "none") {
          grid.style.setProperty("display", "none", "important");
        }
      });
    }
    let scheduled = false;
    function scheduleUpdate() {
      if (scheduled) return;
      scheduled = true;
      requestAnimationFrame(() => {
        scheduled = false;
        updateDropdowns();
      });
    }
    function start() {
      updateDropdowns();
      watchRelevant(document.body, radioSelector, scheduleUpdate, {}, false);
      document.addEventListener("change", event => {
        if (event.target instanceof Element && event.target.matches(radioSelector)) scheduleUpdate();
      }, true);
      document.addEventListener("reset", event => {
        if (event.target instanceof Element && event.target.querySelector(radioSelector)) scheduleUpdate();
      }, true);
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    if (window.__velarNaturalArt) return;
    window.__velarNaturalArt = true;
    const artworks = {
      1282528204: "https://cdn.files.salla.network/products/1447472520/ee305448-476e-4553-ac05-2efb86b606ac-original.webp",
      606139952: "https://cdn.files.salla.network/other/1447472520/1d7f8ab5-f904-44f2-9e99-79b11be011ab-original.webp",
      2062614376: "https://cdn.files.salla.network/other/1447472520/88d1a385-3eba-4e2b-8c0d-ef4e2f182f3b-original.webp",
      1179042957: "https://cdn.files.salla.network/other/1447472520/997d6aee-dfa6-4cc0-a8f7-47aafedd83f5-original.webp",
      1025648482: "https://cdn.files.salla.network/other/1447472520/6daa4448-a964-4c27-acf9-e26b7e9adccd-original.webp"
    };
    const artworkCacheKey = "velar-product-artwork-v1";
    let artworkCache;
    function cachedArtwork(key, value) {
      try {
        const cache = artworkCache || (artworkCache = JSON.parse(sessionStorage.getItem(artworkCacheKey) || "{}"));
        if (value && cache[key] !== value) {
          cache[key] = value;
          sessionStorage.setItem(artworkCacheKey, JSON.stringify(cache));
        }
        return cache[key];
      } catch (_) {
        return null;
      }
    }
    let pending = false;
    const observed = new WeakSet;
    const resizeObserver = new ResizeObserver(schedule);
    function schedule() {
      if (pending) return;
      pending = true;
      requestAnimationFrame(() => {
        pending = false;
        render();
      });
    }
    function render() {
      const product = document.querySelector("#main-content .velar-product-v2");
      const active = Boolean(product);
      if (document.body.classList.contains("velar-natural-art") !== active) {
        document.body.classList.toggle("velar-natural-art", active);
      }
      if (!product) return;
      const links = [ ...document.querySelectorAll("#main-content salla-breadcrumb a[href]") ].reverse();
      let artworkUrl = "";
      for (const link of links) {
        const id = new URL(link.href, location.href).pathname.match(/\/c(\d+)(?:\/|$)/)?.[1];
        if (artworks[id]) {
          artworkUrl = artworks[id];
          break;
        }
      }
      let sketch = product.querySelector(":scope > .velar-natural-sketch");
      const productKey = location.pathname.replace(/\/$/, "");
      if (artworkUrl) cachedArtwork(productKey, artworkUrl);
      if (!artworkUrl) {
        const cached = cachedArtwork(productKey);
        artworkUrl = Object.values(artworks).includes(cached) ? cached : artworks["1282528204"];
      }
      const sidebar = product.querySelector(":scope > .kesra-sidebar");
      const gallery = sidebar?.querySelector("salla-slider");
      const purchase = product.querySelector("salla-add-product-button[quick-buy]");
      if (!sidebar || !gallery || !purchase) return;
      if (!sketch) {
        sketch = document.createElement("div");
        sketch.className = "velar-natural-sketch";
        sketch.setAttribute("aria-hidden", "true");
        product.appendChild(sketch);
      }
      const background = `url("${artworkUrl}")`;
      if (sketch.style.getPropertyValue("background-image") !== background || sketch.style.getPropertyPriority("background-image") !== "important") {
        sketch.style.setProperty("background-image", background, "important");
      }
      [ product, sidebar, gallery, purchase ].forEach(element => {
        if (observed.has(element)) return;
        observed.add(element);
        resizeObserver.observe(element);
      });
      if (window.innerWidth < 768) return;
      const root = product.getBoundingClientRect();
      const side = sidebar.getBoundingClientRect();
      const photo = gallery.getBoundingClientRect();
      const button = purchase.getBoundingClientRect();
      const top = photo.bottom - root.top + 24;
      const bottom = button.top - root.top - 16;
      const geometry = {
        left: `${side.left - root.left}px`,
        top: `${top}px`,
        width: `${side.width}px`,
        height: `${Math.max(0, bottom - top)}px`
      };
      Object.entries(geometry).forEach(([property, value]) => {
        if (sketch.style[property] !== value) sketch.style[property] = value;
      });
    }
    function start() {
      const structure = ".velar-product-v2, .kesra-main-content, .kesra-sidebar, salla-slider, salla-add-product-button[quick-buy], salla-breadcrumb";
      const relevantNode = node => node.nodeType === 1 && (node.matches(structure) || Boolean(node.querySelector(structure)));
      let watchedMain = null;
      const observer = new MutationObserver(records => {
        if (records.some(record => {
          const element = record.target.nodeType === 1 ? record.target : record.target.parentElement;
          if (element?.closest("salla-breadcrumb")) return true;
          if (record.type === "attributes") return element?.matches(".velar-product-v2");
          return [ ...record.addedNodes, ...record.removedNodes ].some(relevantNode);
        })) schedule();
      });
      function bindProduct() {
        const main = document.getElementById("main-content");
        if (watchedMain && watchedMain !== main) {
          observer.disconnect();
          watchedMain = null;
        }
        if (!main || !main.querySelector(".kesra-main-content")) return;
        if (main !== watchedMain) {
          watchedMain = main;
          observer.observe(main, {
            childList: true,
            subtree: true,
            attributes: true,
            attributeFilter: [ "href", "class" ]
          });
        }
        schedule();
      }
      velarDiscovery("#main-content, .kesra-main-content", bindProduct);
      bindProduct();
      window.addEventListener("resize", schedule, {
        passive: true
      });
      window.addEventListener("load", schedule);
      window.addEventListener("pageshow", schedule);
      window.addEventListener("popstate", schedule);
      document.addEventListener("load", event => {
        if (event.target instanceof Element && event.target.closest(".velar-product-v2 .kesra-sidebar")) schedule();
      }, true);
      document.fonts?.ready.then(schedule);
      schedule();
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, {
        once: true
      });
    } else {
      start();
    }
  })();
  (() => {
    function addCartSketch() {
      const main = document.querySelector('#main-content:has(salla-hook[name="cart:start"])');
      if (!main || main.querySelector(".velar-cart-sketch")) return;
      const sketch = document.createElement("div");
      sketch.className = "velar-cart-sketch";
      sketch.setAttribute("aria-hidden", "true");
      main.appendChild(sketch);
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", addCartSketch, {
        once: true
      });
    } else {
      addCartSketch();
    }
  })();
  (() => {
    function applyOilLabels() {
      const parent = window.salla?.config?.get("page.parent");
      if (!parent) return;
      const categoryUrl = String(parent.url || "");
      const categoryName = String(parent.title || "").trim();
      const isOil = categoryUrl.includes("c2062614376") || [ "دهن طبيعي", "دهن العود", "دهن عود طبيعي", "الأدهان" ].includes(categoryName);
      if (!isOil) return;
      const weights = document.querySelectorAll(".product-weight");
      weights.forEach(weight => {
        const section = weight.closest("section");
        if (!section || section.dataset.velarOilLabels) return;
        section.dataset.velarOilLabels = "true";
        function updateLabels() {
          const label = section.querySelector(".form-label span");
          if (label?.textContent.trim() === "الوزن") {
            label.textContent = "الحجم";
          }
          const value = section.querySelector(".product-weight");
          if (!value) return;
          const original = value.textContent;
          const updated = original.replace(/جم|جرام|غرام|\bg\b/gi, "مل");
          if (updated !== original) {
            value.textContent = updated;
          }
        }
        updateLabels();
        new MutationObserver(updateLabels).observe(section, {
          childList: true,
          characterData: true,
          subtree: true
        });
      });
    }
    if (window.Salla?.onReady) {
      window.Salla.onReady(applyOilLabels);
    } else if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", applyOilLabels, {
        once: true
      });
    } else {
      applyOilLabels();
    }
  })();
})();

(() => {
  function markCatchProduct() {
    if (!document.body.classList.contains('product-single')) return;

    const breadcrumb = document.querySelector('nav.breadcrumbs, salla-breadcrumb');
    if (!breadcrumb) return;

    function updateCategory() {
      const root = breadcrumb.querySelector('salla-breadcrumb') || breadcrumb;
      const links = (root.shadowRoot || root).querySelectorAll('a');
      const isCatch = Array.from(links).some(link =>
        link.textContent.trim().replace(/\s+/g, ' ') === 'صيدات فيلار'
      );
      document.body.classList.toggle('velar-catch', isCatch);
    }

    updateCategory();
    new MutationObserver(updateCategory).observe(breadcrumb, {
      childList: true,
      subtree: true,
      characterData: true
    });
    customElements.whenDefined('salla-breadcrumb').then(updateCategory);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', markCatchProduct, { once: true });
  } else {
    markCatchProduct();
  }
})();

;(() => {
const sectionId = 'featured-products-style2-3';
const categoryIds = [1282528204];
const count = 4;

function selectDaily(products) {
// Riyadh is UTC+3. Start with a stable catalogue order across visitors.
const day = Math.floor((Date.now() + 3 * 3600000) / 86400000);
const pool = products.sort((a, b) => Number(a.id) - Number(b.id));
if (!pool.length) return [];
let seed = 0x56e1a4;
function shuffle(items) {
for (let i = items.length - 1; i > 0; i--) {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
const j = Math.floor((seed / 4294967296) * (i + 1));
[items[i], items[j]] = [items[j], items[i]];
}
return items;
}
shuffle(pool);
// Advance by up to four places; even a small pool rotates.
const step = Math.min(count, Math.max(1, pool.length - count));
const start = (day * step) % pool.length;
const picks = Array.from({length: Math.min(count, pool.length)},
(_, index) => pool[(start + index) % pool.length]);
seed = day;
return shuffle(picks);
}

async function loadOud() {
const products = new Map();
const seen = new Set();
const query = {source: 'categories', source_value: categoryIds, per_page: 50};
while (true) {
const response = await salla.product.fetch(query);
const body = Array.isArray(response.data) ? response : response.data;
if (!Array.isArray(body?.data)) throw new Error('Unexpected catalogue response');
for (const p of body.data) {
if (p.id && p.status === 'sale' && !p.is_out_of_stock && p.is_available !== false) {
products.set(String(p.id), p);
}
}
if (!body.cursor?.next) return [...products.values()];
const next = new URL(body.cursor.next, location.origin).searchParams;
const cursor = next.get('cursor');
if (!cursor || seen.has(cursor)) throw new Error('Invalid catalogue cursor');
seen.add(cursor);
query.cursor = cursor;
query.page = Number(next.get('page')) || (query.page || 1) + 1;
}
}

async function start() {
const section = document.getElementById(sectionId);
const original = section?.querySelector('.tabs__item.is-active salla-products-list');
if (!original || section.dataset.velarOudLoading) return;
section.dataset.velarOudLoading = '1';
try {
await customElements.whenDefined('custom-salla-product-card');
const picks = selectDaily(await loadOud());
const grid = document.createElement('div');
grid.className = 's-products-list-wrapper s-products-list-vertical-cards';
for (const product of picks) {
const card = document.createElement('custom-salla-product-card');
card.product = product;
// The theme hides all cards except four hard-coded IDs.
card.style.cssText = 'display:flex!important;flex-direction:column!important;align-items:stretch;align-self:stretch;box-sizing:border-box;width:100%;min-width:0;max-width:none;height:100%;margin:0;padding:0;background:var(--velar-white);color:var(--velar-charcoal);border:1px solid rgba(51,45,39,.14);border-radius:8px;box-shadow:none;overflow:hidden;order:0!important';
grid.append(card);
}
original.replaceWith(grid);
} catch (error) {
delete section.dataset.velarOudLoading;
console.warn('[Velar] Could not load daily oud selection.', error);
}
}

function ready() {
if (window.salla?.onReady) window.salla.onReady(start);
else if (window.salla?.product?.fetch) start();
else document.addEventListener('salla::ready', start, {once: true});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', ready, {once: true});
} else {
ready();
}
})();