/* SHABNAM.DEV WordPress integration */
(function ($) {
    'use strict';

    var themeConfig = window.SHCDMuchWowTheme || {};


    function shabnamCartDropdown() {
        var shell = document.querySelector('[data-shabnam-cart-shell]');
        var toggle = shell ? shell.querySelector('[data-shabnam-cart]') : null;
        var dropdown = shell ? shell.querySelector('[data-shabnam-cart-dropdown]') : null;
        if (!shell || !toggle || !dropdown) return { open: function () {}, close: function () {} };

        var setOpen = function (open) {
            shell.classList.toggle('is-open', Boolean(open));
            toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
            dropdown.setAttribute('aria-hidden', open ? 'false' : 'true');
        };

        toggle.addEventListener('click', function (event) {
            event.preventDefault();
            event.stopPropagation();
            setOpen(!shell.classList.contains('is-open'));
        });
        dropdown.addEventListener('click', function (event) { event.stopPropagation(); });
        document.addEventListener('click', function () { setOpen(false); });
        document.addEventListener('keydown', function (event) { if (event.key === 'Escape') setOpen(false); });

        return { open: function () { setOpen(true); }, close: function () { setOpen(false); } };
    }

    var cartDropdown = shabnamCartDropdown();

    function shabnamRefreshCartFragments(event, fragments) {
        if (!fragments) return;
        var $count = $('.shabnam-cart-count');
        if (!$count.length) return;
        var html = fragments['span.shabnam-cart-count'];
        if (html) $count.replaceWith(html);
    }

    function shabnamCartBump() {
        var cart = document.querySelector('[data-shabnam-cart]');
        if (!cart) return;
        cart.classList.remove('is-bumping');
        void cart.offsetWidth;
        cart.classList.add('is-bumping');
        window.setTimeout(function () { cart.classList.remove('is-bumping'); }, 650);
    }

    function shabnamFindProductImage(source) {
        if (!source) return null;
        var root = source.closest('.shabnam-product-card, li.product, .product, .shabnam-home-shop');
        if (!root) return null;
        return root.querySelector('.shabnam-product-media img, img.wp-post-image, .woocommerce-loop-product__link img, .woocommerce-product-gallery__image img');
    }

    function shabnamFlyToCart(source) {
        if (themeConfig.cartAnimation === false) return;
        var cart = document.querySelector('[data-shabnam-cart]');
        var image = shabnamFindProductImage(source);
        if (!cart || !image) return;

        var start = image.getBoundingClientRect();
        var end = cart.getBoundingClientRect();
        if (!start.width || !start.height || !end.width || !end.height) return;

        var size = Math.max(56, Math.min(92, start.width * 0.28));
        var clone = image.cloneNode(true);
        clone.removeAttribute('srcset');
        clone.removeAttribute('sizes');
        clone.setAttribute('aria-hidden', 'true');
        clone.className = 'shabnam-cart-fly';
        clone.style.left = (start.left + start.width / 2 - size / 2) + 'px';
        clone.style.top = (start.top + start.height / 2 - size / 2) + 'px';
        clone.style.width = size + 'px';
        clone.style.height = size + 'px';
        document.body.appendChild(clone);

        var dx = end.left + end.width / 2 - (start.left + start.width / 2);
        var dy = end.top + end.height / 2 - (start.top + start.height / 2);
        var midX = dx * 0.5;
        var midY = dy * 0.45 - Math.min(90, Math.abs(dx) * 0.12 + 35);

        if (clone.animate) {
            var animation = clone.animate([
                { transform: 'translate3d(0,0,0) scale(1) rotate(0deg)', opacity: 1, offset: 0 },
                { transform: 'translate3d(' + midX + 'px,' + midY + 'px,0) scale(.78) rotate(-10deg)', opacity: .96, offset: .52 },
                { transform: 'translate3d(' + dx + 'px,' + dy + 'px,0) scale(.2) rotate(13deg)', opacity: .15, offset: 1 }
            ], { duration: 720, easing: 'cubic-bezier(.18,.78,.25,1)', fill: 'forwards' });
            animation.onfinish = function () { clone.remove(); shabnamCartBump(); };
            animation.oncancel = function () { clone.remove(); };
        } else {
            clone.style.transition = 'transform .72s cubic-bezier(.18,.78,.25,1),opacity .72s ease';
            window.requestAnimationFrame(function () {
                clone.style.transform = 'translate3d(' + dx + 'px,' + dy + 'px,0) scale(.2) rotate(12deg)';
                clone.style.opacity = '.15';
            });
            window.setTimeout(function () { clone.remove(); shabnamCartBump(); }, 760);
        }
    }

    $(document.body).on('adding_to_cart', function (event, $button) {
        var source = $button && $button[0] ? $button[0] : null;
        shabnamFlyToCart(source);
    });

    $(document.body).on('wc_fragments_refreshed added_to_cart removed_from_cart', function (event, fragments) {
        shabnamRefreshCartFragments(event, fragments);
        if (event.type === 'added_to_cart') {
            shabnamCartBump();
            cartDropdown.open();
            window.clearTimeout(shabnamCartDropdown.autoClose);
            shabnamCartDropdown.autoClose = window.setTimeout(function () { cartDropdown.close(); }, 3600);
        }
    });


    /**
     * WooCommerce My Account SPA navigation.
     *
     * The current content remains on screen while the next endpoint is fetched,
     * so there is no full-page loading state or spinner. Hover/focus prefetching
     * warms the in-memory cache before the user clicks a menu item.
     */
    function shabnamAccountSpa() {
        if (!themeConfig.accountSpa || !themeConfig.accountAjax || !themeConfig.accountNonce) return;

        var navigation = document.querySelector('.woocommerce-MyAccount-navigation');
        var content = document.querySelector('.woocommerce-MyAccount-content');
        var endpointUrls = themeConfig.accountUrls || {};
        if (!navigation || !content || !Object.keys(endpointUrls).length) return;

        var cache = new Map();
        var pending = new Map();
        var activeController = null;
        var accountBase = endpointUrls.dashboard || window.location.href;

        content.classList.add('shabnam-account-spa-ready');
        content.setAttribute('aria-live', 'polite');
        content.setAttribute('aria-atomic', 'true');

        function normalizeUrl(raw) {
            try {
                var url = new URL(raw, window.location.href);
                url.hash = '';
                return url;
            } catch (error) {
                return null;
            }
        }

        function trimPath(path) {
            return (path || '/').replace(/\/+$/, '') || '/';
        }

        function resolveTarget(raw) {
            var target = normalizeUrl(raw);
            if (!target || target.origin !== window.location.origin) return null;

            var candidates = Object.keys(endpointUrls).map(function (endpoint) {
                var base = normalizeUrl(endpointUrls[endpoint]);
                return base ? { endpoint: endpoint, base: base, length: trimPath(base.pathname).length } : null;
            }).filter(Boolean).sort(function (a, b) { return b.length - a.length; });

            for (var i = 0; i < candidates.length; i++) {
                var item = candidates[i];
                if (target.origin !== item.base.origin) continue;

                var basePath = trimPath(item.base.pathname);
                var targetPath = trimPath(target.pathname);
                var isDashboard = item.endpoint === 'dashboard';
                var exactDashboard = isDashboard && targetPath === basePath;
                var endpointMatch = !isDashboard && (targetPath === basePath || targetPath.indexOf(basePath + '/') === 0);

                if (!exactDashboard && !endpointMatch) continue;

                var suffix = endpointMatch ? targetPath.slice(basePath.length).replace(/^\/+|\/+$/g, '') : '';
                var value = suffix ? decodeURIComponent(suffix.split('/')[0]) : '';

                return {
                    endpoint: item.endpoint,
                    value: value,
                    url: target.href,
                    key: item.endpoint + ':' + value
                };
            }

            return null;
        }

        function requestEndpoint(target, prefetch) {
            if (!target) return Promise.reject(new Error('invalid-target'));
            if (cache.has(target.key)) return Promise.resolve(cache.get(target.key));
            if (pending.has(target.key)) return pending.get(target.key);

            var body = new URLSearchParams();
            body.set('action', 'shabnam_muchwow_account_spa');
            body.set('nonce', themeConfig.accountNonce);
            body.set('endpoint', target.endpoint);
            body.set('value', target.value || '');

            var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
            if (!prefetch && activeController && activeController.abort) activeController.abort();
            if (!prefetch) activeController = controller;

            var promise = fetch(themeConfig.accountAjax, {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: body.toString(),
                signal: controller ? controller.signal : undefined
            }).then(function (response) {
                if (!response.ok) throw new Error('http-' + response.status);
                return response.json();
            }).then(function (payload) {
                if (!payload || !payload.success || !payload.data || typeof payload.data.html !== 'string') {
                    throw new Error('invalid-response');
                }
                cache.set(target.key, payload.data.html);
                return payload.data.html;
            }).finally(function () {
                pending.delete(target.key);
                if (!prefetch && activeController === controller) activeController = null;
            });

            pending.set(target.key, promise);
            return promise;
        }

        function setActiveMenu(targetUrl) {
            var links = navigation.querySelectorAll('a[href]');
            links.forEach(function (link) {
                var item = link.closest('li');
                if (!item) return;
                var resolved = resolveTarget(link.href);
                var current = resolveTarget(targetUrl);
                var activeEndpoint = current ? current.endpoint : '';
                if (activeEndpoint === 'view-order') activeEndpoint = 'orders';
                if (activeEndpoint === 'add-payment-method' || activeEndpoint === 'delete-payment-method' || activeEndpoint === 'set-default-payment-method') activeEndpoint = 'payment-methods';
                var active = Boolean(resolved && current && resolved.endpoint === activeEndpoint);
                item.classList.toggle('is-active', active);
                if (active) link.setAttribute('aria-current', 'page');
                else link.removeAttribute('aria-current');
            });
        }

        function reinitializeWooFragments() {
            if (window.jQuery) {
                window.jQuery(document.body).trigger('shabnam_account_spa_updated');
            }
        }

        function swapContent(html, target, pushHistory) {
            var performSwap = function () {
                content.innerHTML = html;
                content.classList.remove('shabnam-account-spa-swap');
                void content.offsetWidth;
                content.classList.add('shabnam-account-spa-swap');
                setActiveMenu(target.url);
                reinitializeWooFragments();

                if (pushHistory) {
                    window.history.pushState({ shabnamAccountSpa: true, url: target.url }, '', target.url);
                }

                var activeLink = Array.prototype.find.call(navigation.querySelectorAll('a[href]'), function (link) {
                    var item = link.closest('li');
                    return item && item.classList.contains('is-active');
                });
                if (activeLink) {
                    var label = activeLink.textContent.trim();
                    if (label) document.title = label + ' – ' + (document.title.split(' – ').slice(-1)[0] || document.title);
                }
            };

            if (document.startViewTransition && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
                document.startViewTransition(performSwap);
            } else {
                performSwap();
            }
        }

        function navigate(rawUrl, pushHistory) {
            var target = resolveTarget(rawUrl);
            if (!target) {
                window.location.href = rawUrl;
                return;
            }

            // Do not show a spinner or blank state; retain existing content until
            // the replacement is fully available.
            content.setAttribute('aria-busy', 'true');
            requestEndpoint(target, false).then(function (html) {
                swapContent(html, target, pushHistory);
            }).catch(function (error) {
                if (error && error.name === 'AbortError') return;
                window.location.href = target.url;
            }).finally(function () {
                content.removeAttribute('aria-busy');
            });
        }

        function shouldHandleClick(event, link) {
            if (!link || !link.href) return false;
            if (event.defaultPrevented || event.button !== 0) return false;
            if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;
            if (link.target && link.target !== '_self') return false;
            if (link.hasAttribute('download')) return false;
            if (link.closest('.woocommerce-MyAccount-navigation-link--customer-logout')) return false;
            var url = normalizeUrl(link.href);
            if (!url || url.searchParams.has('_wpnonce')) return false;
            return Boolean(resolveTarget(link.href));
        }

        document.addEventListener('click', function (event) {
            var link = event.target.closest('a[href]');
            if (!link) return;
            if (!navigation.contains(link) && !content.contains(link)) return;
            if (!shouldHandleClick(event, link)) return;

            event.preventDefault();
            navigate(link.href, true);
        });

        function prefetchLink(link) {
            if (!link || link.dataset.shabnamSpaPrefetched === 'true') return;
            if (link.closest('.woocommerce-MyAccount-navigation-link--customer-logout')) return;
            var target = resolveTarget(link.href);
            if (!target) return;

            requestEndpoint(target, true).then(function () {
                link.dataset.shabnamSpaPrefetched = 'true';
            }).catch(function () {
                // Prefetch is opportunistic. A normal click will retry/fallback.
            });
        }

        navigation.addEventListener('pointerenter', function (event) {
            var link = event.target.closest && event.target.closest('a[href]');
            if (link && navigation.contains(link)) prefetchLink(link);
        }, true);
        navigation.addEventListener('focusin', function (event) {
            var link = event.target.closest && event.target.closest('a[href]');
            if (link) prefetchLink(link);
        });

        // Warm the first few destinations after the browser becomes idle. This
        // makes common account switches effectively instantaneous without
        // blocking the initial page render.
        var warmCache = function () {
            var links = Array.prototype.slice.call(navigation.querySelectorAll('a[href]')).filter(function (link) {
                return !link.closest('.woocommerce-MyAccount-navigation-link--customer-logout');
            }).slice(0, 4);
            links.forEach(function (link, index) {
                window.setTimeout(function () { prefetchLink(link); }, index * 180);
            });
        };
        if ('requestIdleCallback' in window) window.requestIdleCallback(warmCache, { timeout: 1600 });
        else window.setTimeout(warmCache, 650);

        window.addEventListener('popstate', function () {
            var target = resolveTarget(window.location.href);
            if (target) navigate(window.location.href, false);
        });

        // Seed the current dashboard/content state so returning to it is instant.
        var current = resolveTarget(window.location.href);
        if (current) cache.set(current.key, content.innerHTML);
    }

    shabnamAccountSpa();

    // Keep the original theme's optional schema query behavior without throwing errors.
    var schema = new URLSearchParams(window.location.search).get('schema');
    if (typeof window.setDarkMode === 'function') {
        if (schema === 'dark') window.setDarkMode(1);
        if (schema === 'light') window.setDarkMode(0);
    }
})(jQuery);
