/* جمعية المقام — يوضع كاملًا في خانة JavaScript دون وسوم script */
(() => {
  'use strict';
  if (window.__almaqamDonationCards) return;
  window.__almaqamDonationCards = true;
  const CARD = '#main-content custom-salla-product-card, #main-content salla-product-card';
  const INPUT = 'input[name="donating_amount"], input[id^="donation-amount"]';
  // اقتراحات للمشاريع ذات المبلغ المفتوح فقط؛ الخيارات المحددة تُقرأ من سلة.
  const SUGGESTED = [30, 50, 100, 300];
  const cache = new Map();
  const pending = new Map();
  const states = new WeakMap();
  const inputOf = card => card.querySelector(INPUT);
  const amountOf = value => Number(String(value).trim()
    .replace(/[٠-٩]/g, n => String('٠١٢٣٤٥٦٧٨٩'.indexOf(n)))
    .replace(/[۰-۹]/g, n => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(n)))
    .replace(/٫/g, '.'));
  const setText = (element, value) => {
    if (element && element.textContent !== value) element.textContent = value;
  };
  function selectAmount(card, value) {
    const input = inputOf(card);
    if (!input || input.disabled || input.readOnly) return;
    Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, String(value));
    input.dispatchEvent(new Event('input', { bubbles: true }));
    input.dispatchEvent(new Event('change', { bubbles: true }));
  }
  function sync(card) {
    const amount = amountOf(inputOf(card)?.value ?? '');
    card.querySelectorAll('.mq-choices [data-amount]').forEach(button => {
      const selected = String(amount > 0 && Number(button.dataset.amount) === amount);
      if (button.getAttribute('aria-pressed') !== selected) button.setAttribute('aria-pressed', selected);
    });
  }
  function setupActions(card) {
    const native = card.querySelector('salla-add-product-button');
    const field = inputOf(card);
    if (!native || !field || field.disabled) return;
    const row = native.parentElement;
    if (!row || row === card) return;
    row.classList.add('mq-actions');
    setText(native.querySelector('.s-button-text'), 'إضافة');
    if (row.querySelector('.mq-donate')) return;
    const donate = document.createElement('button');
    donate.type = 'button';
    donate.className = 'mq-donate';
    donate.textContent = 'تبرع';
    donate.addEventListener('click', () => {
      if (donate.disabled) return;
      const input = inputOf(card);
      const current = card.querySelector('salla-add-product-button');
      const button = current?.querySelector('button') || current?.shadowRoot?.querySelector('button');
      const amount = amountOf(input?.value ?? '');
      if (!input || input.disabled || !Number.isFinite(amount) || amount <= 0) {
        input?.focus();
        input?.setCustomValidity('أدخل مبلغ تبرع أكبر من صفر');
        input?.reportValidity();
        return;
      }
      input.setCustomValidity('');
      if (!input.checkValidity()) { input.reportValidity(); return; }
      if (!button || button.disabled) return;
      if (!input.readOnly) selectAmount(card, amount);
      // مزامنة خاصية المبلغ الرسمية، مع استخدام زر سلة نفسه للإضافة.
      current.donatingAmount = amount;
      current.setAttribute('donating-amount', String(amount));
      donate.disabled = true;
      donate.textContent = 'جارٍ الإضافة…';
      let timer;
      const cleanup = () => {
        clearTimeout(timer);
        current.removeEventListener('success', success);
        current.removeEventListener('failed', failure);
        donate.disabled = false;
        donate.textContent = 'تبرع';
      };
      const success = () => {
        cleanup();
        window.location.assign(new URL('/cart', location.origin).href);
      };
      const failure = () => cleanup();
      current.addEventListener('success', success);
      current.addEventListener('failed', failure);
      timer = setTimeout(cleanup, 20000);
      button.click();
    });
    row.appendChild(donate);
  }
  function loadOptions(url, id) {
    const key = id + '|' + url;
    if (cache.has(key)) return Promise.resolve(cache.get(key));
    if (pending.has(key)) return pending.get(key);
    const task = (async () => {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), 15000);
      try {
        const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
        if (!response.ok) throw new Error('تعذر الاتصال');
        const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
        const element = [...doc.querySelectorAll('salla-product-options')]
          .find(item => item.getAttribute('product-id') === id);
        const options = JSON.parse(element?.getAttribute('options') || 'null');
        if (!Array.isArray(options)) throw new Error('تعذر قراءة خيارات المشروع');
        const donation = options.find(option => option.type === 'donation');
        if (!donation) throw new Error('لا توجد خيارات تبرع');
        const custom = donation.donation?.custom_amount_enabled === true;
        const amounts = (Array.isArray(donation.details) ? donation.details : [])
          .filter(item => !item.is_out)
          .map(item => ({ value: amountOf(item.option_value ?? item.name), label: String(item.name ?? '') }))
          .filter(item => Number.isFinite(item.value) && item.value > 0)
          .filter((item, index, all) => all.findIndex(other => other.value === item.value) === index);
        const result = { amounts: amounts.length ? amounts : (custom ? SUGGESTED.map(value => ({ value, label: String(value) })) : []), custom, suggested: !amounts.length && custom };
        cache.set(key, result);
        return result;
      } finally { clearTimeout(timer); }
    })();
    pending.set(key, task);
    task.then(() => pending.delete(key), () => pending.delete(key));
    return task;
  }
  function buildChoices(card, options) {
    const choices = document.createElement('div');
    choices.className = 'mq-choices';
    choices.setAttribute('role', 'group');
    choices.setAttribute('aria-label', options.suggested ? 'مبالغ مقترحة للتبرع' : 'اختر مبلغ التبرع');
    for (const item of options.amounts) {
      const button = document.createElement('button');
      button.type = 'button';
      button.dataset.amount = String(item.value);
      button.setAttribute('aria-pressed', 'false');
      button.textContent = Number.isFinite(amountOf(item.label)) && amountOf(item.label) > 0
        ? `ساهم بـ ${item.value} ريال` : item.label || `ساهم بـ ${item.value} ريال`;
      button.addEventListener('click', () => { selectAmount(card, item.value); sync(card); });
      choices.appendChild(button);
    }
    if (options.custom) {
      const custom = document.createElement('button');
      custom.type = 'button';
      custom.textContent = 'تبرع بما تجود به نفسك';
      custom.addEventListener('click', () => { const input = inputOf(card); input?.focus(); input?.select(); });
      choices.appendChild(custom);
    }
    return choices;
  }
  async function reconcile(card) {
    const input = inputOf(card);
    const image = card.querySelector('.product-entry__image, .s-product-card-image');
    const link = image?.querySelector('a[href]');
    const native = card.querySelector('salla-add-product-button');
    if (!input || input.disabled || !image || !link || !native) return;
    const id = native.getAttribute('product-id') || card.id.match(/^product-(\d+)$/)?.[1] || input.id.match(/^donation-amount-(\d+)$/)?.[1];
    if (!id || !/^\d+$/.test(id)) return;
    const url = new URL(link.href, location.href);
    if (url.origin !== location.origin) return;
    url.search = ''; url.hash = '';
    const key = id + '|' + url.href;
    card.classList.add('mq-card'); image.classList.add('mq-image');
    card.querySelector('.content-wrap, .s-product-card-content')?.classList.add('mq-content');
    const originalTitle = card.querySelector('.product-entry__title, .s-product-card-content-title, .content-wrap h3');
    let panel = card.querySelector(':scope > .mq-panel');
    if (!panel) {
      panel = document.createElement('div'); panel.className = 'mq-panel';
      const title = document.createElement('a'); title.className = 'mq-title';
      panel.appendChild(title); image.insertAdjacentElement('afterend', panel);
    }
    const title = panel.querySelector('.mq-title');
    if (title.href !== url.href) title.href = url.href;
    setText(title, originalTitle?.textContent.trim() || link.getAttribute('aria-label') || 'مشروع التبرع');
    originalTitle?.classList.add('mq-original-title');
    setupActions(card);
    let state = states.get(card);
    if (!state || state.key !== key || state.panel !== panel) {
      panel.querySelector('.mq-choices')?.remove(); panel.querySelector('.mq-status')?.remove();
      state = { key, panel, busy: false, done: false, attempts: 0, next: 0 };
      states.set(card, state);
    }
    if (state.busy || state.done || state.attempts >= 3 || Date.now() < state.next) return;
    state.busy = true; state.attempts++;
    let status = panel.querySelector('.mq-status');
    if (!status) { status = document.createElement('div'); status.className = 'mq-status'; status.setAttribute('role', 'status'); panel.appendChild(status); }
    setText(status, 'جارٍ تحميل مبالغ التبرع…');
    try {
      const options = await loadOptions(url.href, id);
      if (!panel.isConnected || states.get(card) !== state) return;
      if (options.amounts.length || options.custom) panel.appendChild(buildChoices(card, options));
      status.remove(); state.done = true; sync(card);
    } catch (_) {
      state.next = Date.now() + 10000;
      if (status.isConnected) setText(status, 'يمكنك إدخال مبلغ التبرع مباشرة');
      if (state.attempts < 3) setTimeout(() => { if (card.isConnected) void reconcile(card); }, 10100);
    } finally { state.busy = false; }
  }
  function scan() { document.querySelectorAll(CARD).forEach(card => void reconcile(card)); }
  function amountChanged(event) {
    if (!(event.target instanceof HTMLInputElement) || !event.target.matches(INPUT)) return;
    event.target.setCustomValidity('');
    const card = event.target.closest('custom-salla-product-card, salla-product-card');
    if (card) sync(card);
  }
  function start() {
    document.addEventListener('input', amountChanged);
    document.addEventListener('change', amountChanged);
    let scheduled = false;
    new MutationObserver(() => {
      if (scheduled) return;
      scheduled = true;
      requestAnimationFrame(() => { scheduled = false; scan(); });
    }).observe(document.body, { childList: true, subtree: true });
    scan();
    // إعادة المحاولة عندما تكمل مكونات سلة تحميل أزرارها.
    [1000, 3000, 6000].forEach(delay => setTimeout(scan, delay));
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });
  else start();
})();