(function($){
  // Wire product buy buttons
  // Preferred: data-product-id (server will derive price/currency/merchant)
  // Legacy fallback: data-merchant, data-amount, data-name, data-desc
  $(document).on('click', '[data-vmo-buy], .vmo-pay-trigger', async function(e){
    e.preventDefault();
    if (!window.vmo_ajax || !vmo_ajax.payments_enabled) {
      if (typeof showToast === 'function') showToast('Payments disabled.', 'warning');
      return;
    }
    const $btn = $(this);
    let product_id = parseInt($btn.data('productId') || $btn.data('product-id'), 10);
    if (!product_id) {
      const href = ($btn.attr('href') || '').toString();
      if (href.includes('vmo_buy_product=')) {
        try {
          const parsed = new URL(href, window.location.origin);
          product_id = parseInt(parsed.searchParams.get('vmo_buy_product'), 10);
        } catch(err) {
          product_id = 0;
        }
      }
    }
    const merchant_user_id = parseInt($btn.data('merchant'), 10); // legacy
    const amount_cents = parseInt($btn.data('amount'), 10); // legacy
    const name = ($btn.data('name')||'Product').toString(); // legacy
    const description = ($btn.data('desc')||'').toString(); // legacy
    const currency = ($btn.data('currency')||'usd').toString(); // legacy
    const success_url = window.location.href.split('#')[0] + (window.location.search ? '&' : '?') + 'checkout=success';
    const cancel_url  = window.location.href.split('#')[0] + (window.location.search ? '&' : '?') + 'checkout=cancel';
  const idempotency_key = 'web_'+Date.now()+'_'+Math.random().toString(36).slice(2);

    try {
      const res = await fetch((window.wpApiSettings?.root || window.location.origin + '/wp-json/') + 'vmo-builder/v1/stripe/connect/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(product_id ?
          { product_id, success_url, cancel_url, idempotency_key } :
          { merchant_user_id, amount_cents, name, description, currency, success_url, cancel_url, idempotency_key }
        )
      });
      const data = await res.json();
      if (res.ok && data.url) {
        window.location.href = data.url;
      } else {
        if (typeof showToast === 'function') showToast(data.message || 'Checkout failed', 'error');
      }
    } catch(err) {
      if (typeof showToast === 'function') showToast('Network error starting checkout', 'error');
    }
  });
})(jQuery);
