/**
 * ISC License
 *
 * Copyright (c) 2026 idnovate.com
 * idnovate is a Registered Trademark & Property of idnovate.com, innovación y desarrollo SCP
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 * @author    idnovate
 * @copyright 2026 idnovate.com
 * @license   https://www.isc.org/licenses/ https://opensource.org/licenses/ISC ISC License
 */

function getQueryString() {
  var key = false, res = {}, itm = null;
  // get the query string without the ?
  var qs = location.search.substring(1);
  // check for the key as an argument
  if (arguments.length > 0 && arguments[0].length > 1)
    key = arguments[0];
  // make a regex pattern to grab key/value
  var pattern = /([^&=]+)=([^&]*)/g;
  // loop the items in the query string, either
  // find a match to the argument, or build an object
  // with key/value pairs
  while (itm = pattern.exec(qs)) {
    if (key !== false && decodeURIComponent(itm[1]) === key)
      return decodeURIComponent(itm[2]);
    else if (key === false)
      res[decodeURIComponent(itm[1])] = decodeURIComponent(itm[2]);
  }

  return key === false ? res : null;
}

/***** EVENTS ******/
/**
 * 1 = On load
 * 2 = When product added to the cart
 * 3 = Exit popup
 * 4 = On element click
 * 5 = Inactivity
*/

$(document).ready(function() {
    // Preview popup
    if (getQueryString('previewPopup')) {
        displayPopup(getQueryString('popupId'));
        return;
    }

    updateVisits();

    if (typeof prestashop != 'undefined'
        && typeof jprestaPcProcessDynamicModules == 'function') {
        prestashop.on(
            'jprestaDynamicContentLoaded',
            function () {
                // 1 = On load
                getPopup(1);

                // 4 = On element click
                getPopup(4);

                // 5 = Inactivity
                getPopup(5);
            }
        );
    } else {
        // 1 = On load
        getPopup(1);

        // 4 = On element click
        getPopup(4);

        // 5 = Inactivity
        getPopup(5);
    }

    // 2 = When product added to the cart
    if (typeof ajaxCart !== "undefined") {
        ajaxCart.add = (function() {
            var ajaxCartaddCached = ajaxCart.add;
            return function(idProduct) {
                ajaxCartaddCached.apply(this, arguments);
                setTimeout(function() {
                    productAddedToTheCart(idProduct);
                }, 100)
            }
        })();
    } else if (typeof prestashop !== "undefined") {
        prestashop.on(
            'updateCart',
            function (event) {
                if (event.reason.linkAction == "add-to-cart") {
                    productAddedToTheCart(event.reason.idProduct,  event.reason.idProductAttribute);
                }
            }
        );

        prestashop.on(
            'stUpdateCart',
            function (event) {
                if (event.reason.linkAction == "add-to-cart") {
                    productAddedToTheCart(event.reason.idProduct, event.reason.idProductAttribute);
                }
            }
        );

        //phbuscadorllantas
        $('body').on('click', '.add1', function() {
            idProduct = $(this).parents('.product-actions').find('input[name="id_product"]').val();
            productAddedToTheCart(idProduct);
        });

    } else if ($('#layer_cart').length || $('.layer_cart_overlay').length || /*$('.blockcart').length ||*/ $('.mfp-container').length) {
        $(document).on('click', '#layer_cart .cross, #layer_cart .continue, .layer_cart_overlay, #blockcart-modal, .mfp-container', function() {
            productAddedToTheCart();
        });

        /*$('.ajax_add_to_cart_button span, .add-to-cart').on('click', function(){
            getPopup(2);
        });
        prestashop.on(
            'stUpdateCart',
            function() { getPopup(2); }
        );*/
    } else {
        $(document).on('click', '.add-to-cart, .product-add-to-cart', function(){
            productAddedToTheCart();
        });
    }

    // 3 = Exit popup
    if (apc_exit_popups) {
        _html = document.documentElement;
        _html.addEventListener('mouseout', handleMouseleave);
    }

    // Add event listeners for user activity
    window.addEventListener('mousemove', startInactivityTimers);
    window.addEventListener('keydown', startInactivityTimers);
    window.addEventListener('scroll', startInactivityTimers);
    window.addEventListener('click', startInactivityTimers);
});

// Array to hold timeout IDs for each inactivity timer
let inactivityTimers = [];
let inactivityActions = [];

// Function to reset all inactivity timers
function startInactivityTimers() {
    // Clear existing timers
    inactivityTimers.forEach(timer => clearTimeout(timer));
    inactivityTimers = [];

    // Set new timers based on the configured durations
    inactivityActions.forEach(({ duration, action }) => {
        const timerId = setTimeout(action, duration);
        inactivityTimers.push(timerId);
    });
}

function productAddedToTheCart(idProduct, idProductAttribute) {
    getPopup(2, idProduct, idProductAttribute);
}

function handleMouseleave(e) {
    e = e ? e : window.event;

    // If this is an autocomplete element.
    if (e.target.tagName.toLowerCase() === "input"
        || e.target.tagName.toLowerCase() === "select") {
        return;
    }
    // Get the current viewport width.
    var vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

    // If the current mouse X position is within 50px of the right edge
    // of the viewport, return.
    if (e.clientX >= (vpWidth - 50)) {
        return;
    }

    // If the current mouse Y position is not within 50px of the top
    // edge of the viewport, return.
    if (e.clientY >= 50) {
        return;
    }

    // Reliable, works on mouse exiting window and
    // user switching active program
    var from = e.relatedTarget || e.toElement;
    if (!from) {
        getPopup(3);
    }

    //_html.removeEventListener('mouseleave', handleMouseleave);
}

function updateVisits() {
    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: apc_link,
        async: true,
        cache: false,
        dataType : "json",
        data: {
            token: apc_token,
            responsiveWidth: window.innerWidth,
            url: encodeURIComponent(window.location.href),
            referrer: encodeURIComponent(document.referrer),
            updateVisits: 1,
            time: (new Date()).getTime(),
            fromController: apc_controller,
            id_product: apc_product,
            id_category: apc_category,
            id_manufacturer: apc_manufacturer,
            id_supplier: apc_supplier,
            id_cms: apc_cms,
        },
        error: function(errorThrown)
        {
            console.log(errorThrown);
        }
    });
}

function getPopup(event, idProduct, idProductAttribute) {
    var availablePopups = [];
    $('.apc_modal').each (function () { availablePopups.push($(this).data('popupId')); });
    availablePopups = availablePopups.join(',');

    if (!availablePopups) {
        return;
    }

    if (!idProduct) {
        idProduct = apc_product;
    }

    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: apc_link,
        async: true,
        cache: false,
        dataType : "json",
        data: {
            token: apc_token,
            responsiveWidth: window.innerWidth,
            url: encodeURIComponent(window.location.href),
            referrer: encodeURIComponent(document.referrer),
            getPopup: 1,
            event: event,
            time: (new Date()).getTime(),
            fromController: apc_controller,
            id_product: idProduct,
            id_product_attribute: idProductAttribute,
            id_category: apc_category,
            id_manufacturer: apc_manufacturer,
            id_supplier: apc_supplier,
            availablePopups: availablePopups
        },
        success: function(jsonData)
        {
            if (!jsonData.hasError && typeof jsonData.popups != "undefined") {
                $.each(jsonData.popups, function(i, item) {
                    var popup = JSON.parse(item);
                    if (event === 4 && popup.selector) {
                        // Clean the selector directly inline
                        let selector = popup.selector;
                        const match = selector.trim().match(/^\$\(\s*(['"])(.*?)\1\s*\)$/);
                        if (match) {
                            selector = match[2]; // Extract the actual CSS selector
                        }

                        $(selector).css('cursor', 'pointer');
                        $(selector).on('click touch', function (event) {
                            displayPopup(popup.id, event);
                        });
                    } else if (event === 5) {
                        inactivityActions = [
                            //{ duration: popup.secs_to_display_inactive * 1000, action: () => displayPopup(popup.id, event) },  // 5 seconds
                        ];

                        // Initialize or reset the inactivity timers based on the response
                        startInactivityTimers();
                    } else {
                        displayPopup(popup.id, event);
                    }
                });
            }
        },
        error: function(errorThrown)
        {
            console.log(errorThrown);
        }
    });
}

function displayPopup(popupId, event) {
    let modalElement = $('#apcModal_' + popupId);

    // Exit if modalElement doesn't exist
    if (!modalElement.length) {
        console.log('#apcModal_'+popupId+' not found');
        return;
    }

    if ($('[id="apcModal_1"]').length > 1) {
        console.log('%cPopup is duplicated', 'background: red; color: white');
    }

    var popupProperties = modalElement.data();

    var secsDisplay = 0;
    if (event === 1) {
        if (popupProperties.secsDisplay) {
            secsDisplay = popupProperties.secsDisplay;
        }
    }

    if (event === 2) {
        if (popupProperties.secsDisplayCart) {
            secsDisplay = popupProperties.secsDisplayCart;
        }
    }

    let myModal = modalElement.modal({
        backdrop: popupProperties.bsBackdrop,
        keyboard: popupProperties.bsKeyboard,
        scroll: true, // Allow scrolling
        show: false // Prevent automatic display
    });

    // Before shown callback
    modalElement.on('show.bs.modal', function () {
        // Another modal is already open
        if ($('.modal.in, .modal.show').length > 0) {
            // Adjust z-index dynamically
            $('.modal-backdrop.show, .modal-backdrop.in').css('z-index', 1051);
            modalElement.css('z-index', 1052);
        }

        // Bug with Uniform
        if (typeof $.fn.uniform === 'function') {
            $("select.form-control,input[type='checkbox']:not(.comparator), input[type='radio'],input#id_carrier2, input[type='file']").not(".not_unifrom, .not_uniform").uniform();
        }

        if (popupProperties.blurBackground) {
            $("main, header, body > section, footer, #page").addClass("apc-effect-blur");
        }

        if (!getQueryString('previewPopup')) {
            $.ajax({
                type: 'POST',
                headers: {"cache-control": "no-cache"},
                url: apc_link,
                async: true,
                cache: false,
                dataType: "json",
                data: 'markAsSeen=1&popupId=' + popupProperties.popupId + '&time=' + (new Date()).getTime() + '&token=' + apc_token
            });
        }

        if (typeof AdvancedPopupBeforeShowCallback == 'function') {
            AdvancedPopupBeforeShowCallback(myModal);
        }
    });

    // After shown callback
    modalElement.on('shown.bs.modal', function () {
        // 1. Desactivar el foco nativo de Bootstrap 3
        $(document).off('focusin.bs.modal');

        const themeLink = document.querySelector('link[href*="/themes/"]');

        if (themeLink) {
            const match = themeLink.href.match(/\/themes\/([^\/]+)\//);
            const themeName = match ? match[1] : "";

            console.log("Tema detectado:", themeName);

            // CORRECCIÓN: Usar themeName para la comparación
            if (themeName === 'warehouse') {

                document.addEventListener('focusin', function(e) {
                    // Buscamos modales de Bootstrap 3 (.in) o Bootstrap 4/5 (.show)
                    var modalAbierto = document.querySelector('.modal.in, .modal.show');

                    if (modalAbierto && !modalAbierto.contains(e.target)) {
                        e.stopImmediatePropagation();
                    }
                }, true); // El 'true' es fundamental para la fase de captura
            }
        }

        if (typeof AdvancedPopupAfterShowCallback == 'function') {
            AdvancedPopupAfterShowCallback(myModal);
        }
    });

    // Before hidden callback
    modalElement.on('hide.bs.modal', function () {
        if (typeof AdvancedPopupBeforeHideCallback == 'function') {
            AdvancedPopupBeforeHideCallback(myModal);
        }
    });


    // Close popup when clicking backdrop
    if (popupProperties.closeOnBackground) {
        modalElement.on('click', function (event) {
            let modalDialog = modalElement[0].querySelector('.modal-dialog');

            // Check if the click was outside the modal dialog
            if (!modalDialog.contains(event.target)) {
                // Close the modal
                modalElement.modal('hide');
            }
        });
    }

    // Set the correct opacity to the backdrop
    if (popupProperties.bsBackdrop !== false) {
        // Delay to ensure the backdrop is created before modifying its opacity
        let intervalId = setInterval(function () {
            let backdrop = document.querySelector('.modal-backdrop.show');
            if (backdrop) {
                backdrop.style.opacity = popupProperties.opacity;
                clearInterval(intervalId); // Stop the interval once the condition is met
            }
        }, 10);
    } else {
        modalElement.css('height', '0');
        modalElement.css('width', '0');
    }

    // Enable Page Scrolling
    if (popupProperties.locked) {
        modalElement.on('shown.bs.modal', function () {
            // Remove the modal-open class
            document.body.classList.remove('modal-open');

            // Reset inline styles for overflow and padding-right
            document.body.style.overflow = ''; // Allow scrolling
            document.body.style.paddingRight = ''; // Remove padding-right adjustment
        });
    }

    modalElement.on('hidden.bs.modal', function () {
        if (popupProperties.blurBackground) {
            $("main, header, body > section, footer, #page").removeClass("apc-effect-blur");
        }

        if (typeof AdvancedPopupAfterHideCallback == 'function') {
            AdvancedPopupAfterHideCallback(myModal);
        }

        // Remove any remaining backdrop elements
        // document.querySelectorAll('.modal-backdrop').forEach(function (backdrop) {
        //    backdrop.remove();
        // });

        if ($('.modal.in, .modal.show').length > 0) {
            // Adjust z-index dynamically
            $('.modal-backdrop.show, .modal-backdrop.in').css('z-index', 1049);

            // Append a new backdrop
            // let $backdrop = $('<div class="modal-backdrop fade show in"></div>');
            // $('body').append($backdrop);
        }

        // Ensure the page becomes scrollable again
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.body.style.paddingRight = '';
    });

    // Display sticky block
    /* if (popupProperties.stickyDisplayClose) {
        modalElement.on('hidden.bs.modal', function () {
          document.getElementById('stickyBlock_' + popupId).style.visibility = 'visible';
        });

        modalElement.on('shown.bs.modal', function () {
            document.getElementById('stickyBlock_' + popupId).style.visibility = 'hidden';
        });
    }*/

    if (popupProperties.secsClose > 0) {
        // https://medium.com/@volochkov/how-to-create-countdown-timer-on-pure-css-2c0460391a32
        let endTime = new Date().getTime() + popupProperties.secsClose * 1000; // Calculate end time

        let interval = setInterval(() => {
            let timeLeft = endTime - new Date().getTime(); // Remaining time in milliseconds

            if (timeLeft > 0) {
                let progress = 1 - timeLeft / (popupProperties.secsClose * 1000); // Calculate progress

                // Update CSS variable for circular progress
                document.documentElement.style.setProperty(
                    '--inner_percent_deg',
                    Math.round(progress * 10000) / 100 + "%"
                );
            } else {
                myModal.modal('hide');
                clearInterval(interval); // Stop the timer
            }
        }, 16);
    }

    setTimeout(function() {
        myModal.modal('show');
    }, secsDisplay);
}

function apcResizeIframe(iframe, autoWidth) {
    function doResize() {
        try {
            var win  = iframe.contentWindow;
            var body = win.document.body;

            body.style.overflow = 'auto';

            var bodyStyle    = win.getComputedStyle(body);
            var marginTop    = parseFloat(bodyStyle.marginTop)    || 0;
            var marginBottom = parseFloat(bodyStyle.marginBottom) || 0;
            var marginLeft   = parseFloat(bodyStyle.marginLeft)   || 0;
            var marginRight  = parseFloat(bodyStyle.marginRight)  || 0;

            if (autoWidth) {
                var maxWidth       = parseInt(win.getComputedStyle(body).maxWidth);
                var scrollbarWidth = win.innerWidth - win.document.documentElement.clientWidth || 17;
                var contentWidth   = (!isNaN(maxWidth) && maxWidth > 0)
                    ? maxWidth + marginLeft + marginRight + scrollbarWidth
                    : body.offsetWidth + marginLeft + marginRight + scrollbarWidth;

                var dialog = iframe.closest('.modal-dialog');

                // Set width first, defer height so inner doc reflows at new width
                iframe.style.width = contentWidth + 'px';
                if (dialog) { dialog.style.width = contentWidth + 'px'; }

                setTimeout(function() {
                    iframe.style.height = (body.scrollHeight + marginTop + marginBottom) + 'px';
                    if (dialog) { dialog.style.opacity = '1'; }
                }, 50);
            } else {
                iframe.style.height = (body.scrollHeight + marginTop + marginBottom) + 'px';
            }

        } catch (e) {
            // Cross-origin iframe: cannot access contentWindow, skip resize
        }
    }

    try {
        // Poll iframe.contentWindow.document.body fresh each tick.
        // Brevo (and similar) call document.open()/write() which replaces the
        // entire document, so a MutationObserver on the original body reference
        // never fires — the new content lives in a brand-new document object.
        var done = false;
        var pollTimer;
        var attempts = 0;
        var maxAttempts = 100; // 10 s at 100 ms intervals

        function pollForContent() {
            attempts++;
            try {
                var win  = iframe.contentWindow;
                var body = win.document.body;
                if (body && body.scrollHeight > 20) {
                    clearInterval(pollTimer);
                    done = true;
                    doResize();
                } else if (attempts >= maxAttempts) {
                    clearInterval(pollTimer);
                    if (!done) {
                        done = true;
                        doResize();
                    }
                }
            } catch (e) {
                clearInterval(pollTimer);
                if (!done) { done = true; doResize(); }
            }
        }

        // Run first tick immediately, then every 100 ms
        pollForContent();
        if (!done) {
            pollTimer = setInterval(pollForContent, 100);
        }

    } catch (e) {
        doResize();
    }
}

