// ============================================================
// Casa IS — Shopify integration (cart permalink approach)
// No Storefront Access Token needed — uses direct cart URLs
// Upgrade path: swap to Shopify Buy SDK when token is available
// ============================================================

const SHOP_CONFIG = {
  domain: 'casa-is.myshopify.com',
  // When Storefront Access Token is available, add it here:
  // storefrontToken: 'YOUR_TOKEN_HERE',
};

// Cart state management
function useCart() {
  const [items, setItems] = React.useState(() => {
    try {
      return JSON.parse(localStorage.getItem('casais_cart') || '[]');
    } catch { return []; }
  });

  React.useEffect(() => {
    localStorage.setItem('casais_cart', JSON.stringify(items));
  }, [items]);

  const addItem = (product, variant) => {
    setItems(prev => {
      const key = variant?.id || product.id;
      const existing = prev.find(i => i.key === key);
      if (existing) {
        return prev.map(i => i.key === key ? { ...i, quantity: i.quantity + 1 } : i);
      }
      return [...prev, {
        key,
        productId: product.shopifyId,
        variantId: variant?.id,
        title: typeof product.title === 'object' ? product.title.en : product.title,
        variantTitle: variant?.title || '',
        price: variant?.price || product.price,
        quantity: 1,
        image: product.image,
      }];
    });
  };

  const removeItem = (key) => {
    setItems(prev => prev.filter(i => i.key !== key));
  };

  const updateQuantity = (key, quantity) => {
    if (quantity <= 0) return removeItem(key);
    setItems(prev => prev.map(i => i.key === key ? { ...i, quantity } : i));
  };

  const clearCart = () => setItems([]);

  const count = items.reduce((sum, i) => sum + i.quantity, 0);

  // Build Shopify cart permalink for checkout
  // Format: https://casais.studio/cart/variantId:quantity,variantId:quantity
  const checkoutUrl = () => {
    if (items.length === 0) return null;
    const lineItems = items
      .filter(i => i.variantId)
      .map(i => `${i.variantId}:${i.quantity}`)
      .join(',');
    if (!lineItems) return `https://${SHOP_CONFIG.domain}`;
    return `https://${SHOP_CONFIG.domain}/cart/${lineItems}`;
  };

  const goToCheckout = () => {
    const url = checkoutUrl();
    if (url) window.open(url, '_blank');
  };

  return { items, addItem, removeItem, updateQuantity, clearCart, count, goToCheckout, checkoutUrl };
}

// Quick-add: redirect directly to Shopify checkout for a single product
function quickBuy(shopifyHandle) {
  if (shopifyHandle) {
    window.open(`https://${SHOP_CONFIG.domain}/products/${shopifyHandle}`, '_blank');
  }
}

Object.assign(window, { SHOP_CONFIG, useCart, quickBuy });
