(function () {
  "use strict";

  /*
   * متجر جمعية الدعوة بغرب الديرة
   * التبرعات والكفالات - النسخة الموحدة
   * اللون المعتمد: #0c897a
   */

  if (window.__deradawaahUnifiedFinal) return;
  window.__deradawaahUnifiedFinal = true;

  const CONFIG = {
    card: "salla-product-card.s-product-card-donation",
    daiyaId: "1470151624",
    umrahId: "962218395",
    kafalaIds: new Set(["1470151624", "962218395"]),
    donationIds: new Set([
      "1646490926",
      "1386173780",
      "789177350",
      "520915242"
    ]),
    kafalaCategoryId: "485242831",
    donationOptions: [
      { label: "50 ريال", amount: 50 },
      { label: "100 ريال", amount: 100 },
      { label: "300 ريال", amount: 300 },
      { label: "500 ريال", amount: 500 }
    ],
    kafalaOptions: [
      { label: "كفالة يوم", amount: 145 },
      { label: "كفالة أسبوع", amount: 1020 },
      { label: "كفالة شهر", amount: 3500 },
      { label: "كفالة سنة", amount: 42000 }
    ]
  };

  const bindings = new WeakMap();
  const processing = new WeakSet();
  let scheduled = false;

  function productId(card) {
    const match = (card.id || "").match(/product-(\d+)/);
    if (match) return match[1];

    const href =
      card.querySelector('a[href*="/p"]')
        ?.getAttribute("href") || "";

    return href.match(/\/p(\d+)/)?.[1] || "";
  }

  function productUrl(card) {
    const link = card.querySelector('a[href*="/p"]');
    if (!link) return "";

    try {
      const url = new URL(link.href, location.href);
      return url.origin === location.origin
        ? url.href
        : "";
    } catch {
      return "";
    }
  }

  /*
   * الإبقاء على طريقة العثور على حقل
   * المساهمة المستخدمة في النسخة السابقة.
   */

  function amountInput(card) {
    return Array.from(card.querySelectorAll("input"))
      .find(input => {
        const text = [
          input.placeholder,
          input.name,
          input.getAttribute("aria-label")
        ].filter(Boolean).join(" ");

        return /مبلغ|مساهمة|تبرع|amount|donat/i
          .test(text);
      });
  }

  /*
   * آلية تعبئة المبلغ الأصلية
   */

  function setAmount(input, amount) {
    if (!input || !input.isConnected) return;

    const value = String(amount);

    if (input.value === value) return;

    const setter = Object.getOwnPropertyDescriptor(
      HTMLInputElement.prototype,
      "value"
    )?.set;

    if (setter) {
      setter.call(input, value);
    } else {
      input.value = value;
    }

    input.dispatchEvent(new Event("input", {
      bubbles: true,
      composed: true
    }));

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

  function getType(card) {
    const id = productId(card);

    if (id === CONFIG.daiyaId) return "donation";
    if (id === CONFIG.umrahId) return "umrah";

    if (CONFIG.kafalaIds.has(id)) return "kafala";
    if (CONFIG.donationIds.has(id)) return "donation";

    const categoryId =
      card.getAttribute("data-category-id");

    const category =
      card.getAttribute("data-category");

    const categories =
      card.getAttribute("data-categories");

    if (
      categoryId === CONFIG.kafalaCategoryId ||
      category?.trim() === "كفالة" ||
      categories?.split(",")
        .map(x => x.trim())
        .includes(CONFIG.kafalaCategoryId)
    ) {
      return "kafala";
    }

    if (category?.trim() === "تبرع") {
      return "donation";
    }

    return "unknown";
  }

  function createOption(label, price) {
    const button = document.createElement("button");

    button.type = "button";
    button.className = "unified-donation-option";
    button.setAttribute("aria-pressed", "false");

    const text = document.createElement("span");
    text.textContent = label;
    button.appendChild(text);

    if (price) {
      const strong = document.createElement("strong");
      strong.textContent = price;
      button.appendChild(strong);
    }

    return button;
  }

  function activate(buttons, selected) {
    buttons.forEach(button => {
      const active = button === selected;

      button.classList.toggle("is-selected", active);
      button.setAttribute("aria-pressed", String(active));
    });
  }

  function insertChoices(input, wrapper) {
    const field =
      input.closest("label") || input.parentElement;

    if (!field?.parentElement) return false;

    field.parentElement.insertBefore(wrapper, field);
    bindings.set(wrapper, input);

    return true;
  }

  /*
   * خيارات التبرعات العامة
   * وكفالة داعية
   */

  function renderStandard(card, type, input, old) {
    if (
      old?.dataset.type === type &&
      bindings.get(old) === input
    ) {
      return;
    }

    old?.remove();

    const isKafala = type === "kafala";

    const options = isKafala
      ? CONFIG.kafalaOptions
      : CONFIG.donationOptions;

    const wrapper = document.createElement("div");
    wrapper.className = "unified-donation-choices";
    wrapper.dataset.type = type;

    const heading = document.createElement("div");
    heading.className = "unified-donation-heading";
    heading.textContent = isKafala
      ? "اختر مدة الكفالة"
      : "اختر مبلغ التبرع";

    const grid = document.createElement("div");
    grid.className = "unified-donation-grid";

    const buttons = [];

    options.forEach(option => {
      const button = createOption(
        option.label,
        isKafala
          ? option.amount.toLocaleString("en-US") +
            " ريال"
          : null
      );

      button.dataset.amount = String(option.amount);

      button.addEventListener("click", event => {
        event.preventDefault();
        event.stopPropagation();

        activate(buttons, button);
        setAmount(input, option.amount);
      });

      buttons.push(button);
      grid.appendChild(button);
    });

    if (!isKafala) {
      const custom = createOption("مبلغ آخر");

      custom.classList.add(
        "unified-donation-custom"
      );

      custom.addEventListener("click", event => {
        event.preventDefault();
        event.stopPropagation();

        activate(buttons, custom);
        setAmount(input, "");
        input.focus();
      });

      buttons.push(custom);
      grid.appendChild(custom);
    }

    input.addEventListener("input", () => {
      if (!wrapper.isConnected) return;

      const selected = buttons.find(button =>
        button.dataset.amount &&
        button.dataset.amount === input.value
      );

      activate(buttons, selected || null);
    });

    wrapper.append(heading, grid);

    if (!insertChoices(input, wrapper)) {
      wrapper.remove();
    }
  }

  /*
   * كفالة معتمر
   * مقعد: 255 ريال
   * حملة كاملة: 12500 ريال
   * مبلغ آخر: مساهمة مستقلة
   */

  function renderUmrah(card, input, old) {
    if (
      old?.dataset.type === "umrah" &&
      bindings.get(old) === input
    ) {
      return;
    }

    old?.remove();

    const wrapper = document.createElement("div");

    wrapper.className =
      "unified-donation-choices unified-umrah-choices";

    wrapper.dataset.type = "umrah";
    wrapper.style.cssText =
      "direction:rtl;text-align:right;display:grid;gap:12px";

    const heading = document.createElement("div");
    heading.className = "unified-donation-heading";
    heading.textContent = "اختر نوع الكفالة";

    const grid = document.createElement("div");
    grid.className = "unified-donation-grid";

    const seat = createOption(
      "كفالة مقعد أو أكثر",
      "255 ريال للمقعد"
    );

    const full = createOption(
      "كفالة الحملة كاملة",
      "12,500 ريال"
    );

    const custom = createOption("مبلغ آخر");
    custom.classList.add("unified-donation-custom");

    grid.append(seat, full, custom);

    const counter = document.createElement("div");
    counter.style.cssText =
      "display:flex;align-items:center;" +
      "justify-content:space-between;" +
      "gap:10px;flex-wrap:wrap";

    const counterLabel = document.createElement("span");
    counterLabel.textContent = "عدد المقاعد";

    const controls = document.createElement("div");
    controls.style.cssText =
      "display:flex;align-items:center;gap:12px";

    const minus = document.createElement("button");
    minus.type = "button";
    minus.textContent = "−";
    minus.setAttribute(
      "aria-label",
      "تقليل عدد المقاعد"
    );

    const plus = document.createElement("button");
    plus.type = "button";
    plus.textContent = "+";
    plus.setAttribute(
      "aria-label",
      "زيادة عدد المقاعد"
    );

    [minus, plus].forEach(button => {
      button.style.cssText =
        "border:1px solid #0c897a;" +
        "border-radius:8px;" +
        "min-width:36px;min-height:36px;" +
        "font-size:20px;color:#0c897a;" +
        "background:transparent;cursor:pointer";
    });

    const countText = document.createElement("strong");
    countText.style.cssText =
      "min-width:24px;text-align:center";

    controls.append(minus, countText, plus);
    counter.append(counterLabel, controls);

    const summary = document.createElement("div");
    summary.style.cssText =
      "padding:10px 12px;border-radius:9px;" +
      "background:rgba(12,137,122,.08);" +
      "font-weight:700";

    const note = document.createElement("small");
    note.textContent =
      "هدف الحملة 12,500 ريال لـ49 معتمرًا.";
    note.style.cssText =
      "display:block;line-height:1.7;opacity:.8";

    let mode = "seat";
    let count = 1;
    let customAmount = 0;

    function update() {
      const amount =
        mode === "custom"
          ? customAmount
          : mode === "full"
            ? 12500
            : count * 255;

      activate(
        [seat, full, custom],
        mode === "seat"
          ? seat
          : mode === "full"
            ? full
            : custom
      );

      counter.hidden = mode !== "seat";

      countText.textContent = String(count);
      minus.disabled = count <= 1;
      plus.disabled = count >= 49;

      summary.textContent = mode === "custom"
        ? "مبلغ المساهمة: " +
          (amount > 0
            ? amount.toLocaleString("en-US") + " ريال"
            : "أدخل المبلغ أدناه")
        : "إجمالي الكفالة: " +
          amount.toLocaleString("en-US") + " ريال";

      if (mode !== "custom") {
        setAmount(input, amount);
      }
    }

    seat.addEventListener("click", event => {
      event.preventDefault();
      event.stopPropagation();
      mode = "seat";
      update();
    });

    full.addEventListener("click", event => {
      event.preventDefault();
      event.stopPropagation();
      mode = "full";
      update();
    });

    custom.addEventListener("click", event => {
      event.preventDefault();
      event.stopPropagation();

      mode = "custom";
      customAmount = 0;

      setAmount(input, "");
      update();
      input.focus();
    });

    minus.addEventListener("click", event => {
      event.preventDefault();
      event.stopPropagation();

      count = Math.max(1, count - 1);
      mode = "seat";
      update();
    });

    plus.addEventListener("click", event => {
      event.preventDefault();
      event.stopPropagation();

      count = Math.min(49, count + 1);
      mode = "seat";
      update();
    });

    input.addEventListener("input", () => {
      if (!wrapper.isConnected) return;

      if (mode === "custom") {
        customAmount = Number(input.value) || 0;
        update();
      }
    });

    wrapper.addEventListener("click", event => {
      event.stopPropagation();
    });

    wrapper.append(
      heading,
      grid,
      counter,
      summary,
      note
    );

    if (insertChoices(input, wrapper)) {
      update();
    } else {
      wrapper.remove();
    }
  }

  function renderChoices(card, type) {
    const input = amountInput(card);

    const old = card.querySelector(
      ".unified-donation-choices"
    );

    if (!input || type === "unknown") {
      old?.remove();
      return;
    }

    if (type === "umrah") {
      renderUmrah(card, input, old);
    } else {
      renderStandard(card, type, input, old);
    }
  }

  /*
   * المزيد من التفاصيل
   * يظهر فوق خيارات المبالغ
   */

  function addMoreDetails(card) {
    const url = productUrl(card);
    if (!url) return;

    const choices = card.querySelector(
      ".unified-donation-choices"
    );

    if (!choices?.parentElement) return;

    let link = card.querySelector(
      ".deradawaah-more-details"
    );

    if (!link) {
      link = document.createElement("a");
      link.className = "deradawaah-more-details";
      link.textContent = "المزيد من التفاصيل";
    }

    link.href = url;

    if (
      link.parentElement !== choices.parentElement ||
      link.nextElementSibling !== choices
    ) {
      choices.parentElement.insertBefore(
        link,
        choices
      );
    }
  }

  /*
   * زر تبرع الآن:
   * لا نغير وظيفته ولا نعترض الضغط عليه.
   * سلة تتولى الإضافة للسلة بالطريقة الأصلية.
   */

  function donateButton(card) {
    return Array.from(
      card.querySelectorAll("button, salla-button")
    ).find(element =>
      (element.textContent || "").includes("تبرع الآن")
    );
  }

  /*
   * شعارات الدفع - للعرض فقط
   * بدون زر Apple Pay منفصل في البطاقة
   */

  function addPaymentActions(card) {
    const donate = donateButton(card);
    if (!donate) return;

    let row = card.querySelector(
      ".unified-donation-payment"
    );

    if (!row) {
      row = document.createElement("div");
      row.className = "unified-donation-payment";

      row.innerHTML = `
        <span class="unified-pay-visa"
              title="Visa">VISA</span>

        <span class="unified-pay-master"
              title="Mastercard">
          <i></i><i></i>
        </span>

        <span class="unified-pay-bank"
              title="تحويل بنكي">
          <svg viewBox="0 0 24 24"
               width="25" height="25"
               fill="none"
               stroke="currentColor"
               stroke-width="1.8"
               stroke-linecap="round"
               stroke-linejoin="round">
            <path d="m3 10 9-6 9 6"/>
            <path d="M4 10h16"/>
            <path d="M5 20h14"/>
            <path d="M3 22h18"/>
            <path d="M7 10v10"/>
            <path d="M12 10v10"/>
            <path d="M17 10v10"/>
          </svg>
        </span>

        <span class="unified-pay-apple"
              title="Apple Pay">
          <svg viewBox="0 0 24 24"
               width="22" height="22"
               fill="currentColor"
               aria-hidden="true">
            <path d="M17.05 12.54c.02 2.25 1.97 3 1.99 3.01-.02.05-.31 1.07-1.03 2.13-.62.91-1.26 1.82-2.27 1.84-.99.02-1.31-.59-2.45-.59-1.14 0-1.5.57-2.43.61-.97.04-1.7-.99-2.32-1.89-1.27-1.85-2.24-5.23-.94-7.51a3.6 3.6 0 0 1 3.04-1.86c.95-.02 1.85.66 2.43.66.58 0 1.67-.82 2.82-.7.48.02 1.83.19 2.7 1.46-.07.05-1.61.94-1.59 2.84ZM15.99 6.03A3.47 3.47 0 0 0 16.8 3.5a3.53 3.53 0 0 0-2.31 1.2 3.32 3.32 0 0 0-.84 2.45 2.95 2.95 0 0 0 2.34-1.12Z"/>
          </svg>
          <small>Pay</small>
        </span>
      `;
    }

    if (row.previousElementSibling !== donate) {
      donate.insertAdjacentElement("afterend", row);
    }

    let actions = card.querySelector(
      ".unified-donation-actions"
    );

    if (!actions) {
      actions = document.createElement("div");
      actions.className = "unified-donation-actions";
    }

    if (actions.previousElementSibling !== row) {
      row.insertAdjacentElement("afterend", actions);
    }

    actions.querySelectorAll(
      ".unified-donation-apple, .unified-native-apple"
    ).forEach(element => element.remove());

    let gift = actions.querySelector(
      ".unified-donation-gift"
    );

    if (!gift) {
      const url = productUrl(card);
      if (!url) return;

      gift = document.createElement("a");
      gift.href = url;
      gift.className = "unified-donation-gift";
      gift.textContent = "🎁 أرسل كهدية";

      actions.appendChild(gift);
    }
  }

  /*
   * الإهداء الرسمي في سلة
   */

  function prepareGifting(card) {
    const id = productId(card);

    if (
      !CONFIG.kafalaIds.has(id) &&
      !CONFIG.donationIds.has(id)
    ) {
      return;
    }

    if (card.querySelector(".unified-native-gifting")) {
      return;
    }

    const gifting = document.createElement(
      "salla-gifting"
    );

    gifting.className = "unified-native-gifting";
    gifting.setAttribute("product-id", id);
    gifting.setAttribute("widget-title", "أرسل كهدية");
    gifting.setAttribute(
      "widget-subtitle",
      "أرسل هذا المشروع كهدية تسعد أحبابك."
    );

    gifting.style.position = "absolute";
    gifting.style.width = "1px";
    gifting.style.height = "1px";
    gifting.style.overflow = "hidden";
    gifting.style.clipPath = "inset(50%)";

    card.appendChild(gifting);
  }

  document.addEventListener(
    "click",
    async event => {
      const target =
        event.target instanceof Element
          ? event.target
          : null;

      const gift = target?.closest(
        "a.unified-donation-gift"
      );

      if (!gift) return;

      const card = gift.closest(CONFIG.card);
      if (!card) return;

      const id = productId(card);

      const supported =
        CONFIG.kafalaIds.has(id) ||
        CONFIG.donationIds.has(id);

      if (!supported) return;

      event.preventDefault();
      event.stopPropagation();

      prepareGifting(card);

      const widget = card.querySelector(
        ".unified-native-gifting"
      );

      if (!widget) {
        if (gift.href) location.href = gift.href;
        return;
      }

      try {
        await customElements.whenDefined(
          "salla-gifting"
        );

        if (typeof widget.open !== "function") {
          throw new Error("Gifting API unavailable");
        }

        await widget.open();
      } catch (error) {
        console.warn("Salla gifting:", error);

        if (gift.href) {
          location.href = gift.href;
        }
      }
    },
    true
  );

  /*
   * ترتيب قسم التبرع في صفحة المنتج
   *
   * تقديم نموذج التبرع قبل قسم التفاصيل
   * عند وجودهما في الحاوية نفسها.
   * عدم تفكيك النموذج حتى لا يتعطل الدفع.
   */

  function arrangeProductPage() {
    const productArea = document.querySelector(
      ".product-entry, .product-single, main"
    );

    if (!productArea) return;

    const candidates = Array.from(
      productArea.querySelectorAll(
        "form, section, .product-form, .product-options"
      )
    );

    const donationSection = candidates.find(section => {
      if (section.closest(CONFIG.card)) return false;

      const text = section.textContent || "";

      return (
        /تبرع الآن/.test(text) &&
        (
          /اختر المبلغ|اختر مبلغ|مبلغ المساهمة/
            .test(text) ||
          Boolean(section.querySelector(
            'input[name="amount"], ' +
            'input[name="donation_amount"]'
          ))
        )
      );
    });

    if (!donationSection) return;

    const parent = donationSection.parentElement;
    if (!parent) return;

    const details = Array.from(parent.children)
      .find(element => {
        if (element === donationSection) return false;

        const text = element.textContent || "";

        return /تفاصيل المشروع|تفاصيل المنتج|وصف المشروع/
          .test(text);
      });

    if (!details) return;

    const detailsBeforeDonation = Boolean(
      details.compareDocumentPosition(donationSection) &
      Node.DOCUMENT_POSITION_FOLLOWING
    );

    if (detailsBeforeDonation) {
      parent.insertBefore(
        donationSection,
        details
      );
    }

    donationSection.classList.add(
      "deradawaah-donation-first"
    );
  }

  /*
   * التنسيق الإضافي المدمج
   */

  function installStyles() {
    if (
      document.getElementById(
        "deradawaah-unified-final-style"
      )
    ) return;

    const style = document.createElement("style");
    style.id = "deradawaah-unified-final-style";

    style.textContent = `
      ${CONFIG.card} .deradawaah-more-details {
        display:flex!important;
        align-items:center;
        justify-content:center;
        width:100%;
        min-height:48px;
        margin:14px 0 18px!important;
        padding:12px 16px;
        border:1px solid #0c897a;
        border-radius:13px;
        background:#f0f8f6;
        color:#0c897a!important;
        font-size:15px;
        font-weight:700;
        text-align:center;
        text-decoration:none!important;
        cursor:pointer;
        box-sizing:border-box;
      }

      ${CONFIG.card} .deradawaah-more-details:hover {
        background:#e2f3ee;
      }

      ${CONFIG.card} .unified-donation-payment {
        display:grid!important;
        grid-template-columns:repeat(4,minmax(0,1fr));
        gap:7px;
        align-items:center;
        width:100%;
        margin:12px 0;
      }

      ${CONFIG.card} .unified-donation-payment > span {
        display:flex!important;
        align-items:center;
        justify-content:center;
        width:100%!important;
        min-width:0;
        min-height:38px;
        padding:4px;
        background:#fff;
        border:1px solid #e1e8e6;
        border-radius:9px;
        box-sizing:border-box;
      }

      ${CONFIG.card} .unified-pay-apple {
        color:#111!important;
        gap:2px;
        white-space:nowrap;
        font-weight:700;
      }

      ${CONFIG.card} .unified-pay-apple small {
        font-size:12px;
      }

      ${CONFIG.card} .unified-donation-apple,
      ${CONFIG.card} .unified-native-apple {
        display:none!important;
      }

      ${CONFIG.card} .unified-donation-actions {
        width:100%;
      }

      ${CONFIG.card} .unified-donation-gift {
        display:flex!important;
        align-items:center;
        justify-content:center;
        width:100%;
        min-height:48px;
        padding:12px;
        border:1px solid #0c897a;
        border-radius:12px;
        color:#0c897a!important;
        background:#fff;
        font-weight:700;
        text-decoration:none!important;
        box-sizing:border-box;
      }

      .deradawaah-donation-first {
        margin-bottom:20px;
      }

      @media(max-width:767px) {
        ${CONFIG.card} .unified-donation-payment {
          gap:5px;
        }

        ${CONFIG.card} .deradawaah-more-details {
          min-height:48px;
        }
      }
    `;

    document.head.appendChild(style);
  }

  /*
   * تشغيل التخصيص على جميع البطاقات
   */

  function enhanceCard(card) {
    if (processing.has(card)) return;

    processing.add(card);

    try {
      const type = getType(card);

      card.classList.toggle(
        "unified-is-kafala",
        type === "kafala" || type === "umrah"
      );

      renderChoices(card, type);
      addMoreDetails(card);
      addPaymentActions(card);
      prepareGifting(card);

    } catch (error) {
      console.error(
        "Donation enhancement error:",
        error
      );
    } finally {
      processing.delete(card);
    }
  }

  function scan() {
    document.querySelectorAll(CONFIG.card)
      .forEach(enhanceCard);

    arrangeProductPage();
  }

  function scheduleScan() {
    if (scheduled) return;

    scheduled = true;

    requestAnimationFrame(() => {
      scheduled = false;

      if (!document.hidden) {
        scan();
      }
    });
  }

  function start() {
    installStyles();
    scan();

    const observer = new MutationObserver(records => {
      const changed = records.some(record =>
        record.addedNodes.length > 0 ||
        record.removedNodes.length > 0
      );

      if (changed) scheduleScan();
    });

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

    window.addEventListener(
      "pageshow",
      scheduleScan
    );

    window.addEventListener(
      "popstate",
      scheduleScan
    );

    window.addEventListener(
      "hashchange",
      scheduleScan
    );

    document.addEventListener(
      "visibilitychange",
      () => {
        if (!document.hidden) scheduleScan();
      }
    );

    document.addEventListener(
      "salla::page:loaded",
      scheduleScan
    );

    document.addEventListener(
      "salla::products:loaded",
      scheduleScan
    );
  }

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

})();


/*
 * تقديم قسم التبرع على تفاصيل المنتج
 * لجميع صفحات التبرعات والكفالات الداخلية
 */

(function () {
  "use strict";

  if (window.__deradawaahProductOrderV2) return;
  window.__deradawaahProductOrderV2 = true;

  let scheduled = false;

  function isVisible(element) {
    return element &&
      element.getClientRects().length > 0;
  }

  function isProductPage() {
    return Boolean(
      document.querySelector(
        ".product-entry, .product-single, " +
        ".product-details, [class*='product-details']"
      )
    ) || /\/p\d+(?:\/|$)/.test(location.pathname);
  }

  function findDonationBlock() {
    const selectors = [
      "form",
      "section",
      ".product-form",
      ".product-options",
      "[class*='donation']"
    ];

    const candidates = Array.from(
      document.querySelectorAll(
        selectors.join(",")
      )
    ).filter(el =>
      !el.closest(
        "salla-product-card.s-product-card-donation"
      )
    );

    const matches = candidates.filter(el => {
      if (!isVisible(el)) return false;

      const text = el.textContent || "";

      return (
        /اختر المبلغ/.test(text) &&
        (
          /أضف لسلة التبرعات|تبرع الآن/.test(text)
        )
      );
    });

    // اختيار أصغر حاوية تشمل المبلغ وزر التبرع
    return matches.sort((a, b) =>
      a.querySelectorAll("*").length -
      b.querySelectorAll("*").length
    )[0] || null;
  }

  function arrange() {
    if (!isProductPage()) return;

    const donation = findDonationBlock();
    if (!donation) return;

    const parent = donation.parentElement;
    if (!parent) return;

    // تجنب نقل النموذج خارج حاويته
    const siblings = Array.from(parent.children);

    const first = siblings.find(el =>
      el !== donation &&
      el.nodeType === 1 &&
      isVisible(el)
    );

    if (!first) return;

    if (donation.nextElementSibling === first) {
      return;
    }

    // نقل القسم كاملًا مع المحافظة على الأحداث
    parent.insertBefore(donation, first);

    donation.classList.add(
      "deradawaah-donation-first"
    );
  }

  function schedule() {
    if (scheduled) return;

    scheduled = true;

    requestAnimationFrame(() => {
      scheduled = false;
      arrange();
    });
  }

  function start() {
    schedule();

    const observer = new MutationObserver(records => {
      if (records.some(record =>
        record.addedNodes.length ||
        record.removedNodes.length
      )) {
        schedule();
      }
    });

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

    window.addEventListener("pageshow", schedule);
    window.addEventListener("popstate", schedule);

    document.addEventListener(
      "salla::page:loaded",
      schedule
    );
  }

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