/* Masabeeh | Salla donation card enhancement
 * Replaces the previous scripts for donation-card shares and labels.
 * Keeps Salla's own add-to-cart logic and native subtitle intact.
 */
(() => {
  'use strict';

  const CARD_SELECTOR = 'salla-product-card, custom-salla-product-card';
  const INPUT_SELECTOR = 'input[name="donating_amount"]';
  const PANEL_SELECTOR = '.msb-stable-options';
  const SHARES = [
    { label: 'سهم العطاء', amount: 50 },
    { label: 'سهم الخير', amount: 100 },
    { label: 'سهم الإحسان', amount: 200 }
  ];

  // Allow safe reloading of the script without duplicate listeners/observers.
  window.__MASABEEH_CARD__?.stop?.();
  const controller = new AbortController();
  let observer;
  let scheduled = false;

  function setNativeInputValue(input, amount) {
    const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
    if (setter) setter.call(input, String(amount));
    else input.value = String(amount);
    input.dispatchEvent(new Event('input', { bubbles: true }));
    input.dispatchEvent(new Event('change', { bubbles: true }));
  }

  function updateActive(card) {
    const input = card.querySelector(INPUT_SELECTOR);
    if (!input) return;
    const value = input.value.trim();
    card.querySelectorAll('.msb-stable-share').forEach(button => {
      const active = value !== '' && Number(value) === Number(button.dataset.amount);
      button.classList.toggle('is-active', active);
      button.setAttribute('aria-pressed', String(active));
    });
  }

  function buildPanel() {
    const panel = document.createElement('div');
    panel.className = 'msb-stable-options';
    panel.dir = 'rtl';

    const heading = document.createElement('div');
    heading.className = 'msb-stable-title';
    heading.textContent = 'اختر سهم المساهمة';

    const grid = document.createElement('div');
    grid.className = 'msb-stable-grid';
    SHARES.forEach(({ label, amount }) => {
      const button = document.createElement('button');
      button.type = 'button';
      button.className = 'msb-stable-share';
      button.dataset.amount = String(amount);
      button.setAttribute('aria-pressed', 'false');
      button.textContent = label;
      grid.append(button);
    });
    panel.append(heading, grid);
    return panel;
  }

  function enhanceCard(card) {
    const input = card.querySelector(INPUT_SELECTOR);
    if (!input) return;

    // Native Salla subtitle is already present: avoid duplicate descriptions.
    if (card.querySelector('.s-product-card-content-subtitle')) {
      card.querySelectorAll('.msb-product-subtitle').forEach(node => node.remove());
    }

    // Remove legacy panels if any; preserve the one canonical panel.
    card.querySelectorAll('.msb-donation, .msb-native-options').forEach(node => node.remove());
    const panels = card.querySelectorAll(PANEL_SELECTOR);
    panels.forEach((panel, index) => { if (index > 0) panel.remove(); });

    if (!panels.length) {
      const container = input.closest('.s-product-card-donation-input') || input.parentElement;
      if (container?.parentElement) container.before(buildPanel());
    }

    // Only replace the exact old labels to avoid overwriting custom merchant text.
    const label = input.closest('.s-product-card-donation-input')?.querySelector('label');
    if (label && label.textContent.trim().includes('مبلغ المساهمة')) {
      label.textContent = 'تبرع بما تجود به نفسك ';
      const required = document.createElement('span');
      required.textContent = '*';
      label.append(required);
    }

    const action = card.querySelector('salla-add-product-button .s-button-text');
    if (action && action.textContent.trim() === 'أضف لسلة التبرعات') {
      action.textContent = 'تبرع الآن';
    }
    updateActive(card);
  }

  function scan() {
    document.querySelectorAll(CARD_SELECTOR).forEach(enhanceCard);
  }

  function scheduleScan() {
    if (scheduled) return;
    scheduled = true;
    requestAnimationFrame(() => {
      scheduled = false;
      scan();
    });
  }

  function relevantMutation(record) {
    return [...record.addedNodes, ...record.removedNodes].some(node =>
      node.nodeType === 1 && (
        node.matches?.(CARD_SELECTOR) ||
        node.matches?.(INPUT_SELECTOR) ||
        node.querySelector?.(CARD_SELECTOR) ||
        node.querySelector?.(INPUT_SELECTOR)
      )
    );
  }

  function onClick(event) {
    const button = event.target.closest?.('.msb-stable-share');
    if (!button) return;
    const card = button.closest(CARD_SELECTOR);
    const input = card?.querySelector(INPUT_SELECTOR);
    if (!input) return;
    event.preventDefault();
    event.stopPropagation();
    setNativeInputValue(input, button.dataset.amount);
    updateActive(card);
  }

  function onInput(event) {
    if (!event.target.matches?.(INPUT_SELECTOR)) return;
    const card = event.target.closest(CARD_SELECTOR);
    if (card) updateActive(card);
  }

  function start() {
    if (!document.body) return;
    scan();
    document.addEventListener('click', onClick, { signal: controller.signal });
    document.addEventListener('input', onInput, { signal: controller.signal });
    document.addEventListener('change', onInput, { signal: controller.signal });
    window.addEventListener('pageshow', scheduleScan, { signal: controller.signal });
    window.addEventListener('popstate', scheduleScan, { signal: controller.signal });
    observer = new MutationObserver(records => {
      if (records.some(relevantMutation)) scheduleScan();
    });
    observer.observe(document.body, { childList: true, subtree: true });
  }

  window.__MASABEEH_CARD__ = {
    refresh: scheduleScan,
    stop() { controller.abort(); observer?.disconnect(); }
  };

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