var L=Object.defineProperty;var j=(r,t)=>()=>(r&&(t=r(r=0)),t);var H=(r,t)=>{for(var e in t)L(r,e,{get:t[e],enumerable:!0})};var D={};H(D,{buildGoogleSheetsCsvUrl:()=>y,loadFromSheets:()=>N,parseCSV:()=>g});function B(r){let t=[],e="",o=!1;for(let n=0;ns.trim().toLowerCase()),o=q.filter(s=>!e.includes(s));if(o.length>0)throw new Error(`Missing required columns: ${o.join(", ")}`);let n=[];for(let s=1;s{a[f]=l[u]!=null?l[u].trim():""});let d={id:a.id,name:a.name,price:parseFloat(a.price)||0,stock:parseInt(a.stock,10)||0,category:a.category,image:a.image};for(let f of V)a[f]&&a[f]!==""&&(d[f]=a[f].split(",").map(u=>u.trim()).filter(u=>u!==""));n.push(d)}return n}function y(r){let t=new URL(r);if(t.hostname.includes("docs.google.com")){if(!t.pathname.includes("/export")){let e=t.pathname.match(/\/d\/([^/]+)/);if(e){let o=e[1],n=t.searchParams.get("gid")||"0";return`https://docs.google.com/spreadsheets/d/${o}/export?format=csv&gid=${n}`}}return t.searchParams.set("format","csv"),t.toString()}return r.toString()}async function N(r,t={}){if(!t.proxyUrl&&!t.sheetUrl)throw new Error("loadFromSheets() requires either 'proxyUrl' or 'sheetUrl'");let e;t.proxyUrl?e=t.proxyUrl:e=y(t.sheetUrl);let o=t.timeout||15e3,n=new AbortController,s=setTimeout(()=>n.abort(),o),c;try{c=await fetch(e,{signal:n.signal})}catch(u){throw clearTimeout(s),u.name==="AbortError"?new Error(`Request timed out after ${o}ms`):u}if(clearTimeout(s),!c.ok)throw new Error(`Failed to fetch products: ${c.status} ${c.statusText}`);let l=c.headers.get("content-type")||"",a=await c.text(),d=a;if(l.includes("application/json")){let u;try{u=JSON.parse(a)}catch(U){throw new Error(`Invalid JSON response: ${U.message}`)}if(u.csv)d=u.csv;else if(u.products)return r.setProducts(u.products),u.products}let f=g(d);return r.setProducts(f),f}var q,V,w=j(()=>{q=["id","name","price","stock","category","image"],V=["relatedids","upsellids","crosssellids"]});var i={W001:"search() requiere un texto de b\xFAsqueda",W002:"Producto no encontrado",W003:"La cantidad debe ser un n\xFAmero entero positivo",W004:"Stock insuficiente",W005:"La cantidad debe ser un n\xFAmero entero no negativo",W006:"Producto no encontrado en el carrito",W007:"El c\xF3digo del cup\xF3n debe ser un texto",W008:"Cup\xF3n inv\xE1lido",W009:"El cup\xF3n ha expirado",W010:"El cup\xF3n alcanz\xF3 su l\xEDmite de usos",W011:"Monto m\xEDnimo de orden no alcanzado",W012:"El valor de env\xEDo debe ser un n\xFAmero no negativo",W013:"El umbral de env\xEDo gratis debe ser un n\xFAmero positivo",W014:"El env\xEDo por \xEDtem debe ser un n\xFAmero no negativo",W015:"M\xE9todo de env\xEDo inv\xE1lido",W016:"M\xE9todo de pago inv\xE1lido",W017:"M\xE9todo de entrega inv\xE1lido",W018:"El carrito est\xE1 vac\xEDo",W019:"El nombre del cliente es requerido",W020:"La direcci\xF3n del cliente es requerida",W021:"El m\xE9todo de pago es requerido",W022:"El m\xE9todo de entrega es requerido",W023:"Estado inv\xE1lido",W024:"Orden no encontrada",W025:"N\xFAmero de WhatsApp no configurado",W026:"El n\xFAmero de WhatsApp debe ser texto o n\xFAmero",W027:"El n\xFAmero de WhatsApp debe tener entre 7 y 15 d\xEDgitos",W028:"La plantilla debe ser una funci\xF3n",W029:"Plantilla no encontrada",W030:"No se puede eliminar la plantilla por defecto",W031:"El ID de la plantilla debe ser un texto no vac\xEDo",W032:"Plantilla activa no encontrada",W033:"El cup\xF3n debe tener un 'code' v\xE1lido",W034:"El cup\xF3n debe tener un 'amount' num\xE9rico",W035:"setProducts() requiere un arreglo",W036:"debe ser un n\xFAmero positivo",W037:"Moneda no soportada",W038:"Regi\xF3n no soportada",W039:"Hook cancelado",W040:"JSON inv\xE1lido en load()",W041:"load() espera un objeto JSON"};function m(r,t){let e={...r};for(let o of Object.keys(t))t[o]&&typeof t[o]=="object"&&!Array.isArray(t[o])&&r[o]&&typeof r[o]=="object"&&!Array.isArray(r[o])?e[o]=m(r[o],t[o]):e[o]=t[o];return e}function x(r){r.prototype._productProp=function(t,e,o){let n=this.getProduct(t);return n&&n[e]!=null?n[e]:o},r.prototype._resolveProductIds=function(t,e,o=null){let n=t[e];if(!n||!Array.isArray(n))return[];let s=n.map(c=>this.getProduct(c)).filter(c=>c!==null);return o&&(s=s.filter(o)),s},r.prototype._findCartItem=function(t){return this.state.cart.find(e=>e.productId===t)},r.prototype._hasCartItem=function(t){return this._findCartItem(t)!==void 0},r.prototype._freeShippingGoal=function(){let t=this.config.shipping.freeFrom;return typeof t=="number"&&t>0?t:0},r.prototype._validatePositiveNumber=function(t,e){if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new Error(`${e} ${i.W036}`)},r.prototype._stockError=function(t,e){return`${i.W004}: "${t}". Disponible: ${e}`},r.prototype._sanitizeString=function(t){return typeof t!="string"?t:t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")},r.prototype._sanitizeObject=function(t){if(t===null||typeof t!="object")return typeof t=="string"?this._sanitizeString(t):t;if(Array.isArray(t))return t.map(o=>this._sanitizeObject(o));let e={};for(let[o,n]of Object.entries(t))typeof n=="string"?e[o]=this._sanitizeString(n):typeof n=="object"&&n!==null?e[o]=this._sanitizeObject(n):e[o]=n;return e},r.prototype._createRateLimiter=function(t=100,e=6e4){let o=[];return{check:()=>{let n=Date.now();for(o.push(n);o.length>0&&o[0]0&&!e.includes(t))throw new Error(`${i.W037}: "${t}". Soportadas: ${e.join(", ")}`);this.state.activeCurrency=t},r.prototype.getCurrency=function(){return this.state.activeCurrency},r.prototype.getExchangeRate=function(t){return this.config.currencies[t]?this.config.currencies[t]:1},r.prototype.convertPrice=function(t){if(typeof t!="number"||!Number.isFinite(t))return 0;let e=this.getExchangeRate(this.state.activeCurrency);return Math.round(t*e*100)/100},r.prototype.formatPrice=function(t,e){let o=e||this.state.activeCurrency;try{return new Intl.NumberFormat(this.config.locale,{style:"currency",currency:o}).format(t)}catch{return`${o} ${t.toFixed(2)}`}}}function v(r){r.prototype.setRegion=function(t){let e=Object.keys(this.config.regions);if(e.length>0&&!e.includes(t))throw new Error(`${i.W038}: "${t}". Soportadas: ${e.join(", ")}`);this.state.activeRegion=t;let o=this.config.regions[t];o&&o.currency&&(this.state.activeCurrency=o.currency)},r.prototype.getRegion=function(){return this.state.activeRegion},r.prototype.getTax=function(){let t=this.config.regions[this.state.activeRegion];return!t||!t.tax?0:typeof t.tax=="number"?t.tax:typeof t.tax=="object"&&t.tax.rate!==void 0?t.tax.rate:0},r.prototype.getTaxName=function(){let t=this.config.regions[this.state.activeRegion];return!t||!t.tax?"Tax":typeof t.tax=="object"&&t.tax.name?t.tax.name:"Tax"},r.prototype.getRegionalShippingCost=function(t){let e=this.config.regions[this.state.activeRegion];if(!e||!e.shipping)return this.config.shipping.value||0;let o=t!==void 0?t:this.getSubtotal(),n=e.shipping;return n.freeFrom&&o>=n.freeFrom?0:n.flat!==void 0?n.flat:n.type==="per_item"?this.getCartItemCount()*(n.perItem||0):0}}function b(r){r.prototype.on=function(t,e){if(!this.hooks[t]){console.warn(`Whanda: unknown hook "${t}"`);return}this.hooks[t].push(e)},r.prototype.off=function(t,e){this.hooks[t]&&(this.hooks[t]=this.hooks[t].filter(o=>o!==e))},r.prototype.runHooks=async function(t,e){if(!this.hooks[t])return e;let o=e;for(let n of this.hooks[t])try{let s=await n(o);if(s!=null&&(o=s),s&&typeof s=="object"&&s.abort===!0){let c=new Error(s.message||`${i.W039}: "${t}"`);throw c._whandaAborted=!0,c}}catch(s){if(s._whandaAborted)throw s;console.error(`Whanda: hook "${t}" error:`,s)}return o}}function E(r){r.prototype.setProducts=function(t){if(!Array.isArray(t))throw new Error(i.W035);this.state.products=this._sanitizeObject(t)},r.prototype.getProducts=function(t={}){let e=[...this.state.products];if(t.category&&(e=e.filter(o=>o.category===t.category)),t.minPrice!=null&&(e=e.filter(o=>o.price>=t.minPrice)),t.maxPrice!=null&&(e=e.filter(o=>o.price<=t.maxPrice)),t.search){let o=t.search.toLowerCase();e=e.filter(n=>n.name&&n.name.toLowerCase().includes(o)||n.category&&n.category.toLowerCase().includes(o))}if(t.sort){let o=t.order==="desc"?-1:1;e.sort((n,s)=>n[t.sort]s[t.sort]?1*o:0)}return t.limit!=null&&(e=e.slice(0,t.limit)),e},r.prototype.getProduct=function(t){return this.state.products.find(e=>e.id===t)||null},r.prototype.getPrice=function(t){return this._productProp(t,"price",0)},r.prototype.getStock=function(t){return this._productProp(t,"stock",0)},r.prototype.getImages=function(t){return this._productProp(t,"images",[])},r.prototype.getCategory=function(t){return this._productProp(t,"category",null)},r.prototype.getCategories=function(){return[...new Set(this.state.products.map(t=>t.category).filter(t=>t!=null&&t!==""))]},r.prototype.search=function(t){if(typeof t!="string")throw new Error(i.W001);return this.getProducts({search:t})},r.prototype.filterByCategory=function(t){return this.getProducts({category:t})},r.prototype.getRelatedProducts=function(t){let e=this.getProduct(t);if(!e)return[];let o=this._resolveProductIds(e,"relatedIds");return o.length>0?o:this.filterByCategory(e.category).filter(n=>n.id!==t)},r.prototype.getUpsells=function(t){let e=this.getProduct(t);if(!e)return[];let o=this._resolveProductIds(e,"upsellIds",n=>n.price>e.price);return o.length>0?o:this.filterByCategory(e.category).filter(n=>n.price>e.price&&n.id!==t)},r.prototype.getCrossSells=function(t){let e=this.getProduct(t);if(!e)return[];let o=this._resolveProductIds(e,"crossSellIds");return o.length>0?o:this.getRelatedProducts(t)},r.prototype.getForCart=function(){if(this.state.cart.length===0)return[];let t=this.state.cart.map(n=>n.productId),e=[...new Set(this.state.cart.map(n=>this.getCategory(n.productId)).filter(n=>n!=null))],o=new Set;return this.state.products.filter(n=>e.includes(n.category)&&!t.includes(n.id)&&!o.has(n.id)?(o.add(n.id),!0):!1)}}function k(r){r.prototype.getCart=function(){return[...this.state.cart]},r.prototype.addItem=async function(t,e=1){if(typeof t!="string"&&typeof t!="number")throw new Error(i.W002);if(!Number.isInteger(e)||e<=0)throw new Error(i.W003);await this.runHooks("beforeAddToCart",{productId:t,quantity:e});let o=this.getProduct(t);if(!o)throw new Error(i.W002);if(o.stock!=null&&o.stock{}),this.state.cart=[],this.runHooks("afterCartChange",this.state.cart).catch(()=>{})},r.prototype.removeCartItem=function(t){this.runHooks("onRemoveItem",{productId:t,cart:[...this.state.cart]}).catch(()=>{}),this.state.cart=this.state.cart.filter(e=>e.productId!==t),this.runHooks("afterCartChange",this.state.cart).catch(()=>{})},r.prototype.updateQuantity=function(t,e){if(!Number.isInteger(e)||e<0)throw new Error(i.W005);let o=this._findCartItem(t);if(!o)throw new Error(i.W006);if(e===0)this.removeCartItem(t);else{let n=this.getProduct(t);if(n&&n.stock!=null&&n.stock{})}},r.prototype.hasCartItem=function(t){return this._hasCartItem(t)},r.prototype.getCartItemCount=function(){return this.state.cart.reduce((t,e)=>t+e.quantity,0)}}function P(r){r.prototype.getSubtotal=function(){return this.state.cart.reduce((t,e)=>t+e.price*e.quantity,0)},r.prototype.getShippingCost=function(){let t=this.getSubtotal(),e=this._freeShippingGoal();if(e>0&&t>=e)return 0;if(this.config.shipping.type==="fixed")return this.config.shipping.value;if(this.config.shipping.type==="per_item"){let o=this.getCartItemCount();return this.config.shipping.perItem*o}return 0},r.prototype.getDiscountAmount=function(){if(!this.state.coupon)return 0;let t=this.state.coupon,e=this.getSubtotal();if(t.type==="percent"){let o=e*(t.amount/100);return t.maxDiscount!=null?Math.min(o,t.maxDiscount):o}return t.amount||0},r.prototype.getTotal=function(){let t=this.getSubtotal(),e=this.getDiscountAmount(),o=this.getShippingCost(),n=this.getTax(),s=Math.round((t-e)*n*100)/100,c=t-e+o+s;return Math.max(0,c)},r.prototype.calculate=function(){let t=this.getSubtotal(),e=this.getDiscountAmount(),o=this.getTax(),n=Math.round((t-e)*o*100)/100;return{subtotal:t,shipping:this.getShippingCost(),discount:e,tax:n,taxRate:o,total:this.getTotal()}}}function $(r){r.prototype.addCoupon=function(t){if(!t||typeof t.code!="string"||t.code.trim()==="")throw new Error(i.W033);if(t.amount==null||typeof t.amount!="number"||t.amount<=0)throw new Error(i.W034);this.state.coupons.push(t)},r.prototype.getCoupons=function(){return[...this.state.coupons]},r.prototype.validateCoupon=function(t){return typeof t!="string"?!1:this.state.coupons.some(e=>e.code===t)},r.prototype.applyCoupon=function(t){if(typeof t!="string")throw new Error(i.W007);let e=this.state.coupons.find(o=>o.code===t);if(!e)throw new Error(i.W008);if(e.expiresAt&&new Date(e.expiresAt)=e.maxUses)throw new Error(i.W010);if(e.minOrder!=null&&this.getSubtotal()s.code===this.state.coupon.code);n!==-1&&(this.state.coupons[n].usedCount=(this.state.coupons[n].usedCount||0)+1)}return this.state.orders.push(o),this.state.cart=[],this.state.coupon=null,this.state.checkout={paymentMethod:null,deliveryMethod:null},await this.runHooks("afterCheckout",o),await this.runHooks("afterCartChange",this.state.cart),o}}function A(r){r.prototype.getOrder=function(t){return this.state.orders.find(e=>e.id===t)||null},r.prototype.getLastOrder=function(){return this.state.orders[this.state.orders.length-1]||null},r.prototype.listOrders=function(){return[...this.state.orders]},r.prototype.updateOrderStatus=function(t,e){let o=["pending","confirmed","shipped","delivered","cancelled"];if(!o.includes(e))throw new Error(`${i.W023}. Debe ser uno de: ${o.join(", ")}`);let n=this.state.orders.find(s=>s.id===t);if(!n)throw new Error(i.W024);return n.status=e,n},r.prototype.cancelOrder=function(t){return this.updateOrderStatus(t,"cancelled")}}function I(r){r.prototype.save=function(){return JSON.stringify({config:this.config,state:this.state,templates:{active:this.templates.active}})},r.prototype.load=function(t){let e;try{e=JSON.parse(t)}catch(o){throw new Error(`${i.W040}: ${o.message}`)}if(e===null||typeof e!="object")throw new Error(i.W041);if(e.config){let o=["currency","locale","whatsappNumber","shipping","paymentMethods","deliveryMethods","storeName"],n={};for(let s of o)e.config[s]!==void 0&&(n[s]=e.config[s]);this.config={...this.config,...n}}if(e.state){let o=["cart","coupons","coupon","customer","checkout","orders","downsell","seasons","urgency","bundles","cro","recentlyViewed"],n={};for(let s of o)e.state[s]!==void 0&&(n[s]=e.state[s]);this.state={...this.state,...n}}e.templates&&e.templates.active&&(this.templates.active=e.templates.active)},r.prototype.reset=function(){this.state.cart=[],this.state.coupon=null,this.state.customer={name:null,address:null,notes:null},this.state.checkout={paymentMethod:null,deliveryMethod:null}}}function O(r){r.prototype.sync=async function(t){let o=await this.runHooks("beforeSync",t);return await this.runHooks("afterSync",o),o}}function T(r){r.prototype.loadFromSources=async function(t){if(this._rateLimiters.sources||(this._rateLimiters.sources=this._createRateLimiter(10,6e4)),!this._rateLimiters.sources.check())throw new Error("Demasiadas solicitudes. Intenta de nuevo en un minuto.");let e=[];for(let o of t)try{if(o.type==="json"){let n=await fetch(o.url);if(n.ok){let s=await n.json(),c=Array.isArray(s)?s:s.products||[];e.push(...c)}}else if(o.type==="sheets"){let{loadFromSheets:n}=await Promise.resolve().then(()=>(w(),D)),s=await n(this,{sheetUrl:o.url,proxyUrl:o.proxyUrl,timeout:o.timeout||15e3});e.push(...s)}else if(o.type==="cache"){let n=this._getCache("whanda_products");n&&e.push(...n)}}catch(n){console.warn(`Whanda: Failed to load from source "${o.type}":`,n.message)}return e.length>0&&this.setProducts(e),e},r.prototype._setCache=function(t,e,o=3600){let n={value:e,expires:Date.now()+o*1e3};try{localStorage.setItem(`whanda_${t}`,JSON.stringify(n))}catch{}},r.prototype._getCache=function(t){try{let e=JSON.parse(localStorage.getItem(`whanda_${t}`));return!e||Date.now()>e.expires?(localStorage.removeItem(`whanda_${t}`),null):e.value}catch{return null}},r.prototype._clearCache=function(t){t?localStorage.removeItem(`whanda_${t}`):Object.keys(localStorage).filter(o=>o.startsWith("whanda_")).forEach(o=>localStorage.removeItem(o))},r.prototype.cacheProducts=function(t=3600){this._setCache("products",this.state.products,t)},r.prototype.loadProductsFromCache=function(){let t=this._getCache("products");return t&&Array.isArray(t)?(this.state.products=this._sanitizeObject(t),!0):!1},r.prototype.getProductsPaginated=function(t=1,e=20,o={}){let n=this.getProducts(o),s=n.length,c=Math.ceil(s/e),l=(t-1)*e;return{products:n.slice(l,l+e),total:s,page:t,pageSize:e,totalPages:c,hasNext:t1}},r.prototype.createProductIterator=function(t=20){let e=0,o=this.state.products;return{getNextBatch:()=>{let n=o.slice(e,e+t);return e+=t,n},hasMore:()=>e{e=0},getTotal:()=>o.length,getLoaded:()=>e}}}function F(r){r.prototype.setWhatsAppNumber=function(t){if(typeof t!="string"&&typeof t!="number")throw new Error(i.W026);let e=String(t).replace(/[^0-9]/g,"");if(e.length<7||e.length>15)throw new Error(i.W027);this.config.whatsappNumber=e},r.prototype.registerWhatsAppTemplate=function(t,e){if(typeof t!="string"||t.trim()==="")throw new Error(i.W031);if(typeof e!="function")throw new Error(i.W028);this.templates.whatsapp[t]={id:t,fn:e}},r.prototype.setWhatsAppTemplate=function(t){if(!this.templates.whatsapp[t])throw new Error(`${i.W029}: "${t}"`);this.templates.active=t},r.prototype.listWhatsAppTemplates=function(){return Object.keys(this.templates.whatsapp)},r.prototype.getWhatsAppTemplate=function(t){return this.templates.whatsapp[t]||null},r.prototype.removeWhatsAppTemplate=function(t){if(t==="default")throw new Error(i.W030);if(!this.templates.whatsapp[t])throw new Error(`${i.W029}: "${t}"`);this.templates.active===t&&(this.templates.active="default"),delete this.templates.whatsapp[t]},r.prototype.previewWhatsAppTemplate=function(t,e){let o=this.templates.whatsapp[t];if(!o)throw new Error(i.W029);return o.fn(e)},r.prototype.generateMessage=async function(t){let e=this.templates.whatsapp[this.templates.active];if(!e)throw new Error(i.W032);let o=e.fn(t);return o=await this.runHooks("beforeGenerateWhatsApp",o),o=await this.runHooks("afterGenerateWhatsApp",o),o},r.prototype.generateLink=async function(t){if(!this.config.whatsappNumber)throw new Error(i.W025);let e=encodeURIComponent(await this.generateMessage(t));return`https://wa.me/${this.config.whatsappNumber}?text=${e}`},r.prototype.sendToWhatsApp=async function(t){return await this.runHooks("beforeWhatsAppSend",t),await this.generateLink(t)},r.prototype.getShareCatalogUrl=function(t={}){let e=this.config.storeName||"Mi Tienda",o=this.state.products.length,n=this.getCategories(),s=n.length>0?` \u{1F4E6} Categor\xEDas: ${n.join(", ")}`:"",c=t.message||`\u{1F6CD}\uFE0F *${e}* Tenemos ${o} productos disponibles${s} ${t.url?`Ver cat\xE1logo: ${t.url}`:""}`;return`https://api.whatsapp.com/send?text=${encodeURIComponent(c.trim())}`},r.prototype.getThankYouHtml=function(t={}){let{message:e="\xA1Gracias por tu compra!",showOrderSummary:o=!0,shareText:n="Compra en nuestra tienda",catalogUrl:s="#"}=t,c=this.getLastOrder(),l=this.config.storeName||"Mi Tienda",a="";o&&c&&(a=`

Resumen de tu orden

    ${c.items.map(u=>`
  • ${this._sanitizeString(u.name)} x${u.quantity} - ${this.formatPrice(u.price*u.quantity)}
  • `).join("")}

Total: ${this.formatPrice(c.total)}

`);let d=this._sanitizeString(s);return`

\u2713 ${this._sanitizeString(e)}

${this._sanitizeString(l)}

${a}
`.trim()},r.prototype._defaultWhatsAppTemplate=function(){return t=>{let e=t.items.map(c=>`- ${c.name} x${c.quantity}`).join(` `),o=t.customer.name?` \u{1F464} *Cliente:* ${t.customer.name} \u{1F4CD} *Direcci\xF3n:* ${t.customer.address}`:"",n=t.tax>0?` ${t.taxName||"Tax"} (${(t.taxRate*100).toFixed(0)}%): ${t.tax}`:"",s=t.currency&&t.currency!=="DOP"?` \u{1F4B1} Moneda: ${t.currency}`:"";return` \u{1F6D2} *Nuevo Pedido* ${o} ${e} Subtotal: ${t.subtotal} Env\xEDo: ${t.shipping} Descuento: ${t.discount}${n}${s} Total: *${t.total}* Pago: ${t.paymentMethod||"N/A"} Entrega: ${t.deliveryMethod||"N/A"} `.trim()}}}var p=class{constructor(t={}){this.config=m({currency:"DOP",locale:"es-DO",whatsappNumber:null,shipping:{type:"fixed",value:0,freeFrom:null,perItem:0},paymentMethods:["Cash","Bank Transfer"],deliveryMethods:["Home Delivery","In-store Pickup"],currencies:{},regions:{},storeName:"Mi Tienda"},t),this.state={products:[],cart:[],coupons:[],coupon:null,customer:{name:null,address:null,notes:null},checkout:{paymentMethod:null,deliveryMethod:null},orders:[],downsell:null,seasons:[],urgency:{},bundles:[],cro:{freeShippingBar:!1,freeShippingGoal:0,lowStockAlert:!1,socialProof:!1,recentlyViewed:!1,exitIntent:!1,exitMessage:"",exitDiscount:0},recentlyViewed:[],activeCurrency:t.currency||"DOP",activeRegion:null},this.hooks={beforeAddToCart:[],afterAddToCart:[],afterCartChange:[],beforeCheckout:[],afterCheckout:[],beforeWhatsAppSend:[],beforeGenerateWhatsApp:[],afterGenerateWhatsApp:[],beforeSync:[],afterSync:[],onCartEmpty:[],onRemoveItem:[]},this.templates={whatsapp:{default:{id:"default",fn:this._defaultWhatsAppTemplate()}},active:"default"},this._rateLimiters={}}};x(p);C(p);S(p);v(p);b(p);E(p);k(p);P(p);$(p);M(p);_(p);R(p);A(p);I(p);O(p);T(p);F(p);w();var h={W100:"Bundle requiere id, name, y products",W101:"Bundle no encontrado",W102:"Season requiere id, name, start, y end",W103:"Downsell requiere un discount num\xE9rico positivo",W104:"Urgency requiere al menos uno de: lowStock, deadline, o badge",W105:"Las fechas de season deben ser v\xE1lidas y start debe ser anterior a end",W106:"Ya existe un elemento con ese ID"};function z(r){r.prototype.setDownsell=function(t){if(!t||typeof t.discount!="number"||t.discount<=0)throw new Error(h.W103);this.state.downsell=t},r.prototype.getDownsell=function(){return this.state.downsell?{...this.state.downsell}:null},r.prototype.clearDownsell=function(){this.state.downsell=null},r.prototype.createSeason=function(t){if(!t.id||!t.name||!t.start||!t.end)throw new Error(h.W102);let e=new Date(t.start),o=new Date(t.end);if(isNaN(e.getTime())||isNaN(o.getTime())||e>=o)throw new Error(h.W105);if(this.state.seasons.some(n=>n.id===t.id))throw new Error(h.W106);this.state.seasons.push(t)},r.prototype.getSeasons=function(){return[...this.state.seasons]},r.prototype.getActiveSeason=function(){let t=new Date;return this.state.seasons.find(e=>t>=new Date(e.start)&&t<=new Date(e.end))||null},r.prototype.isInSeason=function(t){let e=this.getActiveSeason();return e?e.products&&e.products.includes(t):!1},r.prototype.removeSeason=function(t){this.state.seasons=this.state.seasons.filter(e=>e.id!==t)},r.prototype.setProductUrgency=function(t,e){if(!e||!e.lowStock&&!e.deadline&&!e.badge)throw new Error(h.W104);this.state.urgency[t]=e},r.prototype.getUrgency=function(t){let e=this.state.urgency[t];if(!e)return null;let o=this.getProduct(t),n=o?o.stock:null,s=e.deadline?new Date<=new Date(e.deadline):!1,c=e.lowStock&&n!==null?n<=e.lowStock:!1,l=e.deadline?new Datet.lowStock).map(([t,e])=>{let o=this.getProduct(t);return o&&o.stock<=e.lowStock?o:null}).filter(Boolean)},r.prototype.createBundle=function(t){if(!t.id||!t.name||!t.products)throw new Error(h.W100);if(this.state.bundles.some(s=>s.id===t.id))throw new Error(h.W106);let e=0;t.products.forEach(s=>{let c=typeof s=="string"?s:s.productId,l=typeof s=="string"?1:s.quantity||1,a=this.getProduct(c);a&&(e+=a.price*l)});let o=t.discount?e*(1-t.discount):e,n=t.products.map(s=>typeof s=="string"?{productId:s,quantity:1}:{productId:s.productId,quantity:s.quantity||1});this.state.bundles.push({...t,products:n,originalPrice:e,bundlePrice:Math.max(0,o)})},r.prototype.getBundles=function(){return[...this.state.bundles]},r.prototype.getBundle=function(t){return this.state.bundles.find(e=>e.id===t)||null},r.prototype.addBundle=async function(t,e=1){let o=this.getBundle(t);if(!o)throw new Error(h.W101);for(let n of o.products)await this.addItem(n.productId,e*(n.quantity||1))},r.prototype.removeBundle=function(t){let e=this.getBundle(t);if(!e)throw new Error(h.W101);e.products.forEach(o=>{this.removeCartItem(o.productId)})},r.prototype.deleteBundle=function(t){this.state.bundles=this.state.bundles.filter(e=>e.id!==t)},r.prototype.setCRO=function(t){this.state.cro={...this.state.cro,...t}},r.prototype.getCROData=function(){return{freeShippingProgress:this.checkFreeShippingProgress(),lowStockProducts:this.getLowStockProducts(),recentlyViewed:this.getRecentlyViewed(),exitIntent:this.state.cro.exitIntent||null}},r.prototype.trackProductView=function(t){this.state.recentlyViewed||(this.state.recentlyViewed=[]),this.state.recentlyViewed=this.state.recentlyViewed.filter(e=>e!==t),this.state.recentlyViewed.unshift(t),this.state.recentlyViewed.length>10&&(this.state.recentlyViewed=this.state.recentlyViewed.slice(0,10))},r.prototype.getRecentlyViewed=function(){return this.state.recentlyViewed?this.state.recentlyViewed.map(t=>this.getProduct(t)).filter(Boolean):[]},r.prototype.getSocialProof=function(t){let e=t.split("").reduce((s,c)=>s+c.charCodeAt(0),0),o=e%20+5,n=e%15+2;return{productId:t,viewers:o,purchasers:n,message:`${o} people are viewing this right now`,recentPurchaseMessage:`${n} people bought this recently`}},r.prototype.checkFreeShippingProgress=function(){let t=this.state.cro.freeShippingGoal||this.config.shipping.freeFrom||0,o=(this.state.cart||[]).reduce((n,s)=>{let c=this.getProduct(s.productId);return n+(c?c.price*s.quantity:0)},0);return{current:o,goal:t,remaining:Math.max(0,t-o),qualifies:o>=t,progress:t>0?Math.min(1,o/t):1}}}function W(r){r.prototype.exportOrders=function(){if(this.state.orders.length===0)return"";let t=n=>{let s=String(n??"");return s=s.replace(/&/g,"&").replace(//g,">"),s.includes(",")||s.includes('"')||s.includes(` `)?`"${s.replace(/"/g,'""')}"`:s},e=["ID,Fecha,Cliente,Total,Pago,Entrega,Status"],o=this.state.orders.map(n=>`${t(n.id)},${t(n.createdAt)},${t(n.customer.name)},${n.total},${t(n.paymentMethod)},${t(n.deliveryMethod)},${t(n.status)}`);return e.concat(o).join(` `)}}export{p as Whanda,y as buildGoogleSheetsCsvUrl,W as initExtensions,z as initPlugins,N as loadFromSheets,g as parseCSV};