/* ==========================================================================
   Salla — استبدال "نفدت الكمية" بـ "يتوفر قريباً"
   يشتغل على بطاقات المنتجات وصفحة المنتج وزرار الإضافة المعطّل.
   ضع الكود في: تصميم المتجر > كود مخصص > JavaScript
   ========================================================================== */
(function () {
  'use strict';

  /* ─────────────────────────  الإعدادات  ───────────────────────── */
  const CONFIG = {
    // النص الجديد
    text: 'يتوفر قريباً',

    // النصوص اللي هتتستبدل (قارن بعد إزالة المسافات الزيادة)
    match: [
      'نفدت الكمية',
      'نفذت الكمية',
      'نفدت الكميه',
      'نفد المخزون',
      'غير متوفر',
      'غير متوفر حالياً',
      'Out of stock',
      'Sold out'
    ],

    // استبدال النص في الـ tooltips و aria-label كمان
    fixAttributes: true,

    // اطبع في الـ Console عدد الاستبدالات (للتشخيص)
    debug: true,

    // --- وضوح الشارة فوق الصورة ---
    restyleBadge: true,
    badgeBg: 'transparent',        // 'transparent' أو لون مصمت زي '#111111'
    badgeColor: '#ffffff',
    badgeBorderColor: '#ffffff',   // '' لو مش عايز بوردر
    badgeSize: 13,                 // حجم الخط
    badgeRadius: 3,
    badgeShadow: true,             // ظل خفيف حوالين الحروف عشان تبان فوق الصور الفاتحة

    // --- وضوح زرار "يتوفر قريباً" المعطّل ---
    restyleButton: true,
    buttonBg: '#f2f2f2',
    buttonColor: '#111111',
    buttonBorderColor: 'rgba(17,17,17,.45)'
  };
  /* ─────────────────────────────────────────────────────────────── */

  const NEW = CONFIG.text;

  function escapeRx(s) {
    return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  // ريجيكس لكل عبارة: يسمح بأي مسافات بين الكلمات + محارف الاتجاه المخفية
  const RX = CONFIG.match.map(function (phrase) {
    const body = phrase.trim().split(/\s+/).map(escapeRx).join('[\\s\\u200f\\u200e]+');
    return new RegExp('[\\u200f\\u200e]*' + body + '[\\u200f\\u200e]*', 'g');
  });

  // يرجّع النص بعد الاستبدال، أو null لو مفيش تطابق
  function replaceIn(str) {
    if (!str) return null;
    let out = str;
    let changed = false;
    for (let i = 0; i < RX.length; i++) {
      RX[i].lastIndex = 0;
      if (RX[i].test(out)) {
        RX[i].lastIndex = 0;
        out = out.replace(RX[i], NEW);
        changed = true;
      }
    }
    return changed ? out : null;
  }

  /* ---------- استبدال النصوص ---------- */

  function replaceTextNodes(root) {
    const walker = document.createTreeWalker(
      root,
      NodeFilter.SHOW_TEXT,
      {
        acceptNode: function (node) {
          const p = node.parentNode;
          if (!p) return NodeFilter.FILTER_REJECT;
          const tag = p.nodeName;
          if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'TEXTAREA' || tag === 'NOSCRIPT') {
            return NodeFilter.FILTER_REJECT;
          }
          const t = node.nodeValue;
          if (!t || t.length > 300 || t.trim().length < 3) return NodeFilter.FILTER_SKIP;
          return NodeFilter.FILTER_ACCEPT;
        }
      }
    );

    const nodes = [];
    let n;
    while ((n = walker.nextNode())) nodes.push(n);

    const parents = [];
    nodes.forEach(function (node) {
      const rep = replaceIn(node.nodeValue);
      if (rep !== null && rep !== node.nodeValue) {
        node.nodeValue = rep;
        if (node.parentElement) parents.push(node.parentElement);
      }
    });

    return parents;
  }

  function replaceAttributes(root) {
    if (!CONFIG.fixAttributes) return;
    const attrs = ['aria-label', 'title', 'data-title', 'alt'];
    const sel = attrs.map(function (a) { return '[' + a + ']'; }).join(',');

    root.querySelectorAll(sel).forEach(function (el) {
      attrs.forEach(function (a) {
        const v = el.getAttribute(a);
        const rep = replaceIn(v);
        if (rep !== null && rep !== v) el.setAttribute(a, rep);
      });
    });
  }

  /* ---------- الستايل ---------- */

  const styleParts = [];

  if (CONFIG.restyleBadge) {
    styleParts.push(`
      .product-card__out-label,
      .product-card .product-card__out-label,
      custom-salla-product-card .product-card__out-label,
      [class*="out-label"]{
        background:${CONFIG.badgeBg}!important;
        color:${CONFIG.badgeColor}!important;
        ${CONFIG.badgeBorderColor
          ? `border:1px solid ${CONFIG.badgeBorderColor}!important;`
          : 'border:0!important;'}
        border-radius:${CONFIG.badgeRadius}px!important;
        padding:6px 12px!important;
        font-size:${CONFIG.badgeSize}px!important;
        font-weight:700!important;
        line-height:1.25!important;
        letter-spacing:.02em!important;
        white-space:nowrap!important;
        opacity:1!important;
        width:auto!important; max-width:none!important;
        ${CONFIG.badgeShadow
          ? `text-shadow:0 1px 4px rgba(0,0,0,.65), 0 0 2px rgba(0,0,0,.5)!important;
             box-shadow:0 1px 6px rgba(0,0,0,.28)!important;`
          : 'text-shadow:none!important; box-shadow:none!important;'}
      }
    `);
  }

  if (CONFIG.restyleButton) {
    styleParts.push(`
      salla-add-product-button button[disabled],
      salla-add-product-button .s-button-element[disabled],
      .s-button-element.s-button-disabled,
      button.s-button-element[disabled]{
        opacity:1!important;
        background:${CONFIG.buttonBg}!important;
        color:${CONFIG.buttonColor}!important;
        border-color:${CONFIG.buttonBorderColor}!important;
        cursor:not-allowed!important;
      }
      salla-add-product-button button[disabled] .s-button-text,
      .s-button-element.s-button-disabled .s-button-text,
      button.s-button-element[disabled] .s-button-text,
      salla-add-product-button button[disabled] i,
      .s-button-element.s-button-disabled i{
        color:${CONFIG.buttonColor}!important;
        opacity:1!important;
        font-weight:600!important;
      }
    `);
  }

  if (styleParts.length) {
    let style = document.getElementById('salla-coming-soon-style');
    if (!style) {
      style = document.createElement('style');
      style.id = 'salla-coming-soon-style';
      (document.head || document.documentElement).appendChild(style);
    }
    style.textContent = styleParts.join('\n');
  }

  /* ---------- تطبيق الستايل مباشرة على العنصر (يغلب أي CSS) ---------- */

  function force(el, props) {
    Object.keys(props).forEach(function (k) {
      el.style.setProperty(k, props[k], 'important');
    });
  }

  function styleBadge(el) {
    if (!CONFIG.restyleBadge || !el || el.dataset.csBadge === '1') return;
    el.dataset.csBadge = '1';

    force(el, {
      'background': CONFIG.badgeBg,
      'background-color': CONFIG.badgeBg,
      'color': CONFIG.badgeColor,
      'border': CONFIG.badgeBorderColor ? '1px solid ' + CONFIG.badgeBorderColor : '0',
      'border-color': CONFIG.badgeBorderColor || 'transparent',
      'border-radius': CONFIG.badgeRadius + 'px',
      'padding': '6px 12px',
      'font-size': CONFIG.badgeSize + 'px',
      'font-weight': '700',
      'line-height': '1.25',
      'opacity': '1',
      'white-space': 'nowrap',
      'width': 'auto',
      'max-width': 'none',
      'text-shadow': CONFIG.badgeShadow
        ? '0 1px 4px rgba(0,0,0,.7), 0 0 2px rgba(0,0,0,.55)'
        : 'none',
      'box-shadow': CONFIG.badgeShadow ? '0 1px 6px rgba(0,0,0,.28)' : 'none'
    });
  }

  function styleDisabledButton(el) {
    if (!CONFIG.restyleButton || !el || el.dataset.csBtn === '1') return;
    el.dataset.csBtn = '1';

    force(el, {
      'opacity': '1',
      'background': CONFIG.buttonBg,
      'background-color': CONFIG.buttonBg,
      'color': CONFIG.buttonColor,
      'border-color': CONFIG.buttonBorderColor,
      'cursor': 'not-allowed'
    });

    el.querySelectorAll('.s-button-text, i, span').forEach(function (c) {
      force(c, { 'color': CONFIG.buttonColor, 'opacity': '1' });
    });
  }

  /* ---------- التشغيل والمراقبة ---------- */

  function run() {
    if (!document.body) return;

    const parents = replaceTextNodes(document.body);
    replaceAttributes(document.body);

    // العنصر اللي فيه النص: لو مش جوه زرار يبقى هو الشارة
    parents.forEach(function (p) {
      if (p.closest('button, salla-add-product-button, .s-button-element, .s-button-wrap')) return;
      styleBadge(p);
    });

    // الشارات اللي ممكن تكون اتحمّلت من غير ما نستبدل نصها
    document
      .querySelectorAll('[class*="out-label"], [class*="out_label"], .out-of-stock-label')
      .forEach(styleBadge);

    // الأزرار المعطّلة
    document
      .querySelectorAll('salla-add-product-button button[disabled], button.s-button-element[disabled], .s-button-element.s-button-disabled')
      .forEach(styleDisabledButton);

    if (CONFIG.debug && parents.length) {
      console.log('[coming-soon] تم استبدال', parents.length, 'نص:', parents.map(function (p) {
        return p.tagName.toLowerCase() + '.' + (p.className || '(بدون كلاس)');
      }));
    }
  }

  let timer = null;
  function schedule() {
    clearTimeout(timer);
    timer = setTimeout(run, 120);
  }

  // المراقبة على إضافة العناصر فقط (مش على تغيير النص) عشان ما يحصلش لوب
  new MutationObserver(schedule).observe(document.documentElement, {
    childList: true,
    subtree: true
  });

  document.addEventListener('DOMContentLoaded', schedule);
  window.addEventListener('load', schedule);
  schedule();

  if (window.salla && salla.event && typeof salla.event.on === 'function') {
    ['theme::ready', 'products::updated', 'product::updated', 'infiniteScroll::loaded', 'filter::applied']
      .forEach(function (ev) { try { salla.event.on(ev, schedule); } catch (e) {} });
  }
})();


#product-944164332 > div.product-card__image > span{
  color: #fff !important;
}