/**
 * BrewmyApp – Cart Sync (Frontend)
 *
 * Keeps the WooCommerce mini-cart fragments in sync with changes
 * made from the mobile app (or any external source).
 *
 * Only triggers `wc_fragment_refresh` which is a READ-ONLY operation
 * (fetches fresh mini-cart HTML from the server).
 *
 * We intentionally do NOT trigger `wc_update_cart` or `updated_wc_div`
 * because those are WRITE operations that re-submit the cart form and
 * can race with user-initiated removals, causing removed items to
 * reappear.
 */
(function ($) {
  "use strict";

  var lastRefresh = 0;
  var COOLDOWN = 5000; // 5 seconds — avoid excessive AJAX calls

  function refreshCartFragments() {
    var now = Date.now();
    if (now - lastRefresh < COOLDOWN) return;
    lastRefresh = now;

    // Nuke cached fragments so WC fetches fresh ones
    try {
      sessionStorage.removeItem("wc_fragments");
      sessionStorage.removeItem("wc_cart_created");
    } catch (e) {
      /* sessionStorage may be unavailable */
    }

    // Tell WooCommerce to re-fetch cart fragments (mini-cart, etc.)
    // This is read-only — it does NOT modify the cart on the server.
    $(document.body).trigger("wc_fragment_refresh");
  }

  // ── Tab visibility change (covers most desktop + mobile browsers)
  document.addEventListener("visibilitychange", function () {
    if (document.visibilityState === "visible") {
      refreshCartFragments();
    }
  });

  // ── Window focus (catches alt-tab and some edge cases)
  $(window).on("focus", function () {
    refreshCartFragments();
  });
})(jQuery);
