/*
 * Glizer — temporary storefront fix until the next theme update is published.
 * Paste into: Salla dashboard → Store design → the theme → Custom JS. Remove it after the update
 * (the update drops these products from the theme's option data and skips deleted ones).
 *
 * The theme's option data still lists products deleted from the store. The quick view of
 * «بطاقات ايتونز» opens on the first one (سعودي 50 ريال) and gets "not found". This sends a
 * request for a deleted product to the closest one the store has, then selects its card so
 * the highlighted package matches the product shown.
 */
(function () {
  if (window.__glizerHotfix) return;
  window.__glizerHotfix = true;

  // deleted product id → [the product shown instead, its card's amount]
  var REPLACE = {
    1869468748: [1869085451, '150'], // ايتونز سعودي 50 ريال  → 150 ريال
    445531100: [1869085451, '150'], // ايتونز سعودي 75 ريال  → 150 ريال
    2042280341: [1869085451, '150'], // ايتونز سعودي 100 ريال → 150 ريال
    165340196: [1645258458, '160'], // بلايستيشن سعودي 200 دولار → 160 دولار
  };

  function selectCard(amount) {
    var tries = 0;
    var timer = setInterval(function () {
      tries += 1;
      var cards = document.querySelectorAll('.package-purchase__package');
      for (var i = 0; i < cards.length; i += 1) {
        var label = cards[i].querySelector('.package-purchase__package-amount');
        if (label && label.textContent.trim() === amount) {
          if (!cards[i].classList.contains('is-selected')) cards[i].click();
          clearInterval(timer);
          return;
        }
      }
      if (tries > 60) clearInterval(timer);
    }, 150);
  }

  var originalFetch = window.fetch;
  window.fetch = function (input, init) {
    try {
      var url = typeof input === 'string' ? input : input && input.url;
      var match = url && /\/products\/(\d+)\/details/.exec(url);
      var swap = match && REPLACE[match[1]];
      if (swap) {
        var next = url.replace('/products/' + match[1] + '/details', '/products/' + swap[0] + '/details');
        input = typeof input === 'string' ? next : new Request(next, input);
        selectCard(swap[1]);
      }
    } catch (error) {
      /* leave the request as it was */
    }
    return originalFetch.call(this, input, init);
  };
})();

/*
 * Apple Pay in the packages look (quick view and product page), until the theme update that
 * builds it in is published. Salla's own Apple Pay button (salla-quick-buy) is added under the
 * two purchase buttons, only where Salla itself would show it: the store takes Apple Pay through
 * Salla's gateway with buy now on, and this device can pay with it (Safari on an Apple device).
 * It reads the purchase form (the id typed, the server picked); the form's required fields are
 * checked first.
 *
 * Smooth: it goes in with the bar itself (the page is watched, no timer), its place is held at
 * the button's height from the start, the button fades in once Apple has drawn it, and a package
 * switch only changes the product on the same button (nothing is removed or redrawn).
 */
(function () {
  if (window.__glizerApplePay) return;
  window.__glizerApplePay = true;

  function available() {
    try {
      var session = window.ApplePaySession;
      if (!session || !session.canMakePayments || !session.canMakePayments()) return false;
      var config = window.salla && window.salla.config;
      if (!config || !config.get) return false;
      var payments = config.get('store.settings.payments') || [];
      var buyNow = config.get('store.settings.buy_now');
      return (
        payments.indexOf('apple_pay') > -1 &&
        config.get('store.settings.is_salla_gateway', false) === true &&
        !!buyNow &&
        !buyNow.hostedRedirect &&
        !!window.customElements &&
        !!window.customElements.get('salla-quick-buy')
      );
    } catch (error) {
      return false;
    }
  }

  function guard(event) {
    var owner = event.currentTarget.__form;
    if (owner && !owner.checkValidity()) {
      event.preventDefault();
      event.stopPropagation();
      var invalid = owner.querySelector(':invalid');
      if (invalid) {
        invalid.scrollIntoView({ block: 'center', behavior: 'smooth' });
        if (invalid.reportValidity) invalid.reportValidity();
      }
    }
  }

  function sync() {
    var bars = document.querySelectorAll('.package-purchase__bar');
    for (var i = 0; i < bars.length; i += 1) {
      var bar = bars[i];
      var cart = bar.querySelector('button[type="submit"][form]');
      var form = cart && document.getElementById(cart.getAttribute('form'));
      var idInput = form && form.querySelector('input[name="id"]');
      var id = idInput && idInput.value;
      if (!id) continue;
      var wrap = bar.querySelector('.glizer-apple-pay');
      if (!wrap) {
        wrap = document.createElement('div');
        wrap.className = 'glizer-apple-pay';
        // The form's own checks first: an empty id or server stops the payment sheet.
        wrap.addEventListener('click', guard, true);
        var button = document.createElement('salla-quick-buy');
        button.setAttribute('type', 'buy');
        wrap.appendChild(button);
        bar.appendChild(wrap);
      }
      wrap.__form = form;
      var quick = wrap.querySelector('salla-quick-buy');
      var selector = 'form[id="' + form.id + '"]';
      if (quick.getAttribute('data-form-selector') !== selector) quick.setAttribute('data-form-selector', selector);
      if (quick.getAttribute('product-id') !== id) {
        quick.setAttribute('product-id', id);
        price(quick, id);
      }
      // Shown once Apple's button has a size: no half-drawn button, no jump.
      if (!wrap.classList.contains('is-ready')) {
        var drawn = quick.querySelector('apple-pay-button');
        if (drawn && drawn.getBoundingClientRect().height > 0) wrap.classList.add('is-ready');
      }
    }
  }

  // The button reads its price once, when it first draws: after a switch it is given the new
  // product's price (as Salla's button sets it, in the store's base currency), so the payment
  // sheet shows the right amount.
  function price(quick, id) {
    if (!quick.__priced) {
      quick.__priced = id;
      return; // the first product: the button fetches its own price
    }
    quick.__priced = id;
    try {
      window.salla.product.getDetails(id, []).then(function (response) {
        if (quick.getAttribute('product-id') !== id) return; // switched again meanwhile
        var data = (response && response.data) || {};
        var base = data.base_currency_price;
        if (base && base.amount != null) {
          quick.amount = base.amount;
          if (base.currency) quick.currency = base.currency;
        } else if (data.price != null) {
          quick.amount = data.price;
        }
        quick.isRequireShipping = !!data.is_require_shipping;
      });
    } catch (error) {
      /* the button keeps the price it had */
    }
  }

  var queued = false;
  function schedule() {
    if (queued) return;
    queued = true;
    requestAnimationFrame(function () {
      queued = false;
      sync();
    });
  }

  function start() {
    if (!available()) return;
    // The loading bar (before the product arrives) holds the button's place too: the panel
    // does not grow when the real bar takes over.
    document.documentElement.classList.add('glizer-has-apple-pay');
    sync();
    new MutationObserver(schedule).observe(document.body, { childList: true, subtree: true });
    // A package switch changes the form's product id as a value, which the page watch does not
    // see on its own: a light check now and then.
    setInterval(sync, 500);
  }

  if (window.salla && window.salla.onReady) window.salla.onReady(start);
  else window.addEventListener('load', start);
})();