/* ============================================================
   SHOPIFY — Storefront GraphQL API helper
   ============================================================ */
const SHOPIFY_CART_ID_KEY = "mye_shopify_cart_id";
const SHOPIFY_CHECKOUT_URL_KEY = "mye_shopify_checkout_url";

const SHOPIFY_BUNDLE_HANDLES = {
  single: "mye-noir-single",
  duo: "mye-noir-duo",
  trio: "mye-noir-trio",
  host: "mye-noir-maison",
};

const ShopifyAPI = (() => {
  const cfg = window.MYE_SHOPIFY_ENV || {};
  const variantCache = {};

  const apiVersion = cfg.apiVersion || "2026-04";
  const storeDomain = (cfg.storeDomain || "").replace(/^https?:\/\//, "").replace(/\/$/, "");
  const endpoint = storeDomain ? `https://${storeDomain}/api/${apiVersion}/graphql.json` : "";

  function assertConfigured() {
    if (!storeDomain || !cfg.storefrontAccessToken) {
      throw new Error("Shopify is not configured. Add VITE_SHOPIFY_STORE_DOMAIN and VITE_SHOPIFY_STOREFRONT_ACCESS_TOKEN in Vercel.");
    }
  }

  async function graphql(query, variables = {}) {
    assertConfigured();
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Shopify-Storefront-Access-Token": cfg.storefrontAccessToken,
      },
      body: JSON.stringify({ query, variables }),
    });
    const json = await response.json();
    if (!response.ok || json.errors) {
      const message = json.errors ? json.errors.map((e) => e.message).join("; ") : `Shopify request failed (${response.status})`;
      throw new Error(message);
    }
    return json.data;
  }

  async function getProducts() {
    const data = await graphql(`
      query GetProducts {
        products(first: 20) {
          nodes {
            id
            title
            handle
            featuredImage { url altText }
            variants(first: 10) {
              nodes {
                id
                title
                availableForSale
                price { amount currencyCode }
              }
            }
          }
        }
      }
    `);
    return data.products.nodes;
  }

  function persistCart(cart) {
    if (!cart) return;
    localStorage.setItem(SHOPIFY_CART_ID_KEY, cart.id);
    localStorage.setItem(SHOPIFY_CHECKOUT_URL_KEY, cart.checkoutUrl);
  }

  async function createCartWithLines(lines) {
    const data = await graphql(`
      mutation CreateCart($lines: [CartLineInput!]!) {
        cartCreate(input: { lines: $lines }) {
          cart {
            id
            checkoutUrl
            totalQuantity
          }
          userErrors {
            field
            message
          }
        }
      }
    `, { lines });
    const errors = data.cartCreate.userErrors || [];
    if (errors.length) throw new Error(errors.map((e) => e.message).join("; "));
    persistCart(data.cartCreate.cart);
    return data.cartCreate.cart;
  }

  async function createCart(variantId, quantity = 1) {
    return createCartWithLines([{ merchandiseId: variantId, quantity }]);
  }

  async function addToCart(cartId, variantId, quantity = 1) {
    const data = await graphql(`
      mutation AddToCart($cartId: ID!, $lines: [CartLineInput!]!) {
        cartLinesAdd(cartId: $cartId, lines: $lines) {
          cart {
            id
            checkoutUrl
            totalQuantity
          }
          userErrors {
            field
            message
          }
        }
      }
    `, {
      cartId,
      lines: [{ merchandiseId: variantId, quantity }],
    });
    const errors = data.cartLinesAdd.userErrors || [];
    if (errors.length) throw new Error(errors.map((e) => e.message).join("; "));
    persistCart(data.cartLinesAdd.cart);
    return data.cartLinesAdd.cart;
  }

  async function variantIdForBundle(bundleId) {
    if (variantCache[bundleId]) return variantCache[bundleId];
    const handle = SHOPIFY_BUNDLE_HANDLES[bundleId];
    if (!handle) throw new Error(`No Shopify product handle configured for bundle "${bundleId}".`);
    const data = await graphql(`
      query BundleVariant($handle: String!) {
        product(handle: $handle) {
          title
          variants(first: 1) {
            nodes {
              id
              availableForSale
            }
          }
        }
      }
    `, { handle });
    const variant = data.product && data.product.variants.nodes[0];
    if (!variant) throw new Error(`Shopify product "${handle}" was not found or has no variants.`);
    if (!variant.availableForSale) throw new Error(`Shopify product "${data.product.title}" is not available for sale.`);
    variantCache[bundleId] = variant.id;
    return variant.id;
  }

  async function buyNow(bundleId, quantity = 1) {
    const variantId = await variantIdForBundle(bundleId);
    const cart = await createCart(variantId, quantity);
    window.location.href = cart.checkoutUrl;
  }

  async function addBundleToCart(bundleId, quantity = 1) {
    const variantId = await variantIdForBundle(bundleId);
    const existingCartId = localStorage.getItem(SHOPIFY_CART_ID_KEY);
    return existingCartId
      ? addToCart(existingCartId, variantId, quantity)
      : createCart(variantId, quantity);
  }

  async function replaceCartFromItems(items) {
    if (!items.length) {
      localStorage.removeItem(SHOPIFY_CART_ID_KEY);
      localStorage.removeItem(SHOPIFY_CHECKOUT_URL_KEY);
      return null;
    }
    const lines = await Promise.all(items.map(async (item) => ({
      merchandiseId: await variantIdForBundle(item.bundleId),
      quantity: item.qty,
    })));
    return createCartWithLines(lines);
  }

  function checkout() {
    const checkoutUrl = localStorage.getItem(SHOPIFY_CHECKOUT_URL_KEY);
    if (!checkoutUrl) throw new Error("No Shopify checkout is available yet. Add a product to cart first.");
    window.location.href = checkoutUrl;
  }

  return {
    getProducts,
    createCart,
    addToCart,
    buyNow,
    addBundleToCart,
    replaceCartFromItems,
    checkout,
    isConfigured: () => Boolean(storeDomain && cfg.storefrontAccessToken),
  };
})();

Object.assign(window, {
  ShopifyAPI,
  getProducts: ShopifyAPI.getProducts,
  createCart: ShopifyAPI.createCart,
  addToCart: ShopifyAPI.addToCart,
});
