/*
 * @package     VP Neoteric
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2023-2025 Virtueplanet Services LLP. All Rights Reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

var Joomla = window.Joomla || {};
var Neoteric = window.Neoteric || {};

(function (Joomla, tmpl, document, window) {
    'use strict';

    tmpl.toggleClassOnHover = function (elementSelector, cssClass, callbackFunction) {
        [].slice.call(document.querySelectorAll(elementSelector)).forEach(function (element) {
            element.removeEventListener('mouseenter', tmpl._toggleClassOnHover.bind(null, elementSelector, cssClass, callbackFunction));
            element.addEventListener('mouseenter', tmpl._toggleClassOnHover.bind(null, elementSelector, cssClass, callbackFunction));
            element.removeEventListener('mouseleave', tmpl._toggleClassOnHover.bind(null, elementSelector, cssClass, callbackFunction));
            element.addEventListener('mouseleave', tmpl._toggleClassOnHover.bind(null, elementSelector, cssClass, callbackFunction));
        });
    }

    tmpl._toggleClassOnHover = function (elementSelector, cssClass, callbackFunction, event) {
        var isEnter = event.type === 'mouseenter';

        [].slice.call(document.querySelectorAll(elementSelector)).forEach(function (element) {
            element.classList.remove(cssClass);
        });

        if (event.target) {
            event.target.classList[isEnter ? "add" : "remove"](cssClass);
        }

        if (typeof callbackFunction === 'function') {
            callbackFunction(event, isEnter);
        }
    }

    tmpl.setCookie = function (name, value, tenureDays) {
        var date = new Date();

        date.setTime(date.getTime() + (tenureDays * 24 * 60 * 60 * 1000));

        var expires = 'expires=' + date.toUTCString();

        document.cookie = name + '=' + (value || '') + ';' + expires + ';path=/';
    }

    tmpl.getCookie = function (cname, dValue) {
        dValue = dValue || null;

        var name = cname + '=';
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');

        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];

            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }

            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }

        return dValue;
    }

    tmpl.initProducts = function () {
        tmpl.toggleClassOnHover('.product .product-container', 'state-hover', function (event, isEnter) {
            if (event.target && isEnter) {
                var backdrop = event.target.querySelector('.product-backdrop');
                var bottom = event.target.querySelector('.product-bottom-container');
                var tnsOvh = event.target.closest('.tns-ovh');

                if (backdrop && bottom) {
                    backdrop.style.marginBottom = '-' + bottom.offsetHeight + 'px';

                    if (tnsOvh) {
                        tnsOvh.style.height = '';
                        tnsOvh.style.marginBottom = '';

                        tnsOvh.style.height = (tnsOvh.offsetHeight + bottom.offsetHeight) + 'px';
                        tnsOvh.style.marginBottom = '-' + bottom.offsetHeight + 'px';
                    }
                }
            } else if (event.target && !isEnter) {
                var tnsOvh = event.target.closest('.tns-ovh');

                if (tnsOvh) {
                    tnsOvh.style.height = '';
                    tnsOvh.style.marginBottom = '';
                }
            }
        });

        [].slice.call(document.querySelectorAll('.vm-customfield-choice:not(.choices__input)')).forEach(function (select) {
            new Choices(select, {
                searchEnabled: false,
                searchChoices: false,
                shouldSort: false,
                allowHTML: true,
                classNames: {
                    containerOuter: 'choices choices__customfield'
                },
                callbackOnCreateTemplates: function (template) {
                    return {
                        item: function (items, data) {
                            var classNames = items.classNames;
                            return template(`
                          <div class="${classNames.item} ${data.highlighted ? classNames.highlightedState : classNames.itemSelectable} ${data.placeholder ? classNames.placeholder : ''} ${data.customProperties.className ? data.customProperties.className : ''}" data-item data-id="${data.id}" data-value="${data.value}" ${data.active ? 'aria-selected="true"' : ''
                                } ${data.disabled ? 'aria-disabled="true"' : ''}>
                                ${data.label}
                                ${data.customProperties.price ? '<span class="choices__price">' + data.customProperties.price + '</span>' : ''}
                                </div>
                        `);
                        },
                        choice: function (items, data) {
                            var classNames = items.classNames;
                            return template(`
                          <div id="${data.elementId}" class="${classNames.item} ${classNames.itemChoice} ${data.disabled ? classNames.itemDisabled : classNames.itemSelectable
                                } ${data.placeholder ? classNames.placeholder : ''} ${data.customProperties.className ? data.customProperties.className : ''}" data-select-text="${this.config.itemSelectText}" data-choice ${data.disabled
                                    ? 'data-choice-disabled aria-disabled="true"'
                                    : 'data-choice-selectable'
                                } data-id="${data.id}" data-value="${data.value}" ${data.groupId > 0 ? 'role="treeitem"' : 'role="option"'
                                }>
                                ${data.label}
                                ${data.customProperties.price ? '<span class="choices__price">' + data.customProperties.price + '</span>' : ''}
                                </div>
                        `);
                        },
                    };
                }
            });
        });

        if (typeof window.bootstrap != 'undefined' && typeof window.bootstrap.Tooltip != 'undefined') {
            var leftOutElements = Array.from(document.querySelectorAll('.tooltip[role="tooltip"]'));

            if (leftOutElements.length) {
                leftOutElements.map(function (el) {
                    el.remove();
                });
            }

            var elements = Array.from(document.querySelectorAll('.has-tooltip'));
            var options = {
                animation: true,
                container: 'body',
                delay: 0,
                html: true,
                selector: false,
                trigger: 'hover focus',
                fallbackPlacement: null,
                boundary: 'clippingParents',
                title: '',
                customClass: '',
                sanitize: true,
                sanitizeFn: null,
                popperConfig: null
            };

            if (elements.length) {
                elements.map(function (el) {
                    return new window.bootstrap.Tooltip(el, options);
                });
            }
        }

        if (typeof window.bootstrap != 'undefined' && typeof window.bootstrap.Popover != 'undefined') {
            var leftOutElements = Array.from(document.querySelectorAll('.popover[role="tooltip"]'));

            if (leftOutElements.length) {
                leftOutElements.map(function (el) {
                    el.remove();
                });
            }

            var elements = Array.from(document.querySelectorAll('.has-popover'));
            var options = {
                animation: true,
                container: 'body',
                delay: {
                    "show": 50,
                    "hide": 200
                },
                html: true,
                placement: 'top',
                selector: false,
                title: '',
                trigger: 'hover focus',
                offset: [
                    0,
                    10
                ],
                fallbackPlacement: 'flip',
                boundary: 'scrollParent',
                customClass: '',
                sanitize: true,
                sanitizeFn: null,
                popperConfig: null
            };

            if (elements.length) {
                elements.map(function (el) {
                    return new window.bootstrap.Popover(el, options);
                });
            }
        }

        // Initialize tab links
        tmpl.initTabLinks();
    }

    tmpl.initLazyLoad = function () {
        var ll = new LazyLoad({
            class_applied: "lz-applied",
            class_loading: "lz-loading",
            class_loaded: "lz-loaded",
            class_error: "lz-error",
            class_entered: "lz-entered",
            class_exited: "lz-exited",
            callback_loaded: function (el) {
                var customLoadEvent = new CustomEvent('lazyImageLoaded');
                el.dispatchEvent(customLoadEvent);
            }
        });
    }

    tmpl.initTabLinks = function () {
        [].slice.call(document.querySelectorAll('[data-bs-tablink]')).forEach(function (link) {
            if (link.dataset.bsTablink !== 'ready') {
                link.addEventListener('click', function (event) {
                    event.preventDefault();
                    const target = document.querySelector(link.getAttribute('href'));
                    const stickyHeader = document.querySelector('.header-content.sticky-top');

                    if (target && window.bootstrap) {
                        const tab = window.bootstrap.Tab.getOrCreateInstance(target);

                        if (tab) {
                            target.addEventListener('shown.bs.tab', function () {
                                if (stickyHeader) {
                                    target.style.scrollMarginTop = stickyHeader.offsetHeight + 'px';
                                }

                                target.scrollIntoView();
                            });

                            tab.show();
                        }
                    }
                });

                link.dataset.bsTablink = 'ready';
            }
        });
    }

    tmpl.initTemplate = function (event) {
        var target = event && event.target ? event.target : document;

        /**
         * Prevent clicks on buttons within a disabled fieldset
         */
        var fieldsets = target.querySelectorAll('fieldset.btn-group');
        for (var i = 0; i < fieldsets.length; i++) {
            var self = fieldsets[i];
            if (self.getAttribute('disabled') === true) {
                self.style.pointerEvents = 'none';
                var btns = self.querySelectorAll('.btn');
                for (var ib = 0; ib < btns.length; ib++) {
                    btns[ib].classList.add('disabled');
                }
            }
        }

        [].slice.call(document.querySelectorAll('[data-tmpl-toggle="search"]')).forEach(function (link) {
            link.addEventListener('click', function (event) {
                event.preventDefault();
                document.body.classList.toggle('header-search-open');

                if (document.body.classList.contains('header-search-open')) {
                    var searchContainer = document.getElementById('headerSearch');

                    if (searchContainer) {
                        var input = searchContainer.querySelector('input[type="search"]');

                        if (!input) {
                            input = searchContainer.querySelector('input[type="text"]');
                        }

                        if (input) {
                            setTimeout(function () {
                                input.focus();
                            }, 400);
                        }
                    }
                }
            })
        });

        [].slice.call(document.querySelectorAll('.normal-choice')).forEach(function (select) {
            new Choices(select, {
                searchEnabled: false,
                searchChoices: false,
                shouldSort: false,
                allowHTML: true,
                classNames: {
                    containerOuter: 'choices choices-sm'
                }
            });
        });

        [].slice.call(document.querySelectorAll('.normal-choice-wrapper > select')).forEach(function (select) {
            new Choices(select, {
                searchEnabled: false,
                searchChoices: false,
                allowHTML: true,
                classNames: {
                    containerOuter: 'choices choices-sm'
                }
            });
        });

        [].slice.call(document.head.querySelectorAll('link[rel="lazy-stylesheet"]')).forEach(function ($link) {
            $link.rel = "stylesheet";
        });

        [].slice.call(document.querySelectorAll('[data-submitonchange="true"]')).forEach(function ($field) {
            $field.addEventListener('change', function (e) {
                if (e.target && e.target.closest('form')) {
                    e.target.closest('form').submit();
                }
            });
        });

        [].slice.call(document.querySelectorAll('[data-bs-toggle="offcanvas"]')).forEach(function ($toggle) {
            let $target = document.querySelector(
                $toggle.getAttribute("data-bs-target")
            );

            if (!$target) {
                $target = document.querySelector($toggle.getAttribute("href"));
            }

            if ($target) {
                $target.addEventListener("shown.bs.offcanvas", function () {
                    $target.setAttribute("aria-hidden", "false");
                    $target.setAttribute("tabindex", "0");
                });

                $target.addEventListener("hidden.bs.offcanvas", function () {
                    $target.setAttribute("aria-hidden", "true");
                    $target.setAttribute("tabindex", "-1");
                });
            }
        });

        /**
         * Back to top
         */
        var backToTop = document.getElementById('back-top');

        if (backToTop) {
            function checkScrollPos() {
                if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
                    backToTop.classList.add('visible');
                } else {
                    backToTop.classList.remove('visible')
                }
            }

            checkScrollPos();

            window.onscroll = function () {
                checkScrollPos();
            };

            backToTop.addEventListener('click', function (event) {
                event.preventDefault();
                window.scrollTo(0, 0);
            });
        }

        /**
         * Cookie consent
         */
        var CookieConsent = document.getElementById('VPCookieConsent');

        if (CookieConsent) {
            var cookieTenure = CookieConsent.dataset.tenure || 30;
            var cookieName = '_vp_cookie_consent';
            var hasConsent = tmpl.getCookie(cookieName, 0);

            if (!hasConsent) {
                CookieConsent.classList.remove('vp-hide');

                setTimeout(function () {
                    CookieConsent.classList.remove('vp-fade');
                    CookieConsent.setAttribute('aria-hidden', 'false');
                    CookieConsent.setAttribute('tabindex', '0');
                }, 500);
            }

            [].slice.call(CookieConsent.querySelectorAll('[data-btn="cookieconsent"]')).forEach(function (consentBtn) {
                consentBtn.addEventListener('click', function (event) {
                    event.preventDefault();
                    tmpl.setCookie(cookieName, 1, cookieTenure);
                    CookieConsent.classList.add('vp-fade');

                    setTimeout(function () {
                        CookieConsent.classList.add('vp-hide');
                        CookieConsent.setAttribute('aria-hidden', 'true');
                        CookieConsent.setAttribute('tabindex', '-1');
                    }, 500);
                })
            });
        }

        /**
         * Convert rem to pixels
         */
        var convertRemToPixels = function (rem) {
            return rem * parseFloat(getComputedStyle(document.documentElement).fontSize);
        }

        /**
         * Add special class to header when it is sticky
         */
        var headerContainer = document.querySelector('.header-content');
        var topbarContainer = document.querySelector('.top-bar-content');
        var scrollTop, topBarHeight, scrollTimeout;
        var stickyTop, currentTop;

        if (headerContainer && headerContainer.classList.contains('sticky-top')) {
            var headerDiff = convertRemToPixels(2) - convertRemToPixels(1.2);

            var addShadowToHeader = function () {
                if (topbarContainer) {
                    if (!document.body.classList.contains('header-is-sticky')) {
                        topBarHeight = topbarContainer.getBoundingClientRect().height;
                        document.body.dataset.headerHeight = topBarHeight;
                    } else {
                        topBarHeight = document.body.dataset.headerHeight ? document.body.dataset.headerHeight : topbarContainer.getBoundingClientRect().height;
                    }
                } else {
                    topBarHeight = 0;
                }

                topBarHeight = parseFloat(topBarHeight);
                scrollTop = window.scrollY || document.documentElement.scrollTop;
                scrollTop = parseFloat(scrollTop);
                stickyTop = parseFloat(window.getComputedStyle(headerContainer).top);
                currentTop = parseFloat(headerContainer.getBoundingClientRect().top);

                if (stickyTop >= currentTop && scrollTop > topBarHeight + (headerDiff * 2)) {
                    document.body.classList.add('header-is-sticky');
                } else if ((topBarHeight > 0 && scrollTop <= topBarHeight - headerDiff) || scrollTop === 0) {
                    document.body.classList.remove('header-is-sticky');
                }
            }

            addShadowToHeader();

            window.addEventListener('scroll', function () {
                if (scrollTimeout) {
                    clearTimeout(scrollTimeout);
                }

                scrollTimeout = setTimeout(addShadowToHeader, 10);
            });
        }

        // Initialize tab links
        tmpl.initTabLinks();
    }

    document.addEventListener('DOMContentLoaded', function (event) {
        tmpl.initTemplate(event);
        tmpl.initProducts();
        tmpl.initLazyLoad();

        const filterResultsContainer = document.getElementById('bd_results');

        if (filterResultsContainer) {
            [].slice.call(filterResultsContainer.querySelectorAll('.category-view')).forEach(function (categoryView) {
                var observer = new MutationObserver(function (mutations) {
                    mutations.forEach(function (mutation) {
                        if (mutation.type === 'childList') {
                            if (mutation.removedNodes.length === 0) {
                                return;
                            }
    
                            document.dispatchEvent(new Event('joomla:updated'));
                            document.dispatchEvent(new Event('product:updated'));
                        }
                    });
                });
    
                observer.observe(categoryView, {
                    childList: true,
                    subtree: true
                });
            });
        }
    });

    /**
     * Initialize when a part of the page was updated
     */
    var joomlaUpdateTimeout;
    var productUpdateTimeout;

    document.addEventListener('joomla:updated', function (event) {
        if (joomlaUpdateTimeout) {
            clearTimeout(joomlaUpdateTimeout);
        }

        joomlaUpdateTimeout = setTimeout(function () {
            tmpl.initTemplate(event);
        }, 100);
    });

    document.addEventListener('product:updated', function (event) {
        if (productUpdateTimeout) {
            clearTimeout(productUpdateTimeout);
        }

        productUpdateTimeout = setTimeout(function () {
            tmpl.initProducts(event);
            tmpl.initLazyLoad(event);
        }, 100);
    });

    /**
     * Initialize when a part of the page was updated by VirtueMart and triggered jQuery events.
     */
    if (typeof jQuery != 'undefined') {
        jQuery('body').on('updateVirtueMartProductDetail', function(event) {
            document.dispatchEvent(new Event('product:updated'));
        });
    }

})(Joomla, Neoteric, document, window);
