/**
 * Recently Viewed Products Tracking
 *
 * Tracks product views via cookies for the Recently Viewed widget.
 *
 * @package GGM_Commerce
 */

(function($) {
    'use strict';

    var config = window.ggmcRecentlyViewed || {};
    var hasTracked = false;

    /**
     * Get cookie value by name.
     *
     * @param {string} name Cookie name.
     * @returns {string|null} Cookie value or null.
     */
    function getCookie(name) {
        var nameEQ = name + '=';
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) === 0) {
                return decodeURIComponent(c.substring(nameEQ.length, c.length));
            }
        }
        return null;
    }

    /**
     * Set cookie value.
     *
     * @param {string} name  Cookie name.
     * @param {string} value Cookie value.
     * @param {number} days  Expiration in days.
     */
    function setCookie(name, value, days) {
        var expires = '';
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = '; expires=' + date.toUTCString();
        }
        var path = config.cookiePath || '/';
        document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=' + path + '; SameSite=Lax';
    }

    /**
     * Get recently viewed product IDs from cookie.
     *
     * @returns {Array} Array of product IDs.
     */
    function getViewedProductIds() {
        var cookieValue = getCookie(config.cookieName);
        if (!cookieValue) {
            return [];
        }
        try {
            var ids = JSON.parse(cookieValue);
            if (Array.isArray(ids)) {
                return ids.map(function(id) {
                    return parseInt(id, 10);
                }).filter(function(id) {
                    return id > 0;
                });
            }
        } catch (e) {
            // Silent fail - cookie may be corrupted.
        }
        return [];
    }

    /**
     * Save recently viewed product IDs to cookie.
     *
     * @param {Array} ids Array of product IDs.
     */
    function saveViewedProductIds(ids) {
        var value = JSON.stringify(ids);
        setCookie(config.cookieName, value, config.cookieExpiration || 30);
    }

    /**
     * Add a product ID to recently viewed.
     *
     * @param {number} productId Product ID to add.
     */
    function addViewedProduct(productId) {
        productId = parseInt(productId, 10);
        if (!productId || productId <= 0) {
            return;
        }

        var viewedIds = getViewedProductIds();

        // Remove if already exists (we'll add to front).
        var existingIndex = viewedIds.indexOf(productId);
        if (existingIndex > -1) {
            viewedIds.splice(existingIndex, 1);
        }

        // Add to front (most recent first).
        viewedIds.unshift(productId);

        // Limit to max products.
        var maxProducts = config.maxProducts || 20;
        if (viewedIds.length > maxProducts) {
            viewedIds = viewedIds.slice(0, maxProducts);
        }

        saveViewedProductIds(viewedIds);
        hasTracked = true;
    }

    /**
     * Track current product if not already tracked.
     */
    function trackCurrentProduct() {
        if (hasTracked) {
            return;
        }
        // Re-read config in case it was updated by footer script.
        config = window.ggmcRecentlyViewed || {};
        if (config.currentProductId && config.currentProductId > 0) {
            addViewedProduct(config.currentProductId);
        }
    }

    // Track on DOM ready (in case product ID was set early).
    $(document).ready(function() {
        trackCurrentProduct();
    });

    // Also track on window load (in case footer script updated the ID after DOM ready).
    $(window).on('load', function() {
        trackCurrentProduct();
    });

    // Expose API for external use and for footer script to trigger tracking.
    window.ggmcRecentlyViewedAPI = {
        addProduct: addViewedProduct,
        getProductIds: getViewedProductIds,
        trackCurrent: trackCurrentProduct
    };

})(jQuery);
