/** Shopify CDN: Minification failed

Line 6:0 Unexpected "("

**/
(() => {
  "use strict";

  if (window.__TBC_SERVING_CART_FIXED__) return;
  window.__TBC_SERVING_CART_FIXED__ = true;

  const shopRoot = window.Shopify?.routes?.root || "/";

  const cartUrl = `${shopRoot}cart.js`;
  const cartAddUrl = `${shopRoot}cart/add.js`;
  const cartUpdateUrl = `${shopRoot}cart/update.js`;

  function getSection(element) {
    return element?.closest(".tbc-serving");
  }

  function getQuantity(section) {
    return Math.max(
      1,
      Number(
        section.querySelector(".tbc-qty-number")
          ?.textContent
      ) || 1
    );
  }

  function setQuantity(section, quantity) {
    const quantityElement =
      section.querySelector(".tbc-qty-number");

    if (quantityElement) {
      quantityElement.textContent =
        Math.max(1, quantity);
    }
  }

  function updateRecommendation(section) {
    const serves =
      Number(section.dataset.serves) || 1;

    const guestInput =
      section.querySelector(".tbc-guest-input");

    const recommendation =
      section.querySelector(".tbc-rec-boxes");

    if (!guestInput || !recommendation) return;

    const guests = Math.max(
      5,
      Number(guestInput.value) || serves
    );

    recommendation.textContent = Math.max(
      1,
      Math.ceil(guests / serves)
    );
  }

  function getButtonLabel(button) {
    return (
      button.querySelector(
        "span:not(.loading__spinner)"
      ) || button
    );
  }

  function updateHeaderCartIcon(html) {
    if (!html) return;

    const currentIcon =
      document.getElementById("cart-icon-bubble");

    if (!currentIcon) return;

    const parsed = new DOMParser().parseFromString(
      html,
      "text/html"
    );

    const incomingIcon =
      parsed.getElementById("cart-icon-bubble");

    if (incomingIcon) {
      currentIcon.innerHTML =
        incomingIcon.innerHTML;
    }
  }

  async function refreshHeaderCartIcon() {
    const separator =
      window.location.pathname.includes("?")
        ? "&"
        : "?";

    const response = await fetch(
      `${window.location.pathname}${separator}sections=cart-icon-bubble`,
      {
        headers: {
          Accept: "application/json",
          "X-Requested-With": "XMLHttpRequest"
        },
        credentials: "same-origin"
      }
    );

    if (!response.ok) return;

    const sections = await response.json();

    updateHeaderCartIcon(
      sections["cart-icon-bubble"]
    );
  }

  async function getCurrentCart() {
    const response = await fetch(cartUrl, {
      headers: {
        Accept: "application/json",
        "X-Requested-With": "XMLHttpRequest"
      },
      credentials: "same-origin"
    });

    if (!response.ok) {
      throw new Error("Unable to read the cart.");
    }

    return response.json();
  }

  function forceCustomCartClosed() {
    document
      .querySelectorAll(
        [
          "cart-drawer",
          "cart-notification",
          ".drawer",
          ".cart-drawer",
          ".cart-notification",
          ".tbc-cart-drawer",
          ".custom-cart-drawer",
          "[data-cart-drawer]",
          "[data-cart-panel]"
        ].join(",")
      )
      .forEach((element) => {
        if (typeof element.close === "function") {
          try {
            element.close();
          } catch (error) {}
        }

        element.classList.remove(
          "active",
          "animate",
          "open",
          "is-open",
          "visible"
        );

        element.removeAttribute("open");
      });

    document.body.classList.remove(
      "overflow-hidden",
      "cart-open",
      "drawer-open"
    );
  }

  async function addOrMergeProduct(
    variantId,
    quantity
  ) {
    const cart = await getCurrentCart();

    const matchingItems = cart.items.filter(
      (item) =>
        Number(item.variant_id) ===
        Number(variantId)
    );

    const sectionPayload = {
      sections: ["cart-icon-bubble"],
      sections_url: window.location.pathname
    };

    let response;

    if (matchingItems.length) {
      /*
       * Combine every existing line for this variant
       * into one cart row and increase its quantity.
       */
      const existingQuantity =
        matchingItems.reduce(
          (total, item) =>
            total + Number(item.quantity || 0),
          0
        );

      const updates = {};

      updates[matchingItems[0].key] =
        existingQuantity + quantity;

      matchingItems
        .slice(1)
        .forEach((item) => {
          updates[item.key] = 0;
        });

      response = await fetch(cartUpdateUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-Requested-With": "XMLHttpRequest"
        },
        body: JSON.stringify({
          ...sectionPayload,
          updates
        }),
        credentials: "same-origin"
      });
    } else {
      response = await fetch(cartAddUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-Requested-With": "XMLHttpRequest"
        },
        body: JSON.stringify({
          ...sectionPayload,
          items: [
            {
              id: Number(variantId),
              quantity
            }
          ]
        }),
        credentials: "same-origin"
      });
    }

    const result = await response.json();

    if (!response.ok || result.status) {
      throw new Error(
        result.description ||
          result.message ||
          "Unable to add this product."
      );
    }

    if (result.sections?.["cart-icon-bubble"]) {
      updateHeaderCartIcon(
        result.sections["cart-icon-bubble"]
      );
    } else {
      await refreshHeaderCartIcon();
    }

    forceCustomCartClosed();

    window.setTimeout(forceCustomCartClosed, 50);
    window.setTimeout(forceCustomCartClosed, 250);
    window.setTimeout(forceCustomCartClosed, 700);

    return result;
  }

  async function handleAdd(button) {
    if (
      button.disabled ||
      button.dataset.tbcAdding === "true"
    ) {
      return;
    }

    const section = getSection(button);
    if (!section) return;

    const variantId = Number(
      button.dataset.variantId
    );

    if (!variantId) {
      console.error("TBC: Missing variant ID.");
      return;
    }

    const quantity = getQuantity(section);
    const label = getButtonLabel(button);
    const originalText =
      label.textContent.trim();

    button.dataset.tbcAdding = "true";
    button.disabled = true;
    button.setAttribute("aria-busy", "true");

    label.textContent = "Adding";

    try {
      await addOrMergeProduct(
        variantId,
        quantity
      );

      label.textContent = "Added";

      window.setTimeout(() => {
        label.textContent = originalText;
      }, 1200);
    } catch (error) {
      console.error(
        "TBC serving cart:",
        error
      );

      label.textContent = "Try again";

      window.setTimeout(() => {
        label.textContent = originalText;
      }, 1500);
    } finally {
      button.disabled = false;
      button.removeAttribute("aria-busy");
      delete button.dataset.tbcAdding;
    }
  }

  function prepareControls() {
    document
      .querySelectorAll(".tbc-serving")
      .forEach((section) => {
        const addButton =
          section.querySelector(".tbc-add-cart");

        const plusButton =
          section.querySelector(".tbc-plus");

        const minusButton =
          section.querySelector(".tbc-minus");

        /*
         * Prevent all three controls from submitting
         * a surrounding Shopify product form.
         */
        if (addButton) {
          addButton.type = "button";
        }

        if (plusButton) {
          plusButton.type = "button";
        }

        if (minusButton) {
          minusButton.type = "button";
        }

        updateRecommendation(section);
      });
  }

  /*
   * Capture clicks before the old direct listener
   * or Shopify product-form code can run.
   */
  window.addEventListener(
    "click",
    (event) => {
      const addButton =
        event.target.closest(".tbc-add-cart");

      const plusButton =
        event.target.closest(".tbc-plus");

      const minusButton =
        event.target.closest(".tbc-minus");

      if (addButton) {
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();

        handleAdd(addButton);
        return;
      }

      if (plusButton) {
        const section = getSection(plusButton);
        if (!section) return;

        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();

        setQuantity(
          section,
          getQuantity(section) + 1
        );

        return;
      }

      if (minusButton) {
        const section = getSection(minusButton);
        if (!section) return;

        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();

        setQuantity(
          section,
          getQuantity(section) - 1
        );
      }
    },
    true
  );

  window.addEventListener(
    "submit",
    (event) => {
      const form = event.target;

      if (
        !(form instanceof HTMLFormElement) ||
        !form.querySelector(".tbc-add-cart")
      ) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();

      const button =
        form.querySelector(".tbc-add-cart");

      if (button) {
        handleAdd(button);
      }
    },
    true
  );

  document.addEventListener(
    "input",
    (event) => {
      if (
        !event.target.matches(
          ".tbc-guest-input"
        )
      ) {
        return;
      }

      const section = getSection(event.target);

      if (section) {
        updateRecommendation(section);
      }
    }
  );

  if (document.readyState === "loading") {
    document.addEventListener(
      "DOMContentLoaded",
      prepareControls,
      { once: true }
    );
  } else {
    prepareControls();
  }

  document.addEventListener(
    "shopify:section:load",
    prepareControls
  );
})();