// source --> https://mfrash.com/wp-content/plugins/woo-ajax-cart/assets/woo-ajax-cart.js?ver=1778869174 
/* global wacData */
(function () {
    'use strict';

    // ─── أيقونات SVG داخلية ───
    var ICONS = {
        check:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>',
        checkCircle: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2 4-4"/></svg>',
        error:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>',
        cart:     '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1.5"/><circle cx="18" cy="21" r="1.5"/><path d="M2.5 3h2.4l2.5 12.5a2 2 0 0 0 2 1.6h8.4a2 2 0 0 0 2-1.5L21 8H6"/></svg>',
        truck:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 7h11v9H2z"/><path d="M13 10h5l3 3v3h-8z"/><circle cx="6" cy="18.5" r="1.7"/><circle cx="17" cy="18.5" r="1.7"/></svg>',
        truckFast:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h10v8H3z"/><path d="M13 11h5l3 3v2h-8z"/><circle cx="7" cy="18" r="1.6"/><circle cx="17" cy="18" r="1.6"/><path d="M1 11h3M1 14h2"/></svg>',
        arrow:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5"/><path d="M12 5l-7 7 7 7"/></svg>',
        chevron:  '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>',
        close:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>',
        ticket:   '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 9.5V7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v2.5a2.5 2.5 0 0 0 0 5V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-2.5a2.5 2.5 0 0 0 0-5z"/><path d="M9 5v14"/></svg>',
        copy:     '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',
        check2:   '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>',
        shield:   '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"/><path d="M9 12l2 2 4-4"/></svg>',
        medal:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="14" r="6"/><path d="M9 11.5L7 3h10l-2 8.5"/><path d="M12 11v6"/><path d="M9.5 14h5"/></svg>',
        flame:    '<svg viewBox="0 0 24 24" fill="#fff" stroke="#fff" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2c1 3 4 5 4 9a4 4 0 1 1-8 0c0-1.5.5-2.5 1.5-3.5C10 9 11 6.5 12 2z"/></svg>',
        headset:  '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 14v-2a9 9 0 0 1 18 0v2"/><path d="M3 14a2 2 0 0 1 2-2h2v6H5a2 2 0 0 1-2-2v-2z"/><path d="M21 14a2 2 0 0 0-2-2h-2v6h2a2 2 0 0 0 2-2v-2z"/><path d="M17 18v1a3 3 0 0 1-3 3h-2"/></svg>',
        lock:     '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>',
        savings:  '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-1"/><path d="M16 12h5v4h-5a2 2 0 0 1 0-4z"/></svg>',
        users:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>'
    };

    // عداد عملاء عشوائي ثابت لكل زيارة (8 → 29)
    var SOCIAL_COUNT = (function () {
        try {
            var k = 'wac_social_count';
            var v = sessionStorage.getItem(k);
            if (v) return parseInt(v, 10);
            v = 8 + Math.floor(Math.random() * 22);
            sessionStorage.setItem(k, v);
            return v;
        } catch (e) {
            return 12 + Math.floor(Math.random() * 15);
        }
    })();

    // عدد القطع المتبقية في المخزون (3 → 7)
    var STOCK_LEFT = (function () {
        try {
            var k = 'wac_stock_left';
            var v = sessionStorage.getItem(k);
            if (v) return parseInt(v, 10);
            v = 3 + Math.floor(Math.random() * 5);
            sessionStorage.setItem(k, v);
            return v;
        } catch (e) {
            return 3 + Math.floor(Math.random() * 5);
        }
    })();

    // ─── مساعدات DOM ───
    function el(tag, attrs, html) {
        var n = document.createElement(tag);
        if (attrs) for (var k in attrs) {
            if (k === 'class') n.className = attrs[k];
            else if (k === 'style') n.style.cssText = attrs[k];
            else n.setAttribute(k, attrs[k]);
        }
        if (html != null) n.innerHTML = html;
        return n;
    }
    function on(node, ev, fn) { node.addEventListener(ev, fn); }
    function $find(root, sel) { return (root || document).querySelector(sel); }
    function $all(root, sel) { return (root || document).querySelectorAll(sel); }
    function hasClass(n, c) { return n && n.classList && n.classList.contains(c); }
    function escAttr(s) { return String(s == null ? '' : s).replace(/"/g, '&quot;'); }

    var WAC = {
        toast: null,
        overlay: null,
        timer: null,
        _ownAdd: false,
        _lastSubtotal: null,
        _noncePromise: null,

        refreshNonce: function () {
            // يُعيد Promise محفوظ — ينتهي بمجرد الحصول على nonce جديد أو الفشل الصامت.
            // يضمن أن طلبات الإضافة لا تُرسَل بـ nonce قديم من الكاش.
            if (WAC._noncePromise) return WAC._noncePromise;
            WAC._noncePromise = new Promise(function (resolve) {
                var body = new FormData();
                body.append('action', 'wac_get_nonce');
                fetch(wacData.ajaxUrl + '?_=' + Date.now(), { method: 'POST', body: body, credentials: 'same-origin' })
                    .then(function (r) { return r.json(); })
                    .then(function (res) {
                        if (res && res.success && res.data && res.data.nonce) {
                            wacData.nonce = res.data.nonce;
                        }
                        resolve();
                    })
                    .catch(function () { resolve(); });
            });
            return WAC._noncePromise;
        },

        init: function () {
            WAC.overlay = el('div', { class: 'wac-overlay' });
            WAC.toast   = el('div', { class: 'wac-toast', role: 'alert', 'aria-live': 'polite' });
            document.body.appendChild(WAC.overlay);
            document.body.appendChild(WAC.toast);

            WAC.refreshNonce();   // تحديث الـ nonce فوراً لتجاوز الكاش

            on(WAC.overlay, 'click', WAC.hide);

            if (document.body.classList.contains('single-product')) {
                document.addEventListener('submit', function (e) {
                    var f = e.target;
                    if (f && f.tagName === 'FORM' && hasClass(f, 'cart')) WAC.onSubmit(e, f);
                }, true);
            }

            if (window.jQuery) {
                window.jQuery(document.body).on('added_to_cart', function (e, fragments, cart_hash, $btn) {
                    WAC.onNativeAdded($btn && $btn.length ? $btn[0] : null);
                });
            }
        },

        onSubmit: function (e, form) {
            if (!form.querySelector('[name="add-to-cart"]') &&
                !form.querySelector('[name="product_id"]')) return;

            e.preventDefault();
            e.stopImmediatePropagation();

            var btn        = form.querySelector('[type="submit"]:not([name="update_cart"])');
            var productId  = parseInt((form.querySelector('[name="product_id"]') || form.querySelector('[name="add-to-cart"]') || {}).value || 0, 10);
            var variation  = form.querySelector('[name="variation_id"]');
            var variationId = parseInt((variation || {}).value || 0, 10);
            var qty = parseFloat((form.querySelector('[name="quantity"]') || {}).value || 1);

            if (form.classList.contains('variations_form')) {
                if (!variationId || variationId < 1) {
                    WAC.show(WAC.errorHtml(wacData.selectVar), 'error');
                    return;
                }
            }

            var attrs = {};
            $all(form, '[name^="attribute_"]').forEach(function (n) { attrs[n.name] = n.value; });

            var originalHtml = btn ? btn.innerHTML : '';
            if (btn) {
                btn.disabled = true;
                btn.classList.add('wac-btn-loading');
                btn.textContent = wacData.addingText;
            }

            var data = {
                action: 'woo_ajax_add_to_cart',
                nonce: wacData.nonce,
                product_id: productId,
                variation_id: variationId,
                quantity: qty
            };
            for (var k in attrs) data[k] = attrs[k];

            // ننتظر تحديث الـ nonce قبل الإرسال لتجنب nonce قديم من الكاش
            WAC.refreshNonce().then(function () {
                data.nonce = wacData.nonce;
                WAC.request(data, btn, originalHtml, 0);
            });
        },

        request: function (data, btn, originalHtml, attempt) {
            var body = new URLSearchParams();
            for (var k in data) body.append(k, data[k]);

            fetch(wacData.ajaxUrl + '?_=' + Date.now(), {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: body.toString()
            })
            .then(function (r) {
                if (!r.ok) throw new Error('http_' + r.status);
                return r.json();
            })
            .then(function (res) {
                if (!res.success && res.data && res.data.code === 'nonce_expired' && res.data.new_nonce && attempt === 0) {
                    wacData.nonce = res.data.new_nonce;
                    data.nonce = res.data.new_nonce;
                    WAC.request(data, btn, originalHtml, 1);
                    return;
                }
                if (btn) {
                    btn.disabled = false;
                    btn.classList.remove('wac-btn-loading');
                    btn.innerHTML = originalHtml;
                }
                if (res.success) {
                    WAC._ownAdd = true;
                    if (window.jQuery && typeof window.wc_cart_fragments_params !== 'undefined') {
                        window.jQuery(document.body).trigger('wc_fragment_refresh');
                        window.jQuery(document.body).trigger('added_to_cart', [{}, {}, btn ? window.jQuery(btn) : window.jQuery()]);
                    }
                    WAC._ownAdd = false;

                    if (res.data && typeof res.data.cart_subtotal !== 'undefined') {
                        WAC._lastSubtotal = parseFloat(res.data.cart_subtotal);
                    }
                    WAC.show(WAC.successHtml(res.data || {}), 'success');
                } else {
                    var msg = (res.data && res.data.message) ? res.data.message : wacData.errorText;
                    WAC.show(WAC.errorHtml(msg), 'error');
                }
            })
            .catch(function () {
                if (btn) {
                    btn.disabled = false;
                    btn.classList.remove('wac-btn-loading');
                    btn.innerHTML = originalHtml;
                }
                WAC.show(WAC.errorHtml(wacData.errorText), 'error');
            });
        },

        onNativeAdded: function (btn) {
            if (WAC._ownAdd) return;
            if (document.body.classList.contains('single-product')) return;

            var name = '', img = '';
            if (btn) {
                var product = btn.closest('li.product, .product');
                if (product) {
                    var t = product.querySelector('.woocommerce-loop-product__title, h2, h3');
                    if (t) name = t.textContent.trim();
                    var i = product.querySelector('img.wp-post-image, img');
                    if (i) img = i.getAttribute('src') || '';
                }
            }
            WAC.show(WAC.successHtml({ product_name: name, product_image: img }), 'success');

            var body = new URLSearchParams();
            body.append('action', 'wac_get_cart_totals');
            fetch(wacData.ajaxUrl + '?_=' + Date.now(), {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: body.toString()
            })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                if (res && res.success && res.data) {
                    WAC._lastSubtotal = parseFloat(res.data.cart_subtotal);
                    WAC.updateShipBar(res.data.cart_subtotal);
                }
            })
            .catch(function(){});
        },

        formatAmount: function (amount) {
            var n = parseFloat(amount) || 0;
            var f = (Math.round(n * 100) / 100).toLocaleString('ar', {
                minimumFractionDigits: 0, maximumFractionDigits: 2
            });
            return f + ' ' + (wacData.currencySymbol || '');
        },

        // ─── شريط الشحن المجاني ───
        shipBarHtml: function (subtotal) {
            if (!parseInt(wacData.enableShipBar)) return '';
            var threshold = parseFloat(wacData.freeShipThreshold) || 0;
            if (threshold <= 0) return '';
            var sub = parseFloat(subtotal);
            if (isNaN(sub) || sub < 0) sub = 0;
            var pct = Math.min(100, Math.round((sub / threshold) * 100));
            var unlocked = sub >= threshold;
            var msg, savings;
            if (unlocked) {
                msg = wacData.freeShipUnlockedText;
                // التوفير = قيمة الشحن المُوفّرة (مثلاً 20)
                var savedAmt = parseFloat(wacData.shippingCost) || 20;
                savings = '<span class="wac-ship-savings">' +
                              '<span>' + ICONS.savings + '</span>' +
                              '<span>وفّرتي ' + WAC.formatAmount(savedAmt) + '</span>' +
                          '</span>';
            } else {
                var remaining = Math.max(0, threshold - sub);
                var tpl = wacData.freeShipRemainingTpl || 'أضف %s للحصول على الشحن المجاني';
                msg = tpl.replace('%s', '<strong>' + WAC.formatAmount(remaining) + '</strong>');
                savings = '';
            }
            return '<div class="wac-ship-bar">' +
                       '<div class="wac-ship-bar-row">' +
                           '<span class="wac-ship-icon">' + ICONS.truckFast + '</span>' +
                           '<span class="wac-ship-bar-msg"><span class="wac-ship-bar-text">' + msg + '</span></span>' +
                           savings +
                       '</div>' +
                       '<div class="wac-ship-bar-track">' +
                           '<div class="wac-ship-bar-fill" style="width:' + pct + '%"></div>' +
                       '</div>' +
                   '</div>';
        },

        updateShipBar: function (subtotal) {
            if (!WAC.toast || !WAC.toast.classList.contains('wac-toast--show')) return;
            var bar = $find(WAC.toast, '.wac-ship-bar');
            var html = WAC.shipBarHtml(subtotal);
            if (!html) return;
            if (!bar) {
                var top = $find(WAC.toast, '.wac-toast-top');
                if (top) top.insertAdjacentHTML('afterend', html);
                return;
            }
            bar.outerHTML = html;
            var fill = $find(WAC.toast, '.wac-ship-bar-fill');
            if (fill) {
                var w = fill.style.width;
                fill.style.width = '0%';
                setTimeout(function () { fill.style.width = w; }, 30);
            }
        },

        // ─── الكوبون (مع دائرة النسبة) ───
        couponHtml: function (subtotal) {
            if (!parseInt(wacData.enableCoupon)) return '';
            var code = (wacData.couponCode || '').trim();
            if (!code) return '';
            var min = parseFloat(wacData.couponMin) || 0;
            var sub = parseFloat(subtotal);
            if (min > 0 && (isNaN(sub) || sub < min)) return '';

            var label    = wacData.couponLabel || 'كوبون خصم حصري لك';
            var desc     = wacData.couponDesc  || '';
            var copyTxt  = wacData.couponCopyText || 'نسخ الكود';
            var note     = wacData.couponNote || 'استخدمي الكود في صفحة الدفع';
            var pct      = parseInt(wacData.couponPercent || 0, 10);

            var circle = pct > 0 ? '<div class="wac-coupon-circle">' +
                                       '<span class="wac-coupon-circle-pct">' + pct + '%</span>' +
                                       '<span class="wac-coupon-circle-label">وفري أكثر</span>' +
                                   '</div>' : '';

            return '<div class="wac-coupon">' +
                       '<div class="wac-coupon-head">' +
                           '<span class="wac-coupon-icon-tag">' + ICONS.ticket + '</span>' +
                           '<span class="wac-coupon-label">' + label + '</span>' +
                       '</div>' +
                       '<div class="wac-coupon-row">' +
                           '<button type="button" class="wac-coupon-copy" data-wac-coupon-copy="1">' +
                               '<span class="wac-coupon-copy-icon">' + ICONS.copy + '</span>' +
                               '<span class="wac-coupon-copy-text">' + copyTxt + '</span>' +
                           '</button>' +
                           '<div class="wac-coupon-main">' +
                               '<div class="wac-coupon-code" data-wac-coupon-code="' + escAttr(code) + '">' +
                                   '<span class="wac-coupon-code-text">' + code + '</span>' +
                                   (desc ? '<span class="wac-coupon-code-desc">' + desc + '</span>' : '') +
                               '</div>' +
                           '</div>' +
                           circle +
                       '</div>' +
                       (note ? '<div class="wac-coupon-note">' + note + '</div>' : '') +
                   '</div>';
        },

        // ─── شارات الثقة (4 عناصر) ───
        trustBadgesHtml: function () {
            if (!parseInt(wacData.enableTrustBadges)) return '';
            var b1 = (wacData.trustBadge1 || '').trim() || 'توصيل سريع لجميع المناطق';
            var b2 = (wacData.trustBadge2 || '').trim() || 'منتجات أصلية 100%';
            var b3 = (wacData.trustBadge3 || '').trim() || 'دفع آمن 100%';
            var b4 = (wacData.trustBadge4 || '').trim() || 'خدمة عملاء 24/7';

            var item = function (icon, text) {
                return '<div class="wac-trust-item">' +
                           '<span class="wac-trust-icon">' + icon + '</span>' +
                           '<span class="wac-trust-text">' + text + '</span>' +
                       '</div>';
            };
            return '<div class="wac-trust-badges">' +
                       item(ICONS.truckFast, b1) +
                       item(ICONS.medal, b2) +
                       item(ICONS.shield, b3) +
                       item(ICONS.headset, b4) +
                   '</div>';
        },

        // ─── إثبات اجتماعي + المخزون المتبقي ───
        socialAndStockHtml: function () {
            var avatarColors = ['#fb7185', '#60a5fa', '#fbbf24', '#34d399'];
            var avatars = '';
            for (var i = 0; i < 3; i++) {
                avatars += '<span style="background:' + avatarColors[i] + '"></span>';
            }
            return '<div class="wac-social-row">' +
                       '<div class="wac-social-proof">' +
                           '<span class="wac-social-avatars">' + avatars + '</span>' +
                           '<span class="wac-social-text"><strong>' + SOCIAL_COUNT + '</strong> عميل اشتروا هذا المنتج اليوم</span>' +
                       '</div>' +
                       '<span class="wac-low-stock">' +
                           '<span class="wac-low-stock-icon">' + ICONS.flame + '</span>' +
                           '<span>يتبقى ' + STOCK_LEFT + ' قطع فقط في المخزون</span>' +
                       '</span>' +
                   '</div>';
        },

        // ─── المنتجات المقترحة ───
        crossSellsHtml: function (items) {
            if (!items || !items.length) return '';
            var title = wacData.crossSellsTitle || 'عملاؤنا أحبوا هذه المنتجات';
            var subtitle = wacData.crossSellsSubtitle || 'اختاري ما يناسب ذوقك وكملي تجربة راحتك';
            var addText = wacData.crossSellsAddText || 'أضف للسلة';
            var selText = wacData.crossSellsSelectText || 'اختر الخيارات';
            var bestseller = wacData.crossSellsBestseller || 'الأكثر مبيعاً';

            var rows = '';
            for (var i = 0; i < items.length; i++) {
                var it = items[i];
                var btn;
                if (it.is_simple) {
                    btn = '<button type="button" class="wac-cs-btn wac-cs-btn--add" data-wac-cs-add="' + it.id + '">' +
                              '<span class="wac-toast-icon">' + ICONS.cart + '</span> ' + addText +
                          '</button>';
                } else {
                    btn = '<a href="' + it.permalink + '" class="wac-cs-btn wac-cs-btn--select">' +
                              '<span class="wac-toast-icon">' + ICONS.arrow + '</span> ' + selText +
                          '</a>';
                }
                var badge = (i === 0) ? '<span class="wac-cs-bestseller">' + bestseller + '</span>' : '';
                rows +=
                    '<div class="wac-cs-item">' + badge +
                        '<a href="' + it.permalink + '" class="wac-cs-img-wrap-link">' +
                            '<img src="' + it.image + '" class="wac-cs-img" alt="" loading="lazy">' +
                        '</a>' +
                        '<div class="wac-cs-info">' +
                            '<a href="' + it.permalink + '" class="wac-cs-name">' + it.name + '</a>' +
                            '<span class="wac-cs-price">' + (it.price || '') + '</span>' +
                        '</div>' +
                        btn +
                    '</div>';
            }
            var arrow = (items.length > 2) ? '<span class="wac-cs-arrow">' + ICONS.chevron + '</span>' : '';
            return '<div class="wac-cross-sells">' +
                       '<div class="wac-cs-title">' +
                           '<span class="wac-cs-title-emoji">😍</span>' +
                           '<span>' + title + '</span>' +
                       '</div>' +
                       '<div class="wac-cs-subtitle">' + subtitle + '</div>' +
                       '<div class="wac-cs-scroll">' +
                           '<div class="wac-cs-list">' + rows + '</div>' +
                           arrow +
                       '</div>' +
                   '</div>';
        },

        addCrossSell: function (productId, btn) {
            var originalHtml = btn ? btn.innerHTML : '';
            if (btn) {
                btn.disabled = true;
                btn.classList.add('wac-cs-btn--loading');
                btn.textContent = wacData.addingText;
            }
            var data = {
                action: 'woo_ajax_add_to_cart',
                nonce: wacData.nonce,
                product_id: productId,
                variation_id: 0,
                quantity: 1
            };
            WAC.request(data, btn, originalHtml, 0);
        },

        copyCoupon: function (btn) {
            var codeEl = $find(WAC.toast, '.wac-coupon-code');
            if (!codeEl) return;
            var code = codeEl.getAttribute('data-wac-coupon-code') || codeEl.textContent;
            var done = function () {
                btn.classList.add('wac-coupon-copy--done');
                var icon = $find(btn, '.wac-coupon-copy-icon');
                var text = $find(btn, '.wac-coupon-copy-text');
                if (icon) icon.innerHTML = ICONS.check2;
                if (text) {
                    var copiedText = (wacData.couponCopiedText || 'تم النسخ').replace(/[✓✔√]/g, '').trim();
                    text.textContent = copiedText;
                }
            };
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(code).then(done).catch(function () {
                    WAC.fallbackCopy(code); done();
                });
            } else {
                WAC.fallbackCopy(code); done();
            }
        },

        fallbackCopy: function (text) {
            var ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed'; ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            try { document.execCommand('copy'); } catch (e) {}
            document.body.removeChild(ta);
        },

        // ─── قالب نجاح كامل (مرتب حسب التصميم المرجعي) ───
        successHtml: function (d) {
            var name = d.product_name || '';
            var img  = d.product_image || '';
            var imgWrap = img
                ? '<div class="wac-toast-img-wrap">' +
                      '<img src="' + img + '" class="wac-toast-img" alt="">' +
                      '<span class="wac-toast-badge">' + ICONS.check + '</span>' +
                  '</div>'
                : '<div class="wac-toast-img-wrap wac-toast-img-wrap--icon">' +
                      '<span class="wac-toast-icon-only">' + ICONS.check + '</span>' +
                  '</div>';

            var sub = (typeof d.cart_subtotal !== 'undefined') ? d.cart_subtotal : WAC._lastSubtotal;
            var cartCount = (typeof d.cart_count !== 'undefined' && d.cart_count !== null) ? parseInt(d.cart_count, 10) : 0;
            var ship   = (sub !== null && typeof sub !== 'undefined') ? WAC.shipBarHtml(sub) : '';
            var cross  = WAC.crossSellsHtml(d.cross_sells || []);
            var coupon = WAC.couponHtml(sub);
            var trust  = WAC.trustBadgesHtml();
            var social = (d.cross_sells && d.cross_sells.length) ? WAC.socialAndStockHtml() : '';

            var cartLabel    = (wacData.cartText || 'عرض السلة') + (cartCount > 0 ? ' (' + cartCount + ')' : '');
            var continueText = wacData.continueText || 'متابعة التسوق';
            var checkoutText = wacData.checkoutText || 'إتمام الطلب';
            if (checkoutText.indexOf('الآن') === -1) checkoutText = checkoutText + ' الآن';
            var tagline      = wacData.checkoutTagline || 'خطوة واحدة تفصلك عن الراحة والجمال';

            var checkoutBlock =
                '<div class="wac-toast-checkout-wrap">' +
                    '<a href="' + wacData.checkoutUrl + '" class="wac-toast-btn wac-toast-btn--checkout wac-toast-btn--main">' +
                        '<span class="wac-toast-icon">' + ICONS.lock + '</span> ' + checkoutText +
                    '</a>' +
                    '<div class="wac-checkout-tagline">' +
                        '<span class="wac-checkout-tagline-icon">' + ICONS.checkCircle + '</span>' +
                        '<span>' + tagline + '</span>' +
                    '</div>' +
                '</div>';

            var actions =
                '<div class="wac-toast-actions">' +
                    '<a href="' + wacData.cartUrl + '" class="wac-toast-btn wac-toast-btn--cart">' +
                        '<span class="wac-toast-icon">' + ICONS.cart + '</span> ' + cartLabel +
                    '</a>' +
                    '<button type="button" class="wac-toast-btn wac-toast-btn--continue" data-wac-continue="1">' +
                        continueText + ' <span class="wac-toast-icon">' + ICONS.arrow + '</span>' +
                    '</button>' +
                '</div>';

            return '<div class="wac-toast-progress"></div>' +
                '<button type="button" class="wac-toast-close" data-wac-close="1" aria-label="إغلاق">' + ICONS.close + '</button>' +
                '<div class="wac-toast-inner">' +
                    '<div class="wac-toast-top">' +
                        imgWrap +
                        '<div class="wac-toast-msg">' +
                            '<span class="wac-toast-label"><span class="wac-toast-label-icon">' + ICONS.check + '</span>' + (wacData.successText || '') + '</span>' +
                            (name ? '<span class="wac-toast-name">' + name + '</span>' : '') +
                        '</div>' +
                    '</div>' +
                    ship +
                    coupon +
                    cross +
                    trust +
                    social +
                    checkoutBlock +
                    actions +
                '</div>';
        },

        errorHtml: function (msg) {
            return '<div class="wac-toast-progress"></div>' +
                '<button type="button" class="wac-toast-close" data-wac-close="1" aria-label="إغلاق">' + ICONS.close + '</button>' +
                '<div class="wac-toast-inner">' +
                    '<div class="wac-toast-top">' +
                        '<div class="wac-toast-msg">' +
                            '<span class="wac-toast-label wac-toast-label--error"><span class="wac-toast-label-icon">' + ICONS.error + '</span>' + (msg || wacData.errorText) + '</span>' +
                        '</div>' +
                    '</div>' +
                '</div>';
        },

        hide: function () {
            clearTimeout(WAC.timer);
            WAC.toast.classList.remove('wac-toast--show');
            WAC.overlay.classList.remove('wac-overlay--show');
        },

        show: function (html, type) {
            clearTimeout(WAC.timer);
            WAC.toast.innerHTML = html;
            WAC.toast.classList.remove('wac-toast--success', 'wac-toast--error');
            WAC.toast.classList.add(type === 'error' ? 'wac-toast--error' : 'wac-toast--success');
            void WAC.toast.offsetHeight;
            WAC.toast.classList.add('wac-toast--show');
            WAC.overlay.classList.add('wac-overlay--show');

            var closeBtns = $all(WAC.toast, '[data-wac-close="1"], [data-wac-continue="1"]');
            closeBtns.forEach(function (b) {
                on(b, 'click', function (e) {
                    if (b.dataset.wacContinue === '1' && wacData.continueUrl) {
                        window.location.href = wacData.continueUrl;
                        return;
                    }
                    e.preventDefault();
                    WAC.hide();
                });
            });

            $all(WAC.toast, '[data-wac-cs-add]').forEach(function (b) {
                on(b, 'click', function (e) {
                    e.preventDefault();
                    var pid = parseInt(b.getAttribute('data-wac-cs-add'), 10);
                    if (pid) WAC.addCrossSell(pid, b);
                });
            });

            $all(WAC.toast, '[data-wac-coupon-copy="1"]').forEach(function (b) {
                on(b, 'click', function (e) {
                    e.preventDefault();
                    WAC.copyCoupon(b);
                });
            });
            $all(WAC.toast, '.wac-coupon-code').forEach(function (c) {
                on(c, 'click', function (e) {
                    e.preventDefault();
                    var btn = $find(WAC.toast, '[data-wac-coupon-copy="1"]');
                    if (btn) WAC.copyCoupon(btn);
                });
            });

            // أنيميشن تعبئة شريط الشحن
            var fill = $find(WAC.toast, '.wac-ship-bar-fill');
            if (fill) {
                var w = fill.style.width;
                fill.style.width = '0%';
                setTimeout(function () { fill.style.width = w; }, 50);
            }

            // العد التنازلي + الإغلاق التلقائي (لو displayMs > 0)
            var displayMs = parseInt(wacData.displayMs);
            if (isNaN(displayMs)) displayMs = 0;
            if (type === 'error') displayMs = 3500;
            if (displayMs > 0) {
                var bar = $find(WAC.toast, '.wac-toast-progress');
                if (bar) {
                    bar.style.setProperty('--wac-countdown', (displayMs / 1000) + 's');
                    // إعادة تشغيل الأنيميشن
                    bar.classList.remove('wac-toast-progress--active');
                    void bar.offsetWidth;
                    bar.classList.add('wac-toast-progress--active');
                }
                WAC.timer = setTimeout(WAC.hide, displayMs);
            }
        }
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', WAC.init);
    } else {
        WAC.init();
    }
})();
// source --> https://mfrash.com/wp-content/plugins/woo-discount-rules/v2/Assets/Js/site_main.js?ver=2.6.15 
(function ($) {
    /**
     * refresh cart when payment method changed
     */
    if (awdr_params.refresh_order_review == '1') {
        $(document).on('change', 'input[name="payment_method"],input[name="billing_city"],input[name="billing_postcode"]', function () {
            refreshCart();
        });

        /**
         * refresh cart when Email changed
         */
        $(document).on('blur', 'input[name="billing_email"], select#billing_state', function () {
            refreshCart();
        });
    }

    function refreshCart() {
        $('body').trigger('update_checkout');
    }

    $(document).ready(function ($) {
        function init_events() {
            if (awdr_params.enable_update_price_with_qty == 'show_dynamically') {
                function getWDRDPTarget(form, target, is_variable){
                    let $price_place = '';
                    if (form.find(target).length) {
                        $price_place = form.find(target).first();
                        if(is_variable === true){
                            if (!form.find(target+' .price').length) {
                                $price_place.html("<div class='price'></div>");
                            }
                            $price_place = form.find(target+' .price').first();
                        }
                    } else {
                        $price_place = $(target).first();
                        if(is_variable === true){
                            if (!$(target+' .price').length) {
                                $price_place.html("<div class='price'></div>");
                            }
                            $price_place = $(target+' .price').first();
                        }
                    }
                    return $price_place;
                }
                $(document).on('change', '[name="quantity"]', function (){
                    var awdr_qty_object = $(this);
                    setTimeout(function(){
                        var $qty = awdr_qty_object.val();
                        var $product_id = 0;
                        var $price_place = "";
                        var form = awdr_qty_object.closest("form");
                        if (form.find('button[name="add-to-cart"]').length) {
                            $product_id = form.find('button[name="add-to-cart"]').first().val();
                            var target = 'div.product p.price';
                            if(awdr_params.custom_target_simple_product != undefined){
                                if(awdr_params.custom_target_simple_product != ""){
                                    target = awdr_params.custom_target_simple_product;
                                }
                            }
                            $price_place = getWDRDPTarget(form, target, false);
                        } else if (form.find('input[name="variation_id"]').length) {
                            $product_id = form.find('input[name="variation_id"]').val();
                            var target = 'div.product .woocommerce-variation-price';
                            if(awdr_params.custom_target_variable_product != undefined){
                                if(awdr_params.custom_target_variable_product != ""){
                                    target = awdr_params.custom_target_variable_product;
                                }
                            }
                            $price_place = getWDRDPTarget(form, target, true);
                        } else if (form.find('input[name="add-to-cart"]').length) {
                            $product_id = form.find('input[name="add-to-cart"]').first().val();
                            var target = 'div.product p.price';
                            if(awdr_params.custom_target_simple_product != undefined){
                                if(awdr_params.custom_target_simple_product != ""){
                                    target = awdr_params.custom_target_simple_product;
                                }
                            }
                            $price_place = getWDRDPTarget(form, target, false);
                        }
                        if(!$product_id || $product_id == 0){
                            if(awdr_params.custom_simple_product_id_selector != undefined){
                                if(awdr_params.custom_simple_product_id_selector != ""){
                                    let simple_product_id_selector = awdr_params.custom_simple_product_id_selector;
                                    $product_id = $(simple_product_id_selector).val();
                                    let target = 'div.product p.price';
                                    if(awdr_params.custom_target_simple_product != undefined){
                                        if(awdr_params.custom_target_simple_product != ""){
                                            target = awdr_params.custom_target_simple_product;
                                        }
                                    }
                                    $price_place = getWDRDPTarget(form, target, false);
                                }
                            }

                            if(awdr_params.custom_variable_product_id_selector != undefined){
                                if(awdr_params.custom_variable_product_id_selector != ""){
                                    let variable_product_id_selector = awdr_params.custom_variable_product_id_selector;
                                    $product_id = $(variable_product_id_selector).val();
                                    let target = 'div.product .woocommerce-variation-price';
                                    if(awdr_params.custom_target_variable_product != undefined){
                                        if(awdr_params.custom_target_variable_product != ""){
                                            target = awdr_params.custom_target_variable_product;
                                        }
                                    }
                                    $price_place = getWDRDPTarget(form, target, true);
                                }
                            }
                        }

                        if (!$product_id || !$price_place || $product_id == 0) {
                            return;
                        }

                        var data = {
                            action: 'wdr_ajax',
                            method: 'get_price_html',
                            product_id: $product_id,
                            qty: $qty,
                            awdr_nonce: awdr_params.nonce,
                        };
                        $.ajax({
                            url: awdr_params.ajaxurl,
                            data: data,
                            type: 'POST',
                            success: function (response) {
                                if (response.price_html) {
                                    $price_place.html(response.price_html)
                                } else {
                                    if(response.original_price_html != undefined){
                                        $price_place.html(response.original_price_html)
                                    }
                                }
                                // Trigger the custom price_updated event
                                $(document).trigger('wdr_dynamic_price_update', [response]);
                            },
                            error: function (response) {
                                $price_place.html("")
                            }
                        });
                    }, 0);
                });
            }
        }

        if (awdr_params.js_init_trigger) {
            $(document).on(awdr_params.js_init_trigger, function () {
                init_events();
            });
        }
        init_events();

        if (awdr_params.awdr_dynamic_bulk_table_status == "1") {
            if(awdr_params.awdr_dynamic_bulk_table_off == "on"){
                function awdr_load_variation_table(variation_id){
                    setTimeout(function(){
                        if(variation_id != '' && variation_id != '0'){
                            var data = {
                                action: 'wdr_ajax',
                                method: 'get_variable_product_bulk_table',
                                product_id: variation_id,
                                awdr_nonce: awdr_params.nonce,
                            };

                            let awdr_opacity = 'div.awdr-bulk-customizable-table';

                            if(awdr_params.awdr_opacity_to_bulk_table != undefined){
                                if(awdr_params.awdr_opacity_to_bulk_table != ""){
                                    awdr_opacity = awdr_params.awdr_opacity_to_bulk_table;
                                }
                            }

                            $.ajax({
                                url: awdr_params.ajaxurl,
                                data: data,
                                type: 'POST',
                                beforeSend: function () {
                                    $(awdr_opacity).css('opacity','0.5');
                                },
                                complete: function () {
                                    $(awdr_opacity).css('opacity','1');
                                },
                                success: function (response) {
                                    if (response.bulk_table) {
                                        $('.awdr-bulk-customizable-table').html(response.bulk_table);
                                    }
                                },
                                error: function (response) {
                                    $('.awdr-bulk-customizable-table').html("")
                                }
                            });
                        }
                    }, 100);
                }
                $( ".single_variation_wrap" ).on( "hide_variation", function ( event ) {
                    let variation_id = $(this).closest('form').find('input[name="product_id"]').val();
                    awdr_load_variation_table(variation_id);
                });
                $( ".single_variation_wrap" ).on( "show_variation", function ( event, variation, purchasable ) {
                    let variation_id = variation.variation_id;
                    if(variation.is_bundled != undefined){
                        if(variation.is_bundled == true){
                            return;
                        }
                    }
                    awdr_load_variation_table(variation_id);
                });
            }
        }
    });
})(jQuery);
// source --> https://mfrash.com/wp-content/plugins/woo-discount-rules/v2/Assets/Js/awdr-dynamic-price.js?ver=2.6.15 
(function ($) {
    $.extend({
        AdvanceWooDiscountRules: {
            form: null,
            product_id: null,
            quantity: 0,
            options: [],
            target: null,
            getDynamicDiscountPriceFromCartForm: function($form, $target, $options){
                if (typeof $options !== 'undefined') {
                    this.options = $options;
                }
                if (typeof $target !== 'undefined') {
                    this.target = $target;
                }
                if (typeof $form !== 'undefined' && $form.is('form')) {
                    this.form = $form;
                } else {
                    this.logError("Incorrect form provided");
                }
                this.product_id = this.getProductIdFromForm();

                this.quantity = this.getProductQuantityFromForm();
                this.getDiscountPriceForProduct();
            },
            getDiscountPriceForProduct: function () {
                if(this.product_id === null || this.product_id == 0){
                    this.logError("Invalid product");
                    return [];
                }
                var data = {
                    action: 'awdr_get_product_discount',
                    product_id: this.product_id,
                    qty: this.quantity,
                    awdr_nonce: awdr_params.nonce,
                };
                if (typeof this.options.custom_price !== 'undefined') {
                    data.custom_price = this.options.custom_price;
                }
                var $target = this.target;
                var $options = this.options;
                $.ajax({
                    url: awdr_params.ajaxurl,
                    data: data,
                    type: 'POST',
                    success: function (response) {
                        $(document.body).trigger("advanced_woo_discount_rules_on_get_response_for_dynamic_discount", [ response, $target, $options ]);
                        //return response;
                    },
                    error: function (response) {
                    }
                });
            },
            getProductIdFromForm: function () {
                var variationIdEl = this.form.find('[name="variation_id"]');
                var productIdEl = this.form.find('[name="add-to-cart"]');

                if (variationIdEl.length) {
                    return parseInt(variationIdEl.val());
                } else if (productIdEl.length) {
                    return parseInt(productIdEl.val());
                }

                return false;
            },
            getProductQuantityFromForm: function () {
                var $input = this.form.find('input[name="quantity"]');
                if ($input.length === 0) {
                    return 0;
                }

                return $input.val();
            },
            logError: function($text) {
                console.error("Advance discount rule error: %s", $text);
            }
        }
    });
})(jQuery);