/**
 * صندوق آل جمجوم – تحسين صفحة منتج التبرع (نسخة ٤.٠)
 * ──────────────────────────────────────────────────────
 * المكان: الإعدادات ← تصميم المتجر ← تخصيص JavaScript
 */
(function () {
  'use strict';

  /* ══════════════════ الإعدادات ══════════════════ */
  var CFG = {
    productId : '567148503',
    phone     : '+966500236600',
    amounts   : [50, 100, 250, 500, 1000],
    popular   : 250,

    programs: [
      { icon: '🤝', name: 'التكافل الاجتماعي'  },
      { icon: '🚨', name: 'الإغاثة الطارئة'     },
      { icon: '💍', name: 'دعم الزواج'          },
      { icon: '📖', name: 'الدعم التعليمي'       },
      { icon: '🌱', name: 'التوظيف والريادة'     },
      { icon: '🏡', name: 'أنشطة التواصل الأسري' },
      { icon: '🌿', name: 'المبادرات الخيرية'    },
      { icon: '📸', name: 'التوثيق والإعلام'     }
    ],

    stats: [
      { num: '+٣٠٠', lbl: 'أسرة مستفيدة'     },
      { num: '+٨٠٠', lbl: 'عضو في العائلة'    },
      { num: '١٠٠٪', lbl: 'شفافية ومصداقية'  }
    ],

    trust: [
      'مرخص من وزارة الموارد البشرية والتنمية الاجتماعية',
      'تقارير سنوية شفافة ومدققة للمتبرعين',
      'إيصال إلكتروني رسمي فوري بعد كل تبرع',
      'Apple Pay · مدى · فيزا · مدفوعات آمنة ١٠٠٪'
    ]
  };

  /* ══════════ مساعدات ══════════ */
  function fmt(n) { return Number(n).toLocaleString('ar-SA') + ' ر.س'; }

  function isTargetPage() {
    var h = window.location.href;
    return h.indexOf(CFG.productId) !== -1 ||
           h.indexOf('donate')      !== -1 ||
           h.indexOf('تبرع')        !== -1 ||
           h.indexOf('jamjoom')     !== -1;
  }

  function findInput() {
    var sels = [
      'input[name="donation_amount"]',
      'input[id*="donation"]',
      'input[class*="donation"]',
      'input[placeholder*="مبلغ"]',
      'input[type="number"]'
    ];
    for (var i = 0; i < sels.length; i++) {
      var el = document.querySelector(sels[i]);
      if (el) return el;
    }
    return null;
  }

  var _done = false;
  function isDone() { return _done || !!document.getElementById('jff-ribbon'); }

  /* ══════════════════════════════════════════
     ١. شريط رفيع علوي
  ══════════════════════════════════════════ */
  function buildRibbon() {
    var el = document.createElement('div');
    el.id = 'jff-ribbon';
    el.innerHTML =
      '<span class="jff-rib-brand">🌿 صندوق آل جمجوم الخيري</span>' +
      '<span class="jff-rib-dot">·</span>' +
      '<span class="jff-rib-text">معاً نرعى بعضنا — تبرعك يصنع الفرق في حياة أبناء العائلة</span>';
    return el;
  }

  /* ══════════════════════════════════════════
     ٢. بطاقة اختيار المبلغ
     (تتحكم مباشرةً في حقل سلة بدون نسخ)
  ══════════════════════════════════════════ */
  function buildAmountCard(sallaInput) {
    var card = document.createElement('div');
    card.id = 'jff-amount-card';

    /* العنوان */
    var head = document.createElement('div');
    head.className = 'jff-card-head';
    head.innerHTML =
      '<div class="jff-card-head-icon">💚</div>' +
      '<div>' +
        '<h2>اختر مبلغ تبرعك</h2>' +
        '<p>تبرعك يصل مباشرةً لأبناء عائلة آل جمجوم</p>' +
      '</div>';
    card.appendChild(head);

    /* أزرار المبالغ */
    var grid = document.createElement('div');
    grid.className = 'jff-amounts';
    CFG.amounts.forEach(function(amt) {
      var btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'jff-amt' + (amt === CFG.popular ? ' jff-amt--hot' : '');
      btn.setAttribute('data-amt', String(amt));
      if (amt === CFG.popular) {
        btn.innerHTML = '<span class="jff-hot-badge">الأكثر</span>' + fmt(amt);
      } else {
        btn.innerHTML = fmt(amt);
      }
      btn.addEventListener('click', function () { selectAmount(amt, sallaInput); });
      grid.appendChild(btn);
    });
    card.appendChild(grid);

    return card;
  }

  /* ══════════════════════════════════════════
     ٣. بطاقة الثقة + الإحصائيات + التواصل
  ══════════════════════════════════════════ */
  function buildInfoCard() {
    var card = document.createElement('div');
    card.id = 'jff-info-card';

    /* قسم الثقة */
    var trustHTML = CFG.trust.map(function(t) {
      return '<div class="jff-trust-row">' +
               '<span class="jff-tick">✓</span>' +
               '<span>' + t + '</span>' +
             '</div>';
    }).join('');

    /* الإحصائيات */
    var statsHTML = CFG.stats.map(function(s) {
      return '<div class="jff-stat">' +
               '<strong>' + s.num + '</strong>' +
               '<span>' + s.lbl + '</span>' +
             '</div>';
    }).join('');

    card.innerHTML =
      '<div class="jff-info-trust">' +
        '<div class="jff-info-label">🛡️ لماذا نستحق ثقتك؟</div>' +
        trustHTML +
      '</div>' +
      '<div class="jff-info-stats">' + statsHTML + '</div>' +
      '<div class="jff-info-contact">' +
        '<span>للاستفسار وخدمة المتبرعين</span>' +
        '<a href="tel:' + CFG.phone + '">' + CFG.phone + '</a>' +
      '</div>';

    return card;
  }

  /* ══════════════════════════════════════════
     ٤. برامج الصندوق (chips)
  ══════════════════════════════════════════ */
  function buildPrograms() {
    var sec = document.createElement('div');
    sec.id = 'jff-programs';

    var chips = CFG.programs.map(function(p) {
      return '<span class="jff-chip">' + p.icon + ' ' + p.name + '</span>';
    }).join('');

    sec.innerHTML =
      '<div class="jff-prog-label">💚 برامج صندوق آل جمجوم</div>' +
      '<div class="jff-chips">' + chips + '</div>';

    return sec;
  }

  /* ══════════════════════════════════════════
     تحديد المبلغ وتحديث الحقل الأصلي
  ══════════════════════════════════════════ */
  function selectAmount(amt, input) {
    document.querySelectorAll('.jff-amt').forEach(function(b) {
      b.classList.toggle('jff-amt--active', Number(b.getAttribute('data-amt')) === amt);
    });
    if (input) {
      var np = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value');
      if (np && np.set) np.set.call(input, amt);
      input.value = amt;
      ['input', 'change', 'keyup'].forEach(function(ev) {
        input.dispatchEvent(new Event(ev, { bubbles: true }));
      });
    }
  }

  /* ══════════════════════════════════════════
     إخفاء عنصر السعر الأصلي من سلة (JS fallback)
     يعمل بعد CSS في حالة Shadow DOM أو تأخر التحميل
  ══════════════════════════════════════════ */
  function hidePriceElements() {
    var priceSelectors = [
      'p.font-bold.text-xl.inline-block',   /* ← الـ class الفعلي المكتشف */
      'p.font-bold.text-xl',
      '.font-bold.text-xl.inline-block',
      '[class*="product-price"]',
      '[class*="s-product-price"]',
      '[class*="ProductPrice"]',
      '[class*="price-value"]',
      '[class*="price-wrap"]',
      'salla-price',
      'salla-product-price',
      'salla-money',
      '.s-price',
      '.s-product-price',
      '.product-price'
    ];
    priceSelectors.forEach(function(sel) {
      try {
        document.querySelectorAll(sel).forEach(function(el) {
          /* تبديل النص بـ "الحد الأدنى: ٥٠ ر.س" بدلاً من الإخفاء الكامل */
          if (el.tagName === 'INPUT' || el.tagName === 'BUTTON') return;
          el.style.setProperty('display', 'none', 'important');
        });
      } catch(e) {}
    });
    /* تكرار متعدد المراحل لضمان الإخفاء بعد تحميل Web Components */
    [800, 1500, 3000].forEach(function(delay) {
      setTimeout(function() {
        priceSelectors.forEach(function(sel) {
          try {
            document.querySelectorAll(sel).forEach(function(el) {
              if (el.tagName === 'INPUT' || el.tagName === 'BUTTON') return;
              el.style.setProperty('display', 'none', 'important');
            });
          } catch(e) {}
        });
        /* استهداف salla-money بشكل خاص */
        try {
          document.querySelectorAll('salla-money, salla-price, salla-product-price').forEach(function(el) {
            el.style.setProperty('display', 'none', 'important');
          });
        } catch(e) {}
        /* debug: اطبع عناصر السعر في الكونسول لمعرفة الـ class */
        if (delay === 1500) {
          var found = document.querySelectorAll('[class*="price"]:not(input):not(button):not(label)');
          if (found.length) {
            console.log('[JFF] عناصر السعر الموجودة:', Array.from(found).map(function(e){
              return e.tagName + '.' + (e.className||'') + ' → ' + e.textContent.trim().substring(0,20);
            }));
          }
        }
      }, delay);
    });
  }

  /* ══════════════════════════════════════════
     التجميع الرئيسي
  ══════════════════════════════════════════ */
  function enhance() {
    if (!isTargetPage() || isDone()) return;

    var sallaInput = findInput();
    if (!sallaInput) { setTimeout(enhance, 600); return; }
    _done = true;

    /* حاوية سلة الأصلية */
    var sallaWrap = sallaInput.closest('form')              ||
                    sallaInput.closest('[class*="product"]') ||
                    sallaInput.closest('main')               ||
                    document.body;
    sallaWrap.id = 'jff-salla-orig';

    /* ─ تمييز الصفحة لتقييد CSS عليها فقط ─ */
    document.body.classList.add('jff-product-page');

    var pageTop = document.querySelector('main')              ||
                  document.querySelector('[class*="content"]') ||
                  document.body;

    /* ─ ١. شريط رفيع ─ */
    pageTop.insertBefore(buildRibbon(), pageTop.firstChild);

    /* ─ ٢. بطاقة المبالغ قبل سلة ─ */
    var amountCard = buildAmountCard(sallaInput);
    sallaWrap.parentNode.insertBefore(amountCard, sallaWrap);

    /* ─ ٣. بطاقة الثقة بعد سلة ─ */
    var infoCard = buildInfoCard();
    if (sallaWrap.nextSibling) {
      sallaWrap.parentNode.insertBefore(infoCard, sallaWrap.nextSibling);
    } else {
      sallaWrap.parentNode.appendChild(infoCard);
    }

    /* ─ ٤. برامج الصندوق ─ */
    var programs = buildPrograms();
    if (infoCard.nextSibling) {
      infoCard.parentNode.insertBefore(programs, infoCard.nextSibling);
    } else {
      infoCard.parentNode.appendChild(programs);
    }

    /* ─ ٥. إخفاء سعر المنتج الأصلي (fallback JS) ─ */
    hidePriceElements();

    /* ─ ٦. تهيئة المبلغ الافتراضي ─ */
    var urlAmt = new URLSearchParams(window.location.search).get('amount');
    selectAmount(urlAmt ? Number(urlAmt) : CFG.popular, sallaInput);

    /* ─ ٦. مزامنة الكتابة اليدوية ─ */
    sallaInput.addEventListener('input', function () {
      var v = Number(this.value);
      document.querySelectorAll('.jff-amt').forEach(function(b) {
        b.classList.toggle('jff-amt--active', Number(b.getAttribute('data-amt')) === v);
      });
    });

    console.log('[JFF] ✅ v4 جاهز');
  }

  /* ══════════════════ الإطلاق ══════════════════ */
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', enhance);
  } else { enhance(); }
  window.addEventListener('load', function () { setTimeout(enhance, 400); });
  setTimeout(enhance, 900);
  setTimeout(enhance, 2200);

})();