(function (w, d) {
    var OVERLAY = d.getElementById('dk-loading-overlay');
    var TITLE_ID = 'dk-loading-title';
    function showOverlay(message) {

        if (message) {
            var title = OVERLAY.querySelector('#' + TITLE_ID);
            if (title) title.textContent = message;
        }
        OVERLAY.style.display = 'flex';
        d.body.style.overflow = 'hidden';
    }

    function hideOverlay() {

        if (!OVERLAY) return;
        OVERLAY.style.display = 'none';
        d.body.style.overflow = '';
    }

    w.showOverlay = showOverlay;
    w.hideOverlay = hideOverlay;




})(window, document);

window.BWDK = window.BWDK || {};
window.BWDK.startDigifyCheckout = function (opts) {
    opts = opts || {};
    showOverlay();

    var origin = opts.origin;
    if (!origin) {
        var pathname = window.location.pathname;
        origin = 'checkout';

        if (pathname.indexOf('/checkout') !== -1) {
            origin = 'checkout';
        } else if (pathname.indexOf('/cart') !== -1) {
            origin = 'cart';
        } else {
            if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.cart_url) {
                origin = 'cart';
            } else {
                origin = 'checkout';
            }
        }
    }

    console.log('[BWDK] Origin determined:', origin, 'pathname:', window.location.pathname);

    function fetchAdminAjax() {
        return fetch(bwdk_ajax.ajax_url, {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'bwdk_get_cart',
                _ajax_nonce: bwdk_ajax.nonce,
                callback_url: window.location.href,
                bwdk_origin: origin
            })
        });
    }

    function fetchCartFromStoreAPI() {
        var storeApiUrl = new URL('/wp-json/wc/store/cart', window.location.origin);
        return fetch(storeApiUrl, {
            method: 'GET',
            credentials: 'include',
            headers: {
                'Accept': 'application/json'
            }
        });
    }

    function fetchCartWithFallback() {
        return fetchAdminAjax().then(function(response) {
            if (response.ok) {
                return response.json().then(function(data) {
                    return { ok: true, data: data };
                });
            }

            if (response.status >= 400) {
                return response.text().then(function(responseText) {
                    var errorData = null;
                    try {
                        errorData = JSON.parse(responseText);
                    } catch (e) {
                    }

                    return fetchCartFromStoreAPI().then(function(storeApiResponse) {
                        if (storeApiResponse.ok) {
                            return fetchAdminAjax().then(function(retryResponse) {
                                if (retryResponse.ok) {
                                    return retryResponse.json().then(function(data) {
                                        return { ok: true, data: data };
                                    });
                                }
                                return {
                                    ok: false,
                                    errorData: errorData,
                                    originalStatus: response.status
                                };
                            }).catch(function() {
                                return {
                                    ok: false,
                                    errorData: errorData,
                                    originalStatus: response.status
                                };
                            });
                        } else {
                            return {
                                ok: false,
                                errorData: errorData,
                                originalStatus: response.status
                            };
                        }
                    }).catch(function() {
                        return {
                            ok: false,
                            errorData: errorData,
                            originalStatus: response.status
                        };
                    });
                });
            }

            return response.text().then(function(responseText) {
                var errorData = null;
                try {
                    errorData = JSON.parse(responseText);
                } catch (e) {
                }
                return { ok: false, errorData: errorData, originalStatus: response.status };
            });
        }).catch(function(error) {
            return fetchCartFromStoreAPI().then(function(storeApiResponse) {
                if (storeApiResponse.ok) {
                    return fetchAdminAjax().then(function(retryResponse) {
                        if (retryResponse.ok) {
                            return retryResponse.json().then(function(data) {
                                return { ok: true, data: data };
                            });
                        }
                        return { ok: false, fetchError: true };
                    }).catch(function() {
                        return { ok: false, fetchError: true };
                    });
                } else {
                    return { ok: false, fetchError: true };
                }
            }).catch(function() {
                return { ok: false, fetchError: true };
            });
        });
    }

    fetchCartWithFallback().then(function(result) {
        console.log('[BWDK] fetchCartWithFallback result', result);
        if (result && result.data) {
            console.log('[BWDK] ajax data', result.data);
        }

        window.__BWDK_LAST_AJAX__ = result;

        if (result.ok && result.data) {
            if (result.data.success) {
                var startUrl = (result.data.data && result.data.data.order_start_url) || result.data.order_start_url;

                if (startUrl && typeof startUrl === 'string' && startUrl.indexOf('http') === 0) {
                    window.location.href = startUrl;
                } else {
                    console.error('[BWDK] Invalid or missing order_start_url:', {
                        result: result,
                        startUrl: startUrl,
                        data: result.data,
                        nestedData: result.data.data
                    });
                    hideOverlay();
                    jQuery('#bwdk-error').html('خطا در دریافت لینک پرداخت. لطفاً دوباره تلاش کنید.');
                    jQuery('.wrap-bwdk-error , .dk-mask').fadeIn();
                }
            } else {
                hideOverlay();
                var errorData = result.data.data || result.data;
                var errorMsg = errorData.message || 'خطای ناشناخته';
                var errorCode = errorData.code || '';

                if (errorCode === 'cart_invalid' || result.originalStatus === 409) {
                    jQuery('#bwdk-error').html(errorMsg);
                    jQuery('.wrap-bwdk-error , .dk-mask').fadeIn();

                    if (typeof jQuery !== 'undefined') {
                        jQuery(document.body).trigger('update_checkout');
                        jQuery(document.body).trigger('wc_fragment_refresh');
                    }
                } else {
                    jQuery('#bwdk-error').html(errorMsg);
                    jQuery('.wrap-bwdk-error , .dk-mask').fadeIn();
                }
            }
        } else {
            var msg = 'خطای ناشناخته';
            var errorCode = '';

            if (result && result.errorData) {
                var errorData = result.errorData.data || result.errorData;
                msg = errorData.message || result.errorData.message || msg;
                errorCode = errorData.code || '';
            }

            hideOverlay();

            if (errorCode === 'cart_invalid' || result.originalStatus === 409) {
                jQuery('#bwdk-error').html(msg);
                jQuery('.wrap-bwdk-error , .dk-mask').fadeIn();

                if (typeof jQuery !== 'undefined') {
                    jQuery(document.body).trigger('update_checkout');
                    jQuery(document.body).trigger('wc_fragment_refresh');
                }
            } else {
                jQuery('#bwdk-error').html(msg);
                jQuery('.wrap-bwdk-error , .dk-mask').fadeIn();
            }
        }
    }).catch(function(error) {
        console.error('[BWDK] fetchCartWithFallback error:', error);
        hideOverlay();
        jQuery('#bwdk-error').html('خطای ناشناخته');
        jQuery('.wrap-bwdk-error , .dk-mask').fadeIn();
    });
};

document.addEventListener('click', function (e) {
    var host = null;
    var i;
    if (e.composedPath) {
        var path = e.composedPath();
        for (i = 0; i < path.length; i++) {
            var n = path[i];
            if (n && n.nodeType === 1 && n.matches && n.matches('digify-clickable-box[data-bwdk-context="cart-checkout"]')) {
                host = n;
                break;
            }
        }
    } else if (e.target && e.target.closest) {
        host = e.target.closest('digify-clickable-box[data-bwdk-context="cart-checkout"]');
    }
    if (!host) {
        return;
    }
    e.preventDefault();
    if (typeof window.BWDK.startDigifyCheckout === 'function') {
        window.BWDK.startDigifyCheckout();
    }
}, true);

jQuery(document).ready(function ($) {

    jQuery('.wrap-bwdk-error span , .dk-mask').on('click', function () {
        jQuery('.wrap-bwdk-error , .dk-mask').fadeOut();
    });

    jQuery('.digikala-box-after-addToCart ,.digikala-box-before-header').on('click', function () {
        jQuery('.digikala-modal-sp , .dk-mask').fadeIn();
    });

    jQuery('.digikala-modal-sp button, .close-modal-sp, .dk-mask').on('click', function () {
        jQuery('.digikala-modal-sp , .dk-mask').fadeOut();
    });
});
// Initialize BWDK button click handler once using delegated binding
jQuery(document).ready(function () {
    // Use delegated binding with namespace to prevent duplicate handlers
    // This binds once and works for dynamically added buttons
    jQuery(document).off('click.bwdk', '.bwdk-button').on('click.bwdk', '.bwdk-button', function (e) {
        e.preventDefault();
        window.BWDK.startDigifyCheckout();
    });
    });



jQuery(function ($) {
    var $box = $('.wrap-anim-text .anim-text');
    var $items = $box.children('span');

    if (!$box.length || $items.length < 2) return;

    var step = $items.first().outerHeight();
    var dur = 300;
    var wait = 1000;
    var total = $items.length - 1;
    var i = 0;

    $('.wrap-anim-text').css({overflow: 'hidden', height: step});

    function tick() {
        i++;
        $box.css({
            transition: 'transform ' + dur + 'ms',
            transform: 'translateY(' + (-i * step) + 'px)'
        });

        if (i === total) {
            setTimeout(function () {
                $box.css({transition: 'none', transform: 'translateY(0px)'});
                i = 0;
            }, dur + 20);
        }

        setTimeout(tick, dur + wait);
    }

    tick();
});

jQuery(function ($) {
    var $wrap = $('.pdp-anim-text');
    var $box = $wrap.find('.anim-text');
    var $items = $box.children('span');

    if (!$wrap.length || !$box.length || $items.length < 2) return;

    if ($items.last().text().trim() !== $items.first().text().trim()) {
        $box.append($items.first().clone());
        $items = $box.children('span');
    }

    var step = Math.round($wrap.height()) || $items.first().outerHeight();
    var dur = 300;
    var wait = 1000;
    var total = $items.length - 1;
    var i = 0;

    $wrap.css({overflow: 'hidden', height: step});
    $box.css({willChange: 'transform'});

    function tick() {
        i++;
        $box.css({
            transition: 'transform ' + dur + 'ms',
            transform: 'translateY(' + (-i * step) + 'px)'
        });

        if (i === total) {
            setTimeout(function () {
                $box.css({transition: 'none', transform: 'translateY(0px)'});
                i = 0;
            }, dur + 20);
        }

        setTimeout(tick, dur + wait);
    }

    tick();
});

jQuery(document.body).on('wc_fragments_loaded', function(){
    var wrap = jQuery('.wrap-anim-text-addToCart-pop');
    var box = jQuery('#anim-text');

    var items = box.children('span');

    if (!wrap.length || !box.length || items.length < 2) return;

    if (items.last().text().trim() !== items.first().text().trim()) {
        box.append(items.first().clone());
        items = box.children('span');
    }

    var step = Math.round(wrap.height()) || items.first().outerHeight();
    var dur = 300;
    var wait = 1000;
    var total = items.length - 1;
    var i = 0;

    wrap.css({overflow: 'hidden', height: step});
    box.css({willChange: 'transform'});

    function tick() {
        i++;
        box.css({
            transition: 'transform ' + dur + 'ms',
            transform: 'translateY(' + (-i * step) + 'px)'
        });

        if (i === total) {
            setTimeout(function () {
                box.css({transition: 'none', transform: 'translateY(0px)'});
                i = 0;
            }, dur + 20);
        }

        setTimeout(tick, dur + wait);
    }
    tick();

});

jQuery(function ($) {
    function activateBox() {
        var $box = $('.digikala-box-before-ct');
        if (!$box.length) return;
        $box.removeClass('active');
        setTimeout(function () {
            $box.addClass('active');
        }, 10);
    }

    setTimeout(activateBox, 1000);

    $(document.body).on(
        'updated_wc_div updated_cart_totals cart_totals_refreshed wc_fragments_loaded wc_fragments_refreshed removed_from_cart added_to_cart',
        function ($) {
            setTimeout(activateBox, 100);
        }
    );

    var observer = new MutationObserver(function (mutations) {
        for (var i = 0; i < mutations.length; i++) {
            var m = mutations[i];
            if ($(m.addedNodes).find('.digikala-box-before-ct').length) {
                setTimeout(activateBox, 50);
                break;
            }
        }
    });
    observer.observe(document.body, { childList: true, subtree: true });
});

// Hotfix: Remove empty tags from .dk-content-before-ct container
// This is a backup solution in case PHP cleaning doesn't catch everything
jQuery(function ($) {
    function removeEmptyTags() {
        $('.dk-content-before-ct').each(function() {
            var $container = $(this);
            
            // Remove empty <p> tags
            $container.find('p:empty').remove();
            $container.find('p').filter(function() {
                return $(this).text().trim() === '' && $(this).children().length === 0;
            }).remove();
            
            // Remove standalone empty <br> tags
            $container.find('br').each(function() {
                var $br = $(this);
                var $parent = $br.parent();
                var prevText = $br[0].previousSibling;
                var nextText = $br[0].nextSibling;
                
                // Check if br has no meaningful content around it
                var hasPrevContent = prevText && prevText.nodeType === 3 && prevText.textContent.trim() !== '';
                var hasNextContent = nextText && nextText.nodeType === 3 && nextText.textContent.trim() !== '';
                
                if (!hasPrevContent && !hasNextContent) {
                    // Check if parent only has this br
                    var parentText = $parent.text().trim();
                    if (parentText === '' || ($parent.children().length === 1 && $parent.children().is('br'))) {
                        $br.remove();
                    }
                }
            });
            
            // Remove empty <a class="bwdk-button"> tags
            $container.find('a.bwdk-button').each(function() {
                var $btn = $(this);
                var hasContent = $btn.text().trim() !== '' || $btn.children().length > 0;
                if (!hasContent) {
                    $btn.remove();
                }
            });
        });
    }
    
    // Run on DOM ready
    removeEmptyTags();
    
    // Run after AJAX updates (WooCommerce fragments, etc.)
    $(document.body).on('updated_wc_div updated_cart_totals cart_totals_refreshed wc_fragments_loaded wc_fragments_refreshed', function() {
        setTimeout(removeEmptyTags, 100);
    });
    
    // Also observe for dynamically added content
    var hotfixObserver = new MutationObserver(function(mutations) {
        var shouldClean = false;
        for (var i = 0; i < mutations.length; i++) {
            var m = mutations[i];
            if (m.addedNodes.length > 0) {
                for (var j = 0; j < m.addedNodes.length; j++) {
                    var node = m.addedNodes[j];
                    if (node.nodeType === 1) { // Element node
                        if ($(node).hasClass('dk-content-before-ct') || $(node).find('.dk-content-before-ct').length > 0) {
                            shouldClean = true;
                            break;
                        }
                    }
                }
            }
            if (shouldClean) break;
        }
        if (shouldClean) {
            setTimeout(removeEmptyTags, 50);
        }
    });
    
    hotfixObserver.observe(document.body, {
        childList: true,
        subtree: true
    });
});





jQuery(function ($) {
    var COOKIE = 'bwdk_error';

    function getCookie(name) {
        var m = document.cookie.match(new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()\[\]\\\/\+^])/g,'\\$1') + '=([^;]*)'));
        return m ? m[1] : null;
    }



    function eraseCookieAllScopes(name) {
        var host = location.hostname;
        var domains = ['', host, '.' + host];

        if (host.indexOf('www.') === 0) {
            var noWWW = host.replace(/^www\./, '');
            domains.push(noWWW, '.' + noWWW);
        }
        domains.push(host);



        var paths = ['/'];
        var parts = location.pathname.split('/').filter(Boolean);
        var cur = '';
        for (var i = 0; i < parts.length; i++) {
            cur += '/' + parts[i];
            paths.push(cur);
        }

        var base = '; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0';
        $.each(domains, function (_, d) {
            $.each(paths, function (_, p) {
                document.cookie = name + '=' + base + '; path=/'+ (d ? '; domain=' + d : '');
            });
        });
    }

    var raw = getCookie(COOKIE);
    if (!raw) return;

    try { raw = decodeURIComponent(raw.replace(/\+/g, ' ')); } catch (e) {}


    $('#bwdk-error')
        .html(raw || 'خطای ناشناخته');
    $('.wrap-bwdk-error , .dk-mask').fadeIn();


    eraseCookieAllScopes(COOKIE);
});

// Single Buy Button Tip
(function($){
  $(function(){
    // Check if tip was previously dismissed
    if (window.localStorage && localStorage.getItem('bwdk_single_tip_closed') === '1') {
      return;
    }

    // Find the single buy button and its form
    var $btn = $('.bwdk-single-buy-button').first();
    if (!$btn.length) return;
    
    var $form = $('#bwdk-single-buy-form');
    if (!$form.length) return;
    
    // Check if tip already exists
    if ($('.bwdk-single-tip').length) return;

    // Get the image URL for tooltip (always use digiLogoRed.svg)
    var logoUrl = '';
    var $btnImg = $btn.find('img.logo-digi');
    if ($btnImg.length) {
      // Replace digiLogo.svg with digiLogoRed.svg in the path
      var btnImgSrc = $btnImg.attr('src');
      logoUrl = btnImgSrc.replace('digiLogo.svg', 'digiLogoRed.svg');
    } else {
      // Fallback: construct path based on plugin structure
      var pluginPath = window.location.pathname.match(/\/wp-content\/plugins\/[^\/]+/);
      if (pluginPath) {
        logoUrl = pluginPath[0] + '/assets/public/img/digiLogoRed.svg';
      }
    }

    // Build the tip HTML
    var tipImgHtml = logoUrl ? '<img src="' + logoUrl + '" alt="digikala" class="logo-digi">' : '';
    var $tip = $(
      '<div class="bwdk-single-tip">' +
        '<div class="bwdk-single-tip-inner">' +
          '<div class="bwdk-single-tip-header">' +
            '<span class="bwdk-single-tip-title">' +
              tipImgHtml +
              '<span>خرید با دیجی‌کالا</span>' +
            '</span>' +
            '<button type="button" class="bwdk-single-tip-close" aria-label="بستن">×</button>' +
          '</div>' +
          '<p>می‌توانید محصول موردنظر خود را بدون طی مراحل سبد خرید، به‌سرعت و با حساب دیجی‌کالایتان سفارش دهید</p>' +
          '<div class="bwdk-single-tip-footer">' +
            '<button type="button" class="bwdk-single-tip-ok">متوجه شدم</button>' +
          '</div>' +
        '</div>' +
      '</div>'
    );

    // Build the mask overlay
    var $mask = $('<div class="dk-mask"></div>');

    // Insert tip inside the form (absolutely positioned relative to form)
    $tip.hide().appendTo($form);
    
    // Append mask to body
    $mask.hide().appendTo('body');

    // Show tooltip and mask with fade-in after 1 second
    setTimeout(function() {
      $tip.fadeIn(200);
      //$mask.fadeIn(200);
    }, 1000);

    // Handle close and OK button clicks
    function closeTip() {
      // Save dismissal to localStorage
      if (window.localStorage) {
        localStorage.setItem('bwdk_single_tip_closed', '1');
      }
      
      // Fade out and remove tooltip
      $tip.fadeOut(200, function() {
        $(this).remove();
      });
      
      // Fade out and remove mask
      $mask.fadeOut(200, function() {
        $(this).remove();
      });
    }

    $tip.on('click', '.bwdk-single-tip-close, .bwdk-single-tip-ok', closeTip);
  });
})(jQuery);

