import type {
  StorefrontCart,
  StorefrontWishlist,
  StorefrontWishlistItem,
} from "@/types/storefront";

export const STOREFRONT_CART_UPDATED = "shop-starter:cart-updated";
export const STOREFRONT_WISHLIST_UPDATED = "shop-starter:wishlist-updated";
export const STOREFRONT_WISHLIST_ADDED = "shop-starter:wishlist-added";

export type StorefrontCartUpdateReason =
  | "add-item"
  | "update-item"
  | "remove-item"
  | "move-to-wishlist";

export function dispatchStorefrontCartUpdated(
  cart: StorefrontCart,
  reason: StorefrontCartUpdateReason = "update-item",
) {
  if (typeof window === "undefined") {
    return;
  }

  window.dispatchEvent(
    new CustomEvent(STOREFRONT_CART_UPDATED, {
      detail: { cart, count: cart.itemCount, reason },
    }),
  );
}

export function dispatchStorefrontWishlistUpdated(wishlist: StorefrontWishlist) {
  if (typeof window === "undefined") {
    return;
  }

  window.dispatchEvent(
    new CustomEvent(STOREFRONT_WISHLIST_UPDATED, {
      detail: { wishlist, count: wishlist.itemCount },
    }),
  );
}

export function dispatchStorefrontWishlistAdded(item: StorefrontWishlistItem) {
  if (typeof window === "undefined") {
    return;
  }

  window.dispatchEvent(
    new CustomEvent(STOREFRONT_WISHLIST_ADDED, {
      detail: { item },
    }),
  );
}
