@nextblock-cms/ecom 0.0.10 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/actions.d.ts +2 -0
  2. package/currency-rest-client-CwoqdgAP.js +23 -0
  3. package/currency-rest-client-uolJxUkL.cjs +1 -0
  4. package/index.cjs.js +1 -0
  5. package/index.d.ts +35 -0
  6. package/index.es.js +3226 -0
  7. package/invoice-ui-BJZfedDd.cjs +332 -0
  8. package/invoice-ui-GJ1ADAjn.js +5759 -0
  9. package/lib/CurrencyProvider.d.ts +18 -0
  10. package/lib/cart-store.d.ts +47 -0
  11. package/lib/components/AccountNavigationMenu.d.ts +14 -0
  12. package/lib/components/AddToCartButton.d.ts +8 -0
  13. package/lib/components/Cart.d.ts +1 -0
  14. package/lib/components/CartDrawer.d.ts +1 -0
  15. package/lib/components/CartIcon.d.ts +1 -0
  16. package/lib/components/Checkout.d.ts +6 -0
  17. package/lib/components/CouponForm.d.ts +8 -0
  18. package/lib/components/CurrencySwitcher.d.ts +1 -0
  19. package/lib/components/CustomerProfileForm.d.ts +21 -0
  20. package/lib/components/FeaturedProduct.d.ts +8 -0
  21. package/lib/components/InvoiceDocument.d.ts +32 -0
  22. package/lib/components/InvoiceViewerShell.d.ts +26 -0
  23. package/lib/components/ProductCard.d.ts +7 -0
  24. package/lib/components/ProductDetailsLayout.d.ts +7 -0
  25. package/lib/components/ProductGallery.d.ts +9 -0
  26. package/lib/components/ProductGrid.d.ts +8 -0
  27. package/lib/components/ShippingEstimator.d.ts +5 -0
  28. package/lib/components/SimpleTiptapRenderer.d.ts +7 -0
  29. package/lib/components/SubscriptionSelector.d.ts +7 -0
  30. package/lib/components/media/MediaImage.d.ts +12 -0
  31. package/lib/components/media/MediaPickerDialog.d.ts +16 -0
  32. package/lib/components/media/MediaUploadForm.d.ts +10 -0
  33. package/lib/components/media/UploadFolderContext.d.ts +10 -0
  34. package/lib/countries.d.ts +5 -0
  35. package/lib/coupon-server.d.ts +22 -0
  36. package/lib/coupon-server.test.d.ts +1 -0
  37. package/lib/coupons.d.ts +41 -0
  38. package/lib/currency-constants.d.ts +1 -0
  39. package/lib/currency-rest-client.d.ts +1 -0
  40. package/lib/currency-sale-schedule.test.d.ts +1 -0
  41. package/lib/currency-store.d.ts +20 -0
  42. package/lib/currency-sync.d.ts +19 -0
  43. package/lib/currency.d.ts +116 -0
  44. package/lib/customer-addresses.d.ts +19 -0
  45. package/lib/customer-orders.d.ts +23 -0
  46. package/lib/customer.d.ts +51 -0
  47. package/lib/export-helpers.d.ts +48 -0
  48. package/lib/factory.d.ts +2 -0
  49. package/lib/freemius-coupons.d.ts +58 -0
  50. package/lib/freemius-order-sync.d.ts +133 -0
  51. package/lib/freemius-order-sync.test.d.ts +1 -0
  52. package/lib/inventory-settings.d.ts +16 -0
  53. package/lib/invoice-server.d.ts +18 -0
  54. package/lib/invoice-ui.d.ts +29 -0
  55. package/lib/invoice.d.ts +75 -0
  56. package/lib/order-inventory.d.ts +7 -0
  57. package/lib/order-tax-details.d.ts +57 -0
  58. package/lib/pages/cms/coupons/CouponEditorForm.d.ts +23 -0
  59. package/lib/pages/cms/coupons/CouponsPage.d.ts +8 -0
  60. package/lib/pages/cms/coupons/CreateCouponDialog.d.ts +6 -0
  61. package/lib/pages/cms/coupons/EditCouponPage.d.ts +5 -0
  62. package/lib/pages/cms/coupons/ProductScopePicker.d.ts +16 -0
  63. package/lib/pages/cms/coupons/actions.d.ts +5 -0
  64. package/lib/pages/cms/coupons/index.d.ts +2 -0
  65. package/lib/pages/cms/coupons/product-options.d.ts +2 -0
  66. package/lib/pages/cms/orders/ExportReportsDialog.d.ts +2 -0
  67. package/lib/pages/cms/orders/MarkPaidButton.d.ts +3 -0
  68. package/lib/pages/cms/orders/OrderDetailPage.d.ts +5 -0
  69. package/lib/pages/cms/orders/OrderPrintButton.d.ts +3 -0
  70. package/lib/pages/cms/orders/OrderStatusForm.d.ts +4 -0
  71. package/lib/pages/cms/orders/OrdersPage.d.ts +6 -0
  72. package/lib/pages/cms/orders/actions.d.ts +7 -0
  73. package/lib/pages/cms/orders/export-actions.d.ts +2 -0
  74. package/lib/pages/cms/orders/index.d.ts +6 -0
  75. package/lib/pages/cms/orders/server-actions.d.ts +11 -0
  76. package/lib/pages/cms/orders/types.d.ts +60 -0
  77. package/lib/pages/cms/payments/PaymentsClient.d.ts +19 -0
  78. package/lib/pages/cms/payments/PaymentsPage.d.ts +1 -0
  79. package/lib/pages/cms/payments/actions.d.ts +4 -0
  80. package/lib/pages/cms/payments/index.d.ts +2 -0
  81. package/lib/pages/cms/payments/queries.d.ts +12 -0
  82. package/lib/pages/cms/products/ProductsPage.d.ts +7 -0
  83. package/lib/pages/cms/products/[id]/edit/EditProductPage.d.ts +12 -0
  84. package/lib/pages/cms/products/actions.d.ts +18201 -0
  85. package/lib/pages/cms/products/attributes/AttributeManagementPage.d.ts +1 -0
  86. package/lib/pages/cms/products/attributes/components/AttributeManager.d.ts +50 -0
  87. package/lib/pages/cms/products/categories/CategoryManagementPage.d.ts +1 -0
  88. package/lib/pages/cms/products/categories/components/CategoryManager.d.ts +47 -0
  89. package/lib/pages/cms/products/components/CopyProductFromLanguage.d.ts +9 -0
  90. package/lib/pages/cms/products/components/CurrencyPriceFields.d.ts +18 -0
  91. package/lib/pages/cms/products/components/DeleteProductButton.d.ts +9 -0
  92. package/lib/pages/cms/products/components/FreemiusPricingDashboard.d.ts +24 -0
  93. package/lib/pages/cms/products/components/ProductCategorySelector.d.ts +14 -0
  94. package/lib/pages/cms/products/components/ProductForm.d.ts +62 -0
  95. package/lib/pages/cms/products/components/ProductMediaManager.d.ts +17 -0
  96. package/lib/pages/cms/products/components/ProductsBulkTable.d.ts +32 -0
  97. package/lib/pages/cms/products/components/SaleScheduleFields.d.ts +16 -0
  98. package/lib/pages/cms/products/components/SyncFreemiusButton.d.ts +3 -0
  99. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.d.ts +5 -0
  100. package/lib/pages/cms/products/components/SyncProductForm.d.ts +1 -0
  101. package/lib/pages/cms/products/components/VariationsEditor.d.ts +26 -0
  102. package/lib/pages/cms/products/index.d.ts +7 -0
  103. package/lib/pages/cms/products/inventory/InventoryPage.d.ts +1 -0
  104. package/lib/pages/cms/products/inventory/InventoryTableClient.d.ts +6 -0
  105. package/lib/pages/cms/products/inventory/actions.d.ts +38 -0
  106. package/lib/pages/cms/products/new/NewProductPage.d.ts +9 -0
  107. package/lib/pages/cms/products/product-price-sync.d.ts +43 -0
  108. package/lib/pages/cms/products/server-actions.d.ts +125 -0
  109. package/lib/pages/cms/shipping/ShippingPage.d.ts +6 -0
  110. package/lib/pages/cms/shipping/components/RateForm.d.ts +26 -0
  111. package/lib/pages/cms/shipping/components/ZoneForm.d.ts +13 -0
  112. package/lib/pages/cms/shipping/index.d.ts +2 -0
  113. package/lib/pages/cms/shipping/server-actions.d.ts +80 -0
  114. package/lib/pages/cms/taxes/TaxesPage.d.ts +5 -0
  115. package/lib/pages/cms/taxes/actions.d.ts +3 -0
  116. package/lib/pages/cms/taxes/components/TaxRateForm.d.ts +8 -0
  117. package/lib/pages/cms/taxes/index.d.ts +2 -0
  118. package/lib/product-actions.d.ts +18457 -0
  119. package/lib/product-context.d.ts +7 -0
  120. package/lib/product-schema.d.ts +73 -0
  121. package/lib/providers/freemius.d.ts +49 -0
  122. package/lib/providers/stripe.d.ts +13 -0
  123. package/lib/server-actions/coupon-actions.d.ts +17 -0
  124. package/lib/server-actions/customer-actions.d.ts +18 -0
  125. package/lib/server-actions/product-actions.d.ts +69 -0
  126. package/lib/server-actions/shipping-actions.d.ts +10 -0
  127. package/lib/server-actions/tax-actions.d.ts +7 -0
  128. package/lib/shared-inventory.d.ts +38 -0
  129. package/lib/shipping/resolver.d.ts +16 -0
  130. package/lib/shipping-rate-currency.d.ts +39 -0
  131. package/lib/states.d.ts +9 -0
  132. package/lib/stripe/checkout.d.ts +6 -0
  133. package/lib/stripe/client.d.ts +2 -0
  134. package/lib/stripe/order-sync.d.ts +18 -0
  135. package/lib/stripe/webhooks.d.ts +4 -0
  136. package/lib/tax-calculation.d.ts +23 -0
  137. package/lib/trials.d.ts +15 -0
  138. package/lib/types.d.ts +245 -0
  139. package/lib/use-cart.d.ts +11 -0
  140. package/lib/variation-utils.d.ts +72 -0
  141. package/lib/zod-config.d.ts +2 -0
  142. package/package.json +47 -2
  143. package/server.cjs.js +110 -0
  144. package/server.d.ts +31 -0
  145. package/server.es.js +6039 -0
  146. package/index.ts +0 -12
  147. package/tsconfig.lib.json +0 -10
@@ -0,0 +1,332 @@
1
+ "use strict";const z=require("@nextblock-cms/db/server"),E=require("@nextblock-cms/utils"),s=require("react/jsx-runtime"),it=require("next/link"),H=require("D:/Websites/nextblock-sandbox/node_modules/lucide-react/dist/esm/lucide-react.js"),Ot=require("@nextblock-cms/ui/button"),ar=require("next/image"),P=require("react"),vn=require("D:/Websites/nextblock-sandbox/node_modules/@hookform/resolvers/zod/dist/zod.mjs"),x=require("@nextblock-cms/ui"),S=require("D:/Websites/nextblock-sandbox/node_modules/zod/index.js"),Cn=require("react-hook-form"),Se=require("D:/Websites/nextblock-sandbox/node_modules/sonner/dist/index.mjs"),Sn=require("@nextblock-cms/utils/server");require("D:/Websites/nextblock-sandbox/node_modules/server-only/index.js");const gt=require("@supabase/supabase-js"),cr=require("crypto"),wn=require("D:/Websites/nextblock-sandbox/node_modules/@freemius/sdk/dist/index.mjs"),M=require("next/cache"),Nn=require("next/navigation"),dr={stripe:!1,freemius:!1};function jn(e){if(!e||typeof e!="object"||Array.isArray(e))return{...dr};const t=e;return{stripe:t.stripe===!0,freemius:t.freemius===!0}}function ht(e){return e==="digital"?"freemius":"stripe"}function ur(e){return e?"provider"in e&&e.provider?e.provider:e.payment_provider?e.payment_provider:e.product_type?ht(e.product_type):"freemius_product_id"in e&&e.freemius_product_id?"freemius":null:null}function lr(e){return ur(e)==="freemius"}function Pn(e){return lr(e)}const mr=["none","nearest","up","down","charm"],En={AU:"AUD",CA:"CAD",CH:"CHF",CZ:"CZK",DE:"EUR",DK:"DKK",ES:"EUR",EU:"EUR",FI:"EUR",FR:"EUR",GB:"GBP",IE:"EUR",IN:"INR",IT:"EUR",JP:"JPY",MX:"MXN",NL:"EUR",NO:"NOK",NZ:"NZD",PL:"PLN",PT:"EUR",SE:"SEK",SG:"SGD",US:"USD"};function yt(e){return typeof e=="number"&&Number.isFinite(e)}function pr(e,t=1){const r=typeof e=="string"?Number.parseInt(e,10):e;return typeof r=="number"&&Number.isFinite(r)&&r>0?Math.max(1,Math.round(r)):t}function An(e){const t=typeof e=="string"?Number.parseInt(e,10):e;return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.round(t):null}function _r(e){if(typeof e=="string"){const t=e.trim().toLowerCase();if(mr.includes(t))return t}return"none"}function W(e){const t=e||{},r=E.normalizeCurrencyCode(typeof t.code=="string"?t.code:null),n=t.is_default===!0;return{code:r,symbol:typeof t.symbol=="string"&&t.symbol.trim()?t.symbol.trim():r,exchange_rate:n?1:yt(t.exchange_rate)&&t.exchange_rate>0?t.exchange_rate:1,is_default:n,is_active:t.is_active!==!1,auto_sync_product_prices:n?!1:t.auto_sync_product_prices===!0,rounding_mode:_r(t.rounding_mode),rounding_increment:pr(t.rounding_increment,1),rounding_charm_amount:An(t.rounding_charm_amount),auto_update_exchange_rate:n?!1:t.auto_update_exchange_rate!==!1,exchange_rate_source:typeof t.exchange_rate_source=="string"&&t.exchange_rate_source.trim()?t.exchange_rate_source.trim():null,exchange_rate_updated_at:typeof t.exchange_rate_updated_at=="string"&&t.exchange_rate_updated_at.trim()?t.exchange_rate_updated_at:null}}function ee(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((t,[r,n])=>{const i=E.normalizeCurrencyCode(r),o=typeof n=="string"?Number.parseFloat(n):n;return yt(o)&&o>=0&&(t[i]=Math.round(o)),t},{})}function Ee(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((t,[r,n])=>{const i=E.normalizeCurrencyCode(r),o=typeof n=="string"?Number.parseFloat(n):n;return o===null?(t[i]=null,t):(yt(o)&&o>=0&&(t[i]=Math.round(o)),t)},{})}function ie(e){return e.map(W).find(t=>t.is_default)??W(e[0])??W({code:"USD",symbol:"$",exchange_rate:1,is_default:!0,is_active:!0})}function We(e){return e.reduce((t,r)=>{const n=W(r);return t[n.code]=n,t},{})}function kn(e,t){const r=E.normalizeCurrencyCode(t),n=ie(e);return We(e)[r]?.exchange_rate??(r===n.code,1)}function _e(e){const{amount:t,currencies:r}=e,n=E.normalizeCurrencyCode(e.fromCurrencyCode),i=E.normalizeCurrencyCode(e.toCurrencyCode);if(!Number.isFinite(t))return 0;if(n===i)return Math.round(t);const o=We(r),a=ie(r),c=o[n]?.exchange_rate??(n===a.code?1:a.exchange_rate),d=o[i]?.exchange_rate??(i===a.code?1:a.exchange_rate),_=t/E.getCurrencyMinorUnitFactor(n)/c*d,u=E.majorUnitAmountToMinor(_,i);return e.applyRounding?fr({amount:u,currencyCode:i,currencies:r}):u}function fr(e){const t=Math.max(0,Math.round(e.amount)),r=E.normalizeCurrencyCode(e.currencyCode),i=We(e.currencies)[r]??W(ie(e.currencies)),o=pr(i.rounding_increment,1);if(i.rounding_mode==="nearest")return Math.round(t/o)*o;if(i.rounding_mode==="up")return Math.ceil(t/o)*o;if(i.rounding_mode==="down")return Math.floor(t/o)*o;if(i.rounding_mode==="charm"){const a=E.getCurrencyMinorUnitFactor(i.code),c=Math.min(Math.max(i.rounding_charm_amount??0,0),Math.max(a-1,0));let m=Math.floor(t/a)*a+c;return m<t&&(m+=a),m}return t}function In(e){const t=W(e);if(t.rounding_mode==="nearest")return`Nearest ${E.formatPrice(t.rounding_increment??1,t.code)}`;if(t.rounding_mode==="up")return`Round up to ${E.formatPrice(t.rounding_increment??1,t.code)}`;if(t.rounding_mode==="down")return`Round down to ${E.formatPrice(t.rounding_increment??1,t.code)}`;if(t.rounding_mode==="charm"){const r=t.rounding_charm_amount??0;return`Charm ending ${E.formatPrice(r,t.code)}`}return`Exact conversion (${E.minorUnitAmountToMajor(1,t.code).toFixed(E.getCurrencyMinorUnitFactor(t.code)===1?0:2)} step)`}function Mn(e,t){const r=ie(t);return e[r.code]!==void 0?r.code:Object.keys(e)[0]??r.code}function $t(e){const{amountMap:t,fallbackAmount:r,currencies:n}=e,i=E.normalizeCurrencyCode(e.currencyCode),o=ee(t);if(o[i]!==void 0)return o[i];if(Object.keys(o).length>0){const a=Mn(o,n),c=o[a];if(c!==void 0)return _e({amount:c,fromCurrencyCode:a,toCurrencyCode:i,currencies:n,applyRounding:!0})}if(typeof r=="number"&&Number.isFinite(r)){const a=ie(n);return _e({amount:r,fromCurrencyCode:a.code,toCurrencyCode:i,currencies:n,applyRounding:!0})}return 0}function gr(e){const{prices:t={},salePrices:r={},fallbackPrice:n,fallbackSalePrice:i,currencies:o}=e,a=E.normalizeCurrencyCode(e.currencyCode),c=ee(t),d=Ee(r),m=$t({amountMap:c,fallbackAmount:n,currencyCode:a,currencies:o}),l=$t({amountMap:ee(d),fallbackAmount:i,currencyCode:a,currencies:o});return{currencyCode:a,price:m,sale_price:l>0&&l<=m?l:null}}function Te(e){const t=(e.now??new Date).getTime();if(e.saleStartAt){const r=new Date(e.saleStartAt).getTime();if(Number.isFinite(r)&&t<r)return!1}if(e.saleEndAt){const r=new Date(e.saleEndAt).getTime();if(Number.isFinite(r)&&t>=r)return!1}return!0}function hr(e){if(!e.scheduledPriceAt)return!1;const t=new Date(e.scheduledPriceAt).getTime();return Number.isFinite(t)?(e.now??new Date).getTime()>=t:!1}function De(e){const t=e.now??new Date,r=hr({scheduledPriceAt:e.scheduledPriceAt,now:t}),n=r?e.scheduledPrices:e.prices,i=r?e.scheduledPrice:e.fallbackPrice,o=Te({saleStartAt:e.saleStartAt,saleEndAt:e.saleEndAt,now:t});return gr({prices:n,salePrices:o?e.salePrices:null,fallbackPrice:i,fallbackSalePrice:o?e.fallbackSalePrice:null,currencyCode:e.currencyCode,currencies:e.currencies})}function Tn(e){const t=e.entries.map(r=>De({prices:r.prices,salePrices:r.sale_prices,fallbackPrice:r.price,fallbackSalePrice:r.sale_price,saleStartAt:r.sale_start_at,saleEndAt:r.sale_end_at,scheduledPrice:r.scheduled_price,scheduledPrices:r.scheduled_prices,scheduledPriceAt:r.scheduled_price_at,currencyCode:e.currencyCode,currencies:e.currencies,now:e.now})).map(r=>r.sale_price??r.price).filter(r=>Number.isFinite(r));return t.length?{min:Math.min(...t),max:Math.max(...t)}:null}function Fn(e,t){const r=ie(t),n=e?.trim();if(!n)return r.code;const o=n.replace("_","-").split("-").map(d=>d.toUpperCase())[1];if(!o)return r.code;const a=En[o];return a&&new Set(t.map(d=>E.normalizeCurrencyCode(d.code))).has(a)?a:r.code}function Rn(e){return e.map(W).sort((t,r)=>t.is_default!==r.is_default?t.is_default?-1:1:E.normalizeCurrencyCode(t.code).localeCompare(E.normalizeCurrencyCode(r.code)))}const zn="NEXTBLOCK_CURRENCY";function yr(e){return(e||"").trim().replace(/\s+/g,"").toUpperCase()}function xt(e){return`${e.product_id}:${e.variant_id||"base"}`}function xr(){return{stripe:0,freemius:0}}function Lt(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function Dn(e,t){return e==="all"||e===t}function qn(e){return e==="stripe"||e==="freemius"?e:null}async function Un(e){const{data:t,error:r}=await e.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0});if(r)throw new Error(r.message);return(t||[]).map(n=>W(n))}async function On(e){const{client:t,items:r}=e,n=await Un(t);if(n.length===0)throw new Error("No active currencies are configured.");const i=n.find(b=>b.code===(e.currencyCode||"").toUpperCase())??ie(n),o=[...new Set(r.map(b=>b.product_id).filter(Boolean))],a=[...new Set(r.map(b=>b.variant_id).filter(b=>!!b))];if(o.length===0)return{lines:[],currencies:n,selectedCurrency:i};const[{data:c,error:d},m]=await Promise.all([t.from("products").select("id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, product_type, payment_provider, freemius_product_id, freemius_plan_id").in("id",o),a.length?t.from("product_variants").select("id, product_id, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at").in("id",a):Promise.resolve({data:[],error:null})]);if(d)throw new Error(d.message);if(m.error)throw new Error(m.error.message);const l=c||[],_=m.data||[],u=new Map(l.map(b=>[b.id,b])),h=new Map(_.map(b=>[b.id,b])),f=[];for(const b of r){const v=u.get(b.product_id);if(!v)continue;const w=qn(v.payment_provider)??(v.product_type==="digital"?"freemius":"stripe"),N=b.variant_id?h.get(b.variant_id):null,g=N&&N.product_id===v.id?N:v,F=De({prices:ee(g.prices),salePrices:Ee(g.sale_prices),fallbackPrice:g.price,fallbackSalePrice:g.sale_price,saleStartAt:g.sale_start_at,saleEndAt:g.sale_end_at,scheduledPrice:g.scheduled_price,scheduledPrices:ee(g.scheduled_prices),scheduledPriceAt:g.scheduled_price_at,currencyCode:i.code,currencies:n}),L=w==="freemius"?1:Math.max(1,Number(b.quantity)||1),T=Math.max(0,F.sale_price??F.price);f.push({key:xt(b),product_id:v.id,variant_id:N?.id??null,title:v.title,quantity:L,provider:w,subtotal:T*L,freemius_product_id:v.freemius_product_id??null,freemius_plan_id:v.freemius_plan_id??null})}return{lines:f,currencies:n,selectedCurrency:i}}async function $n(e,t){const{data:r,error:n}=await e.from("coupon_products").select("product_id").eq("coupon_id",t);if(n)throw new Error(n.message);return new Set((r||[]).map(i=>i.product_id))}function Ln(e,t){const r=e.reduce((a,c)=>a+c.subtotal,0),n=Math.min(t,r);if(r<=0||n<=0)return new Map;const i=new Map;let o=0;return e.forEach((a,c)=>{const m=c===e.length-1?n-o:Math.min(a.subtotal,Math.floor(n*a.subtotal/r));o+=m,i.set(a.key,m)}),i}async function br(e){const t=yr(e.code);if(!t)return{success:!1,error:"Enter a coupon code.",errorKey:"ecommerce.coupon_code_required"};if(!e.items.length)return{success:!1,error:"Add an item to your cart before applying a coupon.",errorKey:"ecommerce.coupon_cart_empty"};const{data:r,error:n}=await e.client.from("coupons").select("id, code, name, provider_scope, discount_type, discount_amount, is_active, starts_at, ends_at, redemption_limit, redemptions_count").ilike("code",t).maybeSingle();if(n)throw new Error(n.message);if(!r)return{success:!1,error:"Coupon code not found.",errorKey:"ecommerce.coupon_not_found"};const i=r,o=new Date,a=Lt(i.starts_at),c=Lt(i.ends_at);if(!i.is_active)return{success:!1,error:"This coupon is not active.",errorKey:"ecommerce.coupon_inactive"};if(a&&a>o)return{success:!1,error:"This coupon is not active yet.",errorKey:"ecommerce.coupon_not_started"};if(c&&c<=o)return{success:!1,error:"This coupon has expired.",errorKey:"ecommerce.coupon_expired"};if(i.redemption_limit!==null&&(i.redemptions_count??0)>=i.redemption_limit)return{success:!1,error:"This coupon has reached its redemption limit.",errorKey:"ecommerce.coupon_limit_reached"};const[{lines:d},m]=await Promise.all([On({client:e.client,items:e.items,currencyCode:e.currencyCode}),$n(e.client,i.id)]),l=m.size>0,_=d.filter(v=>v.subtotal>0&&Dn(i.provider_scope,v.provider)&&(!l||m.has(v.product_id)));if(_.length===0)return{success:!1,error:"This coupon does not apply to the items in your cart.",errorKey:"ecommerce.coupon_not_applicable"};const u=i.discount_type==="fixed"?Ln(_,i.discount_amount):null,h=xr(),f=_.map(v=>{const w=i.discount_type==="percent"?Math.min(v.subtotal,Math.round(v.subtotal*i.discount_amount/100)):u?.get(v.key)??0;return h[v.provider]+=w,{key:v.key,product_id:v.product_id,variant_id:v.variant_id,provider:v.provider,title:v.title,quantity:v.quantity,subtotal:v.subtotal,discount:w}});return{success:!0,quote:{couponId:i.id,code:i.code,name:i.name,discountType:i.discount_type,discountAmount:i.discount_amount,providerScope:i.provider_scope,eligibleSubtotal:_.reduce((v,w)=>v+w.subtotal,0),discountTotal:h.stripe+h.freemius,providerDiscounts:h,lineDiscounts:f}}}function Bn(e){const t=new Map;for(const r of e?.lineDiscounts??[])t.set(r.key,r.discount);return t}async function vr(e){const{error:t}=await e.client.from("coupon_redemptions").insert({coupon_id:e.quote.couponId,order_id:e.orderId,coupon_code:e.quote.code,provider:e.provider,discount_total:Math.max(0,e.discountTotal),user_id:e.userId||null,customer_email:e.customerEmail||null,metadata:e.metadata||{}});if(t){console.error("Failed to record coupon redemption:",t);return}const{data:r}=await e.client.from("coupons").select("redemptions_count").eq("id",e.quote.couponId).single();await e.client.from("coupons").update({redemptions_count:(r?.redemptions_count??0)+1,updated_at:new Date().toISOString()}).eq("id",e.quote.couponId)}const ot=[{code:"US",name:"United States"},{code:"CA",name:"Canada"},{code:"GB",name:"United Kingdom"},{code:"AU",name:"Australia"},{code:"NZ",name:"New Zealand"},{code:"IE",name:"Ireland"},{code:"FR",name:"France"},{code:"DE",name:"Germany"},{code:"IT",name:"Italy"},{code:"ES",name:"Spain"},{code:"MX",name:"Mexico"},{code:"BR",name:"Brazil"},{code:"AR",name:"Argentina"},{code:"CL",name:"Chile"},{code:"CO",name:"Colombia"},{code:"PE",name:"Peru"},{code:"ZA",name:"South Africa"},{code:"NG",name:"Nigeria"},{code:"KE",name:"Kenya"},{code:"IN",name:"India"},{code:"JP",name:"Japan"},{code:"KR",name:"South Korea"},{code:"CN",name:"China"},{code:"SG",name:"Singapore"},{code:"MY",name:"Malaysia"},{code:"PH",name:"Philippines"},{code:"TH",name:"Thailand"},{code:"VN",name:"Vietnam"},{code:"ID",name:"Indonesia"},{code:"AE",name:"United Arab Emirates"},{code:"SA",name:"Saudi Arabia"},{code:"EG",name:"Egypt"},{code:"MA",name:"Morocco"},{code:"DZ",name:"Algeria"},{code:"TN",name:"Tunisia"},{code:"PT",name:"Portugal"},{code:"NL",name:"Netherlands"},{code:"BE",name:"Belgium"},{code:"CH",name:"Switzerland"},{code:"AT",name:"Austria"},{code:"SE",name:"Sweden"},{code:"NO",name:"Norway"},{code:"DK",name:"Denmark"},{code:"FI",name:"Finland"},{code:"PL",name:"Poland"},{code:"CZ",name:"Czech Republic"},{code:"HU",name:"Hungary"},{code:"RO",name:"Romania"},{code:"BG",name:"Bulgaria"},{code:"GR",name:"Greece"},{code:"TR",name:"Turkey"},{code:"IL",name:"Israel"},{code:"CY",name:"Cyprus"},{code:"MT",name:"Malta"}],Kn={USA:"US","UNITED STATES OF AMERICA":"US",UK:"GB","GREAT BRITAIN":"GB"};function Ae(e){const t=e?.trim();if(!t)return null;const r=t.toUpperCase(),n=Kn[r];if(n)return n;const i=ot.find(a=>a.code===r);return i?i.code:ot.find(a=>a.name.toUpperCase()===r)?.code??null}const Vn=["auto","manual"];function bt(e){if(typeof e=="string"){const t=e.trim().toLowerCase();if(Vn.includes(t))return t}return"auto"}function at(e,t=0){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.round(e):t}function Cr(e){const t=E.normalizeCurrencyCode(e.sourceCurrencyCode),r=ee(e.amountMap);if(r[t]!==void 0)return t;const n=Object.keys(r)[0];return n?E.normalizeCurrencyCode(n):ie(e.currencies).code}function Yn(e){const t=bt(e.mode),r=ee(e.costAmounts),n=ee(e.minOrderAmounts),i=Cr({amountMap:Object.keys(r).length>0?r:n,sourceCurrencyCode:e.sourceCurrencyCode,currencies:e.currencies}),o=r[i]??at(e.fallbackCostAmount),a=n[i]??at(e.fallbackMinOrderAmount);if(t==="auto")return{mode:t,sourceCurrencyCode:i,costAmounts:{[i]:o},minOrderAmounts:{[i]:a}};const c=Object.keys(r).length>0?{...r}:{[i]:o},d=Object.keys(n).length>0?{...n}:{[i]:a};return c[i]===void 0&&(c[i]=o),d[i]===void 0&&(d[i]=a),{mode:t,sourceCurrencyCode:i,costAmounts:c,minOrderAmounts:d}}function Bt(e){const t=bt(e.mode),r=ee(e.amountMap),n=E.normalizeCurrencyCode(e.currencyCode);if(t==="manual"&&r[n]!==void 0)return r[n];const i=Cr({amountMap:r,sourceCurrencyCode:e.sourceCurrencyCode,currencies:e.currencies}),o=r[i]??at(e.fallbackAmount);return n===i?o:_e({amount:o,fromCurrencyCode:i,toCurrencyCode:n,currencies:e.currencies})}function Ne(e){return!e||typeof e!="object"||Array.isArray(e)?null:Object.entries(e).reduce((t,[r,n])=>(typeof n=="string"&&n.trim()&&(t[r]=n.trim()),t),{})}function ye(e,t,r){return!r||!t?e:t[r]?.trim()||e}function ct(e,t){return ye(e.name,e.name_translations,t)}function dt(e,t){return ye(e.value,e.value_translations,t)}function Gn(e){return e?e.startsWith("http")?e:process.env.NEXT_PUBLIC_R2_BASE_URL?`${process.env.NEXT_PUBLIC_R2_BASE_URL}/${e}`:process.env.NEXT_PUBLIC_SUPABASE_URL?`${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/media/${e}`:e:null}function Xn(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function vt(e){return[...e].sort().join("__")}function Ct(e){return e.map(t=>t.term_value).join(" / ")}function Hn(e){return e.length===0?[]:e.reduce((t,r)=>t.flatMap(n=>r.map(i=>[...n,i])),[[]])}function Sr(e){const{baseSku:t,basePrice:r,basePrices:n={},baseSalePrice:i=null,baseSalePrices:o={},selectedAttributes:a,previousVariants:c=[]}=e;if(a.length===0||a.some(l=>l.terms.length===0))return[];const d=new Map(c.map(l=>[l.combination_key,l])),m=a.map(l=>l.terms.map(_=>({attribute_id:l.attribute_id,attribute_name:l.attribute_name,term:_})));return Hn(m).map(l=>{const _=l.map(({attribute_id:v,attribute_name:w,term:N})=>({attribute_id:v,attribute_name:w,term_id:N.id,term_value:N.value,term_slug:N.slug})),u=_.map(v=>v.term_id),h=vt(u),f=d.get(h),b=_.map(v=>(v.term_slug?v.term_slug:Xn(v.term_value)).toUpperCase()).filter(Boolean).join("-");return{id:f?.id,combination_key:h,sku:f?.sku||[t.trim(),b].filter(Boolean).join("-"),upc:f?.upc??null,price:f?.price??r,prices:f?.prices??ee(n),sale_price:f?.sale_price??i,sale_prices:f?.sale_prices??Ee(o),sale_start_at:f?.sale_start_at??null,sale_end_at:f?.sale_end_at??null,stock_quantity:f?.stock_quantity??0,main_media_id:f?.main_media_id??null,main_image_url:f?.main_image_url??null,attribute_term_ids:u,selected_options:_,label:Ct(_)}})}function wr(e){const t={};for(const r of e)for(const n of r.selected_options??[]){const i=new Set(t[n.attribute_id]??[]);i.add(n.term_id),t[n.attribute_id]=[...i]}return t}function Wn(e,t){const r=Object.values(t).filter(Boolean);return r.length===0?null:e.find(n=>n.attribute_term_ids.length===r.length&&r.every(i=>n.attribute_term_ids.includes(i)))??null}function Nr(e,t,r){const n=new Set;for(const i of e){if(!Object.entries(r).every(([c,d])=>!d||c===t?!0:i.attribute_term_ids.includes(d)))continue;const a=i.selected_options.find(c=>c.attribute_id===t);a&&n.add(a.term_id)}return n}function Qn(e,t){const r=t.find(n=>n.stock_quantity>0)??t[0]??null;return r?r.selected_options.reduce((n,i)=>(n[i.attribute_id]=i.term_id,n),{}):e.reduce((n,i)=>{const o=i.terms[0];return o&&(n[i.id]=o.id),n},{})}function Jn(e,t,r){const n={...r};for(const i of e){const o=Nr(t,i.id,n);if(o.size===0){delete n[i.id];continue}const a=n[i.id];if(a&&o.has(a))continue;const c=i.terms.find(d=>o.has(d.id));c&&(n[i.id]=c.id)}return n}function Zn(e=[],t){const r=new Map,n=e.map(o=>{const a=(o.variant_attribute_mapping||[]).map(d=>{const m=d.product_attribute_terms,l=m?.product_attributes;if(!m||!l)return null;const _=r.get(l.id)||{id:l.id,name:ye(l.name,Ne(l.name_translations),t),slug:l.slug,name_translations:Ne(l.name_translations),terms:[],_termIds:new Set};return _._termIds.has(m.id)||(_.terms.push({id:m.id,attribute_id:m.attribute_id,value:ye(m.value,Ne(m.value_translations),t),slug:m.slug,sort_order:m.sort_order??null,value_translations:Ne(m.value_translations)}),_._termIds.add(m.id)),r.set(l.id,_),{attribute_id:l.id,attribute_name:ye(l.name,Ne(l.name_translations),t),term_id:m.id,term_value:ye(m.value,Ne(m.value_translations),t),term_slug:m.slug}}).filter(d=>d!==null).sort((d,m)=>d.attribute_name.localeCompare(m.attribute_name)),c=a.map(d=>d.term_id);return{id:o.id,combination_key:vt(c),sku:o.sku,upc:o.upc??null,price:o.price??0,prices:ee(o.prices),sale_price:o.sale_price??null,sale_prices:Ee(o.sale_prices),sale_start_at:o.sale_start_at??null,sale_end_at:o.sale_end_at??null,scheduled_price:o.scheduled_price??null,scheduled_prices:ee(o.scheduled_prices),scheduled_price_at:o.scheduled_price_at??null,stock_quantity:o.stock_quantity??0,main_media_id:o.main_media_id??null,image_url:Gn(o.media?.file_path??o.media?.object_key??null),attribute_term_ids:c,selected_options:a,label:Ct(a)}});return{attributes:[...r.values()].map(o=>({id:o.id,name:o.name,slug:o.slug,name_translations:o.name_translations,terms:[...o.terms].sort((a,c)=>{const d=a.sort_order??Number.MAX_SAFE_INTEGER,m=c.sort_order??Number.MAX_SAFE_INTEGER;return d!==m?d-m:a.value.localeCompare(c.value)})})).sort((o,a)=>o.name.localeCompare(a.name)),variants:n}}function es(e,t){if(!e.length)return null;const r=e.map(n=>Te({saleStartAt:n.sale_start_at,saleEndAt:n.sale_end_at,now:t})&&typeof n.sale_price=="number"?n.sale_price:n.price);return{min:Math.min(...r),max:Math.max(...r)}}async function ts(e,t,r,n){const i=z.getSsgSupabaseClient(),{data:o}=await i.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}),a=o??[],c=ie(a),d=n||c.code,{data:m,error:l}=await i.from("shipping_zone_locations").select(`
2
+ zone_id,
3
+ country_code,
4
+ state_code,
5
+ postal_code,
6
+ shipping_zones!inner(priority_order)
7
+ `).eq("country_code",t.country).order("shipping_zones(priority_order)",{ascending:!0});if(l||!m||m.length===0)return[];let _=null;if(t.state){const w=m.find(N=>N.state_code===t.state);w&&(_=w.zone_id)}if(!_){const w=m.find(N=>!N.state_code&&!N.postal_code);w&&(_=w.zone_id)}_||(_=m[0].zone_id);const{data:u,error:h}=await i.from("shipping_zone_methods").select("id, zone_id, method_type, cost_amount, cost_amounts, cost_currency, currency_pricing_mode, min_order_amount, min_order_amounts, name, name_translations").eq("zone_id",_);if(h||!u)return[];const v=u.filter(w=>{const N=Bt({amountMap:w.min_order_amounts||{},fallbackAmount:w.min_order_amount||0,sourceCurrencyCode:w.cost_currency||c.code,mode:w.currency_pricing_mode,currencyCode:d,currencies:a});return e>=N}).map(w=>({id:w.id,name:ye(w.name,w.name_translations||null,r),amount:Bt({amountMap:w.cost_amounts||{},fallbackAmount:w.cost_amount||0,sourceCurrencyCode:w.cost_currency||c.code,mode:w.currency_pricing_mode,currencyCode:d,currencies:a}),currency:d,type:w.method_type})).sort((w,N)=>w.amount-N.amount)[0];return v?[v]:[]}const rs=[{code:"AL",name:"Alabama"},{code:"AK",name:"Alaska"},{code:"AZ",name:"Arizona"},{code:"AR",name:"Arkansas"},{code:"CA",name:"California"},{code:"CO",name:"Colorado"},{code:"CT",name:"Connecticut"},{code:"DE",name:"Delaware"},{code:"DC",name:"District of Columbia"},{code:"FL",name:"Florida"},{code:"GA",name:"Georgia"},{code:"HI",name:"Hawaii"},{code:"ID",name:"Idaho"},{code:"IL",name:"Illinois"},{code:"IN",name:"Indiana"},{code:"IA",name:"Iowa"},{code:"KS",name:"Kansas"},{code:"KY",name:"Kentucky"},{code:"LA",name:"Louisiana"},{code:"ME",name:"Maine"},{code:"MD",name:"Maryland"},{code:"MA",name:"Massachusetts"},{code:"MI",name:"Michigan"},{code:"MN",name:"Minnesota"},{code:"MS",name:"Mississippi"},{code:"MO",name:"Missouri"},{code:"MT",name:"Montana"},{code:"NE",name:"Nebraska"},{code:"NV",name:"Nevada"},{code:"NH",name:"New Hampshire"},{code:"NJ",name:"New Jersey"},{code:"NM",name:"New Mexico"},{code:"NY",name:"New York"},{code:"NC",name:"North Carolina"},{code:"ND",name:"North Dakota"},{code:"OH",name:"Ohio"},{code:"OK",name:"Oklahoma"},{code:"OR",name:"Oregon"},{code:"PA",name:"Pennsylvania"},{code:"RI",name:"Rhode Island"},{code:"SC",name:"South Carolina"},{code:"SD",name:"South Dakota"},{code:"TN",name:"Tennessee"},{code:"TX",name:"Texas"},{code:"UT",name:"Utah"},{code:"VT",name:"Vermont"},{code:"VA",name:"Virginia"},{code:"WA",name:"Washington"},{code:"WV",name:"West Virginia"},{code:"WI",name:"Wisconsin"},{code:"WY",name:"Wyoming"}],ns=[{code:"AB",name:"Alberta"},{code:"BC",name:"British Columbia"},{code:"MB",name:"Manitoba"},{code:"NB",name:"New Brunswick"},{code:"NL",name:"Newfoundland and Labrador"},{code:"NS",name:"Nova Scotia"},{code:"NT",name:"Northwest Territories"},{code:"NU",name:"Nunavut"},{code:"ON",name:"Ontario"},{code:"PE",name:"Prince Edward Island"},{code:"QC",name:"Quebec"},{code:"SK",name:"Saskatchewan"},{code:"YT",name:"Yukon"}],St={US:rs,CA:ns},Kt={US:{CALIFORNIA:"CA",NEWYORK:"NY","NEW YORK":"NY",DISTRICTOFCOLUMBIA:"DC","DISTRICT OF COLUMBIA":"DC"},CA:{QUEBEC:"QC",ONTARIO:"ON","BRITISH COLUMBIA":"BC",BRITISHCOLUMBIA:"BC","NEWFOUNDLAND AND LABRADOR":"NL",NEWFOUNDLANDANDLABRADOR:"NL","NORTHWEST TERRITORIES":"NT",NORTHWESTTERRITORIES:"NT","PRINCE EDWARD ISLAND":"PE",PRINCEEDWARDISLAND:"PE"}};function jr(e){const t=Ae(e);return t?St[t]??[]:[]}function Pr(e){return jr(e).length>0}function Qe(e,t){const r=Ae(e),n=t?.trim();if(!r||!n)return n||null;const i=St[r];if(!i?.length)return n.toUpperCase();const o=n.toUpperCase(),a=i.find(l=>l.code===o);if(a)return a.code;const c=i.find(l=>l.name.toUpperCase()===o);if(c)return c.code;const d=o.replace(/\s+/g,"");return Kt[r]?.[o]??Kt[r]?.[d]??o}function ss(e,t){const r=Ae(e),n=Qe(e,t);return!r||!n?t??null:St[r]?.find(o=>o.code===n)?.name??n}const wt="ecommerce_inventory_settings",he={trackQuantities:!0,enableTaxes:!1,taxCalculationMode:"manual"};function st(e,t=!0){if(typeof e=="boolean")return e;if(typeof e=="string"){const r=e.trim().toLowerCase();if(["true","1","yes","on"].includes(r))return!0;if(["false","0","no","off"].includes(r))return!1}return t}function is(e,t=he.taxCalculationMode){return e==="automatic"?"automatic":e==="manual"?"manual":t}function Er(e){if(e&&typeof e=="object"&&!Array.isArray(e)){const t=e;return{trackQuantities:st(t.trackQuantities??t.track_quantities,he.trackQuantities),enableTaxes:st(t.enableTaxes??t.enable_taxes,he.enableTaxes),taxCalculationMode:is(t.taxCalculationMode??t.tax_calculation_mode,he.taxCalculationMode)}}return{trackQuantities:st(e,he.trackQuantities),enableTaxes:he.enableTaxes,taxCalculationMode:he.taxCalculationMode}}async function Ar(e){const{data:t,error:r}=await e.from("site_settings").select("value").eq("key",wt).maybeSingle();return r||!t?he:Er(t.value)}async function os(e,t){return e.from("site_settings").upsert({key:wt,value:{track_quantities:t.trackQuantities,enable_taxes:t.enableTaxes,tax_calculation_mode:t.taxCalculationMode}})}function as(e){return{error:`${e} is no longer available.`,errorKey:"ecommerce.inventory_item_unavailable",errorParams:{item:e},errorStatus:409}}function cs(e,t){return{error:`Only ${t} units remain for ${e}.`,errorKey:"ecommerce.inventory_insufficient",errorParams:{item:e,count:t},errorStatus:409}}const ds="txcd_99999999",kr="txcd_00000000",us="txcd_92010001";function ls(e){return e?ds:kr}async function ms(e,t,r,n,i){if(!t.length)return[];const o=[...new Set(t.map(m=>m.product_id))],{data:a,error:c}=await e.from("products").select("id, is_taxable").in("id",o);if(c)throw new Error(c.message);const d=new Map((a||[]).map(m=>[m.id,m]));return t.reduce((m,l)=>{const _=d.get(l.product_id);if(!_)return m;const u=De({prices:l.prices,salePrices:l.sale_prices,fallbackPrice:l.price,fallbackSalePrice:l.sale_price,saleStartAt:l.sale_start_at,saleEndAt:l.sale_end_at,scheduledPrice:l.scheduled_price,scheduledPrices:l.scheduled_prices,scheduledPriceAt:l.scheduled_price_at,currencyCode:r,currencies:n});return m.push({product_id:_.id,quantity:l.quantity,unit_amount:u.sale_price??u.price,discount_amount:i?.get(xt(l))??0,is_taxable:_.is_taxable??!0}),m},[])}async function ps(e,t){const r=await Ar(e),n=t.items.reduce((_,u)=>u.is_taxable?_+Math.max(0,u.unit_amount*u.quantity-(u.discount_amount??0)):_,0);if(!r.enableTaxes||n<=0)return{enabled:!1,mode:r.taxCalculationMode,amount:0,taxableSubtotal:n,lines:[]};if(r.taxCalculationMode==="automatic")return{enabled:!0,mode:"automatic",amount:0,taxableSubtotal:n,lines:[],isPendingExternalCalculation:!0};const i=Ae(t.destination?.country_code),o=Qe(i,t.destination?.state)||null;if(!i)return{enabled:!0,mode:"manual",amount:0,taxableSubtotal:n,lines:[]};let a=e.from("tax_rates").select("id, country_code, state_code, tax_name, tax_rate, created_at, updated_at").eq("country_code",i);a=o?a.or(`state_code.is.null,state_code.eq.${o}`):a.is("state_code",null);const{data:c,error:d}=await a;if(d)throw new Error(d.message);const l=(c||[]).map(_=>({id:_.id,name:_.tax_name,rate:Number(_.tax_rate),amount:Math.round(n*Number(_.tax_rate)/100),country_code:_.country_code,state_code:_.state_code??null}));return{enabled:!0,mode:"manual",amount:l.reduce((_,u)=>_+u.amount,0),taxableSubtotal:n,lines:l}}const _s=()=>({company_name:"",recipient_name:"",line1:"",line2:"",city:"",state:"",postal_code:"",country_code:"CA"});function de(e){const t=e?.trim();return t||null}function xe(e){if(!e)return null;const t={company_name:de(e.company_name),recipient_name:de(e.recipient_name),line1:de(e.line1),line2:de(e.line2),city:de(e.city),postal_code:de(e.postal_code),country_code:Ae(e.country_code)};return t.state=Qe(t.country_code,de(e.state)),Object.values(t).some(Boolean)?t:null}function fs(e){const t=xe(e);return t?!!(t.recipient_name&&t.line1&&t.city&&t.postal_code&&t.country_code&&(!Pr(t.country_code)||t.state)):!1}function Ir(e){const t=xe(e.billing),r=xe(e.shipping),n=de(e.email)?.toLowerCase()??null,i=de(e.phone),o=de(e.name)??t?.recipient_name??r?.recipient_name??null;return{email:n,name:o,phone:i,billing:t,shipping:r}}function gs(e,t){const r=xe(e),n=xe(t);return JSON.stringify(r)===JSON.stringify(n)}function je(e){const t=e?.trim();return t||null}function Vt(e){return e?xe({company_name:e.company_name,recipient_name:e.recipient_name,line1:e.line1,line2:e.line2,city:e.city,state:e.state,postal_code:e.postal_code,country_code:e.country_code}):null}function Yt(e,t){return e?.find(r=>r.address_type===t&&r.is_default)??e?.find(r=>r.address_type===t)??null}async function Gt(e,t,r,n){const i=xe(n),{data:o,error:a}=await e.from("user_addresses").select("*").eq("user_id",t).eq("address_type",r).order("is_default",{ascending:!1}).order("updated_at",{ascending:!1});if(a)throw new Error(a.message);const c=o?.[0]??null,d=(o??[]).slice(1).map(l=>l.id);if(!i){if(o?.length){const l=o.map(u=>u.id),{error:_}=await e.from("user_addresses").delete().in("id",l);if(_)throw new Error(_.message)}return}const m={user_id:t,address_type:r,is_default:!0,company_name:i.company_name??null,recipient_name:i.recipient_name??null,line1:i.line1??null,line2:i.line2??null,city:i.city??null,state:i.state??null,postal_code:i.postal_code??null,country_code:i.country_code??null,updated_at:new Date().toISOString()};if(c){const{error:l}=await e.from("user_addresses").update(m).eq("id",c.id);if(l)throw new Error(l.message)}else{const{error:l}=await e.from("user_addresses").insert(m);if(l)throw new Error(l.message)}if(d.length){const{error:l}=await e.from("user_addresses").delete().in("id",d);if(l)throw new Error(l.message)}}async function hs(e,t){const r=t??z.createClient(),{data:n,error:i}=await r.from("user_addresses").select("*").eq("user_id",e).in("address_type",["billing","shipping"]).order("is_default",{ascending:!1}).order("updated_at",{ascending:!1});if(i)throw new Error(i.message);const o=Vt(Yt(n??[],"billing")),a=Vt(Yt(n??[],"shipping"));return{billingAddress:o,shippingAddress:a}}async function Mr(e){const t=e.client??z.createClient();await Gt(t,e.userId,"billing",e.billingAddress??null),await Gt(t,e.userId,"shipping",e.shippingAddress??null)}async function Tr(e){const t=e.client??z.createClient(),r=je(e.fullName),n=je(e.phone);if(!r&&!n)return;const{data:i,error:o}=await t.from("profiles").select("full_name, phone").eq("id",e.userId).maybeSingle();if(o)throw new Error(o.message);if(!i)return;const a=je(i.full_name)||r,c=je(i.phone)||n;if(je(i.full_name)===a&&je(i.phone)===c)return;const{error:d}=await t.from("profiles").update({full_name:a,phone:c,updated_at:new Date().toISOString()}).eq("id",e.userId);if(d)throw new Error(d.message)}function Nt(e){return e??z.getServiceRoleSupabaseClient()}function ys(e){return e?(Array.isArray(e)?e:[e]).map(r=>r?.code?.toUpperCase().trim()).filter(r=>!!r):[]}function Ce(e){return[...new Set(e)].sort((t,r)=>t.localeCompare(r))}function xs(e,t){return!e||e===t?t:"mixed"}async function Ve(e,t){const r=Array.from(t.reduce((i,o)=>{const a=o.sku.trim();return a&&i.set(a,{sku:a,quantity:Math.max(0,Math.trunc(o.quantity))}),i},new Map).values());if(r.length===0)return;const{error:n}=await e.from("inventory_items").upsert(r,{onConflict:"sku"});if(n)throw new Error(n.message)}async function Xt(e,t){const r=Ce(t.map(o=>o.trim()).filter(Boolean));if(r.length===0)return new Map;const{data:n,error:i}=await e.from("inventory_items").select("sku, quantity").in("sku",r);if(i)throw new Error(i.message);return new Map((n||[]).map(o=>[o.sku,Math.max(0,o.quantity??0)]))}async function Fr(e){const{data:t,error:r}=await e.from("products").select(`
8
+ id,
9
+ title,
10
+ sku,
11
+ stock,
12
+ status,
13
+ languages (
14
+ code
15
+ ),
16
+ product_variants (
17
+ id,
18
+ sku,
19
+ stock_quantity
20
+ )
21
+ `).order("title",{ascending:!0});if(r)throw new Error(r.message);const n=new Map,i=(o,a,c,d,m)=>{const l=o.trim();if(!l)return;const _=ys(d.languages),u=n.get(l);if(u){u.usageType=xs(u.usageType,a),u.stockFallback=Math.min(u.stockFallback,c),u.productTitles.add(d.title),u.parentProductSkus.add(d.sku),u.languages=new Set([...u.languages,..._]),u.statuses.add(d.status),u.productIds.add(d.id),m&&u.variantIds.add(m);return}n.set(l,{sku:l,stockFallback:c,usageType:a,productTitles:new Set([d.title]),parentProductSkus:new Set([d.sku]),languages:new Set(_),statuses:new Set([d.status]),productIds:new Set([d.id]),variantIds:m?new Set([m]):new Set})};for(const o of t||[]){const a=o.product_variants||[];if(a.length>0){for(const c of a)i(c.sku,"variant",Math.max(0,c.stock_quantity??0),o,c.id);continue}i(o.sku,"product",Math.max(0,o.stock??0),o)}return n}async function bs(e){const t=Nt(e),r=await Fr(t),n=[...r.keys()];if(n.length===0)return[];let i=await Xt(t,n);const o=n.filter(a=>!i.has(a)).flatMap(a=>{const c=r.get(a);return c?[{sku:a,quantity:c.stockFallback}]:[]});return o.length>0&&(await Ve(t,o),i=await Xt(t,n)),n.flatMap(a=>{const c=r.get(a);return c?{key:a,sku:a,stock:i.get(a)??c.stockFallback,usageType:c.usageType,productTitles:Ce(c.productTitles),parentProductSkus:Ce(c.parentProductSkus),languages:Ce(c.languages),statuses:Ce(c.statuses),productIds:Ce(c.productIds),variantIds:Ce(c.variantIds)}:[]}).sort((a,c)=>a.sku.localeCompare(c.sku)||a.usageType.localeCompare(c.usageType)||a.productTitles.join(", ").localeCompare(c.productTitles.join(", ")))}async function vs(e,t){const r=Nt(t),n=e.sku.trim(),i=Math.max(0,Math.trunc(e.stock));if(!n)throw new Error("SKU is required to update inventory.");await Ve(r,[{sku:n,quantity:i}]);const a=(await Fr(r)).get(n),c=(a?.productIds.size??0)+(a?.variantIds.size??0);return{stock:i,affectedCount:c}}async function Rr(e,t,r){const n=Nt(r);if(t.variants&&t.variants.length>0){const i=Array.from(t.variants.reduce((o,a)=>(o.set(a.sku.trim(),Math.max(0,Math.trunc(a.stock_quantity))),o),new Map).entries()).map(([o,a])=>({sku:o,quantity:a}));await Ve(n,i);return}await Ve(n,[{sku:t.sku,quantity:Math.max(0,Math.trunc(t.stock))}])}const Fe=e=>Math.round(e*100);function Ye(e){return Object.entries(e||{}).reduce((t,[r,n])=>(typeof n=="number"&&Number.isFinite(n)&&n>=0&&(t[E.normalizeCurrencyCode(r)]=Fe(n)),t),{})}function Cs(e){return(e||[]).map(t=>({id:t.id,sku:t.sku,upc:t.upc??null,price:Fe(t.price),sale_price:typeof t.sale_price=="number"&&!isNaN(t.sale_price)?Fe(t.sale_price):null,prices:Ye(t.prices),sale_prices:Ye(t.sale_prices),sale_start_at:t.sale_start_at??null,sale_end_at:t.sale_end_at??null,stock_quantity:t.stock_quantity,main_media_id:t.main_media_id??null,attribute_term_ids:t.attribute_term_ids}))}function zr(e,t){const n=e.product_type==="digital"&&e.payment_provider==="freemius"?Math.max(0,Number(e.trial_period_days??0)):0;return{id:t,product_type:e.product_type,payment_provider:e.payment_provider,title:e.title,slug:e.slug,sku:e.sku,upc:e.upc??null,stock:e.stock,status:e.status,short_description:e.short_description??null,description_json:e.description_json??null,metadata:{},price:Fe(e.price),sale_price:typeof e.sale_price=="number"&&!isNaN(e.sale_price)?Fe(e.sale_price):null,prices:Ye(e.prices),sale_prices:Ye(e.sale_prices),sale_start_at:e.sale_start_at??null,sale_end_at:e.sale_end_at??null,freemius_plan_id:e.freemius_plan_id??null,freemius_product_id:e.freemius_product_id??null,trial_period_days:n,trial_requires_payment_method:n>0?e.trial_requires_payment_method??!1:!1,is_taxable:e.is_taxable,language_id:e.language_id,translation_group_id:e.translation_group_id||void 0,variants:Cs(e.variants)}}async function Dr(e,t,r){const{error:n}=await e.from("products").update({is_taxable:r,updated_at:new Date().toISOString()}).eq("id",t);if(n)throw n}async function qr(e,t,r){const n=new Date().toISOString(),{data:i}=await e.from("products").select("sku, sale_price, sale_prices").eq("id",t).maybeSingle(),o=i?.sku??r.sku,{data:a}=await e.from("products").select("id").eq("sku",o),c=(a??[]).map(u=>u.id);c.length===0&&c.push(t);const{error:d}=await e.from("products").update({sale_price:i?.sale_price??null,sale_prices:i?.sale_prices??null,sale_start_at:r.sale_start_at??null,sale_end_at:r.sale_end_at??null,updated_at:n}).in("id",c);if(d)throw d;const m=r.variants??[];if(m.length===0)return;const{data:l}=await e.from("product_variants").select("sku, sale_price, sale_prices").eq("product_id",t),_=new Map((l??[]).map(u=>[u.sku,u]));for(const u of m){const h=_.get(u.sku);if(!h)continue;const{error:f}=await e.from("product_variants").update({sale_price:h.sale_price??null,sale_prices:h.sale_prices??null,sale_start_at:u.sale_start_at??null,sale_end_at:u.sale_end_at??null,updated_at:n}).eq("sku",u.sku).in("product_id",c);if(f)throw f}}async function Ur(e,{page:t=1,limit:r=10,search:n="",languageId:i,categoryId:o}={}){const a=(t-1)*r,c=a+r-1;let d=e.from("products").select("id, title, sku, upc, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, is_taxable, product_type, payment_provider, short_description, stock, status, slug, language_id, translation_group_id, freemius_product_id, freemius_plan_id, trial_period_days, trial_requires_payment_method, product_media(media(file_path, object_key)), product_variants(id, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at), freemius_plans(id, name, title, freemius_pricing(id, license_quota, api_monthly_price, api_annual_price, api_lifetime_price, override_monthly_price, override_annual_price, override_lifetime_price, is_active)), product_categories(category:categories(id, name, slug, description, name_translations, description_translations))",{count:"exact"}).range(a,c).order("created_at",{ascending:!1});if(i&&(d=d.eq("language_id",i)),o){const{data:m,error:l}=await e.from("product_categories").select("product_id").eq("category_id",o);if(l)return{data:[],error:l,count:0};const _=(m||[]).map(u=>u.product_id).filter(Boolean);if(_.length===0)return{data:[],error:null,count:0};d=d.in("id",_)}return n&&(d=d.or(`title.ilike.%${n}%,sku.ilike.%${n}%`)),d}async function Or(e,t){return e.from("products").select(`
22
+ *,
23
+ languages (
24
+ code
25
+ ),
26
+ product_media (
27
+ media_id,
28
+ sort_order,
29
+ media (
30
+ id,
31
+ file_path,
32
+ object_key,
33
+ file_name,
34
+ blur_data_url,
35
+ width,
36
+ height
37
+ )
38
+ ),
39
+ product_variants (
40
+ id,
41
+ sku,
42
+ upc,
43
+ main_media_id,
44
+ price,
45
+ prices,
46
+ sale_price,
47
+ sale_prices,
48
+ sale_start_at,
49
+ sale_end_at,
50
+ scheduled_price,
51
+ scheduled_prices,
52
+ scheduled_price_at,
53
+ stock_quantity,
54
+ media:main_media_id (
55
+ id,
56
+ file_path,
57
+ object_key,
58
+ description
59
+ ),
60
+ variant_attribute_mapping (
61
+ attribute_term_id,
62
+ product_attribute_terms (
63
+ id,
64
+ attribute_id,
65
+ value,
66
+ slug,
67
+ sort_order,
68
+ value_translations,
69
+ product_attributes (
70
+ id,
71
+ name,
72
+ slug,
73
+ name_translations
74
+ )
75
+ )
76
+ )
77
+ ),
78
+ freemius_plans (
79
+ id,
80
+ name,
81
+ title,
82
+ freemius_pricing (
83
+ id,
84
+ license_quota,
85
+ api_monthly_price,
86
+ api_annual_price,
87
+ api_lifetime_price,
88
+ override_monthly_price,
89
+ override_annual_price,
90
+ override_lifetime_price,
91
+ is_active
92
+ )
93
+ ),
94
+ product_categories (
95
+ category:categories (
96
+ id,
97
+ name,
98
+ slug,
99
+ description,
100
+ name_translations,
101
+ description_translations
102
+ )
103
+ )
104
+ `).eq("id",t).single()}async function Ss(e,t,r){const{data:n,error:i}=await e.from("products").select(`
105
+ *,
106
+ languages (
107
+ id,
108
+ code,
109
+ is_default
110
+ ),
111
+ product_media (
112
+ media_id,
113
+ sort_order,
114
+ media (
115
+ id,
116
+ file_path,
117
+ object_key,
118
+ file_name,
119
+ blur_data_url,
120
+ width,
121
+ height
122
+ )
123
+ ),
124
+ product_variants (
125
+ id,
126
+ sku,
127
+ upc,
128
+ main_media_id,
129
+ price,
130
+ prices,
131
+ sale_price,
132
+ sale_prices,
133
+ sale_start_at,
134
+ sale_end_at,
135
+ scheduled_price,
136
+ scheduled_prices,
137
+ scheduled_price_at,
138
+ stock_quantity,
139
+ media:main_media_id (
140
+ id,
141
+ file_path,
142
+ object_key,
143
+ description
144
+ ),
145
+ variant_attribute_mapping (
146
+ attribute_term_id,
147
+ product_attribute_terms (
148
+ id,
149
+ attribute_id,
150
+ value,
151
+ slug,
152
+ sort_order,
153
+ value_translations,
154
+ product_attributes (
155
+ id,
156
+ name,
157
+ slug,
158
+ name_translations
159
+ )
160
+ )
161
+ )
162
+ ),
163
+ freemius_plans (
164
+ id,
165
+ name,
166
+ title,
167
+ freemius_pricing (
168
+ id,
169
+ license_quota,
170
+ api_monthly_price,
171
+ api_annual_price,
172
+ api_lifetime_price,
173
+ override_monthly_price,
174
+ override_annual_price,
175
+ override_lifetime_price,
176
+ is_active
177
+ )
178
+ ),
179
+ product_categories (
180
+ category:categories (
181
+ id,
182
+ name,
183
+ slug,
184
+ description,
185
+ name_translations,
186
+ description_translations
187
+ )
188
+ )
189
+ `).eq("slug",t);if(i)return{data:null,error:i};if(!n||n.length===0)return{data:null,error:{message:"Product not found",code:"PGRST116"}};let o=null;return r&&(o=n.find(a=>(Array.isArray(a.languages)?a.languages[0]:a.languages)?.code===r)),o||(o=n.find(a=>(Array.isArray(a.languages)?a.languages[0]:a.languages)?.is_default)),o||(o=n.find(a=>(Array.isArray(a.languages)?a.languages[0]:a.languages)?.code==="en")),o||(o=n[0]),{data:o,error:null}}async function $r(e,t){const{data:r,error:n}=await e.rpc("upsert_product_with_variants",{product_payload:zr(t)});if(n||!r)throw n||new Error("Failed to create product");if(t.product_media&&t.product_media.length>0){const o=t.product_media.map((a,c)=>({product_id:r,media_id:a.media_id,sort_order:c}));await e.from("product_media").insert(o)}else t.media_id&&await e.from("product_media").insert({product_id:r,media_id:t.media_id,sort_order:0});await Dr(e,r,t.is_taxable),await qr(e,r,t),await Rr(r,t),t.category_ids!==void 0&&await Je(e,r,t.category_ids);const{data:i}=await e.from("products").select("*").eq("id",r).single();return i}async function ws(e,t,r){const{data:n}=await e.from("product_media").select("media_id").eq("product_id",t),i=n?.map(u=>u.media_id)||[],{data:o,error:a}=await e.rpc("upsert_product_with_variants",{product_payload:zr(r,t)});if(a||!o)throw a||new Error("Failed to update product");if(r.product_media){if(await e.from("product_media").delete().eq("product_id",t),r.product_media.length>0){const u=r.product_media.map((h,f)=>({product_id:t,media_id:h.media_id,sort_order:f}));await e.from("product_media").insert(u)}}else r.media_id&&(await e.from("product_media").delete().eq("product_id",t),await e.from("product_media").insert({product_id:t,media_id:r.media_id,sort_order:0}));await Dr(e,o,r.is_taxable),await qr(e,o,r);const c=r.product_media?r.product_media.map(u=>u.media_id):r.media_id?[r.media_id]:[],d=r.explicitly_removed_media_ids||[],m=i.filter(u=>!c.includes(u)),l=Array.from(new Set([...m,...d]));if(l.length>0)for(const u of l){const{count:h}=await e.from("product_media").select("*",{count:"exact",head:!0}).eq("media_id",u);if(h&&h>0)continue;const{count:f}=await e.from("posts").select("*",{count:"exact",head:!0}).eq("feature_image_id",u);if(f&&f>0)continue;const{count:b}=await e.from("logos").select("*",{count:"exact",head:!0}).eq("media_id",u);if(b&&b>0)continue;const{count:v}=await e.from("product_variants").select("*",{count:"exact",head:!0}).eq("main_media_id",u);if(v&&v>0)continue;const{data:w}=await e.from("media").select("object_key, variants").eq("id",u).single();if(w){const N=[w.object_key];w.variants&&Array.isArray(w.variants)&&w.variants.forEach(g=>{g.objectKey&&N.push(g.objectKey)}),await Sn.deleteMediaFiles(N),await e.from("media").delete().eq("id",u)}}await Rr(o,r),r.category_ids!==void 0&&await Je(e,t,r.category_ids);const{data:_}=await e.from("products").select("*").eq("id",o).single();return _}async function Lr(e,t){const{error:r}=await e.from("products").delete().eq("id",t);if(r)throw r;return!0}async function Br(e,t,r){const{data:n,error:i}=await e.from("products").select("*").eq("id",r).single();if(i||!n)throw new Error(i?.message||"Source product not found");const{data:o,error:a}=await e.from("products").select("language_id").eq("id",t).single();if(a||!o)throw new Error(a?.message||"Target product not found");const{error:c}=await e.from("products").update({title:n.title,short_description:n.short_description,description_json:n.description_json}).eq("id",t);if(c)throw c;const{data:d,error:m}=await e.from("blocks").select("*").eq("product_id",r).order("order",{ascending:!0});if(m)throw m;if(await e.from("blocks").delete().eq("product_id",t),d&&d.length>0){const _=d.map(h=>{const{id:f,created_at:b,updated_at:v,...w}=h;return{...w,product_id:t,language_id:o.language_id}}),{error:u}=await e.from("blocks").insert(_);if(u)throw u}await e.from("product_drafts").delete().eq("product_id",t),await e.from("product_media").delete().eq("product_id",t);const{data:l}=await e.from("product_media").select("media_id, sort_order").eq("product_id",r);if(l&&l.length>0){const _=l.map(u=>({product_id:t,media_id:u.media_id,sort_order:u.sort_order}));await e.from("product_media").insert(_)}return{success:!0}}async function Ns(e,t,r,n=[],i=[]){const{data:o}=await e.from("languages").select("id").eq("code",r).single();if(!o)return{data:[],error:"Language not found"};const a=[];t.length>0&&a.push(`translation_group_id.in.(${t.join(",")})`),n.length>0&&a.push(`sku.in.(${n.map(m=>`"${m}"`).join(",")})`),i.length>0&&a.push(`id.in.(${i.join(",")})`);let c=e.from("products").select(`
190
+ id,
191
+ title,
192
+ sku,
193
+ price,
194
+ prices,
195
+ sale_price,
196
+ sale_prices,
197
+ sale_start_at,
198
+ sale_end_at,
199
+ scheduled_price,
200
+ scheduled_prices,
201
+ scheduled_price_at,
202
+ stock,
203
+ slug,
204
+ language_id,
205
+ product_type,
206
+ payment_provider,
207
+ freemius_product_id,
208
+ freemius_plan_id,
209
+ trial_period_days,
210
+ trial_requires_payment_method,
211
+ is_taxable,
212
+ product_media (
213
+ media (
214
+ file_path,
215
+ object_key
216
+ )
217
+ ),
218
+ product_variants (
219
+ id,
220
+ sku,
221
+ upc,
222
+ main_media_id,
223
+ price,
224
+ prices,
225
+ sale_price,
226
+ sale_prices,
227
+ sale_start_at,
228
+ sale_end_at,
229
+ scheduled_price,
230
+ scheduled_prices,
231
+ scheduled_price_at,
232
+ stock_quantity,
233
+ media:main_media_id (
234
+ file_path,
235
+ object_key,
236
+ description
237
+ ),
238
+ variant_attribute_mapping (
239
+ attribute_term_id,
240
+ product_attribute_terms (
241
+ id,
242
+ attribute_id,
243
+ value,
244
+ slug,
245
+ sort_order,
246
+ value_translations,
247
+ product_attributes (
248
+ id,
249
+ name,
250
+ slug,
251
+ name_translations
252
+ )
253
+ )
254
+ )
255
+ ),
256
+ translation_group_id
257
+ `).eq("language_id",o.id).eq("status","active");return a.length>0&&(c=c.or(a.join(","))),await c.order("id")}async function Je(e,t,r){const{data:n}=await e.from("products").select("translation_group_id").eq("id",t).single();if(!n||!n.translation_group_id){if(await e.from("product_categories").delete().eq("product_id",t),r.length>0){const a=r.map(c=>({product_id:t,category_id:c}));await e.from("product_categories").insert(a)}return}const{data:i}=await e.from("products").select("id").eq("translation_group_id",n.translation_group_id),o=i&&i.length>0?i.map(a=>a.id):[t];if(await e.from("product_categories").delete().in("product_id",o),r.length>0){const a=[];for(const c of o)for(const d of r)a.push({product_id:c,category_id:d});await e.from("product_categories").insert(a)}}function B(e){const t=process.env[e];if(!t)return null;const r=t.trim();return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1).trim():r}function js(e){const t=e?.trim();if(!t)return{firstName:null,lastName:null};const[r,...n]=t.split(/\s+/);return{firstName:r||null,lastName:n.length>0?n.join(" "):null}}function Kr(e){if(e==null||e==="")return 0;const t=Number(e);return!Number.isFinite(t)||t<=0?0:Math.round(t)}function Ps(e){return e===!0||e===1||e==="1"||e==="true"}function Es(e,t){const r=e?.[t];return Array.isArray(r)?r:r&&typeof r=="object"?[r]:[]}function ut(e,t){for(const r of t){const n=Es(e,r);if(n.length>0)return n}return Array.isArray(e)?e:[]}function Pe(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function As(e){return e===null?0:e>5e3?(console.warn(`[Freemius Sync] Suspiciously high price detected: ${e}. Assuming it is already in cents.`),Math.round(e)):Math.round(e*100)}function ks(e){const t=Number(e);return!Number.isFinite(t)||t<1?1:Math.round(t)}function Vr(){const e=B("FREEMIUS_CHECKOUT_PRODUCTS_JSON");if(!e)return null;try{const t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch(t){return console.error("[Freemius Checkout] Failed to parse FREEMIUS_CHECKOUT_PRODUCTS_JSON:",t),null}}function jt(e){const t=Vr(),r=String(e),n=t?.[r],i=B("FREEMIUS_PRODUCT_ID"),o=B("FREEMIUS_ECOMMERCE_SANDBOX_PUBLIC_KEY"),a=B("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY");return n?.publicKey?{publicKey:n.publicKey,secretKey:n.secretKey??null,apiKey:n.apiKey??null,source:"product-map"}:process.env.FREEMIUS_SANDBOX_ENABLED==="true"&&i&&i===r&&o?{publicKey:o,secretKey:a,apiKey:B("FREEMIUS_API_KEY"),source:"single-product-sandbox-env"}:i&&i===r&&B("FREEMIUS_PUBLIC_KEY")?{publicKey:B("FREEMIUS_PUBLIC_KEY"),secretKey:B("FREEMIUS_SECRET_KEY"),apiKey:B("FREEMIUS_API_KEY"),source:"single-product-env"}:{publicKey:B("FREEMIUS_PUBLIC_KEY"),secretKey:B("FREEMIUS_SECRET_KEY"),apiKey:B("FREEMIUS_API_KEY"),source:"legacy-env"}}async function Is(e){if(!e.apiKey)throw new Error("Missing Freemius API key for SDK sandbox generation.");return new wn.Freemius({productId:Number(e.productId),apiKey:e.apiKey,secretKey:e.secretKey,publicKey:e.publicKey}).checkout.getSandboxParams()}class Ms{getProviderName(){return"Freemius"}async createCheckoutSession({items:t,customerEmail:r,customerPhone:n,userId:i,billingAddress:o,shippingAddress:a,currencyCode:c,couponCode:d,couponContextItems:m}){const l=process.env.NEXT_PUBLIC_SUPABASE_URL,_=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!l||!_)return{error:"Missing Supabase credentials for checkout (Service Key required).",url:null};const u=gt.createClient(l,_);if(!t||t.length===0)return{error:"Cart is empty",url:null};if(t.length!==1)return{error:"Freemius items must be checked out one at a time.",url:null};const{data:h,error:f}=await u.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}),b=h??[];if(f||b.length===0)return{error:"Failed to resolve store currencies",url:null};const v=ie(b),w=b.find(D=>D.code===(c||"").toUpperCase())??v,N=t[0],{data:g,error:F}=await u.from("products").select("id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, freemius_plan_id, freemius_product_id, trial_period_days, trial_requires_payment_method").eq("id",N.product_id).single();if(F||!g)return{error:"Product not found",url:null};const L=g.freemius_plan_id,T=g.freemius_product_id;if(!L||!T)return{error:"Product is not configured for Freemius checkout (missing Plan ID or Product ID)",url:null};const te=De({prices:g.prices||{},salePrices:g.sale_prices||{},fallbackPrice:g.price,fallbackSalePrice:g.sale_price,saleStartAt:g.sale_start_at,saleEndAt:g.sale_end_at,scheduledPrice:g.scheduled_price,scheduledPrices:g.scheduled_prices||{},scheduledPriceAt:g.scheduled_price_at,currencyCode:w.code,currencies:b}),A=te.sale_price??te.price,oe=Te({saleStartAt:g.sale_start_at,saleEndAt:g.sale_end_at}),I=A*N.quantity;let p=null,y=0;if(d){const D=await br({client:u,code:d,items:m&&m.length>0?m:t,currencyCode:w.code});if(!D.success)return{error:D.error,errorKey:D.errorKey,errorStatus:400,url:null};p=D.quote,y=Math.min(I,p.lineDiscounts.filter(se=>se.product_id===g.id).reduce((se,ue)=>se+ue.discount,0))}const C=Kr(g.trial_period_days),k=C>0?N.trial_preference?N.trial_preference:g.trial_requires_payment_method?"paid":"free":null,R="pending",U=js(o?.recipient_name??null),{data:K,error:Y}=await u.from("orders").insert({status:R,total:Math.max(0,I-y),currency:w.code,exchange_rate_at_purchase:w.exchange_rate,subtotal:I,discount_total:y,coupon_id:p?.couponId??null,coupon_code:p?.code??null,discount_details:p?{code:p.code,discount_type:p.discountType,discount_amount:p.discountAmount,provider:"freemius",provider_discounts:p.providerDiscounts,line_discounts:p.lineDiscounts,final_amount_owned_by:"freemius"}:null,provider:"freemius",freemius_product_id:String(T),freemius_plan_id:String(L),user_id:i||null,customer_details:Ir({email:r,phone:n,name:o?.recipient_name,billing:o,shipping:a})}).select("id").single();if(Y||!K)return console.error("Failed to create pending order:",Y),{error:"Failed to initiate order",url:null};const{error:V}=await u.from("order_items").insert([{order_id:K.id,product_id:g.id,quantity:N.quantity,price_at_purchase:A}]);if(V&&console.error("Failed to insert order items:",V),i)try{await Mr({userId:i,billingAddress:o,shippingAddress:a,client:u}),await Tr({userId:i,fullName:o?.recipient_name??a?.recipient_name??null,phone:n,client:u})}catch(D){console.error("Failed to sync checkout profile defaults before checkout:",D)}p&&await vr({client:u,quote:p,orderId:K.id,provider:"freemius",discountTotal:y,userId:i,customerEmail:r,metadata:{currency:w.code,subtotal:I,final_amount_owned_by:"freemius"}});const re=process.env.FREEMIUS_SANDBOX_ENABLED==="true",fe=jt(T),ae=fe.publicKey,ge=fe.secretKey,ke=fe.apiKey;if(!ae||re&&!ge)return{error:"Missing FREEMIUS credentials (PUBLIC_KEY or SECRET_KEY) in environment variables.",url:null};if(re&&fe.source==="legacy-env"){const D=B("FREEMIUS_PRODUCT_ID"),se=!!B("FREEMIUS_ECOMMERCE_SANDBOX_PUBLIC_KEY"),ue=!!B("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY");console.warn(`[Freemius Checkout] Sandbox is enabled for product ${T}, but no product-scoped checkout credentials were selected. Falling back to legacy FREEMIUS_PUBLIC_KEY/FREEMIUS_SECRET_KEY may open live checkout instead of sandbox.`,{configuredProductId:D,productIdsMatch:D===String(T),hasSandboxOverridePublicKey:se,hasSandboxOverrideSecretKey:ue,hasCheckoutProductsJson:!!B("FREEMIUS_CHECKOUT_PRODUCTS_JSON")})}let ne=!1;if(re&&ge&&ae)try{ne=await Is({productId:T,publicKey:ae,secretKey:ge,apiKey:ke})}catch(D){console.warn("Freemius Checkout - SDK sandbox generation failed. Falling back to manual token generation.",D,{credentialSource:fe.source,hasApiKey:!!ke});const se=Math.floor(Date.now()/1e3).toString(),ue=`${se}${T}${ge}${ae}checkout`,Ie=cr.createHash("md5").update(ue).digest("hex");ne={ctx:se,token:Ie}}const O=new URL(`https://checkout.freemius.com/app/${T}/plan/${L}/`);if(re&&ge&&ae?(O.searchParams.append("sandbox",ne.token),O.searchParams.append("s_ctx_ts",ne.ctx)):re&&O.searchParams.append("sandbox","true"),r&&O.searchParams.append("user_email",r),U.firstName&&O.searchParams.append("user_firstname",U.firstName),U.lastName&&O.searchParams.append("user_lastname",U.lastName),O.searchParams.append("currency",w.code.toLowerCase()),N.billing_cycle&&O.searchParams.append("billing_cycle",N.billing_cycle),k&&O.searchParams.append("trial",k),p)O.searchParams.append("coupon",p.code);else if(oe){const{data:D}=await u.from("product_freemius_sale_coupons").select("freemius_coupon_code, is_active, starts_at, ends_at, sync_status").eq("product_id",g.id).maybeSingle();D?.is_active&&D.sync_status==="synced"&&D.freemius_coupon_code&&Te({saleStartAt:D.starts_at,saleEndAt:D.ends_at})&&O.searchParams.append("coupon",D.freemius_coupon_code)}return{url:O.toString(),customProps:{provider:"freemius",plugin_id:T,plan_id:L,public_key:ae,user_email:r,user_firstname:U.firstName,user_lastname:U.lastName,credential_source:fe.source,sandbox:ne,billing_cycle:N.billing_cycle,trial:k,trial_period_days:C,trial_requires_payment_method:g.trial_requires_payment_method,initial_order_status:R,coupon:p?.code??null,order_id:K.id}}}}async function Yr(e,t,r,n){const o=new Date().toUTCString().replace("GMT","+0000"),a=`GET
258
+
259
+
260
+ ${o}
261
+ ${e}`,c=cr.createHmac("sha256",n).update(a).digest("hex"),d=Buffer.from(c).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),m=`FS ${t}:${r}:${d}`,l=await fetch(`https://api.freemius.com${e}`,{headers:{Authorization:m,Date:o,Accept:"application/json"}});if(!l.ok){const _=await l.text();throw console.error(`[Freemius API] [ERROR] ${e} returned ${l.status}: ${_}`),new Error(`Freemius API failed on ${e}: ${l.status} - ${_}`)}return l.json()}async function Gr(){const e=B("FREEMIUS_DEVELOPER_ID"),t=B("FREEMIUS_PUBLIC_KEY"),r=B("FREEMIUS_SECRET_KEY"),n=process.env.NEXT_PUBLIC_SUPABASE_URL,i=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!e||!t||!r||!n||!i)throw new Error("Missing necessary environment variables for Freemius Sync.");const o=gt.createClient(n,i,{auth:{autoRefreshToken:!1,persistSession:!1}}),a=c=>Yr(c,e,t,r);try{console.log(`[Freemius Sync] Fetching all plugins for developer ${e}...`);const c=await a(`/v1/developers/${e}/plugins.json`),d=ut(c,["plugins","plugin"]);console.log(`[Freemius Sync] Found ${d.length} plugins. Syncing plans...`);let m=0;const{data:l}=await o.from("languages").select("id").eq("code","en").single(),_=l?.id;if(!_)throw new Error("English language not found in database. Cannot sync products.");for(const u of d){const h=u.id?.toString();if(!h){console.warn("[Freemius Sync] Skipping plugin without an id:",u);continue}const f=await Hr(o,e,h,u.title||u.name||`Freemius Product ${h}`,a,_);m+=f}return{success:!0,count:m}}catch(c){throw console.error("[Freemius Sync] Global Error:",c),c}}async function Xr(e){const t=B("FREEMIUS_DEVELOPER_ID"),r=B("FREEMIUS_PUBLIC_KEY"),n=B("FREEMIUS_SECRET_KEY"),i=process.env.NEXT_PUBLIC_SUPABASE_URL,o=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!t||!r||!n||!i||!o)throw new Error("Missing environment variables for Freemius Sync.");const a=gt.createClient(i,o),c=h=>Yr(h,t,r,n),{data:d}=await a.from("languages").select("id").eq("code","en").single(),m=d?.id;if(!m)throw new Error("English language not found in database. Cannot sync products.");const l=await c(`/v1/developers/${t}/plugins/${e}.json`),_=l.plugin??l;return{success:!0,count:await Hr(a,t,e,_.title||_.name||`Freemius Product ${e}`,c,m)}}async function Hr(e,t,r,n,i,o){console.log(`[Freemius Sync] Fetching plans for plugin: ${n} (${r})...`);let a=0;try{const c=`/v1/developers/${t}/plugins/${r}/plans.json`,d=await i(c),m=ut(d,["plans","plan"]);console.log(`[Freemius Sync] Received ${m.length} plans for plugin ${r}.`);for(const l of m){const _=l.id?.toString();if(!_){console.warn("[Freemius Sync] Skipping plan without an id:",l);continue}const u=l.name||l.title||_,h=l.title||u;console.log(`[Freemius Sync] Processing plan: ${h} (${_})...`);let f=l;if(f.trial_period===void 0||f.is_require_subscription===void 0)try{const p=`/v1/developers/${t}/plugins/${r}/plans/${_}.json`,y=await i(p),C=y.plan??y;f={...f,...C}}catch(p){console.warn(`[Freemius Sync] Could not fetch trial details for plan ${_}:`,p instanceof Error?p.message:p)}const b=Kr(f.trial_period),v=b>0&&Ps(f.is_require_subscription);let w=0,N=[];try{const p=`/v1/developers/${t}/plugins/${r}/plans/${_}/pricing.json`,y=await i(p);if(N=ut(y,["pricing","prices","pricings"]),N.length>0){const C=N[0],k=Pe(C.annual_price)??Pe(C.monthly_price)??Pe(C.lifetime_price);w=As(k)}console.log(`[Freemius Sync] Plan: ${h} -> Resolved Price (cents): ${w}`)}catch(p){console.warn(`[Freemius Sync] Could not fetch pricing for plan ${_}:`,p instanceof Error?p.message:p)}const g=`${n}-${h}`.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,""),F={title:`${n} - ${h}`,slug:g,short_description:l.description||"",price:w,product_type:"digital",payment_provider:"freemius",freemius_plan_id:_,freemius_product_id:r,trial_period_days:b,trial_requires_payment_method:v,status:"active",stock:999,sku:`FM-${r}-${_}`,language_id:o},{data:L,error:T}=await e.from("products").upsert(F,{onConflict:"language_id, sku"}).select();if(T||!L||L.length===0){console.error(`[Freemius Sync] Error upserting product ${F.sku}:`,T);continue}const te=L[0].id,{data:A,error:oe}=await e.from("freemius_plans").select("id").eq("product_id",te).eq("name",u).maybeSingle();oe&&console.warn(`[Freemius Sync] Could not check existing local plan for ${F.sku}:`,oe.message||oe);let I="";if(A){I=A.id;const{error:p}=await e.from("freemius_plans").update({title:h,updated_at:new Date().toISOString()}).eq("id",I);p&&console.warn(`[Freemius Sync] Could not update local plan ${I}:`,p.message||p)}else{const{data:p,error:y}=await e.from("freemius_plans").insert({product_id:te,name:u,title:h}).select("id").single();y&&console.warn(`[Freemius Sync] Could not insert local plan for ${F.sku}:`,y.message||y),p&&(I=p.id)}if(I&&N.length>0)for(const p of N){const y=ks(p.licenses??p.license_quota??p.quota),{data:C,error:k}=await e.from("freemius_pricing").select("id").eq("plan_id",I).eq("license_quota",y).maybeSingle();k&&console.warn(`[Freemius Sync] Could not check pricing for plan ${I}, quota ${y}:`,k.message||k);const R={api_monthly_price:Pe(p.monthly_price),api_annual_price:Pe(p.annual_price),api_lifetime_price:Pe(p.lifetime_price),updated_at:new Date().toISOString()};if(C){const{error:U}=await e.from("freemius_pricing").update(R).eq("id",C.id);U&&console.warn(`[Freemius Sync] Could not update pricing ${C.id}:`,U.message||U)}else{const{error:U}=await e.from("freemius_pricing").insert({plan_id:I,license_quota:y,...R});U&&console.warn(`[Freemius Sync] Could not insert pricing for plan ${I}, quota ${y}:`,U.message||U)}}console.log(`[Freemius Sync] Successfully fully synced product ${F.sku}.`),a++}}catch(c){console.error(`[Freemius Sync] Failed sync for plugin ${r}:`,c.message)}return a}async function Ts(e){const t=z.createClient(),{data:r,count:n,error:i}=await await Ur(t,e);if(i)throw new Error(i.message);return{data:r,count:n}}async function Fs(e){const t=z.createClient(),{data:r,error:n}=await Or(t,e);if(n)throw new Error(n.message);return r}async function Rs(){try{const e=await Gr();return M.revalidatePath("/cms/products","page"),{success:!0,data:e}}catch(e){return{error:e.message||"Failed to sync with Freemius"}}}async function zs(e){try{const t=await Xr(e);return M.revalidatePath("/cms/products","page"),{success:!0,data:t}}catch(t){return{error:t.message||"Failed to sync product with Freemius"}}}async function Ds(e,t){try{const r=z.createClient();return await Br(r,e,t),M.revalidatePath("/cms/products"),M.revalidatePath(`/cms/products/${e}/edit`),{success:!0}}catch(r){return{success:!1,error:r.message||"Failed to copy product content"}}}async function qs(e){const t=z.createClient(),{data:r,error:n}=await t.from("products").select("id, title, language_id, slug").eq("translation_group_id",e);if(n)throw new Error(n.message);return r}async function Us(){const e=z.getServiceRoleSupabaseClient(),{data:t,error:r}=await e.from("product_attributes").select(`
262
+ id,
263
+ name,
264
+ name_translations,
265
+ slug,
266
+ product_attribute_terms (
267
+ id,
268
+ attribute_id,
269
+ value,
270
+ slug,
271
+ sort_order,
272
+ value_translations
273
+ )
274
+ `);if(r)throw new Error(r.message);return(t||[]).map(n=>({...n,product_attribute_terms:(n.product_attribute_terms||[]).sort((i,o)=>(i.sort_order??Number.MAX_SAFE_INTEGER)-(o.sort_order??Number.MAX_SAFE_INTEGER)||i.value.localeCompare(o.value))})).sort((n,i)=>n.name.localeCompare(i.name))}async function Os(e){const t=z.createClient(),{data:r,error:n}=await t.from("freemius_plans").select(`
275
+ id,
276
+ name,
277
+ title,
278
+ freemius_pricing (
279
+ id,
280
+ license_quota,
281
+ api_monthly_price,
282
+ api_annual_price,
283
+ api_lifetime_price,
284
+ override_monthly_price,
285
+ override_annual_price,
286
+ override_lifetime_price,
287
+ is_active
288
+ )
289
+ `).eq("product_id",e);if(n)throw new Error(n.message);return r}async function $s(e,t){const r=z.createClient(),{error:n}=await r.from("freemius_pricing").update({...t,updated_at:new Date().toISOString()}).eq("id",e);return n?{success:!1,error:n.message}:(M.revalidatePath("/cms/products"),{success:!0})}async function Ls(e){const t=z.createClient(),{data:r}=await t.from("products").select("translation_group_id").eq("id",e).maybeSingle();let n=[e];if(r?.translation_group_id){const{data:c}=await t.from("products").select("id").eq("translation_group_id",r.translation_group_id);c&&c.length>0&&(n=c.map(d=>d.id))}const{data:i,error:o}=await t.from("freemius_plans").select(`
290
+ id,
291
+ name,
292
+ title,
293
+ freemius_pricing (
294
+ id,
295
+ license_quota,
296
+ api_monthly_price,
297
+ api_annual_price,
298
+ api_lifetime_price,
299
+ override_monthly_price,
300
+ override_annual_price,
301
+ override_lifetime_price,
302
+ is_active
303
+ )
304
+ `).in("product_id",n);if(o)throw new Error(o.message);return(i||[]).map(c=>({id:c.id,name:c.name,title:c.title,pricing:(c.freemius_pricing||[]).filter(d=>d.is_active!==!1).map(d=>({id:d.id,license_quota:d.license_quota,monthly_price:d.override_monthly_price??d.api_monthly_price,annual_price:d.override_annual_price??d.api_annual_price,lifetime_price:d.override_lifetime_price??d.api_lifetime_price,is_active:d.is_active}))}))}async function Bs(){const e=z.createClient(),{data:t,error:r}=await e.from("categories").select("id, name, slug, description, created_at, name_translations, description_translations, product_categories(count)").order("name",{ascending:!0});if(r)throw new Error(r.message);return(t||[]).map(n=>{const i=n.product_categories?.[0]?.count??n.product_categories?.count??0;return{id:n.id,name:n.name,slug:n.slug,description:n.description??"",created_at:n.created_at,productCount:Number(i),name_translations:n.name_translations||{},description_translations:n.description_translations||{}}})}async function Ks(e){const t=z.createClient(),{data:r,error:n}=await t.from("categories").select("id, name, slug, description, created_at").eq("slug",e).maybeSingle();if(n)throw new Error(n.message);return r}async function Vs(e){const t=z.createClient(),{data:r,error:n}=await t.from("product_categories").select("category:categories(id, name, slug, description, name_translations, description_translations, created_at)").eq("product_id",e);if(n)throw new Error(n.message);return(r||[]).map(i=>i.category).filter(Boolean)}const Ys="invoice_settings",Pt={businessName:"",email:"",phone:"",address:{line1:"",line2:"",city:"",state:"",postal_code:"",country_code:"CA"},taxRegistrations:[]};function Z(e){return typeof e!="string"?"":e.trim()}function Wr(e){if(!e||typeof e!="object"||Array.isArray(e))return{...Pt.address};const t=e;return{line1:Z(t.line1),line2:Z(t.line2),city:Z(t.city),state:Z(t.state),postal_code:Z(t.postal_code),country_code:Z(t.country_code).toUpperCase()||"CA"}}function Qr(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;const r=t,n=Z(r.label),i=Z(r.value);return!n&&!i?null:{label:n,value:i}}).filter(t=>!!t):[]}function Gs(e){if(!e||typeof e!="object"||Array.isArray(e))return{...Pt};const t=e;return{businessName:Z(t.business_name??t.businessName),email:Z(t.email),phone:Z(t.phone),address:Wr(t.address),taxRegistrations:Qr(t.tax_registrations??t.taxRegistrations)}}function Xs(e){return{business_name:Z(e.businessName),email:Z(e.email),phone:Z(e.phone),address:Wr(e.address),tax_registrations:Qr(e.taxRegistrations)}}function pe(e,t="usd",r="en-US"){return new Intl.NumberFormat(r,{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Jr(e,t="en-US"){if(!e)return"";const r=new Date(e);return Number.isNaN(r.getTime())?"":new Intl.DateTimeFormat(t,{year:"numeric",month:"short",day:"numeric"}).format(r)}function Ke(e){if(!e)return[];const t=[e.city,e.state,e.postal_code].filter(Boolean).join(", ").replace(", ,",",").trim();return["company_name"in e&&e.company_name||"","recipient_name"in e&&e.recipient_name||"",e.line1||"",e.line2||"",t,e.country_code||""].filter(Boolean)}const Ht={gst:"GST",qst:"QST",hst:"HST",pst:"PST",vat:"VAT",sales_tax:"Sales Tax",amusement_tax:"Amusement Tax",retail_delivery_fee:"Retail Delivery Fee"};function Et(){return new Date().toISOString()}function Re(e){const t=e.tax_type?.trim().toLowerCase();return t&&Ht[t]?Ht[t]:e.display_name||"Tax"}function ze(e){return typeof e.effective_percentage=="number"?e.effective_percentage:typeof e.percentage=="number"?e.percentage:null}function Ge(e){return e.jurisdiction?e.jurisdiction:[e.state,e.country].filter(Boolean).join(", ")||null}function Hs(e){return JSON.stringify({source:e.source,rate_id:e.rate.id??null,display_name:Re(e.rate),percentage:ze(e.rate),jurisdiction:Ge(e.rate),jurisdiction_level:e.rate.jurisdiction_level??null,country:e.rate.country??null,state:e.rate.state??null,tax_type:e.rate.tax_type??null,inclusive:e.rate.inclusive??null})}function At(e){const t=new Map;for(const r of e){const n=Hs(r),i=t.get(n);if(!i){t.set(n,{...r,scope:"aggregate",line_item_id:null});continue}i.amount+=r.amount,typeof i.taxable_amount=="number"||typeof r.taxable_amount=="number"?i.taxable_amount=(typeof i.taxable_amount=="number"?i.taxable_amount:0)+(typeof r.taxable_amount=="number"?r.taxable_amount:0):i.taxable_amount=null,i.description!==r.description&&(i.description=null),i.taxability_reason!==r.taxability_reason&&(i.taxability_reason=null)}return[...t.values()].sort((r,n)=>{const i=Re(r.rate).localeCompare(Re(n.rate));return i!==0?i:(ze(r.rate)??0)-(ze(n.rate)??0)})}function Ws(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return typeof t.currency!="string"?null:{source:t.source==="manual"||t.source==="stripe_checkout"||t.source==="none"?t.source:"none",mode:t.mode==="automatic"?"automatic":"manual",currency:t.currency,subtotal:typeof t.subtotal=="number"?t.subtotal:0,shipping_total:typeof t.shipping_total=="number"?t.shipping_total:0,tax_total:typeof t.tax_total=="number"?t.tax_total:0,total:typeof t.total=="number"?t.total:0,is_finalized:!!t.is_finalized,lines:Array.isArray(t.lines)?At(t.lines):[],updated_at:typeof t.updated_at=="string"?t.updated_at:Et()}}function Qs(e){const t=e.currency||"usd",r=e.calculation.mode==="manual"&&!e.calculation.isPendingExternalCalculation;return{source:e.calculation.enabled&&e.calculation.mode==="manual"?"manual":e.calculation.mode==="automatic"?"stripe_checkout":"none",mode:e.calculation.mode,currency:t,subtotal:e.subtotal,shipping_total:e.shippingTotal,tax_total:e.calculation.amount,total:e.total,is_finalized:r,lines:e.calculation.enabled&&e.calculation.mode==="manual"?e.calculation.lines.map(n=>({scope:"aggregate",source:"manual",amount:n.amount,taxable_amount:e.calculation.taxableSubtotal,description:n.name,rate:{id:n.id??null,display_name:n.name,percentage:n.rate,country:n.country_code,state:n.state_code??null}})):[],updated_at:Et()}}function Wt(e){return{id:e.id,display_name:e.display_name,percentage:e.percentage,effective_percentage:e.effective_percentage,jurisdiction:e.jurisdiction,jurisdiction_level:e.jurisdiction_level,country:e.country,state:e.state,tax_type:e.tax_type,inclusive:e.inclusive,description:e.description}}function Js(e){const t=e.currency||e.session.currency||"usd",r=typeof e.session.amount_total=="number"?e.session.amount_total:0,n=e.session.total_details?.amount_tax??0,i=[];for(const a of e.lineItems)for(const c of a.taxes||[])i.push({scope:"line_item",source:"stripe_checkout",amount:c.amount,taxable_amount:c.taxable_amount,description:a.description||void 0,line_item_id:a.id,taxability_reason:c.taxability_reason,rate:Wt(c.rate)});if(i.length===0)for(const a of e.session.total_details?.breakdown?.taxes||[])i.push({scope:"aggregate",source:"stripe_checkout",amount:a.amount,taxable_amount:a.taxable_amount,description:a.rate.display_name,taxability_reason:a.taxability_reason,rate:Wt(a.rate)});const o=At(i);return{source:n>0||o.length>0?"stripe_checkout":"none",mode:e.fallbackMode==="manual"?"manual":"automatic",currency:t,subtotal:e.subtotal,shipping_total:e.shippingTotal,tax_total:n,total:r,is_finalized:!0,lines:o,updated_at:Et()}}function Zr({data:e,labels:t,locale:r="en-US",className:n=""}){const i=Ke(e.settings.address),o=Ke(e.order.customer_details?.billing),a=Ke(e.order.customer_details?.shipping);return s.jsxs("section",{className:`rounded-2xl border bg-white text-slate-900 shadow-sm print:rounded-none print:border-0 print:text-[10px] print:shadow-none ${n}`,children:[s.jsx("div",{className:"border-b px-6 py-6 print:px-0",children:s.jsxs("div",{className:"grid gap-6 md:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] md:items-start print:grid-cols-[minmax(0,1fr)_72px_280px] print:items-start print:gap-4",children:[s.jsxs("div",{className:"order-2 max-w-md space-y-4 print:order-none print:max-w-none print:space-y-2 md:order-none",children:[s.jsxs("div",{className:"space-y-1 text-sm print:text-[10px]",children:[s.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-slate-500",children:t.from}),e.settings.businessName?s.jsx("p",{className:"text-base font-semibold",children:e.settings.businessName}):null,i.map((c,d)=>s.jsx("p",{children:c},`seller-${d}-${c}`)),e.settings.email?s.jsx("p",{children:e.settings.email}):null,e.settings.phone?s.jsx("p",{children:e.settings.phone}):null]}),e.settings.taxRegistrations.length>0?s.jsxs("div",{className:"rounded-xl border bg-slate-50 px-4 py-3 text-sm print:px-3 print:py-2 print:text-[10px]",children:[s.jsx("p",{className:"mb-2 font-semibold",children:t.taxRegistrations}),s.jsx("div",{className:"space-y-1",children:e.settings.taxRegistrations.map((c,d)=>s.jsxs("p",{children:[s.jsx("span",{className:"font-medium",children:c.label}),c.label&&c.value?": ":"",c.value]},`${c.label}-${c.value}-${d}`))})]}):null]}),s.jsx("div",{className:"order-1 flex justify-center md:order-none md:pt-2 print:order-none print:pt-1",children:e.logo?.url?s.jsx(ar,{src:e.logo.url,alt:e.logo.name||e.settings.businessName||"Logo",className:"mx-auto h-24 w-auto object-contain print:h-14",width:e.logo.width||320,height:e.logo.height||120}):null}),s.jsx("div",{className:"order-3 flex justify-start md:order-none md:justify-end print:order-none",children:s.jsxs("div",{className:"w-full max-w-[380px] rounded-2xl bg-slate-950 px-5 py-5 text-white print:max-w-none print:border print:border-slate-300 print:bg-white print:px-3 print:py-3 print:text-[10px] print:text-slate-950",children:[s.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/70 print:text-slate-500",children:t.invoice}),s.jsxs("div",{className:"mt-4 space-y-3 text-sm print:mt-3 print:space-y-2 print:text-[10px]",children:[s.jsx(Ue,{label:t.invoiceNumber,value:e.order.invoice_number||"--"}),s.jsx(Ue,{label:t.orderNumber,value:e.order.id}),s.jsx(Ue,{label:t.paidOn,value:Jr(e.order.paid_at||e.order.created_at,r)||"--"}),s.jsx(Ue,{label:t.status,value:e.order.status})]})]})})]})}),s.jsxs("div",{className:"grid gap-4 border-b px-6 py-6 md:grid-cols-2 print:grid-cols-2 print:gap-3 print:px-0 print:py-3",children:[s.jsx(Qt,{title:t.billTo,lines:o}),s.jsx(Qt,{title:t.shipTo,lines:a})]}),s.jsxs("div",{className:"px-6 py-6 print:px-0 print:py-3",children:[s.jsx("div",{className:"overflow-hidden rounded-2xl border",children:s.jsxs("table",{className:"w-full border-collapse text-sm print:table-fixed print:text-[9px]",children:[s.jsx("thead",{className:"bg-slate-50",children:s.jsxs("tr",{children:[s.jsx("th",{className:"px-4 py-3 text-left font-semibold print:w-[22%] print:px-2 print:py-1.5",children:t.item}),s.jsx("th",{className:"px-4 py-3 text-left font-semibold print:w-[38%] print:px-2 print:py-1.5",children:t.details}),s.jsx("th",{className:"px-4 py-3 text-right font-semibold print:w-[10%] print:px-2 print:py-1.5",children:t.quantity}),s.jsx("th",{className:"px-4 py-3 text-right font-semibold print:w-[15%] print:px-2 print:py-1.5",children:t.price}),s.jsx("th",{className:"px-4 py-3 text-right font-semibold print:w-[15%] print:px-2 print:py-1.5",children:t.amount})]})}),s.jsx("tbody",{children:e.order.items.map(c=>s.jsxs("tr",{className:"border-t",children:[s.jsx("td",{className:"px-4 py-4 font-medium print:px-2 print:py-1.5",children:c.title}),s.jsx("td",{className:"px-4 py-4 text-slate-600 print:px-2 print:py-1.5",children:c.description||"--"}),s.jsx("td",{className:"px-4 py-4 text-right print:px-2 print:py-1.5",children:c.quantity}),s.jsx("td",{className:"px-4 py-4 text-right print:px-2 print:py-1.5",children:pe(c.unit_amount,e.order.currency,r)}),s.jsx("td",{className:"px-4 py-4 text-right font-medium print:px-2 print:py-1.5",children:pe(c.total_amount,e.order.currency,r)})]},c.id))})]})}),s.jsxs("div",{className:"mt-6 grid gap-6 md:grid-cols-[minmax(0,1fr)_320px] print:mt-4 print:grid-cols-[minmax(0,1fr)_220px] print:items-start print:gap-4",children:[s.jsx("div",{children:e.order.tax_details?.lines?.length?s.jsxs("div",{className:"rounded-xl border bg-slate-50 px-5 py-4 print:break-inside-avoid print:px-3 print:py-2.5 print:text-[10px]",children:[s.jsx("p",{className:"mb-3 font-semibold",children:t.taxBreakdown}),s.jsx("div",{className:"space-y-3 text-sm print:space-y-2 print:text-[10px]",children:e.order.tax_details.lines.map((c,d)=>{const m=ze(c.rate);return s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsxs("p",{className:"font-medium",children:[Re(c.rate),typeof m=="number"?` - ${m.toFixed(4)}%`:""]}),Ge(c.rate)?s.jsx("p",{className:"text-xs text-slate-500 print:text-[9px]",children:Ge(c.rate)}):null]}),s.jsx("span",{children:pe(c.amount,e.order.currency,r)})]},`${c.rate.display_name}-${c.description||"tax"}-${d}`)})})]}):null}),s.jsxs("div",{className:"rounded-xl border bg-slate-950 px-5 py-5 text-sm text-white print:break-inside-avoid print:border-slate-300 print:bg-white print:px-3 print:py-3 print:text-[10px] print:text-slate-950",children:[s.jsxs("div",{className:"space-y-3 print:space-y-2",children:[s.jsx(Me,{label:t.subtotal,value:pe(e.order.subtotal,e.order.currency,r)}),e.order.discount_total>0?s.jsx(Me,{label:e.order.coupon_code?`${t.discount} (${e.order.coupon_code})`:t.discount,value:`-${pe(e.order.discount_total,e.order.currency,r)}`}):null,s.jsx(Me,{label:t.shipping,value:pe(e.order.shipping_total,e.order.currency,r)}),s.jsx(Me,{label:t.tax,value:pe(e.order.tax_total,e.order.currency,r)})]}),s.jsx("div",{className:"mt-4 border-t border-white/15 pt-4 print:mt-3 print:border-slate-300 print:pt-3",children:s.jsx(Me,{label:t.total,value:pe(e.order.total,e.order.currency,r),strong:!0})})]})]})]})]})}function Qt({title:e,lines:t}){return s.jsxs("div",{className:"rounded-xl border bg-slate-50 px-5 py-4 print:break-inside-avoid print:px-3 print:py-2.5 print:text-[10px]",children:[s.jsx("p",{className:"mb-3 text-xs font-semibold uppercase tracking-[0.2em] text-slate-500",children:e}),t.length?s.jsx("div",{className:"space-y-1 text-sm print:text-[10px]",children:t.map((r,n)=>s.jsx("p",{children:r},`${e}-${n}-${r}`))}):s.jsx("p",{className:"text-sm text-slate-500",children:"--"})]})}function Ue({label:e,value:t}){return s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("span",{className:"text-white/70 print:text-[9px] print:text-slate-500",children:e}),s.jsx("span",{className:"text-right font-medium",children:t})]})}function Me({label:e,value:t,strong:r=!1}){return s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("span",{className:r?"text-base font-semibold print:text-sm":"text-white/75 print:text-[9px] print:text-slate-500",children:e}),s.jsx("span",{className:r?"text-lg font-semibold print:text-base":"font-medium",children:t})]})}function Zs({invoice:e,labels:t,locale:r,title:n,description:i,printLabel:o,headerVisual:a,action:c,loading:d=!1,loadingMessage:m,error:l,emptyMessage:_,className:u="",showHeader:h=!0}){return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:`
305
+ @media print {
306
+ @page {
307
+ size: portrait;
308
+ margin: 12mm;
309
+ }
310
+
311
+ body {
312
+ background: white !important;
313
+ }
314
+
315
+ body * {
316
+ visibility: hidden;
317
+ }
318
+
319
+ [data-print-invoice-root],
320
+ [data-print-invoice-root] * {
321
+ visibility: visible;
322
+ }
323
+
324
+ [data-print-invoice-root] {
325
+ position: absolute;
326
+ inset: 0;
327
+ width: 100%;
328
+ margin: 0;
329
+ padding: 0;
330
+ }
331
+ }
332
+ `}),s.jsxs("div",{className:`mx-auto max-w-6xl px-4 py-10 md:px-6 print:max-w-none print:px-0 print:py-0 ${u}`,children:[h?s.jsxs("div",{className:"mb-6 flex flex-col gap-4 md:flex-row md:items-center md:justify-between print:hidden",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[a?s.jsx("div",{className:"shrink-0",children:a}):null,s.jsxs("div",{children:[s.jsx("h1",{className:"text-3xl font-bold",children:n}),i?s.jsx("p",{className:"text-sm text-muted-foreground",children:i}):null]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs(Ot.Button,{type:"button",variant:"outline",onClick:()=>window.print(),disabled:!e,children:[s.jsx(H.Printer,{className:"mr-2 h-4 w-4"}),o]}),c?s.jsx(Ot.Button,{asChild:!0,variant:c.variant||"default",children:s.jsx(it,{href:c.href,children:c.label})}):null]})]}):null,d?s.jsx("div",{className:"mb-6 flex items-center justify-center gap-3 rounded-2xl border bg-background px-5 py-4 text-sm text-muted-foreground print:hidden",children:m}):null,l?s.jsx("div",{className:"mb-6 rounded-2xl border border-amber-200 bg-amber-50 px-5 py-4 text-sm text-amber-700 print:hidden",children:l}):null,e?s.jsx("div",{"data-print-invoice-root":!0,children:s.jsx(Zr,{data:e,labels:t,locale:r})}):!d&&!l?s.jsx("div",{className:"rounded-2xl border bg-background px-6 py-12 text-center text-muted-foreground print:hidden",children:_}):null]})]})}S.z.config({jitless:!0});const ei=S.z.enum(["physical","digital"]).or(S.z.literal("")).refine(e=>e!=="",{message:"Product type is required"}).transform(e=>e),en=S.z.record(S.z.string().regex(/^[A-Z]{3}$/,"Currency code must be ISO 4217"),S.z.coerce.number().min(0,"Prices must be non-negative")),tn=S.z.record(S.z.string().regex(/^[A-Z]{3}$/,"Currency code must be ISO 4217"),S.z.coerce.number().min(0,"Sale prices must be non-negative").nullable()),Xe=S.z.string().trim().refine(e=>e===""||!Number.isNaN(Date.parse(e)),{message:"Must be a valid date and time"}).transform(e=>e===""?null:e).nullable().optional();function rn(e,t){if(!e||!t)return!0;const r=Date.parse(e),n=Date.parse(t);return Number.isNaN(r)||Number.isNaN(n)?!0:r<n}const ti=S.z.object({attribute_id:S.z.string().uuid(),attribute_name:S.z.string(),term_id:S.z.string().uuid(),term_value:S.z.string(),term_slug:S.z.string().optional()}),ri=S.z.object({id:S.z.string().uuid().optional(),combination_key:S.z.string().min(1),sku:S.z.string().min(1,"Variant SKU is required"),upc:S.z.string().optional().nullable(),price:S.z.coerce.number().min(0,"Variant price must be non-negative"),prices:en.default({}),sale_price:S.z.coerce.number().min(0,"Variant sale price must be non-negative").optional().nullable(),sale_prices:tn.default({}),sale_start_at:Xe,sale_end_at:Xe,stock_quantity:S.z.coerce.number().int().min(0,"Variant stock must be a non-negative integer"),main_media_id:S.z.string().uuid().optional().nullable(),main_image_url:S.z.string().optional().nullable(),attribute_term_ids:S.z.array(S.z.string().uuid()).min(1),selected_options:S.z.array(ti).min(1),label:S.z.string().min(1)}).refine(e=>e.sale_price===null||e.sale_price===void 0||e.sale_price<=e.price,{message:"Variant sale price cannot exceed the regular price",path:["sale_price"]}).refine(e=>Object.entries(e.sale_prices||{}).every(([t,r])=>{if(r==null)return!0;const n=e.prices?.[t];return typeof n=="number"?r<=n:!0}),{message:"Variant sale prices cannot exceed regular prices",path:["sale_prices"]}).refine(e=>rn(e.sale_start_at,e.sale_end_at),{message:"Sale end must be after the sale start",path:["sale_end_at"]}),ni=S.z.object({attribute_id:S.z.string().uuid(),term_ids:S.z.array(S.z.string().uuid())}),nn=S.z.object({product_type:ei,payment_provider:S.z.enum(["stripe","freemius"]),title:S.z.string().min(1,"Title is required"),slug:S.z.string().min(1,"Slug is required").regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Slug must be lowercase alphanumeric with hyphens"),sku:S.z.string().min(1,"SKU is required"),upc:S.z.string().optional().nullable(),price:S.z.coerce.number().min(0,"Price must be non-negative"),prices:en.default({}),sale_price:S.z.coerce.number().min(0,"Sale price must be non-negative").optional().nullable(),sale_prices:tn.default({}),sale_start_at:Xe,sale_end_at:Xe,stock:S.z.coerce.number().int().min(0,"Stock must be a non-negative integer"),meta_title:S.z.string().optional().nullable(),meta_description:S.z.string().optional().nullable(),short_description:S.z.string().optional(),description_json:S.z.any().optional(),freemius_plan_id:S.z.string().optional(),freemius_product_id:S.z.string().optional(),trial_period_days:S.z.coerce.number().int().min(0,"Trial period must be zero or greater").default(0),trial_requires_payment_method:S.z.boolean().default(!1),media_id:S.z.string().optional(),product_media:S.z.array(S.z.object({media_id:S.z.string()})).optional(),category_ids:S.z.array(S.z.string().uuid()).optional(),is_taxable:S.z.boolean(),status:S.z.enum(["draft","active","archived"]),language_id:S.z.coerce.number().int().min(1,"Language is required"),translation_group_id:S.z.string().uuid().optional().or(S.z.literal("")).transform(e=>e===""?void 0:e),explicitly_removed_media_ids:S.z.array(S.z.string()).optional(),variation_attributes:S.z.array(ni).optional(),variants:S.z.array(ri).optional()}).refine(e=>e.sale_price===null||e.sale_price===void 0||e.sale_price<=e.price,{message:"Sale price cannot exceed the regular price",path:["sale_price"]}).refine(e=>Object.entries(e.sale_prices||{}).every(([t,r])=>{if(r==null)return!0;const n=e.prices?.[t];return typeof n=="number"?r<=n:!0}),{message:"Sale prices cannot exceed regular prices",path:["sale_prices"]}).refine(e=>rn(e.sale_start_at,e.sale_end_at),{message:"Sale end must be after the sale start",path:["sale_end_at"]}),Jt=process.env.NEXT_PUBLIC_R2_BASE_URL||"",Zt=e=>e?e.startsWith("http")||!Jt?e:`${Jt.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:"",si=({initialMedia:e,onUpdate:t,mediaPickerNode:r})=>{const[n,i]=P.useState(e),o=P.useRef(null),a=P.useRef(null);P.useEffect(()=>{i(e)},[e]);const c=(h,f)=>{o.current=f,h.dataTransfer.effectAllowed="move"},d=(h,f)=>{a.current=f,h.preventDefault()},m=h=>{h.preventDefault()},l=h=>{if(h.preventDefault(),o.current===null||a.current===null)return;const f=[...n],b=f[o.current];f.splice(o.current,1),f.splice(a.current,0,b),o.current=null,a.current=null;const v=f.map((w,N)=>({...w,sort_order:N}));i(v),t(v)},_=h=>{if(!h||n.some(v=>v.media_id===h.id))return;const f={id:`temp-${Date.now()}`,media_id:h.id,file_path:h.file_path||h.object_key,alt:h.description||h.file_name||"",sort_order:n.length,isNew:!0},b=[...n,f];i(b),t(b)},u=h=>{const b=n.filter((v,w)=>w!==h).map((v,w)=>({...v,sort_order:w}));i(b),t(b)};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-4",children:[n.map((h,f)=>s.jsxs("div",{className:"group relative aspect-square bg-muted/40 rounded-lg border overflow-hidden cursor-move transition-all hover:shadow-md",draggable:!0,onDragStart:b=>c(b,f),onDragEnter:b=>d(b,f),onDragOver:m,onDrop:l,children:[f===0&&s.jsx("div",{className:"absolute top-2 left-2 z-10 bg-primary text-primary-foreground text-[10px] font-bold px-2 py-0.5 rounded shadow-sm",children:"MAIN"}),s.jsx("button",{type:"button",onClick:()=>u(f),className:"absolute top-1 right-1 z-20 p-1 bg-destructive/90 text-destructive-foreground rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx(H.X,{className:"w-3 h-3"})}),s.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/5 transition-colors pointer-events-none"}),s.jsx("div",{className:"absolute bottom-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx(H.GripVertical,{className:"w-4 h-4 text-white drop-shadow-md"})}),Zt(h.file_path)?s.jsx(ar,{src:Zt(h.file_path),alt:h.alt,fill:!0,className:"object-cover",sizes:"(max-width: 768px) 50vw, 33vw"}):s.jsx("div",{className:"flex h-full w-full items-center justify-center text-muted-foreground",children:s.jsx(H.Image,{className:"w-8 h-8 opacity-30"})})]},h.id)),r?P.cloneElement(r,{onSelect:_,children:s.jsxs("button",{type:"button",className:"group relative aspect-square flex flex-col items-center justify-center border-2 border-dashed rounded-lg bg-muted/10 text-muted-foreground hover:bg-muted/20 hover:border-muted-foreground/50 transition-all focus:outline-none focus:ring-2 focus:ring-primary",children:[s.jsx(H.Image,{className:"w-8 h-8 mb-2 opacity-50 group-hover:opacity-75 transition-opacity"}),s.jsx("span",{className:"text-sm font-medium",children:"Add Image"})]})}):s.jsxs("div",{className:"relative aspect-square flex flex-col items-center justify-center border-2 border-dashed rounded-lg bg-muted/10 text-muted-foreground",children:[s.jsx(H.Image,{className:"w-8 h-8 mb-2 opacity-30"}),s.jsx("span",{className:"text-xs text-center px-2",children:"Media Picker not injected"})]})]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag and drop images to reorder. The first image will be used as the main product image."})]})};function ii({productId:e}){const[t,r]=P.useState(!1),n=async()=>{if(!e){Se.toast.error("Product ID is missing");return}r(!0);try{const i=await zs(e);i.error?Se.toast.error(i.error):Se.toast.success("Pricing sync complete!")}catch(i){Se.toast.error(i.message||"An unexpected error occurred during sync")}finally{r(!1)}};return s.jsxs(x.Button,{variant:"outline",onClick:n,disabled:t,className:"gap-2",children:[s.jsx(H.RefreshCw,{className:`w-4 h-4 ${t?"animate-spin":""}`}),t?"Syncing...":"Sync Prices from Freemius"]})}function lt({idPrefix:e="currency",currencies:t,prices:r,salePrices:n,managedCurrencyCodes:i=[],onPriceChange:o,onSalePriceChange:a,readOnly:c=!1,helperText:d,trailing:m}){const l=t.find(u=>u.is_default)??t[0],_=new Set(i);return l?s.jsxs("div",{className:"flex flex-col gap-2",children:[d&&s.jsx("p",{className:"text-xs text-muted-foreground bg-muted/20 p-2 rounded-md border",children:d}),s.jsx("div",{className:"divide-y divide-muted/50",children:t.map(u=>{const h=W(u),f=h.is_default!==!0&&_.has(h.code),b=c||f;return s.jsxs("div",{className:"flex flex-wrap items-stretch gap-4 py-3 first:pt-0 last:pb-0",children:[s.jsxs("div",{className:"flex items-center gap-2 w-[160px] shrink-0 self-stretch border-r border-border/50 pr-4",children:[s.jsx("span",{className:"text-sm font-black tracking-tighter text-foreground",children:h.code}),s.jsx("span",{className:"text-[11px] text-muted-foreground font-medium",children:h.symbol}),h.is_default?s.jsx("span",{className:"text-[9px] uppercase font-bold bg-primary/10 text-primary px-1.5 py-0.5 rounded tracking-widest leading-none",children:"Default"}):f?s.jsx("span",{className:"text-[9px] uppercase font-bold bg-muted text-muted-foreground px-1.5 py-0.5 rounded tracking-widest leading-none",children:"Auto"}):null,!h.is_default&&s.jsxs("span",{className:"text-[9px] text-muted-foreground/80 font-medium tracking-wide leading-none ml-auto",children:["x",h.exchange_rate]})]}),s.jsxs("div",{className:"grid flex-1 grid-cols-2 items-end gap-3 sm:grid-cols-4",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[s.jsx(x.Label,{htmlFor:`${e}-price-${h.code}`,className:"block text-[10px] uppercase font-bold text-muted-foreground tracking-widest",children:"Price"}),s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-bold pointer-events-none",children:h.symbol}),s.jsx(x.Input,{id:`${e}-price-${h.code}`,type:"number",step:"0.01",min:"0",value:r[h.code]??"",disabled:b,className:"h-8 w-full text-sm pl-6",onChange:v=>o(h.code,Number(v.target.value||0))})]})]}),s.jsxs("div",{className:"min-w-0 space-y-1",children:[s.jsx(x.Label,{htmlFor:`${e}-sale-price-${h.code}`,className:"block text-[10px] uppercase font-bold text-muted-foreground tracking-widest",children:"Sale"}),s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-bold pointer-events-none",children:h.symbol}),s.jsx(x.Input,{id:`${e}-sale-price-${h.code}`,type:"number",step:"0.01",min:"0",value:n[h.code]??"",disabled:b,placeholder:f?"Auto":"—",className:"h-8 w-full text-sm pl-6",onChange:v=>a(h.code,v.target.value===""?null:Number(v.target.value))})]})]}),m&&h.is_default?m:null]})]},h.code)})})]}):null}const Oe=e=>String(e).padStart(2,"0");function $e(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":`${t.getFullYear()}-${Oe(t.getMonth()+1)}-${Oe(t.getDate())}T${Oe(t.getHours())}:${Oe(t.getMinutes())}`}function Le(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t.toISOString()}function mt({idPrefix:e="product",startAt:t,endAt:r,onChange:n,error:i,disabled:o,description:a,dense:c,bare:d}){const m=Intl.DateTimeFormat().resolvedOptions().timeZone,l=E.cn("h-7 text-xs",c||d?"w-[150px]":"w-[160px] sm:w-[180px]"),_=s.jsxs(s.Fragment,{children:[s.jsx(x.Label,{htmlFor:`${e}-sale-start-at`,className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Starts"}),s.jsx(x.Input,{id:`${e}-sale-start-at`,type:"datetime-local",value:$e(t),disabled:o,onChange:u=>n("sale_start_at",Le(u.target.value)),className:l}),s.jsx("span",{className:"text-xs text-muted-foreground",children:"→"}),s.jsx(x.Label,{htmlFor:`${e}-sale-end-at`,className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Ends"}),s.jsx(x.Input,{id:`${e}-sale-end-at`,type:"datetime-local",value:$e(r),disabled:o,onChange:u=>n("sale_end_at",Le(u.target.value)),className:l})]});return d?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[s.jsx(x.Label,{htmlFor:`${e}-sale-start-at`,className:"block text-[10px] uppercase font-bold tracking-widest text-muted-foreground",children:"Starts"}),s.jsx(x.Input,{id:`${e}-sale-start-at`,type:"datetime-local",value:$e(t),disabled:o,onChange:u=>n("sale_start_at",Le(u.target.value)),className:"h-8 w-full text-xs"})]}),s.jsxs("div",{className:"min-w-0 space-y-1",children:[s.jsx(x.Label,{htmlFor:`${e}-sale-end-at`,className:"block text-[10px] uppercase font-bold tracking-widest text-muted-foreground",children:"Ends"}),s.jsx(x.Input,{id:`${e}-sale-end-at`,type:"datetime-local",value:$e(r),disabled:o,onChange:u=>n("sale_end_at",Le(u.target.value)),className:"h-8 w-full text-xs"}),i?s.jsx("p",{className:"mt-0.5 text-[10px] text-destructive",children:i}):null]})]}):s.jsxs("div",{className:E.cn("rounded border border-dashed bg-muted/5 space-y-1",c?"p-1.5":"p-2"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5",children:[s.jsx("span",{className:"shrink-0 text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Sale window"}),_,s.jsxs("span",{className:"ml-auto text-[10px] text-muted-foreground",children:[m||"local time"," · empty = always on"]})]}),a&&!c?s.jsx("p",{className:"text-[10px] leading-snug text-muted-foreground",children:a}):null,i?s.jsx("p",{className:"text-[11px] text-destructive",children:i}):null]})}function pt(e){return Object.entries(e||{}).reduce((t,[r,n])=>(typeof n=="number"&&Number.isFinite(n)&&n>=0?t[E.normalizeCurrencyCode(r)]=n:n===null&&(t[E.normalizeCurrencyCode(r)]=null),t),{})}function _t(e){const t=W(e);return t.is_default!==!0&&t.auto_sync_product_prices===!0}function kt(e){return e.map(t=>W(t)).filter(t=>_t(t)).map(t=>t.code)}function He(e,t){const r=new Set(kt(t)),n=pt(e);return Object.entries(n).reduce((i,[o,a])=>(r.has(o)||(i[o]=a),i),{})}function er(e){const{baseAmount:t,defaultCurrencyCode:r,targetCurrencyCode:n,currencies:i}=e;if(typeof t!="number"||!Number.isFinite(t)||t<0)return null;const o=_e({amount:E.majorUnitAmountToMinor(t,r),fromCurrencyCode:r,toCurrencyCode:n,currencies:i,applyRounding:!0});return E.minorUnitAmountToMajor(o,n)}function sn(e){const{currencies:t,fallbackPrice:r,fallbackSalePrice:n}=e,i=pt(e.prices),o=pt(e.salePrices),a=t.find(u=>u.is_default)??t[0];if(!a)return{prices:i,salePrices:o};const c=E.normalizeCurrencyCode(a.code),d=i[c]??(typeof r=="number"?r:null),m=o[c]??(typeof n=="number"?n:null),l=t.reduce((u,h)=>{const f=W(h);return _t(f)?(u[f.code]=er({baseAmount:d,defaultCurrencyCode:c,targetCurrencyCode:f.code,currencies:t}),u):(u[f.code]=i[f.code]??(f.code===c?d:void 0),u)},{}),_=t.reduce((u,h)=>{const f=W(h);return _t(f)?(u[f.code]=er({baseAmount:m,defaultCurrencyCode:c,targetCurrencyCode:f.code,currencies:t}),u):(u[f.code]=o[f.code]??(f.code===c?m:void 0),u)},{});return{prices:l,salePrices:_}}function oi(e,t){const r=t.find(a=>a.is_default)??t[0],n=r?E.normalizeCurrencyCode(r.code):"USD",i=He(e.prices,t),o=He(e.sale_prices,t);return{...e,price:typeof i[n]=="number"?i[n]:e.price,prices:i,sale_price:typeof o[n]=="number"?o[n]:e.sale_price??null,sale_prices:o}}function ft(e,t){return e?.map(r=>oi(r,t))||[]}function Ze(e,t){const r=t.find(a=>a.is_default)??t[0],n=r?E.normalizeCurrencyCode(r.code):"USD",i=He(e.prices,t),o=He(e.sale_prices,t);return{...e,price:typeof i[n]=="number"?i[n]:e.price,prices:i,sale_price:typeof o[n]=="number"?o[n]:e.sale_price??null,sale_prices:o,variants:ft(e.variants,t)}}const tr=process.env.NEXT_PUBLIC_R2_BASE_URL||"",rr=process.env.NEXT_PUBLIC_SUPABASE_URL||"",ai=e=>e.startsWith("http")?e:tr?`${tr.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:rr?`${rr.replace(/\/+$/,"")}/storage/v1/object/public/media/${e.replace(/^\/+/,"")}`:e;function nr(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t}).format(e)}function ci(e){return Object.entries(e).filter(([,t])=>t.length>0).map(([t,r])=>({attribute_id:t,term_ids:r}))}function di({globalAttributes:e,currentLanguageCode:t,baseSku:r,basePrice:n,basePrices:i,baseSalePrice:o,baseSalePrices:a,currencies:c,availableVariantImages:d=[],initialVariationAttributes:m,initialVariants:l,onChange:_}){const[u,h]=P.useState(()=>m&&m.length>0?m.reduce((p,y)=>(p[y.attribute_id]=y.term_ids,p),{}):wr(l||[])),[f,b]=P.useState(ft(l||[],c)),v=P.useMemo(()=>e.map(p=>({attribute_id:p.id,attribute_name:ct(p,t),terms:p.terms.filter(y=>(u[p.id]||[]).includes(y.id)).map(y=>({...y,value:dt(y,t)}))})).filter(p=>p.terms.length>0),[t,e,u]);P.useEffect(()=>{if(v.length===0){b([]);return}b(p=>ft(Sr({baseSku:r,basePrice:n,basePrices:ee(i),baseSalePrice:o,baseSalePrices:Ee(a),selectedAttributes:v,previousVariants:p}),c))},[n,i,o,a,r,c,v]),P.useEffect(()=>{_({variationAttributes:ci(u),variants:f})},[_,u,f]);const w=f.reduce((p,y)=>p+(y.stock_quantity||0),0),N=c.find(p=>p.is_default)??c[0],g=P.useMemo(()=>kt(c),[c]),F=(p,y)=>{h(C=>{const k=new Set(C[p]||[]);return k.has(y)?k.delete(y):k.add(y),{...C,[p]:[...k]}})},L=(p,y,C)=>{b(k=>k.map(R=>{if(R.combination_key!==p)return R;if(y==="sku")return{...R,sku:C};if(y==="upc")return{...R,upc:C};if(y==="sale_price"&&C==="")return{...R,sale_price:null};if(y==="prices"||y==="sale_prices")return R;const U=C===""?0:Number(C);return{...R,[y]:Number.isFinite(U)?U:0}}))},T=(p,y,C)=>{b(k=>k.map(R=>R.combination_key===p?{...R,[y]:C}:R))},te=(p,y,C,k)=>{const R=c.find(U=>U.is_default)??c[0];b(U=>U.map(K=>{if(K.combination_key!==p)return K;const Y={...C==="prices"?K.prices:K.sale_prices,[y]:k};return{...K,[C]:Y,...y===R?.code?C==="prices"?{price:k??0}:{sale_price:k}:{}}}))},A=p=>{const y=c.find(k=>k.is_default)??c[0],C=new Set(g);y&&b(k=>k.map(R=>{if(R.combination_key!==p)return R;const U=c.reduce((Y,V)=>{if(V.code!==y.code&&C.has(V.code))return Y;const re=_e({amount:E.majorUnitAmountToMinor(R.price,y.code),fromCurrencyCode:y.code,toCurrencyCode:V.code,currencies:c,applyRounding:!0});return Y[V.code]=E.minorUnitAmountToMajor(re,V.code),Y},{}),K=c.reduce((Y,V)=>{if(V.code!==y.code&&C.has(V.code))return Y;if(typeof R.sale_price!="number")return Y[V.code]=null,Y;const re=_e({amount:E.majorUnitAmountToMinor(R.sale_price,y.code),fromCurrencyCode:y.code,toCurrencyCode:V.code,currencies:c,applyRounding:!0});return Y[V.code]=E.minorUnitAmountToMajor(re,V.code),Y},{});return{...R,prices:U,sale_prices:K}}))},oe=(p,y)=>{const C=d.find(U=>U.media_id===y);if(!C)return;const k=C.file_path,R=ai(k);b(U=>U.map(K=>K.combination_key===p?{...K,main_media_id:C.media_id,main_image_url:R}:K))},I=p=>{b(y=>y.map(C=>C.combination_key===p?{...C,main_media_id:null,main_image_url:null}:C))};return e.length===0?s.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:["No global attributes have been created yet. Create them first in"," ",s.jsx(it,{href:"/cms/products/attributes",className:"font-medium text-primary underline-offset-4 hover:underline",children:"Attribute Management"}),"."]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Attributes"}),s.jsxs(x.Badge,{variant:"outline",className:"text-[10px] px-1.5 h-4",children:[f.length," variants"]}),s.jsxs(x.Badge,{variant:"secondary",className:"text-[10px] px-1.5 h-4",children:["Stock: ",w]})]}),s.jsx(x.Button,{asChild:!0,variant:"outline",size:"sm",className:"h-7 text-xs px-3",children:s.jsx(it,{href:"/cms/products/attributes",children:"Manage"})})]}),s.jsx("div",{className:"grid gap-2 lg:grid-cols-2",children:e.map(p=>{const y=u[p.id]||[];return s.jsxs("div",{className:"flex items-center gap-3 rounded border p-2.5",children:[s.jsxs("div",{className:"shrink-0 w-[100px]",children:[s.jsx("span",{className:"text-sm font-bold block leading-tight",children:ct(p,t)}),s.jsxs("span",{className:"text-[10px] text-muted-foreground leading-none",children:[y.length," selected"]})]}),s.jsx("div",{className:"flex flex-wrap gap-1.5 flex-1",children:p.terms.map(C=>{const k=y.includes(C.id);return s.jsx("button",{type:"button",onClick:()=>F(p.id,C.id),className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${k?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground hover:border-primary/40"}`,children:dt(C,t)},C.id)})})]},p.id)})})]}),f.length===0?s.jsx("div",{className:"rounded border border-dashed p-3 text-xs text-muted-foreground text-center",children:"Select terms above to generate variations."}):s.jsx("div",{className:"space-y-2",children:f.map(p=>{const y=sn({currencies:c,prices:p.prices||{},salePrices:p.sale_prices||{},fallbackPrice:p.price,fallbackSalePrice:p.sale_price});return s.jsxs("div",{className:"rounded border p-3 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-bold",children:p.label}),s.jsx("span",{className:"text-xs text-muted-foreground",children:p.selected_options.map(C=>`${C.attribute_name}: ${C.term_value}`).join(" · ")})]}),s.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[s.jsxs("span",{children:["Reg: ",nr(p.price,N?.code||"USD")]}),s.jsxs("span",{children:["Sale:"," ",p.sale_price!==null&&p.sale_price!==void 0?nr(p.sale_price,N?.code||"USD"):"—"]})]})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(x.Label,{htmlFor:`variant-sku-${p.combination_key}`,className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"SKU"}),s.jsx(x.Input,{id:`variant-sku-${p.combination_key}`,value:p.sku,onChange:C=>L(p.combination_key,"sku",C.target.value),placeholder:"SKU",className:"h-8 text-sm font-mono"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(x.Label,{htmlFor:`variant-upc-${p.combination_key}`,className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"UPC"}),s.jsx(x.Input,{id:`variant-upc-${p.combination_key}`,value:p.upc??"",onChange:C=>L(p.combination_key,"upc",C.target.value),placeholder:"—",className:"h-8 text-sm font-mono"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(x.Label,{htmlFor:`variant-stock-${p.combination_key}`,className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"Qty"}),s.jsx(x.Input,{id:`variant-stock-${p.combination_key}`,type:"number",min:"0",value:p.stock_quantity,onChange:C=>L(p.combination_key,"stock_quantity",C.target.value),className:"h-8 text-sm font-mono w-20"})]})]}),s.jsx(lt,{idPrefix:`variant-${p.combination_key}`,currencies:c,prices:y.prices,salePrices:y.salePrices,managedCurrencyCodes:g,onPriceChange:(C,k)=>te(p.combination_key,C,"prices",k),onSalePriceChange:(C,k)=>te(p.combination_key,C,"sale_prices",k),onAutoFill:()=>A(p.combination_key),helperText:g.length>0?`Store-managed currencies derive from ${N?.code||"the base currency"}.`:void 0,trailing:s.jsx(mt,{idPrefix:`variant-${p.combination_key}`,startAt:p.sale_start_at,endAt:p.sale_end_at,onChange:(C,k)=>T(p.combination_key,C,k),bare:!0})}),s.jsxs("div",{className:"flex items-center gap-3 pt-1.5 border-t border-muted/30",children:[p.main_image_url&&s.jsx("div",{className:"h-9 w-9 overflow-hidden rounded border bg-background shrink-0",children:s.jsx("img",{src:p.main_image_url,alt:`${p.label} image`,className:"h-full w-full object-cover"})}),s.jsx("span",{className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"Image"}),d.length>0?s.jsxs("select",{className:"flex h-8 rounded-md border border-input bg-background px-2 py-1 text-sm min-w-[180px]",value:p.main_media_id??"",onChange:C=>{if(!C.target.value){I(p.combination_key);return}oe(p.combination_key,C.target.value)},children:[s.jsx("option",{value:"",children:"Use parent image"}),d.map((C,k)=>s.jsx("option",{value:C.media_id,children:C.alt?.trim()||`Gallery image ${k+1}`},C.media_id))]}):s.jsx("span",{className:"text-xs text-muted-foreground",children:"Add gallery images first."}),p.main_media_id&&s.jsx(x.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2 text-muted-foreground hover:text-destructive",onClick:()=>I(p.combination_key),children:"Remove"})]})]},p.combination_key)})})]})}function sr(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}function ui(e){return e==="percent"?"percentage":"dollar"}function li(e){return jt(e).apiKey||B("FREEMIUS_API_KEY")}async function It(e){const t=li(e.productId);if(!t)throw new Error(`Missing Freemius API bearer token for product ${e.productId}. Set FREEMIUS_API_KEY or FREEMIUS_CHECKOUT_PRODUCTS_JSON[${e.productId}].apiKey.`);const r=e.couponId?`/${e.couponId}`:"",n=await fetch(`https://api.freemius.com/v1/products/${e.productId}/coupons${r}.json`,{method:e.method,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",Accept:"application/json"},body:e.method==="DELETE"?void 0:JSON.stringify(e.body||{})}),i=await n.text(),o=i?JSON.parse(i):null;if(!n.ok)throw new Error(o?.message||o?.error?.message||`Freemius coupon request failed with ${n.status}`);return o}function on(e,t){return{code:e.code,discount:e.discount_type==="fixed"?E.minorUnitAmountToMajor(e.discount_amount,"USD"):e.discount_amount,discount_type:ui(e.discount_type),plans:t.planIds.length>0?t.planIds.join(","):null,licenses:null,billing_cycles:null,start_date:sr(e.starts_at),end_date:sr(e.ends_at),redemptions_limit:e.redemption_limit??null,has_renewals_discount:!1,has_addons_discount:!1,is_one_per_user:!1,is_active:e.is_active,user_type:"all"}}async function mi(e,t){if(t.provider_scope==="stripe")return[];const{data:r,error:n}=await e.from("coupon_products").select("product_id").eq("coupon_id",t.id);if(n)throw new Error(n.message);const i=(r||[]).map(m=>m.product_id);let o=e.from("products").select("id, freemius_product_id, freemius_plan_id").eq("payment_provider","freemius").not("freemius_product_id","is",null);i.length>0&&(o=o.in("id",i));const{data:a,error:c}=await o;if(c)throw new Error(c.message);const d=new Map;for(const m of a||[]){const l=String(m.freemius_product_id||"").trim();if(!l)continue;const _=d.get(l)??{freemiusProductId:l,productId:m.id,planIds:[]};i.length>0&&m.freemius_plan_id&&_.planIds.push(String(m.freemius_plan_id)),d.set(l,_)}return[...d.values()].map(m=>({...m,planIds:[...new Set(m.planIds)]}))}async function pi(e,t){const{data:r}=await e.from("coupon_freemius_mappings").select("sync_status, sync_error").eq("coupon_id",t),n=r||[];if(n.length===0){await e.from("coupons").update({freemius_sync_status:"not_required",freemius_sync_error:null}).eq("id",t);return}const i=n.find(o=>o.sync_status==="failed");await e.from("coupons").update({freemius_sync_status:i?"failed":"synced",freemius_sync_error:i?.sync_error??null}).eq("id",t)}async function _i(e){const{data:t,error:r}=await e.client.from("coupons").select("id, code, name, internal_note, provider_scope, discount_type, discount_amount, is_active, starts_at, ends_at, redemption_limit").eq("id",e.couponId).single();if(r||!t)return{success:!1,error:r?.message||"Coupon not found"};const n=t,i=await mi(e.client,n);await e.client.from("coupons").update({freemius_sync_status:i.length>0?"pending":"not_required",freemius_sync_error:null}).eq("id",n.id);for(const o of i){const{data:a}=await e.client.from("coupon_freemius_mappings").select("id, freemius_coupon_id").eq("coupon_id",n.id).eq("freemius_product_id",o.freemiusProductId).maybeSingle(),c=on(n,o);try{const d=await It({productId:o.freemiusProductId,method:a?.freemius_coupon_id?"PUT":"POST",couponId:a?.freemius_coupon_id??null,body:c}),m=d?.coupon??d;await e.client.from("coupon_freemius_mappings").upsert({id:a?.id,coupon_id:n.id,product_id:o.productId,freemius_product_id:o.freemiusProductId,freemius_coupon_id:m?.id?String(m.id):a?.freemius_coupon_id??null,freemius_coupon_code:n.code,sync_status:"synced",sync_error:null,remote_payload:d,last_synced_at:new Date().toISOString()},{onConflict:"coupon_id,freemius_product_id"})}catch(d){await e.client.from("coupon_freemius_mappings").upsert({id:a?.id,coupon_id:n.id,product_id:o.productId,freemius_product_id:o.freemiusProductId,freemius_coupon_id:a?.freemius_coupon_id??null,freemius_coupon_code:n.code,sync_status:"failed",sync_error:d.message||"Freemius sync failed",last_synced_at:new Date().toISOString()},{onConflict:"coupon_id,freemius_product_id"})}}return await pi(e.client,n.id),{success:!0,targetCount:i.length}}function fi(e){const t=(e.sku||"").toUpperCase().replace(/[^A-Z0-9]/g,"");return t?`SALE${t}`.slice(0,32):`SALE${e.productId.replace(/[^A-Za-z0-9]/g,"").toUpperCase()}`.slice(0,32)}function gi(e,t){if(typeof e!="number"||e<=0||typeof t!="number"||t<0||t>=e)return null;const r=Math.round((1-t/e)*100);return r<=0||r>100?null:r}async function an(e){const{data:t,error:r}=await e.client.from("products").select("id, sku, price, sale_price, sale_start_at, sale_end_at, payment_provider, freemius_product_id, freemius_plan_id").eq("id",e.productId).maybeSingle();if(r||!t)return{success:!1,error:r?.message||"Product not found"};const n=t,i=String(n.freemius_product_id||"").trim();if(n.payment_provider!=="freemius"||!i)return{success:!0,skipped:!0,reason:"not_a_freemius_product"};const o=gi(n.price,n.sale_price),a=o!==null,{data:c}=await e.client.from("product_freemius_sale_coupons").select("id, freemius_coupon_id, freemius_coupon_code, discount_percent, is_active").eq("product_id",n.id).maybeSingle();if(!a&&!c?.freemius_coupon_id)return c?.id&&await e.client.from("product_freemius_sale_coupons").update({is_active:!1,updated_at:new Date().toISOString()}).eq("id",c.id),{success:!0,active:!1};const d=c?.freemius_coupon_code||fi({sku:n.sku,productId:n.id}),m=n.freemius_plan_id?[String(n.freemius_plan_id)]:[],l=o??c?.discount_percent??1,_={id:n.id,code:d,name:`Scheduled sale ${n.sku||n.id}`,discount_type:"percent",discount_amount:l,is_active:a,starts_at:n.sale_start_at,ends_at:n.sale_end_at,redemption_limit:null},u={productId:n.id,planIds:m},h=on(_,u);try{const f=await It({productId:i,method:c?.freemius_coupon_id?"PUT":"POST",couponId:c?.freemius_coupon_id??null,body:h}),b=f?.coupon??f;return await e.client.from("product_freemius_sale_coupons").upsert({id:c?.id,product_id:n.id,freemius_product_id:i,freemius_plan_id:n.freemius_plan_id?String(n.freemius_plan_id):null,freemius_coupon_id:b?.id?String(b.id):c?.freemius_coupon_id??null,freemius_coupon_code:d,discount_percent:o,starts_at:n.sale_start_at,ends_at:n.sale_end_at,is_active:a,sync_status:"synced",sync_error:null,remote_payload:f,last_synced_at:new Date().toISOString()},{onConflict:"product_id"}),{success:!0,active:a,code:d}}catch(f){return await e.client.from("product_freemius_sale_coupons").upsert({id:c?.id,product_id:n.id,freemius_product_id:i,freemius_plan_id:n.freemius_plan_id?String(n.freemius_plan_id):null,freemius_coupon_id:c?.freemius_coupon_id??null,freemius_coupon_code:d,discount_percent:o,starts_at:n.sale_start_at,ends_at:n.sale_end_at,is_active:a,sync_status:"failed",sync_error:f.message||"Freemius sale coupon sync failed",last_synced_at:new Date().toISOString()},{onConflict:"product_id"}),{success:!1,error:f.message||"Freemius sale coupon sync failed"}}}async function hi(e){const{data:t}=await e.client.from("coupon_freemius_mappings").select("id, freemius_product_id, freemius_coupon_id").eq("coupon_id",e.couponId).not("freemius_coupon_id","is",null);for(const r of t||[])try{await It({productId:r.freemius_product_id,couponId:r.freemius_coupon_id,method:"DELETE"}),await e.client.from("coupon_freemius_mappings").update({sync_status:"deleted",sync_error:null,updated_at:new Date().toISOString()}).eq("id",r.id)}catch(n){await e.client.from("coupon_freemius_mappings").update({sync_status:"failed",sync_error:n.message||"Freemius delete failed",updated_at:new Date().toISOString()}).eq("id",r.id)}}function et(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}async function yi(e){const t=z.createClient(),{data:r}=await t.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}),n=Ze(e,(r||[]).map(o=>W(o))),i=await $r(t,n);if(n.payment_provider==="freemius"&&i?.id)try{await an({productId:i.id,client:z.getServiceRoleSupabaseClient()})}catch(o){console.error("Failed to sync Freemius sale coupon on create:",o)}M.revalidatePath("/cms/products"),Nn.redirect("/cms/products")}async function xi(e,t){const r=z.createClient(),{data:{user:n}}=await r.auth.getUser();if(!n)throw new Error("User not authenticated.");const{data:i}=await r.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}),o=Ze(t,(i||[]).map(c=>W(c))),{error:a}=await r.from("product_drafts").upsert({product_id:e,author_id:n.id,meta:o,updated_at:new Date().toISOString()},{onConflict:"product_id"});if(a)throw new Error(`Failed to save product draft: ${a.message}`);return{success:!0}}async function bi(e){const t=z.createClient();await Lr(t,e),M.revalidatePath("/cms/products")}function cn(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean)))}async function vi(e){const t=cn(e);if(t.length===0)return{success:!1,error:"Select at least one product."};const r=z.createClient(),{error:n}=await r.from("products").delete().in("id",t);return n?{success:!1,error:n.message}:(M.revalidatePath("/cms/products"),{success:!0,count:t.length})}async function Ci(e){const t=cn(e);if(t.length===0)return{success:!1,error:"Select at least one product."};const r=z.createClient(),{error:n}=await r.from("products").update({status:"draft",updated_at:new Date().toISOString()}).in("id",t);return n?{success:!1,error:n.message}:(M.revalidatePath("/cms/products"),{success:!0,count:t.length})}async function Si(e){const t=z.getServiceRoleSupabaseClient(),r=e.name.trim(),n=et(e.slug?.trim()||e.name);if(!r||!n)return{success:!1,error:"Attribute name is required."};const{error:i}=await t.from("product_attributes").insert({name:r,slug:n});return i?{success:!1,error:i.message}:(M.revalidatePath("/cms/products/attributes"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0})}async function wi(e){const t=z.getServiceRoleSupabaseClient(),{error:r}=await t.from("product_attributes").delete().eq("id",e);return r?{success:!1,error:r.message}:(M.revalidatePath("/cms/products/attributes"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0})}async function Ni(e){const t=z.getServiceRoleSupabaseClient(),r=e.value.trim(),n=et(e.slug?.trim()||e.value);if(!r||!n)return{success:!1,error:"Term value is required."};const{data:i}=await t.from("product_attribute_terms").select("sort_order").eq("attribute_id",e.attributeId).order("sort_order",{ascending:!1}).limit(1),o=typeof i?.[0]?.sort_order=="number"?i[0].sort_order+1:0,{error:a}=await t.from("product_attribute_terms").insert({attribute_id:e.attributeId,value:r,slug:n,sort_order:o});return a?{success:!1,error:a.message}:(M.revalidatePath("/cms/products/attributes"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0})}async function ji(e){const t=z.getServiceRoleSupabaseClient();for(const[r,n]of e.orderedTermIds.entries()){const{error:i}=await t.from("product_attribute_terms").update({sort_order:r,updated_at:new Date().toISOString()}).eq("id",n).eq("attribute_id",e.attributeId);if(i)return{success:!1,error:i.message}}return M.revalidatePath("/cms/products/attributes"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0}}async function Pi(e){const t=z.getServiceRoleSupabaseClient(),{error:r}=await t.from("product_attributes").update({name_translations:e.nameTranslations,updated_at:new Date().toISOString()}).eq("id",e.attributeId);if(r)return{success:!1,error:r.message};for(const n of e.termTranslations){const{error:i}=await t.from("product_attribute_terms").update({value_translations:n.valueTranslations,updated_at:new Date().toISOString()}).eq("id",n.termId).eq("attribute_id",e.attributeId);if(i)return{success:!1,error:i.message}}return M.revalidatePath("/cms/products/attributes"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0}}async function Ei(e){const t=z.getServiceRoleSupabaseClient(),{error:r}=await t.from("product_attribute_terms").delete().eq("id",e);return r?{success:!1,error:r.message}:(M.revalidatePath("/cms/products/attributes"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0})}async function dn(e){const t=z.getServiceRoleSupabaseClient(),r=e.name.trim(),n=et(e.slug?.trim()||e.name);if(!r||!n)return{success:!1,error:"Category name is required."};const{data:i,error:o}=await t.from("categories").insert({name:r,slug:n,description:e.description?.trim()||null,name_translations:e.nameTranslations||{},description_translations:e.descriptionTranslations||{}}).select().single();return o?{success:!1,error:o.message}:(M.revalidatePath("/cms/products/categories"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0,category:i})}async function Ai(e,t){const r=z.getServiceRoleSupabaseClient(),n=t.name.trim(),i=et(t.slug?.trim()||t.name);if(!n||!i)return{success:!1,error:"Category name is required."};const{error:o}=await r.from("categories").update({name:n,slug:i,description:t.description?.trim()||null,name_translations:t.nameTranslations||{},description_translations:t.descriptionTranslations||{}}).eq("id",e);return o?{success:!1,error:o.message}:(M.revalidatePath("/cms/products/categories"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0})}async function ki(e){const t=z.getServiceRoleSupabaseClient(),{error:r}=await t.from("categories").delete().eq("id",e);return r?{success:!1,error:r.message}:(M.revalidatePath("/cms/products/categories"),M.revalidatePath("/cms/products/new"),M.revalidatePath("/cms/products"),{success:!0})}async function Ii(e,t){const r=z.getServiceRoleSupabaseClient();try{return await Je(r,e,t),M.revalidatePath("/cms/products"),M.revalidatePath(`/cms/products/${e}/edit`),{success:!0}}catch(n){return{success:!1,error:n.message}}}function un({categories:e=[],selectedIds:t=[],onChange:r,placeholder:n="Select categories..."}){const[i,o]=P.useState(!1),[a,c]=P.useState(""),[d,m]=P.useState(e),[l,_]=P.useState(!1);P.useEffect(()=>{m(e)},[e]);const u=P.useMemo(()=>d.filter(g=>t.includes(g.id)),[d,t]),h=P.useMemo(()=>{if(!a)return d;const g=a.toLowerCase();return d.filter(F=>F.name.toLowerCase().includes(g)||F.slug.toLowerCase().includes(g))},[d,a]),f=a.trim(),b=P.useMemo(()=>{if(!f)return!1;const g=f.toLowerCase();return!d.some(F=>F.name.toLowerCase()===g)},[d,f]),v=async()=>{if(f){_(!0);try{const g=await dn({name:f});if(g.success&&g.category){const F={id:g.category.id,name:g.category.name,slug:g.category.slug};m(L=>[...L,F]),r([...t,F.id]),c(""),Se.toast.success(`Category "${F.name}" created successfully.`)}else Se.toast.error(g.error||"Failed to create category.")}catch(g){Se.toast.error(g.message||"An error occurred while creating category.")}finally{_(!1)}}},w=g=>{const F=t.includes(g)?t.filter(L=>L!==g):[...t,g];r(F)},N=(g,F)=>{F.stopPropagation(),r(t.filter(L=>L!==g))};return s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"flex flex-wrap gap-1.5 min-h-[32px] p-1 border rounded-md bg-background focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",children:u.length===0?s.jsx("span",{className:"text-xs text-muted-foreground self-center px-2 py-1 select-none",children:"No categories selected."}):u.map(g=>s.jsxs(x.Badge,{variant:"secondary",className:"pl-2 pr-1.5 py-0.5 text-xs flex items-center gap-1 bg-amber-500/10 text-amber-800 dark:text-amber-300 border border-amber-500/20 rounded-full",children:[g.name,s.jsx("button",{type:"button",onClick:F=>N(g.id,F),className:"rounded-full p-0.5 text-muted-foreground hover:bg-amber-500/20 hover:text-amber-950 dark:hover:text-amber-50 transition-colors cursor-pointer","aria-label":`Remove ${g.name}`,children:s.jsx(H.X,{className:"h-3 w-3"})})]},g.id))}),s.jsxs(x.Popover,{open:i,onOpenChange:o,children:[s.jsx(x.PopoverTrigger,{asChild:!0,children:s.jsxs(x.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"w-full justify-between h-8 text-xs font-normal",children:[s.jsx("span",{className:"truncate",children:t.length>0?`${t.length} categor${t.length===1?"y":"ies"} selected`:n}),s.jsx(H.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),s.jsxs(x.PopoverContent,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:[s.jsxs("div",{className:"flex items-center border-b px-3",children:[s.jsx(H.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),s.jsx(x.Input,{className:"flex h-9 w-full rounded-md bg-transparent py-2 text-xs outline-none border-0 focus-visible:ring-0 focus-visible:ring-offset-0",placeholder:"Search categories...",value:a,onChange:g=>c(g.target.value)})]}),b&&s.jsx("div",{className:"border-b border-border/50 p-1",children:s.jsxs(x.Button,{type:"button",variant:"ghost",size:"sm",className:"w-full justify-start text-xs h-8 text-amber-600 dark:text-amber-400 hover:text-amber-700 hover:bg-amber-500/10 cursor-pointer",onClick:v,disabled:l,children:[l?s.jsx(H.Loader2,{className:"mr-2 h-3 w-3 animate-spin"}):s.jsx("span",{className:"font-bold mr-1.5",children:"+"}),'Create category "',f,'"']})}),s.jsx("div",{className:"max-h-60 overflow-y-auto p-1",children:h.length===0?s.jsx("p",{className:"py-4 text-center text-xs text-muted-foreground",children:"No categories found."}):s.jsx("div",{className:"flex flex-col gap-0.5",children:h.map(g=>{const F=t.includes(g.id);return s.jsxs("div",{onClick:()=>w(g.id),className:E.cn("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-xs outline-none hover:bg-accent hover:text-accent-foreground text-left transition-colors",F&&"bg-accent/40 font-medium"),children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center pointer-events-none",children:s.jsx(x.Checkbox,{checked:F,tabIndex:-1,"aria-label":`Toggle ${g.name}`,className:"h-3.5 w-3.5"})}),s.jsxs("span",{className:"flex flex-col",children:[s.jsx("span",{children:g.name}),s.jsxs("span",{className:"font-mono text-[9px] text-muted-foreground leading-none",children:["/",g.slug]})]}),F&&s.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(H.Check,{className:"h-3.5 w-3.5 text-primary"})})]},g.id)})})})]})]})]})}function Be({title:e,description:t,action:r,children:n,hideHeader:i}){return s.jsxs("section",{className:"rounded-lg border bg-card p-3 shadow-sm space-y-3",children:[!i&&s.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap border-b border-muted/50 pb-2 mb-1",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx("h2",{className:"text-sm font-bold tracking-tight",children:e}),t?s.jsx("p",{className:"text-[11px] text-muted-foreground leading-none",children:t}):null]}),r]}),s.jsx("div",{className:i?"":"pt-1",children:n})]})}function Mi(e,t,r){const n=t?Number.parseInt(t,10):void 0;return e?.language_id||(Number.isFinite(n)?n:void 0)||r.find(i=>i.is_default)?.id||r[0]?.id||1}function ir(e,t,r,n,i){const a=(n.find(u=>u.is_default)??n[0])?.code||"USD",c=e?.prices&&Object.keys(e.prices).length>0?e.prices:{[a]:typeof e?.price=="number"?e.price/100:0},d=e?.sale_prices&&Object.keys(e.sale_prices).length>0?e.sale_prices:typeof e?.sale_price=="number"?{[a]:e.sale_price/100}:{},m=e?.product_type||"",l=e?.payment_provider||(e?.product_type?ht(e.product_type):"stripe");return{...Ze({product_type:m||"physical",payment_provider:l,title:e?.title||"",slug:e?.slug||"",sku:e?.sku||"",upc:e?.upc||"",is_taxable:e?.is_taxable??!0,price:typeof e?.price=="number"?e.price/100:0,prices:c,sale_price:typeof e?.sale_price=="number"?e.sale_price/100:null,sale_prices:d,stock:e?.stock||0,meta_title:e?.meta_title||"",meta_description:e?.meta_description||"",short_description:e?.short_description||"",description_json:e?.description_json||{type:"doc",content:[{type:"paragraph"}]},freemius_product_id:e?.freemius_product_id||"",freemius_plan_id:e?.freemius_plan_id||"",trial_period_days:e?.trial_period_days??0,trial_requires_payment_method:e?.trial_requires_payment_method??!1,status:e?.status||"draft",language_id:Mi(e,t,r),translation_group_id:e?.translation_group_id||i||void 0,product_media:e?.product_media?.map(u=>({media_id:u.media_id}))||[],category_ids:e?.category_ids||[],variation_attributes:e?.variation_attributes||[],variants:e?.variants?.map(u=>({...u,prices:u.prices||{},sale_prices:u.sale_prices||{}}))||[]},n),product_type:m,payment_provider:l}}function or(e){return e?e.map(t=>({id:t.id||t.media_id,media_id:t.media_id,file_path:t.media?.file_path||t.media?.object_key||"",alt:t.media?.alt_text||"",sort_order:t.sort_order??0})).sort((t,r)=>t.sort_order-r.sort_order):[]}function Ti(e){return e.map(t=>({media_id:t.media_id}))}function Fi(e){return e.map(t=>({media_id:t.media_id,file_path:t.file_path,alt:t.alt}))}const Ri=e=>e.toString().toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+/,"").replace(/-+$/,"");function zi({initialData:e,isEdit:t=!1,mediaPickerNode:r,availableLanguagesProp:n,globalAttributesProp:i,currenciesProp:o,translationGroupId:a,targetLanguageId:c,freemiusDashboardNode:d,enabledProviders:m,configStatus:l,createAction:_,updateAction:u,availableCategoriesProp:h=[]}){const[f,b]=P.useState(!1),[v,w]=P.useState(()=>!!e?.variants?.length),N=P.useMemo(()=>o.filter(j=>j.is_active!==!1).sort((j,q)=>j.is_default!==q.is_default?j.is_default?-1:1:j.code.localeCompare(q.code)),[o]),g=P.useMemo(()=>N.find(j=>j.is_default)??N[0],[N]),F=P.useMemo(()=>kt(N),[N]),L=Cn.useForm({resolver:vn.zodResolver(nn),defaultValues:ir(e,c,n,N,a)}),{register:T,handleSubmit:te,setValue:A,reset:oe,watch:I,setError:p,formState:{errors:y,dirtyFields:C}}=L,k=P.useRef(!0),R=P.useRef(null),[U,K]=P.useState(!1),[Y,V]=P.useState(null),[re,fe]=P.useState(null),ae=I(),ge=L.formState.isDirty;P.useEffect(()=>{if(!t)return;if(k.current){k.current=!1,R.current=JSON.stringify(ae);return}if(!ge)return;const j=JSON.stringify(ae);if(j===R.current)return;const q=setTimeout(()=>{f||(R.current=j,te(Ut)())},1e3);return()=>clearTimeout(q)},[ae,t,ge,f,te]);const ke=I("title"),ne=I("product_type"),O=ne==="digital"?"freemius":ne==="physical"?"stripe":void 0,D=ne==="physical",se=ne==="digital",ue=O?m[O]:!1,Ie=O?l[O].hasKeys:!1,mn=!!I("freemius_product_id"),Mt=Number(I("trial_period_days")||0),Tt=!!I("trial_requires_payment_method"),pn=I("variants")||[],be=I("price"),we=I("sale_price"),ce=I("prices")||{},ve=I("sale_prices")||{},le=(pn?.length||0)>0,_n=I("language_id"),fn=n.find(j=>j.id===_n)?.code||n.find(j=>j.is_default)?.code||n[0]?.code,qe=P.useMemo(()=>sn({currencies:N,prices:ce,salePrices:ve,fallbackPrice:be,fallbackSalePrice:we}),[be,we,N,ce,ve]),gn=P.useMemo(()=>e?.variants?.map(j=>({...j,prices:j.prices||{},sale_prices:j.sale_prices||{}})),[e?.variants]);P.useEffect(()=>{if(C.title&&!t){const j=Ri(ke);A("slug",j,{shouldValidate:!0})}},[ke,C.title,A,t]);const[tt,Ft]=P.useState(()=>or(e?.product_media)),[rt,Rt]=P.useState(new Set);P.useEffect(()=>{oe(ir(e,c,n,N,a)),Ft(or(e?.product_media)),Rt(new Set),w(!!e?.variants?.length)},[n,N,e,oe,c,a]);const hn=j=>{const q=new Set(j.map(X=>X.id)),G=tt.filter(X=>!q.has(X.id)),Q=new Set(rt);G.forEach(X=>{X.media_id&&Q.add(X.media_id)}),Rt(Q),Ft(j),A("product_media",Ti(j),{shouldDirty:!0}),A("explicitly_removed_media_ids",Array.from(Q),{shouldDirty:!0})};P.useEffect(()=>{A("explicitly_removed_media_ids",Array.from(rt))},[rt,A]),P.useEffect(()=>{le&&w(!0)},[le]),P.useEffect(()=>{T("is_taxable"),T("price"),T("sale_price"),T("payment_provider"),T("trial_requires_payment_method")},[T]),P.useEffect(()=>{if(!se){A("trial_period_days",0,{shouldDirty:!1,shouldValidate:!0}),A("trial_requires_payment_method",!1,{shouldDirty:!1,shouldValidate:!0});return}Mt<=0&&A("trial_requires_payment_method",!1,{shouldDirty:!1,shouldValidate:!0})},[se,A,Mt]),P.useEffect(()=>{O&&A("payment_provider",O,{shouldDirty:!1,shouldValidate:!0})},[O,A]),P.useEffect(()=>{g&&ce[g.code]===void 0&&A("prices",{...ce,[g.code]:be||0},{shouldDirty:!1})},[be,g,ce,A]);const zt=P.useCallback((j,q)=>{const G={...ce,[j]:q};A("prices",G,{shouldDirty:!0,shouldValidate:!0}),j===g?.code&&A("price",q,{shouldDirty:!0,shouldValidate:!0})},[g?.code,ce,A]),Dt=P.useCallback((j,q)=>{const G={...ve,[j]:q};A("sale_prices",G,{shouldDirty:!0,shouldValidate:!0}),j===g?.code&&A("sale_price",q,{shouldDirty:!0,shouldValidate:!0})},[g?.code,ve,A]),qt=P.useCallback(()=>{if(!g)return;const j=new Set(F),q=ce[g.code]??be??0,G=ve[g.code]??we??null,Q=N.reduce((me,J)=>{if(J.code!==g.code&&j.has(J.code))return me;const nt=_e({amount:E.majorUnitAmountToMinor(q,g.code),fromCurrencyCode:g.code,toCurrencyCode:J.code,currencies:N,applyRounding:!0});return me[J.code]=E.minorUnitAmountToMajor(nt,J.code),me},{}),X=N.reduce((me,J)=>{if(J.code!==g.code&&j.has(J.code))return me;if(typeof G!="number")return(J.code===g.code||!j.has(J.code))&&(me[J.code]=null),me;const nt=_e({amount:E.majorUnitAmountToMinor(G,g.code),fromCurrencyCode:g.code,toCurrencyCode:J.code,currencies:N,applyRounding:!0});return me[J.code]=E.minorUnitAmountToMajor(nt,J.code),me},{});A("prices",Q,{shouldDirty:!0,shouldValidate:!0}),A("sale_prices",X,{shouldDirty:!0,shouldValidate:!0}),A("price",Q[g.code]??q,{shouldDirty:!0,shouldValidate:!0}),A("sale_price",X[g.code]??null,{shouldDirty:!0,shouldValidate:!0})},[N,g,ce,ve,A,F,be,we]),yn=P.useCallback(({variationAttributes:j,variants:q})=>{A("variation_attributes",j,{shouldDirty:!0}),A("variants",q,{shouldDirty:!0,shouldValidate:!0})},[A]),Ut=async j=>{b(!0),K(!0),V(null);try{if(!O){const X="Select whether this product is physical or digital before saving.";p("product_type",{type:"manual",message:X}),t?V(X):alert(X),b(!1),K(!1);return}if(j.status==="active"&&(!ue||!Ie)){const X=`${O==="stripe"?"Stripe":"Freemius"} must be enabled and fully configured before this product can be published.`;p("product_type",{type:"manual",message:X}),t?V(X):alert(X),b(!1),K(!1);return}const q=D?0:Math.max(0,Number(j.trial_period_days||0)),G={...j,product_type:j.product_type,payment_provider:O,freemius_product_id:D?"":j.freemius_product_id,freemius_plan_id:D?"":j.freemius_plan_id,trial_period_days:q,trial_requires_payment_method:!D&&q>0?j.trial_requires_payment_method:!1,upc:D?j.upc:null,is_taxable:D?j.is_taxable:!1,variation_attributes:D?j.variation_attributes:[],variants:D?j.variants:[]},Q=Ze(G,N);if(t&&u)await u(Q),fe(new Date);else if(_)await _(Q);else throw new Error("Product form action is not configured.")}catch(q){if(console.error(q),q.message==="NEXT_REDIRECT")return;let G=q.message||"An error occurred while saving.";if(q.code==="23505"){const Q=q.message?.toLowerCase()||"";Q.includes("products_slug_key")||Q.includes("slug")?(G="This slug is already in use. Please choose another one.",p("slug",{type:"manual",message:G})):(Q.includes("products_sku_key")||Q.includes("sku"))&&(G="This SKU is already in use.",p("sku",{type:"manual",message:G}))}t?V(G):alert(G)}finally{b(!1),K(!1)}},xn=le?"bg-muted/60 text-muted-foreground opacity-70":"",bn=Fi(tt);return s.jsxs("form",{onSubmit:te(Ut),className:"space-y-2.5 pb-4",children:[s.jsx("input",{type:"hidden",...T("translation_group_id")}),s.jsx("input",{type:"hidden",...T("payment_provider")}),s.jsxs("div",{className:"space-y-2.5 w-full",children:[s.jsxs("div",{className:"rounded-lg border bg-card p-2.5 px-4 shadow-sm flex items-center justify-between gap-3 flex-wrap",children:[s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"flex h-9 items-center gap-2",children:[s.jsx("span",{className:"text-sm font-bold whitespace-nowrap leading-none pt-0.5",children:"Product Type"}),y.product_type&&s.jsx(H.AlertCircle,{className:"h-4 w-4 text-destructive"})]}),s.jsx("div",{className:"flex h-9 items-center",children:s.jsxs(x.Select,{onValueChange:j=>A("product_type",j,{shouldDirty:!0,shouldValidate:!0}),value:ne||void 0,children:[s.jsx(x.SelectTrigger,{className:"w-[160px] h-9 text-xs",children:s.jsx(x.SelectValue,{placeholder:"Select Type"})}),s.jsxs(x.SelectContent,{children:[s.jsx(x.SelectItem,{value:"physical",children:"Physical Product"}),s.jsx(x.SelectItem,{value:"digital",children:"Digital Product"})]})]})})]}),s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"flex h-9 items-center gap-3",children:[s.jsx("span",{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-wider leading-none",children:"Payment Provider"}),s.jsx(x.Badge,{variant:"outline",className:"text-xs py-1 font-bold bg-muted/30 leading-none",children:O?O==="stripe"?"Stripe":"Freemius":"—"})]}),O&&s.jsx("div",{className:"flex h-9 items-center gap-2",children:ue&&Ie?s.jsxs("span",{className:"flex items-center gap-1.5 text-emerald-600 text-[10px] font-bold bg-emerald-50 px-2 py-1 rounded-full border border-emerald-100 uppercase leading-none",children:[s.jsx(H.CheckCircle2,{className:"h-3 w-3"}),"Ready"]}):s.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600 text-[10px] font-bold bg-amber-50 px-2 py-1 rounded-full border border-amber-100 uppercase leading-none",children:[s.jsx(H.AlertCircle,{className:"h-3 w-3"}),ue?"Keys Missing":"Disabled"]})}),!Ie&&O&&l[O].missing.length>0&&s.jsxs("div",{className:"hidden xl:flex h-9 items-center gap-1 text-[10px] text-muted-foreground bg-muted/50 px-2 py-1 rounded border border-dashed leading-none",children:[s.jsx(H.Info,{className:"h-3 w-3"}),"Missing: ",l[O].missing.join(", ")]})]})]}),s.jsxs(Be,{title:"Product Information",hideHeader:!0,children:[t&&s.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground pb-2 border-b border-border/40 mb-2.5",children:[s.jsx("span",{className:"font-semibold text-[11px] uppercase tracking-wider text-muted-foreground/80",children:"Product Settings"}),s.jsx("div",{className:"flex items-center gap-1.5 min-h-[16px]",children:U?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"relative flex h-2 w-2",children:[s.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"}),s.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-amber-500"})]}),s.jsx("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:"Autosaving settings..."})]}):Y?s.jsxs("span",{className:"text-red-500 font-medium",children:["Error saving settings: ",Y]}):re?s.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400 font-medium",children:["Settings autosaved at ",re.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})]}):s.jsx("span",{className:"text-muted-foreground/60",children:"Settings autosave in draft mode"})})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-2.5",children:[s.jsxs("div",{className:"col-span-2 space-y-1",children:[s.jsx(x.Label,{htmlFor:"title",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Title"}),s.jsx(x.Input,{id:"title",placeholder:"Product title",...T("title"),className:"h-8 text-sm"}),y.title&&s.jsx("p",{className:"text-destructive text-[11px] leading-none",children:y.title.message})]}),s.jsxs("div",{className:"col-span-2 space-y-1",children:[s.jsx(x.Label,{htmlFor:"slug",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Slug"}),s.jsx(x.Input,{id:"slug",placeholder:"product-slug",...T("slug"),className:"h-8 text-sm"}),y.slug&&s.jsx("p",{className:"text-destructive text-[11px] leading-none",children:y.slug.message})]}),s.jsxs("div",{className:"col-span-1 space-y-1",children:[s.jsx(x.Label,{htmlFor:"sku",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"SKU"}),s.jsx(x.Input,{id:"sku",placeholder:"SKU",...T("sku"),className:"h-8 text-sm font-mono"}),y.sku&&s.jsx("p",{className:"text-destructive text-[11px] leading-none",children:y.sku.message})]}),s.jsxs("div",{className:"col-span-1 space-y-1",children:[s.jsx(x.Label,{htmlFor:"upc_ean",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"UPC / EAN"}),s.jsx(x.Input,{id:"upc_ean",placeholder:"000000000",...T("upc"),className:"h-8 text-sm font-mono",readOnly:le})]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-2.5 mt-2",children:[s.jsxs("div",{className:"lg:col-span-2 col-span-2 space-y-1",children:[s.jsx(x.Label,{htmlFor:"meta_title",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Meta Title"}),s.jsx(x.Input,{id:"meta_title",...T("meta_title"),placeholder:"SEO page title (50-60 chars)",className:"h-8 text-sm"})]}),s.jsxs("div",{className:`lg:col-span-${t?"3":"4"} col-span-2 space-y-1`,children:[s.jsx(x.Label,{htmlFor:"meta_description",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Meta Description"}),s.jsx(x.Input,{id:"meta_description",...T("meta_description"),placeholder:"SEO description (150-160 chars)",className:"h-8 text-sm"})]}),t&&s.jsxs("div",{className:"lg:col-span-1 col-span-2 space-y-1",children:[s.jsx(x.Label,{htmlFor:"status",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Status"}),s.jsxs(x.Select,{onValueChange:j=>A("status",j,{shouldDirty:!0}),value:I("status"),children:[s.jsx(x.SelectTrigger,{className:"h-8 text-xs",children:s.jsx(x.SelectValue,{placeholder:"Status"})}),s.jsxs(x.SelectContent,{children:[s.jsx(x.SelectItem,{value:"draft",children:"Draft"}),s.jsx(x.SelectItem,{value:"active",children:"Active"}),s.jsx(x.SelectItem,{value:"archived",children:"Archived"})]})]})]})]})]}),s.jsx(Be,{title:"Product Categories",description:"Assign this product to one or more categories.",children:s.jsx(un,{categories:h,selectedIds:I("category_ids")||[],onChange:j=>A("category_ids",j,{shouldDirty:!0,shouldValidate:!0})})}),s.jsxs("section",{className:"rounded-lg border bg-card p-3 shadow-sm space-y-3",children:[D&&s.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap border-b border-muted/50 pb-2",children:[s.jsx("div",{className:"flex items-center gap-4",children:s.jsxs("div",{className:"space-y-0.5",children:[s.jsx("h2",{className:"text-sm font-bold tracking-tight",children:"Pricing & Inventory"}),s.jsx("p",{className:"text-[11px] text-muted-foreground leading-none",children:"Manage simple or variant pricing."})]})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2 bg-muted/40 rounded-md px-2.5 py-1.5",children:[s.jsx("span",{className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Stock"}),s.jsx(x.Input,{id:"stock",type:"number",min:"0",...T("stock",{valueAsNumber:!0}),placeholder:"0",readOnly:le,className:`${xn} h-8 w-20 text-sm text-center font-mono bg-background`})]}),le?s.jsx(x.Badge,{variant:"secondary",className:"text-[11px] py-0 px-2 h-5",children:"Variant pricing"}):null]})]}),D?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"w-full",children:[s.jsx(lt,{idPrefix:"product",currencies:N,prices:qe.prices,salePrices:qe.salePrices,managedCurrencyCodes:F,onPriceChange:zt,onSalePriceChange:Dt,onAutoFill:qt,readOnly:le,helperText:le?"Parent prices stay as a fallback, but active variants define the live shopper price.":void 0,trailing:s.jsx(mt,{idPrefix:"product",startAt:I("sale_start_at"),endAt:I("sale_end_at"),onChange:(j,q)=>A(j,q,{shouldDirty:!0,shouldValidate:!0}),error:y.sale_end_at?.message,bare:!0})}),y.price&&s.jsx("p",{className:"text-destructive text-sm mt-1",children:y.price.message}),y.sale_price&&s.jsx("p",{className:"text-destructive text-sm mt-1",children:y.sale_price.message}),y.stock&&s.jsx("p",{className:"text-destructive text-[10px] font-medium leading-none mt-1",children:y.stock.message})]}),s.jsxs("div",{className:"flex items-center justify-between gap-3 rounded border border-dashed p-2.5 bg-muted/5",children:[s.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:le?"Variations Active":"Variations"}),s.jsx(x.Button,{type:"button",variant:v?"outline":"default",onClick:()=>w(j=>!j),size:"sm",className:"h-7 text-xs px-3",children:v?"Hide":"Manage"})]}),v&&s.jsx("div",{className:"border-t pt-3",children:s.jsx(di,{globalAttributes:i,currentLanguageCode:fn,baseSku:I("sku")||"",basePrice:be||0,basePrices:ce,baseSalePrice:typeof we=="number"?we:null,baseSalePrices:ve,currencies:N,availableVariantImages:bn,initialVariationAttributes:e?.variation_attributes,initialVariants:gn,onChange:yn})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-end gap-4 w-full",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx(x.Label,{htmlFor:"freemius_product_id",className:"text-[11px] uppercase tracking-wider text-muted-foreground font-bold mb-1.5 block",children:"Freemius Product ID"}),s.jsx(x.Input,{id:"freemius_product_id",...T("freemius_product_id"),className:"h-9"})]}),s.jsxs("div",{className:"flex-1",children:[s.jsx(x.Label,{htmlFor:"freemius_plan_id",className:"text-[11px] uppercase tracking-wider text-muted-foreground font-bold mb-1.5 block",children:"Freemius Plan ID"}),s.jsx(x.Input,{id:"freemius_plan_id",...T("freemius_plan_id"),className:"h-9"})]}),mn?s.jsx(ii,{productId:I("freemius_product_id")}):null]}),s.jsxs("div",{className:"bg-muted/10 border rounded-md overflow-hidden",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-6 bg-muted/20 border-b p-2.5 px-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Free Trial"}),s.jsxs(x.Badge,{variant:"outline",className:"font-mono text-xs shadow-sm bg-background",children:[String(I("trial_period_days")||0)," Days"]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Card Required"}),s.jsx(x.Badge,{variant:Tt?"default":"secondary",className:"text-xs shadow-sm",children:Tt?"Yes":"No"})]}),s.jsx("span",{className:"text-[10px] text-muted-foreground ml-auto",children:"Managed in Freemius dashboard"}),s.jsx("input",{type:"hidden",...T("trial_period_days",{valueAsNumber:!0})})]}),s.jsxs("div",{className:"w-full p-4 pt-3 space-y-2",children:[s.jsx(lt,{idPrefix:"product",currencies:N,prices:qe.prices,salePrices:qe.salePrices,managedCurrencyCodes:F,onPriceChange:zt,onSalePriceChange:Dt,onAutoFill:qt,readOnly:!0,trailing:s.jsx(mt,{idPrefix:"product",startAt:I("sale_start_at"),endAt:I("sale_end_at"),onChange:(j,q)=>A(j,q,{shouldDirty:!0,shouldValidate:!0}),error:y.sale_end_at?.message,bare:!0})}),s.jsx("p",{className:"text-[10px] leading-snug text-muted-foreground",children:"Scheduling a sale on a Freemius product generates a time-bounded Freemius coupon so the discount is enforced at Freemius checkout."})]})]})]}),d&&s.jsx("div",{className:"pt-2 border-t",children:d})]})]}),s.jsx(Be,{title:"Product Description",hideHeader:!0,children:s.jsx("div",{className:"space-y-2",children:s.jsxs("div",{className:"space-y-1",children:[s.jsx(x.Label,{htmlFor:"short_description",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Short Description"}),s.jsx(x.Input,{id:"short_description",...T("short_description"),placeholder:"Brief summary for product cards...",className:"h-8 text-sm"})]})})}),s.jsxs(Be,{title:"Media Gallery",description:"Drag to reorder. First image is the hero.",children:[s.jsx(si,{initialMedia:tt,onUpdate:hn,mediaPickerNode:r}),s.jsx("input",{type:"hidden",...T("product_media")})]}),!t&&s.jsxs("div",{className:"rounded-lg border bg-card p-3 px-4 shadow-sm flex items-center justify-between gap-3 flex-wrap",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Status"}),s.jsxs(x.Select,{onValueChange:j=>A("status",j),value:I("status"),children:[s.jsx(x.SelectTrigger,{className:"h-8 w-[110px] text-sm",children:s.jsx(x.SelectValue,{placeholder:"Status"})}),s.jsxs(x.SelectContent,{children:[s.jsx(x.SelectItem,{value:"draft",children:"Draft"}),s.jsx(x.SelectItem,{value:"active",children:"Active"}),s.jsx(x.SelectItem,{value:"archived",children:"Archived"})]})]})]}),s.jsx(x.Button,{disabled:f,type:"submit",size:"sm",className:"h-8 text-sm px-5",children:f?"Saving...":"Save Changes"})]})]})]})}function $(e,t,r){const n=e(t);return n===t?r:n}function Di(e){return{invoice:$(e,"invoice","Invoice"),invoiceNumber:$(e,"invoice_number","Invoice #"),orderNumber:$(e,"order_number","Order #"),paidOn:$(e,"paid_on","Paid on"),status:$(e,"status","Status"),from:$(e,"from","From"),billTo:$(e,"bill_to","Bill to"),shipTo:$(e,"ship_to","Ship to"),item:$(e,"product","Item"),details:$(e,"details","Details"),quantity:$(e,"ecommerce.qty","Qty"),price:$(e,"price","Price"),amount:$(e,"amount","Amount"),subtotal:$(e,"ecommerce.subtotal","Subtotal"),discount:$(e,"ecommerce.discount","Discount"),shipping:$(e,"ecommerce.shipping","Shipping"),tax:$(e,"ecommerce.tax","Tax"),total:$(e,"ecommerce.total","Total"),taxBreakdown:$(e,"tax_breakdown","Tax breakdown"),taxRegistrations:$(e,"tax_registrations","Tax registrations")}}function qi(e){return e==="fr"?"fr-CA":"en-US"}function ln(e,t){if(!e)return"";switch(e.toLowerCase()){case"paid":return $(t,"order_status_paid","Paid");case"pending":return $(t,"order_status_pending","Pending");case"trial":return $(t,"order_status_trial","Trial");case"shipped":return $(t,"order_status_shipped","Shipped");case"cancelled":return $(t,"order_status_cancelled","Cancelled");case"refunded":return $(t,"order_status_refunded","Refunded");default:return e}}function Ui(e,t){return e?{...e,order:{...e.order,status:ln(e.order.status,t)}}:null}exports.CURRENCY_COOKIE_NAME=zn;exports.CURRENCY_ROUNDING_MODES=mr;exports.DEFAULT_ENABLED_PAYMENT_PROVIDERS=dr;exports.DEFAULT_INVOICE_SETTINGS=Pt;exports.ECOMMERCE_INVENTORY_SETTINGS_KEY=wt;exports.FreemiusProvider=Ms;exports.INVOICE_SETTINGS_KEY=Ys;exports.InvoiceDocument=Zr;exports.InvoiceViewerShell=Zs;exports.ProductCategorySelector=un;exports.ProductForm=zi;exports.STRIPE_TAX_CODE_NONTAXABLE=kr;exports.STRIPE_TAX_CODE_SHIPPING=us;exports.addressesMatch=gs;exports.aggregateOrderTaxLines=At;exports.applyCurrencyRounding=fr;exports.buildCheckoutTaxableItemsFromCart=ms;exports.buildCombinationKey=vt;exports.buildInvoiceDocumentLabels=Di;exports.buildOrderTaxDetailsFromCalculation=Qs;exports.buildOrderTaxDetailsFromStripeSession=Js;exports.buildVariantLabel=Ct;exports.bulkDeleteProductsAction=vi;exports.bulkDraftProductsAction=Ci;exports.calculateCheckoutTaxes=ps;exports.chooseInitialVariantSelections=Qn;exports.convertMinorUnitAmount=_e;exports.copyProductFromLanguage=Br;exports.copyProductFromLanguageAction=Ds;exports.countries=ot;exports.countryUsesStructuredStates=Pr;exports.createCategoryAction=dn;exports.createInventoryInsufficientError=cs;exports.createInventoryUnavailableError=as;exports.createProduct=$r;exports.createProductAction=yi;exports.createProductAttributeAction=Si;exports.createProductAttributeTermAction=Ni;exports.deleteCategoryAction=ki;exports.deleteCouponFromFreemius=hi;exports.deleteProduct=Lr;exports.deleteProductAction=bi;exports.deleteProductAttributeAction=wi;exports.deleteProductAttributeTermAction=Ei;exports.derivePaymentProviderFromProductType=ht;exports.describeCurrencyRoundingRule=In;exports.emptyCustomerAddress=_s;exports.emptyProviderDiscounts=xr;exports.extractSelectedTermsByAttribute=wr;exports.fetchTranslatedProductsForCartInternal=Ns;exports.fillMissingUserProfileCheckoutDetails=Tr;exports.findMatchingVariant=Wn;exports.formatInvoiceCurrency=pe;exports.formatInvoiceDate=Jr;exports.generateVariantDrafts=Sr;exports.getAvailableTermIdsForAttribute=Nr;exports.getCartLineCouponKey=xt;exports.getCategoriesWithCount=Bs;exports.getCategoryBySlug=Ks;exports.getCouponQuote=br;exports.getCurrencyLookup=We;exports.getDefaultCurrency=ie;exports.getDefaultUserAddresses=hs;exports.getEcommerceInventorySettings=Ar;exports.getExchangeRateForCurrency=kn;exports.getFreemiusPricingByProductId=Os;exports.getGlobalProductAttributes=Us;exports.getInventoryItems=bs;exports.getInvoiceAddressLines=Ke;exports.getInvoiceLocale=qi;exports.getOrderTaxRateJurisdiction=Ge;exports.getOrderTaxRateLabel=Re;exports.getOrderTaxRatePercentage=ze;exports.getProduct=Fs;exports.getProduct$1=Or;exports.getProductBySlug=Ss;exports.getProductCategories=Vs;exports.getProductPaymentProvider=ur;exports.getProductTranslations=qs;exports.getProducts=Ts;exports.getProducts$1=Ur;exports.getPublicFreemiusPricing=Ls;exports.getQuoteLineDiscountMap=Bn;exports.getStatesForCountry=jr;exports.getStripeTaxCodeForProduct=ls;exports.getVariantEffectivePriceRange=es;exports.inferCurrencyCodeFromLocale=Fn;exports.isCustomerAddressComplete=fs;exports.isDigitalItem=Pn;exports.isDigitalProduct=lr;exports.isSaleWindowActive=Te;exports.isScheduledPriceDue=hr;exports.localizeInvoicePresentationData=Ui;exports.mapRawVariantRelations=Zn;exports.normalizeCountryCode=Ae;exports.normalizeCouponCode=yr;exports.normalizeCurrencyRecord=W;exports.normalizeCurrencyRoundingMode=_r;exports.normalizeCustomerAddress=xe;exports.normalizeEcommerceInventorySettings=Er;exports.normalizeEnabledPaymentProviders=jn;exports.normalizeInvoiceSettings=Gs;exports.normalizeOrderCustomerDetails=Ir;exports.normalizeOrderTaxDetails=Ws;exports.normalizePriceMap=ee;exports.normalizeSalePriceMap=Ee;exports.normalizeSelectionsToAvailableVariants=Jn;exports.normalizeShippingRateCurrencyMode=bt;exports.normalizeSubdivisionCode=Qe;exports.parseFreemiusCheckoutCredentialsMap=Vr;exports.productSchema=nn;exports.readFreemiusEnvValue=B;exports.recordCouponRedemption=vr;exports.reorderProductAttributeTermsAction=ji;exports.resolveAttributeName=ct;exports.resolveEffectivePriceForCurrency=De;exports.resolveFreemiusCheckoutCredentials=jt;exports.resolvePriceForCurrency=gr;exports.resolvePriceRangeForCurrency=Tn;exports.resolveShippingOptions=ts;exports.resolveSubdivisionName=ss;exports.resolveTermValue=dt;exports.resolveTranslatedText=ye;exports.sanitizeShippingRateAmountMaps=Yn;exports.serializeInvoiceSettings=Xs;exports.setSharedInventoryQuantity=vs;exports.sortCurrencies=Rn;exports.syncCategoriesForTranslationGroup=Je;exports.syncCouponToFreemius=_i;exports.syncFreemiusProductsToSupabase=Gr;exports.syncProductCategoriesAction=Ii;exports.syncProductSaleCouponToFreemius=an;exports.syncSingleFreemiusProduct=Xr;exports.translateOrFallback=$;exports.translateOrderStatus=ln;exports.triggerFreemiusSync=Rs;exports.updateCategoryAction=Ai;exports.updateFreemiusOverride=$s;exports.updateProduct=ws;exports.updateProductAction=xi;exports.updateProductAttributeTranslationsAction=Pi;exports.upsertDefaultUserAddresses=Mr;exports.upsertEcommerceInventorySettings=os;