/**
 * `aieo/free-shipping-pdp` — view script.
 *
 * Keeps the bar in sync with the cart on every cart change. Listens
 * to:
 *   - `updated_cart_totals` (jQuery, fires on WC AJAX add-to-cart)
 *   - `wc_fragments_refreshed` (jQuery, fires after fragments AJAX
 *     completes — covers the variations-form add path)
 *   - `added_to_cart` (jQuery, fires from the `Add to Cart` button on
 *     the PDP itself)
 *   - `aieo:cart:updated` (custom event the AIEO side-cart fires after
 *     it has computed fresh totals — preferred when present, since it
 *     means the side cart already has fresh totals locally)
 *
 * On any of these, we POST to `wc-ajax=aieo_fs_pdp_state` for the
 * fresh `{message_html, fill_percent, qualified}` triple. Server is the
 * single source of truth for message-template interpolation and
 * tax-mode handling — keeps the JS thin.
 *
 * Self-throttle: dedupe identical-cart-hash refetches within 500ms so
 * a burst of events (some plugins fire 4+ on a single add) only hits
 * the network once.
 */
(function ($) {
    'use strict';

    if (!$ || !$.fn) { return; }

    var endpoint = (function () {
        // wc-ajax endpoint pattern; falls back to admin-ajax with our
        // custom action if WC's wc_ajax_url isn't on the page (e.g. in
        // an iframe context).
        if (window.wc_add_to_cart_params && window.wc_add_to_cart_params.wc_ajax_url) {
            return window.wc_add_to_cart_params.wc_ajax_url.replace('%%endpoint%%', 'aieo_fs_pdp_state');
        }
        return '/wp-admin/admin-ajax.php?action=aieo_fs_pdp_state';
    })();

    var lastFetchAt = 0;

    function $bars() { return $('[data-aieo-fs-pdp]'); }

    function refresh() {
        var $els = $bars();
        if (!$els.length) { return; }

        var now = Date.now();
        if (now - lastFetchAt < 400) { return; }
        lastFetchAt = now;

        $.get(endpoint).done(function (resp) {
            if (!resp || resp.success !== true || !resp.data) { return; }
            var d = resp.data;
            $els.each(function () {
                var $w = $(this);
                var $msg = $w.find('[data-aieo-fs-pdp-msg]').first();
                var $fill = $w.find('[data-aieo-fs-pdp-fill]').first();
                if ($msg.length && typeof d.message_html === 'string') {
                    $msg.html(d.message_html);
                }
                if ($fill.length && typeof d.fill_percent === 'number') {
                    $fill.css('width', Math.max(0, Math.min(100, d.fill_percent)) + '%');
                }
                $w.attr('aria-valuenow', String(d.fill_percent || 0));
                $w.removeClass('aieo-fs-pdp--qualified aieo-fs-pdp--progress')
                  .addClass(d.qualified ? 'aieo-fs-pdp--qualified' : 'aieo-fs-pdp--progress');
            });
        });
    }

    $(document.body).on(
        'updated_cart_totals wc_fragments_refreshed added_to_cart aieo:cart:updated',
        refresh
    );

    // First sync on load — the server already painted the correct
    // state from PHP, but if the side-cart loaded a session that
    // diverges from this page's render context (e.g. tab restored
    // from history), reconcile once.
    $(function () {
        if ($bars().length) { refresh(); }
    });

})(jQuery);
