XStore theme eCommerce WordPress Themes xstore official website WooCommerce templates for modern stores Find additional templates Find your perfect theme Official website XStore by 8theme wordpress support forum 8theme.com - WooCommerce WordPress themes Click here to see more XStore theme by 8theme.com best wordpress themes Learn more WordPress WooCommerce Themes Explore our best WordPress themes here Discover WooCommerce templates for your online store Find the perfect WordPress theme for your business Browse our collection of premium WooCommerce themes See our top-rated WordPress eCommerce themes Premium WordPress Themes Try XStore Demo WooCommerce Themes Read more on our blog WordPress Themes 8theme WordPress forum Visit website WordPress Themes by 8theme Check XStore Docs wordpress support forum See our recommended WordPress themes Best WooCommerce Themes XStore WordPress Themes XStore Documentation eCommerce WordPress Themes

توب رست لتوزيع المياه

تسوق كراتين المياه من علامات تكاريه متعددة بأحجام مختلفة مع خدمة التوصيل للمنازل والمساجد مجانا

توب رست لتوزيع المياه
وسائل دفع متعددة

نوفر خيارات دفع متعددة حسب الوسائل المتاحة في المتجر

تنفيذ الطلب

تتم معالجة الطلب بعد تأكيد البيانات وتوفر المنتج

متابعة الطلب

يمكن التواصل معك لتأكيد تفاصيل الطلب وموعد التوصيل

أحدث العروض الحالية

عرض مياه الحبيبة 200 مل – 10+1 مجانًا بـ130 ريال

السعر الأصلي هو: SAR 143.00.السعر الحالي هو: SAR 130.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

عرض مياه وطني 200 مل – 15 كرتون بـ199 ريال

السعر الأصلي هو: SAR 235.20.السعر الحالي هو: SAR 199.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

عرض مياه أوسكا 200 مل – 14+1 مجانًا بـ210 ريال

السعر الأصلي هو: SAR 235.80.السعر الحالي هو: SAR 210.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

عرض مياه الحبيبة 200 مل – 20 كرتون بـ230 ريال

السعر الأصلي هو: SAR 260.00.السعر الحالي هو: SAR 230.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

عرض مياه منعا 200 مل – 15+1 مجانًا بـ240 ريال

السعر الأصلي هو: SAR 272.00.السعر الحالي هو: SAR 240.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

عرض مياه تانيا 200 مل – 15+1 مجانًا بـ249 ريال

السعر الأصلي هو: SAR 312.00.السعر الحالي هو: SAR 249.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

سقيا المساجد – مياه سقيا المدينة 200 مل × 20 كرتون

السعر الأصلي هو: SAR 260.00.السعر الحالي هو: SAR 249.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

عرض مياه بيرين 200 مل – 15 كرتون بـ285 ريال

السعر الأصلي هو: SAR 320.25.السعر الحالي هو: SAR 285.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

الاكثر مبيعاً

مياه الريان 200 مل – كرتون 48 عبوة

السعر الأصلي هو: SAR 13.00.السعر الحالي هو: SAR 12.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه الحبيبة 200 مل (كرتون 48 عبوة)

السعر الأصلي هو: SAR 13.00.السعر الحالي هو: SAR 11.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه اوسكا 200 مل – كرتون 48 عبوة

السعر الأصلي هو: SAR 15.72.السعر الحالي هو: SAR 14.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه رست 200 مل – كرتون 48 عبوة

السعر الأصلي هو: SAR 19.00.السعر الحالي هو: SAR 17.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه الريان 330 مل – كرتون 40 عبوة

السعر الأصلي هو: SAR 15.00.السعر الحالي هو: SAR 13.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه عذبة 330 مل – شدة 24 عبوة

السعر الأصلي هو: SAR 6.55.السعر الحالي هو: SAR 5.75. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه منعا 200 مل ربطة 20 عبوة

السعر الأصلي هو: SAR 7.99.السعر الحالي هو: SAR 6.99. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه اوسكا 330 مل كرتون 40 عبوة

السعر الأصلي هو: SAR 15.72.السعر الحالي هو: SAR 14.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

حجم 200 مل

مياه الريان 200 مل – كرتون 48 عبوة

السعر الأصلي هو: SAR 13.00.السعر الحالي هو: SAR 12.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه الحبيبة 200 مل (كرتون 48 عبوة)

السعر الأصلي هو: SAR 13.00.السعر الحالي هو: SAR 11.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه اوسكا 200 مل – كرتون 48 عبوة

السعر الأصلي هو: SAR 15.72.السعر الحالي هو: SAR 14.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه رست 200 مل – كرتون 48 عبوة

السعر الأصلي هو: SAR 19.00.السعر الحالي هو: SAR 17.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه منعا 200 مل ربطة 20 عبوة

السعر الأصلي هو: SAR 7.99.السعر الحالي هو: SAR 6.99. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه سقيا المدينة 200 مل كرتون 48 عبوة

السعر الأصلي هو: SAR 16.50.السعر الحالي هو: SAR 13.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه سقيا المدينة 200 مل 24 عبوة

السعر الأصلي هو: SAR 6.50.السعر الحالي هو: SAR 5.90. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه بيرين – 200 مل – 48 عبوة

SAR 21.35 SAR 19.80 إضافة إلى السلة

حجم 330 مل

مياه الريان 330 مل – كرتون 40 عبوة

السعر الأصلي هو: SAR 15.00.السعر الحالي هو: SAR 13.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه عذبة 330 مل – شدة 24 عبوة

السعر الأصلي هو: SAR 6.55.السعر الحالي هو: SAR 5.75. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه اوسكا 330 مل كرتون 40 عبوة

السعر الأصلي هو: SAR 15.72.السعر الحالي هو: SAR 14.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه الحبيبة 330 مل كرتون 40 عبوة

السعر الأصلي هو: SAR 13.00.السعر الحالي هو: SAR 12.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه سقيا المدينة 330 مل شرنك 20 عبوة

السعر الأصلي هو: SAR 6.50.السعر الحالي هو: SAR 5.90. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه نوفا 330 مل كرتون 40 عبوة

SAR 22.00 SAR 20.00 إضافة إلى السلة

مياه اكويا 330 مل 40 حبة

السعر الأصلي هو: SAR 19.00.السعر الحالي هو: SAR 17.00. شامل ضريبة القيمة المضافة

غير متوفر في المخزون

قراءة المزيد

مياه رست 330 مل كرتون 40 عبوة

السعر الأصلي هو: SAR 19.65.السعر الحالي هو: SAR 17.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

حجم 600 مل

مياه الحبيبة 600 مل 30 حبة

السعر الأصلي هو: SAR 13.00.السعر الحالي هو: SAR 12.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه ميراد 600 مل 30 حبة

SAR 16.00 SAR 14.00 إضافة إلى السلة

مياه وي 600 مل كرتون 30 عبوة

السعر الأصلي هو: SAR 15.50.السعر الحالي هو: SAR 14.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه تانيا 600 مل – كرتون 30 عبوة

السعر الأصلي هو: SAR 18.18.السعر الحالي هو: SAR 17.50. شامل ضريبة القيمة المضافة إضافة إلى السلة

الاحجام الكبيرة

مياه وطني 12 لتر 2 عبوة

SAR 16.50 SAR 15.00 إضافة إلى السلة

جالون مياه للبرادات 16 لتر

SAR 9.50 SAR 8.00 إضافة إلى السلة

مياه تانيا 1500 مل – شدة 6 عبوات

السعر الأصلي هو: SAR 10.15.السعر الحالي هو: SAR 9.34. شامل ضريبة القيمة المضافة إضافة إلى السلة

مياه وطني 5 لتر 4 عبوة

SAR 16.34 SAR 15.00 إضافة إلى السلة

جالون مياه البيداء 16 لتر

السعر الأصلي هو: SAR 8.00.السعر الحالي هو: SAR 7.00. شامل ضريبة القيمة المضافة إضافة إلى السلة

أراء العملاء

حسان عسيري عسيري تم التقييم بـ 5 نجوم.
[email protected] تم التقييم بـ 5 نجوم.
اسماء الحفظي الحفظي تم التقييم بـ 5 نجوم.
[email protected] ممتاز
[email protected] ممتاز
[email protected] ممتاز
				
					<script>
(function () {
  "use strict";

  if (window.__TR_FINAL_FOOTER_V7__) {
    return;
  }

  window.__TR_FINAL_FOOTER_V7__ = true;

  var TR = {
    googleMapsApiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    googleMapsLanguage: "ar",
    googleMapsRegion: "SA",
    locationTimeoutMs: 10000,
    locationMaximumAgeMs: 300000,
    locationEnableHighAccuracy: false,
    googleMapsPreloadDelayMs: 1000,

    autoGenerateEmail: true,
    generatedEmailDomain: "toprest.store",
    hideGeneratedEmailField: true,

    loginPath: "/my-account/",
    loginRedirectDelayMs: 300,
    loginReturnExpiryMs: 30 * 60 * 1000,
    accountWatchDurationMs: 25000,

    returnUrlKey: "tr_checkout_return_url",
    returnTimeKey: "tr_checkout_return_time",
    loginRequiredKey: "tr_checkout_login_required",
    savedPhoneKey: "tr_checkout_saved_phone",
    mapLinkKey: "tr_checkout_map_link",
    latitudeKey: "tr_checkout_lat",
    longitudeKey: "tr_checkout_lng"
  };

  var trGoogleMapsPromise = null;
  var trGooglePreloadScheduled = false;
  var trLocationBusy = false;
  var trAccountWatchUntil = 0;
  var trRedirectStarted = false;
  var trPageObserver = null;
  var trPeriodicTimer = null;

  function trGetParam(name) {
    return new URLSearchParams(window.location.search).get(name);
  }

  function trIsCheckoutPage() {
    return (
      document.body.classList.contains("woocommerce-checkout") ||
      document.body.classList.contains("page-checkout") ||
      !!document.querySelector(
        "form.checkout," +
        "form[name='checkout']," +
        "#place_order," +
        ".place-order," +
        ".wc-block-checkout"
      )
    );
  }

  function trIsOrderReceivedPage() {
    return (
      document.body.classList.contains("woocommerce-order-received") ||
      !!document.querySelector(".woocommerce-order-received")
    );
  }

  function trIsMyAccountPage() {
    var path = window.location.pathname
      .replace(/\/+$/, "")
      .toLowerCase();

    var accountPath = TR.loginPath
      .replace(/\/+$/, "")
      .toLowerCase();

    return (
      path === accountPath ||
      path.indexOf(accountPath + "/") === 0
    );
  }

  function trIsLoggedIn() {
    if (document.body.classList.contains("logged-in")) {
      return true;
    }

    var accountNavigation = document.querySelector(
      ".woocommerce-MyAccount-navigation"
    );

    var loginForm = document.querySelector(
      "form.woocommerce-form-login, form.login"
    );

    return !!accountNavigation && !loginForm;
  }

  function trStorageGet(key) {
    try {
      return sessionStorage.getItem(key) || "";
    } catch (error) {
      return "";
    }
  }

  function trStorageSet(key, value) {
    try {
      sessionStorage.setItem(key, String(value));
    } catch (error) {}
  }

  function trStorageRemove(key) {
    try {
      sessionStorage.removeItem(key);
    } catch (error) {}
  }

  function trSafeSetValue(element, value, triggerEvents) {
    if (
      !element ||
      value === undefined ||
      value === null ||
      element.value === value
    ) {
      return;
    }

    element.value = value;

    if (triggerEvents) {
      element.dispatchEvent(
        new Event("input", { bubbles: true })
      );

      element.dispatchEvent(
        new Event("change", { bubbles: true })
      );
    }
  }

  function trForceLTR(element) {
    if (!element) {
      return;
    }

    element.setAttribute("dir", "ltr");
    element.style.direction = "ltr";
    element.style.textAlign = "left";
    element.style.unicodeBidi = "plaintext";
  }

  function trNormalizeText(text) {
    return String(text || "")
      .toLowerCase()
      .replace(/[ً-ٰٟ]/g, "")
      .replace(/[إأآ]/g, "ا")
      .replace(/ة/g, "ه")
      .replace(/\s+/g, " ")
      .trim();
  }

  function trNormalizeSaudiPhone(phone) {
    var digits = String(phone || "").replace(/\D/g, "");

    if (digits.indexOf("00966") === 0) {
      digits = digits.substring(2);
    }

    if (
      digits.indexOf("05") === 0 &&
      digits.length === 10
    ) {
      return "966" + digits.substring(1);
    }

    if (
      digits.indexOf("5") === 0 &&
      digits.length === 9
    ) {
      return "966" + digits;
    }

    return digits;
  }

  function trGetValidSaudiMobile(phone) {
    var normalized =
      trNormalizeSaudiPhone(phone);

    return /^9665\d{8}$/.test(normalized)
      ? normalized
      : "";
  }

  function trIsGeneratedEmail(email) {
    var value =
      String(email || "")
        .trim()
        .toLowerCase();

    var domain =
      String(
        TR.generatedEmailDomain ||
        "toprest.store"
      )
        .trim()
        .toLowerCase();

    if (!domain) {
      return false;
    }

    return value.slice(
      -(domain.length + 1)
    ) === "@" + domain;
  }

  function trGetEmailField() {
    return document.querySelector(
      "#billing_email," +
      "input[name='billing_email']," +
      "input[type='email'][name*='billing']"
    );
  }

  function trHideGeneratedEmailField() {
    if (!TR.hideGeneratedEmailField) {
      return;
    }

    var field = trGetEmailField();

    if (!field) {
      return;
    }

    var wrapper =
      field.closest(
        "#billing_email_field," +
        ".form-row," +
        "p," +
        ".woocommerce-form-row," +
        ".thwcfd-field-wrapper," +
        ".field-wrapper," +
        ".wc-block-components-text-input"
      );

    if (wrapper) {
      wrapper.style.setProperty(
        "display",
        "none",
        "important"
      );
    } else {
      field.style.setProperty(
        "display",
        "none",
        "important"
      );
    }
  }

  function trAutoGenerateEmail(triggerEvents) {
    if (
      !TR.autoGenerateEmail ||
      !trIsCheckoutPage() ||
      trIsOrderReceivedPage()
    ) {
      return false;
    }

    var phoneInput =
      document.querySelector(
        "#billing_phone," +
        "input[name='billing_phone']"
      );

    var emailInput =
      trGetEmailField();

    if (!phoneInput || !emailInput) {
      return false;
    }

    trForceLTR(phoneInput);
    trForceLTR(emailInput);
    trHideGeneratedEmailField();

    var phone966 =
      trGetValidSaudiMobile(
        phoneInput.value
      );

    if (!phone966) {
      return false;
    }

    var domain =
      String(
        TR.generatedEmailDomain ||
        "toprest.store"
      )
        .trim()
        .toLowerCase();

    var generatedEmail =
      phone966 + "@" + domain;

    var currentEmail =
      String(
        emailInput.value || ""
      ).trim();

    /*
     * لا نكتب فوق بريد حقيقي.
     * نعبئ فقط إذا كان الحقل فارغًا أو كان يحتوي بريدًا
     * مولدًا سابقًا من نفس نطاق topRest.store.
     */
    if (
      currentEmail &&
      !trIsGeneratedEmail(currentEmail)
    ) {
      return false;
    }

    if (
      currentEmail !== generatedEmail
    ) {
      trSafeSetValue(
        emailInput,
        generatedEmail,
        !!triggerEvents
      );

      try {
        localStorage.setItem(
          "tr_last_checkout_email",
          generatedEmail
        );
      } catch (error) {}
    }

    return true;
  }

  function trInitStoreUI() {
    var branchId = trGetParam("branch_id");

    if (branchId) {
      if (branchId === "1318") {
        trStorageSet("trIsRiyadhBranch", "true");
      } else {
        trStorageRemove("trIsRiyadhBranch");
      }
    }

    if (
      trStorageGet("trIsRiyadhBranch") === "true" &&
      !document.getElementById("trRiyadhFreeShippingBar")
    ) {
      var bar = document.createElement("div");

      bar.id = "trRiyadhFreeShippingBar";
      bar.className = "tr-riyadh-shipping-bar";
      bar.dir = "rtl";
      bar.textContent =
        "📢 أضف مشتريات بقيمة 200 ريال للحصول على الشحن المجاني لمدينة الرياض";

      document.body.insertBefore(bar, document.body.firstChild);
      bar.style.display = "block";
    }

    var salesElement = document.querySelector(
      "[lang^='en'] .sales-booster-total-sales"
    );

    if (salesElement && !salesElement.dataset.trFixed) {
      var salesMatch = salesElement.innerText.match(/\d+/);

      if (salesMatch) {
        salesElement.innerHTML =
          salesMatch[0] +
          " products sold in the last few hours 🔥";

        salesElement.dataset.trFixed = "1";
      }
    }

    var visitorsBox = document.querySelector(
      "[lang^='en'] .live-visitors-box"
    );

    if (visitorsBox && !visitorsBox.dataset.trFixed) {
      var strongTag = visitorsBox.querySelector("strong");

      if (strongTag) {
        visitorsBox.innerHTML =
          "👀 <strong>" +
          strongTag.innerText +
          "</strong> people are watching this product right now";

        visitorsBox.dataset.trFixed = "1";
      }
    }
  }

  function trGetNationalAddressField() {
    return document.querySelector(
      "#billing_national_address," +
      "#billing_address_short_code," +
      "input[name='billing_national_address']," +
      "input[name='billing_address_short_code']," +
      "input[name*='national_address']," +
      "input[name*='short_code']"
    );
  }

  function trNormalizeShortAddress(value) {
    var match = String(value || "")
      .toUpperCase()
      .match(/([A-Z]{4})[\s-]?(\d{4})/);

    return match ? match[1] + match[2] : "";
  }

  function trGetCurrentShortAddress() {
    var field = trGetNationalAddressField();

    if (!field) {
      return "";
    }

    return trNormalizeShortAddress(field.value);
  }

  function trSetNationalAddress(value) {
    var field = trGetNationalAddressField();
    var normalized = trNormalizeShortAddress(value);

    if (!field || !normalized) {
      return false;
    }

    trForceLTR(field);
    trSafeSetValue(field, normalized, true);

    return true;
  }

  function trNormalizeNationalField() {
    var field = trGetNationalAddressField();

    if (!field) {
      return;
    }

    trForceLTR(field);

    var normalized = trNormalizeShortAddress(field.value);

    if (normalized && field.value !== normalized) {
      trSafeSetValue(field, normalized, false);
    }
  }

  function trNormalizeCheckoutDirections() {
    var fields = document.querySelectorAll(
      "#billing_email," +
      "input[name='billing_email']," +
      "input[type='email']," +
      "#billing_phone," +
      "input[name='billing_phone']," +
      "#billing_national_address," +
      "#billing_address_short_code," +
      "input[name*='national']," +
      "input[name*='short_code']," +
      "#billing_map_link," +
      "input[name='billing_map_link']," +
      "textarea[name='billing_map_link']"
    );

    Array.prototype.forEach.call(fields, trForceLTR);
  }

  function trGetMapLinkField() {
    return document.querySelector(
      "#billing_map_link," +
      "input[name='billing_map_link']," +
      "textarea[name='billing_map_link']"
    );
  }

  function trHideMapLinkField() {
    var field = trGetMapLinkField();

    if (!field) {
      return;
    }

    trForceLTR(field);

    var wrapper = field.closest(
      "#billing_map_link_field," +
      ".form-row," +
      ".woocommerce-form-row," +
      ".thwcfd-field-wrapper," +
      ".field-wrapper," +
      "p"
    );

    if (wrapper) {
      wrapper.style.setProperty(
        "display",
        "none",
        "important"
      );
    }
  }

  function trCoordinatesAreValid(latitude, longitude) {
    var lat = Number(latitude);
    var lng = Number(longitude);

    return (
      Number.isFinite(lat) &&
      Number.isFinite(lng) &&
      lat >= -90 &&
      lat <= 90 &&
      lng >= -180 &&
      lng <= 180
    );
  }

  function trBuildGoogleMapLink(latitude, longitude) {
    if (!trCoordinatesAreValid(latitude, longitude)) {
      return "";
    }

    return (
      "https://www.google.com/maps/search/?api=1&query=" +
      Number(latitude) + "," + Number(longitude)
    );
  }

  function trBuildShortAddressMapLink(shortAddress) {
    var normalized = trNormalizeShortAddress(shortAddress);

    if (!normalized) {
      return "";
    }

    return (
      "https://www.google.com/maps/search/?api=1&query=" +
      encodeURIComponent(
        normalized + " Saudi Arabia"
      )
    );
  }

  function trBuildBestMapLink() {
    var latitude = trStorageGet(TR.latitudeKey);
    var longitude = trStorageGet(TR.longitudeKey);

    if (trCoordinatesAreValid(latitude, longitude)) {
      return trBuildGoogleMapLink(
        latitude,
        longitude
      );
    }

    var shortAddress = trGetCurrentShortAddress();

    if (shortAddress) {
      return trBuildShortAddressMapLink(
        shortAddress
      );
    }

    return "";
  }

  function trWriteMapLink(latitude, longitude) {
    var mapLink = "";

    if (trCoordinatesAreValid(latitude, longitude)) {
      mapLink = trBuildGoogleMapLink(
        latitude,
        longitude
      );
    }

    if (!mapLink) {
      mapLink = trBuildBestMapLink();
    }

    if (!mapLink) {
      return false;
    }

    trStorageSet(TR.mapLinkKey, mapLink);

    var field = trGetMapLinkField();

    if (!field) {
      return false;
    }

    trHideMapLinkField();

    if (field.value !== mapLink) {
      trSafeSetValue(
        field,
        mapLink,
        true
      );
    }

    return true;
  }

  function trRestoreMapLink() {
    var field = trGetMapLinkField();

    if (!field) {
      return false;
    }

    trHideMapLinkField();

    var mapLink = trStorageGet(TR.mapLinkKey);

    if (!mapLink) {
      mapLink = trBuildBestMapLink();
    }

    if (!mapLink) {
      return false;
    }

    trStorageSet(TR.mapLinkKey, mapLink);

    if (field.value !== mapLink) {
      trSafeSetValue(
        field,
        mapLink,
        true
      );
    }

    return true;
  }

  function trSetLocationStatus(type, message) {
    var status = document.getElementById("trLocationStatus");

    if (!status) {
      return;
    }

    status.className = "is-" + type;
    status.textContent = message;
  }

  function trSetSelectByText(select, values) {
    if (!select || !select.options || !values || !values.length) {
      return false;
    }

    var normalizedValues = values
      .map(function (value) {
        return String(value || "").trim().toLowerCase();
      })
      .filter(Boolean);

    var matched = false;

    Array.prototype.some.call(select.options, function (option) {
      var text = String(option.text || "").trim().toLowerCase();
      var value = String(option.value || "").trim().toLowerCase();

      matched = normalizedValues.some(function (candidate) {
        return (
          candidate &&
          (
            text.indexOf(candidate) !== -1 ||
            value === candidate
          )
        );
      });

      if (matched) {
        select.value = option.value;

        select.dispatchEvent(
          new Event("change", { bubbles: true })
        );
      }

      return matched;
    });

    return matched;
  }

  function trWriteCoordinates(latitude, longitude) {
    trStorageSet(TR.latitudeKey, latitude);
    trStorageSet(TR.longitudeKey, longitude);

    var latitudeFields = document.querySelectorAll(
      "#billing_latitude," +
      "input[name='billing_latitude']," +
      "#billing_lat," +
      "input[name='billing_lat']," +
      "input[name*='latitude']"
    );

    var longitudeFields = document.querySelectorAll(
      "#billing_longitude," +
      "input[name='billing_longitude']," +
      "#billing_lng," +
      "input[name='billing_lng']," +
      "input[name*='longitude']"
    );

    Array.prototype.forEach.call(latitudeFields, function (field) {
      trSafeSetValue(
        field,
        String(latitude),
        false
      );
    });

    Array.prototype.forEach.call(longitudeFields, function (field) {
      trSafeSetValue(
        field,
        String(longitude),
        false
      );
    });

    trWriteMapLink(
      latitude,
      longitude
    );

    trShowMapPreview(
      latitude,
      longitude
    );
  }

  function trShowMapPreview(latitude, longitude) {
    if (!trCoordinatesAreValid(latitude, longitude)) {
      return false;
    }

    var preview =
      document.getElementById("trMapPreview");

    if (!preview) {
      return false;
    }

    var iframe =
      preview.querySelector("iframe");

    if (!iframe) {
      iframe =
        document.createElement("iframe");

      iframe.setAttribute(
        "title",
        "معاينة موقع التوصيل"
      );

      iframe.setAttribute(
        "loading",
        "lazy"
      );

      iframe.setAttribute(
        "referrerpolicy",
        "no-referrer-when-downgrade"
      );

      iframe.setAttribute(
        "allowfullscreen",
        ""
      );

      preview.appendChild(iframe);
    }

    var src =
      "https://www.google.com/maps?q=" +
      encodeURIComponent(
        Number(latitude) + "," + Number(longitude)
      ) +
      "&z=16&output=embed";

    if (iframe.src !== src) {
      iframe.src = src;
    }

    preview.classList.add(
      "is-visible"
    );

    return true;
  }

  function trHasUsableGoogleMapsKey() {
    var key = String(TR.googleMapsApiKey || "").trim();

    if (!key) {
      return false;
    }

    return !/(ضع_|YOUR_|API_KEY|مفتاح)/i.test(key);
  }

  function trWaitForGoogleMaps(timeoutMs) {
    return new Promise(function (resolve) {
      var started = Date.now();

      var timer = setInterval(function () {
        if (
          window.google &&
          window.google.maps &&
          window.google.maps.Geocoder
        ) {
          clearInterval(timer);
          resolve(window.google);
        } else if (Date.now() - started >= timeoutMs) {
          clearInterval(timer);
          resolve(null);
        }
      }, 120);
    });
  }

  function trLoadGoogleMaps() {
    if (
      window.google &&
      window.google.maps &&
      window.google.maps.Geocoder
    ) {
      return Promise.resolve(window.google);
    }

    if (trGoogleMapsPromise) {
      return trGoogleMapsPromise;
    }

    trGoogleMapsPromise = new Promise(function (resolve) {
      var existingScript = document.querySelector(
        'script[src*="maps.googleapis.com/maps/api/js"],' +
        'script[src*="maps.google.com/maps/api/js"]'
      );

      if (existingScript) {
        trWaitForGoogleMaps(8000).then(resolve);
        return;
      }

      if (!trHasUsableGoogleMapsKey()) {
        resolve(null);
        return;
      }

      var callbackName =
        "__trGoogleMapsReady" + Date.now();

      var script = document.createElement("script");

      var params = [
        "key=" + encodeURIComponent(TR.googleMapsApiKey),
        "language=" + encodeURIComponent(TR.googleMapsLanguage),
        "region=" + encodeURIComponent(TR.googleMapsRegion),
        "loading=async",
        "callback=" + encodeURIComponent(callbackName)
      ];

      window[callbackName] = function () {
        try {
          delete window[callbackName];
        } catch (error) {
          window[callbackName] = undefined;
        }

        resolve(window.google || null);
      };

      script.src =
        "https://maps.googleapis.com/maps/api/js?" +
        params.join("&");

      script.async = true;
      script.defer = true;

      try {
        script.fetchPriority = "low";
      } catch (error) {}

      script.onerror = function () {
        try {
          delete window[callbackName];
        } catch (error) {
          window[callbackName] = undefined;
        }

        resolve(null);
      };

      document.head.appendChild(script);
    });

    return trGoogleMapsPromise;
  }

  function trScheduleGoogleMapsPreload() {
    if (
      !trIsCheckoutPage() ||
      trIsOrderReceivedPage() ||
      trGoogleMapsPromise ||
      trGooglePreloadScheduled
    ) {
      return;
    }

    trGooglePreloadScheduled = true;

    setTimeout(function () {
      var startPreload = function () {
        if (trIsCheckoutPage() && !trIsOrderReceivedPage()) {
          trLoadGoogleMaps();
        }
      };

      if ("requestIdleCallback" in window) {
        window.requestIdleCallback(
          startPreload,
          { timeout: 1800 }
        );
      } else {
        setTimeout(startPreload, 0);
      }
    }, TR.googleMapsPreloadDelayMs);
  }

  function trFindAddressComponent(
    components,
    types,
    preferShortName
  ) {
    var result = "";

    Array.prototype.some.call(
      components || [],
      function (component) {
        var found = (component.types || []).some(
          function (type) {
            return types.indexOf(type) !== -1;
          }
        );

        if (found) {
          result = preferShortName
            ? component.short_name ||
              component.long_name ||
              ""
            : component.long_name ||
              component.short_name ||
              "";
        }

        return found;
      }
    );

    return result;
  }

  function trSetTextFieldIfEmpty(
    selectors,
    value,
    triggerEvents
  ) {
    if (!value) {
      return false;
    }

    var field = document.querySelector(selectors);

    if (!field || String(field.value || "").trim()) {
      return false;
    }

    trSafeSetValue(
      field,
      value,
      triggerEvents
    );

    return true;
  }

  function trApplyGoogleAddress(result) {
    if (!result) {
      return false;
    }

    var components =
      result.address_components || [];

    var building = trFindAddressComponent(
      components,
      ["street_number"]
    );

    var route = trFindAddressComponent(
      components,
      ["route"]
    );

    var district = trFindAddressComponent(
      components,
      [
        "neighborhood",
        "sublocality_level_1",
        "sublocality_level_2",
        "sublocality"
      ]
    );

    var city = trFindAddressComponent(
      components,
      [
        "locality",
        "administrative_area_level_2"
      ]
    );

    var region = trFindAddressComponent(
      components,
      ["administrative_area_level_1"]
    );

    var postcode = trFindAddressComponent(
      components,
      ["postal_code"]
    );

    var countryCode = trFindAddressComponent(
      components,
      ["country"],
      true
    );

    var addressParts = [
      building,
      route,
      district
    ].filter(Boolean);

    var addressText =
      addressParts.join("، ");

    if (!addressText && result.formatted_address) {
      addressText = String(result.formatted_address)
        .split(",")
        .slice(0, 3)
        .join("، ")
        .trim();
    }

    trSetTextFieldIfEmpty(
      "#billing_address_1, input[name='billing_address_1']",
      addressText,
      true
    );

    trSetTextFieldIfEmpty(
      "#billing_postcode, input[name='billing_postcode']",
      postcode,
      false
    );

    var cityField = document.querySelector(
      "#billing_city," +
      "select[name='billing_city']," +
      "input[name='billing_city']"
    );

    if (cityField) {
      if (cityField.tagName === "SELECT") {
        trSetSelectByText(
          cityField,
          [city, region]
        );
      } else if (!String(cityField.value || "").trim()) {
        trSafeSetValue(
          cityField,
          city || region,
          true
        );
      }
    }

    var stateField = document.querySelector(
      "#billing_state," +
      "select[name='billing_state']," +
      "input[name='billing_state']"
    );

    if (stateField) {
      if (stateField.tagName === "SELECT") {
        trSetSelectByText(
          stateField,
          [region, city]
        );
      } else if (!String(stateField.value || "").trim()) {
        trSafeSetValue(
          stateField,
          region || city,
          true
        );
      }
    }

    var countryField = document.querySelector(
      "#billing_country," +
      "select[name='billing_country']"
    );

    if (
      countryField &&
      countryField.tagName === "SELECT" &&
      countryCode &&
      !countryField.value
    ) {
      countryField.value =
        String(countryCode).toUpperCase() === "SA"
          ? "SA"
          : countryCode;

      countryField.dispatchEvent(
        new Event("change", {
          bubbles: true
        })
      );
    }

    trSetNationalAddress(
      result.formatted_address || ""
    );

    trStorageSet(
      "tr_google_formatted_address",
      result.formatted_address || ""
    );

    trRestoreMapLink();

    return !!(
      addressText ||
      city ||
      region ||
      postcode
    );
  }

  function trResetLocationButton() {
    var button = document.getElementById(
      "trUseLocationBtn"
    );

    if (!button) {
      return;
    }

    button.disabled = false;

    button.textContent =
      trStorageGet("tr_location_completed") === "1"
        ? "📍 تحديث موقعي"
        : "📍 إعادة تحديد موقعي";
  }

  function trRequestLocation() {
    var button = document.getElementById(
      "trUseLocationBtn"
    );

    if (trLocationBusy) {
      return;
    }

    if (!navigator.geolocation) {
      trSetLocationStatus(
        "error",
        "المتصفح لا يدعم تحديد الموقع. أكمل العنوان يدويًا."
      );

      return;
    }

    trLocationBusy = true;

    if (button) {
      button.disabled = true;
      button.textContent =
        "جارٍ تحديد موقعك…";
    }

    trSetLocationStatus(
      "info",
      "اختر «سماح» من رسالة المتصفح. سنستخدم الموقع لتعبئة العنوان فقط."
    );

    var mapsReadyPromise =
      trLoadGoogleMaps();

    navigator.geolocation.getCurrentPosition(
      function (position) {
        var latitude = Number(
          position.coords.latitude
        );

        var longitude = Number(
          position.coords.longitude
        );

        trWriteCoordinates(
          latitude,
          longitude
        );

        trStorageSet(
          "tr_location_completed",
          "1"
        );

        mapsReadyPromise
          .then(function (googleObject) {
            if (
              !googleObject ||
              !googleObject.maps ||
              !googleObject.maps.Geocoder
            ) {
              return null;
            }

            return new Promise(
              function (resolve) {
                try {
                  var geocoder =
                    new googleObject.maps.Geocoder();

                  geocoder.geocode(
                    {
                      location: {
                        lat: latitude,
                        lng: longitude
                      },
                      region: TR.googleMapsRegion
                    },
                    function (results, status) {
                      if (
                        status === "OK" &&
                        results &&
                        results[0]
                      ) {
                        trApplyGoogleAddress(
                          results[0]
                        );

                        resolve(results[0]);
                      } else {
                        resolve(null);
                      }
                    }
                  );
                } catch (error) {
                  resolve(null);
                }
              }
            );
          })
          .then(function (result) {
            if (result) {
              trSetLocationStatus(
                "success",
                "تم تحديد موقعك وتعبئة بيانات العنوان المتاحة. راجع العنوان قبل إكمال الطلب."
              );

              trNormalizeNationalField();
              trWriteMapLink(
                latitude,
                longitude
              );

              if (window.jQuery) {
                window
                  .jQuery(document.body)
                  .trigger("update_checkout");
              }
            } else {
              trSetLocationStatus(
                "warning",
                "تم تحديد موقعك، لكن تعذر تحويله إلى عنوان. أكمل العنوان يدويًا."
              );
            }
          })
          .catch(function () {
            trSetLocationStatus(
              "warning",
              "تم تحديد موقعك، لكن تعذر تعبئة العنوان تلقائيًا. أكمله يدويًا."
            );
          })
          .then(function () {
            trLocationBusy = false;
            trResetLocationButton();
          });
      },

      function (error) {
        var message =
          "تعذر تحديد الموقع. يمكنك إكمال العنوان يدويًا أو إعادة المحاولة.";

        if (error && error.code === 1) {
          message =
            "لم يتم السماح بالموقع. اسمح به من إعدادات المتصفح ثم أعد المحاولة.";
        } else if (error && error.code === 2) {
          message =
            "تعذر العثور على موقعك. فعّل خدمة الموقع ثم أعد المحاولة.";
        } else if (error && error.code === 3) {
          message =
            "استغرق تحديد الموقع وقتًا طويلًا. أعد المحاولة أو أكمل العنوان يدويًا.";
        }

        trSetLocationStatus(
          "error",
          message
        );

        trLocationBusy = false;
        trResetLocationButton();
      },

      {
        enableHighAccuracy:
          TR.locationEnableHighAccuracy,

        timeout:
          TR.locationTimeoutMs,

        maximumAge:
          TR.locationMaximumAgeMs
      }
    );
  }

  function trEnsureLocationAssist() {
    if (
      !trIsCheckoutPage() ||
      trIsOrderReceivedPage() ||
      document.getElementById(
        "trLocationAssist"
      )
    ) {
      return;
    }

    /*
     * في النسخة السابقة كان ظهور الزر يعتمد على وجود
     * billing_national_address تحديدًا. بعض قوالب/إعدادات
     * Checkout لا تحتوي هذا الحقل، لذلك نستخدم أكثر من
     * نقطة ارتكاز ونستمر حتى لو لم يوجد العنوان الوطني.
     */
    var anchorField =
      trGetNationalAddressField() ||
      document.querySelector(
        "#billing_address_1," +
        "input[name='billing_address_1']," +
        "#billing_phone," +
        "input[name='billing_phone']," +
        "#billing_email," +
        "input[name='billing_email']," +
        "#billing_first_name," +
        "input[name='billing_first_name']"
      );

    var wrapper = null;

    if (anchorField) {
      wrapper =
        anchorField.closest(
          ".form-row," +
          "p," +
          ".woocommerce-form-row," +
          ".field-wrapper," +
          ".thwcfd-field-wrapper," +
          ".wc-block-components-text-input"
        ) ||
        anchorField.parentNode;
    }

    var fallbackContainer =
      document.querySelector(
        ".woocommerce-billing-fields__field-wrapper," +
        ".woocommerce-billing-fields," +
        "form.checkout .woocommerce-billing-fields__field-wrapper," +
        "form.checkout," +
        ".wc-block-checkout__form," +
        ".wc-block-checkout"
      );

    if (
      (!wrapper || !wrapper.parentNode) &&
      !fallbackContainer
    ) {
      return;
    }

    var box =
      document.createElement("div");

    box.id = "trLocationAssist";
    box.dir = "rtl";

    box.innerHTML =
      '<p class="tr-location-title">تحديد الموقع وتعبئة العنوان</p>' +
      '<p class="tr-location-help">اضغط الزر فقط عندما تريد تحديد موقعك. لن نطلب صلاحية الموقع عند فتح الصفحة.</p>' +
      '<button type="button" id="trUseLocationBtn">📍 تحديد موقعي وتعبئة العنوان</button>' +
      '<div id="trLocationStatus" role="status" aria-live="polite"></div>' +
      '<div id="trMapPreview" aria-label="معاينة موقع التوصيل"></div>';

    if (wrapper && wrapper.parentNode) {
      wrapper.parentNode.insertBefore(
        box,
        wrapper.nextSibling
      );
    } else {
      fallbackContainer.insertBefore(
        box,
        fallbackContainer.firstChild
      );
    }

    var button =
      document.getElementById(
        "trUseLocationBtn"
      );

    if (button) {
      button.addEventListener(
        "click",
        trRequestLocation
      );
    }

    var savedLatitude =
      trStorageGet(TR.latitudeKey);

    var savedLongitude =
      trStorageGet(TR.longitudeKey);

    if (
      trCoordinatesAreValid(
        savedLatitude,
        savedLongitude
      )
    ) {
      trShowMapPreview(
        savedLatitude,
        savedLongitude
      );
    }
  }

  function trSaveCheckoutPhone() {
    var phoneInput = document.querySelector(
      "#billing_phone," +
      "input[name='billing_phone']"
    );

    if (!phoneInput || !phoneInput.value) {
      return;
    }

    trStorageSet(
      TR.savedPhoneKey,
      trNormalizeSaudiPhone(
        phoneInput.value
      )
    );
  }

  function trSaveCheckoutContext() {
    if (
      !trIsCheckoutPage() ||
      trIsOrderReceivedPage()
    ) {
      return;
    }

    var checkoutUrl =
      window.location.origin +
      window.location.pathname +
      window.location.search;

    trStorageSet(
      TR.returnUrlKey,
      checkoutUrl
    );

    trStorageSet(
      TR.returnTimeKey,
      Date.now()
    );

    trSaveCheckoutPhone();
  }

  function trGetSavedCheckoutUrl() {
    var savedUrl = trStorageGet(
      TR.returnUrlKey
    );

    var savedTime = parseInt(
      trStorageGet(TR.returnTimeKey) || "0",
      10
    );

    if (!savedUrl || !savedTime) {
      return "";
    }

    if (
      Date.now() - savedTime >
      TR.loginReturnExpiryMs
    ) {
      trClearLoginFlow();
      return "";
    }

    try {
      var parsedUrl = new URL(
        savedUrl,
        window.location.origin
      );

      if (
        parsedUrl.origin !==
        window.location.origin
      ) {
        trClearLoginFlow();
        return "";
      }

      return parsedUrl.href;
    } catch (error) {
      return "";
    }
  }

  function trClearLoginFlow() {
    trStorageRemove(TR.returnUrlKey);
    trStorageRemove(TR.returnTimeKey);
    trStorageRemove(TR.loginRequiredKey);
    trStorageRemove(TR.savedPhoneKey);
  }

  function trIsExistingAccountText(text) {
    var normalized =
      trNormalizeText(text);

    if (!normalized) {
      return false;
    }

    var existingPhrase =
      normalized.indexOf("already in use") !== -1 ||
      normalized.indexOf("already used") !== -1 ||
      normalized.indexOf("already registered") !== -1 ||
      normalized.indexOf("already exists") !== -1 ||
      normalized.indexOf("مستخدم بالفعل") !== -1 ||
      normalized.indexOf("مسجل بالفعل") !== -1 ||
      normalized.indexOf("موجود بالفعل") !== -1;

    if (!existingPhrase) {
      return false;
    }

    var accountField =
      normalized.indexOf("رقم الهاتف") !== -1 ||
      normalized.indexOf("رقم الجوال") !== -1 ||
      normalized.indexOf("الهاتف") !== -1 ||
      normalized.indexOf("الجوال") !== -1 ||
      normalized.indexOf("البريد") !== -1 ||
      normalized.indexOf("الحساب") !== -1 ||
      normalized.indexOf("المستخدم") !== -1 ||
      normalized.indexOf("phone") !== -1 ||
      normalized.indexOf("mobile") !== -1 ||
      normalized.indexOf("email") !== -1 ||
      normalized.indexOf("account") !== -1 ||
      normalized.indexOf("user") !== -1;

    return (
      accountField ||
      Date.now() <= trAccountWatchUntil
    );
  }

  function trArmAccountCheck() {
    trAccountWatchUntil =
      Date.now() +
      TR.accountWatchDurationMs;

    trSaveCheckoutContext();
  }

  function trShowArabicAccountNotice() {
    if (
      document.getElementById(
        "trExistingAccountArabicNotice"
      )
    ) {
      return;
    }

    var notice =
      document.createElement("div");

    notice.id =
      "trExistingAccountArabicNotice";

    notice.setAttribute(
      "role",
      "alert"
    );

    notice.innerHTML =
      "رقم الهاتف مرتبط بحساب مسجل" +
      "<small>جارٍ تحويلك إلى تسجيل الدخول لإكمال الطلب…</small>";

    document.body.appendChild(notice);
  }

  function trHideAlertNode(node) {
    var element =
      node && node.nodeType === 1
        ? node
        : node && node.parentElement
          ? node.parentElement
          : null;

    var steps = 0;

    while (
      element &&
      element !== document.body &&
      steps < 10
    ) {
      var role = String(
        element.getAttribute("role") || ""
      ).toLowerCase();

      var classes = String(
        element.className || ""
      );

      var looksLikeAlert =
        role === "alert" ||
        role === "status" ||
        /(toast|alert|snack|notif|izi|swal|error|message)/i.test(
          classes
        );

      if (looksLikeAlert) {
        element.style.setProperty(
          "display",
          "none",
          "important"
        );

        element.setAttribute(
          "aria-hidden",
          "true"
        );

        return;
      }

      element = element.parentElement;
      steps++;
    }
  }

  function trHideKnownEnglishAlerts() {
    var selectors = [
      "[role='alert']",
      "[role='status']",
      ".toast",
      ".toast-message",
      ".toastify",
      ".iziToast",
      ".iziToast-wrapper",
      ".swal2-container",
      ".swal2-popup",
      ".snackbar",
      ".notification",
      ".alert",
      ".error-message",
      "[class*='toast']",
      "[class*='Toast']",
      "[class*='alert']",
      "[class*='Alert']",
      "[class*='snack']",
      "[class*='notif']",
      "[class*='swal']"
    ];

    var elements =
      document.querySelectorAll(
        selectors.join(",")
      );

    for (
      var index = 0;
      index < elements.length;
      index++
    ) {
      if (
        trIsExistingAccountText(
          elements[index].textContent || ""
        )
      ) {
        elements[index].style.setProperty(
          "display",
          "none",
          "important"
        );

        elements[index].setAttribute(
          "aria-hidden",
          "true"
        );
      }
    }
  }

  function trRedirectToLogin(sourceNode) {
    if (
      trRedirectStarted ||
      !trIsCheckoutPage() ||
      trIsOrderReceivedPage()
    ) {
      return;
    }

    trRedirectStarted = true;
    trSaveCheckoutContext();

    trStorageSet(
      TR.loginRequiredKey,
      "1"
    );

    if (sourceNode) {
      trHideAlertNode(sourceNode);
    }

    trHideKnownEnglishAlerts();
    trShowArabicAccountNotice();

    var loginUrl = new URL(
      TR.loginPath,
      window.location.origin
    );

    loginUrl.searchParams.set(
      "tr_from_checkout",
      "1"
    );

    window.setTimeout(function () {
      window.location.replace(
        loginUrl.href
      );
    }, TR.loginRedirectDelayMs);
  }

  function trInspectAccountText(
    text,
    sourceNode
  ) {
    if (
      trRedirectStarted ||
      Date.now() > trAccountWatchUntil
    ) {
      return false;
    }

    if (trIsExistingAccountText(text)) {
      trRedirectToLogin(sourceNode);
      return true;
    }

    return false;
  }

  function trInspectNode(node) {
    if (
      !node ||
      Date.now() > trAccountWatchUntil
    ) {
      return false;
    }

    var text = "";

    if (node.nodeType === 3) {
      text = node.nodeValue || "";
    } else if (node.nodeType === 1) {
      text = node.textContent || "";
    }

    return trInspectAccountText(
      text,
      node
    );
  }

  function trCheckWholeCheckoutPage() {
    if (
      !trIsCheckoutPage() ||
      trIsOrderReceivedPage() ||
      trRedirectStarted ||
      Date.now() > trAccountWatchUntil ||
      !document.body
    ) {
      return;
    }

    trInspectAccountText(
      document.body.innerText ||
      document.body.textContent ||
      "",
      null
    );
  }

  function trWrapFetch() {
    if (
      !window.fetch ||
      window.fetch.__trFinalWrapped
    ) {
      return;
    }

    var originalFetch =
      window.fetch;

    var wrappedFetch = function () {
      return originalFetch
        .apply(this, arguments)
        .then(function (response) {
          if (
            Date.now() <= trAccountWatchUntil
          ) {
            try {
              response
                .clone()
                .text()
                .then(function (text) {
                  trInspectAccountText(
                    text,
                    null
                  );
                });
            } catch (error) {}
          }

          return response;
        });
    };

    wrappedFetch.__trFinalWrapped = true;
    window.fetch = wrappedFetch;
  }

  function trWrapXHR() {
    if (
      !window.XMLHttpRequest ||
      window.XMLHttpRequest
        .prototype
        .__trFinalWrapped
    ) {
      return;
    }

    var originalOpen =
      window.XMLHttpRequest
        .prototype
        .open;

    window.XMLHttpRequest
      .prototype
      .open = function () {
        this.addEventListener(
          "load",
          function () {
            if (
              Date.now() >
              trAccountWatchUntil
            ) {
              return;
            }

            try {
              trInspectAccountText(
                this.responseText,
                null
              );
            } catch (error) {}
          }
        );

        return originalOpen.apply(
          this,
          arguments
        );
      };

    window.XMLHttpRequest
      .prototype
      .__trFinalWrapped = true;
  }

  function trBindWindowMessages() {
    window.addEventListener(
      "message",
      function (event) {
        if (
          Date.now() >
          trAccountWatchUntil
        ) {
          return;
        }

        var text = "";

        if (
          typeof event.data === "string"
        ) {
          text = event.data;
        } else {
          try {
            text = JSON.stringify(
              event.data
            );
          } catch (error) {
            text = String(
              event.data || ""
            );
          }
        }

        trInspectAccountText(
          text,
          null
        );
      }
    );
  }

  function trIsCheckoutLoginFlow() {
    return (
      trGetParam(
        "tr_from_checkout"
      ) === "1" ||
      trStorageGet(
        TR.loginRequiredKey
      ) === "1"
    );
  }

  function trFindOtpCard(phoneInput) {
    if (!phoneInput) {
      return null;
    }

    var current = phoneInput;
    var candidate = null;
    var steps = 0;

    while (
      current &&
      current !== document.body &&
      steps < 9
    ) {
      var hasButton =
        current.querySelector &&
        current.querySelector(
          "button, input[type='submit']"
        );

      var text = trNormalizeText(
        current.textContent || ""
      );

      var looksLikeOtp =
        text.indexOf("واتساب") !== -1 ||
        text.indexOf("كود التحقق") !== -1 ||
        text.indexOf("ارسال كود") !== -1 ||
        text.indexOf("إرسال كود") !== -1 ||
        text.indexOf("otp") !== -1;

      if (
        hasButton &&
        looksLikeOtp
      ) {
        candidate = current;
        break;
      }

      if (
        current.classList &&
        (
          current.classList.contains(
            "woocommerce"
          ) ||
          current.id ===
          "customer_login"
        )
      ) {
        break;
      }

      current =
        current.parentElement;

      steps++;
    }

    return (
      candidate ||
      phoneInput.closest("form") ||
      phoneInput.closest(
        "[class*='wln-otp-form']"
      ) ||
      phoneInput.parentElement
    );
  }

  function trGetLoginColumn(element) {
    if (
      !element ||
      !element.closest
    ) {
      return null;
    }

    return element.closest(
      ".u-column1, .u-column2, .col-1, .col-2"
    );
  }

  function trHideOldLoginHeadings(root) {
    if (!root) {
      return;
    }

    var headings =
      root.querySelectorAll(
        "h1, h2, h3"
      );

    Array.prototype.forEach.call(
      headings,
      function (heading) {
        if (
          heading.id ===
          "trCheckoutLoginIntro"
        ) {
          return;
        }

        var text = trNormalizeText(
          heading.textContent || ""
        );

        if (
          text === "تسجيل الدخول" ||
          text === "دخول" ||
          text === "login"
        ) {
          heading.classList.add(
            "tr-login-old-heading"
          );
        }
      }
    );
  }

  function trHideLoginSeparators(root) {
    if (!root) {
      return;
    }

    var elements =
      root.querySelectorAll(
        "p, span, div"
      );

    Array.prototype.forEach.call(
      elements,
      function (element) {
        if (
          element.id ===
          "trCheckoutLoginIntro"
        ) {
          return;
        }

        if (
          element.children.length > 1
        ) {
          return;
        }

        var text = String(
          element.textContent || ""
        )
          .replace(/\s+/g, "")
          .toLowerCase();

        if (
          text === "أو" ||
          text === "او" ||
          text === "or"
        ) {
          element.classList.add(
            "tr-login-separator-hide"
          );
        }
      }
    );
  }

  function trCreateLoginIntro(target) {
    if (
      !target ||
      !target.parentNode ||
      document.getElementById(
        "trCheckoutLoginIntro"
      )
    ) {
      return;
    }

    var intro =
      document.createElement("div");

    intro.id =
      "trCheckoutLoginIntro";

    intro.innerHTML =
      "<h2>تسجيل الدخول لإكمال الطلب</h2>" +
      '<p class="tr-login-description">أرسل رمز التحقق إلى رقمك المسجل، وبعد الدخول سنعيدك تلقائيًا إلى صفحة إتمام الطلب.</p>' +
      '<p class="tr-login-notice">هذا الرقم مرتبط بحساب سابق. سجّل الدخول برمز التحقق للمتابعة.</p>';

    target.parentNode.insertBefore(
      intro,
      target
    );
  }

  function trCreateLoginActions(
    target,
    standardTarget
  ) {
    if (
      !target ||
      !target.parentNode ||
      document.getElementById(
        "trCheckoutLoginActions"
      )
    ) {
      return;
    }

    var actions =
      document.createElement("div");

    actions.id =
      "trCheckoutLoginActions";

    if (standardTarget) {
      var toggleButton =
        document.createElement(
          "button"
        );

      toggleButton.type = "button";

      toggleButton.id =
        "trShowPasswordLogin";

      toggleButton.textContent =
        "الدخول بالبريد أو كلمة المرور";

      toggleButton.addEventListener(
        "click",
        function () {
          var opened =
            standardTarget
              .classList
              .toggle("is-open");

          toggleButton.textContent =
            opened
              ? "إخفاء الدخول بكلمة المرور"
              : "الدخول بالبريد أو كلمة المرور";

          if (opened) {
            standardTarget.scrollIntoView(
              {
                behavior: "smooth",
                block: "center"
              }
            );
          }
        }
      );

      actions.appendChild(
        toggleButton
      );
    }

    var backLink =
      document.createElement("a");

    var checkoutUrl =
      trGetSavedCheckoutUrl() ||
      "/checkout/";

    backLink.id =
      "trBackToCheckout";

    backLink.href =
      checkoutUrl;

    backLink.textContent =
      "رقم جديد؟ العودة إلى إتمام الطلب";

    backLink.addEventListener(
      "click",
      function () {
        trClearLoginFlow();
      }
    );

    actions.appendChild(backLink);

    target.parentNode.insertBefore(
      actions,
      target.nextSibling
    );
  }

  function trPrefillOtpPhone(
    phoneInput
  ) {
    if (
      !phoneInput ||
      String(
        phoneInput.value || ""
      ).trim()
    ) {
      return;
    }

    var savedPhone =
      trNormalizeSaudiPhone(
        trStorageGet(
          TR.savedPhoneKey
        )
      );

    if (!savedPhone) {
      return;
    }

    trSafeSetValue(
      phoneInput,
      savedPhone,
      true
    );
  }

  function trSetupLoginPage() {
    if (
      !trIsMyAccountPage() ||
      !trIsCheckoutLoginFlow() ||
      trIsLoggedIn()
    ) {
      return false;
    }

    document.body.classList.add(
      "tr-checkout-login-mode"
    );

    var root =
      document.querySelector(
        ".woocommerce, .woocommerce-account"
      );

    var phoneInput =
      document.querySelector(
        "#wln-phone-input"
      );

    if (!root || !phoneInput) {
      return false;
    }

    var otpCard =
      trFindOtpCard(phoneInput);

    if (!otpCard) {
      return false;
    }

    otpCard.classList.add(
      "tr-primary-login-box"
    );

    var otpColumn =
      trGetLoginColumn(otpCard);

    var otpTarget =
      otpColumn ||
      otpCard;

    otpTarget.classList.add(
      "tr-otp-login-target"
    );

    var loginForms =
      document.querySelectorAll(
        "form.woocommerce-form-login, form.login"
      );

    var standardForm = null;

    Array.prototype.some.call(
      loginForms,
      function (form) {
        if (
          !form.contains(phoneInput)
        ) {
          standardForm = form;
          return true;
        }

        return false;
      }
    );

    var standardTarget = null;

    if (standardForm) {
      var standardColumn =
        trGetLoginColumn(
          standardForm
        );

      if (
        standardColumn &&
        !standardColumn.contains(
          otpCard
        )
      ) {
        standardTarget =
          standardColumn;
      } else {
        standardTarget =
          standardForm;
      }

      standardTarget.classList.add(
        "tr-standard-login-target"
      );
    }

    var columnsContainer =
      otpTarget.closest(
        "#customer_login, .u-columns, .col2-set"
      );

    if (columnsContainer) {
      columnsContainer.classList.add(
        "tr-login-columns-container"
      );
    }

    trHideOldLoginHeadings(root);
    trHideLoginSeparators(root);

    trCreateLoginIntro(
      otpTarget
    );

    trCreateLoginActions(
      otpTarget,
      standardTarget
    );

    trPrefillOtpPhone(
      phoneInput
    );

    return true;
  }

  function trReturnToCheckoutAfterLogin() {
    if (
      trStorageGet(
        TR.loginRequiredKey
      ) !== "1" ||
      !trIsLoggedIn()
    ) {
      return;
    }

    var checkoutUrl =
      trGetSavedCheckoutUrl();

    if (!checkoutUrl) {
      trClearLoginFlow();
      return;
    }

    trClearLoginFlow();

    window.location.replace(
      checkoutUrl
    );
  }

  function trBindCheckoutForm() {
    var checkoutForm =
      document.querySelector(
        "form.checkout, form[name='checkout']"
      );

    if (
      !checkoutForm ||
      checkoutForm.dataset
        .trFinalBound === "1"
    ) {
      return;
    }

    checkoutForm.dataset
      .trFinalBound = "1";

    checkoutForm.addEventListener(
      "input",
      function (event) {
        if (
          event.target.matches(
            "#billing_phone, input[name='billing_phone']"
          )
        ) {
          trSaveCheckoutPhone();
          trAutoGenerateEmail(false);
        }

        if (
          event.target.matches(
            "#billing_first_name," +
            "input[name='billing_first_name']," +
            "#billing_phone," +
            "input[name='billing_phone']"
          )
        ) {
          trScheduleGoogleMapsPreload();
        }

        if (
          event.target.matches(
            "#billing_national_address," +
            "#billing_address_short_code," +
            "input[name='billing_national_address']," +
            "input[name='billing_address_short_code']," +
            "input[name*='national_address']," +
            "input[name*='short_code']"
          )
        ) {
          trRestoreMapLink();
        }
      },
      true
    );

    checkoutForm.addEventListener(
      "focusin",
      function (event) {
        if (
          event.target.matches(
            "#billing_first_name," +
            "input[name='billing_first_name']," +
            "#billing_phone," +
            "input[name='billing_phone']"
          )
        ) {
          trScheduleGoogleMapsPreload();
        }
      },
      true
    );

    checkoutForm.addEventListener(
      "blur",
      function (event) {
        if (
          event.target.matches &&
          event.target.matches(
            "#billing_phone, input[name='billing_phone']"
          )
        ) {
          trSaveCheckoutPhone();
          trAutoGenerateEmail(true);
        }

        if (
          event.target ===
          trGetNationalAddressField()
        ) {
          trNormalizeNationalField();
          trRestoreMapLink();
        }
      },
      true
    );

    checkoutForm.addEventListener(
      "submit",
      function () {
        trAutoGenerateEmail(true);
        trNormalizeNationalField();
        trRestoreMapLink();
        trArmAccountCheck();
      },
      true
    );
  }

  function trBindGlobalEvents() {
    if (
      document.body.dataset
        .trFinalGlobalBound === "1"
    ) {
      return;
    }

    document.body.dataset
      .trFinalGlobalBound = "1";

    document.addEventListener(
      "click",
      function (event) {
        var target = event.target;

        if (
          !target ||
          !target.closest
        ) {
          return;
        }

        var orderButton =
          target.closest(
            "#place_order," +
            "button[name='woocommerce_checkout_place_order']," +
            ".wc-block-components-checkout-place-order-button," +
            ".place-order button," +
            "form.checkout button[type='submit']"
          );

        if (!orderButton) {
          return;
        }

        trAutoGenerateEmail(true);
        trNormalizeNationalField();
        trRestoreMapLink();
        trArmAccountCheck();

        setTimeout(
          trCheckWholeCheckoutPage,
          100
        );

        setTimeout(
          trCheckWholeCheckoutPage,
          300
        );

        setTimeout(
          trCheckWholeCheckoutPage,
          700
        );

        setTimeout(
          trCheckWholeCheckoutPage,
          1200
        );
      },
      true
    );

    if (window.jQuery) {
      window
        .jQuery(document)
        .ajaxComplete(
          function (event, xhr) {
            if (
              Date.now() >
              trAccountWatchUntil
            ) {
              return;
            }

            try {
              trInspectAccountText(
                xhr.responseText,
                null
              );
            } catch (error) {}
          }
        );

      window
        .jQuery(document.body)
        .on(
          "checkout_error",
          function () {
            setTimeout(
              trCheckWholeCheckoutPage,
              10
            );
          }
        );

      window
        .jQuery(document.body)
        .on(
          "updated_checkout",
          function () {
            setTimeout(
              function () {
                trInitCheckoutFeatures();
                trAutoGenerateEmail(false);
                trCheckWholeCheckoutPage();
              },
              120
            );
          }
        );

      window
        .jQuery(document.body)
        .on(
          "checkout_place_order",
          function () {
            trAutoGenerateEmail(true);
            trNormalizeNationalField();
            trRestoreMapLink();
            trArmAccountCheck();

            return true;
          }
        );
    }
  }

  function trInitCheckoutFeatures() {
    if (
      !trIsCheckoutPage() ||
      trIsOrderReceivedPage()
    ) {
      return;
    }

    trNormalizeCheckoutDirections();
    trHideGeneratedEmailField();
    trAutoGenerateEmail(false);
    trNormalizeNationalField();
    trEnsureLocationAssist();
    trHideMapLinkField();
    trRestoreMapLink();
    trBindCheckoutForm();
  }

  function trStartPageObserver() {
    if (
      !document.body ||
      !window.MutationObserver ||
      trPageObserver
    ) {
      return;
    }

    var timer = null;

    trPageObserver =
      new MutationObserver(
        function (mutations) {
          if (
            trIsCheckoutPage() &&
            Date.now() <=
              trAccountWatchUntil &&
            !trRedirectStarted
          ) {
            for (
              var index = 0;
              index < mutations.length;
              index++
            ) {
              var mutation =
                mutations[index];

              if (
                mutation.type ===
                  "characterData" &&
                trInspectNode(
                  mutation.target
                )
              ) {
                return;
              }

              var addedNodes =
                mutation.addedNodes ||
                [];

              for (
                var nodeIndex = 0;
                nodeIndex <
                  addedNodes.length;
                nodeIndex++
              ) {
                if (
                  trInspectNode(
                    addedNodes[
                      nodeIndex
                    ]
                  )
                ) {
                  return;
                }
              }
            }
          }

          clearTimeout(timer);

          timer = setTimeout(
            function () {
              if (
                trIsCheckoutPage()
              ) {
                trInitCheckoutFeatures();
                trCheckWholeCheckoutPage();
              }

              if (
                trIsMyAccountPage()
              ) {
                trSetupLoginPage();
                trReturnToCheckoutAfterLogin();
              }
            },
            90
          );
        }
      );

    trPageObserver.observe(
      document.body,
      {
        childList: true,
        subtree: true,
        characterData: true
      }
    );
  }

  function trClearCompletedOrderLocation() {
    if (!trIsOrderReceivedPage()) {
      return;
    }

    trStorageRemove(
      TR.mapLinkKey
    );

    trStorageRemove(
      TR.latitudeKey
    );

    trStorageRemove(
      TR.longitudeKey
    );

    trStorageRemove(
      "tr_location_completed"
    );

    trStorageRemove(
      "tr_google_formatted_address"
    );
  }

  function trInitialize() {
    trClearCompletedOrderLocation();

    trWrapFetch();
    trWrapXHR();
    trBindWindowMessages();
    trBindGlobalEvents();
    trStartPageObserver();

    trInitStoreUI();
    trInitCheckoutFeatures();

    if (trIsCheckoutPage()) {
      trSaveCheckoutContext();
    }

    if (trIsMyAccountPage()) {
      trSetupLoginPage();
      trReturnToCheckoutAfterLogin();
    }

    if (!trPeriodicTimer) {
      trPeriodicTimer =
        setInterval(
          function () {
            if (
              trIsCheckoutPage() &&
              Date.now() <=
                trAccountWatchUntil
            ) {
              trCheckWholeCheckoutPage();
            }

            if (
              trIsMyAccountPage() &&
              trIsCheckoutLoginFlow()
            ) {
              trSetupLoginPage();
              trReturnToCheckoutAfterLogin();
            }
          },
          400
        );
    }
  }

  if (
    document.readyState ===
    "loading"
  ) {
    document.addEventListener(
      "DOMContentLoaded",
      trInitialize
    );
  } else {
    trInitialize();
  }

  window.addEventListener(
    "load",
    function () {
      setTimeout(
        trInitialize,
        250
      );
    }
  );
})();
</script>

				
			
عرض توب رست 🛒 طلب العرض الآن