var qm=Object.defineProperty;var Hm=(r,t,s)=>t in r?qm(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s;var qs=(r,t,s)=>Hm(r,typeof t!="symbol"?t+"":t,s);import{r as p,a as Km,g as $n,R as jt,b as Ym,c as _s,u as Jt,d as _t,L as es,e as To,f as Xr,N as Jm,h as su,i as nt,B as Zm}from"./react-vendor-DXAaEtp_.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var ru={exports:{}},Ln={};/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var Xm=p,Qm=Symbol.for("react.element"),ep=Symbol.for("react.fragment"),tp=Object.prototype.hasOwnProperty,sp=Xm.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,rp={key:!0,ref:!0,__self:!0,__source:!0};function au(r,t,s){var a,n={},i=null,o=null;s!==void 0&&(i=""+s),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(o=t.ref);for(a in t)tp.call(t,a)&&!rp.hasOwnProperty(a)&&(n[a]=t[a]);if(r&&r.defaultProps)for(a in t=r.defaultProps,t)n[a]===void 0&&(n[a]=t[a]);return{$$typeof:Qm,type:r,key:i,ref:o,props:n,_owner:sp.current}}Ln.Fragment=ep;Ln.jsx=au;Ln.jsxs=au;ru.exports=Ln;var e=ru.exports,nu,Gl=Km;nu=Gl.createRoot,Gl.hydrateRoot;var ap=typeof Element<"u",np=typeof Map=="function",ip=typeof Set=="function",op=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function mn(r,t){if(r===t)return!0;if(r&&t&&typeof r=="object"&&typeof t=="object"){if(r.constructor!==t.constructor)return!1;var s,a,n;if(Array.isArray(r)){if(s=r.length,s!=t.length)return!1;for(a=s;a--!==0;)if(!mn(r[a],t[a]))return!1;return!0}var i;if(np&&r instanceof Map&&t instanceof Map){if(r.size!==t.size)return!1;for(i=r.entries();!(a=i.next()).done;)if(!t.has(a.value[0]))return!1;for(i=r.entries();!(a=i.next()).done;)if(!mn(a.value[1],t.get(a.value[0])))return!1;return!0}if(ip&&r instanceof Set&&t instanceof Set){if(r.size!==t.size)return!1;for(i=r.entries();!(a=i.next()).done;)if(!t.has(a.value[0]))return!1;return!0}if(op&&ArrayBuffer.isView(r)&&ArrayBuffer.isView(t)){if(s=r.length,s!=t.length)return!1;for(a=s;a--!==0;)if(r[a]!==t[a])return!1;return!0}if(r.constructor===RegExp)return r.source===t.source&&r.flags===t.flags;if(r.valueOf!==Object.prototype.valueOf&&typeof r.valueOf=="function"&&typeof t.valueOf=="function")return r.valueOf()===t.valueOf();if(r.toString!==Object.prototype.toString&&typeof r.toString=="function"&&typeof t.toString=="function")return r.toString()===t.toString();if(n=Object.keys(r),s=n.length,s!==Object.keys(t).length)return!1;for(a=s;a--!==0;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;if(ap&&r instanceof Element)return!1;for(a=s;a--!==0;)if(!((n[a]==="_owner"||n[a]==="__v"||n[a]==="__o")&&r.$$typeof)&&!mn(r[n[a]],t[n[a]]))return!1;return!0}return r!==r&&t!==t}var lp=function(t,s){try{return mn(t,s)}catch(a){if((a.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw a}};const cp=$n(lp);var dp=function(r,t,s,a,n,i,o,l){if(!r){var c;if(t===void 0)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[s,a,n,i,o,l],d=0;c=new Error(t.replace(/%s/g,function(){return u[d++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},up=dp;const Ul=$n(up);var hp=function(t,s,a,n){var i=a?a.call(n,t,s):void 0;if(i!==void 0)return!!i;if(t===s)return!0;if(typeof t!="object"||!t||typeof s!="object"||!s)return!1;var o=Object.keys(t),l=Object.keys(s);if(o.length!==l.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(s),u=0;u<o.length;u++){var d=o[u];if(!c(d))return!1;var h=t[d],m=s[d];if(i=a?a.call(n,h,m,d):void 0,i===!1||i===void 0&&h!==m)return!1}return!0};const mp=$n(hp);var iu=(r=>(r.BASE="base",r.BODY="body",r.HEAD="head",r.HTML="html",r.LINK="link",r.META="meta",r.NOSCRIPT="noscript",r.SCRIPT="script",r.STYLE="style",r.TITLE="title",r.FRAGMENT="Symbol(react.fragment)",r))(iu||{}),si={link:{rel:["amphtml","canonical","alternate"]},script:{type:["application/ld+json"]},meta:{charset:"",name:["generator","robots","description"],property:["og:type","og:title","og:url","og:image","og:image:alt","og:description","twitter:url","twitter:title","twitter:description","twitter:image","twitter:image:alt","twitter:card","twitter:site"]}},Vl=Object.values(iu),Ao={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},pp=Object.entries(Ao).reduce((r,[t,s])=>(r[s]=t,r),{}),Rs="data-rh",zr={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},Wr=(r,t)=>{for(let s=r.length-1;s>=0;s-=1){const a=r[s];if(Object.prototype.hasOwnProperty.call(a,t))return a[t]}return null},gp=r=>{let t=Wr(r,"title");const s=Wr(r,zr.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),s&&t)return s.replace(/%s/g,()=>t);const a=Wr(r,zr.DEFAULT_TITLE);return t||a||void 0},fp=r=>Wr(r,zr.ON_CHANGE_CLIENT_STATE)||(()=>{}),ri=(r,t)=>t.filter(s=>typeof s[r]<"u").map(s=>s[r]).reduce((s,a)=>({...s,...a}),{}),xp=(r,t)=>t.filter(s=>typeof s.base<"u").map(s=>s.base).reverse().reduce((s,a)=>{if(!s.length){const n=Object.keys(a);for(let i=0;i<n.length;i+=1){const l=n[i].toLowerCase();if(r.indexOf(l)!==-1&&a[l])return s.concat(a)}}return s},[]),yp=r=>console&&typeof console.warn=="function"&&console.warn(r),ia=(r,t,s)=>{const a={};return s.filter(n=>Array.isArray(n[r])?!0:(typeof n[r]<"u"&&yp(`Helmet: ${r} should be of type "Array". Instead found type "${typeof n[r]}"`),!1)).map(n=>n[r]).reverse().reduce((n,i)=>{const o={};i.filter(c=>{let u;const d=Object.keys(c);for(let m=0;m<d.length;m+=1){const g=d[m],f=g.toLowerCase();t.indexOf(f)!==-1&&!(u==="rel"&&c[u].toLowerCase()==="canonical")&&!(f==="rel"&&c[f].toLowerCase()==="stylesheet")&&(u=f),t.indexOf(g)!==-1&&(g==="innerHTML"||g==="cssText"||g==="itemprop")&&(u=g)}if(!u||!c[u])return!1;const h=c[u].toLowerCase();return a[u]||(a[u]={}),o[u]||(o[u]={}),a[u][h]?!1:(o[u][h]=!0,!0)}).reverse().forEach(c=>n.push(c));const l=Object.keys(o);for(let c=0;c<l.length;c+=1){const u=l[c],d={...a[u],...o[u]};a[u]=d}return n},[]).reverse()},bp=(r,t)=>{if(Array.isArray(r)&&r.length){for(let s=0;s<r.length;s+=1)if(r[s][t])return!0}return!1},vp=r=>({baseTag:xp(["href"],r),bodyAttributes:ri("bodyAttributes",r),defer:Wr(r,zr.DEFER),encode:Wr(r,zr.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:ri("htmlAttributes",r),linkTags:ia("link",["rel","href"],r),metaTags:ia("meta",["name","charset","http-equiv","property","itemprop"],r),noscriptTags:ia("noscript",["innerHTML"],r),onChangeClientState:fp(r),scriptTags:ia("script",["src","innerHTML"],r),styleTags:ia("style",["cssText"],r),title:gp(r),titleAttributes:ri("titleAttributes",r),prioritizeSeoTags:bp(r,zr.PRIORITIZE_SEO_TAGS)}),ou=r=>Array.isArray(r)?r.join(""):r,wp=(r,t)=>{const s=Object.keys(r);for(let a=0;a<s.length;a+=1)if(t[s[a]]&&t[s[a]].includes(r[s[a]]))return!0;return!1},ai=(r,t)=>Array.isArray(r)?r.reduce((s,a)=>(wp(a,t)?s.priority.push(a):s.default.push(a),s),{priority:[],default:[]}):{default:r,priority:[]},zl=(r,t)=>({...r,[t]:void 0}),jp=["noscript","script","style"],Ri=(r,t=!0)=>t===!1?String(r):String(r).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),lu=r=>Object.keys(r).reduce((t,s)=>{const a=typeof r[s]<"u"?`${s}="${r[s]}"`:`${s}`;return t?`${t} ${a}`:a},""),Np=(r,t,s,a)=>{const n=lu(s),i=ou(t);return n?`<${r} ${Rs}="true" ${n}>${Ri(i,a)}</${r}>`:`<${r} ${Rs}="true">${Ri(i,a)}</${r}>`},kp=(r,t,s=!0)=>t.reduce((a,n)=>{const i=n,o=Object.keys(i).filter(u=>!(u==="innerHTML"||u==="cssText")).reduce((u,d)=>{const h=typeof i[d]>"u"?d:`${d}="${Ri(i[d],s)}"`;return u?`${u} ${h}`:h},""),l=i.innerHTML||i.cssText||"",c=jp.indexOf(r)===-1;return`${a}<${r} ${Rs}="true" ${o}${c?"/>":`>${l}</${r}>`}`},""),cu=(r,t={})=>Object.keys(r).reduce((s,a)=>{const n=Ao[a];return s[n||a]=r[a],s},t),_p=(r,t,s)=>{const a={key:t,[Rs]:!0},n=cu(s,a);return[jt.createElement("title",n,t)]},pn=(r,t)=>t.map((s,a)=>{const n={key:a,[Rs]:!0};return Object.keys(s).forEach(i=>{const l=Ao[i]||i;if(l==="innerHTML"||l==="cssText"){const c=s.innerHTML||s.cssText;n.dangerouslySetInnerHTML={__html:c}}else n[l]=s[i]}),jt.createElement(r,n)}),Ns=(r,t,s=!0)=>{switch(r){case"title":return{toComponent:()=>_p(r,t.title,t.titleAttributes),toString:()=>Np(r,t.title,t.titleAttributes,s)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>cu(t),toString:()=>lu(t)};default:return{toComponent:()=>pn(r,t),toString:()=>kp(r,t,s)}}},Sp=({metaTags:r,linkTags:t,scriptTags:s,encode:a})=>{const n=ai(r,si.meta),i=ai(t,si.link),o=ai(s,si.script);return{priorityMethods:{toComponent:()=>[...pn("meta",n.priority),...pn("link",i.priority),...pn("script",o.priority)],toString:()=>`${Ns("meta",n.priority,a)} ${Ns("link",i.priority,a)} ${Ns("script",o.priority,a)}`},metaTags:n.default,linkTags:i.default,scriptTags:o.default}},Cp=r=>{const{baseTag:t,bodyAttributes:s,encode:a=!0,htmlAttributes:n,noscriptTags:i,styleTags:o,title:l="",titleAttributes:c,prioritizeSeoTags:u}=r;let{linkTags:d,metaTags:h,scriptTags:m}=r,g={toComponent:()=>{},toString:()=>""};return u&&({priorityMethods:g,linkTags:d,metaTags:h,scriptTags:m}=Sp(r)),{priority:g,base:Ns("base",t,a),bodyAttributes:Ns("bodyAttributes",s,a),htmlAttributes:Ns("htmlAttributes",n,a),link:Ns("link",d,a),meta:Ns("meta",h,a),noscript:Ns("noscript",i,a),script:Ns("script",m,a),style:Ns("style",o,a),title:Ns("title",{title:l,titleAttributes:c},a)}},$i=Cp,Xa=[],du=!!(typeof window<"u"&&window.document&&window.document.createElement),Li=class{constructor(r,t){qs(this,"instances",[]);qs(this,"canUseDOM",du);qs(this,"context");qs(this,"value",{setHelmet:r=>{this.context.helmet=r},helmetInstances:{get:()=>this.canUseDOM?Xa:this.instances,add:r=>{(this.canUseDOM?Xa:this.instances).push(r)},remove:r=>{const t=(this.canUseDOM?Xa:this.instances).indexOf(r);(this.canUseDOM?Xa:this.instances).splice(t,1)}}});this.context=r,this.canUseDOM=t||!1,t||(r.helmet=$i({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},Pp={},uu=jt.createContext(Pp),br,hu=(br=class extends p.Component{constructor(s){super(s);qs(this,"helmetData");this.helmetData=new Li(this.props.context||{},br.canUseDOM)}render(){return jt.createElement(uu.Provider,{value:this.helmetData.value},this.props.children)}},qs(br,"canUseDOM",du),br),Tr=(r,t)=>{const s=document.head||document.querySelector("head"),a=s.querySelectorAll(`${r}[${Rs}]`),n=[].slice.call(a),i=[];let o;return t&&t.length&&t.forEach(l=>{const c=document.createElement(r);for(const u in l)if(Object.prototype.hasOwnProperty.call(l,u))if(u==="innerHTML")c.innerHTML=l.innerHTML;else if(u==="cssText")c.styleSheet?c.styleSheet.cssText=l.cssText:c.appendChild(document.createTextNode(l.cssText));else{const d=u,h=typeof l[d]>"u"?"":l[d];c.setAttribute(u,h)}c.setAttribute(Rs,"true"),n.some((u,d)=>(o=d,c.isEqualNode(u)))?n.splice(o,1):i.push(c)}),n.forEach(l=>{var c;return(c=l.parentNode)==null?void 0:c.removeChild(l)}),i.forEach(l=>s.appendChild(l)),{oldTags:n,newTags:i}},Oi=(r,t)=>{const s=document.getElementsByTagName(r)[0];if(!s)return;const a=s.getAttribute(Rs),n=a?a.split(","):[],i=[...n],o=Object.keys(t);for(const l of o){const c=t[l]||"";s.getAttribute(l)!==c&&s.setAttribute(l,c),n.indexOf(l)===-1&&n.push(l);const u=i.indexOf(l);u!==-1&&i.splice(u,1)}for(let l=i.length-1;l>=0;l-=1)s.removeAttribute(i[l]);n.length===i.length?s.removeAttribute(Rs):s.getAttribute(Rs)!==o.join(",")&&s.setAttribute(Rs,o.join(","))},Ep=(r,t)=>{typeof r<"u"&&document.title!==r&&(document.title=ou(r)),Oi("title",t)},Wl=(r,t)=>{const{baseTag:s,bodyAttributes:a,htmlAttributes:n,linkTags:i,metaTags:o,noscriptTags:l,onChangeClientState:c,scriptTags:u,styleTags:d,title:h,titleAttributes:m}=r;Oi("body",a),Oi("html",n),Ep(h,m);const g={baseTag:Tr("base",s),linkTags:Tr("link",i),metaTags:Tr("meta",o),noscriptTags:Tr("noscript",l),scriptTags:Tr("script",u),styleTags:Tr("style",d)},f={},v={};Object.keys(g).forEach(x=>{const{newTags:j,oldTags:b}=g[x];j.length&&(f[x]=j),b.length&&(v[x]=g[x].oldTags)}),t&&t(),c(r,f,v)},oa=null,Tp=r=>{oa&&cancelAnimationFrame(oa),r.defer?oa=requestAnimationFrame(()=>{Wl(r,()=>{oa=null})}):(Wl(r),oa=null)},Ap=Tp,ql=class extends p.Component{constructor(){super(...arguments);qs(this,"rendered",!1)}shouldComponentUpdate(t){return!mp(t,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:t}=this.props.context;t.remove(this),this.emitChange()}emitChange(){const{helmetInstances:t,setHelmet:s}=this.props.context;let a=null;const n=vp(t.get().map(i=>{const o={...i.props};return delete o.context,o}));hu.canUseDOM?Ap(n):$i&&(a=$i(n)),s(a)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:t}=this.props.context;t.add(this),this.emitChange()}render(){return this.init(),null}},Ii,as=(Ii=class extends p.Component{shouldComponentUpdate(r){return!cp(zl(this.props,"helmetData"),zl(r,"helmetData"))}mapNestedChildrenToProps(r,t){if(!t)return null;switch(r.type){case"script":case"noscript":return{innerHTML:t};case"style":return{cssText:t};default:throw new Error(`<${r.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(r,t,s,a){return{...t,[r.type]:[...t[r.type]||[],{...s,...this.mapNestedChildrenToProps(r,a)}]}}mapObjectTypeChildren(r,t,s,a){switch(r.type){case"title":return{...t,[r.type]:a,titleAttributes:{...s}};case"body":return{...t,bodyAttributes:{...s}};case"html":return{...t,htmlAttributes:{...s}};default:return{...t,[r.type]:{...s}}}}mapArrayTypeChildrenToProps(r,t){let s={...t};return Object.keys(r).forEach(a=>{s={...s,[a]:r[a]}}),s}warnOnInvalidChildren(r,t){return Ul(Vl.some(s=>r.type===s),typeof r.type=="function"?"You may be attempting to nest <Helmet> components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${Vl.join(", ")} are allowed. Helmet does not support rendering <${r.type}> elements. Refer to our API for more information.`),Ul(!t||typeof t=="string"||Array.isArray(t)&&!t.some(s=>typeof s!="string"),`Helmet expects a string as a child of <${r.type}>. Did you forget to wrap your children in braces? ( <${r.type}>{\`\`}</${r.type}> ) Refer to our API for more information.`),!0}mapChildrenToProps(r,t){let s={};return jt.Children.forEach(r,a=>{if(!a||!a.props)return;const{children:n,...i}=a.props,o=Object.keys(i).reduce((c,u)=>(c[pp[u]||u]=i[u],c),{});let{type:l}=a;switch(typeof l=="symbol"?l=l.toString():this.warnOnInvalidChildren(a,n),l){case"Symbol(react.fragment)":t=this.mapChildrenToProps(n,t);break;case"link":case"meta":case"noscript":case"script":case"style":s=this.flattenArrayTypeChildren(a,s,o,n);break;default:t=this.mapObjectTypeChildren(a,t,o,n);break}}),this.mapArrayTypeChildrenToProps(s,t)}render(){const{children:r,...t}=this.props;let s={...t},{helmetData:a}=t;if(r&&(s=this.mapChildrenToProps(r,s)),a&&!(a instanceof Li)){const n=a;a=new Li(n.context,!0),delete s.helmetData}return a?jt.createElement(ql,{...s,context:a.value}):jt.createElement(uu.Consumer,null,n=>jt.createElement(ql,{...s,context:n}))}},qs(Ii,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),Ii);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */var Ip={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Rp=r=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),je=(r,t)=>{const s=p.forwardRef(({color:a="currentColor",size:n=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:l="",children:c,...u},d)=>p.createElement("svg",{ref:d,...Ip,width:n,height:n,stroke:a,strokeWidth:o?Number(i)*24/Number(n):i,className:["lucide",`lucide-${Rp(r)}`,l].join(" "),...u},[...t.map(([h,m])=>p.createElement(h,m)),...Array.isArray(c)?c:[c]]));return s.displayName=`${r}`,s};/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Mi=je("AlertCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Io=je("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bi=je("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ls=je("BookOpen",[["path",{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z",key:"vv98re"}],["path",{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",key:"1cyq3y"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Hl=je("Book",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20",key:"t4utmx"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $p=je("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Lp=je("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Op=je("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ro=je("CheckCircle",[["path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14",key:"g774vq"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Sa=je("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Us=je("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ut=je("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const gs=je("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const qr=je("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Mp=je("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const mu=je("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bp=je("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const pu=je("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const gu=je("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Fp=je("GlobeLock",[["path",{d:"M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13",key:"qkt0x6"}],["path",{d:"M2 12h8.5",key:"ovaggd"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Fi=je("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $o=je("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const fu=je("Home",[["path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"y5dka4"}],["polyline",{points:"9 22 9 12 15 12 15 22",key:"e2us08"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Di=je("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Dp=je("Instagram",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"5",ry:"5",key:"2e1cvw"}],["path",{d:"M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z",key:"9exkf1"}],["line",{x1:"17.5",x2:"17.51",y1:"6.5",y2:"6.5",key:"r4j83e"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ni=je("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ue=je("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const jn=je("Loader",[["line",{x1:"12",x2:"12",y1:"2",y2:"6",key:"gza1u7"}],["line",{x1:"12",x2:"12",y1:"18",y2:"22",key:"1qhbu9"}],["line",{x1:"4.93",x2:"7.76",y1:"4.93",y2:"7.76",key:"xae44r"}],["line",{x1:"16.24",x2:"19.07",y1:"16.24",y2:"19.07",key:"bxnmvf"}],["line",{x1:"2",x2:"6",y1:"12",y2:"12",key:"89khin"}],["line",{x1:"18",x2:"22",y1:"12",y2:"12",key:"pb8tfm"}],["line",{x1:"4.93",x2:"7.76",y1:"19.07",y2:"16.24",key:"1uxjnu"}],["line",{x1:"16.24",x2:"19.07",y1:"7.76",y2:"4.93",key:"6duxfx"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const vt=je("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Gp=je("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Lo=je("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ma=je("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const xa=je("MapPin",[["path",{d:"M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z",key:"2oe9fu"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Up=je("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Vp=je("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const xu=je("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const yu=je("Pause",[["rect",{width:"4",height:"16",x:"6",y:"4",key:"iffhe4"}],["rect",{width:"4",height:"16",x:"14",y:"4",key:"sjin7j"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const On=je("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ca=je("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const zp=je("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Gs=je("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Wp=je("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const qp=je("Server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const gn=je("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const bu=je("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const vu=je("ShoppingBag",[["path",{d:"M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z",key:"hou9p0"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Hp=je("Sparkle",[["path",{d:"m12 3-1.9 5.8a2 2 0 0 1-1.287 1.288L3 12l5.8 1.9a2 2 0 0 1 1.288 1.287L12 21l1.9-5.8a2 2 0 0 1 1.287-1.288L21 12l-5.8-1.9a2 2 0 0 1-1.288-1.287Z",key:"nraa5p"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ba=je("Sparkles",[["path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z",key:"17u4zn"}],["path",{d:"M5 3v4",key:"bklmnn"}],["path",{d:"M19 17v4",key:"iiml17"}],["path",{d:"M3 5h4",key:"nem4j1"}],["path",{d:"M17 19h4",key:"lbex7p"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Pa=je("Star",[["polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2",key:"8f66p6"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Kl=je("Sticker",[["path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z",key:"1wis1t"}],["path",{d:"M14 3v4a2 2 0 0 0 2 2h4",key:"36rjfy"}],["path",{d:"M8 13h0",key:"jdup5h"}],["path",{d:"M16 13h0",key:"l4i2ga"}],["path",{d:"M10 16s.8 1 2 1c1.3 0 2-1 2-1",key:"1vvgv3"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Oo=je("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Kp=je("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ya=je("Truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $t=je("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Gi=je("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const wu=je("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ju=je("Volume2",[["polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5",key:"16drj5"}],["path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",key:"ltjumu"}],["path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",key:"1kegas"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Nu=je("VolumeX",[["polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5",key:"16drj5"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Yp=je("XCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
 * @license lucide-react v0.344.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Cs=je("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Mo=p.createContext({});function Bo(r){const t=p.useRef(null);return t.current===null&&(t.current=r()),t.current}const Mn=p.createContext(null),Fo=p.createContext({transformPagePoint:r=>r,isStatic:!1,reducedMotion:"never"});class Jp extends p.Component{getSnapshotBeforeUpdate(t){const s=this.props.childRef.current;if(s&&t.isPresent&&!this.props.isPresent){const a=this.props.sizeRef.current;a.height=s.offsetHeight||0,a.width=s.offsetWidth||0,a.top=s.offsetTop,a.left=s.offsetLeft}return null}componentDidUpdate(){}render(){return this.props.children}}function Zp({children:r,isPresent:t}){const s=p.useId(),a=p.useRef(null),n=p.useRef({width:0,height:0,top:0,left:0}),{nonce:i}=p.useContext(Fo);return p.useInsertionEffect(()=>{const{width:o,height:l,top:c,left:u}=n.current;if(t||!a.current||!o||!l)return;a.current.dataset.motionPopId=s;const d=document.createElement("style");return i&&(d.nonce=i),document.head.appendChild(d),d.sheet&&d.sheet.insertRule(`
          [data-motion-pop-id="${s}"] {
            position: absolute !important;
            width: ${o}px !important;
            height: ${l}px !important;
            top: ${c}px !important;
            left: ${u}px !important;
          }
        `),()=>{document.head.removeChild(d)}},[t]),e.jsx(Jp,{isPresent:t,childRef:a,sizeRef:n,children:p.cloneElement(r,{ref:a})})}const Xp=({children:r,initial:t,isPresent:s,onExitComplete:a,custom:n,presenceAffectsLayout:i,mode:o})=>{const l=Bo(Qp),c=p.useId(),u=p.useCallback(h=>{l.set(h,!0);for(const m of l.values())if(!m)return;a&&a()},[l,a]),d=p.useMemo(()=>({id:c,initial:t,isPresent:s,custom:n,onExitComplete:u,register:h=>(l.set(h,!1),()=>l.delete(h))}),i?[Math.random(),u]:[s,u]);return p.useMemo(()=>{l.forEach((h,m)=>l.set(m,!1))},[s]),p.useEffect(()=>{!s&&!l.size&&a&&a()},[s]),o==="popLayout"&&(r=e.jsx(Zp,{isPresent:s,children:r})),e.jsx(Mn.Provider,{value:d,children:r})};function Qp(){return new Map}function ku(r=!0){const t=p.useContext(Mn);if(t===null)return[!0,null];const{isPresent:s,onExitComplete:a,register:n}=t,i=p.useId();p.useEffect(()=>{r&&n(i)},[r]);const o=p.useCallback(()=>r&&a&&a(i),[i,a,r]);return!s&&a?[!1,o]:[!0]}const Qa=r=>r.key||"";function Yl(r){const t=[];return p.Children.forEach(r,s=>{p.isValidElement(s)&&t.push(s)}),t}const Do=typeof window<"u",_u=Do?p.useLayoutEffect:p.useEffect,ks=({children:r,custom:t,initial:s=!0,onExitComplete:a,presenceAffectsLayout:n=!0,mode:i="sync",propagate:o=!1})=>{const[l,c]=ku(o),u=p.useMemo(()=>Yl(r),[r]),d=o&&!l?[]:u.map(Qa),h=p.useRef(!0),m=p.useRef(u),g=Bo(()=>new Map),[f,v]=p.useState(u),[x,j]=p.useState(u);_u(()=>{h.current=!1,m.current=u;for(let S=0;S<x.length;S++){const T=Qa(x[S]);d.includes(T)?g.delete(T):g.get(T)!==!0&&g.set(T,!1)}},[x,d.length,d.join("-")]);const b=[];if(u!==f){let S=[...u];for(let T=0;T<x.length;T++){const I=x[T],E=Qa(I);d.includes(E)||(S.splice(T,0,I),b.push(I))}i==="wait"&&b.length&&(S=b),j(Yl(S)),v(u);return}const{forceRender:y}=p.useContext(Mo);return e.jsx(e.Fragment,{children:x.map(S=>{const T=Qa(S),I=o&&!l?!1:u===x||d.includes(T),E=()=>{if(g.has(T))g.set(T,!0);else return;let O=!0;g.forEach(V=>{V||(O=!1)}),O&&(y==null||y(),j(m.current),o&&(c==null||c()),a&&a())};return e.jsx(Xp,{isPresent:I,initial:!h.current||s?void 0:!1,custom:I?void 0:t,presenceAffectsLayout:n,mode:i,onExitComplete:I?void 0:E,children:S},T)})})},bs=r=>r;let Ui=bs;function Go(r){let t;return()=>(t===void 0&&(t=r()),t)}const Hr=(r,t,s)=>{const a=t-r;return a===0?1:(s-r)/a},Js=r=>r*1e3,Zs=r=>r/1e3,eg={skipAnimations:!1,useManualTiming:!1};function tg(r){let t=new Set,s=new Set,a=!1,n=!1;const i=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1};function l(u){i.has(u)&&(c.schedule(u),r()),u(o)}const c={schedule:(u,d=!1,h=!1)=>{const g=h&&a?t:s;return d&&i.add(u),g.has(u)||g.add(u),u},cancel:u=>{s.delete(u),i.delete(u)},process:u=>{if(o=u,a){n=!0;return}a=!0,[t,s]=[s,t],t.forEach(l),t.clear(),a=!1,n&&(n=!1,c.process(u))}};return c}const en=["read","resolveKeyframes","update","preRender","render","postRender"],sg=40;function Su(r,t){let s=!1,a=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>s=!0,o=en.reduce((j,b)=>(j[b]=tg(i),j),{}),{read:l,resolveKeyframes:c,update:u,preRender:d,render:h,postRender:m}=o,g=()=>{const j=performance.now();s=!1,n.delta=a?1e3/60:Math.max(Math.min(j-n.timestamp,sg),1),n.timestamp=j,n.isProcessing=!0,l.process(n),c.process(n),u.process(n),d.process(n),h.process(n),m.process(n),n.isProcessing=!1,s&&t&&(a=!1,r(g))},f=()=>{s=!0,a=!0,n.isProcessing||r(g)};return{schedule:en.reduce((j,b)=>{const y=o[b];return j[b]=(S,T=!1,I=!1)=>(s||f(),y.schedule(S,T,I)),j},{}),cancel:j=>{for(let b=0;b<en.length;b++)o[en[b]].cancel(j)},state:n,steps:o}}const{schedule:Et,cancel:nr,state:rs,steps:ii}=Su(typeof requestAnimationFrame<"u"?requestAnimationFrame:bs,!0),Cu=p.createContext({strict:!1}),Jl={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},Kr={};for(const r in Jl)Kr[r]={isEnabled:t=>Jl[r].some(s=>!!t[s])};function rg(r){for(const t in r)Kr[t]={...Kr[t],...r[t]}}const ag=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Nn(r){return r.startsWith("while")||r.startsWith("drag")&&r!=="draggable"||r.startsWith("layout")||r.startsWith("onTap")||r.startsWith("onPan")||r.startsWith("onLayout")||ag.has(r)}let Pu=r=>!Nn(r);function ng(r){r&&(Pu=t=>t.startsWith("on")?!Nn(t):r(t))}try{ng(require("@emotion/is-prop-valid").default)}catch{}function ig(r,t,s){const a={};for(const n in r)n==="values"&&typeof r.values=="object"||(Pu(n)||s===!0&&Nn(n)||!t&&!Nn(n)||r.draggable&&n.startsWith("onDrag"))&&(a[n]=r[n]);return a}function og(r){if(typeof Proxy>"u")return r;const t=new Map,s=(...a)=>r(...a);return new Proxy(s,{get:(a,n)=>n==="create"?r:(t.has(n)||t.set(n,r(n)),t.get(n))})}const Bn=p.createContext({});function Ea(r){return typeof r=="string"||Array.isArray(r)}function Fn(r){return r!==null&&typeof r=="object"&&typeof r.start=="function"}const Uo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Vo=["initial",...Uo];function Dn(r){return Fn(r.animate)||Vo.some(t=>Ea(r[t]))}function Eu(r){return!!(Dn(r)||r.variants)}function lg(r,t){if(Dn(r)){const{initial:s,animate:a}=r;return{initial:s===!1||Ea(s)?s:void 0,animate:Ea(a)?a:void 0}}return r.inherit!==!1?t:{}}function cg(r){const{initial:t,animate:s}=lg(r,p.useContext(Bn));return p.useMemo(()=>({initial:t,animate:s}),[Zl(t),Zl(s)])}function Zl(r){return Array.isArray(r)?r.join(" "):r}const dg=Symbol.for("motionComponentSymbol");function Fr(r){return r&&typeof r=="object"&&Object.prototype.hasOwnProperty.call(r,"current")}function ug(r,t,s){return p.useCallback(a=>{a&&r.onMount&&r.onMount(a),t&&(a?t.mount(a):t.unmount()),s&&(typeof s=="function"?s(a):Fr(s)&&(s.current=a))},[t])}const zo=r=>r.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),hg="framerAppearId",Tu="data-"+zo(hg),{schedule:Wo,cancel:$1}=Su(queueMicrotask,!1),Au=p.createContext({});function mg(r,t,s,a,n){var i,o;const{visualElement:l}=p.useContext(Bn),c=p.useContext(Cu),u=p.useContext(Mn),d=p.useContext(Fo).reducedMotion,h=p.useRef(null);a=a||c.renderer,!h.current&&a&&(h.current=a(r,{visualState:t,parent:l,props:s,presenceContext:u,blockInitialAnimation:u?u.initial===!1:!1,reducedMotionConfig:d}));const m=h.current,g=p.useContext(Au);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&pg(h.current,s,n,g);const f=p.useRef(!1);p.useInsertionEffect(()=>{m&&f.current&&m.update(s,u)});const v=s[Tu],x=p.useRef(!!v&&!(!((i=window.MotionHandoffIsComplete)===null||i===void 0)&&i.call(window,v))&&((o=window.MotionHasOptimisedAnimation)===null||o===void 0?void 0:o.call(window,v)));return _u(()=>{m&&(f.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),Wo.render(m.render),x.current&&m.animationState&&m.animationState.animateChanges())}),p.useEffect(()=>{m&&(!x.current&&m.animationState&&m.animationState.animateChanges(),x.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)===null||j===void 0||j.call(window,v)}),x.current=!1))}),m}function pg(r,t,s,a){const{layoutId:n,layout:i,drag:o,dragConstraints:l,layoutScroll:c,layoutRoot:u}=t;r.projection=new s(r.latestValues,t["data-framer-portal-id"]?void 0:Iu(r.parent)),r.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!o||l&&Fr(l),visualElement:r,animationType:typeof i=="string"?i:"both",initialPromotionConfig:a,layoutScroll:c,layoutRoot:u})}function Iu(r){if(r)return r.options.allowProjection!==!1?r.projection:Iu(r.parent)}function gg({preloadedFeatures:r,createVisualElement:t,useRender:s,useVisualState:a,Component:n}){var i,o;r&&rg(r);function l(u,d){let h;const m={...p.useContext(Fo),...u,layoutId:fg(u)},{isStatic:g}=m,f=cg(u),v=a(u,g);if(!g&&Do){xg();const x=yg(m);h=x.MeasureLayout,f.visualElement=mg(n,v,m,t,x.ProjectionNode)}return e.jsxs(Bn.Provider,{value:f,children:[h&&f.visualElement?e.jsx(h,{visualElement:f.visualElement,...m}):null,s(n,u,ug(v,f.visualElement,d),v,g,f.visualElement)]})}l.displayName=`motion.${typeof n=="string"?n:`create(${(o=(i=n.displayName)!==null&&i!==void 0?i:n.name)!==null&&o!==void 0?o:""})`}`;const c=p.forwardRef(l);return c[dg]=n,c}function fg({layoutId:r}){const t=p.useContext(Mo).id;return t&&r!==void 0?t+"-"+r:r}function xg(r,t){p.useContext(Cu).strict}function yg(r){const{drag:t,layout:s}=Kr;if(!t&&!s)return{};const a={...t,...s};return{MeasureLayout:t!=null&&t.isEnabled(r)||s!=null&&s.isEnabled(r)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}const bg=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function qo(r){return typeof r!="string"||r.includes("-")?!1:!!(bg.indexOf(r)>-1||/[A-Z]/u.test(r))}function Xl(r){const t=[{},{}];return r==null||r.values.forEach((s,a)=>{t[0][a]=s.get(),t[1][a]=s.getVelocity()}),t}function Ho(r,t,s,a){if(typeof t=="function"){const[n,i]=Xl(a);t=t(s!==void 0?s:r.custom,n,i)}if(typeof t=="string"&&(t=r.variants&&r.variants[t]),typeof t=="function"){const[n,i]=Xl(a);t=t(s!==void 0?s:r.custom,n,i)}return t}const Vi=r=>Array.isArray(r),vg=r=>!!(r&&typeof r=="object"&&r.mix&&r.toValue),wg=r=>Vi(r)?r[r.length-1]||0:r,ls=r=>!!(r&&r.getVelocity);function fn(r){const t=ls(r)?r.get():r;return vg(t)?t.toValue():t}function jg({scrapeMotionValuesFromProps:r,createRenderState:t,onUpdate:s},a,n,i){const o={latestValues:Ng(a,n,i,r),renderState:t()};return s&&(o.onMount=l=>s({props:a,current:l,...o}),o.onUpdate=l=>s(l)),o}const Ru=r=>(t,s)=>{const a=p.useContext(Bn),n=p.useContext(Mn),i=()=>jg(r,t,a,n);return s?i():Bo(i)};function Ng(r,t,s,a){const n={},i=a(r,{});for(const m in i)n[m]=fn(i[m]);let{initial:o,animate:l}=r;const c=Dn(r),u=Eu(r);t&&u&&!c&&r.inherit!==!1&&(o===void 0&&(o=t.initial),l===void 0&&(l=t.animate));let d=s?s.initial===!1:!1;d=d||o===!1;const h=d?l:o;if(h&&typeof h!="boolean"&&!Fn(h)){const m=Array.isArray(h)?h:[h];for(let g=0;g<m.length;g++){const f=Ho(r,m[g]);if(f){const{transitionEnd:v,transition:x,...j}=f;for(const b in j){let y=j[b];if(Array.isArray(y)){const S=d?y.length-1:0;y=y[S]}y!==null&&(n[b]=y)}for(const b in v)n[b]=v[b]}}}return n}const Qr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],wr=new Set(Qr),$u=r=>t=>typeof t=="string"&&t.startsWith(r),Lu=$u("--"),kg=$u("var(--"),Ko=r=>kg(r)?_g.test(r.split("/*")[0].trim()):!1,_g=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ou=(r,t)=>t&&typeof r=="number"?t.transform(r):r,Xs=(r,t,s)=>s>t?t:s<r?r:s,ea={test:r=>typeof r=="number",parse:parseFloat,transform:r=>r},Ta={...ea,transform:r=>Xs(0,1,r)},tn={...ea,default:1},Fa=r=>({test:t=>typeof t=="string"&&t.endsWith(r)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${r}`}),sr=Fa("deg"),Vs=Fa("%"),Oe=Fa("px"),Sg=Fa("vh"),Cg=Fa("vw"),Ql={...Vs,parse:r=>Vs.parse(r)/100,transform:r=>Vs.transform(r*100)},Pg={borderWidth:Oe,borderTopWidth:Oe,borderRightWidth:Oe,borderBottomWidth:Oe,borderLeftWidth:Oe,borderRadius:Oe,radius:Oe,borderTopLeftRadius:Oe,borderTopRightRadius:Oe,borderBottomRightRadius:Oe,borderBottomLeftRadius:Oe,width:Oe,maxWidth:Oe,height:Oe,maxHeight:Oe,top:Oe,right:Oe,bottom:Oe,left:Oe,padding:Oe,paddingTop:Oe,paddingRight:Oe,paddingBottom:Oe,paddingLeft:Oe,margin:Oe,marginTop:Oe,marginRight:Oe,marginBottom:Oe,marginLeft:Oe,backgroundPositionX:Oe,backgroundPositionY:Oe},Eg={rotate:sr,rotateX:sr,rotateY:sr,rotateZ:sr,scale:tn,scaleX:tn,scaleY:tn,scaleZ:tn,skew:sr,skewX:sr,skewY:sr,distance:Oe,translateX:Oe,translateY:Oe,translateZ:Oe,x:Oe,y:Oe,z:Oe,perspective:Oe,transformPerspective:Oe,opacity:Ta,originX:Ql,originY:Ql,originZ:Oe},ec={...ea,transform:Math.round},Yo={...Pg,...Eg,zIndex:ec,size:Oe,fillOpacity:Ta,strokeOpacity:Ta,numOctaves:ec},Tg={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Ag=Qr.length;function Ig(r,t,s){let a="",n=!0;for(let i=0;i<Ag;i++){const o=Qr[i],l=r[o];if(l===void 0)continue;let c=!0;if(typeof l=="number"?c=l===(o.startsWith("scale")?1:0):c=parseFloat(l)===0,!c||s){const u=Ou(l,Yo[o]);if(!c){n=!1;const d=Tg[o]||o;a+=`${d}(${u}) `}s&&(t[o]=u)}}return a=a.trim(),s?a=s(t,n?"":a):n&&(a="none"),a}function Jo(r,t,s){const{style:a,vars:n,transformOrigin:i}=r;let o=!1,l=!1;for(const c in t){const u=t[c];if(wr.has(c)){o=!0;continue}else if(Lu(c)){n[c]=u;continue}else{const d=Ou(u,Yo[c]);c.startsWith("origin")?(l=!0,i[c]=d):a[c]=d}}if(t.transform||(o||s?a.transform=Ig(t,r.transform,s):a.transform&&(a.transform="none")),l){const{originX:c="50%",originY:u="50%",originZ:d=0}=i;a.transformOrigin=`${c} ${u} ${d}`}}const Rg={offset:"stroke-dashoffset",array:"stroke-dasharray"},$g={offset:"strokeDashoffset",array:"strokeDasharray"};function Lg(r,t,s=1,a=0,n=!0){r.pathLength=1;const i=n?Rg:$g;r[i.offset]=Oe.transform(-a);const o=Oe.transform(t),l=Oe.transform(s);r[i.array]=`${o} ${l}`}function tc(r,t,s){return typeof r=="string"?r:Oe.transform(t+s*r)}function Og(r,t,s){const a=tc(t,r.x,r.width),n=tc(s,r.y,r.height);return`${a} ${n}`}function Zo(r,{attrX:t,attrY:s,attrScale:a,originX:n,originY:i,pathLength:o,pathSpacing:l=1,pathOffset:c=0,...u},d,h){if(Jo(r,u,h),d){r.style.viewBox&&(r.attrs.viewBox=r.style.viewBox);return}r.attrs=r.style,r.style={};const{attrs:m,style:g,dimensions:f}=r;m.transform&&(f&&(g.transform=m.transform),delete m.transform),f&&(n!==void 0||i!==void 0||g.transform)&&(g.transformOrigin=Og(f,n!==void 0?n:.5,i!==void 0?i:.5)),t!==void 0&&(m.x=t),s!==void 0&&(m.y=s),a!==void 0&&(m.scale=a),o!==void 0&&Lg(m,o,l,c,!1)}const Xo=()=>({style:{},transform:{},transformOrigin:{},vars:{}}),Mu=()=>({...Xo(),attrs:{}}),Qo=r=>typeof r=="string"&&r.toLowerCase()==="svg";function Bu(r,{style:t,vars:s},a,n){Object.assign(r.style,t,n&&n.getProjectionStyles(a));for(const i in s)r.style.setProperty(i,s[i])}const Fu=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Du(r,t,s,a){Bu(r,t,void 0,a);for(const n in t.attrs)r.setAttribute(Fu.has(n)?n:zo(n),t.attrs[n])}const kn={};function Mg(r){Object.assign(kn,r)}function Gu(r,{layout:t,layoutId:s}){return wr.has(r)||r.startsWith("origin")||(t||s!==void 0)&&(!!kn[r]||r==="opacity")}function el(r,t,s){var a;const{style:n}=r,i={};for(const o in n)(ls(n[o])||t.style&&ls(t.style[o])||Gu(o,r)||((a=s==null?void 0:s.getValue(o))===null||a===void 0?void 0:a.liveStyle)!==void 0)&&(i[o]=n[o]);return i}function Uu(r,t,s){const a=el(r,t,s);for(const n in r)if(ls(r[n])||ls(t[n])){const i=Qr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;a[i]=r[n]}return a}function Bg(r,t){try{t.dimensions=typeof r.getBBox=="function"?r.getBBox():r.getBoundingClientRect()}catch{t.dimensions={x:0,y:0,width:0,height:0}}}const sc=["x","y","width","height","cx","cy","r"],Fg={useVisualState:Ru({scrapeMotionValuesFromProps:Uu,createRenderState:Mu,onUpdate:({props:r,prevProps:t,current:s,renderState:a,latestValues:n})=>{if(!s)return;let i=!!r.drag;if(!i){for(const l in n)if(wr.has(l)){i=!0;break}}if(!i)return;let o=!t;if(t)for(let l=0;l<sc.length;l++){const c=sc[l];r[c]!==t[c]&&(o=!0)}o&&Et.read(()=>{Bg(s,a),Et.render(()=>{Zo(a,n,Qo(s.tagName),r.transformTemplate),Du(s,a)})})}})},Dg={useVisualState:Ru({scrapeMotionValuesFromProps:el,createRenderState:Xo})};function Vu(r,t,s){for(const a in t)!ls(t[a])&&!Gu(a,s)&&(r[a]=t[a])}function Gg({transformTemplate:r},t){return p.useMemo(()=>{const s=Xo();return Jo(s,t,r),Object.assign({},s.vars,s.style)},[t])}function Ug(r,t){const s=r.style||{},a={};return Vu(a,s,r),Object.assign(a,Gg(r,t)),a}function Vg(r,t){const s={},a=Ug(r,t);return r.drag&&r.dragListener!==!1&&(s.draggable=!1,a.userSelect=a.WebkitUserSelect=a.WebkitTouchCallout="none",a.touchAction=r.drag===!0?"none":`pan-${r.drag==="x"?"y":"x"}`),r.tabIndex===void 0&&(r.onTap||r.onTapStart||r.whileTap)&&(s.tabIndex=0),s.style=a,s}function zg(r,t,s,a){const n=p.useMemo(()=>{const i=Mu();return Zo(i,t,Qo(a),r.transformTemplate),{...i.attrs,style:{...i.style}}},[t]);if(r.style){const i={};Vu(i,r.style,r),n.style={...i,...n.style}}return n}function Wg(r=!1){return(s,a,n,{latestValues:i},o)=>{const c=(qo(s)?zg:Vg)(a,i,o,s),u=ig(a,typeof s=="string",r),d=s!==p.Fragment?{...u,...c,ref:n}:{},{children:h}=a,m=p.useMemo(()=>ls(h)?h.get():h,[h]);return p.createElement(s,{...d,children:m})}}function qg(r,t){return function(a,{forwardMotionProps:n}={forwardMotionProps:!1}){const o={...qo(a)?Fg:Dg,preloadedFeatures:r,useRender:Wg(n),createVisualElement:t,Component:a};return gg(o)}}function zu(r,t){if(!Array.isArray(t))return!1;const s=t.length;if(s!==r.length)return!1;for(let a=0;a<s;a++)if(t[a]!==r[a])return!1;return!0}function Gn(r,t,s){const a=r.getProps();return Ho(a,t,s!==void 0?s:a.custom,r)}const Hg=Go(()=>window.ScrollTimeline!==void 0);class Kg{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map(t=>"finished"in t?t.finished:t))}getAll(t){return this.animations[0][t]}setAll(t,s){for(let a=0;a<this.animations.length;a++)this.animations[a][t]=s}attachTimeline(t,s){const a=this.animations.map(n=>{if(Hg()&&n.attachTimeline)return n.attachTimeline(t);if(typeof s=="function")return s(n)});return()=>{a.forEach((n,i)=>{n&&n(),this.animations[i].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let s=0;s<this.animations.length;s++)t=Math.max(t,this.animations[s].duration);return t}runAll(t){this.animations.forEach(s=>s[t]())}flatten(){this.runAll("flatten")}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class Yg extends Kg{then(t,s){return Promise.all(this.animations).then(t).catch(s)}}function tl(r,t){return r?r[t]||r.default||r:void 0}const zi=2e4;function Wu(r){let t=0;const s=50;let a=r.next(t);for(;!a.done&&t<zi;)t+=s,a=r.next(t);return t>=zi?1/0:t}function sl(r){return typeof r=="function"}function rc(r,t){r.timeline=t,r.onfinish=null}const rl=r=>Array.isArray(r)&&typeof r[0]=="number",Jg={linearEasing:void 0};function Zg(r,t){const s=Go(r);return()=>{var a;return(a=Jg[t])!==null&&a!==void 0?a:s()}}const _n=Zg(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),qu=(r,t,s=10)=>{let a="";const n=Math.max(Math.round(t/s),2);for(let i=0;i<n;i++)a+=r(Hr(0,n-1,i))+", ";return`linear(${a.substring(0,a.length-2)})`};function Hu(r){return!!(typeof r=="function"&&_n()||!r||typeof r=="string"&&(r in Wi||_n())||rl(r)||Array.isArray(r)&&r.every(Hu))}const ha=([r,t,s,a])=>`cubic-bezier(${r}, ${t}, ${s}, ${a})`,Wi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:ha([0,.65,.55,1]),circOut:ha([.55,0,1,.45]),backIn:ha([.31,.01,.66,-.59]),backOut:ha([.33,1.53,.69,.99])};function Ku(r,t){if(r)return typeof r=="function"&&_n()?qu(r,t):rl(r)?ha(r):Array.isArray(r)?r.map(s=>Ku(s,t)||Wi.easeOut):Wi[r]}const Ts={x:!1,y:!1};function Yu(){return Ts.x||Ts.y}function Xg(r,t,s){var a;if(r instanceof Element)return[r];if(typeof r=="string"){let n=document;const i=(a=void 0)!==null&&a!==void 0?a:n.querySelectorAll(r);return i?Array.from(i):[]}return Array.from(r)}function Ju(r,t){const s=Xg(r),a=new AbortController,n={passive:!0,...t,signal:a.signal};return[s,n,()=>a.abort()]}function ac(r){return t=>{t.pointerType==="touch"||Yu()||r(t)}}function Qg(r,t,s={}){const[a,n,i]=Ju(r,s),o=ac(l=>{const{target:c}=l,u=t(l);if(typeof u!="function"||!c)return;const d=ac(h=>{u(h),c.removeEventListener("pointerleave",d)});c.addEventListener("pointerleave",d,n)});return a.forEach(l=>{l.addEventListener("pointerenter",o,n)}),i}const Zu=(r,t)=>t?r===t?!0:Zu(r,t.parentElement):!1,al=r=>r.pointerType==="mouse"?typeof r.button!="number"||r.button<=0:r.isPrimary!==!1,ef=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function tf(r){return ef.has(r.tagName)||r.tabIndex!==-1}const ma=new WeakSet;function nc(r){return t=>{t.key==="Enter"&&r(t)}}function oi(r,t){r.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const sf=(r,t)=>{const s=r.currentTarget;if(!s)return;const a=nc(()=>{if(ma.has(s))return;oi(s,"down");const n=nc(()=>{oi(s,"up")}),i=()=>oi(s,"cancel");s.addEventListener("keyup",n,t),s.addEventListener("blur",i,t)});s.addEventListener("keydown",a,t),s.addEventListener("blur",()=>s.removeEventListener("keydown",a),t)};function ic(r){return al(r)&&!Yu()}function rf(r,t,s={}){const[a,n,i]=Ju(r,s),o=l=>{const c=l.currentTarget;if(!ic(l)||ma.has(c))return;ma.add(c);const u=t(l),d=(g,f)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),!(!ic(g)||!ma.has(c))&&(ma.delete(c),typeof u=="function"&&u(g,{success:f}))},h=g=>{d(g,s.useGlobalTarget||Zu(c,g.target))},m=g=>{d(g,!1)};window.addEventListener("pointerup",h,n),window.addEventListener("pointercancel",m,n)};return a.forEach(l=>{!tf(l)&&l.getAttribute("tabindex")===null&&(l.tabIndex=0),(s.useGlobalTarget?window:l).addEventListener("pointerdown",o,n),l.addEventListener("focus",u=>sf(u,n),n)}),i}function af(r){return r==="x"||r==="y"?Ts[r]?null:(Ts[r]=!0,()=>{Ts[r]=!1}):Ts.x||Ts.y?null:(Ts.x=Ts.y=!0,()=>{Ts.x=Ts.y=!1})}const Xu=new Set(["width","height","top","left","right","bottom",...Qr]);let xn;function nf(){xn=void 0}const zs={now:()=>(xn===void 0&&zs.set(rs.isProcessing||eg.useManualTiming?rs.timestamp:performance.now()),xn),set:r=>{xn=r,queueMicrotask(nf)}};function nl(r,t){r.indexOf(t)===-1&&r.push(t)}function il(r,t){const s=r.indexOf(t);s>-1&&r.splice(s,1)}class ol{constructor(){this.subscriptions=[]}add(t){return nl(this.subscriptions,t),()=>il(this.subscriptions,t)}notify(t,s,a){const n=this.subscriptions.length;if(n)if(n===1)this.subscriptions[0](t,s,a);else for(let i=0;i<n;i++){const o=this.subscriptions[i];o&&o(t,s,a)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}function Qu(r,t){return t?r*(1e3/t):0}const oc=30,of=r=>!isNaN(parseFloat(r));class lf{constructor(t,s={}){this.version="11.18.2",this.canTrackVelocity=null,this.events={},this.updateAndNotify=(a,n=!0)=>{const i=zs.now();this.updatedAt!==i&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(a),this.current!==this.prev&&this.events.change&&this.events.change.notify(this.current),n&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.hasAnimated=!1,this.setCurrent(t),this.owner=s.owner}setCurrent(t){this.current=t,this.updatedAt=zs.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=of(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,s){this.events[t]||(this.events[t]=new ol);const a=this.events[t].add(s);return t==="change"?()=>{a(),Et.read(()=>{this.events.change.getSize()||this.stop()})}:a}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,s){this.passiveEffect=t,this.stopPassiveEffect=s}set(t,s=!0){!s||!this.passiveEffect?this.updateAndNotify(t,s):this.passiveEffect(t,this.updateAndNotify)}setWithVelocity(t,s,a){this.set(s),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-a}jump(t,s=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,s&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=zs.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>oc)return 0;const s=Math.min(this.updatedAt-this.prevUpdatedAt,oc);return Qu(parseFloat(this.current)-parseFloat(this.prevFrameValue),s)}start(t){return this.stop(),new Promise(s=>{this.hasAnimated=!0,this.animation=t(s),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Aa(r,t){return new lf(r,t)}function cf(r,t,s){r.hasValue(t)?r.getValue(t).set(s):r.addValue(t,Aa(s))}function df(r,t){const s=Gn(r,t);let{transitionEnd:a={},transition:n={},...i}=s||{};i={...i,...a};for(const o in i){const l=wg(i[o]);cf(r,o,l)}}function uf(r){return!!(ls(r)&&r.add)}function qi(r,t){const s=r.getValue("willChange");if(uf(s))return s.add(t)}function eh(r){return r.props[Tu]}const th=(r,t,s)=>(((1-3*s+3*t)*r+(3*s-6*t))*r+3*t)*r,hf=1e-7,mf=12;function pf(r,t,s,a,n){let i,o,l=0;do o=t+(s-t)/2,i=th(o,a,n)-r,i>0?s=o:t=o;while(Math.abs(i)>hf&&++l<mf);return o}function Da(r,t,s,a){if(r===t&&s===a)return bs;const n=i=>pf(i,0,1,r,s);return i=>i===0||i===1?i:th(n(i),t,a)}const sh=r=>t=>t<=.5?r(2*t)/2:(2-r(2*(1-t)))/2,rh=r=>t=>1-r(1-t),ah=Da(.33,1.53,.69,.99),ll=rh(ah),nh=sh(ll),ih=r=>(r*=2)<1?.5*ll(r):.5*(2-Math.pow(2,-10*(r-1))),cl=r=>1-Math.sin(Math.acos(r)),oh=rh(cl),lh=sh(cl),ch=r=>/^0[^.\s]+$/u.test(r);function gf(r){return typeof r=="number"?r===0:r!==null?r==="none"||r==="0"||ch(r):!0}const ba=r=>Math.round(r*1e5)/1e5,dl=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ff(r){return r==null}const xf=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ul=(r,t)=>s=>!!(typeof s=="string"&&xf.test(s)&&s.startsWith(r)||t&&!ff(s)&&Object.prototype.hasOwnProperty.call(s,t)),dh=(r,t,s)=>a=>{if(typeof a!="string")return a;const[n,i,o,l]=a.match(dl);return{[r]:parseFloat(n),[t]:parseFloat(i),[s]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},yf=r=>Xs(0,255,r),li={...ea,transform:r=>Math.round(yf(r))},xr={test:ul("rgb","red"),parse:dh("red","green","blue"),transform:({red:r,green:t,blue:s,alpha:a=1})=>"rgba("+li.transform(r)+", "+li.transform(t)+", "+li.transform(s)+", "+ba(Ta.transform(a))+")"};function bf(r){let t="",s="",a="",n="";return r.length>5?(t=r.substring(1,3),s=r.substring(3,5),a=r.substring(5,7),n=r.substring(7,9)):(t=r.substring(1,2),s=r.substring(2,3),a=r.substring(3,4),n=r.substring(4,5),t+=t,s+=s,a+=a,n+=n),{red:parseInt(t,16),green:parseInt(s,16),blue:parseInt(a,16),alpha:n?parseInt(n,16)/255:1}}const Hi={test:ul("#"),parse:bf,transform:xr.transform},Dr={test:ul("hsl","hue"),parse:dh("hue","saturation","lightness"),transform:({hue:r,saturation:t,lightness:s,alpha:a=1})=>"hsla("+Math.round(r)+", "+Vs.transform(ba(t))+", "+Vs.transform(ba(s))+", "+ba(Ta.transform(a))+")"},os={test:r=>xr.test(r)||Hi.test(r)||Dr.test(r),parse:r=>xr.test(r)?xr.parse(r):Dr.test(r)?Dr.parse(r):Hi.parse(r),transform:r=>typeof r=="string"?r:r.hasOwnProperty("red")?xr.transform(r):Dr.transform(r)},vf=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function wf(r){var t,s;return isNaN(r)&&typeof r=="string"&&(((t=r.match(dl))===null||t===void 0?void 0:t.length)||0)+(((s=r.match(vf))===null||s===void 0?void 0:s.length)||0)>0}const uh="number",hh="color",jf="var",Nf="var(",lc="${}",kf=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Ia(r){const t=r.toString(),s=[],a={color:[],number:[],var:[]},n=[];let i=0;const l=t.replace(kf,c=>(os.test(c)?(a.color.push(i),n.push(hh),s.push(os.parse(c))):c.startsWith(Nf)?(a.var.push(i),n.push(jf),s.push(c)):(a.number.push(i),n.push(uh),s.push(parseFloat(c))),++i,lc)).split(lc);return{values:s,split:l,indexes:a,types:n}}function mh(r){return Ia(r).values}function ph(r){const{split:t,types:s}=Ia(r),a=t.length;return n=>{let i="";for(let o=0;o<a;o++)if(i+=t[o],n[o]!==void 0){const l=s[o];l===uh?i+=ba(n[o]):l===hh?i+=os.transform(n[o]):i+=n[o]}return i}}const _f=r=>typeof r=="number"?0:r;function Sf(r){const t=mh(r);return ph(r)(t.map(_f))}const ir={test:wf,parse:mh,createTransformer:ph,getAnimatableNone:Sf},Cf=new Set(["brightness","contrast","saturate","opacity"]);function Pf(r){const[t,s]=r.slice(0,-1).split("(");if(t==="drop-shadow")return r;const[a]=s.match(dl)||[];if(!a)return r;const n=s.replace(a,"");let i=Cf.has(t)?1:0;return a!==s&&(i*=100),t+"("+i+n+")"}const Ef=/\b([a-z-]*)\(.*?\)/gu,Ki={...ir,getAnimatableNone:r=>{const t=r.match(Ef);return t?t.map(Pf).join(" "):r}},Tf={...Yo,color:os,backgroundColor:os,outlineColor:os,fill:os,stroke:os,borderColor:os,borderTopColor:os,borderRightColor:os,borderBottomColor:os,borderLeftColor:os,filter:Ki,WebkitFilter:Ki},hl=r=>Tf[r];function gh(r,t){let s=hl(r);return s!==Ki&&(s=ir),s.getAnimatableNone?s.getAnimatableNone(t):void 0}const Af=new Set(["auto","none","0"]);function If(r,t,s){let a=0,n;for(;a<r.length&&!n;){const i=r[a];typeof i=="string"&&!Af.has(i)&&Ia(i).values.length&&(n=r[a]),a++}if(n&&s)for(const i of t)r[i]=gh(s,n)}const cc=r=>r===ea||r===Oe,dc=(r,t)=>parseFloat(r.split(", ")[t]),uc=(r,t)=>(s,{transform:a})=>{if(a==="none"||!a)return 0;const n=a.match(/^matrix3d\((.+)\)$/u);if(n)return dc(n[1],t);{const i=a.match(/^matrix\((.+)\)$/u);return i?dc(i[1],r):0}},Rf=new Set(["x","y","z"]),$f=Qr.filter(r=>!Rf.has(r));function Lf(r){const t=[];return $f.forEach(s=>{const a=r.getValue(s);a!==void 0&&(t.push([s,a.get()]),a.set(s.startsWith("scale")?1:0))}),t}const Yr={width:({x:r},{paddingLeft:t="0",paddingRight:s="0"})=>r.max-r.min-parseFloat(t)-parseFloat(s),height:({y:r},{paddingTop:t="0",paddingBottom:s="0"})=>r.max-r.min-parseFloat(t)-parseFloat(s),top:(r,{top:t})=>parseFloat(t),left:(r,{left:t})=>parseFloat(t),bottom:({y:r},{top:t})=>parseFloat(t)+(r.max-r.min),right:({x:r},{left:t})=>parseFloat(t)+(r.max-r.min),x:uc(4,13),y:uc(5,14)};Yr.translateX=Yr.x;Yr.translateY=Yr.y;const vr=new Set;let Yi=!1,Ji=!1;function fh(){if(Ji){const r=Array.from(vr).filter(a=>a.needsMeasurement),t=new Set(r.map(a=>a.element)),s=new Map;t.forEach(a=>{const n=Lf(a);n.length&&(s.set(a,n),a.render())}),r.forEach(a=>a.measureInitialState()),t.forEach(a=>{a.render();const n=s.get(a);n&&n.forEach(([i,o])=>{var l;(l=a.getValue(i))===null||l===void 0||l.set(o)})}),r.forEach(a=>a.measureEndState()),r.forEach(a=>{a.suspendedScrollY!==void 0&&window.scrollTo(0,a.suspendedScrollY)})}Ji=!1,Yi=!1,vr.forEach(r=>r.complete()),vr.clear()}function xh(){vr.forEach(r=>{r.readKeyframes(),r.needsMeasurement&&(Ji=!0)})}function Of(){xh(),fh()}class ml{constructor(t,s,a,n,i,o=!1){this.isComplete=!1,this.isAsync=!1,this.needsMeasurement=!1,this.isScheduled=!1,this.unresolvedKeyframes=[...t],this.onComplete=s,this.name=a,this.motionValue=n,this.element=i,this.isAsync=o}scheduleResolve(){this.isScheduled=!0,this.isAsync?(vr.add(this),Yi||(Yi=!0,Et.read(xh),Et.resolveKeyframes(fh))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:s,element:a,motionValue:n}=this;for(let i=0;i<t.length;i++)if(t[i]===null)if(i===0){const o=n==null?void 0:n.get(),l=t[t.length-1];if(o!==void 0)t[0]=o;else if(a&&s){const c=a.readValue(s,l);c!=null&&(t[0]=c)}t[0]===void 0&&(t[0]=l),n&&o===void 0&&n.set(t[0])}else t[i]=t[i-1]}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(){this.isComplete=!0,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe),vr.delete(this)}cancel(){this.isComplete||(this.isScheduled=!1,vr.delete(this))}resume(){this.isComplete||this.scheduleResolve()}}const yh=r=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(r),Mf=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Bf(r){const t=Mf.exec(r);if(!t)return[,];const[,s,a,n]=t;return[`--${s??a}`,n]}function bh(r,t,s=1){const[a,n]=Bf(r);if(!a)return;const i=window.getComputedStyle(t).getPropertyValue(a);if(i){const o=i.trim();return yh(o)?parseFloat(o):o}return Ko(n)?bh(n,t,s+1):n}const vh=r=>t=>t.test(r),Ff={test:r=>r==="auto",parse:r=>r},wh=[ea,Oe,Vs,sr,Cg,Sg,Ff],hc=r=>wh.find(vh(r));class jh extends ml{constructor(t,s,a,n,i){super(t,s,a,n,i,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:s,name:a}=this;if(!s||!s.current)return;super.readKeyframes();for(let c=0;c<t.length;c++){let u=t[c];if(typeof u=="string"&&(u=u.trim(),Ko(u))){const d=bh(u,s.current);d!==void 0&&(t[c]=d),c===t.length-1&&(this.finalKeyframe=u)}}if(this.resolveNoneKeyframes(),!Xu.has(a)||t.length!==2)return;const[n,i]=t,o=hc(n),l=hc(i);if(o!==l)if(cc(o)&&cc(l))for(let c=0;c<t.length;c++){const u=t[c];typeof u=="string"&&(t[c]=parseFloat(u))}else this.needsMeasurement=!0}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:s}=this,a=[];for(let n=0;n<t.length;n++)gf(t[n])&&a.push(n);a.length&&If(t,a,s)}measureInitialState(){const{element:t,unresolvedKeyframes:s,name:a}=this;if(!t||!t.current)return;a==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Yr[a](t.measureViewportBox(),window.getComputedStyle(t.current)),s[0]=this.measuredOrigin;const n=s[s.length-1];n!==void 0&&t.getValue(a,n).jump(n,!1)}measureEndState(){var t;const{element:s,name:a,unresolvedKeyframes:n}=this;if(!s||!s.current)return;const i=s.getValue(a);i&&i.jump(this.measuredOrigin,!1);const o=n.length-1,l=n[o];n[o]=Yr[a](s.measureViewportBox(),window.getComputedStyle(s.current)),l!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=l),!((t=this.removedTransforms)===null||t===void 0)&&t.length&&this.removedTransforms.forEach(([c,u])=>{s.getValue(c).set(u)}),this.resolveNoneKeyframes()}}const mc=(r,t)=>t==="zIndex"?!1:!!(typeof r=="number"||Array.isArray(r)||typeof r=="string"&&(ir.test(r)||r==="0")&&!r.startsWith("url("));function Df(r){const t=r[0];if(r.length===1)return!0;for(let s=0;s<r.length;s++)if(r[s]!==t)return!0}function Gf(r,t,s,a){const n=r[0];if(n===null)return!1;if(t==="display"||t==="visibility")return!0;const i=r[r.length-1],o=mc(n,t),l=mc(i,t);return!o||!l?!1:Df(r)||(s==="spring"||sl(s))&&a}const Uf=r=>r!==null;function Un(r,{repeat:t,repeatType:s="loop"},a){const n=r.filter(Uf),i=t&&s!=="loop"&&t%2===1?0:n.length-1;return!i||a===void 0?n[i]:a}const Vf=40;class Nh{constructor({autoplay:t=!0,delay:s=0,type:a="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:o="loop",...l}){this.isStopped=!1,this.hasAttemptedResolve=!1,this.createdAt=zs.now(),this.options={autoplay:t,delay:s,type:a,repeat:n,repeatDelay:i,repeatType:o,...l},this.updateFinishedPromise()}calcStartTime(){return this.resolvedAt?this.resolvedAt-this.createdAt>Vf?this.resolvedAt:this.createdAt:this.createdAt}get resolved(){return!this._resolved&&!this.hasAttemptedResolve&&Of(),this._resolved}onKeyframesResolved(t,s){this.resolvedAt=zs.now(),this.hasAttemptedResolve=!0;const{name:a,type:n,velocity:i,delay:o,onComplete:l,onUpdate:c,isGenerator:u}=this.options;if(!u&&!Gf(t,a,n,i))if(o)this.options.duration=0;else{c&&c(Un(t,this.options,s)),l&&l(),this.resolveFinishedPromise();return}const d=this.initPlayback(t,s);d!==!1&&(this._resolved={keyframes:t,finalKeyframe:s,...d},this.onPostResolved())}onPostResolved(){}then(t,s){return this.currentFinishedPromise.then(t,s)}flatten(){this.options.type="keyframes",this.options.ease="linear"}updateFinishedPromise(){this.currentFinishedPromise=new Promise(t=>{this.resolveFinishedPromise=t})}}const At=(r,t,s)=>r+(t-r)*s;function ci(r,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?r+(t-r)*6*s:s<1/2?t:s<2/3?r+(t-r)*(2/3-s)*6:r}function zf({hue:r,saturation:t,lightness:s,alpha:a}){r/=360,t/=100,s/=100;let n=0,i=0,o=0;if(!t)n=i=o=s;else{const l=s<.5?s*(1+t):s+t-s*t,c=2*s-l;n=ci(c,l,r+1/3),i=ci(c,l,r),o=ci(c,l,r-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:a}}function Sn(r,t){return s=>s>0?t:r}const di=(r,t,s)=>{const a=r*r,n=s*(t*t-a)+a;return n<0?0:Math.sqrt(n)},Wf=[Hi,xr,Dr],qf=r=>Wf.find(t=>t.test(r));function pc(r){const t=qf(r);if(!t)return!1;let s=t.parse(r);return t===Dr&&(s=zf(s)),s}const gc=(r,t)=>{const s=pc(r),a=pc(t);if(!s||!a)return Sn(r,t);const n={...s};return i=>(n.red=di(s.red,a.red,i),n.green=di(s.green,a.green,i),n.blue=di(s.blue,a.blue,i),n.alpha=At(s.alpha,a.alpha,i),xr.transform(n))},Hf=(r,t)=>s=>t(r(s)),Ga=(...r)=>r.reduce(Hf),Zi=new Set(["none","hidden"]);function Kf(r,t){return Zi.has(r)?s=>s<=0?r:t:s=>s>=1?t:r}function Yf(r,t){return s=>At(r,t,s)}function pl(r){return typeof r=="number"?Yf:typeof r=="string"?Ko(r)?Sn:os.test(r)?gc:Xf:Array.isArray(r)?kh:typeof r=="object"?os.test(r)?gc:Jf:Sn}function kh(r,t){const s=[...r],a=s.length,n=r.map((i,o)=>pl(i)(i,t[o]));return i=>{for(let o=0;o<a;o++)s[o]=n[o](i);return s}}function Jf(r,t){const s={...r,...t},a={};for(const n in s)r[n]!==void 0&&t[n]!==void 0&&(a[n]=pl(r[n])(r[n],t[n]));return n=>{for(const i in a)s[i]=a[i](n);return s}}function Zf(r,t){var s;const a=[],n={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){const o=t.types[i],l=r.indexes[o][n[o]],c=(s=r.values[l])!==null&&s!==void 0?s:0;a[i]=c,n[o]++}return a}const Xf=(r,t)=>{const s=ir.createTransformer(t),a=Ia(r),n=Ia(t);return a.indexes.var.length===n.indexes.var.length&&a.indexes.color.length===n.indexes.color.length&&a.indexes.number.length>=n.indexes.number.length?Zi.has(r)&&!n.values.length||Zi.has(t)&&!a.values.length?Kf(r,t):Ga(kh(Zf(a,n),n.values),s):Sn(r,t)};function _h(r,t,s){return typeof r=="number"&&typeof t=="number"&&typeof s=="number"?At(r,t,s):pl(r)(r,t)}const Qf=5;function Sh(r,t,s){const a=Math.max(t-Qf,0);return Qu(s-r(a),t-a)}const Lt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},ui=.001;function ex({duration:r=Lt.duration,bounce:t=Lt.bounce,velocity:s=Lt.velocity,mass:a=Lt.mass}){let n,i,o=1-t;o=Xs(Lt.minDamping,Lt.maxDamping,o),r=Xs(Lt.minDuration,Lt.maxDuration,Zs(r)),o<1?(n=u=>{const d=u*o,h=d*r,m=d-s,g=Xi(u,o),f=Math.exp(-h);return ui-m/g*f},i=u=>{const h=u*o*r,m=h*s+s,g=Math.pow(o,2)*Math.pow(u,2)*r,f=Math.exp(-h),v=Xi(Math.pow(u,2),o);return(-n(u)+ui>0?-1:1)*((m-g)*f)/v}):(n=u=>{const d=Math.exp(-u*r),h=(u-s)*r+1;return-ui+d*h},i=u=>{const d=Math.exp(-u*r),h=(s-u)*(r*r);return d*h});const l=5/r,c=sx(n,i,l);if(r=Js(r),isNaN(c))return{stiffness:Lt.stiffness,damping:Lt.damping,duration:r};{const u=Math.pow(c,2)*a;return{stiffness:u,damping:o*2*Math.sqrt(a*u),duration:r}}}const tx=12;function sx(r,t,s){let a=s;for(let n=1;n<tx;n++)a=a-r(a)/t(a);return a}function Xi(r,t){return r*Math.sqrt(1-t*t)}const rx=["duration","bounce"],ax=["stiffness","damping","mass"];function fc(r,t){return t.some(s=>r[s]!==void 0)}function nx(r){let t={velocity:Lt.velocity,stiffness:Lt.stiffness,damping:Lt.damping,mass:Lt.mass,isResolvedFromDuration:!1,...r};if(!fc(r,ax)&&fc(r,rx))if(r.visualDuration){const s=r.visualDuration,a=2*Math.PI/(s*1.2),n=a*a,i=2*Xs(.05,1,1-(r.bounce||0))*Math.sqrt(n);t={...t,mass:Lt.mass,stiffness:n,damping:i}}else{const s=ex(r);t={...t,...s,mass:Lt.mass},t.isResolvedFromDuration=!0}return t}function Ch(r=Lt.visualDuration,t=Lt.bounce){const s=typeof r!="object"?{visualDuration:r,keyframes:[0,1],bounce:t}:r;let{restSpeed:a,restDelta:n}=s;const i=s.keyframes[0],o=s.keyframes[s.keyframes.length-1],l={done:!1,value:i},{stiffness:c,damping:u,mass:d,duration:h,velocity:m,isResolvedFromDuration:g}=nx({...s,velocity:-Zs(s.velocity||0)}),f=m||0,v=u/(2*Math.sqrt(c*d)),x=o-i,j=Zs(Math.sqrt(c/d)),b=Math.abs(x)<5;a||(a=b?Lt.restSpeed.granular:Lt.restSpeed.default),n||(n=b?Lt.restDelta.granular:Lt.restDelta.default);let y;if(v<1){const T=Xi(j,v);y=I=>{const E=Math.exp(-v*j*I);return o-E*((f+v*j*x)/T*Math.sin(T*I)+x*Math.cos(T*I))}}else if(v===1)y=T=>o-Math.exp(-j*T)*(x+(f+j*x)*T);else{const T=j*Math.sqrt(v*v-1);y=I=>{const E=Math.exp(-v*j*I),O=Math.min(T*I,300);return o-E*((f+v*j*x)*Math.sinh(O)+T*x*Math.cosh(O))/T}}const S={calculatedDuration:g&&h||null,next:T=>{const I=y(T);if(g)l.done=T>=h;else{let E=0;v<1&&(E=T===0?Js(f):Sh(y,T,I));const O=Math.abs(E)<=a,V=Math.abs(o-I)<=n;l.done=O&&V}return l.value=l.done?o:I,l},toString:()=>{const T=Math.min(Wu(S),zi),I=qu(E=>S.next(T*E).value,T,30);return T+"ms "+I}};return S}function xc({keyframes:r,velocity:t=0,power:s=.8,timeConstant:a=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:o,min:l,max:c,restDelta:u=.5,restSpeed:d}){const h=r[0],m={done:!1,value:h},g=O=>l!==void 0&&O<l||c!==void 0&&O>c,f=O=>l===void 0?c:c===void 0||Math.abs(l-O)<Math.abs(c-O)?l:c;let v=s*t;const x=h+v,j=o===void 0?x:o(x);j!==x&&(v=j-h);const b=O=>-v*Math.exp(-O/a),y=O=>j+b(O),S=O=>{const V=b(O),J=y(O);m.done=Math.abs(V)<=u,m.value=m.done?j:J};let T,I;const E=O=>{g(m.value)&&(T=O,I=Ch({keyframes:[m.value,f(m.value)],velocity:Sh(y,O,m.value),damping:n,stiffness:i,restDelta:u,restSpeed:d}))};return E(0),{calculatedDuration:null,next:O=>{let V=!1;return!I&&T===void 0&&(V=!0,S(O),E(O)),T!==void 0&&O>=T?I.next(O-T):(!V&&S(O),m)}}}const ix=Da(.42,0,1,1),ox=Da(0,0,.58,1),Ph=Da(.42,0,.58,1),lx=r=>Array.isArray(r)&&typeof r[0]!="number",yc={linear:bs,easeIn:ix,easeInOut:Ph,easeOut:ox,circIn:cl,circInOut:lh,circOut:oh,backIn:ll,backInOut:nh,backOut:ah,anticipate:ih},bc=r=>{if(rl(r)){Ui(r.length===4);const[t,s,a,n]=r;return Da(t,s,a,n)}else if(typeof r=="string")return Ui(yc[r]!==void 0),yc[r];return r};function cx(r,t,s){const a=[],n=s||_h,i=r.length-1;for(let o=0;o<i;o++){let l=n(r[o],r[o+1]);if(t){const c=Array.isArray(t)?t[o]||bs:t;l=Ga(c,l)}a.push(l)}return a}function dx(r,t,{clamp:s=!0,ease:a,mixer:n}={}){const i=r.length;if(Ui(i===t.length),i===1)return()=>t[0];if(i===2&&t[0]===t[1])return()=>t[1];const o=r[0]===r[1];r[0]>r[i-1]&&(r=[...r].reverse(),t=[...t].reverse());const l=cx(t,a,n),c=l.length,u=d=>{if(o&&d<r[0])return t[0];let h=0;if(c>1)for(;h<r.length-2&&!(d<r[h+1]);h++);const m=Hr(r[h],r[h+1],d);return l[h](m)};return s?d=>u(Xs(r[0],r[i-1],d)):u}function ux(r,t){const s=r[r.length-1];for(let a=1;a<=t;a++){const n=Hr(0,t,a);r.push(At(s,1,n))}}function hx(r){const t=[0];return ux(t,r.length-1),t}function mx(r,t){return r.map(s=>s*t)}function px(r,t){return r.map(()=>t||Ph).splice(0,r.length-1)}function Cn({duration:r=300,keyframes:t,times:s,ease:a="easeInOut"}){const n=lx(a)?a.map(bc):bc(a),i={done:!1,value:t[0]},o=mx(s&&s.length===t.length?s:hx(t),r),l=dx(o,t,{ease:Array.isArray(n)?n:px(t,n)});return{calculatedDuration:r,next:c=>(i.value=l(c),i.done=c>=r,i)}}const gx=r=>{const t=({timestamp:s})=>r(s);return{start:()=>Et.update(t,!0),stop:()=>nr(t),now:()=>rs.isProcessing?rs.timestamp:zs.now()}},fx={decay:xc,inertia:xc,tween:Cn,keyframes:Cn,spring:Ch},xx=r=>r/100;class gl extends Nh{constructor(t){super(t),this.holdTime=null,this.cancelTime=null,this.currentTime=0,this.playbackSpeed=1,this.pendingPlayState="running",this.startTime=null,this.state="idle",this.stop=()=>{if(this.resolver.cancel(),this.isStopped=!0,this.state==="idle")return;this.teardown();const{onStop:c}=this.options;c&&c()};const{name:s,motionValue:a,element:n,keyframes:i}=this.options,o=(n==null?void 0:n.KeyframeResolver)||ml,l=(c,u)=>this.onKeyframesResolved(c,u);this.resolver=new o(i,l,s,a,n),this.resolver.scheduleResolve()}flatten(){super.flatten(),this._resolved&&Object.assign(this._resolved,this.initPlayback(this._resolved.keyframes))}initPlayback(t){const{type:s="keyframes",repeat:a=0,repeatDelay:n=0,repeatType:i,velocity:o=0}=this.options,l=sl(s)?s:fx[s]||Cn;let c,u;l!==Cn&&typeof t[0]!="number"&&(c=Ga(xx,_h(t[0],t[1])),t=[0,100]);const d=l({...this.options,keyframes:t});i==="mirror"&&(u=l({...this.options,keyframes:[...t].reverse(),velocity:-o})),d.calculatedDuration===null&&(d.calculatedDuration=Wu(d));const{calculatedDuration:h}=d,m=h+n,g=m*(a+1)-n;return{generator:d,mirroredGenerator:u,mapPercentToKeyframes:c,calculatedDuration:h,resolvedDuration:m,totalDuration:g}}onPostResolved(){const{autoplay:t=!0}=this.options;this.play(),this.pendingPlayState==="paused"||!t?this.pause():this.state=this.pendingPlayState}tick(t,s=!1){const{resolved:a}=this;if(!a){const{keyframes:O}=this.options;return{done:!0,value:O[O.length-1]}}const{finalKeyframe:n,generator:i,mirroredGenerator:o,mapPercentToKeyframes:l,keyframes:c,calculatedDuration:u,totalDuration:d,resolvedDuration:h}=a;if(this.startTime===null)return i.next(0);const{delay:m,repeat:g,repeatType:f,repeatDelay:v,onUpdate:x}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-d/this.speed,this.startTime)),s?this.currentTime=t:this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=Math.round(t-this.startTime)*this.speed;const j=this.currentTime-m*(this.speed>=0?1:-1),b=this.speed>=0?j<0:j>d;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=d);let y=this.currentTime,S=i;if(g){const O=Math.min(this.currentTime,d)/h;let V=Math.floor(O),J=O%1;!J&&O>=1&&(J=1),J===1&&V--,V=Math.min(V,g+1),!!(V%2)&&(f==="reverse"?(J=1-J,v&&(J-=v/h)):f==="mirror"&&(S=o)),y=Xs(0,1,J)*h}const T=b?{done:!1,value:c[0]}:S.next(y);l&&(T.value=l(T.value));let{done:I}=T;!b&&u!==null&&(I=this.speed>=0?this.currentTime>=d:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&I);return E&&n!==void 0&&(T.value=Un(c,this.options,n)),x&&x(T.value),E&&this.finish(),T}get duration(){const{resolved:t}=this;return t?Zs(t.calculatedDuration):0}get time(){return Zs(this.currentTime)}set time(t){t=Js(t),this.currentTime=t,this.holdTime!==null||this.speed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.speed)}get speed(){return this.playbackSpeed}set speed(t){const s=this.playbackSpeed!==t;this.playbackSpeed=t,s&&(this.time=Zs(this.currentTime))}play(){if(this.resolver.isScheduled||this.resolver.resume(),!this._resolved){this.pendingPlayState="running";return}if(this.isStopped)return;const{driver:t=gx,onPlay:s,startTime:a}=this.options;this.driver||(this.driver=t(i=>this.tick(i))),s&&s();const n=this.driver.now();this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime?this.state==="finished"&&(this.startTime=n):this.startTime=a??this.calcStartTime(),this.state==="finished"&&this.updateFinishedPromise(),this.cancelTime=this.startTime,this.holdTime=null,this.state="running",this.driver.start()}pause(){var t;if(!this._resolved){this.pendingPlayState="paused";return}this.state="paused",this.holdTime=(t=this.currentTime)!==null&&t!==void 0?t:0}complete(){this.state!=="running"&&this.play(),this.pendingPlayState=this.state="finished",this.holdTime=null}finish(){this.teardown(),this.state="finished";const{onComplete:t}=this.options;t&&t()}cancel(){this.cancelTime!==null&&this.tick(this.cancelTime),this.teardown(),this.updateFinishedPromise()}teardown(){this.state="idle",this.stopDriver(),this.resolveFinishedPromise(),this.updateFinishedPromise(),this.startTime=this.cancelTime=null,this.resolver.cancel()}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}}const yx=new Set(["opacity","clipPath","filter","transform"]);function bx(r,t,s,{delay:a=0,duration:n=300,repeat:i=0,repeatType:o="loop",ease:l="easeInOut",times:c}={}){const u={[t]:s};c&&(u.offset=c);const d=Ku(l,n);return Array.isArray(d)&&(u.easing=d),r.animate(u,{delay:a,duration:n,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:i+1,direction:o==="reverse"?"alternate":"normal"})}const vx=Go(()=>Object.hasOwnProperty.call(Element.prototype,"animate")),Pn=10,wx=2e4;function jx(r){return sl(r.type)||r.type==="spring"||!Hu(r.ease)}function Nx(r,t){const s=new gl({...t,keyframes:r,repeat:0,delay:0,isGenerator:!0});let a={done:!1,value:r[0]};const n=[];let i=0;for(;!a.done&&i<wx;)a=s.sample(i),n.push(a.value),i+=Pn;return{times:void 0,keyframes:n,duration:i-Pn,ease:"linear"}}const Eh={anticipate:ih,backInOut:nh,circInOut:lh};function kx(r){return r in Eh}class vc extends Nh{constructor(t){super(t);const{name:s,motionValue:a,element:n,keyframes:i}=this.options;this.resolver=new jh(i,(o,l)=>this.onKeyframesResolved(o,l),s,a,n),this.resolver.scheduleResolve()}initPlayback(t,s){let{duration:a=300,times:n,ease:i,type:o,motionValue:l,name:c,startTime:u}=this.options;if(!l.owner||!l.owner.current)return!1;if(typeof i=="string"&&_n()&&kx(i)&&(i=Eh[i]),jx(this.options)){const{onComplete:h,onUpdate:m,motionValue:g,element:f,...v}=this.options,x=Nx(t,v);t=x.keyframes,t.length===1&&(t[1]=t[0]),a=x.duration,n=x.times,i=x.ease,o="keyframes"}const d=bx(l.owner.current,c,t,{...this.options,duration:a,times:n,ease:i});return d.startTime=u??this.calcStartTime(),this.pendingTimeline?(rc(d,this.pendingTimeline),this.pendingTimeline=void 0):d.onfinish=()=>{const{onComplete:h}=this.options;l.set(Un(t,this.options,s)),h&&h(),this.cancel(),this.resolveFinishedPromise()},{animation:d,duration:a,times:n,type:o,ease:i,keyframes:t}}get duration(){const{resolved:t}=this;if(!t)return 0;const{duration:s}=t;return Zs(s)}get time(){const{resolved:t}=this;if(!t)return 0;const{animation:s}=t;return Zs(s.currentTime||0)}set time(t){const{resolved:s}=this;if(!s)return;const{animation:a}=s;a.currentTime=Js(t)}get speed(){const{resolved:t}=this;if(!t)return 1;const{animation:s}=t;return s.playbackRate}set speed(t){const{resolved:s}=this;if(!s)return;const{animation:a}=s;a.playbackRate=t}get state(){const{resolved:t}=this;if(!t)return"idle";const{animation:s}=t;return s.playState}get startTime(){const{resolved:t}=this;if(!t)return null;const{animation:s}=t;return s.startTime}attachTimeline(t){if(!this._resolved)this.pendingTimeline=t;else{const{resolved:s}=this;if(!s)return bs;const{animation:a}=s;rc(a,t)}return bs}play(){if(this.isStopped)return;const{resolved:t}=this;if(!t)return;const{animation:s}=t;s.playState==="finished"&&this.updateFinishedPromise(),s.play()}pause(){const{resolved:t}=this;if(!t)return;const{animation:s}=t;s.pause()}stop(){if(this.resolver.cancel(),this.isStopped=!0,this.state==="idle")return;this.resolveFinishedPromise(),this.updateFinishedPromise();const{resolved:t}=this;if(!t)return;const{animation:s,keyframes:a,duration:n,type:i,ease:o,times:l}=t;if(s.playState==="idle"||s.playState==="finished")return;if(this.time){const{motionValue:u,onUpdate:d,onComplete:h,element:m,...g}=this.options,f=new gl({...g,keyframes:a,duration:n,type:i,ease:o,times:l,isGenerator:!0}),v=Js(this.time);u.setWithVelocity(f.sample(v-Pn).value,f.sample(v).value,Pn)}const{onStop:c}=this.options;c&&c(),this.cancel()}complete(){const{resolved:t}=this;t&&t.animation.finish()}cancel(){const{resolved:t}=this;t&&t.animation.cancel()}static supports(t){const{motionValue:s,name:a,repeatDelay:n,repeatType:i,damping:o,type:l}=t;if(!s||!s.owner||!(s.owner.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=s.owner.getProps();return vx()&&a&&yx.has(a)&&!c&&!u&&!n&&i!=="mirror"&&o!==0&&l!=="inertia"}}const _x={type:"spring",stiffness:500,damping:25,restSpeed:10},Sx=r=>({type:"spring",stiffness:550,damping:r===0?2*Math.sqrt(550):30,restSpeed:10}),Cx={type:"keyframes",duration:.8},Px={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Ex=(r,{keyframes:t})=>t.length>2?Cx:wr.has(r)?r.startsWith("scale")?Sx(t[1]):_x:Px;function Tx({when:r,delay:t,delayChildren:s,staggerChildren:a,staggerDirection:n,repeat:i,repeatType:o,repeatDelay:l,from:c,elapsed:u,...d}){return!!Object.keys(d).length}const fl=(r,t,s,a={},n,i)=>o=>{const l=tl(a,r)||{},c=l.delay||a.delay||0;let{elapsed:u=0}=a;u=u-Js(c);let d={keyframes:Array.isArray(s)?s:[null,s],ease:"easeOut",velocity:t.getVelocity(),...l,delay:-u,onUpdate:m=>{t.set(m),l.onUpdate&&l.onUpdate(m)},onComplete:()=>{o(),l.onComplete&&l.onComplete()},name:r,motionValue:t,element:i?void 0:n};Tx(l)||(d={...d,...Ex(r,d)}),d.duration&&(d.duration=Js(d.duration)),d.repeatDelay&&(d.repeatDelay=Js(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let h=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(d.duration=0,d.delay===0&&(h=!0)),h&&!i&&t.get()!==void 0){const m=Un(d.keyframes,l);if(m!==void 0)return Et.update(()=>{d.onUpdate(m),d.onComplete()}),new Yg([])}return!i&&vc.supports(d)?new vc(d):new gl(d)};function Ax({protectedKeys:r,needsAnimating:t},s){const a=r.hasOwnProperty(s)&&t[s]!==!0;return t[s]=!1,a}function Th(r,t,{delay:s=0,transitionOverride:a,type:n}={}){var i;let{transition:o=r.getDefaultTransition(),transitionEnd:l,...c}=t;a&&(o=a);const u=[],d=n&&r.animationState&&r.animationState.getState()[n];for(const h in c){const m=r.getValue(h,(i=r.latestValues[h])!==null&&i!==void 0?i:null),g=c[h];if(g===void 0||d&&Ax(d,h))continue;const f={delay:s,...tl(o||{},h)};let v=!1;if(window.MotionHandoffAnimation){const j=eh(r);if(j){const b=window.MotionHandoffAnimation(j,h,Et);b!==null&&(f.startTime=b,v=!0)}}qi(r,h),m.start(fl(h,m,g,r.shouldReduceMotion&&Xu.has(h)?{type:!1}:f,r,v));const x=m.animation;x&&u.push(x)}return l&&Promise.all(u).then(()=>{Et.update(()=>{l&&df(r,l)})}),u}function Qi(r,t,s={}){var a;const n=Gn(r,t,s.type==="exit"?(a=r.presenceContext)===null||a===void 0?void 0:a.custom:void 0);let{transition:i=r.getDefaultTransition()||{}}=n||{};s.transitionOverride&&(i=s.transitionOverride);const o=n?()=>Promise.all(Th(r,n,s)):()=>Promise.resolve(),l=r.variantChildren&&r.variantChildren.size?(u=0)=>{const{delayChildren:d=0,staggerChildren:h,staggerDirection:m}=i;return Ix(r,t,d+u,h,m,s)}:()=>Promise.resolve(),{when:c}=i;if(c){const[u,d]=c==="beforeChildren"?[o,l]:[l,o];return u().then(()=>d())}else return Promise.all([o(),l(s.delay)])}function Ix(r,t,s=0,a=0,n=1,i){const o=[],l=(r.variantChildren.size-1)*a,c=n===1?(u=0)=>u*a:(u=0)=>l-u*a;return Array.from(r.variantChildren).sort(Rx).forEach((u,d)=>{u.notify("AnimationStart",t),o.push(Qi(u,t,{...i,delay:s+c(d)}).then(()=>u.notify("AnimationComplete",t)))}),Promise.all(o)}function Rx(r,t){return r.sortNodePosition(t)}function $x(r,t,s={}){r.notify("AnimationStart",t);let a;if(Array.isArray(t)){const n=t.map(i=>Qi(r,i,s));a=Promise.all(n)}else if(typeof t=="string")a=Qi(r,t,s);else{const n=typeof t=="function"?Gn(r,t,s.custom):t;a=Promise.all(Th(r,n,s))}return a.then(()=>{r.notify("AnimationComplete",t)})}const Lx=Vo.length;function Ah(r){if(!r)return;if(!r.isControllingVariants){const s=r.parent?Ah(r.parent)||{}:{};return r.props.initial!==void 0&&(s.initial=r.props.initial),s}const t={};for(let s=0;s<Lx;s++){const a=Vo[s],n=r.props[a];(Ea(n)||n===!1)&&(t[a]=n)}return t}const Ox=[...Uo].reverse(),Mx=Uo.length;function Bx(r){return t=>Promise.all(t.map(({animation:s,options:a})=>$x(r,s,a)))}function Fx(r){let t=Bx(r),s=wc(),a=!0;const n=c=>(u,d)=>{var h;const m=Gn(r,d,c==="exit"?(h=r.presenceContext)===null||h===void 0?void 0:h.custom:void 0);if(m){const{transition:g,transitionEnd:f,...v}=m;u={...u,...v,...f}}return u};function i(c){t=c(r)}function o(c){const{props:u}=r,d=Ah(r.parent)||{},h=[],m=new Set;let g={},f=1/0;for(let x=0;x<Mx;x++){const j=Ox[x],b=s[j],y=u[j]!==void 0?u[j]:d[j],S=Ea(y),T=j===c?b.isActive:null;T===!1&&(f=x);let I=y===d[j]&&y!==u[j]&&S;if(I&&a&&r.manuallyAnimateOnMount&&(I=!1),b.protectedKeys={...g},!b.isActive&&T===null||!y&&!b.prevProp||Fn(y)||typeof y=="boolean")continue;const E=Dx(b.prevProp,y);let O=E||j===c&&b.isActive&&!I&&S||x>f&&S,V=!1;const J=Array.isArray(y)?y:[y];let U=J.reduce(n(j),{});T===!1&&(U={});const{prevResolvedValues:Ge={}}=b,Te={...Ge,...U},Me=ue=>{O=!0,m.has(ue)&&(V=!0,m.delete(ue)),b.needsAnimating[ue]=!0;const re=r.getValue(ue);re&&(re.liveStyle=!1)};for(const ue in Te){const re=U[ue],Ne=Ge[ue];if(g.hasOwnProperty(ue))continue;let fe=!1;Vi(re)&&Vi(Ne)?fe=!zu(re,Ne):fe=re!==Ne,fe?re!=null?Me(ue):m.add(ue):re!==void 0&&m.has(ue)?Me(ue):b.protectedKeys[ue]=!0}b.prevProp=y,b.prevResolvedValues=U,b.isActive&&(g={...g,...U}),a&&r.blockInitialAnimation&&(O=!1),O&&(!(I&&E)||V)&&h.push(...J.map(ue=>({animation:ue,options:{type:j}})))}if(m.size){const x={};m.forEach(j=>{const b=r.getBaseTarget(j),y=r.getValue(j);y&&(y.liveStyle=!0),x[j]=b??null}),h.push({animation:x})}let v=!!h.length;return a&&(u.initial===!1||u.initial===u.animate)&&!r.manuallyAnimateOnMount&&(v=!1),a=!1,v?t(h):Promise.resolve()}function l(c,u){var d;if(s[c].isActive===u)return Promise.resolve();(d=r.variantChildren)===null||d===void 0||d.forEach(m=>{var g;return(g=m.animationState)===null||g===void 0?void 0:g.setActive(c,u)}),s[c].isActive=u;const h=o(c);for(const m in s)s[m].protectedKeys={};return h}return{animateChanges:o,setActive:l,setAnimateFunction:i,getState:()=>s,reset:()=>{s=wc(),a=!0}}}function Dx(r,t){return typeof t=="string"?t!==r:Array.isArray(t)?!zu(t,r):!1}function cr(r=!1){return{isActive:r,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function wc(){return{animate:cr(!0),whileInView:cr(),whileHover:cr(),whileTap:cr(),whileDrag:cr(),whileFocus:cr(),exit:cr()}}class or{constructor(t){this.isMounted=!1,this.node=t}update(){}}class Gx extends or{constructor(t){super(t),t.animationState||(t.animationState=Fx(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Fn(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:s}=this.node.prevProps||{};t!==s&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)===null||t===void 0||t.call(this)}}let Ux=0;class Vx extends or{constructor(){super(...arguments),this.id=Ux++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:s}=this.node.presenceContext,{isPresent:a}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===a)return;const n=this.node.animationState.setActive("exit",!t);s&&!t&&n.then(()=>s(this.id))}mount(){const{register:t}=this.node.presenceContext||{};t&&(this.unmount=t(this.id))}unmount(){}}const zx={animation:{Feature:Gx},exit:{Feature:Vx}};function Ra(r,t,s,a={passive:!0}){return r.addEventListener(t,s,a),()=>r.removeEventListener(t,s)}function Ua(r){return{point:{x:r.pageX,y:r.pageY}}}const Wx=r=>t=>al(t)&&r(t,Ua(t));function va(r,t,s,a){return Ra(r,t,Wx(s),a)}const jc=(r,t)=>Math.abs(r-t);function qx(r,t){const s=jc(r.x,t.x),a=jc(r.y,t.y);return Math.sqrt(s**2+a**2)}class Ih{constructor(t,s,{transformPagePoint:a,contextWindow:n,dragSnapToOrigin:i=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=mi(this.lastMoveEventInfo,this.history),m=this.startEvent!==null,g=qx(h.offset,{x:0,y:0})>=3;if(!m&&!g)return;const{point:f}=h,{timestamp:v}=rs;this.history.push({...f,timestamp:v});const{onStart:x,onMove:j}=this.handlers;m||(x&&x(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),j&&j(this.lastMoveEvent,h)},this.handlePointerMove=(h,m)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=hi(m,this.transformPagePoint),Et.update(this.updatePoint,!0)},this.handlePointerUp=(h,m)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=mi(h.type==="pointercancel"?this.lastMoveEventInfo:hi(m,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,x),f&&f(h,x)},!al(t))return;this.dragSnapToOrigin=i,this.handlers=s,this.transformPagePoint=a,this.contextWindow=n||window;const o=Ua(t),l=hi(o,this.transformPagePoint),{point:c}=l,{timestamp:u}=rs;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=s;d&&d(t,mi(l,this.history)),this.removeListeners=Ga(va(this.contextWindow,"pointermove",this.handlePointerMove),va(this.contextWindow,"pointerup",this.handlePointerUp),va(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),nr(this.updatePoint)}}function hi(r,t){return t?{point:t(r.point)}:r}function Nc(r,t){return{x:r.x-t.x,y:r.y-t.y}}function mi({point:r},t){return{point:r,delta:Nc(r,Rh(t)),offset:Nc(r,Hx(t)),velocity:Kx(t,.1)}}function Hx(r){return r[0]}function Rh(r){return r[r.length-1]}function Kx(r,t){if(r.length<2)return{x:0,y:0};let s=r.length-1,a=null;const n=Rh(r);for(;s>=0&&(a=r[s],!(n.timestamp-a.timestamp>Js(t)));)s--;if(!a)return{x:0,y:0};const i=Zs(n.timestamp-a.timestamp);if(i===0)return{x:0,y:0};const o={x:(n.x-a.x)/i,y:(n.y-a.y)/i};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}const $h=1e-4,Yx=1-$h,Jx=1+$h,Lh=.01,Zx=0-Lh,Xx=0+Lh;function vs(r){return r.max-r.min}function Qx(r,t,s){return Math.abs(r-t)<=s}function kc(r,t,s,a=.5){r.origin=a,r.originPoint=At(t.min,t.max,r.origin),r.scale=vs(s)/vs(t),r.translate=At(s.min,s.max,r.origin)-r.originPoint,(r.scale>=Yx&&r.scale<=Jx||isNaN(r.scale))&&(r.scale=1),(r.translate>=Zx&&r.translate<=Xx||isNaN(r.translate))&&(r.translate=0)}function wa(r,t,s,a){kc(r.x,t.x,s.x,a?a.originX:void 0),kc(r.y,t.y,s.y,a?a.originY:void 0)}function _c(r,t,s){r.min=s.min+t.min,r.max=r.min+vs(t)}function e0(r,t,s){_c(r.x,t.x,s.x),_c(r.y,t.y,s.y)}function Sc(r,t,s){r.min=t.min-s.min,r.max=r.min+vs(t)}function ja(r,t,s){Sc(r.x,t.x,s.x),Sc(r.y,t.y,s.y)}function t0(r,{min:t,max:s},a){return t!==void 0&&r<t?r=a?At(t,r,a.min):Math.max(r,t):s!==void 0&&r>s&&(r=a?At(s,r,a.max):Math.min(r,s)),r}function Cc(r,t,s){return{min:t!==void 0?r.min+t:void 0,max:s!==void 0?r.max+s-(r.max-r.min):void 0}}function s0(r,{top:t,left:s,bottom:a,right:n}){return{x:Cc(r.x,s,n),y:Cc(r.y,t,a)}}function Pc(r,t){let s=t.min-r.min,a=t.max-r.max;return t.max-t.min<r.max-r.min&&([s,a]=[a,s]),{min:s,max:a}}function r0(r,t){return{x:Pc(r.x,t.x),y:Pc(r.y,t.y)}}function a0(r,t){let s=.5;const a=vs(r),n=vs(t);return n>a?s=Hr(t.min,t.max-a,r.min):a>n&&(s=Hr(r.min,r.max-n,t.min)),Xs(0,1,s)}function n0(r,t){const s={};return t.min!==void 0&&(s.min=t.min-r.min),t.max!==void 0&&(s.max=t.max-r.min),s}const eo=.35;function i0(r=eo){return r===!1?r=0:r===!0&&(r=eo),{x:Ec(r,"left","right"),y:Ec(r,"top","bottom")}}function Ec(r,t,s){return{min:Tc(r,t),max:Tc(r,s)}}function Tc(r,t){return typeof r=="number"?r:r[t]||0}const Ac=()=>({translate:0,scale:1,origin:0,originPoint:0}),Gr=()=>({x:Ac(),y:Ac()}),Ic=()=>({min:0,max:0}),Dt=()=>({x:Ic(),y:Ic()});function js(r){return[r("x"),r("y")]}function Oh({top:r,left:t,right:s,bottom:a}){return{x:{min:t,max:s},y:{min:r,max:a}}}function o0({x:r,y:t}){return{top:t.min,right:r.max,bottom:t.max,left:r.min}}function l0(r,t){if(!t)return r;const s=t({x:r.left,y:r.top}),a=t({x:r.right,y:r.bottom});return{top:s.y,left:s.x,bottom:a.y,right:a.x}}function pi(r){return r===void 0||r===1}function to({scale:r,scaleX:t,scaleY:s}){return!pi(r)||!pi(t)||!pi(s)}function hr(r){return to(r)||Mh(r)||r.z||r.rotate||r.rotateX||r.rotateY||r.skewX||r.skewY}function Mh(r){return Rc(r.x)||Rc(r.y)}function Rc(r){return r&&r!=="0%"}function En(r,t,s){const a=r-s,n=t*a;return s+n}function $c(r,t,s,a,n){return n!==void 0&&(r=En(r,n,a)),En(r,s,a)+t}function so(r,t=0,s=1,a,n){r.min=$c(r.min,t,s,a,n),r.max=$c(r.max,t,s,a,n)}function Bh(r,{x:t,y:s}){so(r.x,t.translate,t.scale,t.originPoint),so(r.y,s.translate,s.scale,s.originPoint)}const Lc=.999999999999,Oc=1.0000000000001;function c0(r,t,s,a=!1){const n=s.length;if(!n)return;t.x=t.y=1;let i,o;for(let l=0;l<n;l++){i=s[l],o=i.projectionDelta;const{visualElement:c}=i.options;c&&c.props.style&&c.props.style.display==="contents"||(a&&i.options.layoutScroll&&i.scroll&&i!==i.root&&Vr(r,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Bh(r,o)),a&&hr(i.latestValues)&&Vr(r,i.latestValues))}t.x<Oc&&t.x>Lc&&(t.x=1),t.y<Oc&&t.y>Lc&&(t.y=1)}function Ur(r,t){r.min=r.min+t,r.max=r.max+t}function Mc(r,t,s,a,n=.5){const i=At(r.min,r.max,n);so(r,t,s,i,a)}function Vr(r,t){Mc(r.x,t.x,t.scaleX,t.scale,t.originX),Mc(r.y,t.y,t.scaleY,t.scale,t.originY)}function Fh(r,t){return Oh(l0(r.getBoundingClientRect(),t))}function d0(r,t,s){const a=Fh(r,s),{scroll:n}=t;return n&&(Ur(a.x,n.offset.x),Ur(a.y,n.offset.y)),a}const Dh=({current:r})=>r?r.ownerDocument.defaultView:null,u0=new WeakMap;class h0{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Dt(),this.visualElement=t}start(t,{snapToCursor:s=!1}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const n=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),s&&this.snapToCursor(Ua(d).point)},i=(d,h)=>{const{drag:m,dragPropagation:g,onDragStart:f}=this.getProps();if(m&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=af(m),!this.openDragLock))return;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),js(x=>{let j=this.getAxisMotionValue(x).get()||0;if(Vs.test(j)){const{projection:b}=this.visualElement;if(b&&b.layout){const y=b.layout.layoutBox[x];y&&(j=vs(y)*(parseFloat(j)/100))}}this.originPoint[x]=j}),f&&Et.postRender(()=>f(d,h)),qi(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},o=(d,h)=>{const{dragPropagation:m,dragDirectionLock:g,onDirectionLock:f,onDrag:v}=this.getProps();if(!m&&!this.openDragLock)return;const{offset:x}=h;if(g&&this.currentDirection===null){this.currentDirection=m0(x),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",h.point,x),this.updateAxis("y",h.point,x),this.visualElement.render(),v&&v(d,h)},l=(d,h)=>this.stop(d,h),c=()=>js(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)===null||h===void 0?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Ih(t,{onSessionStart:n,onStart:i,onMove:o,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,contextWindow:Dh(this.visualElement)})}stop(t,s){const a=this.isDragging;if(this.cancel(),!a)return;const{velocity:n}=s;this.startAnimation(n);const{onDragEnd:i}=this.getProps();i&&Et.postRender(()=>i(t,s))}cancel(){this.isDragging=!1;const{projection:t,animationState:s}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:a}=this.getProps();!a&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),s&&s.setActive("whileDrag",!1)}updateAxis(t,s,a){const{drag:n}=this.getProps();if(!a||!sn(t,n,this.currentDirection))return;const i=this.getAxisMotionValue(t);let o=this.originPoint[t]+a[t];this.constraints&&this.constraints[t]&&(o=t0(o,this.constraints[t],this.elastic[t])),i.set(o)}resolveConstraints(){var t;const{dragConstraints:s,dragElastic:a}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(t=this.visualElement.projection)===null||t===void 0?void 0:t.layout,i=this.constraints;s&&Fr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&n?this.constraints=s0(n.layoutBox,s):this.constraints=!1,this.elastic=i0(a),i!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&js(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=n0(n.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:s}=this.getProps();if(!t||!Fr(t))return!1;const a=t.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=d0(a,n.root,this.visualElement.getTransformPagePoint());let o=r0(n.layout.layoutBox,i);if(s){const l=s(o0(o));this.hasMutatedConstraints=!!l,l&&(o=Oh(l))}return o}startAnimation(t){const{drag:s,dragMomentum:a,dragElastic:n,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},u=js(d=>{if(!sn(d,s,this.currentDirection))return;let h=c&&c[d]||{};o&&(h={min:0,max:0});const m=n?200:1e6,g=n?40:1e7,f={type:"inertia",velocity:a?t[d]:0,bounceStiffness:m,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(d,f)});return Promise.all(u).then(l)}startAxisValueAnimation(t,s){const a=this.getAxisMotionValue(t);return qi(this.visualElement,t),a.start(fl(t,a,0,s,this.visualElement,!1))}stopAnimation(){js(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){js(t=>{var s;return(s=this.getAxisMotionValue(t).animation)===null||s===void 0?void 0:s.pause()})}getAnimationState(t){var s;return(s=this.getAxisMotionValue(t).animation)===null||s===void 0?void 0:s.state}getAxisMotionValue(t){const s=`_drag${t.toUpperCase()}`,a=this.visualElement.getProps(),n=a[s];return n||this.visualElement.getValue(t,(a.initial?a.initial[t]:void 0)||0)}snapToCursor(t){js(s=>{const{drag:a}=this.getProps();if(!sn(s,a,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(s);if(n&&n.layout){const{min:o,max:l}=n.layout.layoutBox[s];i.set(t[s]-At(o,l,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:s}=this.getProps(),{projection:a}=this.visualElement;if(!Fr(s)||!a||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};js(o=>{const l=this.getAxisMotionValue(o);if(l&&this.constraints!==!1){const c=l.get();n[o]=a0({min:c,max:c},this.constraints[o])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",a.root&&a.root.updateScroll(),a.updateLayout(),this.resolveConstraints(),js(o=>{if(!sn(o,t,null))return;const l=this.getAxisMotionValue(o),{min:c,max:u}=this.constraints[o];l.set(At(c,u,n[o]))})}addListeners(){if(!this.visualElement.current)return;u0.set(this.visualElement,this);const t=this.visualElement.current,s=va(t,"pointerdown",c=>{const{drag:u,dragListener:d=!0}=this.getProps();u&&d&&this.start(c)}),a=()=>{const{dragConstraints:c}=this.getProps();Fr(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",a);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Et.read(a);const o=Ra(window,"resize",()=>this.scalePositionWithinConstraints()),l=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(js(d=>{const h=this.getAxisMotionValue(d);h&&(this.originPoint[d]+=c[d].translate,h.set(h.get()+c[d].translate))}),this.visualElement.render())});return()=>{o(),s(),i(),l&&l()}}getProps(){const t=this.visualElement.getProps(),{drag:s=!1,dragDirectionLock:a=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:o=eo,dragMomentum:l=!0}=t;return{...t,drag:s,dragDirectionLock:a,dragPropagation:n,dragConstraints:i,dragElastic:o,dragMomentum:l}}}function sn(r,t,s){return(t===!0||t===r)&&(s===null||s===r)}function m0(r,t=10){let s=null;return Math.abs(r.y)>t?s="y":Math.abs(r.x)>t&&(s="x"),s}class p0 extends or{constructor(t){super(t),this.removeGroupControls=bs,this.removeListeners=bs,this.controls=new h0(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||bs}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bc=r=>(t,s)=>{r&&Et.postRender(()=>r(t,s))};class g0 extends or{constructor(){super(...arguments),this.removePointerDownListener=bs}onPointerDown(t){this.session=new Ih(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Dh(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:s,onPan:a,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bc(t),onStart:Bc(s),onMove:a,onEnd:(i,o)=>{delete this.session,n&&Et.postRender(()=>n(i,o))}}}mount(){this.removePointerDownListener=va(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const yn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Fc(r,t){return t.max===t.min?0:r/(t.max-t.min)*100}const la={correct:(r,t)=>{if(!t.target)return r;if(typeof r=="string")if(Oe.test(r))r=parseFloat(r);else return r;const s=Fc(r,t.target.x),a=Fc(r,t.target.y);return`${s}% ${a}%`}},f0={correct:(r,{treeScale:t,projectionDelta:s})=>{const a=r,n=ir.parse(r);if(n.length>5)return a;const i=ir.createTransformer(r),o=typeof n[0]!="number"?1:0,l=s.x.scale*t.x,c=s.y.scale*t.y;n[0+o]/=l,n[1+o]/=c;const u=At(l,c,.5);return typeof n[2+o]=="number"&&(n[2+o]/=u),typeof n[3+o]=="number"&&(n[3+o]/=u),i(n)}};class x0 extends p.Component{componentDidMount(){const{visualElement:t,layoutGroup:s,switchLayoutGroup:a,layoutId:n}=this.props,{projection:i}=t;Mg(y0),i&&(s.group&&s.group.add(i),a&&a.register&&n&&a.register(i),i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),yn.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:s,visualElement:a,drag:n,isPresent:i}=this.props,o=a.projection;return o&&(o.isPresent=i,n||t.layoutDependency!==s||s===void 0?o.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?o.promote():o.relegate()||Et.postRender(()=>{const l=o.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Wo.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:s,switchLayoutGroup:a}=this.props,{projection:n}=t;n&&(n.scheduleCheckAfterUnmount(),s&&s.group&&s.group.remove(n),a&&a.deregister&&a.deregister(n))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Gh(r){const[t,s]=ku(),a=p.useContext(Mo);return e.jsx(x0,{...r,layoutGroup:a,switchLayoutGroup:p.useContext(Au),isPresent:t,safeToRemove:s})}const y0={borderRadius:{...la,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:la,borderTopRightRadius:la,borderBottomLeftRadius:la,borderBottomRightRadius:la,boxShadow:f0};function b0(r,t,s){const a=ls(r)?r:Aa(r);return a.start(fl("",a,t,s)),a.animation}function v0(r){return r instanceof SVGElement&&r.tagName!=="svg"}const w0=(r,t)=>r.depth-t.depth;class j0{constructor(){this.children=[],this.isDirty=!1}add(t){nl(this.children,t),this.isDirty=!0}remove(t){il(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(w0),this.isDirty=!1,this.children.forEach(t)}}function N0(r,t){const s=zs.now(),a=({timestamp:n})=>{const i=n-s;i>=t&&(nr(a),r(i-t))};return Et.read(a,!0),()=>nr(a)}const Uh=["TopLeft","TopRight","BottomLeft","BottomRight"],k0=Uh.length,Dc=r=>typeof r=="string"?parseFloat(r):r,Gc=r=>typeof r=="number"||Oe.test(r);function _0(r,t,s,a,n,i){n?(r.opacity=At(0,s.opacity!==void 0?s.opacity:1,S0(a)),r.opacityExit=At(t.opacity!==void 0?t.opacity:1,0,C0(a))):i&&(r.opacity=At(t.opacity!==void 0?t.opacity:1,s.opacity!==void 0?s.opacity:1,a));for(let o=0;o<k0;o++){const l=`border${Uh[o]}Radius`;let c=Uc(t,l),u=Uc(s,l);if(c===void 0&&u===void 0)continue;c||(c=0),u||(u=0),c===0||u===0||Gc(c)===Gc(u)?(r[l]=Math.max(At(Dc(c),Dc(u),a),0),(Vs.test(u)||Vs.test(c))&&(r[l]+="%")):r[l]=u}(t.rotate||s.rotate)&&(r.rotate=At(t.rotate||0,s.rotate||0,a))}function Uc(r,t){return r[t]!==void 0?r[t]:r.borderRadius}const S0=Vh(0,.5,oh),C0=Vh(.5,.95,bs);function Vh(r,t,s){return a=>a<r?0:a>t?1:s(Hr(r,t,a))}function Vc(r,t){r.min=t.min,r.max=t.max}function ws(r,t){Vc(r.x,t.x),Vc(r.y,t.y)}function zc(r,t){r.translate=t.translate,r.scale=t.scale,r.originPoint=t.originPoint,r.origin=t.origin}function Wc(r,t,s,a,n){return r-=t,r=En(r,1/s,a),n!==void 0&&(r=En(r,1/n,a)),r}function P0(r,t=0,s=1,a=.5,n,i=r,o=r){if(Vs.test(t)&&(t=parseFloat(t),t=At(o.min,o.max,t/100)-o.min),typeof t!="number")return;let l=At(i.min,i.max,a);r===i&&(l-=t),r.min=Wc(r.min,t,s,l,n),r.max=Wc(r.max,t,s,l,n)}function qc(r,t,[s,a,n],i,o){P0(r,t[s],t[a],t[n],t.scale,i,o)}const E0=["x","scaleX","originX"],T0=["y","scaleY","originY"];function Hc(r,t,s,a){qc(r.x,t,E0,s?s.x:void 0,a?a.x:void 0),qc(r.y,t,T0,s?s.y:void 0,a?a.y:void 0)}function Kc(r){return r.translate===0&&r.scale===1}function zh(r){return Kc(r.x)&&Kc(r.y)}function Yc(r,t){return r.min===t.min&&r.max===t.max}function A0(r,t){return Yc(r.x,t.x)&&Yc(r.y,t.y)}function Jc(r,t){return Math.round(r.min)===Math.round(t.min)&&Math.round(r.max)===Math.round(t.max)}function Wh(r,t){return Jc(r.x,t.x)&&Jc(r.y,t.y)}function Zc(r){return vs(r.x)/vs(r.y)}function Xc(r,t){return r.translate===t.translate&&r.scale===t.scale&&r.originPoint===t.originPoint}class I0{constructor(){this.members=[]}add(t){nl(this.members,t),t.scheduleRender()}remove(t){if(il(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const s=this.members[this.members.length-1];s&&this.promote(s)}}relegate(t){const s=this.members.findIndex(n=>t===n);if(s===0)return!1;let a;for(let n=s;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1){a=i;break}}return a?(this.promote(a),!0):!1}promote(t,s){const a=this.lead;if(t!==a&&(this.prevLead=a,this.lead=t,t.show(),a)){a.instance&&a.scheduleRender(),t.scheduleRender(),t.resumeFrom=a,s&&(t.resumeFrom.preserveOpacity=!0),a.snapshot&&(t.snapshot=a.snapshot,t.snapshot.latestValues=a.animationValues||a.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:n}=t.options;n===!1&&a.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:s,resumingFrom:a}=t;s.onExitComplete&&s.onExitComplete(),a&&a.options.onExitComplete&&a.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function R0(r,t,s){let a="";const n=r.x.translate/t.x,i=r.y.translate/t.y,o=(s==null?void 0:s.z)||0;if((n||i||o)&&(a=`translate3d(${n}px, ${i}px, ${o}px) `),(t.x!==1||t.y!==1)&&(a+=`scale(${1/t.x}, ${1/t.y}) `),s){const{transformPerspective:u,rotate:d,rotateX:h,rotateY:m,skewX:g,skewY:f}=s;u&&(a=`perspective(${u}px) ${a}`),d&&(a+=`rotate(${d}deg) `),h&&(a+=`rotateX(${h}deg) `),m&&(a+=`rotateY(${m}deg) `),g&&(a+=`skewX(${g}deg) `),f&&(a+=`skewY(${f}deg) `)}const l=r.x.scale*t.x,c=r.y.scale*t.y;return(l!==1||c!==1)&&(a+=`scale(${l}, ${c})`),a||"none"}const mr={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0},pa=typeof window<"u"&&window.MotionDebug!==void 0,gi=["","X","Y","Z"],$0={visibility:"hidden"},Qc=1e3;let L0=0;function fi(r,t,s,a){const{latestValues:n}=t;n[r]&&(s[r]=n[r],t.setStaticValue(r,0),a&&(a[r]=0))}function qh(r){if(r.hasCheckedOptimisedAppear=!0,r.root===r)return;const{visualElement:t}=r.options;if(!t)return;const s=eh(t);if(window.MotionHasOptimisedAnimation(s,"transform")){const{layout:n,layoutId:i}=r.options;window.MotionCancelOptimisedAnimation(s,"transform",Et,!(n||i))}const{parent:a}=r;a&&!a.hasCheckedOptimisedAppear&&qh(a)}function Hh({attachResizeListener:r,defaultParent:t,measureScroll:s,checkIsScrollRoot:a,resetTransform:n}){return class{constructor(o={},l=t==null?void 0:t()){this.id=L0++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,pa&&(mr.totalNodes=mr.resolvedTargetDeltas=mr.recalculatedProjection=0),this.nodes.forEach(B0),this.nodes.forEach(V0),this.nodes.forEach(z0),this.nodes.forEach(F0),pa&&window.MotionDebug.record(mr)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=l?l.root||l:this,this.path=l?[...l.path,l]:[],this.parent=l,this.depth=l?l.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new j0)}addEventListener(o,l){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new ol),this.eventHandlers.get(o).add(l)}notifyListeners(o,...l){const c=this.eventHandlers.get(o);c&&c.notify(...l)}hasListeners(o){return this.eventHandlers.has(o)}mount(o,l=this.root.hasTreeAnimated){if(this.instance)return;this.isSVG=v0(o),this.instance=o;const{layoutId:c,layout:u,visualElement:d}=this.options;if(d&&!d.current&&d.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),l&&(u||c)&&(this.isLayoutDirty=!0),r){let h;const m=()=>this.root.updateBlockedByResize=!1;r(o,()=>{this.root.updateBlockedByResize=!0,h&&h(),h=N0(m,250),yn.hasAnimatedSinceResize&&(yn.hasAnimatedSinceResize=!1,this.nodes.forEach(td))})}c&&this.root.registerSharedNode(c,this),this.options.animate!==!1&&d&&(c||u)&&this.addEventListener("didUpdate",({delta:h,hasLayoutChanged:m,hasRelativeTargetChanged:g,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||d.getDefaultTransition()||Y0,{onLayoutAnimationStart:x,onLayoutAnimationComplete:j}=d.getProps(),b=!this.targetLayout||!Wh(this.targetLayout,f)||g,y=!m&&g;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||y||m&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(h,y);const S={...tl(v,"layout"),onPlay:x,onComplete:j};(d.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S)}else m||td(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,nr(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(W0),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&qh(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const h=this.path[d];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:l,layout:c}=this.options;if(l===void 0&&!c)return;const u=this.getTransformTemplate();this.prevTransformTemplateValue=u?u(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(ed);return}this.isUpdating||this.nodes.forEach(G0),this.isUpdating=!1,this.nodes.forEach(U0),this.nodes.forEach(O0),this.nodes.forEach(M0),this.clearAllSnapshots();const l=zs.now();rs.delta=Xs(0,1e3/60,l-rs.timestamp),rs.timestamp=l,rs.isProcessing=!0,ii.update.process(rs),ii.preRender.process(rs),ii.render.process(rs),rs.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Wo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(D0),this.sharedNodes.forEach(q0)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Et.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Et.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure())}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Dt(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:l}=this.options;l&&l.notify("LayoutMeasure",this.layout.layoutBox,o?o.layoutBox:void 0)}updateScroll(o="measure"){let l=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(l=!1),l){const c=a(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:c,offset:s(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!n)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,l=this.projectionDelta&&!zh(this.projectionDelta),c=this.getTransformTemplate(),u=c?c(this.latestValues,""):void 0,d=u!==this.prevTransformTemplateValue;o&&(l||hr(this.latestValues)||d)&&(n(this.instance,u),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const l=this.measurePageBox();let c=this.removeElementScroll(l);return o&&(c=this.removeTransform(c)),J0(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var o;const{visualElement:l}=this.options;if(!l)return Dt();const c=l.measureViewportBox();if(!(((o=this.scroll)===null||o===void 0?void 0:o.wasRoot)||this.path.some(Z0))){const{scroll:d}=this.root;d&&(Ur(c.x,d.offset.x),Ur(c.y,d.offset.y))}return c}removeElementScroll(o){var l;const c=Dt();if(ws(c,o),!((l=this.scroll)===null||l===void 0)&&l.wasRoot)return c;for(let u=0;u<this.path.length;u++){const d=this.path[u],{scroll:h,options:m}=d;d!==this.root&&h&&m.layoutScroll&&(h.wasRoot&&ws(c,o),Ur(c.x,h.offset.x),Ur(c.y,h.offset.y))}return c}applyTransform(o,l=!1){const c=Dt();ws(c,o);for(let u=0;u<this.path.length;u++){const d=this.path[u];!l&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Vr(c,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),hr(d.latestValues)&&Vr(c,d.latestValues)}return hr(this.latestValues)&&Vr(c,this.latestValues),c}removeTransform(o){const l=Dt();ws(l,o);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!u.instance||!hr(u.latestValues))continue;to(u.latestValues)&&u.updateSnapshot();const d=Dt(),h=u.measurePageBox();ws(d,h),Hc(l,u.latestValues,u.snapshot?u.snapshot.layoutBox:void 0,d)}return hr(this.latestValues)&&Hc(l,this.latestValues),l}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==rs.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(o=!1){var l;const c=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=c.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=c.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=c.isSharedProjectionDirty);const u=!!this.resumingFrom||this!==c;if(!(o||u&&this.isSharedProjectionDirty||this.isProjectionDirty||!((l=this.parent)===null||l===void 0)&&l.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:h,layoutId:m}=this.options;if(!(!this.layout||!(h||m))){if(this.resolvedRelativeTargetAt=rs.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Dt(),this.relativeTargetOrigin=Dt(),ja(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),ws(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)){if(this.target||(this.target=Dt(),this.targetWithTransforms=Dt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),e0(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ws(this.target,this.layout.layoutBox),Bh(this.target,this.targetDelta)):ws(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Dt(),this.relativeTargetOrigin=Dt(),ja(this.relativeTargetOrigin,this.target,g.target),ws(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}pa&&mr.resolvedTargetDeltas++}}}getClosestProjectingParent(){if(!(!this.parent||to(this.parent.latestValues)||Mh(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var o;const l=this.getLead(),c=!!this.resumingFrom||this!==l;let u=!0;if((this.isProjectionDirty||!((o=this.parent)===null||o===void 0)&&o.isProjectionDirty)&&(u=!1),c&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(u=!1),this.resolvedRelativeTargetAt===rs.timestamp&&(u=!1),u)return;const{layout:d,layoutId:h}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(d||h))return;ws(this.layoutCorrected,this.layout.layoutBox);const m=this.treeScale.x,g=this.treeScale.y;c0(this.layoutCorrected,this.treeScale,this.path,c),l.layout&&!l.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(l.target=l.layout.layoutBox,l.targetWithTransforms=Dt());const{target:f}=l;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(zc(this.prevProjectionDelta.x,this.projectionDelta.x),zc(this.prevProjectionDelta.y,this.projectionDelta.y)),wa(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==m||this.treeScale.y!==g||!Xc(this.projectionDelta.x,this.prevProjectionDelta.x)||!Xc(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",f)),pa&&mr.recalculatedProjection++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var l;if((l=this.options.visualElement)===null||l===void 0||l.scheduleRender(),o){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Gr(),this.projectionDelta=Gr(),this.projectionDeltaWithTransform=Gr()}setAnimationOrigin(o,l=!1){const c=this.snapshot,u=c?c.latestValues:{},d={...this.latestValues},h=Gr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const m=Dt(),g=c?c.source:void 0,f=this.layout?this.layout.source:void 0,v=g!==f,x=this.getStack(),j=!x||x.members.length<=1,b=!!(v&&!j&&this.options.crossfade===!0&&!this.path.some(K0));this.animationProgress=0;let y;this.mixTargetDelta=S=>{const T=S/1e3;sd(h.x,o.x,T),sd(h.y,o.y,T),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ja(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),H0(this.relativeTarget,this.relativeTargetOrigin,m,T),y&&A0(this.relativeTarget,y)&&(this.isProjectionDirty=!1),y||(y=Dt()),ws(y,this.relativeTarget)),v&&(this.animationValues=d,_0(d,u,this.latestValues,T,b,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=T},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){this.notifyListeners("animationStart"),this.currentAnimation&&this.currentAnimation.stop(),this.resumingFrom&&this.resumingFrom.currentAnimation&&this.resumingFrom.currentAnimation.stop(),this.pendingAnimation&&(nr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Et.update(()=>{yn.hasAnimatedSinceResize=!0,this.currentAnimation=b0(0,Qc,{...o,onUpdate:l=>{this.mixTargetDelta(l),o.onUpdate&&o.onUpdate(l)},onComplete:()=>{o.onComplete&&o.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Qc),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:l,target:c,layout:u,latestValues:d}=o;if(!(!l||!c||!u)){if(this!==o&&this.layout&&u&&Kh(this.options.animationType,this.layout.layoutBox,u.layoutBox)){c=this.target||Dt();const h=vs(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+h;const m=vs(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+m}ws(l,c),Vr(l,d),wa(this.projectionDeltaWithTransform,this.layoutCorrected,l,d)}}registerSharedNode(o,l){this.sharedNodes.has(o)||this.sharedNodes.set(o,new I0),this.sharedNodes.get(o).add(l);const u=l.options.initialPromotionConfig;l.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(l):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())===null||o===void 0?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())===null||o===void 0?void 0:o.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:l,preserveFollowOpacity:c}={}){const u=this.getStack();u&&u.promote(this,c),o&&(this.projectionDelta=void 0,this.needsReset=!0),l&&this.setOptions({transition:l})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let l=!1;const{latestValues:c}=o;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(l=!0),!l)return;const u={};c.z&&fi("z",o,u,this.animationValues);for(let d=0;d<gi.length;d++)fi(`rotate${gi[d]}`,o,u,this.animationValues),fi(`skew${gi[d]}`,o,u,this.animationValues);o.render();for(const d in u)o.setStaticValue(d,u[d]),this.animationValues&&(this.animationValues[d]=u[d]);o.scheduleRender()}getProjectionStyles(o){var l,c;if(!this.instance||this.isSVG)return;if(!this.isVisible)return $0;const u={visibility:""},d=this.getTransformTemplate();if(this.needsReset)return this.needsReset=!1,u.opacity="",u.pointerEvents=fn(o==null?void 0:o.pointerEvents)||"",u.transform=d?d(this.latestValues,""):"none",u;const h=this.getLead();if(!this.projectionDelta||!this.layout||!h.target){const v={};return this.options.layoutId&&(v.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,v.pointerEvents=fn(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!hr(this.latestValues)&&(v.transform=d?d({},""):"none",this.hasProjected=!1),v}const m=h.animationValues||h.latestValues;this.applyTransformsToTarget(),u.transform=R0(this.projectionDeltaWithTransform,this.treeScale,m),d&&(u.transform=d(m,u.transform));const{x:g,y:f}=this.projectionDelta;u.transformOrigin=`${g.origin*100}% ${f.origin*100}% 0`,h.animationValues?u.opacity=h===this?(c=(l=m.opacity)!==null&&l!==void 0?l:this.latestValues.opacity)!==null&&c!==void 0?c:1:this.preserveOpacity?this.latestValues.opacity:m.opacityExit:u.opacity=h===this?m.opacity!==void 0?m.opacity:"":m.opacityExit!==void 0?m.opacityExit:0;for(const v in kn){if(m[v]===void 0)continue;const{correct:x,applyTo:j}=kn[v],b=u.transform==="none"?m[v]:x(m[v],h);if(j){const y=j.length;for(let S=0;S<y;S++)u[j[S]]=b}else u[v]=b}return this.options.layoutId&&(u.pointerEvents=h===this?fn(o==null?void 0:o.pointerEvents)||"":"none"),u}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var l;return(l=o.currentAnimation)===null||l===void 0?void 0:l.stop()}),this.root.nodes.forEach(ed),this.root.sharedNodes.clear()}}}function O0(r){r.updateLayout()}function M0(r){var t;const s=((t=r.resumeFrom)===null||t===void 0?void 0:t.snapshot)||r.snapshot;if(r.isLead()&&r.layout&&s&&r.hasListeners("didUpdate")){const{layoutBox:a,measuredBox:n}=r.layout,{animationType:i}=r.options,o=s.source!==r.layout.source;i==="size"?js(h=>{const m=o?s.measuredBox[h]:s.layoutBox[h],g=vs(m);m.min=a[h].min,m.max=m.min+g}):Kh(i,s.layoutBox,a)&&js(h=>{const m=o?s.measuredBox[h]:s.layoutBox[h],g=vs(a[h]);m.max=m.min+g,r.relativeTarget&&!r.currentAnimation&&(r.isProjectionDirty=!0,r.relativeTarget[h].max=r.relativeTarget[h].min+g)});const l=Gr();wa(l,a,s.layoutBox);const c=Gr();o?wa(c,r.applyTransform(n,!0),s.measuredBox):wa(c,a,s.layoutBox);const u=!zh(l);let d=!1;if(!r.resumeFrom){const h=r.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:g}=h;if(m&&g){const f=Dt();ja(f,s.layoutBox,m.layoutBox);const v=Dt();ja(v,a,g.layoutBox),Wh(f,v)||(d=!0),h.options.layoutRoot&&(r.relativeTarget=v,r.relativeTargetOrigin=f,r.relativeParent=h)}}}r.notifyListeners("didUpdate",{layout:a,snapshot:s,delta:c,layoutDelta:l,hasLayoutChanged:u,hasRelativeTargetChanged:d})}else if(r.isLead()){const{onExitComplete:a}=r.options;a&&a()}r.options.transition=void 0}function B0(r){pa&&mr.totalNodes++,r.parent&&(r.isProjecting()||(r.isProjectionDirty=r.parent.isProjectionDirty),r.isSharedProjectionDirty||(r.isSharedProjectionDirty=!!(r.isProjectionDirty||r.parent.isProjectionDirty||r.parent.isSharedProjectionDirty)),r.isTransformDirty||(r.isTransformDirty=r.parent.isTransformDirty))}function F0(r){r.isProjectionDirty=r.isSharedProjectionDirty=r.isTransformDirty=!1}function D0(r){r.clearSnapshot()}function ed(r){r.clearMeasurements()}function G0(r){r.isLayoutDirty=!1}function U0(r){const{visualElement:t}=r.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),r.resetTransform()}function td(r){r.finishAnimation(),r.targetDelta=r.relativeTarget=r.target=void 0,r.isProjectionDirty=!0}function V0(r){r.resolveTargetDelta()}function z0(r){r.calcProjection()}function W0(r){r.resetSkewAndRotation()}function q0(r){r.removeLeadSnapshot()}function sd(r,t,s){r.translate=At(t.translate,0,s),r.scale=At(t.scale,1,s),r.origin=t.origin,r.originPoint=t.originPoint}function rd(r,t,s,a){r.min=At(t.min,s.min,a),r.max=At(t.max,s.max,a)}function H0(r,t,s,a){rd(r.x,t.x,s.x,a),rd(r.y,t.y,s.y,a)}function K0(r){return r.animationValues&&r.animationValues.opacityExit!==void 0}const Y0={duration:.45,ease:[.4,0,.1,1]},ad=r=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(r),nd=ad("applewebkit/")&&!ad("chrome/")?Math.round:bs;function id(r){r.min=nd(r.min),r.max=nd(r.max)}function J0(r){id(r.x),id(r.y)}function Kh(r,t,s){return r==="position"||r==="preserve-aspect"&&!Qx(Zc(t),Zc(s),.2)}function Z0(r){var t;return r!==r.root&&((t=r.scroll)===null||t===void 0?void 0:t.wasRoot)}const X0=Hh({attachResizeListener:(r,t)=>Ra(r,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),xi={current:void 0},Yh=Hh({measureScroll:r=>({x:r.scrollLeft,y:r.scrollTop}),defaultParent:()=>{if(!xi.current){const r=new X0({});r.mount(window),r.setOptions({layoutScroll:!0}),xi.current=r}return xi.current},resetTransform:(r,t)=>{r.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:r=>window.getComputedStyle(r).position==="fixed"}),Q0={pan:{Feature:g0},drag:{Feature:p0,ProjectionNode:Yh,MeasureLayout:Gh}};function od(r,t,s){const{props:a}=r;r.animationState&&a.whileHover&&r.animationState.setActive("whileHover",s==="Start");const n="onHover"+s,i=a[n];i&&Et.postRender(()=>i(t,Ua(t)))}class ey extends or{mount(){const{current:t}=this.node;t&&(this.unmount=Qg(t,s=>(od(this.node,s,"Start"),a=>od(this.node,a,"End"))))}unmount(){}}class ty extends or{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Ga(Ra(this.node.current,"focus",()=>this.onFocus()),Ra(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function ld(r,t,s){const{props:a}=r;r.animationState&&a.whileTap&&r.animationState.setActive("whileTap",s==="Start");const n="onTap"+(s==="End"?"":s),i=a[n];i&&Et.postRender(()=>i(t,Ua(t)))}class sy extends or{mount(){const{current:t}=this.node;t&&(this.unmount=rf(t,s=>(ld(this.node,s,"Start"),(a,{success:n})=>ld(this.node,a,n?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ro=new WeakMap,yi=new WeakMap,ry=r=>{const t=ro.get(r.target);t&&t(r)},ay=r=>{r.forEach(ry)};function ny({root:r,...t}){const s=r||document;yi.has(s)||yi.set(s,{});const a=yi.get(s),n=JSON.stringify(t);return a[n]||(a[n]=new IntersectionObserver(ay,{root:r,...t})),a[n]}function iy(r,t,s){const a=ny(t);return ro.set(r,s),a.observe(r),()=>{ro.delete(r),a.unobserve(r)}}const oy={some:0,all:1};class ly extends or{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:s,margin:a,amount:n="some",once:i}=t,o={root:s?s.current:void 0,rootMargin:a,threshold:typeof n=="number"?n:oy[n]},l=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:d,onViewportLeave:h}=this.node.getProps(),m=u?d:h;m&&m(c)};return iy(this.node.current,o,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:s}=this.node;["amount","margin","root"].some(cy(t,s))&&this.startObserver()}unmount(){}}function cy({viewport:r={}},{viewport:t={}}={}){return s=>r[s]!==t[s]}const dy={inView:{Feature:ly},tap:{Feature:sy},focus:{Feature:ty},hover:{Feature:ey}},uy={layout:{ProjectionNode:Yh,MeasureLayout:Gh}},ao={current:null},Jh={current:!1};function hy(){if(Jh.current=!0,!!Do)if(window.matchMedia){const r=window.matchMedia("(prefers-reduced-motion)"),t=()=>ao.current=r.matches;r.addListener(t),t()}else ao.current=!1}const my=[...wh,os,ir],py=r=>my.find(vh(r)),cd=new WeakMap;function gy(r,t,s){for(const a in t){const n=t[a],i=s[a];if(ls(n))r.addValue(a,n);else if(ls(i))r.addValue(a,Aa(n,{owner:r}));else if(i!==n)if(r.hasValue(a)){const o=r.getValue(a);o.liveStyle===!0?o.jump(n):o.hasAnimated||o.set(n)}else{const o=r.getStaticValue(a);r.addValue(a,Aa(o!==void 0?o:n,{owner:r}))}}for(const a in s)t[a]===void 0&&r.removeValue(a);return t}const dd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class fy{scrapeMotionValuesFromProps(t,s,a){return{}}constructor({parent:t,props:s,presenceContext:a,reducedMotionConfig:n,blockInitialAnimation:i,visualState:o},l={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=ml,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const g=zs.now();this.renderScheduledAt<g&&(this.renderScheduledAt=g,Et.render(this.render,!1,!0))};const{latestValues:c,renderState:u,onUpdate:d}=o;this.onUpdate=d,this.latestValues=c,this.baseTarget={...c},this.initialValues=s.initial?{...c}:{},this.renderState=u,this.parent=t,this.props=s,this.presenceContext=a,this.depth=t?t.depth+1:0,this.reducedMotionConfig=n,this.options=l,this.blockInitialAnimation=!!i,this.isControllingVariants=Dn(s),this.isVariantNode=Eu(s),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:h,...m}=this.scrapeMotionValuesFromProps(s,{},this);for(const g in m){const f=m[g];c[g]!==void 0&&ls(f)&&f.set(c[g],!1)}}mount(t){this.current=t,cd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((s,a)=>this.bindToMotionValue(a,s)),Jh.current||hy(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ao.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){cd.delete(this.current),this.projection&&this.projection.unmount(),nr(this.notifyUpdate),nr(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const s=this.features[t];s&&(s.unmount(),s.isMounted=!1)}this.current=null}bindToMotionValue(t,s){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const a=wr.has(t),n=s.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Et.preRender(this.notifyUpdate),a&&this.projection&&(this.projection.isTransformDirty=!0)}),i=s.on("renderRequest",this.scheduleRender);let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,s)),this.valueSubscriptions.set(t,()=>{n(),i(),o&&o(),s.owner&&s.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Kr){const s=Kr[t];if(!s)continue;const{isEnabled:a,Feature:n}=s;if(!this.features[t]&&n&&a(this.props)&&(this.features[t]=new n(this)),this.features[t]){const i=this.features[t];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Dt()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,s){this.latestValues[t]=s}update(t,s){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=s;for(let a=0;a<dd.length;a++){const n=dd[a];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);const i="on"+n,o=t[i];o&&(this.propEventSubscriptions[n]=this.on(n,o))}this.prevMotionValues=gy(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue(),this.onUpdate&&this.onUpdate(this)}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const s=this.getClosestVariantNode();if(s)return s.variantChildren&&s.variantChildren.add(t),()=>s.variantChildren.delete(t)}addValue(t,s){const a=this.values.get(t);s!==a&&(a&&this.removeValue(t),this.bindToMotionValue(t,s),this.values.set(t,s),this.latestValues[t]=s.get())}removeValue(t){this.values.delete(t);const s=this.valueSubscriptions.get(t);s&&(s(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,s){if(this.props.values&&this.props.values[t])return this.props.values[t];let a=this.values.get(t);return a===void 0&&s!==void 0&&(a=Aa(s===null?void 0:s,{owner:this}),this.addValue(t,a)),a}readValue(t,s){var a;let n=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:(a=this.getBaseTargetFromProps(this.props,t))!==null&&a!==void 0?a:this.readValueFromInstance(this.current,t,this.options);return n!=null&&(typeof n=="string"&&(yh(n)||ch(n))?n=parseFloat(n):!py(n)&&ir.test(s)&&(n=gh(t,s)),this.setBaseTarget(t,ls(n)?n.get():n)),ls(n)?n.get():n}setBaseTarget(t,s){this.baseTarget[t]=s}getBaseTarget(t){var s;const{initial:a}=this.props;let n;if(typeof a=="string"||typeof a=="object"){const o=Ho(this.props,a,(s=this.presenceContext)===null||s===void 0?void 0:s.custom);o&&(n=o[t])}if(a&&n!==void 0)return n;const i=this.getBaseTargetFromProps(this.props,t);return i!==void 0&&!ls(i)?i:this.initialValues[t]!==void 0&&n===void 0?void 0:this.baseTarget[t]}on(t,s){return this.events[t]||(this.events[t]=new ol),this.events[t].add(s)}notify(t,...s){this.events[t]&&this.events[t].notify(...s)}}class Zh extends fy{constructor(){super(...arguments),this.KeyframeResolver=jh}sortInstanceNodePosition(t,s){return t.compareDocumentPosition(s)&2?1:-1}getBaseTargetFromProps(t,s){return t.style?t.style[s]:void 0}removeValueFromRenderState(t,{vars:s,style:a}){delete s[t],delete a[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;ls(t)&&(this.childSubscription=t.on("change",s=>{this.current&&(this.current.textContent=`${s}`)}))}}function xy(r){return window.getComputedStyle(r)}class yy extends Zh{constructor(){super(...arguments),this.type="html",this.renderInstance=Bu}readValueFromInstance(t,s){if(wr.has(s)){const a=hl(s);return a&&a.default||0}else{const a=xy(t),n=(Lu(s)?a.getPropertyValue(s):a[s])||0;return typeof n=="string"?n.trim():n}}measureInstanceViewportBox(t,{transformPagePoint:s}){return Fh(t,s)}build(t,s,a){Jo(t,s,a.transformTemplate)}scrapeMotionValuesFromProps(t,s,a){return el(t,s,a)}}class by extends Zh{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Dt}getBaseTargetFromProps(t,s){return t[s]}readValueFromInstance(t,s){if(wr.has(s)){const a=hl(s);return a&&a.default||0}return s=Fu.has(s)?s:zo(s),t.getAttribute(s)}scrapeMotionValuesFromProps(t,s,a){return Uu(t,s,a)}build(t,s,a){Zo(t,s,this.isSVGTag,a.transformTemplate)}renderInstance(t,s,a,n){Du(t,s,a,n)}mount(t){this.isSVGTag=Qo(t.tagName),super.mount(t)}}const vy=(r,t)=>qo(r)?new by(t):new yy(t,{allowProjection:r!==p.Fragment}),wy=qg({...zx,...dy,...Q0,...uy},vy),Ie=og(wy),Ss={IN:{name:"India",currency:"INR",symbol:"₹",bookPrice:1399,softCoverPrice:1149,shippingPrice:200,heroImagesPath:"/homepage_images/",heroImageCount:14,heroImageInterval:3e3,headline:"Turn Your Child into a Storybook Hero",subtext:"Using AI magic, we turn your or your child's photos into beautiful personalized storybooks that you will treasure forever",country:"India",postalCodeLabel:"Pincode",postalCodePlaceholder:"6-digit pincode",phoneValidation:/^\d{10}$/,phonePlaceholder:"10-digit number",urlPrefix:""},SG:{name:"Singapore",currency:"SGD",symbol:"S$",bookPrice:44.99,softCoverPrice:29.99,shippingPrice:4.99,heroImagesPath:"/homepage_images_sg/",heroImageCount:16,heroImageInterval:2e3,headline:"Create Your Personalised Books",subtext:"Using AI magic, we turn your child's photos into beautiful personalized storybooks they'll treasure forever",country:"Singapore",postalCodeLabel:"Postal Code",postalCodePlaceholder:"6-digit postal code",phoneValidation:/^\d{8}$/,phonePlaceholder:"8-digit number",urlPrefix:"/sg",hreflang:"en-sg"},US:{name:"United States",currency:"USD",symbol:"$",bookPrice:44.99,softCoverPrice:29.99,shippingPrice:9.99,heroImagesPath:"/homepage_images_sg/",heroImageCount:16,heroImageInterval:2e3,headline:"Create Your Personalised Books",subtext:"Using AI magic, we turn your child's photos into beautiful personalized storybooks they'll treasure forever",country:"United States",postalCodeLabel:"ZIP Code",postalCodePlaceholder:"5-digit ZIP code",phoneValidation:/^\d{10}$/,phonePlaceholder:"10-digit number",urlPrefix:"/us",hreflang:"en-us"}},Fs="IN",no={"":"IN",sg:"SG",us:"US"},Xh=r=>{var a;const s=((a=r.split("/").filter(Boolean)[0])==null?void 0:a.toLowerCase())||"";return no[s]?no[s]:Fs},$a=r=>{var a;const t=r.split("/").filter(Boolean),s=((a=t[0])==null?void 0:a.toLowerCase())||"";return no[s]&&s!==""?"/"+t.slice(1).join("/"):r},Tn=(r,t)=>{const s=Ss[t],a=$a(r),n=a.startsWith("/")?a:`/${a}`;return s.urlPrefix?`${s.urlPrefix}${n==="/"?"":n}`:n},Gt=(r,t)=>{const s=Ss[r];return r==="SG"||r==="US"?`${s.symbol}${t.toFixed(2)}`:`${s.symbol}${Math.round(t)}`},jy=r=>Ss[r]||Ss[Fs],Ny="modulepreload",ky=function(r){return"/"+r},ud={},ta=function(t,s,a){let n=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));n=Promise.allSettled(s.map(c=>{if(c=ky(c),c in ud)return;ud[c]=!0;const u=c.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":Ny,u||(h.as="script"),h.crossOrigin="",h.href=c,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((m,g)=>{h.addEventListener("load",m),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return n.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})},_y=r=>{let t;return r?t=r:typeof fetch>"u"?t=(...s)=>ta(async()=>{const{default:a}=await Promise.resolve().then(()=>sa);return{default:a}},void 0).then(({default:a})=>a(...s)):t=fetch,(...s)=>t(...s)};class xl extends Error{constructor(t,s="FunctionsError",a){super(t),this.name=s,this.context=a}}class Sy extends xl{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class hd extends xl{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class md extends xl{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var io;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(io||(io={}));var Cy=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};class Py{constructor(t,{headers:s={},customFetch:a,region:n=io.Any}={}){this.url=t,this.headers=s,this.region=n,this.fetch=_y(a)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,s={}){var a;return Cy(this,void 0,void 0,function*(){try{const{headers:n,method:i,body:o}=s;let l={},{region:c}=s;c||(c=this.region);const u=new URL(`${this.url}/${t}`);c&&c!=="any"&&(l["x-region"]=c,u.searchParams.set("forceFunctionRegion",c));let d;o&&(n&&!Object.prototype.hasOwnProperty.call(n,"Content-Type")||!n)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",d=o):typeof o=="string"?(l["Content-Type"]="text/plain",d=o):typeof FormData<"u"&&o instanceof FormData?d=o:(l["Content-Type"]="application/json",d=JSON.stringify(o)));const h=yield this.fetch(u.toString(),{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),n),body:d}).catch(v=>{throw new Sy(v)}),m=h.headers.get("x-relay-error");if(m&&m==="true")throw new hd(h);if(!h.ok)throw new md(h);let g=((a=h.headers.get("Content-Type"))!==null&&a!==void 0?a:"text/plain").split(";")[0].trim(),f;return g==="application/json"?f=yield h.json():g==="application/octet-stream"?f=yield h.blob():g==="text/event-stream"?f=h:g==="multipart/form-data"?f=yield h.formData():f=yield h.text(),{data:f,error:null,response:h}}catch(n){return{data:null,error:n,response:n instanceof md||n instanceof hd?n.context:void 0}}})}}var ps={},yl={},Vn={},Va={},zn={},Wn={},Ey=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},Jr=Ey();const Ty=Jr.fetch,Qh=Jr.fetch.bind(Jr),em=Jr.Headers,Ay=Jr.Request,Iy=Jr.Response,sa=Object.freeze(Object.defineProperty({__proto__:null,Headers:em,Request:Ay,Response:Iy,default:Qh,fetch:Ty},Symbol.toStringTag,{value:"Module"})),Ry=Ym(sa);var qn={};Object.defineProperty(qn,"__esModule",{value:!0});let $y=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};qn.default=$y;var tm=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wn,"__esModule",{value:!0});const Ly=tm(Ry),Oy=tm(qn);let My=class{constructor(t){var s,a;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(s=t.shouldThrowOnError)!==null&&s!==void 0?s:!1,this.signal=t.signal,this.isMaybeSingle=(a=t.isMaybeSingle)!==null&&a!==void 0?a:!1,t.fetch?this.fetch=t.fetch:typeof fetch>"u"?this.fetch=Ly.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,s){return this.headers=new Headers(this.headers),this.headers.set(t,s),this}then(t,s){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const a=this.fetch;let n=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var o,l,c,u;let d=null,h=null,m=null,g=i.status,f=i.statusText;if(i.ok){if(this.method!=="HEAD"){const b=await i.text();b===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((o=this.headers.get("Accept"))===null||o===void 0)&&o.includes("application/vnd.pgrst.plan+text"))?h=b:h=JSON.parse(b))}const x=(l=this.headers.get("Prefer"))===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),j=(c=i.headers.get("content-range"))===null||c===void 0?void 0:c.split("/");x&&j&&j.length>1&&(m=parseInt(j[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(h)&&(h.length>1?(d={code:"PGRST116",details:`Results contain ${h.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},h=null,m=null,g=406,f="Not Acceptable"):h.length===1?h=h[0]:h=null)}else{const x=await i.text();try{d=JSON.parse(x),Array.isArray(d)&&i.status===404&&(h=[],d=null,g=200,f="OK")}catch{i.status===404&&x===""?(g=204,f="No Content"):d={message:x}}if(d&&this.isMaybeSingle&&(!((u=d==null?void 0:d.details)===null||u===void 0)&&u.includes("0 rows"))&&(d=null,g=200,f="OK"),d&&this.shouldThrowOnError)throw new Oy.default(d)}return{error:d,data:h,count:m,status:g,statusText:f}});return this.shouldThrowOnError||(n=n.catch(i=>{var o,l,c;return{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(l=i==null?void 0:i.stack)!==null&&l!==void 0?l:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),n.then(t,s)}returns(){return this}overrideTypes(){return this}};Wn.default=My;var By=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zn,"__esModule",{value:!0});const Fy=By(Wn);let Dy=class extends Fy.default{select(t){let s=!1;const a=(t??"*").split("").map(n=>/\s/.test(n)&&!s?"":(n==='"'&&(s=!s),n)).join("");return this.url.searchParams.set("select",a),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:s=!0,nullsFirst:a,foreignTable:n,referencedTable:i=n}={}){const o=i?`${i}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${t}.${s?"asc":"desc"}${a===void 0?"":a?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:s,referencedTable:a=s}={}){const n=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,s,{foreignTable:a,referencedTable:n=a}={}){const i=typeof n>"u"?"offset":`${n}.offset`,o=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(o,`${s-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:s=!1,settings:a=!1,buffers:n=!1,wal:i=!1,format:o="text"}={}){var l;const c=[t?"analyze":null,s?"verbose":null,a?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),u=(l=this.headers.get("Accept"))!==null&&l!==void 0?l:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`),o==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};zn.default=Dy;var Gy=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Va,"__esModule",{value:!0});const Uy=Gy(zn);let Vy=class extends Uy.default{eq(t,s){return this.url.searchParams.append(t,`eq.${s}`),this}neq(t,s){return this.url.searchParams.append(t,`neq.${s}`),this}gt(t,s){return this.url.searchParams.append(t,`gt.${s}`),this}gte(t,s){return this.url.searchParams.append(t,`gte.${s}`),this}lt(t,s){return this.url.searchParams.append(t,`lt.${s}`),this}lte(t,s){return this.url.searchParams.append(t,`lte.${s}`),this}like(t,s){return this.url.searchParams.append(t,`like.${s}`),this}likeAllOf(t,s){return this.url.searchParams.append(t,`like(all).{${s.join(",")}}`),this}likeAnyOf(t,s){return this.url.searchParams.append(t,`like(any).{${s.join(",")}}`),this}ilike(t,s){return this.url.searchParams.append(t,`ilike.${s}`),this}ilikeAllOf(t,s){return this.url.searchParams.append(t,`ilike(all).{${s.join(",")}}`),this}ilikeAnyOf(t,s){return this.url.searchParams.append(t,`ilike(any).{${s.join(",")}}`),this}is(t,s){return this.url.searchParams.append(t,`is.${s}`),this}in(t,s){const a=Array.from(new Set(s)).map(n=>typeof n=="string"&&new RegExp("[,()]").test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${a})`),this}contains(t,s){return typeof s=="string"?this.url.searchParams.append(t,`cs.${s}`):Array.isArray(s)?this.url.searchParams.append(t,`cs.{${s.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(s)}`),this}containedBy(t,s){return typeof s=="string"?this.url.searchParams.append(t,`cd.${s}`):Array.isArray(s)?this.url.searchParams.append(t,`cd.{${s.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(s)}`),this}rangeGt(t,s){return this.url.searchParams.append(t,`sr.${s}`),this}rangeGte(t,s){return this.url.searchParams.append(t,`nxl.${s}`),this}rangeLt(t,s){return this.url.searchParams.append(t,`sl.${s}`),this}rangeLte(t,s){return this.url.searchParams.append(t,`nxr.${s}`),this}rangeAdjacent(t,s){return this.url.searchParams.append(t,`adj.${s}`),this}overlaps(t,s){return typeof s=="string"?this.url.searchParams.append(t,`ov.${s}`):this.url.searchParams.append(t,`ov.{${s.join(",")}}`),this}textSearch(t,s,{config:a,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");const o=a===void 0?"":`(${a})`;return this.url.searchParams.append(t,`${i}fts${o}.${s}`),this}match(t){return Object.entries(t).forEach(([s,a])=>{this.url.searchParams.append(s,`eq.${a}`)}),this}not(t,s,a){return this.url.searchParams.append(t,`not.${s}.${a}`),this}or(t,{foreignTable:s,referencedTable:a=s}={}){const n=a?`${a}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,s,a){return this.url.searchParams.append(t,`${s}.${a}`),this}};Va.default=Vy;var zy=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vn,"__esModule",{value:!0});const ca=zy(Va);let Wy=class{constructor(t,{headers:s={},schema:a,fetch:n}){this.url=t,this.headers=new Headers(s),this.schema=a,this.fetch=n}select(t,{head:s=!1,count:a}={}){const n=s?"HEAD":"GET";let i=!1;const o=(t??"*").split("").map(l=>/\s/.test(l)&&!i?"":(l==='"'&&(i=!i),l)).join("");return this.url.searchParams.set("select",o),a&&this.headers.append("Prefer",`count=${a}`),new ca.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(t,{count:s,defaultToNull:a=!0}={}){var n;const i="POST";if(s&&this.headers.append("Prefer",`count=${s}`),a||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(o.length>0){const l=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",l.join(","))}}return new ca.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch})}upsert(t,{onConflict:s,ignoreDuplicates:a=!1,count:n,defaultToNull:i=!0}={}){var o;const l="POST";if(this.headers.append("Prefer",`resolution=${a?"ignore":"merge"}-duplicates`),s!==void 0&&this.url.searchParams.set("on_conflict",s),n&&this.headers.append("Prefer",`count=${n}`),i||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){const u=[...new Set(c)].map(d=>`"${d}"`);this.url.searchParams.set("columns",u.join(","))}}return new ca.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}update(t,{count:s}={}){var a;const n="PATCH";return s&&this.headers.append("Prefer",`count=${s}`),new ca.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}delete({count:t}={}){var s;const a="DELETE";return t&&this.headers.append("Prefer",`count=${t}`),new ca.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}};Vn.default=Wy;var sm=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(yl,"__esModule",{value:!0});const qy=sm(Vn),Hy=sm(Va);let Ky=class rm{constructor(t,{headers:s={},schema:a,fetch:n}={}){this.url=t,this.headers=new Headers(s),this.schemaName=a,this.fetch=n}from(t){const s=new URL(`${this.url}/${t}`);return new qy.default(s,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new rm(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,s={},{head:a=!1,get:n=!1,count:i}={}){var o;let l;const c=new URL(`${this.url}/rpc/${t}`);let u;a||n?(l=a?"HEAD":"GET",Object.entries(s).filter(([h,m])=>m!==void 0).map(([h,m])=>[h,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([h,m])=>{c.searchParams.append(h,m)})):(l="POST",u=s);const d=new Headers(this.headers);return i&&d.set("Prefer",`count=${i}`),new Hy.default({method:l,url:c,headers:d,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}};yl.default=Ky;var ra=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ps,"__esModule",{value:!0});ps.PostgrestError=ps.PostgrestBuilder=ps.PostgrestTransformBuilder=ps.PostgrestFilterBuilder=ps.PostgrestQueryBuilder=ps.PostgrestClient=void 0;const am=ra(yl);ps.PostgrestClient=am.default;const nm=ra(Vn);ps.PostgrestQueryBuilder=nm.default;const im=ra(Va);ps.PostgrestFilterBuilder=im.default;const om=ra(zn);ps.PostgrestTransformBuilder=om.default;const lm=ra(Wn);ps.PostgrestBuilder=lm.default;const cm=ra(qn);ps.PostgrestError=cm.default;var Yy=ps.default={PostgrestClient:am.default,PostgrestQueryBuilder:nm.default,PostgrestFilterBuilder:im.default,PostgrestTransformBuilder:om.default,PostgrestBuilder:lm.default,PostgrestError:cm.default};const{PostgrestClient:Jy,PostgrestQueryBuilder:G1,PostgrestFilterBuilder:U1,PostgrestTransformBuilder:V1,PostgrestBuilder:z1,PostgrestError:W1}=Yy;class Zy{static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"&&process.versions&&process.versions.node){const s=parseInt(process.versions.node.split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
import ws from "ws"
new RealtimeClient(url, { transport: ws })`}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const t=this.detectEnvironment();if(t.constructor)return t.constructor;let s=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(s+=`

Suggested solution: ${t.workaround}`),new Error(s)}static createWebSocket(t,s){const a=this.getWebSocketConstructor();return new a(t,s)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}}const Xy="2.15.1",Qy=`realtime-js/${Xy}`,eb="1.0.0",oo=1e4,tb=1e3,sb=100;var Na;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(Na||(Na={}));var Ht;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(Ht||(Ht={}));var Is;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(Is||(Is={}));var lo;(function(r){r.websocket="websocket"})(lo||(lo={}));var gr;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(gr||(gr={}));class rb{constructor(){this.HEADER_LENGTH=1}decode(t,s){return t.constructor===ArrayBuffer?s(this._binaryDecode(t)):s(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const s=new DataView(t),a=new TextDecoder;return this._decodeBroadcast(t,s,a)}_decodeBroadcast(t,s,a){const n=s.getUint8(1),i=s.getUint8(2);let o=this.HEADER_LENGTH+2;const l=a.decode(t.slice(o,o+n));o=o+n;const c=a.decode(t.slice(o,o+i));o=o+i;const u=JSON.parse(a.decode(t.slice(o,t.byteLength)));return{ref:null,topic:l,event:c,payload:u}}}class dm{constructor(t,s){this.callback=t,this.timerCalc=s,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=s}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var kt;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(kt||(kt={}));const pd=(r,t,s={})=>{var a;const n=(a=s.skipTypes)!==null&&a!==void 0?a:[];return Object.keys(t).reduce((i,o)=>(i[o]=ab(o,r,t,n),i),{})},ab=(r,t,s,a)=>{const n=t.find(l=>l.name===r),i=n==null?void 0:n.type,o=s[r];return i&&!a.includes(i)?um(i,o):co(o)},um=(r,t)=>{if(r.charAt(0)==="_"){const s=r.slice(1,r.length);return lb(t,s)}switch(r){case kt.bool:return nb(t);case kt.float4:case kt.float8:case kt.int2:case kt.int4:case kt.int8:case kt.numeric:case kt.oid:return ib(t);case kt.json:case kt.jsonb:return ob(t);case kt.timestamp:return cb(t);case kt.abstime:case kt.date:case kt.daterange:case kt.int4range:case kt.int8range:case kt.money:case kt.reltime:case kt.text:case kt.time:case kt.timestamptz:case kt.timetz:case kt.tsrange:case kt.tstzrange:return co(t);default:return co(t)}},co=r=>r,nb=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},ib=r=>{if(typeof r=="string"){const t=parseFloat(r);if(!Number.isNaN(t))return t}return r},ob=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(t){return console.log(`JSON parse error: ${t}`),r}return r},lb=(r,t)=>{if(typeof r!="string")return r;const s=r.length-1,a=r[s];if(r[0]==="{"&&a==="}"){let i;const o=r.slice(1,s);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(l=>um(t,l))}return r},cb=r=>typeof r=="string"?r.replace(" ","T"):r,hm=r=>{let t=r;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")+"/api/broadcast"};class bi{constructor(t,s,a={},n=oo){this.channel=t,this.event=s,this.payload=a,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,s){var a;return this._hasReceived(t)&&s((a=this.receivedResp)===null||a===void 0?void 0:a.response),this.recHooks.push({status:t,callback:s}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=s=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=s,this._matchReceive(s)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,s){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:s})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:s}){this.recHooks.filter(a=>a.status===t).forEach(a=>a.callback(s))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var gd;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(gd||(gd={}));class ka{constructor(t,s){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const a=(s==null?void 0:s.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(a.state,{},n=>{const{onJoin:i,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ka.syncState(this.state,n,i,o),this.pendingDiffs.forEach(c=>{this.state=ka.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],l()}),this.channel._on(a.diff,{},n=>{const{onJoin:i,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=ka.syncDiff(this.state,n,i,o),l())}),this.onJoin((n,i,o)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:o})}),this.onLeave((n,i,o)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,s,a,n){const i=this.cloneDeep(t),o=this.transformState(s),l={},c={};return this.map(i,(u,d)=>{o[u]||(c[u]=d)}),this.map(o,(u,d)=>{const h=i[u];if(h){const m=d.map(x=>x.presence_ref),g=h.map(x=>x.presence_ref),f=d.filter(x=>g.indexOf(x.presence_ref)<0),v=h.filter(x=>m.indexOf(x.presence_ref)<0);f.length>0&&(l[u]=f),v.length>0&&(c[u]=v)}else l[u]=d}),this.syncDiff(i,{joins:l,leaves:c},a,n)}static syncDiff(t,s,a,n){const{joins:i,leaves:o}={joins:this.transformState(s.joins),leaves:this.transformState(s.leaves)};return a||(a=()=>{}),n||(n=()=>{}),this.map(i,(l,c)=>{var u;const d=(u=t[l])!==null&&u!==void 0?u:[];if(t[l]=this.cloneDeep(c),d.length>0){const h=t[l].map(g=>g.presence_ref),m=d.filter(g=>h.indexOf(g.presence_ref)<0);t[l].unshift(...m)}a(l,d,c)}),this.map(o,(l,c)=>{let u=t[l];if(!u)return;const d=c.map(h=>h.presence_ref);u=u.filter(h=>d.indexOf(h.presence_ref)<0),t[l]=u,n(l,u,c),u.length===0&&delete t[l]}),t}static map(t,s){return Object.getOwnPropertyNames(t).map(a=>s(a,t[a]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((s,a)=>{const n=t[a];return"metas"in n?s[a]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):s[a]=n,s},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var fd;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(fd||(fd={}));var _a;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(_a||(_a={}));var Ys;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Ys||(Ys={}));class bl{constructor(t,s={config:{}},a){this.topic=t,this.params=s,this.socket=a,this.bindings={},this.state=Ht.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},s.config),this.timeout=this.socket.timeout,this.joinPush=new bi(this,Is.join,this.params,this.timeout),this.rejoinTimer=new dm(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Ht.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Ht.closed,this.socket._remove(this)}),this._onError(n=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,n),this.state=Ht.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Ht.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",n=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,n),this.state=Ht.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Is.reply,{},(n,i)=>{this._trigger(this._replyEventName(i),n)}),this.presence=new ka(this),this.broadcastEndpointURL=hm(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(t,s=this.timeout){var a,n;if(this.socket.isConnected()||this.socket.connect(),this.state==Ht.closed){const{config:{broadcast:i,presence:o,private:l}}=this.params,c=(n=(a=this.bindings.postgres_changes)===null||a===void 0?void 0:a.map(m=>m.filter))!==null&&n!==void 0?n:[],u=!!this.bindings[_a.PRESENCE]&&this.bindings[_a.PRESENCE].length>0,d={},h={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>t==null?void 0:t(Ys.CHANNEL_ERROR,m)),this._onClose(()=>t==null?void 0:t(Ys.CLOSED)),this.updateJoinPayload(Object.assign({config:h},d)),this.joinedOnce=!0,this._rejoin(s),this.joinPush.receive("ok",async({postgres_changes:m})=>{var g;if(this.socket.setAuth(),m===void 0){t==null||t(Ys.SUBSCRIBED);return}else{const f=this.bindings.postgres_changes,v=(g=f==null?void 0:f.length)!==null&&g!==void 0?g:0,x=[];for(let j=0;j<v;j++){const b=f[j],{filter:{event:y,schema:S,table:T,filter:I}}=b,E=m&&m[j];if(E&&E.event===y&&E.schema===S&&E.table===T&&E.filter===I)x.push(Object.assign(Object.assign({},b),{id:E.id}));else{this.unsubscribe(),this.state=Ht.errored,t==null||t(Ys.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=x,t&&t(Ys.SUBSCRIBED);return}}).receive("error",m=>{this.state=Ht.errored,t==null||t(Ys.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(Ys.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,s={}){return await this.send({type:"presence",event:"track",payload:t},s.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,s,a){return this.state===Ht.joined&&t===_a.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(t,s,a)}async send(t,s={}){var a,n;if(!this._canPush()&&t.type==="broadcast"){const{event:i,payload:o}=t,c={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(a=s.timeout)!==null&&a!==void 0?a:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,c;const u=this._push(t.type,t,s.timeout||this.timeout);t.type==="broadcast"&&!(!((c=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=Ht.leaving;const s=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Is.close,"leave",this._joinRef())};this.joinPush.destroy();let a=null;return new Promise(n=>{a=new bi(this,Is.leave,{},t),a.receive("ok",()=>{s(),n("ok")}).receive("timeout",()=>{s(),n("timed out")}).receive("error",()=>{n("error")}),a.send(),this._canPush()||a.trigger("ok",{})}).finally(()=>{a==null||a.destroy()})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Ht.closed,this.bindings={}}async _fetchWithTimeout(t,s,a){const n=new AbortController,i=setTimeout(()=>n.abort(),a),o=await this.socket.fetch(t,Object.assign(Object.assign({},s),{signal:n.signal}));return clearTimeout(i),o}_push(t,s,a=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new bi(this,t,s,a);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(t){if(t.startTimeout(),this.pushBuffer.push(t),this.pushBuffer.length>sb){const s=this.pushBuffer.shift();s&&(s.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload))}}_onMessage(t,s,a){return s}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,s,a){var n,i;const o=t.toLocaleLowerCase(),{close:l,error:c,leave:u,join:d}=Is;if(a&&[l,c,u,d].indexOf(o)>=0&&a!==this._joinRef())return;let m=this._onMessage(o,s,a);if(s&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(g=>{var f,v,x;return((f=g.filter)===null||f===void 0?void 0:f.event)==="*"||((x=(v=g.filter)===null||v===void 0?void 0:v.event)===null||x===void 0?void 0:x.toLocaleLowerCase())===o}).map(g=>g.callback(m,a)):(i=this.bindings[o])===null||i===void 0||i.filter(g=>{var f,v,x,j,b,y;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){const S=g.id,T=(f=g.filter)===null||f===void 0?void 0:f.event;return S&&((v=s.ids)===null||v===void 0?void 0:v.includes(S))&&(T==="*"||(T==null?void 0:T.toLocaleLowerCase())===((x=s.data)===null||x===void 0?void 0:x.type.toLocaleLowerCase()))}else{const S=(b=(j=g==null?void 0:g.filter)===null||j===void 0?void 0:j.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return S==="*"||S===((y=s==null?void 0:s.event)===null||y===void 0?void 0:y.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof m=="object"&&"ids"in m){const f=m.data,{schema:v,table:x,commit_timestamp:j,type:b,errors:y}=f;m=Object.assign(Object.assign({},{schema:v,table:x,commit_timestamp:j,eventType:b,new:{},old:{},errors:y}),this._getPayloadRecords(f))}g.callback(m,a)})}_isClosed(){return this.state===Ht.closed}_isJoined(){return this.state===Ht.joined}_isJoining(){return this.state===Ht.joining}_isLeaving(){return this.state===Ht.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,s,a){const n=t.toLocaleLowerCase(),i={type:n,filter:s,callback:a};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(t,s){const a=t.toLocaleLowerCase();return this.bindings[a]&&(this.bindings[a]=this.bindings[a].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===a&&bl.isEqual(n.filter,s))})),this}static isEqual(t,s){if(Object.keys(t).length!==Object.keys(s).length)return!1;for(const a in t)if(t[a]!==s[a])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(Is.close,{},t)}_onError(t){this._on(Is.error,{},s=>t(s))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Ht.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const s={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(s.new=pd(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(s.old=pd(t.columns,t.old_record)),s}}const xd=()=>{},rn={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},db=[1e3,2e3,5e3,1e4],ub=1e4,hb=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`;class mb{constructor(t,s){var a;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=oo,this.transport=null,this.heartbeatIntervalMs=rn.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=xd,this.ref=0,this.reconnectTimer=null,this.logger=xd,this.conn=null,this.sendBuffer=[],this.serializer=new rb,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=n=>{let i;return n?i=n:typeof fetch>"u"?i=(...o)=>ta(async()=>{const{default:l}=await Promise.resolve().then(()=>sa);return{default:l}},void 0).then(({default:l})=>l(...o)).catch(l=>{throw new Error(`Failed to load @supabase/node-fetch: ${l.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):i=fetch,(...o)=>i(...o)},!(!((a=s==null?void 0:s.params)===null||a===void 0)&&a.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=s.params.apikey,this.endPoint=`${t}/${lo.websocket}`,this.httpEndpoint=hm(t),this._initializeOptions(s),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(s==null?void 0:s.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Zy.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");const s=t.message;throw s.includes("Node.js")?new Error(`${s}

To use Realtime in Node.js, you need to provide a WebSocket implementation:

Option 1: Use Node.js 22+ which has native WebSocket support
Option 2: Install and provide the "ws" package:

  npm install ws

  import ws from "ws"
  const client = new RealtimeClient(url, {
    ...options,
    transport: ws
  })`):new Error(`WebSocket not available: ${s}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:eb}))}disconnect(t,s){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const a=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(a),this._setConnectionState("disconnected")},t?this.conn.close(t,s??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(t){const s=await t.unsubscribe();return this.channels.length===0&&this.disconnect(),s}async removeAllChannels(){const t=await Promise.all(this.channels.map(s=>s.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,s,a){this.logger(t,s,a)}connectionState(){switch(this.conn&&this.conn.readyState){case Na.connecting:return gr.Connecting;case Na.open:return gr.Open;case Na.closing:return gr.Closing;default:return gr.Closed}}isConnected(){return this.connectionState()===gr.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(t,s={config:{}}){const a=`realtime:${t}`,n=this.getChannels().find(i=>i.topic===a);if(n)return n;{const i=new bl(`realtime:${t}`,s,this);return this.channels.push(i),i}}push(t){const{topic:s,event:a,payload:n,ref:i}=t,o=()=>{this.encode(t,l=>{var c;(c=this.conn)===null||c===void 0||c.send(l)})};this.log("push",`${s} ${a} (${i})`,n),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var t;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),this._wasManualDisconnect=!1,(t=this.conn)===null||t===void 0||t.close(tb,"heartbeat timeout"),setTimeout(()=>{var s;this.isConnected()||(s=this.reconnectTimer)===null||s===void 0||s.scheduleTimeout()},rn.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),this._setAuthSafely("heartbeat")}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let s=this.channels.find(a=>a.topic===t&&(a._isJoined()||a._isJoining()));s&&(this.log("transport",`leaving duplicate topic "${t}"`),s.unsubscribe())}_remove(t){this.channels=this.channels.filter(s=>s.topic!==t.topic)}_onConnMessage(t){this.decode(t.data,s=>{s.topic==="phoenix"&&s.event==="phx_reply"&&this.heartbeatCallback(s.payload.status==="ok"?"ok":"error"),s.ref&&s.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:a,event:n,payload:i,ref:o}=s,l=o?`(${o})`:"",c=i.status||"";this.log("receive",`${c} ${a} ${n} ${l}`.trim(),i),this.channels.filter(u=>u._isMember(a)).forEach(u=>u._trigger(n,i,o)),this._triggerStateCallbacks("message",s)})}_clearTimer(t){var s;t==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):t==="reconnect"&&((s=this.reconnectTimer)===null||s===void 0||s.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(t=>t.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=s=>{this.log("worker","worker error",s.message),this.workerRef.terminate()},this.workerRef.onmessage=s=>{s.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(t){var s;this._setConnectionState("disconnected"),this.log("transport","close",t),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(s=this.reconnectTimer)===null||s===void 0||s.scheduleTimeout(),this._triggerStateCallbacks("close",t)}_onConnError(t){this._setConnectionState("disconnected"),this.log("transport",`${t}`),this._triggerChanError(),this._triggerStateCallbacks("error",t)}_triggerChanError(){this.channels.forEach(t=>t._trigger(Is.error))}_appendParams(t,s){if(Object.keys(s).length===0)return t;const a=t.match(/\?/)?"&":"?",n=new URLSearchParams(s);return`${t}${a}${n}`}_workerObjectUrl(t){let s;if(t)s=t;else{const a=new Blob([hb],{type:"application/javascript"});s=URL.createObjectURL(a)}return s}_setConnectionState(t,s=!1){this._connectionState=t,t==="connecting"?this._wasManualDisconnect=!1:t==="disconnecting"&&(this._wasManualDisconnect=s)}async _performAuth(t=null){let s;t?s=t:this.accessToken?s=await this.accessToken():s=this.accessTokenValue,this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(a=>{const n={access_token:s,version:Qy};s&&a.updateJoinPayload(n),a.joinedOnce&&a._isJoined()&&a._push(Is.access_token,{access_token:s})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this.setAuth().catch(s=>{this.log("error",`error setting auth in ${t}`,s)})}_triggerStateCallbacks(t,s){try{this.stateChangeCallbacks[t].forEach(a=>{try{a(s)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(a){this.log("error",`error triggering ${t} callbacks`,a)}}_setupReconnectionTimer(){this.reconnectTimer=new dm(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},rn.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(t){var s,a,n,i,o,l,c,u;if(this.transport=(s=t==null?void 0:t.transport)!==null&&s!==void 0?s:null,this.timeout=(a=t==null?void 0:t.timeout)!==null&&a!==void 0?a:oo,this.heartbeatIntervalMs=(n=t==null?void 0:t.heartbeatIntervalMs)!==null&&n!==void 0?n:rn.HEARTBEAT_INTERVAL,this.worker=(i=t==null?void 0:t.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=t==null?void 0:t.accessToken)!==null&&o!==void 0?o:null,t!=null&&t.params&&(this.params=t.params),t!=null&&t.logger&&(this.logger=t.logger),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=t==null?void 0:t.reconnectAfterMs)!==null&&l!==void 0?l:d=>db[d-1]||ub,this.encode=(c=t==null?void 0:t.encode)!==null&&c!==void 0?c:(d,h)=>h(JSON.stringify(d)),this.decode=(u=t==null?void 0:t.decode)!==null&&u!==void 0?u:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl}}}class vl extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function Kt(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}class pb extends vl{constructor(t,s,a){super(t),this.name="StorageApiError",this.status=s,this.statusCode=a}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class uo extends vl{constructor(t,s){super(t),this.name="StorageUnknownError",this.originalError=s}}var gb=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};const mm=r=>{let t;return r?t=r:typeof fetch>"u"?t=(...s)=>ta(async()=>{const{default:a}=await Promise.resolve().then(()=>sa);return{default:a}},void 0).then(({default:a})=>a(...s)):t=fetch,(...s)=>t(...s)},fb=()=>gb(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ta(()=>Promise.resolve().then(()=>sa),void 0)).Response:Response}),ho=r=>{if(Array.isArray(r))return r.map(s=>ho(s));if(typeof r=="function"||r!==Object(r))return r;const t={};return Object.entries(r).forEach(([s,a])=>{const n=s.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[n]=ho(a)}),t},xb=r=>{if(typeof r!="object"||r===null)return!1;const t=Object.getPrototypeOf(r);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)};var jr=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};const vi=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),yb=(r,t,s)=>jr(void 0,void 0,void 0,function*(){const a=yield fb();r instanceof a&&!(s!=null&&s.noResolveJson)?r.json().then(n=>{const i=r.status||500,o=(n==null?void 0:n.statusCode)||i+"";t(new pb(vi(n),i,o))}).catch(n=>{t(new uo(vi(n),n))}):t(new uo(vi(r),r))}),bb=(r,t,s,a)=>{const n={method:r,headers:(t==null?void 0:t.headers)||{}};return r==="GET"||!a?n:(xb(a)?(n.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),n.body=JSON.stringify(a)):n.body=a,t!=null&&t.duplex&&(n.duplex=t.duplex),Object.assign(Object.assign({},n),s))};function za(r,t,s,a,n,i){return jr(this,void 0,void 0,function*(){return new Promise((o,l)=>{r(s,bb(t,a,n,i)).then(c=>{if(!c.ok)throw c;return a!=null&&a.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>yb(c,l,a))})})}function An(r,t,s,a){return jr(this,void 0,void 0,function*(){return za(r,"GET",t,s,a)})}function Ds(r,t,s,a,n){return jr(this,void 0,void 0,function*(){return za(r,"POST",t,a,n,s)})}function mo(r,t,s,a,n){return jr(this,void 0,void 0,function*(){return za(r,"PUT",t,a,n,s)})}function vb(r,t,s,a){return jr(this,void 0,void 0,function*(){return za(r,"HEAD",t,Object.assign(Object.assign({},s),{noResolveJson:!0}),a)})}function pm(r,t,s,a,n){return jr(this,void 0,void 0,function*(){return za(r,"DELETE",t,a,n,s)})}var hs=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};const wb={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yd={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class jb{constructor(t,s={},a,n){this.url=t,this.headers=s,this.bucketId=a,this.fetch=mm(n)}uploadOrUpdate(t,s,a,n){return hs(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},yd),n);let l=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(o.upsert)});const c=o.metadata;typeof Blob<"u"&&a instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",a)):typeof FormData<"u"&&a instanceof FormData?(i=a,i.append("cacheControl",o.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=a,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType,c&&(l["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),n!=null&&n.headers&&(l=Object.assign(Object.assign({},l),n.headers));const u=this._removeEmptyFolders(s),d=this._getFinalPath(u),h=yield(t=="PUT"?mo:Ds)(this.fetch,`${this.url}/object/${d}`,i,Object.assign({headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{data:{path:u,id:h.Id,fullPath:h.Key},error:null}}catch(i){if(Kt(i))return{data:null,error:i};throw i}})}upload(t,s,a){return hs(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,s,a)})}uploadToSignedUrl(t,s,a,n){return hs(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(t),o=this._getFinalPath(i),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",s);try{let c;const u=Object.assign({upsert:yd.upsert},n),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&a instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",a)):typeof FormData<"u"&&a instanceof FormData?(c=a,c.append("cacheControl",u.cacheControl)):(c=a,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType);const h=yield mo(this.fetch,l.toString(),c,{headers:d});return{data:{path:i,fullPath:h.Key},error:null}}catch(c){if(Kt(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,s){return hs(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t);const n=Object.assign({},this.headers);s!=null&&s.upsert&&(n["x-upsert"]="true");const i=yield Ds(this.fetch,`${this.url}/object/upload/sign/${a}`,{},{headers:n}),o=new URL(this.url+i.url),l=o.searchParams.get("token");if(!l)throw new vl("No token returned by API");return{data:{signedUrl:o.toString(),path:t,token:l},error:null}}catch(a){if(Kt(a))return{data:null,error:a};throw a}})}update(t,s,a){return hs(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,s,a)})}move(t,s,a){return hs(this,void 0,void 0,function*(){try{return{data:yield Ds(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:s,destinationBucket:a==null?void 0:a.destinationBucket},{headers:this.headers}),error:null}}catch(n){if(Kt(n))return{data:null,error:n};throw n}})}copy(t,s,a){return hs(this,void 0,void 0,function*(){try{return{data:{path:(yield Ds(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:s,destinationBucket:a==null?void 0:a.destinationBucket},{headers:this.headers})).Key},error:null}}catch(n){if(Kt(n))return{data:null,error:n};throw n}})}createSignedUrl(t,s,a){return hs(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t),i=yield Ds(this.fetch,`${this.url}/object/sign/${n}`,Object.assign({expiresIn:s},a!=null&&a.transform?{transform:a.transform}:{}),{headers:this.headers});const o=a!=null&&a.download?`&download=${a.download===!0?"":a.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(n){if(Kt(n))return{data:null,error:n};throw n}})}createSignedUrls(t,s,a){return hs(this,void 0,void 0,function*(){try{const n=yield Ds(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:s,paths:t},{headers:this.headers}),i=a!=null&&a.download?`&download=${a.download===!0?"":a.download}`:"";return{data:n.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(n){if(Kt(n))return{data:null,error:n};throw n}})}download(t,s){return hs(this,void 0,void 0,function*(){const n=typeof(s==null?void 0:s.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((s==null?void 0:s.transform)||{}),o=i?`?${i}`:"";try{const l=this._getFinalPath(t);return{data:yield(yield An(this.fetch,`${this.url}/${n}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(Kt(l))return{data:null,error:l};throw l}})}info(t){return hs(this,void 0,void 0,function*(){const s=this._getFinalPath(t);try{const a=yield An(this.fetch,`${this.url}/object/info/${s}`,{headers:this.headers});return{data:ho(a),error:null}}catch(a){if(Kt(a))return{data:null,error:a};throw a}})}exists(t){return hs(this,void 0,void 0,function*(){const s=this._getFinalPath(t);try{return yield vb(this.fetch,`${this.url}/object/${s}`,{headers:this.headers}),{data:!0,error:null}}catch(a){if(Kt(a)&&a instanceof uo){const n=a.originalError;if([400,404].includes(n==null?void 0:n.status))return{data:!1,error:a}}throw a}})}getPublicUrl(t,s){const a=this._getFinalPath(t),n=[],i=s!=null&&s.download?`download=${s.download===!0?"":s.download}`:"";i!==""&&n.push(i);const l=typeof(s==null?void 0:s.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((s==null?void 0:s.transform)||{});c!==""&&n.push(c);let u=n.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${a}${u}`)}}}remove(t){return hs(this,void 0,void 0,function*(){try{return{data:yield pm(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(s){if(Kt(s))return{data:null,error:s};throw s}})}list(t,s,a){return hs(this,void 0,void 0,function*(){try{const n=Object.assign(Object.assign(Object.assign({},wb),s),{prefix:t||""});return{data:yield Ds(this.fetch,`${this.url}/object/list/${this.bucketId}`,n,{headers:this.headers},a),error:null}}catch(n){if(Kt(n))return{data:null,error:n};throw n}})}listV2(t,s){return hs(this,void 0,void 0,function*(){try{const a=Object.assign({},t);return{data:yield Ds(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,a,{headers:this.headers},s),error:null}}catch(a){if(Kt(a))return{data:null,error:a};throw a}})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const s=[];return t.width&&s.push(`width=${t.width}`),t.height&&s.push(`height=${t.height}`),t.resize&&s.push(`resize=${t.resize}`),t.format&&s.push(`format=${t.format}`),t.quality&&s.push(`quality=${t.quality}`),s.join("&")}}const Nb="2.11.0",kb={"X-Client-Info":`storage-js/${Nb}`};var Ar=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};class _b{constructor(t,s={},a,n){const i=new URL(t);n!=null&&n.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),this.url=i.href,this.headers=Object.assign(Object.assign({},kb),s),this.fetch=mm(a)}listBuckets(){return Ar(this,void 0,void 0,function*(){try{return{data:yield An(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(Kt(t))return{data:null,error:t};throw t}})}getBucket(t){return Ar(this,void 0,void 0,function*(){try{return{data:yield An(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(s){if(Kt(s))return{data:null,error:s};throw s}})}createBucket(t,s={public:!1}){return Ar(this,void 0,void 0,function*(){try{return{data:yield Ds(this.fetch,`${this.url}/bucket`,{id:t,name:t,type:s.type,public:s.public,file_size_limit:s.fileSizeLimit,allowed_mime_types:s.allowedMimeTypes},{headers:this.headers}),error:null}}catch(a){if(Kt(a))return{data:null,error:a};throw a}})}updateBucket(t,s){return Ar(this,void 0,void 0,function*(){try{return{data:yield mo(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:s.public,file_size_limit:s.fileSizeLimit,allowed_mime_types:s.allowedMimeTypes},{headers:this.headers}),error:null}}catch(a){if(Kt(a))return{data:null,error:a};throw a}})}emptyBucket(t){return Ar(this,void 0,void 0,function*(){try{return{data:yield Ds(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(s){if(Kt(s))return{data:null,error:s};throw s}})}deleteBucket(t){return Ar(this,void 0,void 0,function*(){try{return{data:yield pm(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(s){if(Kt(s))return{data:null,error:s};throw s}})}}class Sb extends _b{constructor(t,s={},a,n){super(t,s,a,n)}from(t){return new jb(this.url,this.headers,t,this.fetch)}}const Cb="2.56.0";let ga="";typeof Deno<"u"?ga="deno":typeof document<"u"?ga="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ga="react-native":ga="node";const Pb={"X-Client-Info":`supabase-js-${ga}/${Cb}`},Eb={headers:Pb},Tb={schema:"public"},Ab={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ib={};var Rb=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};const $b=r=>{let t;return r?t=r:typeof fetch>"u"?t=Qh:t=fetch,(...s)=>t(...s)},Lb=()=>typeof Headers>"u"?em:Headers,Ob=(r,t,s)=>{const a=$b(s),n=Lb();return(i,o)=>Rb(void 0,void 0,void 0,function*(){var l;const c=(l=yield t())!==null&&l!==void 0?l:r;let u=new n(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",r),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),a(i,Object.assign(Object.assign({},o),{headers:u}))})};var Mb=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};function Bb(r){return r.endsWith("/")?r:r+"/"}function Fb(r,t){var s,a;const{db:n,auth:i,realtime:o,global:l}=r,{db:c,auth:u,realtime:d,global:h}=t,m={db:Object.assign(Object.assign({},c),n),auth:Object.assign(Object.assign({},u),i),realtime:Object.assign(Object.assign({},d),o),storage:{},global:Object.assign(Object.assign(Object.assign({},h),l),{headers:Object.assign(Object.assign({},(s=h==null?void 0:h.headers)!==null&&s!==void 0?s:{}),(a=l==null?void 0:l.headers)!==null&&a!==void 0?a:{})}),accessToken:()=>Mb(this,void 0,void 0,function*(){return""})};return r.accessToken?m.accessToken=r.accessToken:delete m.accessToken,m}const gm="2.71.1",Mr=30*1e3,po=3,wi=po*Mr,Db="http://localhost:9999",Gb="supabase.auth.token",Ub={"X-Client-Info":`gotrue-js/${gm}`},go="X-Supabase-Api-Version",fm={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Vb=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,zb=10*60*1e3;class wl extends Error{constructor(t,s,a){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=s,this.code=a}}function Je(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}class Wb extends wl{constructor(t,s,a){super(t,s,a),this.name="AuthApiError",this.status=s,this.code=a}}function qb(r){return Je(r)&&r.name==="AuthApiError"}class xm extends wl{constructor(t,s){super(t),this.name="AuthUnknownError",this.originalError=s}}class lr extends wl{constructor(t,s,a,n){super(t,a,n),this.name=s,this.status=a}}class rr extends lr{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Hb(r){return Je(r)&&r.name==="AuthSessionMissingError"}class an extends lr{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class nn extends lr{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class on extends lr{constructor(t,s=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=s}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Kb(r){return Je(r)&&r.name==="AuthImplicitGrantRedirectError"}class bd extends lr{constructor(t,s=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=s}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class fo extends lr{constructor(t,s){super(t,"AuthRetryableFetchError",s,void 0)}}function ji(r){return Je(r)&&r.name==="AuthRetryableFetchError"}class vd extends lr{constructor(t,s,a){super(t,"AuthWeakPasswordError",s,"weak_password"),this.reasons=a}}class xo extends lr{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const In="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),wd=` 	
\r=`.split(""),Yb=(()=>{const r=new Array(128);for(let t=0;t<r.length;t+=1)r[t]=-1;for(let t=0;t<wd.length;t+=1)r[wd[t].charCodeAt(0)]=-2;for(let t=0;t<In.length;t+=1)r[In[t].charCodeAt(0)]=t;return r})();function jd(r,t,s){if(r!==null)for(t.queue=t.queue<<8|r,t.queuedBits+=8;t.queuedBits>=6;){const a=t.queue>>t.queuedBits-6&63;s(In[a]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const a=t.queue>>t.queuedBits-6&63;s(In[a]),t.queuedBits-=6}}function ym(r,t,s){const a=Yb[r];if(a>-1)for(t.queue=t.queue<<6|a,t.queuedBits+=6;t.queuedBits>=8;)s(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(a===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function Nd(r){const t=[],s=o=>{t.push(String.fromCodePoint(o))},a={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=o=>{Xb(o,a,s)};for(let o=0;o<r.length;o+=1)ym(r.charCodeAt(o),n,i);return t.join("")}function Jb(r,t){if(r<=127){t(r);return}else if(r<=2047){t(192|r>>6),t(128|r&63);return}else if(r<=65535){t(224|r>>12),t(128|r>>6&63),t(128|r&63);return}else if(r<=1114111){t(240|r>>18),t(128|r>>12&63),t(128|r>>6&63),t(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function Zb(r,t){for(let s=0;s<r.length;s+=1){let a=r.charCodeAt(s);if(a>55295&&a<=56319){const n=(a-55296)*1024&65535;a=(r.charCodeAt(s+1)-56320&65535|n)+65536,s+=1}Jb(a,t)}}function Xb(r,t,s){if(t.utf8seq===0){if(r<=127){s(r);return}for(let a=1;a<6;a+=1)if(!(r>>7-a&1)){t.utf8seq=a;break}if(t.utf8seq===2)t.codepoint=r&31;else if(t.utf8seq===3)t.codepoint=r&15;else if(t.utf8seq===4)t.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|r&63,t.utf8seq-=1,t.utf8seq===0&&s(t.codepoint)}}function Qb(r){const t=[],s={queue:0,queuedBits:0},a=n=>{t.push(n)};for(let n=0;n<r.length;n+=1)ym(r.charCodeAt(n),s,a);return new Uint8Array(t)}function ev(r){const t=[];return Zb(r,s=>t.push(s)),new Uint8Array(t)}function tv(r){const t=[],s={queue:0,queuedBits:0},a=n=>{t.push(n)};return r.forEach(n=>jd(n,s,a)),jd(null,s,a),t.join("")}function sv(r){return Math.round(Date.now()/1e3)+r}function rv(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){const t=Math.random()*16|0;return(r=="x"?t:t&3|8).toString(16)})}const Es=()=>typeof window<"u"&&typeof document<"u",dr={tested:!1,writable:!1},bm=()=>{if(!Es())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(dr.tested)return dr.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),dr.tested=!0,dr.writable=!0}catch{dr.tested=!0,dr.writable=!1}return dr.writable};function av(r){const t={},s=new URL(r);if(s.hash&&s.hash[0]==="#")try{new URLSearchParams(s.hash.substring(1)).forEach((n,i)=>{t[i]=n})}catch{}return s.searchParams.forEach((a,n)=>{t[n]=a}),t}const vm=r=>{let t;return r?t=r:typeof fetch>"u"?t=(...s)=>ta(async()=>{const{default:a}=await Promise.resolve().then(()=>sa);return{default:a}},void 0).then(({default:a})=>a(...s)):t=fetch,(...s)=>t(...s)},nv=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Br=async(r,t,s)=>{await r.setItem(t,JSON.stringify(s))},ur=async(r,t)=>{const s=await r.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch{return s}},tr=async(r,t)=>{await r.removeItem(t)};class Hn{constructor(){this.promise=new Hn.promiseConstructor((t,s)=>{this.resolve=t,this.reject=s})}}Hn.promiseConstructor=Promise;function Ni(r){const t=r.split(".");if(t.length!==3)throw new xo("Invalid JWT structure");for(let a=0;a<t.length;a++)if(!Vb.test(t[a]))throw new xo("JWT not in base64url format");return{header:JSON.parse(Nd(t[0])),payload:JSON.parse(Nd(t[1])),signature:Qb(t[2]),raw:{header:t[0],payload:t[1]}}}async function iv(r){return await new Promise(t=>{setTimeout(()=>t(null),r)})}function ov(r,t){return new Promise((a,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await r(i);if(!t(i,null,o)){a(o);return}}catch(o){if(!t(i,o)){n(o);return}}})()})}function lv(r){return("0"+r.toString(16)).substr(-2)}function cv(){const t=new Uint32Array(56);if(typeof crypto>"u"){const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",a=s.length;let n="";for(let i=0;i<56;i++)n+=s.charAt(Math.floor(Math.random()*a));return n}return crypto.getRandomValues(t),Array.from(t,lv).join("")}async function dv(r){const s=new TextEncoder().encode(r),a=await crypto.subtle.digest("SHA-256",s),n=new Uint8Array(a);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function uv(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;const s=await dv(r);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ir(r,t,s=!1){const a=cv();let n=a;s&&(n+="/PASSWORD_RECOVERY"),await Br(r,`${t}-code-verifier`,n);const i=await uv(a);return[i,a===i?"plain":"s256"]}const hv=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function mv(r){const t=r.headers.get(go);if(!t||!t.match(hv))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function pv(r){if(!r)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(r<=t)throw new Error("JWT has expired")}function gv(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const fv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Rr(r){if(!fv.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ki(){const r={};return new Proxy(r,{get:(t,s)=>{if(s==="__isUserNotAvailableProxy")return!0;if(typeof s=="symbol"){const a=s.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${s}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,s)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${s}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,s)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${s}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function kd(r){return JSON.parse(JSON.stringify(r))}var xv=function(r,t){var s={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(s[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,a=Object.getOwnPropertySymbols(r);n<a.length;n++)t.indexOf(a[n])<0&&Object.prototype.propertyIsEnumerable.call(r,a[n])&&(s[a[n]]=r[a[n]]);return s};const pr=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),yv=[502,503,504];async function _d(r){var t;if(!nv(r))throw new fo(pr(r),0);if(yv.includes(r.status))throw new fo(pr(r),r.status);let s;try{s=await r.json()}catch(i){throw new xm(pr(i),i)}let a;const n=mv(r);if(n&&n.getTime()>=fm["2024-01-01"].timestamp&&typeof s=="object"&&s&&typeof s.code=="string"?a=s.code:typeof s=="object"&&s&&typeof s.error_code=="string"&&(a=s.error_code),a){if(a==="weak_password")throw new vd(pr(s),r.status,((t=s.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(a==="session_not_found")throw new rr}else if(typeof s=="object"&&s&&typeof s.weak_password=="object"&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new vd(pr(s),r.status,s.weak_password.reasons);throw new Wb(pr(s),r.status||500,a)}const bv=(r,t,s,a)=>{const n={method:r,headers:(t==null?void 0:t.headers)||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),n.body=JSON.stringify(a),Object.assign(Object.assign({},n),s))};async function it(r,t,s,a){var n;const i=Object.assign({},a==null?void 0:a.headers);i[go]||(i[go]=fm["2024-01-01"].name),a!=null&&a.jwt&&(i.Authorization=`Bearer ${a.jwt}`);const o=(n=a==null?void 0:a.query)!==null&&n!==void 0?n:{};a!=null&&a.redirectTo&&(o.redirect_to=a.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await vv(r,t,s+l,{headers:i,noResolveJson:a==null?void 0:a.noResolveJson},{},a==null?void 0:a.body);return a!=null&&a.xform?a==null?void 0:a.xform(c):{data:Object.assign({},c),error:null}}async function vv(r,t,s,a,n,i){const o=bv(t,a,n,i);let l;try{l=await r(s,Object.assign({},o))}catch(c){throw console.error(c),new fo(pr(c),0)}if(l.ok||await _d(l),a!=null&&a.noResolveJson)return l;try{return await l.json()}catch(c){await _d(c)}}function Ks(r){var t;let s=null;kv(r)&&(s=Object.assign({},r),r.expires_at||(s.expires_at=sv(r.expires_in)));const a=(t=r.user)!==null&&t!==void 0?t:r;return{data:{session:s,user:a},error:null}}function Sd(r){const t=Ks(r);return!t.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((s,a)=>s&&typeof a=="string",!0)&&(t.data.weak_password=r.weak_password),t}function ar(r){var t;return{data:{user:(t=r.user)!==null&&t!==void 0?t:r},error:null}}function wv(r){return{data:r,error:null}}function jv(r){const{action_link:t,email_otp:s,hashed_token:a,redirect_to:n,verification_type:i}=r,o=xv(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:s,hashed_token:a,redirect_to:n,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function Nv(r){return r}function kv(r){return r.access_token&&r.refresh_token&&r.expires_in}const _i=["global","local","others"];var _v=function(r,t){var s={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(s[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,a=Object.getOwnPropertySymbols(r);n<a.length;n++)t.indexOf(a[n])<0&&Object.prototype.propertyIsEnumerable.call(r,a[n])&&(s[a[n]]=r[a[n]]);return s};class Sv{constructor({url:t="",headers:s={},fetch:a}){this.url=t,this.headers=s,this.fetch=vm(a),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(t,s=_i[0]){if(_i.indexOf(s)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${_i.join(", ")}`);try{return await it(this.fetch,"POST",`${this.url}/logout?scope=${s}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(a){if(Je(a))return{data:null,error:a};throw a}}async inviteUserByEmail(t,s={}){try{return await it(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:s.data},headers:this.headers,redirectTo:s.redirectTo,xform:ar})}catch(a){if(Je(a))return{data:{user:null},error:a};throw a}}async generateLink(t){try{const{options:s}=t,a=_v(t,["options"]),n=Object.assign(Object.assign({},a),s);return"newEmail"in a&&(n.new_email=a==null?void 0:a.newEmail,delete n.newEmail),await it(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:jv,redirectTo:s==null?void 0:s.redirectTo})}catch(s){if(Je(s))return{data:{properties:null,user:null},error:s};throw s}}async createUser(t){try{return await it(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:ar})}catch(s){if(Je(s))return{data:{user:null},error:s};throw s}}async listUsers(t){var s,a,n,i,o,l,c;try{const u={nextPage:null,lastPage:0,total:0},d=await it(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(s=t==null?void 0:t.page)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:"",per_page:(i=(n=t==null?void 0:t.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Nv});if(d.error)throw d.error;const h=await d.json(),m=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return g.length>0&&(g.forEach(f=>{const v=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(f.split(";")[1].split("=")[1]);u[`${x}Page`]=v}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(Je(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){Rr(t);try{return await it(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:ar})}catch(s){if(Je(s))return{data:{user:null},error:s};throw s}}async updateUserById(t,s){Rr(t);try{return await it(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:s,headers:this.headers,xform:ar})}catch(a){if(Je(a))return{data:{user:null},error:a};throw a}}async deleteUser(t,s=!1){Rr(t);try{return await it(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:s},xform:ar})}catch(a){if(Je(a))return{data:{user:null},error:a};throw a}}async _listFactors(t){Rr(t.userId);try{const{data:s,error:a}=await it(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:s,error:a}}catch(s){if(Je(s))return{data:null,error:s};throw s}}async _deleteFactor(t){Rr(t.userId),Rr(t.id);try{return{data:await it(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(s){if(Je(s))return{data:null,error:s};throw s}}}function Cd(r={}){return{getItem:t=>r[t]||null,setItem:(t,s)=>{r[t]=s},removeItem:t=>{delete r[t]}}}function Cv(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const $r={debug:!!(globalThis&&bm()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class wm extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class Pv extends wm{}async function Ev(r,t,s){$r.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,t);const a=new globalThis.AbortController;return t>0&&setTimeout(()=>{a.abort(),$r.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:a.signal},async n=>{if(n){$r.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,n.name);try{return await s()}finally{$r.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,n.name)}}else{if(t===0)throw $r.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Pv(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if($r.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null,"  "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await s()}}))}Cv();const Tv={url:Db,storageKey:Gb,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ub,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Pd(r,t,s){return await s()}const Lr={};class La{constructor(t){var s,a;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=La.nextInstanceID,La.nextInstanceID+=1,this.instanceID>0&&Es()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const n=Object.assign(Object.assign({},Tv),t);if(this.logDebugMessages=!!n.debug,typeof n.debug=="function"&&(this.logger=n.debug),this.persistSession=n.persistSession,this.storageKey=n.storageKey,this.autoRefreshToken=n.autoRefreshToken,this.admin=new Sv({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=vm(n.fetch),this.lock=n.lock||Pd,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,n.lock?this.lock=n.lock:Es()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Ev:this.lock=Pd,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?(n.storage?this.storage=n.storage:bm()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Cd(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=Cd(this.memoryStorage)),Es()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}get jwks(){var t,s;return(s=(t=Lr[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&s!==void 0?s:{keys:[]}}set jwks(t){Lr[this.storageKey]=Object.assign(Object.assign({},Lr[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,s;return(s=(t=Lr[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&s!==void 0?s:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){Lr[this.storageKey]=Object.assign(Object.assign({},Lr[this.storageKey]),{cachedAt:t})}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${gm}) ${new Date().toISOString()}`,...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{const s=av(window.location.href);let a="none";if(this._isImplicitGrantCallback(s)?a="implicit":await this._isPKCECallback(s)&&(a="pkce"),Es()&&this.detectSessionInUrl&&a!=="none"){const{data:n,error:i}=await this._getSessionFromURL(s,a);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Kb(i)){const c=(t=i.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:l}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(s){return Je(s)?{error:s}:{error:new xm("Unexpected error during initialization",s)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var s,a,n;try{const i=await it(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(a=(s=t==null?void 0:t.options)===null||s===void 0?void 0:s.data)!==null&&a!==void 0?a:{},gotrue_meta_security:{captcha_token:(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.captchaToken}},xform:Ks}),{data:o,error:l}=i;if(l||!o)return{data:{user:null,session:null},error:l};const c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(Je(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var s,a,n;try{let i;if("email"in t){const{email:d,password:h,options:m}=t;let g=null,f=null;this.flowType==="pkce"&&([g,f]=await Ir(this.storage,this.storageKey)),i=await it(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:d,password:h,data:(s=m==null?void 0:m.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:g,code_challenge_method:f},xform:Ks})}else if("phone"in t){const{phone:d,password:h,options:m}=t;i=await it(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(a=m==null?void 0:m.data)!==null&&a!==void 0?a:{},channel:(n=m==null?void 0:m.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken}},xform:Ks})}else throw new nn("You must provide either an email or phone number and a password");const{data:o,error:l}=i;if(l||!o)return{data:{user:null,session:null},error:l};const c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(Je(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(t){try{let s;if("email"in t){const{email:i,password:o,options:l}=t;s=await it(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Sd})}else if("phone"in t){const{phone:i,password:o,options:l}=t;s=await it(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Sd})}else throw new nn("You must provide either an email or phone number and a password");const{data:a,error:n}=s;return n?{data:{user:null,session:null},error:n}:!a||!a.session||!a.user?{data:{user:null,session:null},error:new an}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:Object.assign({user:a.user,session:a.session},a.weak_password?{weakPassword:a.weak_password}:null),error:n})}catch(s){if(Je(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithOAuth(t){var s,a,n,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(s=t.options)===null||s===void 0?void 0:s.redirectTo,scopes:(a=t.options)===null||a===void 0?void 0:a.scopes,queryParams:(n=t.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async signInWithWeb3(t){const{chain:s}=t;if(s==="solana")return await this.signInWithSolana(t);throw new Error(`@supabase/auth-js: Unsupported chain "${s}"`)}async signInWithSolana(t){var s,a,n,i,o,l,c,u,d,h,m,g;let f,v;if("message"in t)f=t.message,v=t.signature;else{const{chain:x,wallet:j,statement:b,options:y}=t;let S;if(Es())if(typeof j=="object")S=j;else{const I=window;if("solana"in I&&typeof I.solana=="object"&&("signIn"in I.solana&&typeof I.solana.signIn=="function"||"signMessage"in I.solana&&typeof I.solana.signMessage=="function"))S=I.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof j!="object"||!(y!=null&&y.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=j}const T=new URL((s=y==null?void 0:y.url)!==null&&s!==void 0?s:window.location.href);if("signIn"in S&&S.signIn){const I=await S.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y==null?void 0:y.signInWithSolana),{version:"1",domain:T.host,uri:T.href}),b?{statement:b}:null));let E;if(Array.isArray(I)&&I[0]&&typeof I[0]=="object")E=I[0];else if(I&&typeof I=="object"&&"signedMessage"in I&&"signature"in I)E=I;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)f=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),v=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in S)||typeof S.signMessage!="function"||!("publicKey"in S)||typeof S!="object"||!S.publicKey||!("toBase58"in S.publicKey)||typeof S.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${T.host} wants you to sign in with your Solana account:`,S.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${T.href}`,`Issued At: ${(n=(a=y==null?void 0:y.signInWithSolana)===null||a===void 0?void 0:a.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=y==null?void 0:y.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...!((o=y==null?void 0:y.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...!((l=y==null?void 0:y.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...!((c=y==null?void 0:y.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...!((u=y==null?void 0:y.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...!((h=(d=y==null?void 0:y.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...y.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
`);const I=await S.signMessage(new TextEncoder().encode(f),"utf8");if(!I||!(I instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=I}}try{const{data:x,error:j}=await it(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:tv(v)},!((m=t.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(g=t.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:Ks});if(j)throw j;return!x||!x.session||!x.user?{data:{user:null,session:null},error:new an}:(x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),{data:Object.assign({},x),error:j})}catch(x){if(Je(x))return{data:{user:null,session:null},error:x};throw x}}async _exchangeCodeForSession(t){const s=await ur(this.storage,`${this.storageKey}-code-verifier`),[a,n]=(s??"").split("/");try{const{data:i,error:o}=await it(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:a},xform:Ks});if(await tr(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new an}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}catch(i){if(Je(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(t){try{const{options:s,provider:a,token:n,access_token:i,nonce:o}=t,l=await it(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:a,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:Ks}),{data:c,error:u}=l;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new an}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(s){if(Je(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithOtp(t){var s,a,n,i,o;try{if("email"in t){const{email:l,options:c}=t;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Ir(this.storage,this.storageKey));const{error:h}=await it(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(a=c==null?void 0:c.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in t){const{phone:l,options:c}=t,{data:u,error:d}=await it(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(o=c==null?void 0:c.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d}}throw new nn("You must provide either an email or phone number.")}catch(l){if(Je(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(t){var s,a;try{let n,i;"options"in t&&(n=(s=t.options)===null||s===void 0?void 0:s.redirectTo,i=(a=t.options)===null||a===void 0?void 0:a.captchaToken);const{data:o,error:l}=await it(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Ks});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const c=o.session,u=o.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(Je(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithSSO(t){var s,a,n;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await Ir(this.storage,this.storageKey)),await it(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(a=(s=t.options)===null||s===void 0?void 0:s.redirectTo)!==null&&a!==void 0?a:void 0}),!((n=t==null?void 0:t.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:wv})}catch(i){if(Je(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:s},error:a}=t;if(a)throw a;if(!s)throw new rr;const{error:n}=await it(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:s.access_token});return{data:{user:null,session:null},error:n}})}catch(t){if(Je(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{const s=`${this.url}/resend`;if("email"in t){const{email:a,type:n,options:i}=t,{error:o}=await it(this.fetch,"POST",s,{headers:this.headers,body:{email:a,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in t){const{phone:a,type:n,options:i}=t,{data:o,error:l}=await it(this.fetch,"POST",s,{headers:this.headers,body:{phone:a,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l}}throw new nn("You must provide either an email or phone number and a type")}catch(s){if(Je(s))return{data:{user:null,session:null},error:s};throw s}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async s=>s))}async _acquireLock(t,s){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const a=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await a,await s()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const a=s();for(this.pendingInLock.push((async()=>{try{await a}catch{}})()),await a;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await a}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const s=await this.__loadSession();return await t(s)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const s=await ur(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",s),s!==null&&(this._isValidSession(s)?t=s:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const a=t.expires_at?t.expires_at*1e3-Date.now()<wi:!1;if(this._debug("#__loadSession()",`session has${a?"":" not"} expired`,"expires_at",t.expires_at),!a){if(this.userStorage){const o=await ur(this.userStorage,this.storageKey+"-user");o!=null&&o.user?t.user=o.user:t.user=ki()}if(this.storage.isServer&&t.user){let o=this.suppressGetSessionWarning;t=new Proxy(t,{get:(c,u,d)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,d))})}return{data:{session:t},error:null}}const{session:n,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{session:null},error:i}:{data:{session:n},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await it(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:ar}):await this._useSession(async s=>{var a,n,i;const{data:o,error:l}=s;if(l)throw l;return!(!((a=o.session)===null||a===void 0)&&a.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new rr}:await it(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:ar})})}catch(s){if(Je(s))return Hb(s)&&(await this._removeSession(),await tr(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:s};throw s}}async updateUser(t,s={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,s))}async _updateUser(t,s={}){try{return await this._useSession(async a=>{const{data:n,error:i}=a;if(i)throw i;if(!n.session)throw new rr;const o=n.session;let l=null,c=null;this.flowType==="pkce"&&t.email!=null&&([l,c]=await Ir(this.storage,this.storageKey));const{data:u,error:d}=await it(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:s==null?void 0:s.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:l,code_challenge_method:c}),jwt:o.access_token,xform:ar});if(d)throw d;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(a){if(Je(a))return{data:{user:null},error:a};throw a}}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new rr;const s=Date.now()/1e3;let a=s,n=!0,i=null;const{payload:o}=Ni(t.access_token);if(o.exp&&(a=o.exp,n=a<=s),n){const{session:l,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:c}=await this._getUser(t.access_token);if(c)throw c;i={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:a-s,expires_at:a},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(s){if(Je(s))return{data:{session:null,user:null},error:s};throw s}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async s=>{var a;if(!t){const{data:o,error:l}=s;if(l)throw l;t=(a=o.session)!==null&&a!==void 0?a:void 0}if(!(t!=null&&t.refresh_token))throw new rr;const{session:n,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{user:null,session:null},error:i}:n?{data:{user:n.user,session:n},error:null}:{data:{user:null,session:null},error:null}})}catch(s){if(Je(s))return{data:{user:null,session:null},error:s};throw s}}async _getSessionFromURL(t,s){try{if(!Es())throw new on("No browser detected.");if(t.error||t.error_description||t.error_code)throw new on(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(s){case"implicit":if(this.flowType==="pkce")throw new bd("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new on("Not a valid implicit grant flow url.");break;default:}if(s==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new bd("No code detected.");const{data:b,error:y}=await this._exchangeCodeForSession(t.code);if(y)throw y;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:b.session,redirectType:null},error:null}}const{provider_token:a,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:l,expires_at:c,token_type:u}=t;if(!i||!l||!o||!u)throw new on("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(l);let m=d+h;c&&(m=parseInt(c));const g=m-d;g*1e3<=Mr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${h}s`);const f=m-h;d-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,m,d):d-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,m,d);const{data:v,error:x}=await this._getUser(i);if(x)throw x;const j={provider_token:a,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:m,refresh_token:o,token_type:u,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:j,redirectType:t.type},error:null}}catch(a){if(Je(a))return{data:{session:null,redirectType:null},error:a};throw a}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const s=await ur(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&s)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async s=>{var a;const{data:n,error:i}=s;if(i)return{error:i};const o=(a=n.session)===null||a===void 0?void 0:a.access_token;if(o){const{error:l}=await this.admin.signOut(o,t);if(l&&!(qb(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return t!=="others"&&(await this._removeSession(),await tr(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const s=rv(),a={id:s,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",s),this.stateChangeEmitters.delete(s)}};return this._debug("#onAuthStateChange()","registered callback with id",s),this.stateChangeEmitters.set(s,a),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(s)})))(),{data:{subscription:a}}}async _emitInitialSession(t){return await this._useSession(async s=>{var a,n;try{const{data:{session:i},error:o}=s;if(o)throw o;await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(t))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,s={}){let a=null,n=null;this.flowType==="pkce"&&([a,n]=await Ir(this.storage,this.storageKey,!0));try{return await it(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:a,code_challenge_method:n,gotrue_meta_security:{captcha_token:s.captchaToken}},headers:this.headers,redirectTo:s.redirectTo})}catch(i){if(Je(i))return{data:null,error:i};throw i}}async getUserIdentities(){var t;try{const{data:s,error:a}=await this.getUser();if(a)throw a;return{data:{identities:(t=s.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(s){if(Je(s))return{data:null,error:s};throw s}}async linkIdentity(t){var s;try{const{data:a,error:n}=await this._useSession(async i=>{var o,l,c,u,d;const{data:h,error:m}=i;if(m)throw m;const g=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=t.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await it(this.fetch,"GET",g,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return Es()&&!(!((s=t.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(a==null?void 0:a.url),{data:{provider:t.provider,url:a==null?void 0:a.url},error:null}}catch(a){if(Je(a))return{data:{provider:t.provider,url:null},error:a};throw a}}async unlinkIdentity(t){try{return await this._useSession(async s=>{var a,n;const{data:i,error:o}=s;if(o)throw o;return await it(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(n=(a=i.session)===null||a===void 0?void 0:a.access_token)!==null&&n!==void 0?n:void 0})})}catch(s){if(Je(s))return{data:null,error:s};throw s}}async _refreshAccessToken(t){const s=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(s,"begin");try{const a=Date.now();return await ov(async n=>(n>0&&await iv(200*Math.pow(2,n-1)),this._debug(s,"refreshing attempt",n),await it(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Ks})),(n,i)=>{const o=200*Math.pow(2,n);return i&&ji(i)&&Date.now()+o-a<Mr})}catch(a){if(this._debug(s,"error",a),Je(a))return{data:{session:null,user:null},error:a};throw a}finally{this._debug(s,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,s){const a=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:s.redirectTo,scopes:s.scopes,queryParams:s.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",s,"url",a),Es()&&!s.skipBrowserRedirect&&window.location.assign(a),{data:{provider:t,url:a},error:null}}async _recoverAndRefresh(){var t,s;const a="#_recoverAndRefresh()";this._debug(a,"begin");try{const n=await ur(this.storage,this.storageKey);if(n&&this.userStorage){let o=await ur(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await Br(this.userStorage,this.storageKey+"-user",o)),n.user=(t=o==null?void 0:o.user)!==null&&t!==void 0?t:ki()}else if(n&&!n.user&&!n.user){const o=await ur(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(n.user=o.user,await tr(this.storage,this.storageKey+"-user"),await Br(this.storage,this.storageKey,n)):n.user=ki()}if(this._debug(a,"session from storage",n),!this._isValidSession(n)){this._debug(a,"session is not valid"),n!==null&&await this._removeSession();return}const i=((s=n.expires_at)!==null&&s!==void 0?s:1/0)*1e3-Date.now()<wi;if(this._debug(a,`session has${i?"":" not"} expired with margin of ${wi}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),ji(o)||(this._debug(a,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:l}=await this._getUser(n.access_token);!l&&(o!=null&&o.user)?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(a,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(a,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(a,"error",n),console.error(n);return}finally{this._debug(a,"end")}}async _callRefreshToken(t){var s,a;if(!t)throw new rr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Hn;const{data:i,error:o}=await this._refreshAccessToken(t);if(o)throw o;if(!i.session)throw new rr;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={session:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(n,"error",i),Je(i)){const o={session:null,error:i};return ji(i)||await this._removeSession(),(s=this.refreshingDeferred)===null||s===void 0||s.resolve(o),o}throw(a=this.refreshingDeferred)===null||a===void 0||a.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(t,s,a=!0){const n=`#_notifyAllSubscribers(${t})`;this._debug(n,"begin",s,`broadcast = ${a}`);try{this.broadcastChannel&&a&&this.broadcastChannel.postMessage({event:t,session:s});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,s)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0;const s=Object.assign({},t),a=s.user&&s.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!a&&s.user&&await Br(this.userStorage,this.storageKey+"-user",{user:s.user});const n=Object.assign({},s);delete n.user;const i=kd(n);await Br(this.storage,this.storageKey,i)}else{const n=kd(s);await Br(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),await tr(this.storage,this.storageKey),await tr(this.storage,this.storageKey+"-code-verifier"),await tr(this.storage,this.storageKey+"-user"),this.userStorage&&await tr(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&Es()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}catch(s){console.error("removing visibilitychange callback failed",s)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Mr);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async s=>{const{data:{session:a}}=s;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((a.expires_at*1e3-t)/Mr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Mr}ms, refresh threshold is ${po} ticks`),n<=po&&await this._callRefreshToken(a.refresh_token)})}catch(s){console.error("Auto refresh tick failed with error. This is likely a transient error.",s)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof wm)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Es()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const s=`#_onVisibilityChanged(${t})`;this._debug(s,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(s,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,s,a){const n=[`provider=${encodeURIComponent(s)}`];if(a!=null&&a.redirectTo&&n.push(`redirect_to=${encodeURIComponent(a.redirectTo)}`),a!=null&&a.scopes&&n.push(`scopes=${encodeURIComponent(a.scopes)}`),this.flowType==="pkce"){const[i,o]=await Ir(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(l.toString())}if(a!=null&&a.queryParams){const i=new URLSearchParams(a.queryParams);n.push(i.toString())}return a!=null&&a.skipBrowserRedirect&&n.push(`skip_http_redirect=${a.skipBrowserRedirect}`),`${t}?${n.join("&")}`}async _unenroll(t){try{return await this._useSession(async s=>{var a;const{data:n,error:i}=s;return i?{data:null,error:i}:await it(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(a=n==null?void 0:n.session)===null||a===void 0?void 0:a.access_token})})}catch(s){if(Je(s))return{data:null,error:s};throw s}}async _enroll(t){try{return await this._useSession(async s=>{var a,n;const{data:i,error:o}=s;if(o)return{data:null,error:o};const l=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:{issuer:t.issuer}),{data:c,error:u}=await it(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(a=i==null?void 0:i.session)===null||a===void 0?void 0:a.access_token});return u?{data:null,error:u}:(t.factorType==="totp"&&(!((n=c==null?void 0:c.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(s){if(Je(s))return{data:null,error:s};throw s}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async s=>{var a;const{data:n,error:i}=s;if(i)return{data:null,error:i};const{data:o,error:l}=await it(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(a=n==null?void 0:n.session)===null||a===void 0?void 0:a.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(s){if(Je(s))return{data:null,error:s};throw s}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async s=>{var a;const{data:n,error:i}=s;return i?{data:null,error:i}:await it(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:{channel:t.channel},headers:this.headers,jwt:(a=n==null?void 0:n.session)===null||a===void 0?void 0:a.access_token})})}catch(s){if(Je(s))return{data:null,error:s};throw s}})}async _challengeAndVerify(t){const{data:s,error:a}=await this._challenge({factorId:t.factorId});return a?{data:null,error:a}:await this._verify({factorId:t.factorId,challengeId:s.id,code:t.code})}async _listFactors(){const{data:{user:t},error:s}=await this.getUser();if(s)return{data:null,error:s};const a=(t==null?void 0:t.factors)||[],n=a.filter(o=>o.factor_type==="totp"&&o.status==="verified"),i=a.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:a,totp:n,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var s,a;const{data:{session:n},error:i}=t;if(i)return{data:null,error:i};if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=Ni(n.access_token);let l=null;o.aal&&(l=o.aal);let c=l;((a=(s=n.user.factors)===null||s===void 0?void 0:s.filter(h=>h.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(c="aal2");const d=o.amr||[];return{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:d},error:null}}))}async fetchJwk(t,s={keys:[]}){let a=s.keys.find(l=>l.kid===t);if(a)return a;const n=Date.now();if(a=this.jwks.keys.find(l=>l.kid===t),a&&this.jwks_cached_at+zb>n)return a;const{data:i,error:o}=await it(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,a=i.keys.find(l=>l.kid===t),!a)?null:a}async getClaims(t,s={}){try{let a=t;if(!a){const{data:g,error:f}=await this.getSession();if(f||!g.session)return{data:null,error:f};a=g.session.access_token}const{header:n,payload:i,signature:o,raw:{header:l,payload:c}}=Ni(a);s!=null&&s.allowExpired||pv(i.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,s!=null&&s.keys?{keys:s.keys}:s==null?void 0:s.jwks);if(!u){const{error:g}=await this.getUser(a);if(g)throw g;return{data:{claims:i,header:n,signature:o},error:null}}const d=gv(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,o,ev(`${l}.${c}`)))throw new xo("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(a){if(Je(a))return{data:null,error:a};throw a}}}La.nextInstanceID=0;const Av=La;class Iv extends Av{constructor(t){super(t)}}var Rv=function(r,t,s,a){function n(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=Promise))(function(i,o){function l(d){try{u(a.next(d))}catch(h){o(h)}}function c(d){try{u(a.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((a=a.apply(r,t||[])).next())})};class $v{constructor(t,s,a){var n,i,o;if(this.supabaseUrl=t,this.supabaseKey=s,!t)throw new Error("supabaseUrl is required.");if(!s)throw new Error("supabaseKey is required.");const l=Bb(t),c=new URL(l);this.realtimeUrl=new URL("realtime/v1",c),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",c),this.storageUrl=new URL("storage/v1",c),this.functionsUrl=new URL("functions/v1",c);const u=`sb-${c.hostname.split(".")[0]}-auth-token`,d={db:Tb,realtime:Ib,auth:Object.assign(Object.assign({},Ab),{storageKey:u}),global:Eb},h=Fb(a??{},d);this.storageKey=(n=h.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(m,g)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(g)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=h.auth)!==null&&o!==void 0?o:{},this.headers,h.global.fetch),this.fetch=Ob(s,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new Jy(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),this.storage=new Sb(this.storageUrl.href,this.headers,this.fetch,a==null?void 0:a.storage),h.accessToken||this._listenForAuthEvents()}get functions(){return new Py(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,s={},a={}){return this.rest.rpc(t,s,a)}channel(t,s={config:{}}){return this.realtime.channel(t,s)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,s;return Rv(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:a}=yield this.auth.getSession();return(s=(t=a.session)===null||t===void 0?void 0:t.access_token)!==null&&s!==void 0?s:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:s,detectSessionInUrl:a,storage:n,storageKey:i,flowType:o,lock:l,debug:c},u,d){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Iv({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),u),storageKey:i,autoRefreshToken:t,persistSession:s,detectSessionInUrl:a,storage:n,flowType:o,lock:l,debug:c,fetch:d,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new mb(this.realtimeUrl.href,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((s,a)=>{this._handleTokenChanged(s,"CLIENT",a==null?void 0:a.access_token)})}_handleTokenChanged(t,s,a){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==a?this.changedAccessToken=a:t==="SIGNED_OUT"&&(this.realtime.setAuth(),s=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Lv=(r,t,s)=>new $v(r,t,s);function Ov(){if(typeof window<"u"||typeof process>"u")return!1;const r=process.version;if(r==null)return!1;const t=r.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}Ov()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Mv="https://qrciwxqxukxwkeobrads.supabase.co",Bv="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFyY2l3eHF4dWt4d2tlb2JyYWRzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTIzNzkwNTAsImV4cCI6MjA2Nzk1NTA1MH0.yu7ej5M3Vq3-h4Y1TK5Qjn9soHbFXtRJtKX38VqpSIQ",de=Lv(Mv,Bv,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),Fv=Object.freeze(Object.defineProperty({__proto__:null,supabase:de},Symbol.toStringTag,{value:"Module"})),da="tb_geo_detected",yo="tb_region_manual",Dv=()=>{const r=Jt(),t=_t(),[s,a]=p.useState(()=>!(localStorage.getItem(da)||localStorage.getItem(yo))),[n,i]=p.useState(!1);return p.useEffect(()=>{(async()=>{if(!(Xh(r.pathname)===Fs&&!r.pathname.startsWith("/sg")))return;const u=localStorage.getItem(yo);if(u){console.log("User has manual region preference:",u);return}const d=localStorage.getItem(da);if(d){let h=d;if(h==="US"&&(h=Fs),console.log("Using cached geo detection:",h),h!==Fs){const m=$a(r.pathname),g=Tn(m||"/",h),f=r.search||"",v=r.hash||"";t(`${g}${f}${v}`,{replace:!0}),i(!0)}return}a(!0),console.log("Calling geo-detection API...");try{const h=new AbortController,m=setTimeout(()=>h.abort(),3e3),{data:g,error:f}=await de.functions.invoke("detect-region",{body:{}});if(clearTimeout(m),f){console.error("Geo detection error:",f),localStorage.setItem(da,Fs);return}let v=(g==null?void 0:g.region)||Fs;if(v==="US"&&(v=Fs),console.log("Geo detection result:",v,"from country:",g==null?void 0:g.detectedCountry),localStorage.setItem(da,v),v!==Fs){const x=$a(r.pathname),j=Tn(x||"/",v),b=r.search||"",y=r.hash||"";console.log("Redirecting to:",j),t(`${j}${b}${y}`,{replace:!0}),i(!0)}}catch(h){console.error("Geo detection failed:",h),localStorage.setItem(da,Fs)}finally{a(!1)}})()},[]),{isDetecting:s,hasRedirected:n}},Gv=r=>{localStorage.setItem(yo,r)},Uv="tb_region",jm=p.createContext(void 0),Vv=({onDetectionStateChange:r})=>{const{isDetecting:t}=Dv();return jt.useEffect(()=>{r(t)},[t,r]),null},zv=({children:r})=>{const t=Jt(),s=_t(),[a,n]=jt.useState(!0),i=p.useMemo(()=>Xh(t.pathname),[t.pathname]),o=a,l=jt.useCallback(m=>{n(m)},[]);p.useEffect(()=>{localStorage.setItem(Uv,i)},[i]);const c=m=>{if(m===i)return;Gv(m);const g=$a(t.pathname),f=Tn(g||"/",m),v=t.search||"",x=t.hash||"";s(`${f}${v}${x}`,{replace:!0})},u=jy(i),d=m=>Tn(m,i),h=()=>$a(t.pathname);return e.jsxs(jm.Provider,{value:{region:i,setRegion:c,config:u,isLoading:o,buildLink:d,getBasePath:h},children:[e.jsx(Vv,{onDetectionStateChange:l}),r]})},ht=()=>{const r=p.useContext(jm);if(r===void 0)throw new Error("useRegion must be used within a RegionProviderInner");return r},Wv=!1,qv=({isOpen:r,onClose:t,scrollToSection:s})=>{const{region:a,setRegion:n,buildLink:i}=ht(),[o,l]=p.useState(!1),[c,u]=p.useState(!1),d=f=>{switch(f){case"IN":return"🇮🇳";case"SG":return"🇸🇬";default:return"🌍"}},h=f=>{n(f),l(!1)},m=[{label:"1-5 years",key:"1-5"},{label:"6-10 years",key:"6-10"}],g=[{label:"Boys",key:"Boy"},{label:"Girls",key:"Girl"}];return e.jsx(ks,{children:r&&e.jsx(Ie.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"fixed inset-0 bg-purple-900 bg-opacity-50 backdrop-blur-sm z-[60] md:hidden",onClick:t,children:e.jsx(Ie.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",damping:25,stiffness:300},className:"absolute top-0 right-0 h-full w-4/5 max-w-sm bg-white shadow-xl overflow-y-auto",onClick:f=>f.stopPropagation(),children:e.jsxs("div",{className:"p-6 flex flex-col min-h-full",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("span",{className:"font-semibold text-lg text-gray-900",children:"Menu"}),e.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 rounded-full transition-colors","aria-label":"Close menu",children:e.jsx(Cs,{className:"w-6 h-6 text-gray-600"})})]}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("button",{onClick:()=>l(!o),className:"w-full flex items-center justify-between px-4 py-3 bg-gray-50 rounded-lg border border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:d(a)}),e.jsx("span",{className:"font-medium text-gray-900",children:a})]}),e.jsx(Us,{className:`w-5 h-5 text-gray-500 transition-transform ${o?"rotate-180":""}`})]}),o&&e.jsx("div",{className:"mt-2 bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden",children:Object.keys(Ss).map(f=>{const v=Ss[f],x=a===f;return e.jsxs("button",{onClick:()=>h(f),className:`w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-purple-50 transition-colors ${x?"bg-purple-50 text-purple-700":"text-gray-700"}`,children:[e.jsx("span",{className:"text-xl",children:d(f)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium",children:v.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[v.symbol," ",v.currency]})]}),x&&e.jsx("svg",{className:"w-4 h-4 text-purple-600",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]},f)})})]}),e.jsxs("nav",{className:"flex flex-col space-y-2 flex-1",children:[e.jsxs(es,{to:i("/"),onClick:t,className:"flex items-center text-gray-900 hover:text-purple-600 transition-colors py-3 px-2 text-lg font-medium",children:[e.jsx(fu,{className:"w-5 h-5 mr-3 text-purple-600"}),"Home"]}),Wv,e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>u(!c),className:"w-full flex items-center justify-between text-gray-900 hover:text-purple-600 transition-colors py-3 px-2 text-lg font-medium",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(Ls,{className:"w-5 h-5 mr-3 text-purple-600"}),"Our Books"]}),e.jsx(Us,{className:`w-5 h-5 text-gray-500 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsxs("div",{className:"ml-8 mt-2 space-y-4 pb-4",children:[e.jsx("div",{children:e.jsx(es,{to:i("/books"),onClick:t,className:"text-purple-600 font-medium text-sm hover:underline",children:"View All Books →"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"By Age"}),e.jsx("div",{className:"space-y-1",children:m.map(f=>e.jsx(es,{to:i(`/books?age=${f.key}`),onClick:t,className:"block text-sm text-gray-700 hover:text-purple-600 py-1",children:f.label},f.key))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"By Gender"}),e.jsx("div",{className:"space-y-1",children:g.map(f=>e.jsx(es,{to:i(`/books?gender=${f.key}`),onClick:t,className:"block text-sm text-gray-700 hover:text-purple-600 py-1",children:f.label},f.key))})]})]})]}),e.jsxs(es,{to:i("/custom-storybooks"),onClick:t,className:"flex items-center text-gray-900 hover:text-purple-600 transition-colors py-3 px-2 text-lg font-medium",children:[e.jsx(Ls,{className:"w-5 h-5 mr-3 text-purple-600"}),"Custom Storybooks"]}),e.jsxs(es,{to:i("/how-it-works"),onClick:t,className:"flex items-center text-gray-900 hover:text-purple-600 transition-colors py-3 px-2 text-lg font-medium",children:[e.jsx(Hp,{className:"w-5 h-5 mr-3 text-purple-600"}),"How It Works"]}),a==="SG"?e.jsxs("button",{onClick:()=>{s("reviews"),t()},className:"flex items-center text-gray-900 hover:text-purple-600 transition-colors py-3 px-2 text-lg font-medium",children:[e.jsx(Pa,{className:"w-5 h-5 mr-3 text-purple-600"}),"Customer Reviews"]}):e.jsxs("a",{href:"https://maps.app.goo.gl/L3NjZRMkhkgdxd978",target:"_blank",rel:"noopener noreferrer",onClick:t,className:"flex items-center text-gray-900 hover:text-purple-600 transition-colors py-3 px-2 text-lg font-medium",children:[e.jsx(Pa,{className:"w-5 h-5 mr-3 text-purple-600"}),"Customer Reviews"]}),e.jsxs("button",{onClick:()=>{s("about"),t()},className:"flex items-center text-gray-900 hover:text-purple-600 transition-colors py-3 px-2 text-lg font-medium",children:[e.jsx(Mp,{className:"w-5 h-5 mr-3 text-purple-600"}),"About Us"]})]})]})})})})},Hv="/talesberry-logo.png",Kv=()=>{const{region:r,setRegion:t,config:s}=ht(),[a,n]=p.useState(!1),i=p.useRef(null);p.useEffect(()=>{const c=u=>{i.current&&!i.current.contains(u.target)&&n(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const o=c=>{t(c),n(!1)},l=c=>{switch(c){case"IN":return"🇮🇳";case"SG":return"🇸🇬";case"US":return"🇺🇸";default:return"🌍"}};return e.jsxs("div",{className:"relative",ref:i,children:[e.jsxs("button",{onClick:()=>n(!a),className:"flex items-center gap-1.5 px-2 py-1.5 text-sm text-gray-700 hover:text-black transition-colors rounded-lg hover:bg-gray-100","aria-label":"Change region",children:[e.jsx(Fi,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:l(r)}),e.jsx("span",{className:"hidden md:inline",children:s.name}),e.jsx(Us,{className:`w-3.5 h-3.5 transition-transform ${a?"rotate-180":""}`})]}),a&&e.jsxs("div",{className:"absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50",children:[e.jsx("div",{className:"px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider border-b",children:"Select Region"}),Object.keys(Ss).map(c=>{const u=Ss[c],d=r===c;return e.jsxs("button",{onClick:()=>o(c),className:`w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-gray-100 transition-colors ${d?"bg-gray-100 text-black":"text-gray-700"}`,children:[e.jsx("span",{className:"text-lg",children:l(c)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium",children:u.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[u.symbol," ",u.currency]})]}),d&&e.jsx("svg",{className:"w-4 h-4 text-black",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]},c)})]})]})},Yv=!1,Jv=()=>{const[r,t]=p.useState(!1),[s,a]=p.useState(!1),[n,i]=p.useState(!1),o=_t(),l=Jt(),{buildLink:c,getBasePath:u,region:d}=ht(),h=l.pathname==="/"||l.pathname==="/in"||l.pathname==="/sg";p.useEffect(()=>{const f=()=>{a(window.scrollY>10),i(window.scrollY>300)};return window.addEventListener("scroll",f),()=>window.removeEventListener("scroll",f)},[]);const m=()=>{window.scrollTo({top:0,behavior:"smooth"})},g=f=>{const v=u()||"";if(!(v==="/"||v===""))o(c("/"),{state:{scrollTo:f}});else{const j=document.getElementById(f);if(j){const S=j.getBoundingClientRect().top+window.pageYOffset-120;window.scrollTo({top:S,behavior:"smooth"})}}t(!1)};return p.useEffect(()=>{const f=l.state;f!=null&&f.scrollTo&&(setTimeout(()=>{f.scrollTo&&g(f.scrollTo)},100),window.history.replaceState({},document.title))},[l]),e.jsxs(e.Fragment,{children:[d==="IN"&&h&&e.jsx("div",{className:"fixed top-0 left-0 right-0 z-50 bg-primary-600 h-[44px]",children:e.jsxs(es,{to:c("/books/101/personalize"),className:"flex items-center justify-center h-[44px] px-4 text-center text-white hover:text-white/80 transition-colors font-medium text-sm leading-tight",children:[e.jsx("span",{className:"hidden md:inline",children:"🎉 New Launch: Personalised Birthday Return Gift Books!"}),e.jsxs("span",{className:"md:hidden text-center",children:["🎉 New Launch: Personalised Birthday",e.jsx("br",{}),"Return Gift Books!"]})]})}),e.jsx("header",{className:`fixed left-0 right-0 z-50 transition-all duration-300 
        ${d==="IN"&&h?"top-[44px]":"top-0"}
        ${s?"bg-white shadow-md py-2":"bg-transparent py-2"}`,children:e.jsxs("div",{className:"container mx-auto px-4 flex justify-between items-center",children:[e.jsxs(es,{to:c("/"),className:"flex items-center",children:[e.jsx("img",{src:Hv,alt:"TalesBerry Logo",className:"w-11 h-11 mr-3"}),e.jsxs("span",{className:"font-bold text-2xl",children:[e.jsx("span",{className:"text-purple-900",children:"Tales"}),e.jsx("span",{className:"text-primary-500",children:"Berry"})]})]}),e.jsxs("nav",{className:"hidden md:flex items-center space-x-6",children:[Yv,e.jsx(es,{to:c("/how-it-works"),className:"text-purple-900 hover:text-purple-600 transition-colors","data-gtm":"home_how_it_works",children:"How It Works"}),e.jsx("button",{onClick:()=>g("books-collection"),className:"text-purple-900 hover:text-purple-600 transition-colors","data-gtm":"home_books_collection","data-track":"home_books_collection",children:"Books Collection"}),e.jsx(es,{to:c("/custom-storybooks"),className:"text-purple-900 hover:text-purple-600 transition-colors","data-gtm":"home_custom_storybooks",children:"Custom Storybooks"}),e.jsx(es,{to:c("/login"),className:"text-purple-900 hover:text-purple-600 transition-colors","data-gtm":"home_drafts",children:"My Drafts"}),e.jsx("button",{onClick:()=>g("about"),className:"text-purple-900 hover:text-purple-600 transition-colors","data-gtm":"home_about",children:"About Us"}),h&&e.jsx(Kv,{})]}),e.jsx("div",{className:"flex items-center gap-2 md:hidden",children:e.jsx("button",{onClick:()=>t(!r),className:"text-purple-900 p-2 -mr-2 touch-feedback","aria-label":"Toggle menu",children:r?e.jsx(Cs,{size:24}):e.jsx(Up,{size:24})})})]})}),e.jsx(qv,{isOpen:r,onClose:()=>t(!1),scrollToSection:g}),e.jsx("button",{onClick:m,className:`fixed bottom-24 right-4 z-30 bg-white rounded-full shadow-lg p-3 transition-all duration-300 ${n?"opacity-100 translate-y-0":"opacity-0 translate-y-10 pointer-events-none"}`,"aria-label":"Scroll to top",children:e.jsx(qr,{className:"w-6 h-6 text-purple-600"})})]})},Zv=()=>{const r=_t(),{buildLink:t,getBasePath:s,region:a}=ht(),n=i=>{if(s()!=="/")r(t("/"),{state:{scrollTo:i}});else{const l=document.getElementById(i);if(l){const d=l.getBoundingClientRect().top+window.pageYOffset-80;window.scrollTo({top:d,behavior:"smooth"})}}};return e.jsx("footer",{className:"bg-purple-900 text-white pt-6 pb-4 md:pt-10 md:pb-6 px-4 relative z-0",children:e.jsxs("div",{className:"container mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-8 mb-4 md:mb-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base md:text-xl font-semibold mb-2 md:mb-4",children:"TalesBerry"}),e.jsx("p",{className:"text-purple-200 mb-2 md:mb-4 text-xs md:text-base hidden sm:block",children:"Creating magical personalized stories that children will treasure for years to come."}),e.jsx("div",{className:"flex",children:e.jsx("a",{href:"https://www.instagram.com/talesberry_official/",target:"_blank",rel:"noopener noreferrer",className:"text-purple-200 hover:text-white transition-colors touch-feedback",children:e.jsx(Dp,{className:"w-4 h-4 md:w-5 md:h-5"})})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base md:text-xl font-semibold mb-2 md:mb-4",children:"Quick Links"}),e.jsxs("ul",{className:"space-y-1 md:space-y-2 text-xs md:text-base",children:[e.jsx("li",{children:e.jsx("button",{onClick:()=>n("how-it-works"),className:"text-gray-300 hover:text-white transition-colors touch-feedback block py-0.5 md:py-1 text-left w-full",children:"How It Works"})}),e.jsx("li",{children:e.jsx("button",{onClick:()=>n("about"),className:"text-gray-300 hover:text-white transition-colors touch-feedback block py-0.5 md:py-1 text-left w-full",children:"About Us"})}),a==="IN"&&e.jsxs(e.Fragment,{children:[e.jsx("li",{children:e.jsx(es,{to:t("/custom-storybooks"),className:"text-purple-200 hover:text-white transition-colors touch-feedback block py-0.5 md:py-1",children:"Custom Storybooks"})}),e.jsx("li",{children:e.jsx(es,{to:t("/books/100/personalize"),className:"text-purple-200 hover:text-white transition-colors touch-feedback block py-0.5 md:py-1",children:"Book for Parents"})}),e.jsx("li",{children:e.jsx(es,{to:t("/books/101/personalize"),className:"text-purple-200 hover:text-white transition-colors touch-feedback block py-0.5 md:py-1",children:"Book for Partner"})})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base md:text-xl font-semibold mb-2 md:mb-4",children:"Support"}),e.jsxs("ul",{className:"space-y-1 md:space-y-2 text-xs md:text-base",children:[e.jsx("li",{children:e.jsx(es,{to:t("/faq"),className:"text-purple-200 hover:text-white transition-colors touch-feedback block py-0.5 md:py-1",children:"FAQ"})}),e.jsx("li",{children:e.jsx(es,{to:t("/policies/privacy-policy"),className:"text-purple-200 hover:text-white transition-colors touch-feedback block py-0.5 md:py-1",children:"Privacy Policy"})})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base md:text-xl font-semibold mb-2 md:mb-4",children:"Contact"}),e.jsx("ul",{className:"space-y-1 md:space-y-2 text-xs md:text-base",children:e.jsxs("li",{className:"flex items-center",children:[e.jsx(Ma,{className:"w-4 h-4 md:w-5 md:h-5 mr-1.5 md:mr-2 text-purple-300 flex-shrink-0"}),e.jsx("a",{href:"mailto:support@talesberry.com",className:"text-purple-200 hover:text-white transition-colors touch-feedback truncate",children:"support@talesberry.com"})]})})]})]}),e.jsx("div",{className:"border-t border-purple-800 pt-4 md:pt-6 text-center text-purple-300 text-xs md:text-sm",children:e.jsxs("p",{children:["© ",new Date().getFullYear()," TalesBerry. All rights reserved."]})})]})})},Si="G-WS570380CY",Xv=()=>{const r=Jt(),t=r.pathname.startsWith("/sg");return p.useEffect(()=>{if(!t||document.getElementById("sg-ga4-script"))return;const s=document.createElement("script");s.id="sg-ga4-script",s.async=!0,s.src=`https://www.googletagmanager.com/gtag/js?id=${Si}`,document.head.appendChild(s);const a=document.createElement("script");a.id="sg-ga4-inline",a.textContent=`
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '${Si}', {
        page_path: window.location.pathname
      });
    `,document.head.appendChild(a)},[t]),p.useEffect(()=>{t&&typeof window.gtag=="function"&&window.gtag("config",Si,{page_path:r.pathname+r.search})},[r.pathname,r.search,t]),null},wt=({children:r,primary:t=!0,className:s="",type:a="button",disabled:n=!1,...i})=>e.jsx("button",{type:a,disabled:n,...i,className:`
        px-6 py-3 rounded-full font-medium text-base transition-all duration-300
        ${t?"bg-black text-white hover:bg-gray-800 hover:translate-y-[-2px] hover:shadow-lg active:translate-y-0 active:shadow-md":"bg-white text-primary-600 border-2 border-primary-400 hover:bg-primary-50 active:bg-primary-100"}
        ${n?"opacity-70 cursor-not-allowed":""}
        ${s}
      `,children:r}),ot="https://d38picfcqfcfl0.cloudfront.net/website_media",Ed=r=>`${ot}${r}`,Rn=(r,t)=>{const s=t==="US"?"sg":t.toLowerCase();return`${ot}/${s}${r}`},fa=r=>`${ot}/in${r}`,Qv=()=>{const[r,t]=p.useState(1),{region:s,config:a}=ht();p.useEffect(()=>{const o=setInterval(()=>{t(l=>l>=a.heroImageCount?1:l+1)},a.heroImageInterval);return()=>clearInterval(o)},[a.heroImageCount,a.heroImageInterval]);const n=Ed(`${a.heroImagesPath}${r}.jpg`),i=()=>{const o=window.innerWidth<768,l=o?"gifts-section":"books-collection-header",c=document.getElementById(l);if(c){const u=o?70:90,h=c.getBoundingClientRect().top+window.pageYOffset-u;window.scrollTo({top:h,behavior:"smooth"})}};return e.jsx("section",{className:`relative overflow-hidden bg-white pb-6 md:pb-4 ${s==="IN"?"pt-24 md:pt-28":"pt-20 md:pt-24"}`,children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-8 md:gap-16 max-w-6xl mx-auto",children:[e.jsx("div",{className:"w-full md:w-[47%] relative",children:e.jsxs("div",{className:"relative rounded-2xl overflow-hidden shadow-2xl aspect-square",children:[s==="IN"&&e.jsx("video",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/animation_homepage.mp4",className:"w-full h-full object-cover md:hidden",autoPlay:!0,loop:!0,muted:!0,playsInline:!0}),e.jsx("img",{src:n,alt:"Storybook hero",className:`w-full h-full object-cover ${s==="IN"?"hidden md:block":""}`,onError:o=>{const l=Ed(`/homepage_images/${r}.jpg`);o.target.src!==l&&(o.target.src=l)}})]})}),e.jsxs("div",{className:"w-full md:w-1/2 text-center md:text-left",children:[s==="IN"&&e.jsx("p",{className:"md:hidden text-sm font-semibold text-amber-700 -mt-4",children:"😊 2500+ Happy Customers"}),e.jsx("h1",{className:"text-4xl md:text-5xl lg:text-6xl font-bold mb-6 leading-tight",children:e.jsx("span",{className:"text-transparent bg-clip-text bg-gradient-to-r from-purple-600 via-purple-500 to-blue-500",children:a.headline})}),e.jsx("p",{className:"hidden md:block text-lg md:text-xl text-gray-700 mb-8 max-w-xl",children:a.subtext}),e.jsx("div",{className:"flex justify-center md:justify-start",children:e.jsx(wt,{onClick:i,className:"px-8 py-3 md:px-6 rounded-full md:rounded-lg w-full md:w-auto max-w-sm md:max-w-none","data-gtm":"home_create","data-track":"Home_Create_Free_Preview_mainCTA",children:s==="IN"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"md:hidden",children:"Create Your Book"}),e.jsxs("div",{className:"hidden md:flex flex-col items-center gap-0.5",children:[e.jsx("span",{children:"Create Free Preview"}),e.jsx("span",{className:"text-xs opacity-80",children:"In just 2 minutes!"})]})]}):e.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[e.jsx("span",{children:"Create Free Preview"}),e.jsx("span",{className:"text-xs opacity-80",children:"In just 2 minutes!"})]})})}),e.jsx("div",{className:"md:hidden text-center mt-1.5",children:e.jsxs("p",{className:"text-base font-semibold text-purple-800",children:["⭐⭐⭐⭐⭐ ",s==="SG"?"Trusted by families worldwide":"Google Reviews"]})})]})]})})})},ew=()=>e.jsx(Qv,{}),tw=[{id:1,title:"Tell us about your child",description:"Share their name, gender, and one clear photo to get started."},{id:2,title:"Instant sample preview",description:"Get a free preview of the first 4 pages to see the quality of the personalisation and inside pages of the book. We use advanced AI to learn details of the input face and then recreate it on each story page hyper-realistically."},{id:3,title:"Place Order to unlock full book",description:"Once you make a purchase, the full book is unlocked. You can also regenerate different variants of every page as needed."},{id:4,title:"Send for printing",description:"Review the complete book and send it for printing when you're fully satisfied."},{id:5,title:"Delivered to your door",description:"Your storybook is printed on premium 220GSM glossy paper and shipped to your doorstep in about 7 business days."}],Nm=({standalone:r=!1})=>e.jsx("section",{id:"how-it-works",className:`bg-white ${r?"py-12 md:py-20":"py-6 sm:py-12"}`,children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:`${r?"mb-8 md:mb-12":"mb-6 sm:mb-8"} text-center`,children:[r?e.jsx("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-gray-900 mb-4",children:"How to Create a Personalised Storybook for Your Child"}):e.jsx("h2",{className:"section-title",children:"How It Works"}),r&&e.jsx("p",{className:"text-gray-600 max-w-2xl mx-auto text-lg",children:"Creating a personalised children's book with TalesBerry is simple. Follow these 5 easy steps to turn your child into the hero of their own story."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12 items-start",children:[e.jsx("ol",{className:"space-y-6",children:tw.map((t,s)=>e.jsxs(Ie.li,{initial:{opacity:0,x:-20},whileInView:{opacity:1,x:0},viewport:{once:!0},transition:{delay:s*.1},className:"flex gap-4",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center",children:e.jsx("span",{className:"text-purple-700 font-semibold text-lg",children:t.id})})}),e.jsxs("div",{className:"flex-1 pt-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-1",children:t.title}),e.jsx("p",{className:"text-gray-600 text-sm leading-relaxed",children:t.description})]})]},t.id))}),e.jsx(Ie.div,{initial:{opacity:0,scale:.95},whileInView:{opacity:1,scale:1},viewport:{once:!0},transition:{delay:.3},className:"lg:sticky lg:top-24",children:e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-gray-100 aspect-[4/3] shadow-xl",children:e.jsxs("video",{className:"w-full h-full object-cover",controls:!0,preload:"auto",children:[e.jsx("source",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/animation_homepage.mp4",type:"video/mp4"}),"Your browser does not support the video tag."]})})})]}),r&&e.jsxs("div",{className:"max-w-3xl mx-auto mt-12 md:mt-16 space-y-8",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-3",children:"Why Create a Personalised Storybook?"}),e.jsx("p",{className:"text-gray-700 leading-relaxed",children:"Personalised children's storybooks are more than just gifts — they're experiences that make your child feel special. When children see their own name and face in a beautifully illustrated story, it sparks imagination, builds confidence, and creates a lifelong love of reading. TalesBerry uses advanced AI technology to generate hyper-realistic illustrations of your child as the hero of the story."})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-3",children:"What Makes TalesBerry Different?"}),e.jsxs("ul",{className:"space-y-3 text-gray-700",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-purple-600 font-bold",children:"•"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Free preview before you buy"})," — see the first 4 pages with your child's face before placing an order."]})]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-purple-600 font-bold",children:"•"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Premium print quality"})," — 220 GSM glossy paper with laminated hardcover, built to last."]})]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-purple-600 font-bold",children:"•"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Multiple story themes"})," — choose adventures tailored to your child's age and interests."]})]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-purple-600 font-bold",children:"•"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Fast delivery"})," — printed and delivered to your doorstep in about 7 business days."]})]})]})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-3",children:"Frequently Asked Questions About Creating Personalised Books"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"How long does it take to create a personalised storybook?"}),e.jsx("p",{className:"text-gray-600 mt-1",children:"The entire process takes just 2 minutes online. You upload a photo, enter your child's details, and get an instant preview. After ordering, the printed book is delivered in about 7 business days."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"Is my child's photo safe?"}),e.jsx("p",{className:"text-gray-600 mt-1",children:"Absolutely. Photos are used only for creating your book and are automatically deleted from our systems within 4 weeks. We never use photos for promotions or AI training."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"Can I see the book before ordering?"}),e.jsx("p",{className:"text-gray-600 mt-1",children:"Yes! TalesBerry offers a free 4-page sample preview so you can see exactly how your child looks in the story before committing to a purchase."})]})]})]})]})]})}),Td=32,Ot=[{id:22,title:"The School of Magic",description:"The School of Magic!",theme:"Creativity & Magic",pages:32,suitableFor:"Girl",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"school_of_magic",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["https://d38picfcqfcfl0.cloudfront.net/website_media/homepage_images/23.jpeg"]},{id:19,title:"The Superpower Girls",description:"Two besties use their superpower and use it for good!",theme:"Fantasy & Thriller",pages:36,suitableFor:"Girl",ageRange:"5-12 years",category_tag:"multi_character_books",backendName:"superpower_girls",hidden:!0,pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["https://d38picfcqfcfl0.cloudfront.net/website_media/homepage_images/27.jpeg"]},{id:21,title:"The Magical Party",description:"Two besties use their superpower and use it for good!",theme:"Fantasy & Thriller",pages:34,suitableFor:"Boy",ageRange:"5-12 years",category_tag:"return_gift_books",backendName:"return_gift",hidden:!0,pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/thumbnails/return_gift_temp.jpg"]},{id:20,title:"The Superpower Boys",description:"Two besties use their superpower and use it for good!",theme:"Fantasy & Thriller",pages:36,suitableFor:"Boy",ageRange:"5-12 years",category_tag:"multi_character_books",backendName:"superpower_boys",hidden:!0,pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/thumbnails/superpower_boys_temp.jpg"]},{id:17,title:"The Deep Space Mission",description:"A brave young girl astronaut goes on a thrilling deep space mission to save Earth's satellite using his own invention!",theme:"Science & Space",pages:34,suitableFor:"Girl",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"deep_space_girl",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["https://d38picfcqfcfl0.cloudfront.net/website_media/homepage_images/26.jpg"]},{id:16,title:"The Deep Space Mission",description:"A brave young boy astronaut goes on a thrilling deep space mission to save Earth's satellite using his own invention!",theme:"Science & Space",pages:34,suitableFor:"Boy",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"deep_space",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["https://d38picfcqfcfl0.cloudfront.net/website_media/homepage_images/25.jpg"]},{id:15,title:"The School of Magic",description:"The School of Magic!",theme:"Creativity & Magic",pages:32,suitableFor:"Boy",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"school_of_magic",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["https://d38picfcqfcfl0.cloudfront.net/website_media/homepage_images/23.jpeg"]},{id:14,title:"The Car Racing Adventure",description:"Boy builds his dream car from scrap metal and races to become the champion of Singapore Grand Prix",theme:"Creativity & Thriller",pages:32,suitableFor:"Boy",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"car_racing",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/car_racing/front.jpg","/car_racing/Story_Images/page01.jpg","/car_racing/Story_Images/page02.jpg","/car_racing/Story_Images/page03.jpg","/car_racing/Story_Images/page04.jpg","/car_racing/Story_Images/page05.jpg","/car_racing/Story_Images/page06.jpg","/car_racing/Story_Images/page07.jpg","/car_racing/Story_Images/page08.jpg","/car_racing/back.jpg"]},{id:13,title:"The CupCake Mystery",description:"A delicious mystery unfolds at the bakery! Your little detective must solve the case of the missing cupcakes using clues, courage, and creativity.",theme:"Fantasy & Thriller",pages:34,suitableFor:"Girl",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"cupcake_mystery",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["https://d38picfcqfcfl0.cloudfront.net/website_media/in/cupcake_mystery/cover1.jpg","https://d38picfcqfcfl0.cloudfront.net/website_media/in/cupcake_mystery/cover2.jpg"]},{id:9,title:"The SuperHero Adventure",description:"Boy goes on an adventure and figures true meaning of a SuperHero.",theme:"Fantasy & Thriller",pages:32,suitableFor:"Boy",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"superhero",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/boy_superhero/front.jpg","/boy_superhero/Story_Images/page04.jpg","/boy_superhero/Story_Images/page05.jpg","/boy_superhero/Story_Images/page06.jpg","/boy_superhero/Story_Images/page07.jpg","/boy_superhero/Story_Images/page08.jpg","/boy_superhero/Story_Images/page09.jpg","/boy_superhero/Story_Images/page10.jpg","/boy_superhero/Story_Images/page11.jpg","/boy_superhero/back.jpg"]},{id:7,title:"[Girl]'s FairyTale Adventure",description:"A magical fairy guides the girl to become Princess of Water, Earth, and Fire — a tale of courage and wonder.",theme:"Fantasy & Thriller",pages:38,suitableFor:"Girl",ageRange:"5-12 years",category_tag:"single_character_books",specialTag:"Girl's special",backendName:"fairytale_adventure",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/girl_fairytale/front.jpg","/girl_fairytale/1.jpg","/girl_fairytale/2.jpg","/girl_fairytale/3.jpg","/girl_fairytale/4.jpg","/girl_fairytale/5.jpg","/girl_fairytale/6.jpg","/girl_fairytale/7.jpg","/girl_fairytale/back.jpeg"]},{id:8,title:"[Boy] & The Tower of Time",description:"Boy's magic watch sends him through time, solving riddles to find his way home.",theme:"Fantasy & Thriller",pages:32,suitableFor:"Boy",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"tower_of_time",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/boy_tower_of_time/front.jpg","/boy_tower_of_time/1.jpg","/boy_tower_of_time/2.jpg","/boy_tower_of_time/3.jpg","/boy_tower_of_time/4.jpg","/boy_tower_of_time/5.jpg","/boy_tower_of_time/6.jpg","/boy_tower_of_time/7.jpg","/boy_tower_of_time/8.jpg","/boy_tower_of_time/back.jpeg"]},{id:18,title:"Princess saves the Icy Land",description:"Fantasy story of the Pricess who saves the Icy Land.",theme:"Fantasy & Fairytale",pages:32,suitableFor:"Girl",ageRange:"5-12 years",category_tag:"single_character_books",backendName:"icy_princess",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["https://d38picfcqfcfl0.cloudfront.net/website_media/homepage_images/22.jpg","/girl_fairytale/1.jpg","/girl_fairytale/2.jpg","/girl_fairytale/3.jpg","/girl_fairytale/4.jpg","/girl_fairytale/5.jpg","/girl_fairytale/6.jpg","/girl_fairytale/7.jpg","/girl_fairytale/back.jpeg"]},{id:2,title:"[Boy]'s Tiny Toes in the Jungle",description:"A magical forest adventure where kids meet Jungle animals and learn some heartwarming lessons!",theme:"Learning",pages:Td,suitableFor:"Boy",ageRange:"2-6 years",backendName:"tiny_toes",category_tag:"little_kids_books",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/boy_tiny_toes/front.jpg","/boy_tiny_toes/1.jpg","/boy_tiny_toes/2.jpg","/boy_tiny_toes/3.jpg","/boy_tiny_toes/4.jpg","/boy_tiny_toes/5.jpg","/boy_tiny_toes/6.jpg","/boy_tiny_toes/7.jpg","/boy_tiny_toes/8.jpg","/boy_tiny_toes/back.jpeg"]},{id:1,title:"[Girl]'s Tiny Toes in the Jungle",description:"A magical forest adventure where kids meet Jungle animals and learn some heartwarming lessons!",theme:"Learning",pages:Td,suitableFor:"Girl",ageRange:"3-6 years",backendName:"tiny_toes",category_tag:"little_kids_books",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/girl_tiny_toes/front.jpg","/girl_tiny_toes/1.jpg","/girl_tiny_toes/2.jpg","/girl_tiny_toes/3.jpg","/girl_tiny_toes/4.jpg","/girl_tiny_toes/5.jpg","/girl_tiny_toes/6.jpg","/girl_tiny_toes/7.jpg","/girl_tiny_toes/8.jpg","/girl_tiny_toes/back.jpeg"]},{id:10,title:"[Boy]'s Alphabet Journey",description:"From A to Z, your child journeys through a world of wonder and giggles!",theme:"Learning",pages:30,suitableFor:"Boy",ageRange:"1-5 years",backendName:"alphabet_journey",category_tag:"little_kids_books",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/boy_alphabet_journey/front.jpg","/boy_alphabet_journey/1.jpg","/boy_alphabet_journey/2.jpg","/boy_alphabet_journey/3.jpg","/boy_alphabet_journey/4.jpg","/boy_alphabet_journey/5.jpg","/boy_alphabet_journey/6.jpg","/boy_alphabet_journey/7.jpg","/boy_alphabet_journey/8.jpg","/boy_alphabet_journey/9.jpg","/boy_alphabet_journey/back.jpeg"]},{id:4,title:"[Girl]'s Alphabet Journey",description:"From A to Z, your child journeys through a world of wonder and giggles!",theme:"Learning",pages:30,suitableFor:"Girl",ageRange:"1-5 years",category_tag:"little_kids_books",backendName:"alphabet_journey",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/girl_alphabet_journey/front.jpg","/girl_alphabet_journey/1.jpg","/girl_alphabet_journey/2.jpg","/girl_alphabet_journey/3.jpg","/girl_alphabet_journey/4.jpg","/girl_alphabet_journey/5.jpg","/girl_alphabet_journey/6.jpg","/girl_alphabet_journey/7.jpg","/girl_alphabet_journey/8.jpg","/girl_alphabet_journey/9.jpg","/girl_alphabet_journey/back.jpeg"]},{id:5,title:"[Boy]'s Big Dreams",description:"[Boy]'s Big Dreams sparks imagination as he explores fun roles like Scientist, Football player, Chef & many more!",theme:"Learning",pages:36,suitableFor:"Boy",ageRange:"4-10 years",category_tag:"single_character_books",backendName:"big_dreams",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/boy_big_dreams/front.jpg","/boy_big_dreams/1.jpg","/boy_big_dreams/2.jpg","/boy_big_dreams/3.jpg","/boy_big_dreams/4.jpg","/boy_big_dreams/5.jpg","/boy_big_dreams/6.jpg","/boy_big_dreams/7.jpg","/boy_big_dreams/8.jpg","/boy_big_dreams/back.jpeg"]},{id:6,title:"[Girl]'s Big Dreams",description:"[Girls]'s Big Dreams sparks imagination as she explores fun roles like Scientist, Fashion Designer, Tennis champ & many more!",theme:"Learning",pages:38,suitableFor:"Girl",ageRange:"4-10 years",category_tag:"single_character_books",backendName:"big_dreams",pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/girl_big_dreams/front.jpg","/girl_big_dreams/1.jpg","/girl_big_dreams/2.jpg","/girl_big_dreams/3.jpg","/girl_big_dreams/4.jpg","/girl_big_dreams/5.jpg","/girl_big_dreams/6.jpg","/girl_big_dreams/7.jpg","/girl_big_dreams/8.jpg","/girl_big_dreams/back.jpeg"]},{id:100,title:"Dad, I love You!",description:"A heartwarming story celebrating the special bond between a father and child, filled with love, adventures, and precious moments together.",theme:"Family & Love",pages:32,suitableFor:"Both",ageRange:"2-8 years",category_tag:"Family Bond",specialTag:"Fathers Day Special",backendName:"father",hidden:!0,pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/papa_love/front.jpeg","/papa_love/1.jpeg","/papa_love/2.jpeg","/papa_love/3.jpeg","/papa_love/4.jpeg","/papa_love/5.jpeg","/papa_love/6.jpeg","/papa_love/7.jpeg","/papa_love/8.jpeg","/papa_love/9.jpeg","/papa_love/10.jpeg","/papa_love/back.jpeg"]},{id:101,title:"I love you because..",description:"A romantic personalized story celebrating the love between you and your partner, filled with cherished memories and heartfelt moments.",theme:"Romance & Love",pages:32,suitableFor:"Female",ageRange:"18-99 years",category_tag:"Romance",specialTag:"Valentines Day Special",backendName:"valentines",hidden:!0,pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/in/girl_coupleBook/front.jpg","/in/girl_coupleBook/Story_Images/page01.jpg","/in/girl_coupleBook/Story_Images/page02.jpg","/in/girl_coupleBook/Story_Images/page03.jpg","/in/girl_coupleBook/Story_Images/page04.jpg","/in/girl_coupleBook/Story_Images/page05.jpg","/in/girl_coupleBook/Story_Images/page06.jpg","/in/girl_coupleBook/Story_Images/page07.jpg","/in/girl_coupleBook/Story_Images/page08.jpg","/in/girl_coupleBook/Story_Images/page09.jpg","/in/girl_coupleBook/Story_Images/page10.jpg","/in/girl_coupleBook/back.jpg"]},{id:102,title:"I love you because..",description:"A romantic personalized story celebrating the love between you and your partner, filled with cherished memories and heartfelt moments.",theme:"Romance & Love",pages:32,suitableFor:"Male",ageRange:"18-99 years",category_tag:"Romance",specialTag:"Valentines Day Special",backendName:"valentines",hidden:!0,pricing:{small:{size:"8.75x8.75 inch",price:1199}},imagePaths:["/in/boy_coupleBook/front.jpg","/in/boy_coupleBook/Story_Images/page01.jpg","/in/boy_coupleBook/Story_Images/page02.jpg","/in/boy_coupleBook/Story_Images/page03.jpg","/in/boy_coupleBook/Story_Images/page04.jpg","/in/boy_coupleBook/Story_Images/page05.jpg","/in/boy_coupleBook/Story_Images/page06.jpg","/in/boy_coupleBook/Story_Images/page07.jpg","/in/boy_coupleBook/Story_Images/page08.jpg","/in/boy_coupleBook/Story_Images/page09.jpg","/in/boy_coupleBook/Story_Images/page10.jpg","/in/boy_coupleBook/back.jpg"]}],sw=r=>({1:"/videos/1.mp4",6:"/videos/1.mp4",2:"/videos/2.mp4",5:"/videos/3.mp4",7:"/videos/3.mp4",10:"/videos/3.mp4",8:"/videos/4.mp4",9:"/videos/5.mp4",4:"/videos/6.mp4",3:"/videos/3.mp4"})[r]||null,Ci=new Map,rw=(()=>{const r=new Set;return{preloadVideo:s=>new Promise((a,n)=>{if(Ci.has(s)||r.has(s)){a();return}r.add(s);const i=document.createElement("video");i.src=s,i.preload="auto",i.muted=!0,i.playsInline=!0;const o=()=>{Ci.set(s,i),i.removeEventListener("canplaythrough",o),i.removeEventListener("error",l),a()},l=()=>{r.delete(s),i.removeEventListener("canplaythrough",o),i.removeEventListener("error",l),n()};i.addEventListener("canplaythrough",o),i.addEventListener("error",l),i.load()}),videoCache:Ci}})(),$s=({imagePath:r,fallbackToIndia:t=!0,alt:s,...a})=>{const{region:n}=ht(),[i,o]=p.useState(!1),l=r.startsWith("http://")||r.startsWith("https://"),c=r.startsWith("/thumbnails/")||r.startsWith("/public/"),u=l||c?r:i?fa(r):Rn(r,n),d=()=>{!i&&t&&n!=="IN"&&o(!0)};return e.jsx("img",{src:u,alt:s,onError:d,...a})},Ad=[{id:"kids",label:"Return Gift Books",image:`${ot}/homepage_categories_images/return_gifts_book.jpg`},{id:"partner",label:"Single character Books",image:`${ot}/homepage_categories_images/Single_character_book.jpg`},{id:"kids-stickers",label:"Multi character Books",image:`${ot}/homepage_categories_images/multi_character_story.jpg`},{id:"dad",label:"Books for kids age 1-5",image:`${ot}/homepage_categories_images/little_kids.jpg`}],Pi={1:{images:["/sg/girl_tiny_toes/coverpage_gif_effect/1.jpg","/sg/girl_tiny_toes/coverpage_gif_effect/2.jpg"],interval:1500},2:{images:["/sg/boy_tiny_toes/coverpage_gif_effect/1.jpg","/sg/boy_tiny_toes/coverpage_gif_effect/2.jpg"],interval:1500},4:{images:["/sg/girl_alphabet_journey/coverpage_gif_effect/1.jpg","/sg/girl_alphabet_journey/coverpage_gif_effect/2.jpg"],interval:1500},5:{images:["/sg/boy_big_dreams/coverpage_gif_effect/1.jpg","/sg/boy_big_dreams/coverpage_gif_effect/2.jpg"],interval:1500},6:{images:["/sg/girl_big_dreams/coverpage_gif_effect/1.jpg","/sg/girl_big_dreams/coverpage_gif_effect/2.jpg"],interval:1500},7:{images:["/sg/girl_fairytale/coverpage_gif_effect/1.jpg","/sg/girl_fairytale/coverpage_gif_effect/2.jpg"],interval:1500},8:{images:["/sg/boy_tower_of_time/coverpage_gif_effect/1.jpg","/sg/boy_tower_of_time/coverpage_gif_effect/2.jpg"],interval:1500},10:{images:["/sg/boy_alphabet_journey/coverpage_gif_effect/1.jpg","/sg/boy_alphabet_journey/coverpage_gif_effect/2.jpg"],interval:1500}},Hs=r=>r.replace(/^\[Girl\]'s\s+/i,"").replace(/^\[Boy\]'s\s+/i,"").replace(/^\[Girl\]\s*&\s*/i,"").replace(/^\[Boy\]\s*&\s*/i,""),aw=()=>{const r=_t(),{buildLink:t,region:s}=ht(),[a,n]=p.useState({}),i=p.useRef(null);p.useEffect(()=>{if(s!=="SG")return;const g=setInterval(()=>{n(f=>{const v={};return Object.keys(Pi).forEach(x=>{const j=Number(x);v[j]=(f[j]||0)===0?1:0}),v})},1500);return()=>clearInterval(g)},[s]);const o=g=>s==="SG"&&g in Pi,l=g=>{const f=Pi[g];if(!f)return"";const v=a[g]||0;return`${ot}${f.images[v]}`},c=g=>{const f=Ot.find(v=>v.id===g);r(t(`/books/${g}/personalize`),{state:{selectedBook:f}})},u=g=>{const f=sw(g);f&&rw.preloadVideo(f).catch(console.error)},d={kids:"return_gift_books",partner:"single_character_books","kids-stickers":"multi_character_books",dad:"little_kids_books"},h=g=>{if(s==="IN"){const v=d[g];if(v){r(t(`/books?category=${v}`));return}}if(g==="kids"){r(t("/kids"));return}if(g==="kids-stickers"){r(t("/stickers"));return}if(g==="partner"){r(t("/books/101/personalize"));return}if(g==="dad"){r(t("/books/102/personalize"));return}const f=document.getElementById("books-collection");f&&f.scrollIntoView({behavior:"smooth"})},m=g=>{i.current&&i.current.scrollBy({left:g==="left"?-200:200,behavior:"smooth"})};return e.jsxs(e.Fragment,{children:[e.jsx("section",{id:"gifts-section",className:"py-4 md:py-12 bg-gradient-to-br from-purple-100/70 via-pink-100/50 to-amber-100/60",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-bold text-black mb-6 text-center",children:"Categories of Adventures"}),s==="IN"&&e.jsx("div",{className:"md:hidden grid grid-cols-2 gap-3",children:Ad.map(g=>e.jsxs(Ie.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},onClick:()=>h(g.id),className:"overflow-hidden rounded-xl w-full cursor-pointer border-[1.5px] border-black/20 shadow-sm",children:[e.jsx("div",{className:"px-2 py-2",style:{backgroundColor:"#d4baab"},children:e.jsx("span",{className:"text-foreground font-semibold text-xs leading-tight block text-center",children:g.label})}),e.jsxs("div",{className:"relative w-full aspect-square",children:[e.jsx("img",{src:g.image,alt:g.label,className:"w-full h-full object-cover",loading:"lazy"}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/60 to-transparent p-2 flex flex-col items-center",children:e.jsx("button",{onClick:f=>{f.stopPropagation(),h(g.id)},className:"px-6 py-1.5 rounded-full bg-white text-black font-medium text-xs shadow-md",children:"Personalize"})})]})]},g.id))}),e.jsxs("div",{className:`relative ${s==="IN"?"hidden md:block":""}`,children:[e.jsx("button",{onClick:()=>m("left"),className:"hidden md:flex absolute -left-4 top-1/2 -translate-y-1/2 z-10 p-2 bg-white/90 backdrop-blur-sm rounded-full shadow-lg hover:shadow-xl hover:bg-white transition-all",children:e.jsx(Ut,{className:"w-5 h-5 text-muted-foreground"})}),e.jsx("div",{ref:i,className:"flex gap-4 overflow-x-auto scrollbar-hide pb-2 snap-x snap-mandatory md:px-8 scroll-smooth justify-center",style:{scrollbarWidth:"none",msOverflowStyle:"none",WebkitOverflowScrolling:"touch"},children:Ad.map(g=>e.jsxs(Ie.button,{onClick:()=>h(g.id),whileHover:{scale:1.02},whileTap:{scale:.98},className:"flex-shrink-0 snap-start relative overflow-hidden rounded-xl w-[140px] md:w-[280px] aspect-[4/5]",children:[e.jsx("img",{src:g.image,alt:g.label,className:"w-full h-full object-cover",loading:"lazy"}),e.jsx("div",{className:"absolute bottom-2 md:bottom-4 left-1/2 -translate-x-1/2",children:e.jsx("span",{className:"bg-white/95 backdrop-blur-sm text-foreground font-medium px-3 md:px-5 py-1.5 md:py-2 rounded-full text-xs md:text-base shadow-md whitespace-nowrap",children:g.label})})]},g.id))}),e.jsx("button",{onClick:()=>m("right"),className:"hidden md:flex absolute -right-4 top-1/2 -translate-y-1/2 z-10 p-2 bg-white/90 backdrop-blur-sm rounded-full shadow-lg hover:shadow-xl hover:bg-white transition-all",children:e.jsx(gs,{className:"w-5 h-5 text-muted-foreground"})})]})]})}),e.jsx("section",{id:"books-collection",className:"py-6 md:pt-4 md:pb-16 bg-white mobile-container",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{id:"books-collection-header",className:"text-center mb-8 sm:mb-12",children:[e.jsx("h2",{className:"section-title",children:"Our Bestselling Books"}),e.jsxs("p",{className:"section-description hidden md:block",children:["Browse our collection of magical adventures where your child can become the hero. A thoughtful gift that children return to again and again."," ",e.jsx("a",{href:t("/why-personalised-books"),className:"text-purple-600 hover:text-purple-700 font-medium transition-colors",children:"Learn why →"})]})]}),e.jsx("div",{className:"md:hidden grid grid-cols-2 gap-1.5 -mx-3 px-0.5 items-stretch",children:(()=>{const g=[16,17,15,22,13,14,7,9,18,5,6,2,1,10,4,8],f=Ot.filter(j=>!j.hidden),v=[];for(const j of g){const b=f.find(y=>y.id===j);b&&v.push(b)}const x=f.filter(j=>!g.includes(j.id));return[...v,...x]})().map((g,f)=>e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:f*.1},className:"bg-white rounded-xl overflow-hidden shadow-lg flex flex-col h-full",children:[e.jsx("div",{className:"relative w-full aspect-square cursor-pointer",onClick:()=>c(g.id),children:o(g.id)?e.jsx("img",{src:l(g.id),alt:Hs(g.title),className:"w-full h-full object-cover transition-opacity duration-300",loading:"lazy",decoding:"async"}):e.jsx($s,{imagePath:g.imagePaths[0],alt:Hs(g.title),className:"w-full h-full object-cover",loading:"lazy",decoding:"async"})}),e.jsxs("div",{className:"p-3",children:[e.jsx("h3",{className:"text-base font-semibold text-purple-900 mb-2 min-h-[2.5rem] flex items-center leading-tight",children:Hs(g.title)}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-semibold ${g.suitableFor.toLowerCase().includes("boy")?"bg-blue-500 text-white":g.suitableFor.toLowerCase().includes("girl")?"bg-pink-500 text-white":"bg-orange-500 text-white"}`,children:g.suitableFor.toLowerCase().includes("boy")&&!g.suitableFor.toLowerCase().includes("girl")?"Boys":g.suitableFor.toLowerCase().includes("girl")&&!g.suitableFor.toLowerCase().includes("boy")?"Girls":g.suitableFor}),e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full text-xs",children:g.ageRange})]}),e.jsx("button",{onClick:()=>c(g.id),className:"w-full bg-black text-white font-medium px-4 py-2 rounded-full text-sm shadow-sm active:opacity-80 transition-opacity","data-track":"Home_Create_Free_Preview","data-book-id":g.id.toString(),"data-book-name":g.title,children:"Personalise"})]})]},g.id))}),e.jsxs("div",{className:"hidden md:block",children:[(()=>{const g=Ot.filter(f=>!f.hidden&&(f.suitableFor.toLowerCase().includes("boy")||f.suitableFor==="All Genders"));return g.length===0?null:e.jsxs("div",{className:"mb-16",children:[e.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-6",children:"Books for your little Boy"}),e.jsx("div",{className:"flex gap-6 overflow-x-auto pb-4 scrollbar-hide",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:g.map((f,v)=>e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:v*.1},className:"flex-shrink-0 w-[280px] bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition-shadow relative flex flex-col h-full",onMouseEnter:()=>u(f.id),children:[e.jsx("div",{className:"relative w-full aspect-square cursor-pointer",onClick:()=>c(f.id),children:o(f.id)?e.jsx("img",{src:l(f.id),alt:Hs(f.title),className:"w-full h-full object-cover transition-opacity duration-300",loading:"lazy",decoding:"async"}):e.jsx($s,{imagePath:f.imagePaths[0],alt:Hs(f.title),className:"w-full h-full object-cover",loading:"lazy",decoding:"async"})}),e.jsxs("div",{className:"p-6 flex flex-col flex-grow",children:[e.jsx("h3",{className:"text-xl font-semibold text-purple-900 mb-2 min-h-[3.5rem] flex items-center",children:Hs(f.title)}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[f.category_tag&&e.jsx("span",{className:"px-2 py-1 bg-purple-100 text-purple-700 rounded-full text-xs",children:f.category_tag}),f.specialTag&&e.jsx("span",{className:"px-2 py-1 bg-pink-100 text-pink-700 rounded-full text-xs",children:f.specialTag}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-semibold ${f.suitableFor.toLowerCase().includes("boy")?"bg-blue-500 text-white":f.suitableFor.toLowerCase().includes("girl")?"bg-pink-500 text-white":"bg-orange-500 text-white"}`,children:f.suitableFor.toLowerCase().includes("boy")&&!f.suitableFor.toLowerCase().includes("girl")?"Suitable for: Boys":f.suitableFor.toLowerCase().includes("girl")&&!f.suitableFor.toLowerCase().includes("boy")?"Suitable for: Girls":`Suitable for: ${f.suitableFor}`}),e.jsx("span",{className:"px-2 py-1 bg-blue-100 text-blue-700 rounded-full text-xs",children:f.ageRange}),e.jsxs("span",{className:"px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs",children:[f.pages," pages"]})]}),e.jsx("div",{className:"flex-grow"}),e.jsx(wt,{onClick:()=>c(f.id),className:"w-full justify-center mt-4 whitespace-nowrap","data-track":"Home_Create_Free_Preview","data-book-id":f.id.toString(),"data-book-name":f.title,children:"Personalise"})]})]},f.id))})]})})(),(()=>{const g=Ot.filter(f=>!f.hidden&&f.suitableFor.toLowerCase().includes("girl")&&!f.suitableFor.toLowerCase().includes("boy"));return g.length===0?null:e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-6",children:"Books for your little Girl"}),e.jsx("div",{className:"flex gap-6 overflow-x-auto pb-4 scrollbar-hide",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:g.map((f,v)=>e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:v*.1},className:"flex-shrink-0 w-[280px] bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition-shadow relative flex flex-col h-full",onMouseEnter:()=>u(f.id),children:[e.jsx("div",{className:"relative w-full aspect-square cursor-pointer",onClick:()=>c(f.id),children:o(f.id)?e.jsx("img",{src:l(f.id),alt:Hs(f.title),className:"w-full h-full object-cover transition-opacity duration-300",loading:"lazy",decoding:"async"}):e.jsx($s,{imagePath:f.imagePaths[0],alt:Hs(f.title),className:"w-full h-full object-cover",loading:"lazy",decoding:"async"})}),e.jsxs("div",{className:"p-6 flex flex-col flex-grow",children:[e.jsx("h3",{className:"text-xl font-semibold text-purple-900 mb-2 min-h-[3.5rem] flex items-center",children:Hs(f.title)}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[f.category_tag&&e.jsx("span",{className:"px-2 py-1 bg-purple-100 text-purple-700 rounded-full text-xs",children:f.category_tag}),f.specialTag&&e.jsx("span",{className:"px-2 py-1 bg-pink-100 text-pink-700 rounded-full text-xs",children:f.specialTag}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-semibold ${f.suitableFor.toLowerCase().includes("boy")?"bg-blue-500 text-white":f.suitableFor.toLowerCase().includes("girl")?"bg-pink-500 text-white":"bg-orange-500 text-white"}`,children:f.suitableFor.toLowerCase().includes("boy")&&!f.suitableFor.toLowerCase().includes("girl")?"Suitable for: Boys":f.suitableFor.toLowerCase().includes("girl")&&!f.suitableFor.toLowerCase().includes("boy")?"Suitable for: Girls":`Suitable for: ${f.suitableFor}`}),e.jsx("span",{className:"px-2 py-1 bg-blue-100 text-blue-700 rounded-full text-xs",children:f.ageRange}),e.jsxs("span",{className:"px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs",children:[f.pages," pages"]})]}),e.jsx("div",{className:"flex-grow"}),e.jsx(wt,{onClick:()=>c(f.id),className:"w-full justify-center mt-4 whitespace-nowrap","data-track":"Home_Create_Free_Preview","data-book-id":f.id.toString(),"data-book-name":f.title,children:"Personalise"})]})]},f.id))})]})})()]})]})})]})},nw=[{name:"Vimal",role:"Co-Founder",image:"/vimal.jpeg",linkedin:"https://www.linkedin.com/in/vimal-jangid/"},{name:"Vaibhav",role:"Co-Founder",image:"/vaibhav.jpeg",linkedin:"https://www.linkedin.com/in/1vaibhavbhargava/"},{name:"Pavithrra",role:"Co-Founder",image:"/pavithrra.jpeg",linkedin:"https://www.linkedin.com/in/pavithrra-venkatraman-b64b4619/"}],iw=()=>{const r=p.useRef(null),{region:t}=ht(),s=t==="IN",a=[{icon:e.jsx(Ba,{className:"w-7 h-7 text-purple-600"}),title:"Magical AI",description:"Our AI technology creates seamless integration of your child's likeness into story illustrations"},{icon:e.jsx(Ls,{className:"w-7 h-7 text-purple-600"}),title:"Engaging Stories",description:"Professional writers craft captivating narratives that inspire imagination and joy"},{icon:e.jsx(bu,{className:"w-7 h-7 text-purple-600"}),title:"Privacy First",description:"Your photos remain private and secure, used only to create your personalized book"},{icon:e.jsx($o,{className:"w-7 h-7 text-purple-600"}),title:"Quality Guarantee",description:"Premium hardcover books with vibrant colors and durable binding, made to last"}];return e.jsx("section",{id:"about",className:"py-6 sm:py-16 bg-white mobile-container",children:e.jsxs("div",{className:"container mx-auto",children:[e.jsxs("div",{className:"text-center mb-8 sm:mb-12",children:[e.jsx("h2",{className:"section-title",children:"About TalesBerry"}),e.jsx("p",{className:"section-description",children:"We combine cutting-edge AI technology with magical storytelling to create unforgettable personalized books."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 sm:gap-8 mb-8 sm:mb-12",children:[e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.1},className:"bg-white rounded-xl p-5 sm:p-6 shadow-sm",children:[e.jsx("h3",{className:"text-xl font-semibold text-purple-900 mb-3 sm:mb-4",children:"Our Story"}),e.jsx("p",{className:"text-gray-700 mb-3 sm:mb-4 text-base",children:"TalesBerry was born from a simple idea: what if children could see themselves in the stories they love? Our team of writers, illustrators, and AI specialists came together to create a unique experience that transforms ordinary photos into extraordinary adventures."}),e.jsx("p",{className:"text-gray-700 text-base mb-6",children:"Each book is crafted with care, ensuring that your child's likeness is beautifully integrated into the story while maintaining the highest quality standards in children's literature."}),s&&e.jsxs("div",{className:"border-t border-purple-100 pt-6",children:[e.jsx("h4",{className:"text-lg font-semibold text-purple-900 mb-4 text-center",children:"Meet Our Team"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:nw.map((n,i)=>e.jsxs("div",{className:"text-center",children:[e.jsx("a",{href:n.linkedin,target:"_blank",rel:"noopener noreferrer",className:"block relative mx-auto mb-2 w-16 h-16 sm:w-20 sm:h-20 group",children:e.jsx("img",{src:n.image,alt:n.name,className:"w-full h-full object-cover rounded-full border-2 border-purple-100 group-hover:border-purple-400 transition-colors"})}),e.jsx("h5",{className:"text-sm font-semibold text-purple-900",children:n.name}),e.jsx("p",{className:"text-gray-600 text-xs",children:n.role})]},i))})]})]}),e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.2},className:"bg-white rounded-xl p-5 sm:p-6 shadow-sm",children:[e.jsx("h3",{className:"text-xl font-semibold text-purple-900 mb-3 sm:mb-4",children:"Our Technology"}),e.jsx("p",{className:"text-gray-700 mb-6 text-base",children:"TalesBerry uses proprietary AI technology to carefully transform your child's photos into beautiful, illustration-style characters that match the book's aesthetic while preserving your child's unique features and expressions."}),e.jsx("div",{className:"hidden md:grid md:grid-cols-2 gap-4",children:a.map((n,i)=>e.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 text-center",children:[e.jsx("div",{className:"bg-white w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-3",children:n.icon}),e.jsx("h4",{className:"text-lg font-semibold text-purple-900 mb-2",children:n.title}),e.jsx("p",{className:"text-sm text-gray-700",children:n.description})]},i))}),e.jsx("div",{ref:r,className:"md:hidden overflow-x-auto -mx-5 px-5 pb-4",children:e.jsx("div",{className:"flex gap-4",style:{minWidth:"max-content"},children:a.map((n,i)=>e.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 text-center w-[260px] flex-shrink-0",children:[e.jsx("div",{className:"bg-white w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-3",children:n.icon}),e.jsx("h4",{className:"text-lg font-semibold text-purple-900 mb-2",children:n.title}),e.jsx("p",{className:"text-sm text-gray-700",children:n.description})]},i))})})]})]})]})})},ow=({onSubmit:r,selectedBook:t})=>{const[s,a]=p.useState({name:"",age:"",gender:"",email:""}),i=(()=>{if(!(t!=null&&t.ageRange))return Array.from({length:12},(c,u)=>u+1);const l=t.ageRange.match(/(\d+)-(\d+)/);if(l){const c=parseInt(l[1]),u=parseInt(l[2]);return Array.from({length:u-c+1},(d,h)=>c+h)}return Array.from({length:12},(c,u)=>u+1)})(),o=l=>{var u,d;l.preventDefault();const c=(u=s.name)==null?void 0:u.trim();if(!c||!s.age||!s.gender||!((d=s.email)!=null&&d.trim())){alert("Please fill in all fields");return}r({...s,name:c,email:s.email.trim()})};return e.jsx("div",{className:"bg-gradient-to-br from-purple-50 via-blue-50 to-pink-50 min-h-screen pt-8",children:e.jsxs("div",{className:"max-w-md mx-auto px-4",children:[e.jsx("div",{className:"text-center mb-6",children:e.jsx("h1",{className:"text-2xl font-bold text-purple-900",children:"Add your child details"})}),e.jsxs("form",{onSubmit:o,className:"bg-white rounded-xl p-6 shadow-lg",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{htmlFor:"name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's Name"}),e.jsx("input",{type:"text",id:"name",required:!0,value:s.name,onChange:l=>a({...s,name:l.target.value}),className:"w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"Enter child's name"})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{htmlFor:"age",className:"block text-sm font-medium text-gray-700 mb-2",children:"Age"}),e.jsxs("select",{id:"age",required:!0,value:s.age,onChange:l=>a({...s,age:l.target.value}),className:"w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",children:[e.jsx("option",{value:"",children:"Select age"}),i.map(l=>e.jsxs("option",{value:l,children:[l," year",l!==1?"s":""]},l))]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Gender"}),e.jsx("div",{className:"flex gap-4",children:["Boy","Girl"].map(l=>e.jsxs("label",{className:`
                  flex-1 flex items-center justify-center p-3 border-2 rounded-lg cursor-pointer transition-all
                  ${s.gender===l?"border-purple-500 bg-purple-50 text-purple-700":"border-gray-200 hover:border-purple-200"}
                `,children:[e.jsx("input",{type:"radio",name:"gender",value:l,checked:s.gender===l,onChange:c=>a({...s,gender:c.target.value}),className:"sr-only",required:!0}),l]},l))})]}),e.jsxs("div",{className:"mb-8",children:[e.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Email address (to receive soft copy of the book)"}),e.jsx("input",{type:"email",id:"email",required:!0,value:s.email,onChange:l=>a({...s,email:l.target.value}),className:"w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"enter your email here"})]}),e.jsx(wt,{type:"submit",className:"w-full",children:"Continue"})]})]})})},lw=({childData:r,onSelect:t})=>{const[s,a]=p.useState(0),n=(d,h)=>{const m=d.match(/(\d+)-(\d+)/);if(!m)return!1;const g=parseInt(m[1]),f=parseInt(m[2]),v=parseInt(h);return v>=g&&v<=f},i=p.useMemo(()=>Ot.filter(d=>{const h=d.suitableFor==="All genders"||d.suitableFor==="All Genders"||d.suitableFor===r.gender,m=n(d.ageRange,r.age);return h&&m}),[r.gender,r.age]);if(jt.useEffect(()=>{s>=i.length&&i.length>0&&a(0)},[i.length,s]),i.length===0)return e.jsxs("div",{className:"max-w-4xl mx-auto text-center",children:[e.jsxs("p",{className:"text-lg text-gray-600 mb-4",children:["Sorry, we don't have any stories that match ",r.name,"'s profile at the moment."]}),e.jsx("p",{className:"text-gray-600",children:"Please try again with different information or contact us for assistance."})]});const o=()=>{a(d=>{const h=Math.max(0,i.length-2);return Math.min(d+1,h)})},l=()=>{a(d=>Math.max(d-1,0))},c=s<i.length-2,u=s>0;return e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("p",{className:"text-center text-lg text-gray-600 mb-8",children:["Here are some stories we think ",r.name," will love"]}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"flex gap-6 overflow-x-auto scrollbar-visible pb-4",style:{scrollbarWidth:"thin"},children:e.jsx("div",{className:"flex gap-6 transition-transform duration-300",style:{transform:`translateX(-${s*(100/2)}%)`},children:i.map((d,h)=>e.jsx(Ie.div,{className:"flex-shrink-0 w-[calc(50%-12px)]",initial:{opacity:0,x:20},animate:{opacity:1,x:0},transition:{delay:h*.1},children:e.jsxs("div",{className:"bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition-shadow flex flex-col h-full",children:[e.jsx("div",{className:"relative w-full overflow-hidden",style:{aspectRatio:"1/1"},children:e.jsx($s,{imagePath:d.imagePaths[0],alt:d.title,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"p-6 flex-1 flex flex-col",children:[e.jsx("h3",{className:"text-xl font-semibold text-purple-900 mb-2 line-clamp-2",children:d.title}),e.jsx("p",{className:"text-gray-600 mb-4 text-sm line-clamp-3 flex-1",children:d.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx("span",{className:"px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm",children:d.theme}),e.jsx("span",{className:"px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm",children:d.ageRange}),e.jsx("span",{className:"px-3 py-1 bg-pink-100 text-pink-700 rounded-full text-sm",children:d.suitableFor}),e.jsxs("span",{className:"px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm",children:[d.pages," pages"]})]}),e.jsx("button",{onClick:()=>t(d),className:"w-full bg-gradient-to-r from-purple-600 to-blue-500 text-white py-3 rounded-lg font-medium hover:shadow-lg transition-shadow mt-auto",children:"Choose This Story"})]})]})},d.id))})}),i.length>2&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:l,disabled:!u,className:`absolute left-0 top-1/2 -translate-y-1/2 bg-white p-3 rounded-full shadow-lg transition-opacity ${u?"opacity-100 hover:bg-gray-50":"opacity-40 cursor-not-allowed"}`,"aria-label":"Previous books",children:e.jsx(Ut,{className:"w-6 h-6 text-purple-600"})}),e.jsx("button",{onClick:o,disabled:!c,className:`absolute right-0 top-1/2 -translate-y-1/2 bg-white p-3 rounded-full shadow-lg transition-opacity ${c?"opacity-100 hover:bg-gray-50":"opacity-40 cursor-not-allowed"}`,"aria-label":"Next books",children:e.jsx(gs,{className:"w-6 h-6 text-purple-600"})})]})]}),e.jsxs("div",{className:"md:hidden",children:[e.jsx("div",{className:"overflow-hidden",children:e.jsx("div",{className:"flex transition-transform duration-300",style:{transform:`translateX(-${s*100}%)`},children:i.map(d=>e.jsx(Ie.div,{className:"w-full flex-shrink-0 px-4",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e.jsxs("div",{className:"bg-white rounded-xl overflow-hidden shadow-lg flex flex-col h-full",children:[e.jsx("div",{className:"relative w-full overflow-hidden",style:{aspectRatio:"1/1"},children:e.jsx($s,{imagePath:d.imagePaths[0],alt:d.title,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"p-6 flex-1 flex flex-col",children:[e.jsx("h3",{className:"text-xl font-semibold text-purple-900 mb-2",children:d.title}),e.jsx("p",{className:"text-gray-600 mb-4 flex-1",children:d.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx("span",{className:"px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm",children:d.theme}),e.jsx("span",{className:"px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm",children:d.ageRange}),e.jsx("span",{className:"px-3 py-1 bg-pink-100 text-pink-700 rounded-full text-sm",children:d.suitableFor}),e.jsxs("span",{className:"px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm",children:[d.pages," pages"]})]}),e.jsx("button",{onClick:()=>t(d),className:"w-full bg-gradient-to-r from-purple-600 to-blue-500 text-white py-3 rounded-lg font-medium hover:shadow-lg transition-shadow mt-auto",children:"Choose This Story"})]})]})},d.id))})}),i.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>a(Math.max(s-1,0)),className:"absolute left-0 top-1/2 -translate-y-1/2 bg-white p-2 rounded-full shadow-lg","aria-label":"Previous book",children:e.jsx(Ut,{className:"w-6 h-6 text-purple-600"})}),e.jsx("button",{onClick:()=>a(Math.min(s+1,i.length-1)),className:"absolute right-0 top-1/2 -translate-y-1/2 bg-white p-2 rounded-full shadow-lg","aria-label":"Next book",children:e.jsx(gs,{className:"w-6 h-6 text-purple-600"})})]})]})]}),i.length>1&&e.jsxs("div",{className:"flex justify-center mt-6 gap-2",children:[e.jsx("div",{className:"hidden md:flex gap-2",children:Array.from({length:Math.ceil(i.length/2)}).map((d,h)=>e.jsx("button",{onClick:()=>a(h),className:`w-3 h-3 rounded-full transition-colors ${h===s?"bg-purple-600":"bg-purple-200"}`,"aria-label":`Go to books ${h*2+1}-${Math.min(h*2+2,i.length)}`},h))}),e.jsx("div",{className:"md:hidden flex gap-2",children:i.map((d,h)=>e.jsx("button",{onClick:()=>a(h),className:`w-3 h-3 rounded-full transition-colors ${h===s?"bg-purple-600":"bg-purple-200"}`,"aria-label":`Go to book ${h+1}`},h))})]})]})},cw=({book:r,onComplete:t})=>{const[s,a]=jt.useState(null),[n,i]=jt.useState(null),[o,l]=jt.useState(!1),[c,u]=jt.useState({}),[d,h]=jt.useState({}),m=jt.useRef({}),g=[{id:"hard-10x10",title:"Hard Cover - 10x10 inch",description:"Premium look and feel, perfect for gifting or own use • Thick hard cover ensures books lasts for years • Larger book size, better suited for kids aged 6 and above",price:1,discountedPrice:1,video:"/videos/product_quality2.mp4",recommended:!0},{id:"hard-8.75x8.75",title:"Hard Cover - 8.75x8.75 inch",description:"Premium look and feel, perfect for gifting or own use • Thick hard cover ensures books lasts for years • More handy book size for younger kids, between ages 1-6 years",price:1,video:"/videos/product_quality4.mp4"}],f=b=>{a(b)},v=()=>{if(!s)return;const b=g.find(y=>y.id===s);b&&(l(!0),setTimeout(()=>{t(b),setTimeout(()=>{l(!1)},5e3)},100))},x=(b,y)=>{b&&(b.preload="auto",b.playsInline=!0,b.addEventListener("loadedmetadata",()=>{console.log(`Video ${y} metadata loaded, streaming ready`)}),b.addEventListener("waiting",()=>{console.log(`Video ${y} buffering`),u(S=>({...S,[y]:!0}))}),b.addEventListener("canplay",()=>{console.log(`Video ${y} can play with current data`),u(S=>({...S,[y]:!1}))}),b.addEventListener("progress",()=>{if(b.buffered.length>0){const S=b.buffered.end(0),T=b.duration||1,I=Math.round(S/T*100);h(E=>({...E,[y]:I})),console.log(`Video ${y} buffered: ${I}%`)}}))},j=(b,y)=>{var T;y.stopPropagation();const S=m.current[b];if(n===b)S&&(S.pause(),console.log(`Paused video ${b}`)),i(null);else{if(n&&m.current[n]&&((T=m.current[n])==null||T.pause()),S){S.volume=1,S.muted=!1,S.currentTime=0,u(E=>({...E,[b]:!0}));const I=S.play();I!==void 0&&I.then(()=>{console.log(`Playing video ${b} successfully`),u(E=>({...E,[b]:!1}))}).catch(E=>{console.error(`Error playing video ${b}:`,E),S.muted=!0,S.play().then(()=>{S.muted=!1,u(O=>({...O,[b]:!1}))}).catch(O=>{console.error(`Second attempt to play video ${b} failed:`,O),u(V=>({...V,[b]:!1}))})})}i(b)}};return p.useEffect(()=>{i(null),a(null),console.log("Book changed in BookQuality component:",r.title)},[r]),p.useEffect(()=>{const b=g.filter(y=>y.video);return console.log("Setting up video preloading for product quality videos"),b.forEach(y=>{if(y.video){u(T=>({...T,[y.id]:!0})),h(T=>({...T,[y.id]:0}));const S=document.createElement("video");if(S.src=y.video,S.preload="auto",S.muted=!0,S.playsInline=!0,S.oncanplaythrough=()=>{console.log(`Video ${y.id} can play through`),u(T=>({...T,[y.id]:!1}))},S.onprogress=()=>{if(S.buffered.length>0){const T=S.buffered.end(0),I=S.duration||1,E=Math.round(T/I*100);h(O=>({...O,[y.id]:E})),console.log(`Video ${y.id} buffered: ${E}%`)}},S.onerror=T=>{console.error(`Error loading video ${y.id}:`,T),u(I=>({...I,[y.id]:!1}))},m.current[y.id]){const T=m.current[y.id];T&&(x(T,y.id),T.preload="auto",T.muted=!1,T.volume=1,T.playsInline=!0,T.onwaiting=()=>u(I=>({...I,[y.id]:!0})),T.onplaying=()=>u(I=>({...I,[y.id]:!1})),T.oncanplaythrough=()=>u(I=>({...I,[y.id]:!1})),T.onerror=()=>{var I;console.error(`Video ${y.id} error: ${((I=T.error)==null?void 0:I.code)||"unknown"}`),u(E=>({...E,[y.id]:!1}))},T.onprogress=()=>{if(T.buffered.length>0){const I=T.buffered.end(0),E=T.duration||1,O=Math.round(I/E*100);h(V=>({...V,[y.id]:O}))}},T.load())}}}),()=>{Object.keys(m.current).forEach(y=>{const S=m.current[y];S&&(S.pause(),S.src="",S.load())})}},[]),p.useEffect(()=>{window.scrollTo(0,0)},[]),e.jsx("div",{className:"bg-gradient-to-br from-purple-50 via-blue-50 to-pink-50 min-h-screen pt-8",children:e.jsxs("div",{className:"max-w-4xl mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold text-purple-900 mb-2",children:"Select the Book Size"}),e.jsx("p",{className:"text-lg text-gray-600",children:"Choose the perfect size for your child's adventure"})]}),e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:g.map(b=>e.jsxs("div",{className:`
              bg-white border-2 rounded-xl overflow-hidden cursor-pointer transition-all duration-300 relative
              ${s===b.id?"border-purple-500 ring-2 ring-purple-200 transform scale-[1.02]":"border-gray-200 hover:border-purple-300 hover:shadow-xl"}
            `,onClick:()=>f(b.id),children:[e.jsx("div",{className:"absolute top-4 left-4 z-10",children:e.jsx("div",{className:`
                w-5 h-5 rounded-full border-2 flex items-center justify-center
                ${s===b.id?"border-purple-500 bg-purple-500":"border-gray-300 bg-white"}
              `,children:s===b.id&&e.jsx("div",{className:"w-2 h-2 bg-white rounded-full"})})}),b.recommended&&e.jsx("div",{className:"absolute top-0 right-0 bg-purple-600 text-white text-xs px-2 py-1 rounded-bl-lg z-10",children:"Recommended"}),e.jsx("div",{className:`${b.video?"relative aspect-square bg-gray-100 overflow-hidden":"aspect-square bg-gray-100 flex items-center justify-center"}`,children:b.video?e.jsxs(e.Fragment,{children:[e.jsx("video",{ref:y=>{y&&(m.current[b.id]=y,x(y,b.id))},className:"w-full h-full object-cover",src:b.video,muted:!1,loop:!0,playsInline:!0,preload:"auto"}),c[b.id]&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black bg-opacity-30",children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-purple-600 bg-opacity-80",children:e.jsx(jn,{size:36,className:"text-white animate-spin"})}),e.jsx("div",{className:"mt-3 bg-white/30 w-32 h-1.5 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-purple-500 transition-all duration-300",style:{width:`${d[b.id]||0}%`}})}),e.jsxs("p",{className:"text-xs text-white mt-1",children:[d[b.id]||0,"% loaded"]})]})}),n!==b.id&&!c[b.id]&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black bg-opacity-30",onClick:y=>j(b.id,y),children:e.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-purple-600 bg-opacity-80",children:e.jsx(Ca,{size:36,className:"text-white ml-1"})})}),n===b.id&&!c[b.id]&&e.jsx("div",{className:"absolute bottom-4 right-4 z-10 bg-purple-600 bg-opacity-80 rounded-full p-2",onClick:y=>{var S;y.stopPropagation(),i(null),m.current[b.id]&&((S=m.current[b.id])==null||S.pause())},children:e.jsx(yu,{size:24,className:"text-white"})})]}):e.jsx("span",{className:"text-gray-400",children:"No preview available"})}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"font-bold text-lg text-purple-900 mb-2",children:b.title}),e.jsx("div",{className:"text-gray-600 text-sm mb-4",children:b.description.split(" • ").map((y,S)=>e.jsxs("div",{className:"flex items-start mb-1",children:[e.jsx("span",{className:"text-purple-600 mr-2",children:"•"}),e.jsx("span",{children:y})]},S))}),e.jsx("div",{className:"mb-3",children:b.discountedPrice?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-gray-500 line-through",children:["₹",b.price,"/-"]}),e.jsxs("span",{className:"font-bold text-purple-900",children:["₹",b.discountedPrice,"/-"]}),e.jsx("span",{className:"bg-green-100 text-green-700 text-xs px-2 py-1 rounded-full",children:"10% off"})]}):e.jsxs("span",{className:"font-bold text-purple-900",children:["₹",b.price,"/-"]})}),e.jsx("p",{className:"text-xs text-gray-500 italic",children:"Free shipping across India!"})]})]},b.id))}),e.jsxs("div",{className:"mt-10 text-center",children:[e.jsx(wt,{onClick:v,className:`
            px-8 py-3 w-full max-w-md mx-auto relative
            ${s?"":"opacity-70 cursor-not-allowed"}
          `,disabled:o||!s,children:e.jsx("div",{className:"flex items-center justify-center",children:o?e.jsxs(e.Fragment,{children:[e.jsx(jn,{size:20,className:"animate-spin mr-2"}),"Redirecting..."]}):e.jsxs(e.Fragment,{children:["Place Your Order!",e.jsx("div",{className:"ml-2 h-6 w-6 bg-[#25D366] rounded-full flex items-center justify-center",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 175.216 175.552",width:"16",height:"16",fill:"#ffffff",children:[e.jsx("path",{d:"M175.216,85.138l-.008-2.012c0-.743-.029-1.482-.073-2.224-.6-10.321-3.031-20.217-7.084-29.478a87.367,87.367,0,0,0-31.868-38.6A87.263,87.263,0,0,0,87.609,0h-.159A87.784,87.784,0,0,0,9.2,60.249a87.08,87.08,0,0,0-5,15.359A88.354,88.354,0,0,0,2.8,87.608q0,1.465.057,2.926c.04,1.154.115,2.3.215,3.441a87.518,87.518,0,0,0,5.633,22.541,85.928,85.928,0,0,0,5.552,10.8a21.341,21.341,0,0,1,2.833,11.013l-4.662,31.007a5.22,5.22,0,0,0,5.12,6.213,5.433,5.433,0,0,0,.792-.06l31.04-4.681a20.063,20.063,0,0,1,3.036-.234,20.8,20.8,0,0,1,7.854,1.571l.021.7.027.014a87.551,87.551,0,0,0,39.7,9.383h.117a87.402,87.402,0,0,0,58.814-22.894A87.257,87.257,0,0,0,175.208,95.05c.007-.083.008-.168.008-.255Z",style:{fill:"#25d366"}}),e.jsx("path",{d:"M134.527,127.553c-4.48,6.311-11.11,14.136-19.346,16a34.8,34.8,0,0,1-3.241.523c-6.569.642-13.646-1.627-26.624-9.525-14.446-8.764-27.571-25.945-34.09-38.118a48.483,48.483,0,0,1-6.414-18.368c-.226-2.028-.354-3.989-.408-5.6-.055-1.424.008-2.778.155-4.063a17.825,17.825,0,0,1,3.7-8.739l.416-.525a10.035,10.035,0,0,1,2.546-2.155,6.692,6.692,0,0,1,9.764,2.527l.6.141c3.6,8.115,4.187,9.856,3.859,12.3a12.786,12.786,0,0,1-2.417,5.463l-.848,1.186a42.556,42.556,0,0,0,8.923,10.631,76.837,76.837,0,0,0,6.64,5.273,42.423,42.423,0,0,0,12.635,6.645l.812-1.067a12.788,12.788,0,0,1,4.609-3.873,6.186,6.186,0,0,1,8,1.841c3.811,5.009,8.409,11.485,8.409,11.485a6.755,6.755,0,0,1-1.08,7.507Z",style:{fill:"#ffffff"}})]})})]})})}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"You'll be redirected to WhatsApp to complete your order"})]})]})})};function Yt(){return e.jsx(as,{children:e.jsx("meta",{name:"robots",content:"noindex, nofollow"})})}const dw=()=>{var g;const t=(g=Jt().state)==null?void 0:g.selectedBook,[s,a]=p.useState(1),[n,i]=p.useState(null),[o,l]=p.useState(t||null);p.useEffect(()=>{window.scrollTo(0,0)},[s]);const c=f=>{i(f),a(o?3:2)},u=f=>{l(f),a(3)},d=f=>{m(f)},h=()=>{a(s-1)},m=f=>{if(!n||!o)return;const v=encodeURIComponent(`Hi! I would like to know more about the TalesBerry personalised books. Here are some details of my child:

*Name:* ${n.name}
*Age:* ${n.age}
*Gender:* ${n.gender}
*Book Theme:* ${o.title}
*Book Type:* ${f.title}
*Price:* ₹${f.discountedPrice||f.price}/- (Free shipping across India)`);window.location.href=`https://wa.me/919535791242?text=${v}`};return e.jsxs("div",{className:"min-h-screen pb-10 bg-gradient-to-br from-purple-50 via-blue-50 to-pink-50",children:[e.jsx(Yt,{}),e.jsxs("div",{className:"container mx-auto px-4",children:[s>1&&e.jsxs("button",{onClick:h,className:"mb-6 flex items-center text-black hover:text-gray-700 transition-colors",children:[e.jsx(Io,{className:"w-5 h-5 mr-2"}),"Back"]}),e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"relative w-full h-2 bg-purple-100 rounded-full mt-4",children:[e.jsx("div",{className:"absolute left-0 top-0 h-full bg-purple-600 rounded-full transition-all duration-500",style:{width:`${o?s/3*100:s/4*100}%`}}),e.jsx("div",{className:"flex justify-between absolute w-full top-0 px-1 transform -translate-y-1/2",children:(o?[1,2,3]:[1,2,3,4]).map(f=>e.jsx("div",{className:`
                    w-6 h-6 rounded-full flex items-center justify-center z-10
                    ${f<=s?"bg-purple-600 text-white":"bg-white border-2 border-purple-200 text-purple-400"}
                  `,children:f},f))}),e.jsx("div",{className:"flex justify-between absolute w-full transform translate-y-8 px-1 text-xs sm:text-sm",children:o?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-center w-14 -ml-3 sm:w-20 sm:-ml-6",children:e.jsx("span",{className:"font-medium bg-white bg-opacity-75 px-1 md:px-2 py-0.5 rounded",children:"Child Info"})}),e.jsx("div",{className:"text-center w-14 sm:w-16",children:e.jsx("span",{className:"font-medium bg-white bg-opacity-75 px-1 md:px-2 py-0.5 rounded",children:"Quality"})}),e.jsx("div",{className:"text-center w-14 -mr-3 sm:w-16 sm:-mr-4",children:e.jsx("span",{className:"font-medium bg-white bg-opacity-75 px-1 md:px-2 py-0.5 rounded",children:"Order"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-center w-14 -ml-3 sm:w-20 sm:-ml-6",children:e.jsx("span",{className:"font-medium bg-white bg-opacity-75 px-1 md:px-2 py-0.5 rounded",children:"Child Info"})}),e.jsx("div",{className:"text-center w-14 sm:w-16",children:e.jsx("span",{className:"font-medium bg-white bg-opacity-75 px-1 md:px-2 py-0.5 rounded",children:"Story"})}),e.jsx("div",{className:"text-center w-14 sm:w-16",children:e.jsx("span",{className:"font-medium bg-white bg-opacity-75 px-1 md:px-2 py-0.5 rounded",children:"Details"})}),e.jsx("div",{className:"text-center w-14 -mr-3 sm:w-16 sm:-mr-4",children:e.jsx("span",{className:"font-medium bg-white bg-opacity-75 px-1 md:px-2 py-0.5 rounded",children:"Order"})})]})})]})}),e.jsx(ks,{mode:"wait",children:e.jsxs(Ie.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},transition:{duration:.3},className:"mt-20",children:[s===1&&e.jsx(ow,{onSubmit:c,selectedBook:o}),s===2&&n&&!o&&e.jsx(lw,{childData:n,onSelect:u}),(s===2&&o||s===3&&o)&&e.jsx(cw,{book:o,onComplete:d})]},s)})]})]})},uw=({showFilters:r,filterOptions:t,activeFilters:s,categoryTags:a,onFilterChange:n,onCategoryTagChange:i,onClearFilters:o})=>r?e.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-md mb-8 animate-slide-up",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("h3",{className:"font-semibold text-lg flex items-center",children:[e.jsx(gu,{className:"w-5 h-5 mr-2 text-purple-600"})," Filter By"]}),e.jsx(wt,{onClick:o,className:"text-sm bg-transparent text-gray-500 hover:text-purple-600 p-0 shadow-none",children:"Clear All"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2 text-gray-700",children:"Categories"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(l=>e.jsx("button",{onClick:()=>i(l.value),className:`px-3 py-1 rounded-full text-sm font-medium transition-colors ${s.categoryTag===l.value?"bg-purple-100 text-purple-700 border border-purple-300":"bg-gray-100 text-gray-700 border border-gray-200 hover:bg-gray-200"}`,children:l.label},l.value))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2 text-gray-700",children:"Gender"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.gender.map(l=>e.jsx("button",{onClick:()=>n("gender",l),className:`px-3 py-1 rounded-full text-sm font-medium transition-colors ${s.gender.includes(l)?"bg-purple-100 text-purple-700 border border-purple-300":"bg-gray-100 text-gray-700 border border-gray-200 hover:bg-gray-200"}`,children:l},l))})]})]})]}):null,hw=({books:r})=>{const t=_t(),{region:s,buildLink:a}=ht(),[n,i]=p.useState(!1);p.useEffect(()=>{const h=()=>i(window.innerWidth<768);return h(),window.addEventListener("resize",h),()=>window.removeEventListener("resize",h)},[]);const o=p.useMemo(()=>{if(!n)return r;const h=r.filter(x=>x.suitableFor.toLowerCase().includes("boy")),m=r.filter(x=>x.suitableFor.toLowerCase().includes("girl")),g=r.filter(x=>!h.includes(x)&&!m.includes(x)),f=[],v=Math.max(h.length,m.length);for(let x=0;x<v;x++)x<h.length&&f.push(h[x]),x<m.length&&f.push(m[x]);return[...f,...g]},[r,n]),l=h=>{s==="IN"?t(a(`/books/${h.id}/personalize`),{state:{selectedBook:h}}):t(a(`/books/${h.id}`))};if(r.length===0)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-gray-600 mb-4",children:"No stories match your selected filters."}),e.jsx(wt,{onClick:()=>{},children:"Clear All Filters"})]});const c=o.length===1,u=Ss[s],d=Math.min(u.softCoverPrice,u.bookPrice);return e.jsx("div",{className:c?"grid grid-cols-1 gap-4 md:gap-6 md:max-w-sm md:mx-auto":"grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 md:gap-6 md:max-w-5xl md:mx-auto",children:o.map((h,m)=>e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:m*.05},onClick:()=>l(h),className:"bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition-shadow flex flex-col relative h-full cursor-pointer",children:[e.jsx("div",{className:"relative w-full bg-gray-50",children:e.jsx("div",{className:"aspect-square",children:e.jsx($s,{imagePath:h.imagePaths[0],alt:h.title,className:"w-full h-full object-contain",loading:"lazy",decoding:"async"})})}),e.jsxs("div",{className:"p-4 md:p-6 flex flex-col flex-grow",children:[e.jsx("h3",{className:"text-lg md:text-xl font-semibold text-purple-900 mb-1 md:mb-2 line-clamp-2",children:h.title}),e.jsx("p",{className:"text-gray-600 text-sm md:text-sm mb-4 leading-relaxed line-clamp-3 md:line-clamp-none",children:h.description}),e.jsx("div",{className:"flex-grow"}),e.jsxs("div",{className:"flex items-center justify-between mt-auto",children:[e.jsxs("p",{className:"text-xl font-bold text-gray-900",children:["From ",e.jsxs("span",{className:"text-purple-600",children:[Gt(s,d),"/-"]})]}),e.jsx("button",{onClick:g=>{g.stopPropagation(),l(h)},className:"bg-purple-500 hover:bg-purple-600 text-white px-6 py-2.5 rounded-full font-semibold text-sm md:text-base transition-colors whitespace-nowrap","data-gtm":"books_book_details","data-track":"book_selected","data-book-id":h.id.toString(),"data-book-name":h.title,children:s==="IN"?"Personalise":"Book Details"})]})]})]},h.id))})},Id=[{value:"return_gift_books",label:"Return Gift Books"},{value:"single_character_books",label:"Single character Books"},{value:"multi_character_books",label:"Multi character Books"},{value:"little_kids_books",label:"Books for Little kids (under age 5)"}],Rd=r=>{const t=r.match(/(\d+)-(\d+)/);return t?[parseInt(t[1],10),parseInt(t[2],10)]:null},mw=(r,t)=>{const s=Rd(r),a=Rd(t);if(!s||!a)return!1;const[n,i]=s,[o,l]=a;return n<=l&&i>=o},pw=()=>{const r=Jt(),t=_t(),[s,a]=To(),{buildLink:n}=ht(),i=r.pathname.startsWith("/sg"),o=i?"https://www.talesberry.com/sg/books":"https://www.talesberry.com/books",[l,c]=p.useState(!1),[u,d]=p.useState({gender:[],ageRange:[],categoryTag:""});p.useEffect(()=>{const x=s.get("age"),j=s.get("gender"),b=s.get("category"),y={gender:[],ageRange:[],categoryTag:""};if(b&&Id.some(S=>S.value===b)&&(y.categoryTag=b),x){const T={"1-5":"1-5 years","6-10":"6-10 years"}[x];T&&(y.ageRange=[T])}j&&(j==="Boy"||j==="Girl")&&(y.gender=[j]),(y.gender.length>0||y.ageRange.length>0||y.categoryTag)&&d(y)},[s]);const h={gender:["Boy","Girl"]},m=p.useMemo(()=>Ot.filter(x=>{const j=!u.categoryTag||x.category_tag===u.categoryTag,b=u.gender.length===0||u.gender.includes(x.suitableFor)||x.suitableFor==="All genders",y=u.ageRange.length===0||u.ageRange.some(S=>mw(x.ageRange,S));return j&&b&&y}),[u]),g=x=>{const j=u.categoryTag===x?"":x;d(b=>({...b,categoryTag:j})),j?s.set("category",j):s.delete("category"),a(s,{replace:!0})},f=(x,j)=>{d(b=>({...b,[x]:b[x].includes(j)?b[x].filter(y=>y!==j):[...b[x],j]}))},v=()=>{d({gender:[],ageRange:[],categoryTag:""}),s.delete("category"),a(s,{replace:!0})};return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"Personalised Books for Kids | TalesBerry"}),e.jsx("link",{rel:"canonical",href:o}),e.jsx("meta",{name:"description",content:"Browse TalesBerry's personalised books for kids. Discover custom storybooks by age and interest that turn children into the heroes of their own stories."}),i&&e.jsx("link",{rel:"alternate",hrefLang:"en-SG",href:"https://www.talesberry.com/sg/books"}),i&&e.jsx("link",{rel:"alternate",hrefLang:"en-IN",href:"https://www.talesberry.com/books"}),i&&e.jsx("link",{rel:"alternate",hrefLang:"x-default",href:"https://www.talesberry.com/books"}),!i&&e.jsx("link",{rel:"alternate",hrefLang:"en-IN",href:"https://www.talesberry.com/books"}),!i&&e.jsx("link",{rel:"alternate",hrefLang:"en-SG",href:"https://www.talesberry.com/sg/books"}),!i&&e.jsx("link",{rel:"alternate",hrefLang:"x-default",href:"https://www.talesberry.com/books"})]}),e.jsx("div",{className:"min-h-screen pb-12 bg-gradient-to-br from-purple-50 via-blue-50 to-pink-50",children:e.jsxs("div",{className:"container mx-auto px-4 pt-8",children:[e.jsx("button",{onClick:()=>t(n("/")),className:"md:hidden mb-4 flex items-center text-sm text-purple-700 font-medium",children:"← Back to Home"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-purple-900 mb-4",children:"Our Books Collection"}),e.jsxs("section",{children:[e.jsx("div",{className:"flex justify-center items-center mb-8",children:e.jsxs("button",{onClick:()=>c(!l),className:"flex items-center text-black hover:text-gray-700 transition-colors",children:[l?e.jsx(Cs,{className:"w-5 h-5 mr-2"}):e.jsx(gu,{className:"w-5 h-5 mr-2"}),l?"Hide Filters":"Show Filters"]})}),e.jsx(uw,{showFilters:l,filterOptions:h,activeFilters:u,categoryTags:Id,onFilterChange:f,onCategoryTagChange:g,onClearFilters:v}),e.jsx(hw,{books:m}),m.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-gray-600 mb-4",children:"No stories match your selected filters."}),e.jsx(wt,{onClick:v,children:"Clear All Filters"})]})]}),e.jsxs("section",{className:"max-w-4xl mx-auto mt-20",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-bold text-purple-900 mb-6",children:"Custom Storybooks That Make Children the Hero"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed mb-6",children:"TalesBerry's personalised books for kids are designed to make reading magical. Each story is customised with your child's name and details, helping them feel deeply connected to the story and excited to read again and again."}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed mb-8",children:"Our personalised children's books are loved by parents for encouraging reading habits, building confidence, and creating meaningful keepsakes that last far beyond childhood."}),e.jsx("h3",{className:"text-xl md:text-2xl font-semibold text-purple-800 mb-4",children:"A meaningful personalised gift for every occasion"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed mb-8",children:"Whether you're looking for a birthday gift, a festive surprise, or a special milestone present, personalised books make thoughtful gifts that children truly cherish."}),e.jsx("h3",{className:"text-xl md:text-2xl font-semibold text-purple-800 mb-4",children:"Books tailored by age and interests"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"Explore personalised books suitable for different age groups and reading levels. From early readers to confident storytellers, there's a personalised book designed for every stage of childhood."})]})]})})]})},gw=()=>{const r=_t(),{buildLink:t}=ht(),s=[{id:"papa-love",title:"Papa, I Love You..",description:"There's no day more perfect than **today** to remind your parents just how deeply you love them! Create a personalised book for your dad and gift precious lifetime memories.",theme:"Family Love",pages:24,ageRange:"All Ages",pricing:{small:{size:"8.75x8.75 inch",price:1}},coverImage:"/papa_love/front.jpeg",features:["Personalized with your Dad's name – Because this story is truly his.","Beautifully crafted using your real emotions – We help you express what's in your heart, in words that truly move.","Stunning illustrations with your Dad in different avatars – From superhero to life guide and protector, see him come alive in magical scenes."]},{id:"papa-love-2",title:"Dad, I Love You..",description:"There's no day more perfect than **today** to remind your parents just how deeply you love them! Create a personalised book for your dad and gift precious lifetime memories.",theme:"Family Love",pages:24,ageRange:"All Ages",pricing:{small:{size:"8.75x8.75 inch",price:1}},coverImage:"/papa_love2/front.jpeg",features:["Personalized with your Dad's name – Because this story is truly his.","Beautifully crafted using your real emotions – We help you express what's in your heart, in words that truly move.","Stunning illustrations with your Dad in different avatars – From superhero to life guide and protector, see him come alive in magical scenes."]}],a=n=>{r(t(`/books/${n}`))};return e.jsx("div",{className:"min-h-screen pb-12 bg-white",children:e.jsxs("div",{className:"container mx-auto px-4 pt-8",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("h1",{className:"text-4xl font-bold text-purple-900 mb-4",children:["Books for ",e.jsx("span",{className:"text-transparent bg-clip-text bg-gradient-to-r from-purple-600 to-pink-500",children:"Parents"})]}),e.jsx("p",{className:"text-lg text-gray-600 max-w-2xl mx-auto",children:"Celebrate the beautiful bond between parents and children with our heartwarming collection of personalized books"})]}),e.jsx("div",{className:"mb-12",children:e.jsx("div",{className:"overflow-x-auto pb-4",children:e.jsx("div",{className:"flex gap-6 justify-center min-w-max px-8",children:s.map(n=>e.jsxs("div",{className:"bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition-all duration-300 hover:-translate-y-1 flex-shrink-0 w-64",children:[e.jsxs("div",{className:"relative w-full aspect-square",children:[e.jsx("img",{src:n.coverImage,alt:n.title,className:"w-full h-full object-cover",onError:i=>{console.log(`Failed to load image: ${n.coverImage}`),i.currentTarget.src="/papa_love/front.jpeg"}}),e.jsx("div",{className:"absolute top-3 right-3 bg-white rounded-full p-1.5 shadow-md",children:e.jsx($o,{className:"w-4 h-4 text-pink-500"})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"text-lg font-bold text-purple-900 mb-2",children:n.title}),e.jsx("p",{className:"text-gray-600 mb-3 leading-relaxed text-sm",children:n.description.split("**today**").map((i,o,l)=>o<l.length-1?e.jsxs("span",{children:[i,e.jsx("strong",{children:"today"})]},o):e.jsx("span",{children:i},o))}),e.jsxs("div",{className:"flex flex-wrap gap-3 mb-3 text-xs",children:[e.jsxs("div",{className:"flex items-center text-purple-600",children:[e.jsx(mu,{className:"w-3 h-3 mr-1"}),n.pages," pages"]}),e.jsxs("div",{className:"flex items-center text-purple-600",children:[e.jsx(wu,{className:"w-3 h-3 mr-1"}),n.ageRange]}),e.jsxs("div",{className:"flex items-center text-purple-600",children:[e.jsx(Pa,{className:"w-3 h-3 mr-1"}),n.theme]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("h4",{className:"font-semibold text-purple-900 mb-2 text-sm",children:"Features:"}),e.jsx("ul",{className:"text-xs text-gray-600 space-y-1.5",children:n.features.map((i,o)=>e.jsxs("li",{className:"flex items-start",children:[e.jsx("div",{className:"w-2 h-2 bg-purple-500 rounded-full mr-2 mt-1.5 flex-shrink-0"}),e.jsx("span",{children:i})]},o))})]}),e.jsx("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-xs text-gray-600",children:n.pricing.small.size}),e.jsxs("span",{className:"text-sm font-bold text-purple-900",children:["₹",n.pricing.small.price]})]})}),e.jsx(wt,{onClick:()=>a(n.id),className:"w-full justify-center text-sm py-2","data-track":"parent_book_selected","data-book-id":n.id,"data-book-name":n.title,children:"Create This Book"})]})]},n.id))})})}),e.jsxs("div",{className:"text-center bg-white rounded-2xl shadow-lg p-8 max-w-2xl mx-auto",children:[e.jsx("h2",{className:"text-2xl font-bold text-purple-900 mb-4",children:"Ready to Create Your Special Book?"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Start creating a personalized book that celebrates your unique family bond"}),e.jsx(wt,{onClick:()=>r(t("/books")),className:"px-8 py-3","data-track":"browse_all_books",children:"Browse All Books"})]})]})})},ln=new Set,fw=()=>typeof window<"u"&&typeof window.fbq=="function",xw=(...r)=>fw()?(window.fbq(...r),!0):!1,yw=r=>{try{return sessionStorage.getItem(r)==="1"}catch{return!1}},bw=r=>{try{sessionStorage.setItem(r,"1")}catch{}},Oa=(r,...t)=>{if(yw(r)||ln.has(r))return;ln.add(r);let s=0;const a=20,n=250,i=()=>{if(xw(...t)){bw(r),ln.delete(r),console.log(`[META PIXEL] ✅ Fired event: ${r}`,t.slice(1));return}if(s+=1,s>=a){ln.delete(r),console.warn(`[META PIXEL] ❌ Failed after ${a} attempts: ${r}`);return}window.setTimeout(i,n)};i()},km=(r,t=r,s)=>{const a=`fbq_viewcontent_${t}`;Oa(a,"track","ViewContent",{content_name:r,content_type:"product",...s&&{content_category:s},value:1149,currency:"INR"})},vw=(r,t,s)=>{const n=`fbq_lead_preview_${s||r}`;Oa(n,"track","Lead",{content_name:r,...t&&{content_category:t},value:1149,currency:"INR"}),Oa(`${n}_custom`,"trackCustom","PreviewGenerated",{content_name:r,...t&&{content_category:t}})},ww=(r,t,s,a)=>{const i=`fbq_booktype_${a||s||r}_${r}`;Oa(i,"trackCustom","BookTypeSelected",{book_type:r,value:t,currency:"INR",...s&&{content_name:s}})},jw=(r,t,s,a)=>{const i=`fbq_initiatecheckout_${a||t||"unknown"}`;Oa(i,"track","InitiateCheckout",{value:r,currency:"INR",num_items:1,...t&&{content_name:t,content_type:"product"},...s&&{book_type:s}})},Nw=()=>{const{id:r}=Xr(),t=_t(),{buildLink:s,region:a}=ht(),[n,i]=p.useState("image"),[o,l]=p.useState(0),c=Ot.find(m=>m.id===Number(r));if(p.useEffect(()=>{c!=null&&c.title&&km(c.title,`book_${r}`,c.category_tag||void 0)},[r,c==null?void 0:c.title,c==null?void 0:c.category_tag]),!c)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Book Not Found"}),e.jsx(wt,{onClick:()=>t(s("/books")),children:"Back to Books"})]})});const u=()=>{t(s(`/books/${r}/personalize`),{state:{selectedBook:c}})},d=()=>{l(m=>(m+1)%c.imagePaths.length)},h=()=>{l(m=>(m-1+c.imagePaths.length)%c.imagePaths.length)};return e.jsxs("div",{className:"min-h-screen bg-white",children:[(()=>{const m=Ss[a],g=c.ageRange.match(/(\d+)\s*[-–]\s*(\d+)/),f=g?parseInt(g[1]):0,v=g?parseInt(g[2]):12,x=m.bookPrice,j=m.currency,b=a==="SG"?"/sg":"",y=Rn(c.imagePaths[0],a),S={"@context":"https://schema.org","@type":"Product",name:`${c.title} - Personalised Storybook`,description:c.description,image:y,brand:{"@type":"Brand",name:"TalesBerry"},offers:{"@type":"Offer",price:x,priceCurrency:j,availability:"https://schema.org/InStock",url:`https://www.talesberry.com${b}/books/${r}`,seller:{"@type":"Organization",name:"TalesBerry"}},audience:{"@type":"PeopleAudience",suggestedMinAge:f,suggestedMaxAge:v},category:"Personalised Children's Books"};return e.jsxs(as,{children:[e.jsxs("title",{children:[c.title," - Personalised Storybook | TalesBerry"]}),e.jsx("link",{rel:"canonical",href:`https://www.talesberry.com${b}/books/${r}`}),e.jsx("meta",{name:"description",content:`${c.title} - ${c.description.substring(0,140)}`}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(S)})]})})(),e.jsx("div",{className:"hidden lg:block bg-white shadow-sm border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-16",children:[e.jsxs("button",{onClick:()=>t(s("/books")),className:"flex items-center text-gray-600 hover:text-gray-800 transition-colors",children:[e.jsx(Ut,{className:"w-5 h-5 mr-1"}),"Back to Books"]}),e.jsx("div",{className:"w-16"})]})})}),e.jsx("div",{className:"hidden lg:block max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:e.jsxs("div",{className:"flex items-center justify-between max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-500 text-white rounded-full flex items-center justify-center text-sm font-medium",children:"1"}),e.jsx("span",{className:"ml-2 text-purple-500 font-medium",children:"Book Details"})]}),e.jsx("div",{className:"flex-1 h-1 bg-purple-200 mx-4"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-sm font-medium",children:"2"}),e.jsx("span",{className:"ml-2 text-gray-400 font-medium",children:"Personalization"})]}),e.jsx("div",{className:"flex-1 h-1 bg-purple-200 mx-4"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-sm font-medium",children:"3"}),e.jsx("span",{className:"ml-2 text-gray-400 font-medium",children:"Preview"})]}),e.jsx("div",{className:"flex-1 h-1 bg-purple-200 mx-4"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-sm font-medium",children:"4"}),e.jsx("span",{className:"ml-2 text-gray-400 font-medium",children:"Checkout"})]})]})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 pb-32 lg:pb-8",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[120px_1fr_300px] gap-2",children:[e.jsx("div",{className:"hidden lg:block order-2 lg:order-1",children:e.jsx("div",{className:"bg-white rounded-lg shadow-sm p-3",children:e.jsx("div",{className:"max-h-80 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300",children:e.jsxs("div",{className:"space-y-2",children:[c.imagePaths.slice(0,6).map((m,g)=>e.jsx("button",{onClick:()=>{i("image"),l(g)},className:`w-14 h-14 rounded border-2 overflow-hidden transition-all hover:scale-105 ${n==="image"&&o===g?"border-primary-500 shadow-md ring-2 ring-primary-200":"border-gray-200 hover:border-gray-300"}`,children:e.jsx($s,{imagePath:m,alt:`${c.title} preview ${g+1}`,className:"w-full h-full object-cover"})},g)),e.jsx("button",{onClick:()=>i("video"),className:`w-14 h-14 rounded border-2 overflow-hidden transition-all flex items-center justify-center bg-gray-50 hover:scale-105 ${n==="video"?"border-primary-500 shadow-md ring-2 ring-primary-200":"border-gray-200 hover:border-gray-300"}`,children:e.jsx(Ca,{className:"w-3 h-3 text-gray-600"})})]})})})}),e.jsx("div",{className:"order-1 lg:order-2 lg:flex-1",children:e.jsx("div",{className:"bg-white rounded-xl shadow-lg p-4",children:n==="image"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-square relative rounded-lg overflow-hidden w-full",children:e.jsx($s,{imagePath:c.imagePaths[o],alt:c.title,className:"w-full h-full object-cover"})}),e.jsx("button",{onClick:h,className:"absolute left-4 top-1/2 transform -translate-y-1/2 p-3 bg-white/90 backdrop-blur-sm rounded-full shadow-lg hover:shadow-xl hover:bg-white transition-all",children:e.jsx(Ut,{className:"w-6 h-6"})}),e.jsx("button",{onClick:d,className:"absolute right-4 top-1/2 transform -translate-y-1/2 p-3 bg-white/90 backdrop-blur-sm rounded-full shadow-lg hover:shadow-xl hover:bg-white transition-all",children:e.jsx(gs,{className:"w-6 h-6"})})]}):e.jsx("div",{className:"aspect-square bg-gray-100 rounded-lg flex items-center justify-center w-full max-w-4xl mx-auto",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ca,{className:"w-20 h-20 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Video preview coming soon"})]})})})}),e.jsx("div",{className:"order-3",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900 mb-2",children:c.title}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-sm text-gray-600 mb-4",children:[e.jsx("span",{className:"bg-primary-100 text-primary-800 px-2 py-1 rounded-full",children:c.theme}),c.category_tag&&e.jsx("span",{className:"bg-secondary-100 text-secondary-800 px-2 py-1 rounded-full",children:c.category_tag}),e.jsx("span",{className:`px-2 py-1 rounded-full ${c.suitableFor.toLowerCase().includes("boy")?"bg-blue-100 text-blue-700":c.suitableFor.toLowerCase().includes("girl")?"bg-pink-100 text-pink-700":"bg-orange-100 text-orange-700"}`,children:c.suitableFor})]})]}),e.jsx("div",{className:"space-y-4 text-gray-700",children:e.jsx("p",{children:c.description})}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"Product Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-600",children:"Pages:"}),e.jsx("span",{className:"ml-1 font-medium",children:c.pages})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-600",children:"Age Range:"}),e.jsx("span",{className:"ml-1 font-medium",children:c.ageRange})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-600",children:"Size:"}),e.jsx("span",{className:"ml-1 font-medium",children:c.pricing.small.size})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-600",children:"Suitable For:"}),e.jsx("span",{className:"ml-1 font-medium",children:c.suitableFor})]})]})]}),e.jsxs("div",{className:"space-y-3 text-sm text-gray-600",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full mr-3"}),e.jsx("span",{children:"High-quality hardcover printing"})]}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full mr-3"}),e.jsx("span",{children:"Personalized with your child's photo and name"})]}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full mr-3"}),e.jsx("span",{children:"Safe, non-toxic materials"})]}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full mr-3"}),e.jsx("span",{children:"Fast delivery worldwide"})]})]}),e.jsx(wt,{onClick:u,className:"hidden lg:block w-full text-lg py-4","data-track":"proceed_to_preview","data-book-id":r,"data-book-name":c.title,children:"Proceed to Free Preview"})]})})]})}),e.jsx("div",{className:"lg:hidden fixed bottom-0 left-0 right-0 bg-white border-t shadow-lg z-50",children:e.jsx("div",{className:"p-4",children:e.jsx(wt,{onClick:u,className:"w-full text-lg py-4","data-track":"proceed_to_preview","data-book-id":r,"data-book-name":c.title,children:"Proceed to Free Preview"})})})]})};var bo=function(r,t){return bo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,a){s.__proto__=a}||function(s,a){for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(s[n]=a[n])},bo(r,t)};function kw(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");bo(r,t);function s(){this.constructor=r}r.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}var Qt=function(){return Qt=Object.assign||function(t){for(var s,a=1,n=arguments.length;a<n;a++){s=arguments[a];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},Qt.apply(this,arguments)};var $d=!1,fr,vo,wo,bn,vn,_m,wn,jo,No,ko,Sm,_o,So,Cm,Pm;function ms(){if(!$d){$d=!0;var r=navigator.userAgent,t=/(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(r),s=/(Mac OS X)|(Windows)|(Linux)/.exec(r);if(_o=/\b(iPhone|iP[ao]d)/.exec(r),So=/\b(iP[ao]d)/.exec(r),ko=/Android/i.exec(r),Cm=/FBAN\/\w+;/i.exec(r),Pm=/Mobile/i.exec(r),Sm=!!/Win64/.exec(r),t){fr=t[1]?parseFloat(t[1]):t[5]?parseFloat(t[5]):NaN,fr&&document&&document.documentMode&&(fr=document.documentMode);var a=/(?:Trident\/(\d+.\d+))/.exec(r);_m=a?parseFloat(a[1])+4:fr,vo=t[2]?parseFloat(t[2]):NaN,wo=t[3]?parseFloat(t[3]):NaN,bn=t[4]?parseFloat(t[4]):NaN,bn?(t=/(?:Chrome\/(\d+\.\d+))/.exec(r),vn=t&&t[1]?parseFloat(t[1]):NaN):vn=NaN}else fr=vo=wo=vn=bn=NaN;if(s){if(s[1]){var n=/(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(r);wn=n?parseFloat(n[1].replace("_",".")):!0}else wn=!1;jo=!!s[2],No=!!s[3]}else wn=jo=No=!1}}var Co={ie:function(){return ms()||fr},ieCompatibilityMode:function(){return ms()||_m>fr},ie64:function(){return Co.ie()&&Sm},firefox:function(){return ms()||vo},opera:function(){return ms()||wo},webkit:function(){return ms()||bn},safari:function(){return Co.webkit()},chrome:function(){return ms()||vn},windows:function(){return ms()||jo},osx:function(){return ms()||wn},linux:function(){return ms()||No},iphone:function(){return ms()||_o},mobile:function(){return ms()||_o||So||ko||Pm},nativeApp:function(){return ms()||Cm},android:function(){return ms()||ko},ipad:function(){return ms()||So}},_w=Co,cn=!!(typeof window<"u"&&window.document&&window.document.createElement),Sw={canUseDOM:cn,canUseWorkers:typeof Worker<"u",canUseEventListeners:cn&&!!(window.addEventListener||window.attachEvent),canUseViewport:cn&&!!window.screen,isInWorker:!cn},Cw=Sw,Em=Cw,Tm;Em.canUseDOM&&(Tm=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0);/**
 * Checks if an event is supported in the current execution environment.
 *
 * NOTE: This will not work correctly for non-generic events such as `change`,
 * `reset`, `load`, `error`, and `select`.
 *
 * Borrows from Modernizr.
 *
 * @param {string} eventNameSuffix Event name, e.g. "click".
 * @param {?boolean} capture Check if the capture phase is supported.
 * @return {boolean} True if the event is supported.
 * @internal
 * @license Modernizr 3.0.0pre (Custom Build) | MIT
 */function Pw(r,t){if(!Em.canUseDOM||t&&!("addEventListener"in document))return!1;var s="on"+r,a=s in document;if(!a){var n=document.createElement("div");n.setAttribute(s,"return;"),a=typeof n[s]=="function"}return!a&&Tm&&r==="wheel"&&(a=document.implementation.hasFeature("Events.wheel","3.0")),a}var Ew=Pw,Tw=_w,Aw=Ew,Ld=10,Od=40,Md=800;function Am(r){var t=0,s=0,a=0,n=0;return"detail"in r&&(s=r.detail),"wheelDelta"in r&&(s=-r.wheelDelta/120),"wheelDeltaY"in r&&(s=-r.wheelDeltaY/120),"wheelDeltaX"in r&&(t=-r.wheelDeltaX/120),"axis"in r&&r.axis===r.HORIZONTAL_AXIS&&(t=s,s=0),a=t*Ld,n=s*Ld,"deltaY"in r&&(n=r.deltaY),"deltaX"in r&&(a=r.deltaX),(a||n)&&r.deltaMode&&(r.deltaMode==1?(a*=Od,n*=Od):(a*=Md,n*=Md)),a&&!t&&(t=a<1?-1:1),n&&!s&&(s=n<1?-1:1),{spinX:t,spinY:s,pixelX:a,pixelY:n}}Am.getEventType=function(){return Tw.firefox()?"DOMMouseScroll":Aw("wheel")?"wheel":"mousewheel"};var Iw=Am,Rw=Iw;const $w=$n(Rw);function Lw(r,t,s,a,n,i){i===void 0&&(i=0);var o=Zr(r,t,i),l=o.width,c=o.height,u=Math.min(l,s),d=Math.min(c,a);return u>d*n?{width:d*n,height:d}:{width:u,height:u/n}}function Ow(r){return r.width>r.height?r.width/r.naturalWidth:r.height/r.naturalHeight}function ua(r,t,s,a,n){n===void 0&&(n=0);var i=Zr(t.width,t.height,n),o=i.width,l=i.height;return{x:Bd(r.x,o,s.width,a),y:Bd(r.y,l,s.height,a)}}function Bd(r,t,s,a){var n=t*a/2-s/2;return Kn(r,-n,n)}function Fd(r,t){return Math.sqrt(Math.pow(r.y-t.y,2)+Math.pow(r.x-t.x,2))}function Dd(r,t){return Math.atan2(t.y-r.y,t.x-r.x)*180/Math.PI}function Mw(r,t,s,a,n,i,o){i===void 0&&(i=0),o===void 0&&(o=!0);var l=o?Bw:Fw,c=Zr(t.width,t.height,i),u=Zr(t.naturalWidth,t.naturalHeight,i),d={x:l(100,((c.width-s.width/n)/2-r.x/n)/c.width*100),y:l(100,((c.height-s.height/n)/2-r.y/n)/c.height*100),width:l(100,s.width/c.width*100/n),height:l(100,s.height/c.height*100/n)},h=Math.round(l(u.width,d.width*u.width/100)),m=Math.round(l(u.height,d.height*u.height/100)),g=u.width>=u.height*a,f=g?{width:Math.round(m*a),height:m}:{width:h,height:Math.round(h/a)},v=Qt(Qt({},f),{x:Math.round(l(u.width-f.width,d.x*u.width/100)),y:Math.round(l(u.height-f.height,d.y*u.height/100))});return{croppedAreaPercentages:d,croppedAreaPixels:v}}function Bw(r,t){return Math.min(r,Math.max(0,t))}function Fw(r,t){return t}function Dw(r,t,s,a,n,i){var o=Zr(t.width,t.height,s),l=Kn(a.width/o.width*(100/r.width),n,i),c={x:l*o.width/2-a.width/2-o.width*l*(r.x/100),y:l*o.height/2-a.height/2-o.height*l*(r.y/100)};return{crop:c,zoom:l}}function Gw(r,t,s){var a=Ow(t);return s.height>s.width?s.height/(r.height*a):s.width/(r.width*a)}function Uw(r,t,s,a,n,i){s===void 0&&(s=0);var o=Zr(t.naturalWidth,t.naturalHeight,s),l=Kn(Gw(r,t,a),n,i),c=a.height>a.width?a.height/r.height:a.width/r.width,u={x:((o.width-r.width)/2-r.x)*c,y:((o.height-r.height)/2-r.y)*c};return{crop:u,zoom:l}}function Gd(r,t){return{x:(t.x+r.x)/2,y:(t.y+r.y)/2}}function Vw(r){return r*Math.PI/180}function Zr(r,t,s){var a=Vw(s);return{width:Math.abs(Math.cos(a)*r)+Math.abs(Math.sin(a)*t),height:Math.abs(Math.sin(a)*r)+Math.abs(Math.cos(a)*t)}}function Kn(r,t,s){return Math.min(Math.max(r,t),s)}function dn(){for(var r=[],t=0;t<arguments.length;t++)r[t]=arguments[t];return r.filter(function(s){return typeof s=="string"&&s.length>0}).join(" ").trim()}var zw=`.reactEasyCrop_Container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  user-select: none;
  touch-action: none;
  cursor: move;
  display: flex;
  justify-content: center;
  align-items: center;
}

.reactEasyCrop_Image,
.reactEasyCrop_Video {
  will-change: transform; /* this improves performances and prevent painting issues on iOS Chrome */
}

.reactEasyCrop_Contain {
  max-width: 100%;
  max-height: 100%;
  margin: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.reactEasyCrop_Cover_Horizontal {
  width: 100%;
  height: auto;
}
.reactEasyCrop_Cover_Vertical {
  width: auto;
  height: 100%;
}

.reactEasyCrop_CropArea {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid rgba(255, 255, 255, 0.5);
  box-sizing: border-box;
  box-shadow: 0 0 0 9999em;
  color: rgba(0, 0, 0, 0.5);
  overflow: hidden;
}

.reactEasyCrop_CropAreaRound {
  border-radius: 50%;
}

.reactEasyCrop_CropAreaGrid::before {
  content: ' ';
  box-sizing: border-box;
  position: absolute;
  border: 1px solid rgba(255, 255, 255, 0.5);
  top: 0;
  bottom: 0;
  left: 33.33%;
  right: 33.33%;
  border-top: 0;
  border-bottom: 0;
}

.reactEasyCrop_CropAreaGrid::after {
  content: ' ';
  box-sizing: border-box;
  position: absolute;
  border: 1px solid rgba(255, 255, 255, 0.5);
  top: 33.33%;
  bottom: 33.33%;
  left: 0;
  right: 0;
  border-left: 0;
  border-right: 0;
}
`,Ww=1,qw=3,Hw=1,As=function(r){kw(t,r);function t(){var s=r!==null&&r.apply(this,arguments)||this;return s.cropperRef=p.createRef(),s.imageRef=p.createRef(),s.videoRef=p.createRef(),s.containerPosition={x:0,y:0},s.containerRef=null,s.styleRef=null,s.containerRect=null,s.mediaSize={width:0,height:0,naturalWidth:0,naturalHeight:0},s.dragStartPosition={x:0,y:0},s.dragStartCrop={x:0,y:0},s.gestureZoomStart=0,s.gestureRotationStart=0,s.isTouching=!1,s.lastPinchDistance=0,s.lastPinchRotation=0,s.rafDragTimeout=null,s.rafPinchTimeout=null,s.wheelTimer=null,s.currentDoc=typeof document<"u"?document:null,s.currentWindow=typeof window<"u"?window:null,s.resizeObserver=null,s.previousCropSize=null,s.isInitialized=!1,s.state={cropSize:null,hasWheelJustStarted:!1,mediaObjectFit:void 0},s.initResizeObserver=function(){if(!(typeof window.ResizeObserver>"u"||!s.containerRef)){var a=!0;s.resizeObserver=new window.ResizeObserver(function(n){if(a){a=!1;return}s.computeSizes()}),s.resizeObserver.observe(s.containerRef)}},s.preventZoomSafari=function(a){return a.preventDefault()},s.cleanEvents=function(){s.currentDoc&&(s.currentDoc.removeEventListener("mousemove",s.onMouseMove),s.currentDoc.removeEventListener("mouseup",s.onDragStopped),s.currentDoc.removeEventListener("touchmove",s.onTouchMove),s.currentDoc.removeEventListener("touchend",s.onDragStopped),s.currentDoc.removeEventListener("gesturechange",s.onGestureChange),s.currentDoc.removeEventListener("gestureend",s.onGestureEnd),s.currentDoc.removeEventListener("scroll",s.onScroll))},s.clearScrollEvent=function(){s.containerRef&&s.containerRef.removeEventListener("wheel",s.onWheel),s.wheelTimer&&clearTimeout(s.wheelTimer)},s.onMediaLoad=function(){var a=s.computeSizes();a&&(s.previousCropSize=a,s.emitCropData(),s.setInitialCrop(a),s.isInitialized=!0),s.props.onMediaLoaded&&s.props.onMediaLoaded(s.mediaSize)},s.setInitialCrop=function(a){if(s.props.initialCroppedAreaPercentages){var n=Dw(s.props.initialCroppedAreaPercentages,s.mediaSize,s.props.rotation,a,s.props.minZoom,s.props.maxZoom),i=n.crop,o=n.zoom;s.props.onCropChange(i),s.props.onZoomChange&&s.props.onZoomChange(o)}else if(s.props.initialCroppedAreaPixels){var l=Uw(s.props.initialCroppedAreaPixels,s.mediaSize,s.props.rotation,a,s.props.minZoom,s.props.maxZoom),i=l.crop,o=l.zoom;s.props.onCropChange(i),s.props.onZoomChange&&s.props.onZoomChange(o)}},s.computeSizes=function(){var a,n,i,o,l,c,u=s.imageRef.current||s.videoRef.current;if(u&&s.containerRef){s.containerRect=s.containerRef.getBoundingClientRect(),s.saveContainerPosition();var d=s.containerRect.width/s.containerRect.height,h=((a=s.imageRef.current)===null||a===void 0?void 0:a.naturalWidth)||((n=s.videoRef.current)===null||n===void 0?void 0:n.videoWidth)||0,m=((i=s.imageRef.current)===null||i===void 0?void 0:i.naturalHeight)||((o=s.videoRef.current)===null||o===void 0?void 0:o.videoHeight)||0,g=u.offsetWidth<h||u.offsetHeight<m,f=h/m,v=void 0;if(g)switch(s.state.mediaObjectFit){default:case"contain":v=d>f?{width:s.containerRect.height*f,height:s.containerRect.height}:{width:s.containerRect.width,height:s.containerRect.width/f};break;case"horizontal-cover":v={width:s.containerRect.width,height:s.containerRect.width/f};break;case"vertical-cover":v={width:s.containerRect.height*f,height:s.containerRect.height};break}else v={width:u.offsetWidth,height:u.offsetHeight};s.mediaSize=Qt(Qt({},v),{naturalWidth:h,naturalHeight:m}),s.props.setMediaSize&&s.props.setMediaSize(s.mediaSize);var x=s.props.cropSize?s.props.cropSize:Lw(s.mediaSize.width,s.mediaSize.height,s.containerRect.width,s.containerRect.height,s.props.aspect,s.props.rotation);return(((l=s.state.cropSize)===null||l===void 0?void 0:l.height)!==x.height||((c=s.state.cropSize)===null||c===void 0?void 0:c.width)!==x.width)&&s.props.onCropSizeChange&&s.props.onCropSizeChange(x),s.setState({cropSize:x},s.recomputeCropPosition),s.props.setCropSize&&s.props.setCropSize(x),x}},s.saveContainerPosition=function(){if(s.containerRef){var a=s.containerRef.getBoundingClientRect();s.containerPosition={x:a.left,y:a.top}}},s.onMouseDown=function(a){s.currentDoc&&(a.preventDefault(),s.currentDoc.addEventListener("mousemove",s.onMouseMove),s.currentDoc.addEventListener("mouseup",s.onDragStopped),s.saveContainerPosition(),s.onDragStart(t.getMousePoint(a)))},s.onMouseMove=function(a){return s.onDrag(t.getMousePoint(a))},s.onScroll=function(a){s.currentDoc&&(a.preventDefault(),s.saveContainerPosition())},s.onTouchStart=function(a){s.currentDoc&&(s.isTouching=!0,!(s.props.onTouchRequest&&!s.props.onTouchRequest(a))&&(s.currentDoc.addEventListener("touchmove",s.onTouchMove,{passive:!1}),s.currentDoc.addEventListener("touchend",s.onDragStopped),s.saveContainerPosition(),a.touches.length===2?s.onPinchStart(a):a.touches.length===1&&s.onDragStart(t.getTouchPoint(a.touches[0]))))},s.onTouchMove=function(a){a.preventDefault(),a.touches.length===2?s.onPinchMove(a):a.touches.length===1&&s.onDrag(t.getTouchPoint(a.touches[0]))},s.onGestureStart=function(a){s.currentDoc&&(a.preventDefault(),s.currentDoc.addEventListener("gesturechange",s.onGestureChange),s.currentDoc.addEventListener("gestureend",s.onGestureEnd),s.gestureZoomStart=s.props.zoom,s.gestureRotationStart=s.props.rotation)},s.onGestureChange=function(a){if(a.preventDefault(),!s.isTouching){var n=t.getMousePoint(a),i=s.gestureZoomStart-1+a.scale;if(s.setNewZoom(i,n,{shouldUpdatePosition:!0}),s.props.onRotationChange){var o=s.gestureRotationStart+a.rotation;s.props.onRotationChange(o)}}},s.onGestureEnd=function(a){s.cleanEvents()},s.onDragStart=function(a){var n,i,o=a.x,l=a.y;s.dragStartPosition={x:o,y:l},s.dragStartCrop=Qt({},s.props.crop),(i=(n=s.props).onInteractionStart)===null||i===void 0||i.call(n)},s.onDrag=function(a){var n=a.x,i=a.y;s.currentWindow&&(s.rafDragTimeout&&s.currentWindow.cancelAnimationFrame(s.rafDragTimeout),s.rafDragTimeout=s.currentWindow.requestAnimationFrame(function(){if(s.state.cropSize&&!(n===void 0||i===void 0)){var o=n-s.dragStartPosition.x,l=i-s.dragStartPosition.y,c={x:s.dragStartCrop.x+o,y:s.dragStartCrop.y+l},u=s.props.restrictPosition?ua(c,s.mediaSize,s.state.cropSize,s.props.zoom,s.props.rotation):c;s.props.onCropChange(u)}}))},s.onDragStopped=function(){var a,n;s.isTouching=!1,s.cleanEvents(),s.emitCropData(),(n=(a=s.props).onInteractionEnd)===null||n===void 0||n.call(a)},s.onWheel=function(a){if(s.currentWindow&&!(s.props.onWheelRequest&&!s.props.onWheelRequest(a))){a.preventDefault();var n=t.getMousePoint(a),i=$w(a).pixelY,o=s.props.zoom-i*s.props.zoomSpeed/200;s.setNewZoom(o,n,{shouldUpdatePosition:!0}),s.state.hasWheelJustStarted||s.setState({hasWheelJustStarted:!0},function(){var l,c;return(c=(l=s.props).onInteractionStart)===null||c===void 0?void 0:c.call(l)}),s.wheelTimer&&clearTimeout(s.wheelTimer),s.wheelTimer=s.currentWindow.setTimeout(function(){return s.setState({hasWheelJustStarted:!1},function(){var l,c;return(c=(l=s.props).onInteractionEnd)===null||c===void 0?void 0:c.call(l)})},250)}},s.getPointOnContainer=function(a,n){var i=a.x,o=a.y;if(!s.containerRect)throw new Error("The Cropper is not mounted");return{x:s.containerRect.width/2-(i-n.x),y:s.containerRect.height/2-(o-n.y)}},s.getPointOnMedia=function(a){var n=a.x,i=a.y,o=s.props,l=o.crop,c=o.zoom;return{x:(n+l.x)/c,y:(i+l.y)/c}},s.setNewZoom=function(a,n,i){var o=i===void 0?{}:i,l=o.shouldUpdatePosition,c=l===void 0?!0:l;if(!(!s.state.cropSize||!s.props.onZoomChange)){var u=Kn(a,s.props.minZoom,s.props.maxZoom);if(c){var d=s.getPointOnContainer(n,s.containerPosition),h=s.getPointOnMedia(d),m={x:h.x*u-d.x,y:h.y*u-d.y},g=s.props.restrictPosition?ua(m,s.mediaSize,s.state.cropSize,u,s.props.rotation):m;s.props.onCropChange(g)}s.props.onZoomChange(u)}},s.getCropData=function(){if(!s.state.cropSize)return null;var a=s.props.restrictPosition?ua(s.props.crop,s.mediaSize,s.state.cropSize,s.props.zoom,s.props.rotation):s.props.crop;return Mw(a,s.mediaSize,s.state.cropSize,s.getAspect(),s.props.zoom,s.props.rotation,s.props.restrictPosition)},s.emitCropData=function(){var a=s.getCropData();if(a){var n=a.croppedAreaPercentages,i=a.croppedAreaPixels;s.props.onCropComplete&&s.props.onCropComplete(n,i),s.props.onCropAreaChange&&s.props.onCropAreaChange(n,i)}},s.emitCropAreaChange=function(){var a=s.getCropData();if(a){var n=a.croppedAreaPercentages,i=a.croppedAreaPixels;s.props.onCropAreaChange&&s.props.onCropAreaChange(n,i)}},s.recomputeCropPosition=function(){if(s.state.cropSize){var a=s.props.crop;if(s.isInitialized&&s.previousCropSize){var n=Math.abs(s.previousCropSize.width-s.state.cropSize.width)>1e-6||Math.abs(s.previousCropSize.height-s.state.cropSize.height)>1e-6;if(n){var i=s.state.cropSize.width/s.previousCropSize.width,o=s.state.cropSize.height/s.previousCropSize.height;a={x:s.props.crop.x*i,y:s.props.crop.y*o}}}var l=s.props.restrictPosition?ua(a,s.mediaSize,s.state.cropSize,s.props.zoom,s.props.rotation):a;s.previousCropSize=s.state.cropSize,s.props.onCropChange(l),s.emitCropData()}},s.onKeyDown=function(a){var n,i,o=s.props,l=o.crop,c=o.onCropChange,u=o.keyboardStep,d=o.zoom,h=o.rotation,m=u;if(s.state.cropSize){a.shiftKey&&(m*=.2);var g=Qt({},l);switch(a.key){case"ArrowUp":g.y-=m,a.preventDefault();break;case"ArrowDown":g.y+=m,a.preventDefault();break;case"ArrowLeft":g.x-=m,a.preventDefault();break;case"ArrowRight":g.x+=m,a.preventDefault();break;default:return}s.props.restrictPosition&&(g=ua(g,s.mediaSize,s.state.cropSize,d,h)),a.repeat||(i=(n=s.props).onInteractionStart)===null||i===void 0||i.call(n),c(g)}},s.onKeyUp=function(a){var n,i;switch(a.key){case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":a.preventDefault();break;default:return}s.emitCropData(),(i=(n=s.props).onInteractionEnd)===null||i===void 0||i.call(n)},s}return t.prototype.componentDidMount=function(){!this.currentDoc||!this.currentWindow||(this.containerRef&&(this.containerRef.ownerDocument&&(this.currentDoc=this.containerRef.ownerDocument),this.currentDoc.defaultView&&(this.currentWindow=this.currentDoc.defaultView),this.initResizeObserver(),typeof window.ResizeObserver>"u"&&this.currentWindow.addEventListener("resize",this.computeSizes),this.props.zoomWithScroll&&this.containerRef.addEventListener("wheel",this.onWheel,{passive:!1}),this.containerRef.addEventListener("gesturestart",this.onGestureStart)),this.currentDoc.addEventListener("scroll",this.onScroll),this.props.disableAutomaticStylesInjection||(this.styleRef=this.currentDoc.createElement("style"),this.styleRef.setAttribute("type","text/css"),this.props.nonce&&this.styleRef.setAttribute("nonce",this.props.nonce),this.styleRef.innerHTML=zw,this.currentDoc.head.appendChild(this.styleRef)),this.imageRef.current&&this.imageRef.current.complete&&this.onMediaLoad(),this.props.setImageRef&&this.props.setImageRef(this.imageRef),this.props.setVideoRef&&this.props.setVideoRef(this.videoRef),this.props.setCropperRef&&this.props.setCropperRef(this.cropperRef))},t.prototype.componentWillUnmount=function(){var s,a;!this.currentDoc||!this.currentWindow||(typeof window.ResizeObserver>"u"&&this.currentWindow.removeEventListener("resize",this.computeSizes),(s=this.resizeObserver)===null||s===void 0||s.disconnect(),this.containerRef&&this.containerRef.removeEventListener("gesturestart",this.preventZoomSafari),this.styleRef&&((a=this.styleRef.parentNode)===null||a===void 0||a.removeChild(this.styleRef)),this.cleanEvents(),this.props.zoomWithScroll&&this.clearScrollEvent())},t.prototype.componentDidUpdate=function(s){var a,n,i,o,l,c,u,d,h;s.rotation!==this.props.rotation?(this.computeSizes(),this.recomputeCropPosition()):s.aspect!==this.props.aspect?this.computeSizes():s.objectFit!==this.props.objectFit?this.computeSizes():s.zoom!==this.props.zoom?this.recomputeCropPosition():((a=s.cropSize)===null||a===void 0?void 0:a.height)!==((n=this.props.cropSize)===null||n===void 0?void 0:n.height)||((i=s.cropSize)===null||i===void 0?void 0:i.width)!==((o=this.props.cropSize)===null||o===void 0?void 0:o.width)?this.computeSizes():(((l=s.crop)===null||l===void 0?void 0:l.x)!==((c=this.props.crop)===null||c===void 0?void 0:c.x)||((u=s.crop)===null||u===void 0?void 0:u.y)!==((d=this.props.crop)===null||d===void 0?void 0:d.y))&&this.emitCropAreaChange(),s.zoomWithScroll!==this.props.zoomWithScroll&&this.containerRef&&(this.props.zoomWithScroll?this.containerRef.addEventListener("wheel",this.onWheel,{passive:!1}):this.clearScrollEvent()),s.video!==this.props.video&&((h=this.videoRef.current)===null||h===void 0||h.load());var m=this.getObjectFit();m!==this.state.mediaObjectFit&&this.setState({mediaObjectFit:m},this.computeSizes)},t.prototype.getAspect=function(){var s=this.props,a=s.cropSize,n=s.aspect;return a?a.width/a.height:n},t.prototype.getObjectFit=function(){var s,a,n,i;if(this.props.objectFit==="cover"){var o=this.imageRef.current||this.videoRef.current;if(o&&this.containerRef){this.containerRect=this.containerRef.getBoundingClientRect();var l=this.containerRect.width/this.containerRect.height,c=((s=this.imageRef.current)===null||s===void 0?void 0:s.naturalWidth)||((a=this.videoRef.current)===null||a===void 0?void 0:a.videoWidth)||0,u=((n=this.imageRef.current)===null||n===void 0?void 0:n.naturalHeight)||((i=this.videoRef.current)===null||i===void 0?void 0:i.videoHeight)||0,d=c/u;return d<l?"horizontal-cover":"vertical-cover"}return"horizontal-cover"}return this.props.objectFit},t.prototype.onPinchStart=function(s){var a=t.getTouchPoint(s.touches[0]),n=t.getTouchPoint(s.touches[1]);this.lastPinchDistance=Fd(a,n),this.lastPinchRotation=Dd(a,n),this.onDragStart(Gd(a,n))},t.prototype.onPinchMove=function(s){var a=this;if(!(!this.currentDoc||!this.currentWindow)){var n=t.getTouchPoint(s.touches[0]),i=t.getTouchPoint(s.touches[1]),o=Gd(n,i);this.onDrag(o),this.rafPinchTimeout&&this.currentWindow.cancelAnimationFrame(this.rafPinchTimeout),this.rafPinchTimeout=this.currentWindow.requestAnimationFrame(function(){var l=Fd(n,i),c=a.props.zoom*(l/a.lastPinchDistance);a.setNewZoom(c,o,{shouldUpdatePosition:!1}),a.lastPinchDistance=l;var u=Dd(n,i),d=a.props.rotation+(u-a.lastPinchRotation);a.props.onRotationChange&&a.props.onRotationChange(d),a.lastPinchRotation=u})}},t.prototype.render=function(){var s=this,a,n=this.props,i=n.image,o=n.video,l=n.mediaProps,c=n.cropperProps,u=n.transform,d=n.crop,h=d.x,m=d.y,g=n.rotation,f=n.zoom,v=n.cropShape,x=n.showGrid,j=n.roundCropAreaPixels,b=n.style,y=b.containerStyle,S=b.cropAreaStyle,T=b.mediaStyle,I=n.classes,E=I.containerClassName,O=I.cropAreaClassName,V=I.mediaClassName,J=(a=this.state.mediaObjectFit)!==null&&a!==void 0?a:this.getObjectFit();return p.createElement("div",{onMouseDown:this.onMouseDown,onTouchStart:this.onTouchStart,ref:function(Ge){return s.containerRef=Ge},"data-testid":"container",style:y,className:dn("reactEasyCrop_Container",E)},i?p.createElement("img",Qt({alt:"",className:dn("reactEasyCrop_Image",J==="contain"&&"reactEasyCrop_Contain",J==="horizontal-cover"&&"reactEasyCrop_Cover_Horizontal",J==="vertical-cover"&&"reactEasyCrop_Cover_Vertical",V)},l,{src:i,ref:this.imageRef,style:Qt(Qt({},T),{transform:u||"translate(".concat(h,"px, ").concat(m,"px) rotate(").concat(g,"deg) scale(").concat(f,")")}),onLoad:this.onMediaLoad})):o&&p.createElement("video",Qt({autoPlay:!0,playsInline:!0,loop:!0,muted:!0,className:dn("reactEasyCrop_Video",J==="contain"&&"reactEasyCrop_Contain",J==="horizontal-cover"&&"reactEasyCrop_Cover_Horizontal",J==="vertical-cover"&&"reactEasyCrop_Cover_Vertical",V)},l,{ref:this.videoRef,onLoadedMetadata:this.onMediaLoad,style:Qt(Qt({},T),{transform:u||"translate(".concat(h,"px, ").concat(m,"px) rotate(").concat(g,"deg) scale(").concat(f,")")}),controls:!1}),(Array.isArray(o)?o:[{src:o}]).map(function(U){return p.createElement("source",Qt({key:U.src},U))})),this.state.cropSize&&p.createElement("div",Qt({ref:this.cropperRef,style:Qt(Qt({},S),{width:j?Math.round(this.state.cropSize.width):this.state.cropSize.width,height:j?Math.round(this.state.cropSize.height):this.state.cropSize.height}),tabIndex:0,onKeyDown:this.onKeyDown,onKeyUp:this.onKeyUp,"data-testid":"cropper",className:dn("reactEasyCrop_CropArea",v==="round"&&"reactEasyCrop_CropAreaRound",x&&"reactEasyCrop_CropAreaGrid",O)},c)))},t.defaultProps={zoom:1,rotation:0,aspect:4/3,maxZoom:qw,minZoom:Ww,cropShape:"rect",objectFit:"contain",showGrid:!0,style:{},classes:{},mediaProps:{},cropperProps:{},zoomSpeed:1,restrictPosition:!0,zoomWithScroll:!0,keyboardStep:Hw},t.getMousePoint=function(s){return{x:Number(s.clientX),y:Number(s.clientY)}},t.getTouchPoint=function(s){return{x:Number(s.clientX),y:Number(s.clientY)}},t}(p.Component);const Yn=[{question:"What is a personalised storybook?",answer:"A personalised storybook is a children's book where your child becomes the main character. At TalesBerry, we use your child's name, photo, age, and gender to create a fully customised story with illustrations that look like your child — making them the hero of their own adventure."},{question:"What is the best personalised gift for kids?",answer:"A personalised children's storybook is one of the most meaningful gifts you can give. Unlike toys that are quickly forgotten, a custom storybook with the child's name and face becomes a cherished keepsake that builds reading habits and lasts for years."},{question:"Are personalised books good for children?",answer:"Yes! Research shows that personalised books boost children's engagement with reading, improve self-esteem, and create stronger emotional connections to stories. When children see themselves as the hero, they're more motivated to read and develop a lifelong love of books."},{question:"What age are personalised storybooks suitable for?",answer:"TalesBerry personalised storybooks are designed for children aged 1 to 10 years. Each story theme has specific age recommendations so you can pick the perfect adventure for your child's developmental stage."},{question:"How is personalised storybook created?",answer:"It's 3 easy steps which takes just 2 minutes of time! First, you choose a story theme that your child will love. Then, enter the child's details like name, age, gender and one single clear photo and generate a FREE sample preview of the book. Lastly, if you like the preview, just place your order on the website itself and a beautiful hard cover book will be printed and shipped to your doorstep."},{question:"How much does a book cost?",answer:"All our books are priced same regardless of the story you chose. Prices vary by the book delivery location. For India-> 1)Hard cover: 1399/- per book 2) Soft cover: 1149/- per book (Shipping fee of 200 Rupees is charged extra). For Singapore -> 1) Hard cover: 44.99 SGD per book 2) Soft cover: 29.99 SGD per book (shipping fee of 4.99SGD is charged extra)"},{question:"How soon will I receive the book after placing my order?",answer:"Once we receive your order, the book typically takes 7-10 business days for production and delivery within India and Singapore. During this time, you will be kept updated on the progress through Email and/or Whatsapp, as applicable."},{question:"How is the quality of the books?",answer:"Our books are premium, glossy laminated hardcover editions, with high-quality 220 GSM thick paper and vibrant digital printing. They're designed to be durable and lasting, perfect for repeated readings and as keepsakes."},{question:"Are my photos safe?",answer:"Absolutely! We take data privacy very seriously. Your photos are only used to create the personalised book for you. Your photos are never used for any promotional purposes or for training AI models. All the photos are cleaned off from all our systems every 4 weeks automatically. If you want us to erase your personal information earlier than 4 weeks, just email us at pavi@talesberry.com, and we will delete all personal data linked to your preview or order within 24 hours from receipt of the email."},{question:"What kind of photos should I submit?",answer:"Front-facing photo with no sunglasses, no caps/headgear and no shadows works best."},{question:"Can I preview the book before ordering?",answer:"Yes! You can create a FREE sample 4 page preview of the book before ordering. This will give you a good idea of what the book contains and how the images are going to look like. After this, you can proceed ahead with placing your order and unlock rest of the images."},{question:"What age group are the books suitable for?",answer:"Our books are designed for children aged 1-10 years, with specific age recommendations for each story theme. You can find the recommended age range in the description of each book on our website."},{question:"Do you offer international shipping?",answer:"Currently, we ship to India and Singapore. We're working on expanding our shipping options to other countries and will announce when other countries shipping becomes available."},{question:"What payment methods do you accept?",answer:"We have integration with Razorpay and we accept all major payment methods including credit cards, debit cards, UPI and net banking."},{question:"Can I order multiple books in single order?",answer:"Currently we do not have capability for multiple books in same orders. Kindly proceed with one book at a time. If you have more than 1 book shipping to same place, just reach out to support via email or whatsapp and we will give you a coupon code to make shipping apply only once."},{question:"What is TalesBerry cancellation and refund policy?",answer:"You can cancel an order in first 12 hours after placing the order by sending us an email on pavi@talesberry.com or sending a message to our customer support whatsapp number and we shall refund the full amount paid. If the book is delivered in a damaged condition, you can request for a free replacement or full refund. Refunds will take a maximum of 7 working days to process at our end. There might be additional time taken by your source account to reflect the credit. In case you do not get the refund amount even after 14 working days, you can contact us at pavi@talesberry.com"}],Ud=["Checking if the image has a solo face...","Verifying the face is front-facing...","Analyzing image brightness and clarity...","Detecting any hats, sunglasses, or bandanas...","Checking for filters or blur...","Validating image quality for personalization..."],Po=({isOpen:r,error:t,onRetry:s})=>{const[a,n]=p.useState(0);return p.useEffect(()=>{if(!r||t)return;const i=setInterval(()=>{n(o=>(o+1)%Ud.length)},2e3);return()=>clearInterval(i)},[r,t]),p.useEffect(()=>{r&&n(0)},[r]),r?e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsx("div",{className:"relative bg-white rounded-2xl shadow-2xl p-8 max-w-md w-full mx-4 animate-scale-in",children:t?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx("svg",{className:"w-8 h-8 text-red-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})}),e.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Validation Failed"}),e.jsxs("div",{className:"mb-6 p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx("p",{className:"text-red-700 text-sm mb-2",children:t}),e.jsx("p",{className:"text-red-600 text-xs",children:"Please try uploading a clearer, front-facing photo of your child without hats, sunglasses, or filters."})]}),e.jsx("button",{onClick:s,className:"w-full bg-black text-white px-6 py-3 rounded-full font-medium hover:bg-gray-800 transition-colors",children:"Try Another Image"})]}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ue,{className:"w-16 h-16 text-purple-500 animate-spin"}),e.jsx("div",{className:"absolute inset-0 rounded-full bg-purple-100 blur-xl opacity-50"})]})}),e.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Validating Your Image"}),e.jsx("div",{className:"h-16 flex items-center justify-center",children:e.jsx("p",{className:"text-gray-600 animate-fade-in",children:Ud[a]},a)})]})})]}):null},jl=typeof window<"u"?window.location.hostname:"",Im=jl.includes("staging"),Rm=jl.includes("lovableproject.com"),Nl=Rm?"https://api.talesberry.com":Im?"https://staging-api.talesberry.com":"https://api.talesberry.com",yt=r=>{const t=r.startsWith("/")?r:`/${r}`;return`${Nl}${t}`},Kw=Rm?"LOVABLE_PREVIEW":Im?"STAGING":"PRODUCTION";console.log(`[API Config] Environment: ${Kw}`);console.log(`[API Config] Hostname: ${jl}`);console.log(`[API Config] API Base URL: ${Nl}`);const Yw=({book:r})=>{const t=p.useRef(null),[s,a]=p.useState(0),[n,i]=p.useState(!1),[o,l]=p.useState(!0),[c,u]=p.useState([]),d=r.imagePaths||[];p.useEffect(()=>{u(new Array(d.length).fill(!1))},[d.length]);const h=v=>{u(x=>{const j=[...x];return j[v]=!0,j})},m=()=>{var I;const v=t.current;if(!v)return;const{scrollLeft:x,scrollWidth:j,clientWidth:b}=v;i(x>10),l(x<j-b-10);const y=((I=v.firstElementChild)==null?void 0:I.clientWidth)||200,T=Math.round(x/(y+12));a(Math.min(T,d.length-1))};p.useEffect(()=>{const v=t.current;if(v)return v.addEventListener("scroll",m),m(),()=>v.removeEventListener("scroll",m)},[d.length]);const g=v=>{var S;const x=t.current;if(!x)return;const y=(((S=x.firstElementChild)==null?void 0:S.clientWidth)||200)+12;x.scrollBy({left:v==="left"?-y:y,behavior:"smooth"})},f=v=>{var y;const x=t.current;if(!x)return;const j=((y=x.firstElementChild)==null?void 0:y.clientWidth)||200;x.scrollTo({left:v*(j+12),behavior:"smooth"})};return d.length?e.jsxs("div",{className:"relative mb-6 -mx-4 md:mx-0",children:[e.jsxs("div",{className:"relative group",children:[e.jsx("button",{onClick:()=>g("left"),className:`absolute left-2 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white/90 backdrop-blur-sm rounded-full shadow-lg flex items-center justify-center transition-all duration-200 ${n?"opacity-100 hover:bg-white hover:scale-110":"opacity-30 pointer-events-none"}`,"aria-label":"Previous image",children:e.jsx(Ut,{className:"w-6 h-6 text-gray-700"})}),e.jsx("div",{ref:t,className:"flex gap-0 md:gap-3 overflow-x-auto scrollbar-hide scroll-smooth pb-0 md:pb-2",style:{scrollSnapType:"x mandatory"},children:d.map((v,x)=>e.jsxs("div",{className:"flex-shrink-0 relative overflow-hidden bg-gray-100 w-full md:w-auto md:rounded-xl shadow-md",style:{scrollSnapAlign:"start"},children:[!c[x]&&e.jsx("div",{className:"absolute inset-0 bg-gray-200 animate-pulse"}),e.jsx($s,{imagePath:v,alt:`${r.title} - Page ${x+1}`,className:`w-[100vw] h-[125vw] md:w-60 md:h-60 object-cover transition-opacity duration-300 ${c[x]?"opacity-100":"opacity-0"}`,loading:x<3?"eager":"lazy",onLoad:()=>h(x)}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/60 text-white text-xs px-2 py-0.5 rounded-full",children:x===0?"Cover":x===d.length-1?"Back":`Page ${x}`})]},x))}),e.jsx("button",{onClick:()=>g("right"),className:`absolute right-2 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white/90 backdrop-blur-sm rounded-full shadow-lg flex items-center justify-center transition-all duration-200 ${o?"opacity-100 hover:bg-white hover:scale-110":"opacity-30 pointer-events-none"}`,"aria-label":"Next image",children:e.jsx(gs,{className:"w-6 h-6 text-gray-700"})})]}),e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-1.5 z-10 md:relative md:bottom-auto md:left-auto md:translate-x-0 md:justify-center md:mt-3",children:d.map((v,x)=>e.jsx("button",{onClick:()=>f(x),className:`w-2 h-2 rounded-full transition-all duration-200 ${x===s?"bg-white md:bg-purple-500 w-4":"bg-white/50 md:bg-gray-300 hover:bg-white/70 md:hover:bg-gray-400"}`,"aria-label":`Go to page ${x+1}`},x))}),e.jsx("style",{children:`
        .scrollbar-hide::-webkit-scrollbar {
          display: none;
        }
        .scrollbar-hide {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
      `})]}):null},Jw=({book:r,showTitle:t=!1})=>{const{region:s}=ht(),a=Ss[s],n=a.bookPrice,i=a.softCoverPrice,o=Math.round(n*1.2),l=Math.round(i*1.2);return e.jsxs("div",{className:"bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-gray-100 mb-6",children:[t&&e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-3",children:r.title}),e.jsx("p",{className:"text-gray-600 text-sm sm:text-base mb-4 leading-relaxed",children:r.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-5",children:[r.theme&&e.jsx("span",{className:"inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-700",children:r.theme}),r.ageRange&&e.jsx("span",{className:"inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-700",children:r.ageRange}),r.category_tag&&e.jsx("span",{className:"inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700",children:r.category_tag}),r.pages&&e.jsxs("span",{className:"inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-700",children:[r.pages," Pages"]})]}),e.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Book Price"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Hardcover"}),e.jsx("span",{className:"text-[10px] bg-purple-500 text-white px-1.5 py-0.5 rounded-full font-medium",children:"Premium"})]}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-lg sm:text-xl font-bold text-gray-900",children:Gt(s,n)}),e.jsx("span",{className:"text-sm text-gray-400 line-through",children:Gt(s,o)})]}),e.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:"+ shipping"}),e.jsx("p",{className:"text-[10px] text-gray-500",children:"Durable & long-lasting"})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Softcover"}),e.jsx("span",{className:"text-[10px] bg-green-500 text-white px-1.5 py-0.5 rounded-full font-medium",children:"Value"})]}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-lg sm:text-xl font-bold text-gray-900",children:Gt(s,i)}),e.jsx("span",{className:"text-sm text-gray-400 line-through",children:Gt(s,l)})]}),e.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:"+ shipping"}),e.jsx("p",{className:"text-[10px] text-gray-500",children:"Light & affordable"})]})]})]})]})},Vd=({className:r="w-4 h-4"})=>e.jsx("div",{className:"flex gap-0.5",children:[...Array(5)].map((t,s)=>e.jsx(Pa,{className:r,fill:"#facc15",stroke:"#facc15"},s))}),zd={rating:4.9,total:85,reviews:[{author_name:"Priya M.",profile_photo_url:"",rating:5,text:"Absolutely loved the personalized book for my daughter! The illustrations were stunning and she was thrilled to see herself in the story. Highly recommend TalesBerry!",time:171e7},{author_name:"Rahul S.",profile_photo_url:"",rating:5,text:"Ordered as a birthday gift for my nephew. The quality of printing exceeded expectations. The story was engaging and he keeps asking us to read it every night.",time:17095e5},{author_name:"Ananya K.",profile_photo_url:"",rating:5,text:"What a wonderful concept! My son was so excited to see his name and face in a real storybook. The delivery was quick and the book quality is premium.",time:1709e6},{author_name:"Vikram P.",profile_photo_url:"",rating:5,text:"Great experience from start to finish. The personalization process was simple and the final product looked amazing. Perfect gift for kids!",time:17085e5},{author_name:"Sneha R.",profile_photo_url:"",rating:5,text:"TalesBerry created something truly special for our family. The book is beautifully made and the story is so heartwarming. Will definitely order again.",time:1708e6}]},kl=()=>{const r=p.useRef(!1),[t,s]=p.useState(new Set),[a,n]=p.useState(null),i=p.useRef(null),o=p.useRef(null);p.useEffect(()=>{var m,g;let d;if(d=setTimeout(()=>{n(f=>f||zd)},4e3),r.current)(g=(m=window.google)==null?void 0:m.maps)!=null&&g.places&&h();else{const f=document.createElement("script");f.src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBSa4EHEDSK7rY15TLIXC8FSvmVRfA-eCg&libraries=places",f.async=!0,f.defer=!0,document.head.appendChild(f),r.current=!0,f.onload=()=>{h()},f.onerror=()=>{n(zd),clearTimeout(d)}}function h(){var j,b;if(!((b=(j=window.google)==null?void 0:j.maps)!=null&&b.places))return;const f="ChIJM9uHzN4XrjsRPjtrgermI24",v=new window.google.maps.Map(document.createElement("div"));new window.google.maps.places.PlacesService(v).getDetails({placeId:f,fields:["name","rating","user_ratings_total","reviews"]},(y,S)=>{if(S!==window.google.maps.places.PlacesServiceStatus.OK)return;const T=(y.reviews||[]).sort((I,E)=>E.time-I.time);clearTimeout(d),n({rating:y.rating,total:y.user_ratings_total,reviews:T})})}return()=>clearTimeout(d)},[]);const l=d=>{s(h=>{const m=new Set(h);return m.has(d)?m.delete(d):m.add(d),m})},c=(d,h)=>{if(!d.current)return;const m=d.current.offsetWidth*.7;d.current.scrollBy({left:h==="left"?-m:m,behavior:"smooth"})},u=a?a.rating.toFixed(1):"4.9";return e.jsx("section",{className:"bg-white pt-0 md:pt-4",children:e.jsx("div",{className:"container mx-auto",children:a&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"md:hidden",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2 mt-1 px-1",children:[e.jsx(Vd,{className:"w-3.5 h-3.5"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-900",children:[u,"/5 · Google Reviews"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:()=>c(o,"left"),className:"absolute left-0 top-1/2 -translate-y-1/2 z-10 bg-white/80 rounded-full p-0.5 shadow-sm","aria-label":"Scroll left",children:e.jsx(Ut,{className:"w-4 h-4 text-gray-700"})}),e.jsx("div",{ref:o,className:"flex gap-3 overflow-x-auto pb-2 snap-x snap-mandatory scrollbar-none px-4",children:a.reviews.map((d,h)=>e.jsxs("div",{onClick:()=>l(h),className:"flex-shrink-0 w-[75%] bg-white border border-gray-200 rounded-lg p-3 shadow-sm snap-start cursor-pointer",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("p",{className:"font-semibold text-gray-900 text-xs",children:d.author_name}),e.jsxs("p",{className:"text-[10px] font-semibold text-gray-900",children:["Rated ",d.rating,"/5"]})]}),e.jsx("p",{className:`text-gray-600 text-xs leading-relaxed transition-all ${t.has(h)?"":"line-clamp-3"}`,children:d.text})]},h))}),e.jsx("button",{onClick:()=>c(o,"right"),className:"absolute right-0 top-1/2 -translate-y-1/2 z-10 bg-white/80 rounded-full p-0.5 shadow-sm","aria-label":"Scroll right",children:e.jsx(gs,{className:"w-4 h-4 text-gray-700"})})]})]}),e.jsxs("div",{className:"hidden md:block",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-8 mt-3",children:[e.jsx(Vd,{className:"w-5 h-5"}),e.jsxs("span",{className:"text-xl font-semibold text-gray-900",children:[u,"/5 · Google Reviews"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:()=>c(i,"left"),className:"absolute -left-4 top-1/2 -translate-y-1/2 z-10 bg-white rounded-full p-1.5 shadow-md hover:shadow-lg transition-shadow","aria-label":"Scroll left",children:e.jsx(Ut,{className:"w-5 h-5 text-gray-700"})}),e.jsx("div",{ref:i,className:"flex gap-4 overflow-x-auto pb-4 snap-x snap-mandatory scrollbar-none",children:a.reviews.map((d,h)=>e.jsxs("div",{onClick:()=>l(h),className:"flex-shrink-0 w-80 bg-white border border-gray-200 rounded-xl p-4 shadow-sm hover:shadow-md transition-all cursor-pointer snap-start",children:[e.jsx("div",{className:"flex items-center gap-3 mb-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:d.author_name}),e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:["Rated ",d.rating,"/5"]})]})}),e.jsx("p",{className:`text-gray-600 text-sm leading-relaxed ${t.has(h)?"":"line-clamp-1"}`,children:d.text}),d.text.length>50&&e.jsx("button",{className:"text-purple-600 text-xs mt-2 hover:text-purple-800 font-medium",children:t.has(h)?"Show less":"Read more"})]},h))}),e.jsx("button",{onClick:()=>c(i,"right"),className:"absolute -right-4 top-1/2 -translate-y-1/2 z-10 bg-white rounded-full p-1.5 shadow-md hover:shadow-lg transition-shadow","aria-label":"Scroll right",children:e.jsx(gs,{className:"w-5 h-5 text-gray-700"})})]})]})]})})})},Zw=({isOpen:r,onClose:t,currentStep:s,setCurrentStep:a,croppedImage:n,imagePreview:i,showCropper:o,crop:l,zoom:c,setCrop:u,setZoom:d,onCropComplete:h,handleCropDone:m,handleImageUpload:g,handleChangeCroppedImage:f,onCancelCrop:v,isValidatingFace:x=!1,faceValidationError:j=null,email:b,setEmail:y,whatsappNumber:S,setWhatsappNumber:T,childName:I,setChildName:E,childAge:O,setChildAge:V,childGender:J,setChildGender:U,hairstylePreference:Ge,setHairstylePreference:Te,consentChecked:Me,setConsentChecked:_e,countryCode:Se,handleNext:ue,isSubmitting:re})=>{const[Ne,fe]=jt.useState(!1);if(!r)return null;const qe=!!n;return e.jsxs("div",{className:"fixed inset-0 z-[60] bg-white overflow-y-auto",children:[e.jsxs("div",{className:"sticky top-0 bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between z-10",children:[e.jsx("h2",{className:"text-lg font-bold text-gray-900",children:"Personalise Your Book"}),e.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 rounded-full transition-colors","aria-label":"Close",children:e.jsx(Cs,{className:"w-6 h-6 text-gray-600"})})]}),e.jsx("div",{className:"px-4 py-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("button",{onClick:()=>a(1),className:`flex-1 py-3 px-4 rounded-xl font-medium text-sm transition-all flex items-center justify-center gap-2 ${s===1?"bg-purple-500 text-white shadow-lg":qe?"bg-green-100 text-green-700 border border-green-300":"bg-gray-100 text-gray-500"}`,children:[qe&&s!==1?e.jsx(Sa,{className:"w-4 h-4"}):e.jsx("span",{className:"w-5 h-5 rounded-full bg-white/20 flex items-center justify-center text-xs",children:"1"}),"Upload Photo"]}),e.jsxs("button",{onClick:()=>qe&&a(2),className:`flex-1 py-3 px-4 rounded-xl font-medium text-sm transition-all flex items-center justify-center gap-2 ${s===2?"bg-purple-500 text-white shadow-lg":qe?"bg-gray-100 text-gray-700 hover:bg-gray-200":"bg-gray-100 text-gray-400 cursor-not-allowed"}`,disabled:!qe,children:[e.jsx("span",{className:"w-5 h-5 rounded-full bg-white/20 flex items-center justify-center text-xs",children:"2"}),"Details"]})]})}),e.jsx("div",{className:"px-4 pb-8",children:s===1?e.jsx("div",{className:"bg-white rounded-2xl border border-gray-200 p-4",children:!o&&!n?e.jsxs("div",{className:"text-center py-2",children:[e.jsx("button",{onClick:()=>fe(!0),className:"text-purple-600 text-sm font-medium underline mb-2 inline-block",children:"View Image Guidelines"}),e.jsxs("label",{className:"inline-block","data-track":"mobile_modal_upload_image",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:g,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Child Image",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]}):o?e.jsxs("div",{className:"rounded-xl overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[350px]",children:e.jsx(As,{image:i,crop:l,zoom:c,aspect:1,onCropChange:u,onZoomChange:d,onCropComplete:h,cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"pt-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:c,onChange:pe=>d(Number(pe.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:v,className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:m,disabled:x,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:x?"Validating...":"Crop & Validate"})]}),j&&e.jsx("p",{className:"text-red-500 text-sm mt-3 text-center",children:j})]})]}):e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:URL.createObjectURL(n),alt:"Cropped preview",className:"w-32 h-32 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-3",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:f,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"}),"Change Image"]}),e.jsx("button",{onClick:()=>a(2),className:"mt-6 w-full bg-purple-500 text-white py-3 rounded-full font-medium hover:bg-purple-600 transition-colors","data-track":"mobile_modal_continue_to_details",children:"Continue to Details →"})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:b,onChange:pe=>y(pe.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy of the book",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"WhatsApp Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-20 px-2 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 font-medium",children:Se}),e.jsx("input",{type:"tel",value:S,onChange:pe=>{T(pe.target.value.replace(/\D/g,"").slice(0,10))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"10 digit number",maxLength:10,required:!0})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Partner's Name *"}),e.jsx("input",{type:"text",value:I,onChange:pe=>E(pe.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Partner's name to be printed on the book"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Partner's age *"}),e.jsx("input",{type:"number",value:O,onChange:pe=>V(pe.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Age",min:"18",max:"120"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Partner's Gender *"}),e.jsxs("select",{value:J,onChange:pe=>U(pe.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"Female",children:"Female"}),e.jsx("option",{value:"Male",children:"Male"})]})]})]}),J==="Female"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:"Choose a hairstyle that resembles your partner the most:"}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[{value:"wavy hair",label:"Wavy",image:"/hairstyles/wavy.jpg"},{value:"very short hair",label:"Short",image:"/hairstyles/short.jpg"},{value:"curly hair",label:"Curly",image:"/hairstyles/curly.jpg"}].map(pe=>e.jsxs("label",{className:"flex flex-col items-center cursor-pointer group",children:[e.jsxs("div",{className:`relative rounded-lg overflow-hidden border-2 transition-all w-full ${Ge===pe.value?"border-purple-500 shadow-lg ring-2 ring-purple-200":"border-gray-200"}`,children:[e.jsx("img",{src:pe.image,alt:pe.label,className:"w-full h-16 object-cover"}),e.jsx("input",{type:"radio",name:"hairstyle",value:pe.value,checked:Ge===pe.value,onChange:Xe=>Te(Xe.target.value),className:"absolute top-1 right-1 w-4 h-4 accent-purple-500"})]}),e.jsx("span",{className:"text-xs mt-1 text-center text-gray-600",children:pe.label})]},pe.value))})]}),e.jsx("div",{className:"pt-2",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:Me,onChange:pe=>_e(pe.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:["I confirm, I am over 18, and I consent to providing these details including the picture of my partner, for creating a personalised storybook, in accordance with the"," ",e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsxs("div",{className:"pt-4",children:[e.jsx(wt,{onClick:ue,disabled:re||!n||!b||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b)||!(I!=null&&I.trim())||!O||!Me,className:"w-full py-4 text-lg","data-track":"mobile_modal_see_book_preview",children:"See Book Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]})]})}),Ne&&e.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/70 p-4",onClick:()=>fe(!1),children:e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx("button",{onClick:()=>fe(!1),className:"absolute -top-8 right-0 text-white hover:text-gray-300 transition-colors","aria-label":"Close guidelines",children:e.jsx("svg",{className:"w-7 h-7",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo upload guidelines",className:"w-full h-auto rounded-lg shadow-2xl",onClick:pe=>pe.stopPropagation()})]})})]})},Xw=r=>r.replace(/^\[Girl\]'s\s+/i,"").replace(/^\[Boy\]'s\s+/i,"").replace(/^\[Girl\]\s*&\s*/i,"").replace(/^\[Boy\]\s*&\s*/i,""),Qw=(r,t)=>{const s=t==="Girl"?"girl":"boy";return{1:"girl_tiny_toes",2:"boy_tiny_toes",4:"girl_alphabet_journey",5:"boy_big_dreams",6:"girl_big_dreams",7:"girl_fairytale",8:"boy_tower_of_time",10:"boy_alphabet_journey"}[r]||`${s}_tiny_toes`},ej=()=>{const{id:r}=Xr(),t=_t(),s=Jt(),{region:a,buildLink:n}=ht(),[i,o]=p.useState(0),[l,c]=p.useState(null),[u,d]=p.useState(""),[h,m]=p.useState(""),[g,f]=p.useState("Boy"),[v,x]=p.useState(""),j=Number(r)===100,b=Number(r)===101||Number(r)===102,y=Number(r)===19||Number(r)===20,S=(k,C)=>{if(!(k!=null&&k.backendName))return k;const F={Boy:["boy","male"],Girl:["girl","female"],Male:["boy","male"],Female:["girl","female"]}[C]||[C.toLowerCase()];return Ot.find(ze=>ze.backendName===k.backendName&&F.includes(ze.suitableFor.toLowerCase()))||k},[T,I]=p.useState("wavy hair"),[E,O]=p.useState(""),[V,J]=p.useState(""),U=a==="SG"?"+65":a==="US"?"+1":"+91",[Ge,Te]=p.useState(!1),[Me,_e]=p.useState(null),[Se,ue]=p.useState(!1),[re,Ne]=p.useState(null),[fe,qe]=p.useState(!1),[pe,Xe]=p.useState(null),[ft,Ze]=p.useState(!1),[ke,Ce]=p.useState(!1),[B,st]=p.useState(null),[Ye,Y]=p.useState(!1),[ie,He]=p.useState({x:0,y:0}),[Qe,lt]=p.useState(1),[gt,we]=p.useState(null),Mt=p.useRef(null),[Z,he]=p.useState(null),[Be,Fe]=p.useState(null),[Pe,K]=p.useState(null),[z,ce]=p.useState(!1),[le,rt]=p.useState({x:0,y:0}),[Ve,Tt]=p.useState(1),[It,Bt]=p.useState(null),bt=p.useRef(null),[me,Zt]=p.useState(null),[ns,X]=p.useState(""),[te,$]=p.useState(""),[be,ee]=p.useState(1),ne=()=>({uploadedImage:null,imagePreview:null,showCropper:!1,crop:{x:0,y:0},zoom:1,croppedAreaPixels:null,croppedImage:null,name:"",age:"",gender:"Boy"}),[M,at]=p.useState([]),[ye,tt]=p.useState(1),[De,St]=p.useState(!1),[Ae,Q]=p.useState(ne()),[$e,ts]=p.useState(!1),[et,ct]=p.useState(null),[zt,Nt]=p.useState(!1),[Ft,Ct]=p.useState(!1),[ss,is]=p.useState(1),aa=p.useRef([]),Wt=Ot.find(k=>k.id===Number(r)),W=Wt,fs=(W==null?void 0:W.category_tag)==="return_gift_books";p.useEffect(()=>{W!=null&&W.title&&km(W.title,s.pathname,W.category_tag||void 0)},[s.pathname,W==null?void 0:W.title,W==null?void 0:W.category_tag]),p.useEffect(()=>{a==="IN"&&(y?(be===1&&Z&&Nt(!0),be===2&&me&&Nt(!0)):Z&&Nt(!0))},[Z,me,a,y,be]),p.useEffect(()=>{if(W!=null&&W.suitableFor){const k=W.suitableFor.toLowerCase();f(b?k==="female"?"Female":"Male":k==="girl"||k==="female"?"Girl":"Boy")}},[W==null?void 0:W.suitableFor,b]),p.useEffect(()=>{const k=a==="SG"&&(W==null?void 0:W.backendName)==="fairytale_adventure";I(k?"dark brown hair":"wavy hair")},[a,W==null?void 0:W.backendName]),p.useEffect(()=>{console.log("🔎 PersonalizationPage init - resolved book:",{id:r,title:W==null?void 0:W.title,backendName:W==null?void 0:W.backendName,canonicalTitle:Wt==null?void 0:Wt.title,canonicalBackendName:Wt==null?void 0:Wt.backendName,computedFromCanonical:Wt?Wt.backendName||Wt.title.toLowerCase().replace(/\s+/g,"_"):null})},[r]),p.useEffect(()=>{},[a,b]);const qa=()=>{};p.useEffect(()=>{if(!b||a!=="IN")return;const k=aa.current[i];k&&(k.currentTime=0,k.play().catch(()=>{}))},[i,b,a]);const na=p.useCallback(()=>{a==="IN"&&(window.history.pushState(null,"",s.pathname),t(n("/"),{replace:!0}))},[a,t,n,s.pathname]);if(p.useEffect(()=>{if(a==="IN")return window.history.pushState(null,"",s.pathname),window.addEventListener("popstate",na),()=>{window.removeEventListener("popstate",na)}},[a,na,s.pathname]),!W)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Book Not Found"}),e.jsx(wt,{onClick:()=>t(n("/")),children:"Back to Home"})]})});const Nr=Qw(W.id,W.suitableFor),Ha=W.id===9,Os=W.id===14,Ka=W.id===13,N=W.id===8,w=W.id===18,P=W.id===15||W.id===22,_=W.id===16,R=W.id===17,A=b?[{type:"video",url:`${ot}/in/girl_coupleBook/female_flipbook.mp4`},{type:"video",url:`${ot}/in/boy_coupleBook/male_flipbook.mp4`}]:Ha?[{type:"image",url:`${ot}/homepage_images/15.jpg`},{type:"image",url:`${ot}/homepage_images/16.jpg`}]:Os?[{type:"image",url:`${ot}/homepage_images/17.jpg`},{type:"image",url:`${ot}/homepage_images/18.jpg`}]:Ka?[{type:"image",url:`${ot}/in/cupcake_mystery/cover1.jpg`},{type:"image",url:`${ot}/in/cupcake_mystery/cover2.jpg`}]:N?[{type:"image",url:`${ot}/homepage_images/13.jpg`},{type:"image",url:`${ot}/homepage_images/14.jpg`}]:w?[{type:"image",url:`${ot}/homepage_images/21.jpg`},{type:"image",url:`${ot}/homepage_images/22.jpg`}]:P?[{type:"video",url:`${ot}/in/school_of_magic/flipbook.mp4`}]:_?[{type:"image",url:`${ot}/homepage_images/25.jpg`}]:R?[{type:"image",url:`${ot}/homepage_images/26.jpg`}]:[{type:"image",url:`${ot}/sg/${Nr}/coverpage_gif_effect/1.jpg`},{type:"image",url:`${ot}/sg/${Nr}/coverpage_gif_effect/2.jpg`}],L=k=>{var H;const C=(H=k.target.files)==null?void 0:H[0];if(C){if(!C.type.match(/^image\/(jpeg|jpg|png)$/)){alert("Please upload a JPG or PNG image only.");return}if(C.size>10*1024*1024){alert("Image size must be less than 10MB.");return}const F=new Image;F.onload=()=>{if(F.width<100||F.height<100){alert("Image resolution must be at least 100 × 100 pixels.");return}if(F.width>6e3||F.height>6e3){alert("Image resolution must be less than 6000 × 6000 pixels.");return}c(C),st(URL.createObjectURL(C)),Y(!0),he(null)},F.src=URL.createObjectURL(C)}},D=k=>new Promise((C,H)=>{const F=new Image;F.addEventListener("load",()=>C(F)),F.addEventListener("error",Re=>H(Re)),F.src=k}),q=async(k,C)=>{const H=await D(k),F=document.createElement("canvas"),Re=F.getContext("2d");if(!Re)throw new Error("Canvas context not available");return F.width=C.width,F.height=C.height,Re.drawImage(H,C.x,C.y,C.width,C.height,0,0,C.width,C.height),new Promise((ze,We)=>{F.toBlob(cs=>{cs?ze(cs):We(new Error("Canvas is empty"))},"image/jpeg",.95)})},oe=async()=>{const k=Mt.current??gt;if(!B||!l){Ne("Please upload an image and try again.");return}if(!k){Ne("Image crop is still loading. Please tap Crop & Continue again.");return}try{ue(!0),Ne(null);const C=await q(B,k),H=new File([C],l.name,{type:"image/jpeg"}),F=await dt(H),Re=F.includes(",")?F.split(",")[1]:F,ze=await fetch(yt("/api/faces/validate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image_data:Re})}),We=await ze.json();if(!ze.ok||(We==null?void 0:We.status)==="failed"||We!=null&&We.error){const cs=(We==null?void 0:We.message)||(We==null?void 0:We.error)||"Face validation failed. Please try again with a clearer, front-facing photo.";Ne(cs);return}he(H),Y(!1),Ne(null),B&&URL.revokeObjectURL(B)}catch(C){console.error("Error cropping/validating image:",C),Ne("Something went wrong while validating your image. Please try again.")}finally{ue(!1)}},G=()=>{he(null),c(null),Ne(null),B&&URL.revokeObjectURL(B),st(null)},ae=k=>{var H;const C=(H=k.target.files)==null?void 0:H[0];if(C){if(!C.type.match(/^image\/(jpeg|jpg|png)$/)){alert("Please upload a JPG or PNG image only.");return}if(C.size>10*1024*1024){alert("Image size must be less than 10MB.");return}const F=new Image;F.onload=()=>{if(F.width<100||F.height<100){alert("Image resolution must be at least 100 × 100 pixels.");return}if(F.width>6e3||F.height>6e3){alert("Image resolution must be less than 6000 × 6000 pixels.");return}Fe(C),K(URL.createObjectURL(C)),ce(!0),Zt(null)},F.src=URL.createObjectURL(C)}},xe=async()=>{const k=bt.current??It;if(!Pe||!Be){Xe("Please upload an image and try again.");return}if(!k){Xe("Image crop is still loading. Please tap Crop & Continue again.");return}try{qe(!0),Xe(null);const C=await q(Pe,k),H=new File([C],Be.name,{type:"image/jpeg"}),F=await dt(H),Re=F.includes(",")?F.split(",")[1]:F,ze=await fetch(yt("/api/faces/validate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image_data:Re})}),We=await ze.json();if(!ze.ok||(We==null?void 0:We.status)==="failed"||We!=null&&We.error){const cs=(We==null?void 0:We.message)||(We==null?void 0:We.error)||"Face validation failed. Please try again with a clearer, front-facing photo.";Xe(cs);return}Zt(H),ce(!1),Xe(null),Pe&&URL.revokeObjectURL(Pe)}catch(C){console.error("Error cropping/validating image 2:",C),Xe("Something went wrong while validating your image. Please try again.")}finally{qe(!1)}},ve=()=>{Zt(null),Fe(null),Xe(null),Pe&&URL.revokeObjectURL(Pe),K(null)},dt=k=>new Promise((C,H)=>{const F=new Image,Re=URL.createObjectURL(k);F.onload=()=>{try{const ze=document.createElement("canvas");ze.width=F.naturalWidth,ze.height=F.naturalHeight;const We=ze.getContext("2d");if(!We)return URL.revokeObjectURL(Re),H(new Error("Canvas not supported"));We.drawImage(F,0,0);const cs=ze.toDataURL("image/jpeg",.92);URL.revokeObjectURL(Re),C(cs)}catch(ze){URL.revokeObjectURL(Re),H(ze)}},F.onerror=()=>{URL.revokeObjectURL(Re);const ze=new FileReader;ze.onload=()=>C(ze.result),ze.onerror=We=>H(We),ze.readAsDataURL(k)},F.src=Re}),se=async()=>{var We,cs,Rl,$l,Ll,Ol,Ml;const k=(W==null?void 0:W.backendName)||((We=W==null?void 0:W.title)==null?void 0:We.toLowerCase().replace(/\s+/g,"_"))||"";if(console.log("▶️ handleNext clicked"),console.log("  book.title:",W==null?void 0:W.title),console.log("  book.backendName:",W==null?void 0:W.backendName),console.log("  ✅ selected gender:",g),console.log("  ✅ book_name for API:",k),!Z){alert(y||fs?"Please upload a photo of Child 1.":"Please upload a photo of your child.");return}if(y&&!me){alert("Please upload a photo of Child 2.");return}if(fs)for(let Rt=0;Rt<M.length;Rt++){if(!M[Rt].croppedImage){alert(`Please upload a photo for Child ${Rt+2}.`);return}if(!((cs=M[Rt].name)!=null&&cs.trim())){alert(`Please enter Child ${Rt+2}'s first name.`);return}if(!M[Rt].age){alert(`Please select Child ${Rt+2}'s age.`);return}}if(!E){alert("Please enter your email address.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){alert("Please enter a valid email address.");return}const H=U==="+91",F=U==="+1",Re=V==null?void 0:V.trim();if(H&&!Re){alert("Please enter your WhatsApp number.");return}if(Re){let Rt,Bs;if(H?(Rt=/^[6-9]\d{9}$/,Bs="Please enter a valid 10-digit WhatsApp number starting with 6-9."):F?(Rt=/^\d{10}$/,Bs="Please enter a valid 10-digit phone number."):(Rt=/^\d{8}$/,Bs="Please enter a valid 8-digit WhatsApp number."),!Rt.test(Re)){alert(Bs);return}}if(!(u==null?void 0:u.trim())){alert(j?"Please enter the father's name.":b?"Please enter your partner's name.":y||fs?"Please enter Child 1's first name.":"Please enter your child's first name.");return}if(!h){alert(j?"Please enter the father's age.":b?"Please enter your partner's age.":y||fs?"Please select Child 1's age.":"Please select your child's age.");return}if(y){if(!(ns!=null&&ns.trim())){alert("Please enter Child 2's first name.");return}if(!te){alert("Please select Child 2's age.");return}}if(j&&!v){alert("Please enter how you call your dad.");return}Te(!0),_e(null);try{console.log("📤 Sending to API - book_name:",k);let Rt,Bs,Ya;if(fs){const ds=[u.trim(),...M.map(us=>us.name.trim())],ys=[h,...M.map(us=>us.age)],Pr=[g.toLowerCase(),...M.map(us=>us.gender.toLowerCase())];Rt=ds.join(","),Bs=ys.join(","),Ya=Pr.join(",")}else y?(Rt=`${u.trim()},${ns.trim()}`,Bs=`${h},${te}`,Ya=`${g.toLowerCase()},${g.toLowerCase()}`):(Rt=u,Bs=h,Ya=g.toLowerCase());const Bl=await fetch(yt("/api/sessions/create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({book_name:k,...j?{father_name:u,dad_nickname:v}:b?{partner_name:u}:{child_name:Rt},gender:Ya,age:y||fs?Bs:parseInt(h),hairstyle_preference:T,email_id:E,whatsapp_number:V,consent_given:!0,consent_text_version:"v1.0"})});if(!Bl.ok)throw new Error("Failed to create session");const Ws=(await Bl.json()).session_id;console.log("💾 Storing session_id in localStorage:",Ws),localStorage.setItem("session_id",Ws);let Ja=(await dt(Z)).trim();/^data:image\/(jpeg|jpg|png);base64,/i.test(Ja)||(Ja=`data:${(Z==null?void 0:Z.type)||"image/jpeg"};base64,`+Ja.replace(/^data:[^,]*,/,""));const ti=await fetch(yt("/api/faces/upload-and-validate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:Ws,face_image_base64:Ja,filename:`child1.${(Rl=Z==null?void 0:Z.type)!=null&&Rl.includes("png")?"png":"jpg"}`})});let Sr;try{Sr=await ti.json()}catch{const ys=await ti.text().catch(()=>"");throw new Error(ys||"Invalid server response while parsing face validation result")}if(!ti.ok||Sr.status!=="uploaded_and_validated")throw new Error(Sr.message||"Face validation failed");const Cr=[Sr];if(y&&me){let ys=(await dt(me)).trim();/^data:image\/(jpeg|jpg|png);base64,/i.test(ys)||(ys=`data:${(me==null?void 0:me.type)||"image/jpeg"};base64,`+ys.replace(/^data:[^,]*,/,""));const Pr=await fetch(yt("/api/faces/upload-and-validate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:Ws,face_image_base64:ys,filename:`child2.${($l=me==null?void 0:me.type)!=null&&$l.includes("png")?"png":"jpg"}`})});let us;try{us=await Pr.json()}catch{const Er=await Pr.text().catch(()=>"");throw new Error(Er||"Face validation failed for Child 2")}if(!Pr.ok||us.status!=="uploaded_and_validated")throw new Error(us.message||"Face validation failed for Child 2");Cr.push(us)}if(fs)for(let ds=0;ds<M.length;ds++){const ys=M[ds];if(!ys.croppedImage)continue;let us=(await dt(ys.croppedImage)).trim();/^data:image\/(jpeg|jpg|png);base64,/i.test(us)||(us=`data:${((Ll=ys.croppedImage)==null?void 0:Ll.type)||"image/jpeg"};base64,`+us.replace(/^data:[^,]*,/,""));const Za=await fetch(yt("/api/faces/upload-and-validate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:Ws,face_image_base64:us,filename:`child${ds+2}.${(Ml=(Ol=ys.croppedImage)==null?void 0:Ol.type)!=null&&Ml.includes("png")?"png":"jpg"}`})});let Er;try{Er=await Za.json()}catch{const Wm=await Za.text().catch(()=>"");throw new Error(Wm||`Face validation failed for Child ${ds+2}`)}if(!Za.ok||Er.status!=="uploaded_and_validated")throw new Error(Er.message||`Face validation failed for Child ${ds+2}`);Cr.push(Er)}console.log("📝 Starting preview generation for session:",Ws);const Fl=await fetch(yt("/api/preview/generate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:Ws})}),Dl=await Fl.json();!Fl.ok||Dl.status!=="started"?console.warn("⚠️ Preview generation may not have started properly:",Dl):console.log("✅ Preview generation started successfully");const zm=S(W,g);t(n(`/preview?sessionId=${Ws}`),{state:{book:zm,childName:Rt,childAge:Bs,childGender:g,hairstylePreference:T,email:E,whatsappNumber:V,sessionId:Ws,faceImageUrl:Cr.length>1?Cr.map(ds=>ds.face_image_url).join(", "):Sr.face_image_url,faceImageKey:Cr.length>1?Cr.map(ds=>ds.face_image_key).join(", "):Sr.face_image_key}})}catch(Rt){_e(Rt instanceof Error?Rt.message:"An error occurred. Please try again.")}},Le=()=>{Te(!1),_e(null),c(null),he(null),B&&URL.revokeObjectURL(B),st(null),y&&(Fe(null),Zt(null),Pe&&URL.revokeObjectURL(Pe),K(null)),fs&&(M.forEach(k=>{k.imagePreview&&URL.revokeObjectURL(k.imagePreview)}),at([]),tt(1),St(!1),Q(ne()))},Ke=k=>e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"w-full max-w-[300px] mx-auto rounded-xl overflow-hidden shadow-lg bg-black",children:e.jsx("video",{src:k,autoPlay:!0,muted:!0,playsInline:!0,loop:!0,preload:"auto",onLoadedMetadata:C=>{C.target.playbackRate=.75},className:"w-full h-auto block"})}),e.jsx("p",{className:"text-center text-purple-700 font-semibold text-base mt-4",children:"Personalise this story in 2 easy steps!"})]}),Ee=()=>e.jsxs("div",{className:"mb-6 -mx-1 md:mx-0",children:[e.jsxs("div",{className:`relative w-full overflow-hidden shadow-lg bg-gray-100 ${b?"aspect-[4/3] md:mx-auto md:max-w-[320px] md:rounded-xl":"aspect-[3/4] md:aspect-square md:mx-auto md:max-w-[260px] md:rounded-xl"}`,children:[A.map((k,C)=>k.type==="video"?e.jsx("video",{ref:H=>{aa.current[C]=H,H&&(H.playbackRate=.75)},src:k.url,autoPlay:i===C,muted:!0,playsInline:!0,loop:A.length===1,preload:"auto",onEnded:qa,onLoadedMetadata:H=>{H.target.playbackRate=.75},className:`absolute inset-0 w-full h-full object-contain transition-opacity duration-500 ${i===C?"opacity-100":"opacity-0"}`},C):e.jsx("img",{src:k.url,alt:`Sample page ${C+1}`,className:`absolute inset-0 w-full h-full object-contain transition-opacity duration-500 ${i===C?"opacity-100":"opacity-0"}`,loading:"eager"},C)),A.length>1&&e.jsx("button",{onClick:()=>o(k=>(k-1+A.length)%A.length),className:`absolute left-2 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white/90 backdrop-blur-sm rounded-full shadow-lg flex items-center justify-center ${i===0?"opacity-30":"opacity-100"}`,children:e.jsx(Ut,{className:"w-6 h-6 text-gray-700"})}),A.length>1&&e.jsx("button",{onClick:()=>o(k=>(k+1)%A.length),className:`absolute right-2 top-1/2 -translate-y-1/2 z-10 w-10 h-10 bg-white/90 backdrop-blur-sm rounded-full shadow-lg flex items-center justify-center ${i===A.length-1?"opacity-30":"opacity-100"}`,children:e.jsx(gs,{className:"w-6 h-6 text-gray-700"})}),e.jsx("div",{className:"absolute bottom-3 left-1/2 transform -translate-x-1/2 flex gap-2",children:A.map((k,C)=>e.jsx("button",{onClick:()=>o(C),className:`w-3 h-3 rounded-full transition-colors cursor-pointer ${i===C?"bg-white":"bg-white/50 hover:bg-white/70"}`,"aria-label":`Show image ${C+1}`},C))})]}),e.jsx("p",{className:`text-center text-purple-700 font-semibold text-base mt-4 ${b?"hidden md:block":""}`,children:"Personalise this story in 2 easy steps!"})]}),ge=()=>e.jsxs(e.Fragment,{children:[a==="IN"?e.jsxs("div",{ref:Qn,className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"w-full px-4 py-4 bg-gray-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-full bg-purple-500 text-white text-xs font-bold whitespace-nowrap",children:"Step 1"}),e.jsx("h2",{className:"text-lg font-bold text-gray-900",children:y?"Upload a photo of Child 1":b?"Upload a photo of your partner":"Upload a photo of your child"})]})}),e.jsx("div",{className:"p-4",children:!Ye&&!Z?e.jsxs("div",{className:"text-center",children:[b?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>Ce(!0),className:"md:hidden text-purple-600 text-sm font-medium underline mb-3 inline-block",children:"View Image Guidelines"}),e.jsx("div",{className:"hidden md:block",children:e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-xs mx-auto rounded-lg border border-gray-200"})})})]}):e.jsx(e.Fragment,{children:e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-xs mx-auto rounded-lg border border-gray-200"})})}),e.jsxs("label",{className:"inline-block","data-gtm":"personalize_choose_image","data-track":"personalize_choose_image",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:L,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Child Image",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]}):Ye?e.jsxs("div",{className:"rounded-xl overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[350px] sm:h-[450px]",children:e.jsx(As,{image:B,crop:ie,zoom:Qe,aspect:1,onCropChange:He,onZoomChange:lt,onCropComplete:(k,C)=>{Mt.current=C,we(C)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"pt-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Qe,onChange:k=>lt(Number(k.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{Y(!1),st(null),c(null),B&&URL.revokeObjectURL(B)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:oe,disabled:Se,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:Se?"Validating...":"Crop & Validate"})]}),re&&e.jsx("p",{className:"text-red-500 text-sm mt-3 text-center min-h-[20px]",children:re})]})]}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:URL.createObjectURL(Z),alt:"Cropped preview",className:"w-32 h-32 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-3",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:G,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"}),"Change Image"]})]})})]}):e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-3",children:y?"Upload a photo of Child 1":b?"Upload a photo of your partner":"Upload a photo of your child"}),!Ye&&!Z?e.jsx("div",{className:"border-2 border-dashed border-purple-300 rounded-2xl p-4 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-xs mx-auto rounded-lg border border-gray-200"})}),e.jsxs("label",{className:"inline-block","data-gtm":"personalize_choose_image","data-track":"personalize_choose_image",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:L,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Child Image",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]})}):Ye?e.jsxs("div",{className:"border-2 border-solid border-purple-300 rounded-2xl bg-white overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[350px] sm:h-[450px]",children:e.jsx(As,{image:B,crop:ie,zoom:Qe,aspect:1,onCropChange:He,onZoomChange:lt,onCropComplete:(k,C)=>{Mt.current=C,we(C)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"p-4 border-t border-gray-200",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Qe,onChange:k=>lt(Number(k.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{Y(!1),st(null),c(null),B&&URL.revokeObjectURL(B)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:oe,disabled:Se,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:Se?"Validating...":"Crop & Validate"})]}),re&&e.jsx("p",{className:"text-red-500 text-sm mt-3 text-center",children:re})]})]}):e.jsx("div",{className:"border-2 border-solid border-purple-300 rounded-2xl p-4 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:URL.createObjectURL(Z),alt:"Cropped preview",className:"w-32 h-32 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-3",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:G,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"}),"Change Image"]})]})})]}),e.jsx("div",{ref:El})]}),ut=()=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"w-full px-4 py-4 bg-gray-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-full bg-purple-500 text-white text-xs font-bold whitespace-nowrap",children:"Step 1"}),e.jsx("h2",{className:"text-lg font-bold text-gray-900",children:"Upload a photo of Child 2"})]})}),Z&&e.jsx("div",{className:"p-4",children:!z&&!me?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-xs mx-auto rounded-lg border border-gray-200"})}),e.jsxs("label",{className:"inline-block",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:ae,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Upload Image ",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]}):z?e.jsxs("div",{className:"rounded-xl overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[350px] sm:h-[450px]",children:e.jsx(As,{image:Pe,crop:le,zoom:Ve,aspect:1,onCropChange:rt,onZoomChange:Tt,onCropComplete:(k,C)=>{bt.current=C,Bt(C)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"pt-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Ve,onChange:k=>Tt(Number(k.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{ce(!1),K(null),Fe(null),Pe&&URL.revokeObjectURL(Pe)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:xe,disabled:fe,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:fe?"Validating...":"Crop & Validate"})]}),pe&&e.jsx("p",{className:"text-red-500 text-sm mt-3 text-center",children:pe})]})]}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:URL.createObjectURL(me),alt:"Cropped preview - Child 2",className:"w-32 h-32 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-3",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:ve,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"})," Change Image"]})]})})]}),mt=()=>e.jsxs("div",{className:"bg-green-50 rounded-2xl shadow-sm border border-green-200 p-4 mb-6 flex items-center gap-4",children:[Z&&e.jsx("img",{src:URL.createObjectURL(Z),alt:"Child 1",className:"w-16 h-16 rounded-full object-cover border-2 border-green-300"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-green-700 font-semibold text-sm",children:"✓ Child 1 Details Complete"}),e.jsxs("div",{className:"text-gray-700 text-sm",children:[u,", Age ",h]})]}),e.jsx("button",{onClick:()=>{ee(1),Nt(!0)},className:"ml-auto text-purple-600 text-sm font-medium hover:underline",children:"Edit"})]}),Vt=()=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6",children:[e.jsxs("div",{className:`w-full px-4 py-4 flex items-center justify-between ${Z?"bg-gray-50 cursor-pointer hover:bg-gray-100":"bg-gray-100 cursor-not-allowed opacity-70"} transition-colors`,onClick:()=>{Z&&Nt(!zt)},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap ${Z?"bg-purple-500 text-white":"bg-gray-300 text-gray-600"}`,children:"Step 2"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("h2",{className:`text-lg font-bold ${Z?"text-gray-900":"text-gray-500"}`,children:"Child 1 Details"}),!Z&&e.jsx("span",{className:"text-xs text-gray-500",children:"(Upload image first)"})]})]}),Z&&(zt?e.jsx(qr,{className:"w-5 h-5 text-gray-500"}):e.jsx(Us,{className:"w-5 h-5 text-gray-500"}))]}),zt&&Z&&e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:E,onChange:k=>O(k.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy of the book",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"WhatsApp Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-20 px-2 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 font-medium",children:U}),e.jsx("input",{type:"tel",value:V,onChange:k=>{const C=U==="+65"?8:10;J(k.target.value.replace(/\D/g,"").slice(0,C))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"10 digit number",maxLength:10,required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Child's First Name *"}),e.jsx("input",{type:"text",value:u,onChange:k=>d(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Child 1's name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]})]}),e.jsx("div",{className:"pt-4",children:e.jsx(wt,{onClick:()=>{if(!(u!=null&&u.trim())){alert("Please enter Child 1's first name.");return}if(!h){alert("Please select Child 1's age.");return}if(!E){alert("Please enter your email address.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){alert("Please enter a valid email address.");return}const k=V==null?void 0:V.trim();if(U==="+91"&&!k){alert("Please enter your WhatsApp number.");return}if(k&&!(U==="+91"?/^[6-9]\d{9}$/:U==="+1"?/^\d{10}$/:/^\d{8}$/).test(k)){alert("Please enter a valid WhatsApp number.");return}ee(2),Nt(!1)},disabled:!Z||!E||!u||!h,className:"w-full py-4 text-lg",children:"Continue to Child 2 →"})})]})]}),pt=()=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6",children:[e.jsx("div",{className:`w-full px-4 py-4 ${me?"bg-gray-50":"bg-gray-100"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap ${me?"bg-purple-500 text-white":"bg-gray-300 text-gray-600"}`,children:"Step 2"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("h2",{className:`text-lg font-bold ${me?"text-gray-900":"text-gray-500"}`,children:"Child 2 Details"}),!me&&e.jsx("span",{className:"text-xs text-gray-500",children:"(Upload image first)"})]})]})}),me&&e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Child's First Name *"}),e.jsx("input",{type:"text",value:ns,onChange:k=>X(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Child 2's name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:te,onChange:k=>$(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]})]}),e.jsx("div",{className:"pt-2",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:ft,onChange:k=>Ze(k.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:["I confirm, I am the parent or legal guardian of these children (or I have the necessary permission), I am over 18, and I consent to providing these details for creating a personalised storybook in accordance with the"," ",e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsxs("div",{className:"pt-4",children:[e.jsx(wt,{onClick:se,disabled:Ge||!Z||!me||!E||!u||!h||!ns||!te||!ft,className:"w-full py-4 text-lg","data-gtm":"personalize_continue_preview","data-track":"personalize_see_book_preview",children:"See Book Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]})]})]}),Pt=()=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6",children:[e.jsxs("div",{className:`w-full px-4 py-4 flex items-center justify-between ${(y?Z&&me:Z)?"bg-gray-50 cursor-pointer hover:bg-gray-100":"bg-gray-100 cursor-not-allowed opacity-70"} transition-colors`,onClick:()=>{(y?Z&&me:Z)&&Nt(!zt)},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap ${(y?Z&&me:Z)?"bg-purple-500 text-white":"bg-gray-300 text-gray-600"}`,children:y?"Step 3":"Step 2"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("h2",{className:`text-lg font-bold ${(y?Z&&me:Z)?"text-gray-900":"text-gray-500"}`,children:"Personalisation Details"}),!(y?Z&&me:Z)&&e.jsx("span",{className:"text-xs text-gray-500",children:y?"(Upload both images first)":"(Upload image first)"})]})]}),(y?Z&&me:Z)&&(zt?e.jsx(qr,{className:"w-5 h-5 text-gray-500"}):e.jsx(Us,{className:"w-5 h-5 text-gray-500"}))]}),zt&&(y?Z&&me:Z)&&e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:E,onChange:k=>O(k.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy of the book",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"WhatsApp Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-20 px-2 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 font-medium",children:U}),e.jsx("input",{type:"tel",value:V,onChange:k=>{const C=U==="+65"?8:10;J(k.target.value.replace(/\D/g,"").slice(0,C))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"10 digit number",maxLength:10,required:!0})]})]}),y?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-semibold text-purple-700 mb-2",children:"Child 1"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"First Name *"}),e.jsx("input",{type:"text",value:u,onChange:k=>d(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Child 1's name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-semibold text-purple-700 mb-2",children:"Child 2"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"First Name *"}),e.jsx("input",{type:"text",value:ns,onChange:k=>X(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Child 2's name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:te,onChange:k=>$(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:j?"Father's name *":b?"Partner's Name *":"Child's first name *"}),e.jsx("input",{type:"text",value:u,onChange:k=>d(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:j?"Father's name to be printed on the book":b?"Partner's name to be printed on the book":"Name to be printed on the book"})]}),j&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"How do you call your dad? *"}),e.jsx("input",{type:"text",value:v,onChange:k=>x(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"e.g., Papa, Daddy, Appa, Baba"})]}),j?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Father's age *"}),e.jsx("input",{type:"number",value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Enter father's age",min:"1",max:"120"})]}):b?e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Partner's age *"}),e.jsx("input",{type:"number",value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Enter partner's age",min:"18",max:"120"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Partner's Gender *"}),e.jsxs("select",{value:g,onChange:k=>f(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"Female",children:"Female"}),e.jsx("option",{value:"Male",children:"Male"})]})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's age *"}),e.jsxs("select",{value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select age"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's Gender *"}),e.jsx("select",{value:g,onChange:k=>f(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:(()=>{var F;const k=W.backendName||((F=W.title)==null?void 0:F.toLowerCase())||"",C=k==="fairytale"||k.includes("fairytale"),H=k==="tower_of_time"||k.includes("tower of time");return C?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"Girl",children:"Girl"}),e.jsx("option",{value:"Boy",disabled:!0,children:"This book is only available for Girls"})]}):H?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"Boy",children:"Boy"}),e.jsx("option",{value:"Girl",disabled:!0,children:"This book is only available for Boys"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"Boy",children:"Boy"}),e.jsx("option",{value:"Girl",children:"Girl"})]})})()})]})]})]}),!j&&g==="Girl"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:b?"Choose a hairstyle that resembles your partner the most:":"Choose a hairstyle that resembles your child the most:"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[{value:"wavy hair",label:"Regular wavy hair",image:"/hairstyles/wavy.jpg"},{value:"very short hair",label:"Very short hair",image:"/hairstyles/short.jpg"},{value:"curly hair",label:"Curly hair",image:"/hairstyles/curly.jpg"}].map(k=>e.jsxs("label",{className:"flex flex-col items-center cursor-pointer group",children:[e.jsxs("div",{className:`relative rounded-lg overflow-hidden border-2 transition-all ${T===k.value?"border-purple-500 shadow-lg ring-2 ring-purple-200":"border-gray-200 group-hover:border-purple-300"}`,children:[e.jsx("img",{src:k.image,alt:k.label,className:"w-full h-20 object-cover"}),e.jsx("input",{type:"radio",name:"hairstyle",value:k.value,checked:T===k.value,onChange:C=>I(C.target.value),className:"absolute top-2 right-2 w-4 h-4 accent-purple-500"})]}),e.jsx("span",{className:"text-xs mt-2 text-center text-gray-600",children:k.label})]},k.value))})]}),e.jsx("div",{className:"pt-2",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:ft,onChange:k=>Ze(k.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:[b?e.jsxs(e.Fragment,{children:["I confirm, I am over 18, and I consent to providing these details including the picture of my partner, for creating a personalised storybook, in accordance with the"," "]}):e.jsxs(e.Fragment,{children:["I confirm, I am the parent or legal guardian of this child (or I have the necessary permission from the parent of this child), I am over 18, and I consent to providing these details for creating a personalised storybook in accordance with the"," "]}),e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsxs("div",{className:"pt-4",children:[e.jsx(wt,{onClick:se,disabled:Ge||!Z||y&&!me||!E||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)||!u||!h||y&&(!ns||!te)||!ft,className:"w-full py-4 text-lg","data-gtm":"personalize_continue_preview","data-track":"personalize_see_book_preview",children:"See Book Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]})]})]}),xs=k=>{var H;const C=(H=k.target.files)==null?void 0:H[0];if(C){if(!C.type.match(/^image\/(jpeg|jpg|png)$/)){alert("Please upload a JPG or PNG image only.");return}if(C.size>10*1024*1024){alert("Image size must be less than 10MB.");return}const F=new Image;F.onload=()=>{if(F.width<100||F.height<100){alert("Image resolution must be at least 100 × 100 pixels.");return}if(F.width>6e3||F.height>6e3){alert("Image resolution must be less than 6000 × 6000 pixels.");return}Q(Re=>({...Re,uploadedImage:C,imagePreview:URL.createObjectURL(C),showCropper:!0,croppedImage:null}))},F.src=URL.createObjectURL(C)}},Ps=async()=>{if(!(!Ae.imagePreview||!Ae.croppedAreaPixels||!Ae.uploadedImage))try{ts(!0),ct(null);const k=await q(Ae.imagePreview,Ae.croppedAreaPixels),C=new File([k],Ae.uploadedImage.name,{type:"image/jpeg"}),H=await dt(C),F=H.includes(",")?H.split(",")[1]:H,Re=await fetch(yt("/api/faces/validate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image_data:F})}),ze=await Re.json();if(!Re.ok||(ze==null?void 0:ze.status)==="failed"||ze!=null&&ze.error){const We=(ze==null?void 0:ze.message)||(ze==null?void 0:ze.error)||"Face validation failed. Please try again with a clearer, front-facing photo.";ct(We);return}Q(We=>({...We,croppedImage:C,showCropper:!1})),ct(null),Ae.imagePreview&&URL.revokeObjectURL(Ae.imagePreview)}catch(k){console.error("Error cropping/validating new child image:",k),ct("Something went wrong while validating your image. Please try again.")}finally{ts(!1)}},kr=()=>{Ae.imagePreview&&URL.revokeObjectURL(Ae.imagePreview),Q(k=>({...k,croppedImage:null,uploadedImage:null,imagePreview:null,showCropper:!1})),ct(null)},qt=()=>{var k;if(!Ae.croppedImage){alert("Please upload a photo for this child.");return}if(!((k=Ae.name)!=null&&k.trim())){alert("Please enter this child's first name.");return}if(!Ae.age){alert("Please select this child's age.");return}at(C=>[...C,{...Ae}]),Q(ne()),St(!1)},Xt=k=>{at(C=>{const H=C[k];return H.imagePreview&&URL.revokeObjectURL(H.imagePreview),C.filter((F,Re)=>Re!==k)})},Ms=(k,C,H,F)=>e.jsxs("div",{className:"bg-green-50 rounded-2xl shadow-sm border border-green-200 p-4 mb-4 flex items-center gap-4",children:[k.croppedImage&&e.jsx("img",{src:URL.createObjectURL(k.croppedImage),alt:H,className:"w-14 h-14 rounded-full object-cover border-2 border-green-300"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"text-green-700 font-semibold text-sm",children:["✓ ",H]}),e.jsxs("div",{className:"text-gray-700 text-sm",children:[k.name,", Age ",k.age,", ",k.gender]})]}),F&&e.jsx("button",{onClick:F,className:"text-red-500 text-sm font-medium hover:underline",children:"Remove"})]},C),Pl=k=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6 ",children:[e.jsx("div",{className:"w-full px-4 py-4 bg-gray-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"px-2.5 py-1 rounded-full bg-purple-500 text-white text-xs font-bold whitespace-nowrap",children:["Child ",M.length+2]}),e.jsx("h2",{className:"text-lg font-bold text-gray-900",children:"Add Child's Details"})]})}),e.jsxs("div",{className:"p-4 space-y-4",children:[!Ae.showCropper&&!Ae.croppedImage?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-xs mx-auto rounded-lg border border-gray-200"})}),e.jsxs("label",{className:"inline-block",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:xs,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Upload Image ",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]})]}):Ae.showCropper?e.jsxs("div",{className:"rounded-xl overflow-hidden",children:[e.jsx("div",{className:`relative w-full ${k?"h-[400px]":"h-[350px]"}`,children:e.jsx(As,{image:Ae.imagePreview,crop:Ae.crop,zoom:Ae.zoom,aspect:1,onCropChange:C=>Q(H=>({...H,crop:C})),onZoomChange:C=>Q(H=>({...H,zoom:C})),onCropComplete:(C,H)=>Q(F=>({...F,croppedAreaPixels:H})),cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"pt-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Ae.zoom,onChange:C=>Q(H=>({...H,zoom:Number(C.target.value)})),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{Ae.imagePreview&&URL.revokeObjectURL(Ae.imagePreview),Q(C=>({...C,showCropper:!1,imagePreview:null,uploadedImage:null})),ct(null)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:Ps,disabled:$e,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:$e?"Validating...":"Crop & Validate"})]}),et&&e.jsx("p",{className:"text-red-500 text-sm mt-3 text-center",children:et})]})]}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:URL.createObjectURL(Ae.croppedImage),alt:"Cropped preview",className:"w-32 h-32 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-3",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:kr,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"})," Change Image"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"First Name *"}),e.jsx("input",{type:"text",value:Ae.name,onChange:C=>Q(H=>({...H,name:C.target.value})),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:Ae.age,onChange:C=>Q(H=>({...H,age:C.target.value})),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{var H;const C=(H=W==null?void 0:W.ageRange)==null?void 0:H.match(/(\d+)-(\d+)/);if(C){const F=parseInt(C[1]),Re=parseInt(C[2]);return Array.from({length:Re-F+1},(ze,We)=>F+We).map(ze=>e.jsx("option",{value:ze.toString(),children:ze},ze))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(F=>e.jsx("option",{value:F.toString(),children:F},F))})()]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Gender *"}),e.jsxs("select",{value:Ae.gender,onChange:C=>Q(H=>({...H,gender:C.target.value})),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"Boy",children:"Boy"}),e.jsx("option",{value:"Girl",children:"Girl"})]})]})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsx("button",{onClick:()=>{St(!1),kr()},className:"flex-1 px-4 py-2.5 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors text-sm font-medium",children:"Cancel"}),e.jsx("button",{onClick:qt,disabled:!Ae.croppedImage||!Ae.name||!Ae.age,className:"flex-1 px-4 py-2.5 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save Child"})]})]})]}),Qn=p.useRef(null),El=p.useRef(null),Tl=p.useRef(null),Al=p.useRef(null),[er,_r]=p.useState("none"),[Dm,ei]=p.useState(!1),Il=p.useRef(er);p.useEffect(()=>{const C=()=>{const H=Al.current,F=El.current,Re=Tl.current;if(Re){const cs=Re.getBoundingClientRect();if(cs.top<window.innerHeight&&cs.bottom>0){_r("needhelp");return}}if(F&&F.getBoundingClientRect().bottom<0){_r("needhelp");return}if(!H){_r("none");return}const ze=H.getBoundingClientRect(),We=window.innerHeight;if(ze.top>We){_r("sticky");return}if(ze.bottom+20<We){_r("inline");return}_r("none")};return window.addEventListener("scroll",C,{passive:!0}),C(),()=>window.removeEventListener("scroll",C)},[a,W]),p.useEffect(()=>{const k=Il.current;if(Il.current=er,er==="sticky")ei(!1);else if(k==="sticky"){const C=setTimeout(()=>ei(!0),310);return()=>clearTimeout(C)}else er==="inline"&&k!=="sticky"&&ei(!0)},[er]);const Gm=er==="sticky",Um=er==="needhelp",Vm=er==="inline"&&Dm;return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(Yt,{}),e.jsx("div",{className:`fixed bottom-0 left-0 right-0 z-50 md:hidden p-3 bg-white/95 backdrop-blur-sm border-t border-gray-100 shadow-[0_-4px_12px_rgba(0,0,0,0.08)] transition-transform duration-300 ${Gm?"translate-y-0":"translate-y-full"}`,children:e.jsx("button",{onClick:()=>{var k;(k=Qn.current)==null||k.scrollIntoView({behavior:"smooth",block:"center"})},className:"w-full bg-purple-500 hover:bg-purple-600 text-white py-3.5 rounded-full font-semibold text-base shadow-lg transition-colors","data-track":"sticky_personalise_cta",children:"Personalise My Book"})}),Um&&e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20need%20help%20with%20personalizing%20my%20book%21",target:"_blank",rel:"noopener noreferrer",className:`fixed bottom-4 right-4 z-50 md:hidden inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
            px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,"data-track":"personalize_whatsapp_support",children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20need%20help%20with%20personalizing%20my%20book%21",target:"_blank",rel:"noopener noreferrer","aria-label":"24x7 WhatsApp Support",className:`hidden md:inline-flex fixed bottom-4 right-4 z-50 items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
          px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,"data-track":"personalize_whatsapp_support",children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 py-2 sm:py-8",children:[e.jsx("div",{className:"hidden lg:block mb-12",children:e.jsxs("div",{className:"flex items-center justify-between max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-500 text-white rounded-full flex items-center justify-center text-sm font-medium",children:"✓"}),e.jsx("span",{className:"ml-2 text-purple-500 font-medium",children:"Book Details"})]}),e.jsx("div",{className:"flex-1 h-1 bg-purple-200 mx-4",children:e.jsx("div",{className:"h-full bg-purple-500 w-full"})}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-500 text-white rounded-full flex items-center justify-center text-sm font-medium",children:"2"}),e.jsx("span",{className:"ml-2 text-purple-500 font-medium",children:"Personalization"})]}),e.jsx("div",{className:"flex-1 h-1 bg-purple-200 mx-4"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-sm font-medium",children:"3"}),e.jsx("span",{className:"ml-2 text-gray-400 font-medium",children:"Preview"})]}),e.jsx("div",{className:"flex-1 h-1 bg-purple-200 mx-4"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-sm font-medium",children:"4"}),e.jsx("span",{className:"ml-2 text-gray-400 font-medium",children:"Checkout"})]})]})}),e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-1",children:b?"❤️ Special Gift for Him/Her":Xw(W.title)}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-4",children:[e.jsx("div",{className:"flex items-center",children:[1,2,3,4,5].map(k=>e.jsx("svg",{className:"w-4 h-4 text-yellow-400",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})},k))}),e.jsxs("span",{className:"text-sm text-gray-500",children:["(",(Number(r)||1)*37%80+120," reviews)"]})]}),e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"A magical personalised adventure where your child becomes the hero of their very own story!"}),a==="IN"?e.jsxs(e.Fragment,{children:[P?Ke(`${ot}/in/school_of_magic/flipbook.mp4`):_?Ke(`${ot}/in/deep_space_boy/flipbook.mp4`):Ee(),e.jsxs("div",{className:"bg-white rounded-xl p-4 mb-6 shadow-sm border border-gray-100",children:[e.jsx("p",{className:"text-gray-600 text-sm leading-relaxed",children:W.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[W.category_tag&&e.jsx("span",{className:"px-2 py-1 bg-purple-100 text-purple-700 rounded-full text-xs",children:W.category_tag}),e.jsx("span",{className:"px-2 py-1 bg-blue-100 text-blue-700 rounded-full text-xs",children:W.ageRange}),e.jsxs("span",{className:"px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs",children:[W.pages," pages"]})]}),e.jsxs("div",{className:"mt-4 space-y-0.5 md:space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("svg",{className:"w-5 h-5 text-gray-800 flex-shrink-0",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M8 14s1.5 2 4 2 4-2 4-2"}),e.jsx("line",{x1:"9",y1:"9",x2:"9.01",y2:"9",strokeLinecap:"round"}),e.jsx("line",{x1:"15",y1:"9",x2:"15.01",y2:"9",strokeLinecap:"round"})]}),e.jsxs("span",{className:"text-sm text-gray-700",children:["Perfect for kids ages ",W.ageRange]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("svg",{className:"w-5 h-5 text-gray-800 flex-shrink-0",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M9 18V5l12-2v13"}),e.jsx("circle",{cx:"6",cy:"18",r:"3"}),e.jsx("circle",{cx:"18",cy:"16",r:"3"}),e.jsx("path",{strokeLinecap:"round",d:"M12 2v4M12 2L9.5 4M12 2l2.5 2"}),e.jsx("path",{d:"M9 21a3 3 0 1 1 0-6M12 3a1 1 0 0 1 1 1v3a1 1 0 0 1-2 0V4a1 1 0 0 1 1-1z",fill:"none",stroke:"none"}),e.jsx("path",{d:"M12 2v0",stroke:"none"})]}),e.jsxs("span",{className:"text-sm text-gray-700",children:["Teaches ",W.theme==="Learning"?"curiosity, creativity, and early learning":W.theme==="Science & Space"?"scientific curiosity, bravery, and problem-solving":W.theme==="Creativity & Magic"?"imagination, wonder, and self-belief":W.theme==="Creativity & Thriller"?"creativity, determination, and perseverance":W.theme==="Fantasy & Fairytale"?"courage, kindness, and inner strength":W.theme==="Fantasy & Nature"?"calm, wonder, and connection with nature":W.theme==="Family & Love"?"love, gratitude, and family bonds":"resilience, patience, and teamwork"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("svg",{className:"w-5 h-5 text-gray-800 flex-shrink-0",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"}),e.jsx("path",{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"})]}),e.jsxs("span",{className:"text-sm text-gray-700",children:[W.pages," Beautifully illustrated pages"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("svg",{className:"w-5 h-5 text-gray-800 flex-shrink-0",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("circle",{cx:"12",cy:"12",r:"8"}),e.jsx("circle",{cx:"12",cy:"12",r:"1"})]}),e.jsx("span",{className:"text-sm text-gray-700",children:"Preview available before ordering"})]})]}),e.jsxs("p",{ref:Al,className:"mt-4 text-xl font-bold text-gray-900",children:["From ",e.jsx("span",{className:"text-purple-600",children:"₹1149/-"})]}),e.jsx("div",{className:`overflow-hidden transition-all duration-200 md:hidden ${Vm?"max-h-20 opacity-100 mt-4":"max-h-0 opacity-0 mt-0"}`,children:e.jsx("button",{onClick:()=>{var k;return(k=Qn.current)==null?void 0:k.scrollIntoView({behavior:"smooth",block:"center"})},className:"w-full bg-purple-500 hover:bg-purple-600 text-white py-3.5 rounded-full font-semibold text-base shadow-lg transition-colors","data-track":"inline_personalise_cta",children:"Personalise My Book"})})]}),e.jsx("div",{className:"mt-6",children:e.jsx(kl,{})}),e.jsx("div",{className:"mt-6",children:e.jsx("div",{className:"divide-y divide-gray-200",children:Yn.slice(0,4).map((k,C)=>{const H=`personalize-faq-${C}`;return e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"flex items-center justify-between cursor-pointer py-2.5 text-sm font-semibold text-gray-800",children:[e.jsx("span",{className:"pr-2",children:k.question}),e.jsx(Us,{className:"w-4 h-4 text-gray-500 flex-shrink-0 transition-transform group-open:rotate-180"})]}),e.jsx("p",{className:"pb-2.5 text-sm text-gray-600 leading-relaxed",children:k.answer})]},H)})})}),b?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"lg:hidden mb-6",children:[e.jsx("button",{onClick:()=>{Ct(!0),is(Z?2:1)},className:"glow-button w-full bg-gradient-to-r from-purple-600 to-pink-500 text-white py-3.5 px-4 rounded-full font-semibold text-base shadow-xl transition-transform hover:scale-[1.02]","data-track":"mobile_personalize_modal_open","data-book-id":W.id,"data-book-name":W.title,children:"✨ Click here to Personalise"}),Z&&e.jsx("p",{className:"text-center text-green-600 text-sm mt-2 font-medium",children:"✓ Image uploaded - tap to continue"})]}),e.jsxs("div",{className:"hidden lg:block",children:[ge(),Pt()]})]}):e.jsx(e.Fragment,{children:y?be===1?e.jsxs(e.Fragment,{children:[ge(),Vt()]}):e.jsxs(e.Fragment,{children:[mt(),ut(),pt()]}):fs?ye===1?e.jsxs(e.Fragment,{children:[ge(),e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6",children:[e.jsxs("div",{className:`w-full px-4 py-4 flex items-center justify-between ${Z?"bg-gray-50 cursor-pointer hover:bg-gray-100":"bg-gray-100 cursor-not-allowed opacity-70"} transition-colors`,onClick:()=>{Z&&Nt(!zt)},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap ${Z?"bg-purple-500 text-white":"bg-gray-300 text-gray-600"}`,children:"Step 2"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("h2",{className:`text-lg font-bold ${Z?"text-gray-900":"text-gray-500"}`,children:"Birthday Child Details"}),!Z&&e.jsx("span",{className:"text-xs text-gray-500",children:"(Upload image first)"})]})]}),Z&&(zt?e.jsx(qr,{className:"w-5 h-5 text-gray-500"}):e.jsx(Us,{className:"w-5 h-5 text-gray-500"}))]}),zt&&Z&&e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:E,onChange:k=>O(k.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy of the book",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"WhatsApp Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-20 px-2 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 font-medium",children:U}),e.jsx("input",{type:"tel",value:V,onChange:k=>{const C=U==="+65"?8:10;J(k.target.value.replace(/\D/g,"").slice(0,C))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"10 digit number",maxLength:10,required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Child's Name *"}),e.jsx("input",{type:"text",value:u,onChange:k=>d(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Gender *"}),e.jsxs("select",{value:g,onChange:k=>f(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"Boy",children:"Boy"}),e.jsx("option",{value:"Girl",children:"Girl"})]})]})]}),e.jsx("div",{className:"pt-4",children:e.jsx(wt,{onClick:()=>{if(!(u!=null&&u.trim())){alert("Please enter the birthday child's name.");return}if(!h){alert("Please select the birthday child's age.");return}if(!E){alert("Please enter your email address.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){alert("Please enter a valid email address.");return}const k=V==null?void 0:V.trim();if(U==="+91"&&!k){alert("Please enter your WhatsApp number.");return}if(k&&!(U==="+91"?/^[6-9]\d{9}$/:U==="+1"?/^\d{10}$/:/^\d{8}$/).test(k)){alert("Please enter a valid WhatsApp number.");return}tt(2),Nt(!1)},disabled:!Z||!E||!u||!h,className:"w-full py-4 text-lg",children:"Continue →"})})]})]})]}):e.jsxs(e.Fragment,{children:[Ms({croppedImage:Z,name:u,age:h,gender:g},-1,"Birthday Child"),M.map((k,C)=>Ms(k,C,`Child ${C+2}`,()=>Xt(C))),De?Pl():e.jsx("button",{onClick:()=>St(!0),className:"w-full mb-6 py-3 border-2 border-dashed border-purple-300 rounded-2xl text-purple-600 font-medium hover:bg-purple-50 transition-colors",children:"+ Add Another Child"}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6 p-4 space-y-4",children:[e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:ft,onChange:k=>Ze(k.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:["I confirm, I am the parent or legal guardian of these children (or I have the necessary permission), I am over 18, and I consent to providing these details for creating a personalised storybook in accordance with the"," ",e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]}),e.jsx(wt,{onClick:se,disabled:Ge||!Z||!E||!u||!h||!ft||De,className:"w-full py-4 text-lg","data-gtm":"personalize_continue_preview","data-track":"personalize_see_book_preview",children:"See Book Preview"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]}),e.jsx("button",{onClick:()=>{tt(1),Nt(!0)},className:"text-purple-600 text-sm font-medium hover:underline mb-4",children:"← Back to Birthday Child Details"})]}):e.jsxs(e.Fragment,{children:[ge(),Pt()]})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Yw,{book:W}),e.jsx(Jw,{book:W}),e.jsx("div",{children:y?be===1?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-4",children:"Upload a photo of Child 1"}),!Ye&&!Z?e.jsx("div",{className:"border-2 border-dashed border-purple-300 rounded-2xl p-6 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("div",{className:"w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{className:"w-10 h-10 text-purple-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 19 7.5 19s3.332-.523 4.5-1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.523 18.246 19 16.5 19c-1.746 0-3.332-.523-4.5-1.253"})})})}),e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-md mx-auto rounded-lg border border-gray-200"})}),e.jsxs("label",{className:"inline-block","data-gtm":"personalize_choose_image","data-track":"personalize_choose_image",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:L,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Child Image ",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]})}):Ye?e.jsxs("div",{className:"border-2 border-solid border-purple-300 rounded-2xl bg-white overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[450px]",children:e.jsx(As,{image:B,crop:ie,zoom:Qe,aspect:1,onCropChange:He,onZoomChange:lt,onCropComplete:(k,C)=>{we(C)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"p-4 border-t border-gray-200",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Qe,onChange:k=>lt(Number(k.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{Y(!1),st(null),c(null),B&&URL.revokeObjectURL(B)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:oe,disabled:Se,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:Se?"Validating...":"Crop & Continue"}),re&&e.jsx("p",{className:"text-red-500 text-sm mt-2 text-center",children:re})]})]})]}):e.jsx("div",{className:"border-2 border-solid border-purple-300 rounded-2xl p-6 bg-white h-[450px] flex flex-col justify-center items-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-6",children:e.jsx("img",{src:URL.createObjectURL(Z),alt:"Cropped preview",className:"w-48 h-48 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-4",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:G,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"})," Change Image"]})]})}),e.jsxs("div",{className:"space-y-6 mt-8",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:E,onChange:k=>O(k.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy of the book",required:!0})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["WhatsApp Number ",U==="+91"?"*":"(Optional)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-20 px-2 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 font-medium",children:U}),e.jsx("input",{type:"tel",value:V,onChange:k=>{const C=U==="+65"?8:10;J(k.target.value.replace(/\D/g,"").slice(0,C))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:U==="+65"?"8 digit number":"10 digit number",maxLength:U==="+65"?8:10,required:U==="+91"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-semibold text-purple-700 mb-2",children:"Child 1"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"First Name *"}),e.jsx("input",{type:"text",value:u,onChange:k=>d(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Child 1's name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]})]})]}),e.jsx("div",{className:"pt-6",children:e.jsx(wt,{onClick:()=>{if(!(u!=null&&u.trim())){alert("Please enter Child 1's first name.");return}if(!h){alert("Please select Child 1's age.");return}if(!E){alert("Please enter your email address.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){alert("Please enter a valid email address.");return}const k=V==null?void 0:V.trim();if(U==="+91"&&!k){alert("Please enter your WhatsApp number.");return}if(k&&!(U==="+91"?/^[6-9]\d{9}$/:U==="+1"?/^\d{10}$/:/^\d{8}$/).test(k)){alert("Please enter a valid WhatsApp number.");return}ee(2)},disabled:!Z||!E||!u||!h,className:"w-full md:w-auto px-8 py-4 text-lg",children:"Continue to Child 2 →"})})]})]}):e.jsxs(e.Fragment,{children:[mt(),e.jsx("h2",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-4 mt-8",children:"Upload a photo of Child 2"}),!z&&!me?e.jsx("div",{className:"border-2 border-dashed border-purple-300 rounded-2xl p-6 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-md mx-auto rounded-lg border border-gray-200"})}),e.jsxs("label",{className:"inline-block",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:ae,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Upload Image ",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]})}):z?e.jsxs("div",{className:"border-2 border-solid border-purple-300 rounded-2xl bg-white overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[450px]",children:e.jsx(As,{image:Pe,crop:le,zoom:Ve,aspect:1,onCropChange:rt,onZoomChange:Tt,onCropComplete:(k,C)=>{bt.current=C,Bt(C)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"p-4 border-t border-gray-200",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Ve,onChange:k=>Tt(Number(k.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{ce(!1),K(null),Fe(null),Pe&&URL.revokeObjectURL(Pe)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:xe,disabled:fe,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:fe?"Validating...":"Crop & Continue"}),pe&&e.jsx("p",{className:"text-red-500 text-sm mt-2 text-center",children:pe})]})]})]}):e.jsx("div",{className:"border-2 border-solid border-purple-300 rounded-2xl p-6 bg-white h-[450px] flex flex-col justify-center items-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-6",children:e.jsx("img",{src:URL.createObjectURL(me),alt:"Cropped preview - Child 2",className:"w-48 h-48 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-4",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:ve,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"})," Change Image"]})]})}),e.jsxs("div",{className:"space-y-6 mt-8",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-semibold text-purple-700 mb-2",children:"Child 2"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"First Name *"}),e.jsx("input",{type:"text",value:ns,onChange:k=>X(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Child 2's name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:te,onChange:k=>$(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]})]})]}),e.jsx("div",{className:"pt-4",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:ft,onChange:k=>Ze(k.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:["I confirm, I am the parent or legal guardian of this child (or I have the necessary permission from the parent of this child), I am over 18, and I consent to providing these details for creating a personalised storybook in accordance with the"," ",e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsxs("div",{className:"pt-6",children:[e.jsx(wt,{onClick:se,disabled:Ge||!Z||!me||!E||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)||!u||!h||!ns||!te||!ft,className:"w-full md:w-auto px-8 py-4 text-lg","data-gtm":"personalize_continue_preview","data-track":"personalize_see_book_preview",children:"See Book Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center md:justify-start gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]})]})]}):fs?ye===1?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-4",children:"Upload a photo of the birthday child"}),!Ye&&!Z?e.jsx("div",{className:"border-2 border-dashed border-purple-300 rounded-2xl p-6 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("div",{className:"w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{className:"w-10 h-10 text-purple-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 19 7.5 19s3.332-.523 4.5-1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.523 18.246 19 16.5 19c-1.746 0-3.332-.523-4.5-1.253"})})})}),e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-md mx-auto rounded-lg border border-gray-200"})}),e.jsxs("label",{className:"inline-block","data-gtm":"personalize_choose_image","data-track":"personalize_choose_image",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:L,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Child Image ",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]})}):Ye?e.jsxs("div",{className:"border-2 border-solid border-purple-300 rounded-2xl bg-white overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[450px]",children:e.jsx(As,{image:B,crop:ie,zoom:Qe,aspect:1,onCropChange:He,onZoomChange:lt,onCropComplete:(k,C)=>{we(C)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"p-4 border-t border-gray-200",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Qe,onChange:k=>lt(Number(k.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{Y(!1),st(null),c(null),B&&URL.revokeObjectURL(B)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:oe,disabled:Se,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:Se?"Validating...":"Crop & Continue"}),re&&e.jsx("p",{className:"text-red-500 text-sm mt-2 text-center",children:re})]})]})]}):e.jsx("div",{className:"border-2 border-solid border-purple-300 rounded-2xl p-6 bg-white h-[450px] flex flex-col justify-center items-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-6",children:e.jsx("img",{src:URL.createObjectURL(Z),alt:"Cropped preview",className:"w-48 h-48 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-4",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:G,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"})," Change Image"]})]})}),e.jsxs("div",{className:"space-y-6 mt-8",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:E,onChange:k=>O(k.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy of the book",required:!0})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["WhatsApp Number ",U==="+91"?"*":"(Optional)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-20 px-2 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 font-medium",children:U}),e.jsx("input",{type:"tel",value:V,onChange:k=>{const C=U==="+65"?8:10;J(k.target.value.replace(/\D/g,"").slice(0,C))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:U==="+65"?"8 digit number":"10 digit number",maxLength:U==="+65"?8:10,required:U==="+91"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-semibold text-purple-700 mb-2",children:"Birthday Child"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"First Name *"}),e.jsx("input",{type:"text",value:u,onChange:k=>d(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Age *"}),e.jsxs("select",{value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 mb-1",children:"Gender *"}),e.jsxs("select",{value:g,onChange:k=>f(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"Boy",children:"Boy"}),e.jsx("option",{value:"Girl",children:"Girl"})]})]})]})]}),e.jsx("div",{className:"pt-6",children:e.jsx(wt,{onClick:()=>{if(!(u!=null&&u.trim())){alert("Please enter the birthday child's name.");return}if(!h){alert("Please select the birthday child's age.");return}if(!E){alert("Please enter your email address.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){alert("Please enter a valid email address.");return}const k=V==null?void 0:V.trim();if(U==="+91"&&!k){alert("Please enter your WhatsApp number.");return}if(k&&!(U==="+91"?/^[6-9]\d{9}$/:U==="+1"?/^\d{10}$/:/^\d{8}$/).test(k)){alert("Please enter a valid WhatsApp number.");return}tt(2)},disabled:!Z||!E||!u||!h,className:"w-full md:w-auto px-8 py-4 text-lg",children:"Continue →"})})]})]}):e.jsxs(e.Fragment,{children:[Ms({croppedImage:Z,name:u,age:h,gender:g},-1,"Birthday Child"),M.map((k,C)=>Ms(k,C,`Child ${C+2}`,()=>Xt(C))),De?Pl(!0):e.jsx("button",{onClick:()=>St(!0),className:"w-full mb-6 py-3 border-2 border-dashed border-purple-300 rounded-2xl text-purple-600 font-medium hover:bg-purple-50 transition-colors",children:"+ Add Another Child"}),e.jsx("div",{className:"pt-4",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:ft,onChange:k=>Ze(k.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:["I confirm, I am the parent or legal guardian of these children (or I have the necessary permission), I am over 18, and I consent to providing these details for creating a personalised storybook in accordance with the"," ",e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsxs("div",{className:"pt-6",children:[e.jsx(wt,{onClick:se,disabled:Ge||!Z||!E||!u||!h||!ft||De,className:"w-full md:w-auto px-8 py-4 text-lg","data-gtm":"personalize_continue_preview","data-track":"personalize_see_book_preview",children:"See Book Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center md:justify-start gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]}),e.jsx("button",{onClick:()=>{tt(1)},className:"text-purple-600 text-sm font-medium hover:underline mt-4 inline-block",children:"← Back to Birthday Child Details"})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-4",children:"Upload a photo of your child"}),!Ye&&!Z?e.jsx("div",{className:"border-2 border-dashed border-purple-300 rounded-2xl p-6 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("div",{className:"w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{className:"w-10 h-10 text-purple-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 19 7.5 19s3.332-.523 4.5-1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.523 18.246 19 16.5 19c-1.746 0-3.332-.523-4.5-1.253"})})})}),e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo guidelines",className:"w-full max-w-md mx-auto rounded-lg border border-gray-200"})}),e.jsxs("label",{className:"inline-block","data-gtm":"personalize_choose_image","data-track":"personalize_choose_image",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:L,className:"hidden"}),e.jsxs("span",{className:"bg-purple-500 text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-purple-600 transition-colors inline-flex items-center",children:["Child Image ",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]})}):Ye?e.jsxs("div",{className:"border-2 border-solid border-purple-300 rounded-2xl bg-white overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[450px]",children:e.jsx(As,{image:B,crop:ie,zoom:Qe,aspect:1,onCropChange:He,onZoomChange:lt,onCropComplete:(k,C)=>{we(C)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"p-4 border-t border-gray-200",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Qe,onChange:k=>lt(Number(k.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{Y(!1),st(null),c(null),B&&URL.revokeObjectURL(B)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:oe,disabled:Se,className:"px-6 py-2 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:Se?"Validating...":"Crop & Continue"}),re&&e.jsx("p",{className:"text-red-500 text-sm mt-2 text-center",children:re})]})]})]}):e.jsx("div",{className:"border-2 border-solid border-purple-300 rounded-2xl p-6 bg-white h-[450px] flex flex-col justify-center items-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-6",children:e.jsx("img",{src:URL.createObjectURL(Z),alt:"Cropped preview",className:"w-48 h-48 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-4",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:G,className:"text-purple-500 hover:text-purple-600 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"})," Change Image"]})]})}),e.jsxs("div",{className:"space-y-6 mt-8",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:E,onChange:k=>O(k.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy of the book",required:!0})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["WhatsApp Number ",U==="+91"?"*":"(Optional)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-20 px-2 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 font-medium",children:U}),e.jsx("input",{type:"tel",value:V,onChange:k=>{const C=U==="+65"?8:10;J(k.target.value.replace(/\D/g,"").slice(0,C))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:U==="+65"?"8 digit number":"10 digit number",maxLength:U==="+65"?8:10,required:U==="+91"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's first name"}),e.jsx("input",{type:"text",value:u,onChange:k=>d(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Name to be printed on the book"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's age"}),e.jsxs("select",{value:h,onChange:k=>m(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select age"}),(()=>{const k=W.ageRange.match(/(\d+)-(\d+)/);if(k){const C=parseInt(k[1]),H=parseInt(k[2]);return Array.from({length:H-C+1},(F,Re)=>C+Re).map(F=>e.jsx("option",{value:F.toString(),children:F},F))}return[1,2,3,4,5,6,7,8,9,10,11,12].map(C=>e.jsx("option",{value:C.toString(),children:C},C))})()]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's Gender"}),e.jsx("select",{value:g,onChange:k=>f(k.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:(()=>{var F;const k=W.backendName||((F=W.title)==null?void 0:F.toLowerCase())||"",C=k==="fairytale"||k.includes("fairytale"),H=k==="tower_of_time"||k.includes("tower of time");return C?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"Girl",children:"Girl"}),e.jsx("option",{value:"Boy",disabled:!0,children:"This book is only available for Girls"})]}):H?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"Boy",children:"Boy"}),e.jsx("option",{value:"Girl",disabled:!0,children:"This book is only available for Boys"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"Boy",children:"Boy"}),e.jsx("option",{value:"Girl",children:"Girl"})]})})()})]})]}),g==="Girl"&&(()=>{const k=a==="SG"&&(W==null?void 0:W.backendName)==="fairytale_adventure",C=k?[{value:"dark brown hair",label:"Dark brown/black hair",image:`${ot}/sg/brown_hair.jpeg`},{value:"light blonde hair",label:"Light Blonde hair",image:`${ot}/sg/blonde_hair.jpeg`}]:[{value:"wavy hair",label:"Regular wavy hair",image:"/hairstyles/wavy.jpg"},{value:"very short hair",label:"Very short hair",image:"/hairstyles/short.jpg"},{value:"curly hair",label:"Curly hair",image:"/hairstyles/curly.jpg"}];return e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:k?"Choose a hair color that resembles your child the most:":"Choose a hairstyle that resembles your child the most:"}),e.jsx("div",{className:`grid gap-4 ${k?"grid-cols-2":"grid-cols-3"}`,children:C.map(H=>e.jsxs("label",{className:"flex flex-col items-center cursor-pointer group",children:[e.jsxs("div",{className:`relative rounded-lg overflow-hidden border-2 transition-all ${T===H.value?"border-purple-500 shadow-lg ring-2 ring-purple-200":"border-gray-200 group-hover:border-purple-300"}`,children:[e.jsx("img",{src:H.image,alt:H.label,className:"w-full h-24 object-cover"}),e.jsx("input",{type:"radio",name:"hairstyle",value:H.value,checked:T===H.value,onChange:F=>I(F.target.value),className:"absolute top-2 right-2 w-4 h-4 accent-purple-500"})]}),e.jsx("span",{className:"text-xs mt-2 text-center text-gray-600",children:H.label})]},H.value))})]})})(),e.jsx("div",{className:"pt-4",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:ft,onChange:k=>Ze(k.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:[b?e.jsxs(e.Fragment,{children:["I confirm, I am over 18, and I consent to providing these details including the picture of my partner, for creating a personalised storybook, in accordance with the"," "]}):e.jsxs(e.Fragment,{children:["I confirm, I am the parent or legal guardian of this child (or I have the necessary permission from the parent of this child), I am over 18, and I consent to providing these details for creating a personalised storybook in accordance with the"," "]}),e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsxs("div",{className:"pt-6",children:[e.jsx(wt,{onClick:se,disabled:Ge||!Z||!E||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)||!u||!h||!ft,className:"w-full md:w-auto px-8 py-4 text-lg","data-gtm":"personalize_continue_preview","data-track":"personalize_see_book_preview",children:"See Book Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center md:justify-start gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]})]})]})})]}),e.jsx("div",{ref:Tl,children:!b&&e.jsxs("div",{className:"mt-6 pt-6 border-t border-gray-200",children:[e.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-6",children:"You may also like"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:Ot.filter(k=>!k.hidden&&k.id!==W.id).slice(0,6).map(k=>e.jsxs("div",{onClick:()=>t(n(`/books/${k.id}/personalize`)),className:"bg-white rounded-xl overflow-hidden shadow-md hover:shadow-lg transition-shadow cursor-pointer",children:[e.jsx("div",{className:"relative w-full aspect-square",children:e.jsx($s,{imagePath:k.imagePaths[0],alt:k.title,className:"w-full h-full object-cover",loading:"lazy"})}),e.jsxs("div",{className:"p-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[k.category_tag&&e.jsx("span",{className:"px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded-full text-[10px]",children:k.category_tag}),e.jsxs("span",{className:"px-1.5 py-0.5 bg-green-100 text-green-700 rounded-full text-[10px]",children:[k.pages," pages"]}),e.jsx("span",{className:"px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded-full text-[10px]",children:k.ageRange})]}),e.jsx("h4",{className:"text-sm font-semibold text-purple-900 line-clamp-2",children:k.title})]})]},k.id))})]})})]})]}),e.jsx(Po,{isOpen:Ge,error:Me,onRetry:Le}),ke&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",onClick:()=>Ce(!1),children:e.jsxs("div",{className:"relative max-w-2xl w-full",children:[e.jsx("button",{onClick:()=>Ce(!1),className:"absolute -top-10 right-0 text-white hover:text-gray-300 transition-colors","aria-label":"Close guidelines",children:e.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),e.jsx("img",{src:"https://d38picfcqfcfl0.cloudfront.net/website_media/image_guidelines.png",alt:"Photo upload guidelines",className:"w-full h-auto rounded-lg shadow-2xl",onClick:k=>k.stopPropagation()})]})}),b&&a==="IN"&&e.jsx(Zw,{isOpen:Ft,onClose:()=>Ct(!1),currentStep:ss,setCurrentStep:is,croppedImage:Z,imagePreview:B,showCropper:Ye,crop:ie,zoom:Qe,setCrop:He,setZoom:lt,onCropComplete:(k,C)=>{we(C)},handleCropDone:async()=>{await oe()},isValidatingFace:Se,faceValidationError:re,handleImageUpload:L,handleChangeCroppedImage:G,onCancelCrop:()=>{Y(!1),st(null),c(null),B&&URL.revokeObjectURL(B)},email:E,setEmail:O,whatsappNumber:V,setWhatsappNumber:J,childName:u,setChildName:d,childAge:h,setChildAge:m,childGender:g,setChildGender:k=>f(k),hairstylePreference:T,setHairstylePreference:k=>I(k),consentChecked:ft,setConsentChecked:Ze,countryCode:U,handleNext:async()=>{if(!Z){alert("Please upload a photo of your partner.");return}if(!E){alert("Please enter your email address.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)){alert("Please enter a valid email address.");return}const C=V==null?void 0:V.trim();if(U==="+91"&&!C){alert("Please enter your WhatsApp number.");return}if(C){const F=U==="+91"?/^[6-9]\d{9}$/:/^\d{8}$/,Re=U==="+91"?"Please enter a valid 10-digit WhatsApp number starting with 6-9.":"Please enter a valid 8-digit WhatsApp number.";if(!F.test(C)){alert(Re);return}}if(!(u==null?void 0:u.trim())){alert("Please enter your partner's name.");return}if(!h){alert("Please enter your partner's age.");return}Ct(!1),se()},isSubmitting:Ge})]})},Wd=5e3,$m=(r,t=!0)=>{const[s,a]=p.useState(null),[n,i]=p.useState([]),[o,l]=p.useState(!0),[c,u]=p.useState(null),d=p.useRef(null),h=(s==null?void 0:s.status)==="success"&&n.length>0;return p.useEffect(()=>{if(console.log("[usePreviewPolling] Hook initialized - sessionId:",r,"enabled:",t),!r){console.warn("[usePreviewPolling] No sessionId, cannot poll"),l(!1);return}if(!t){console.log("[usePreviewPolling] Polling disabled, will start when enabled");return}const m=async()=>{var g,f,v;try{const x=`${Nl}/api/preview/${r}?t=${Date.now()}`;console.log("[POLLING] 🔄 Polling preview status...");const j=await fetch(x,{cache:"no-store"});if(!j.ok){const y=await j.text();console.error("[POLLING] ❌ API error:",j.status,y),u(`API error: ${j.status}`);return}const b=await j.json();console.log("[POLLING] 📦 Received data:"),console.log("[POLLING]   Status:",b.status),console.log("[POLLING]   Images ready:",((g=b.images)==null?void 0:g.length)||0),console.log("[POLLING]   Images pending:",((f=b.missing_images)==null?void 0:f.length)||0),b.images&&b.images.length>0&&(console.log("[POLLING] 🖼️ Available images:"),b.images.forEach((y,S)=>{const I=/_variant\d+$/.test(y.key)?"🔄 (VARIANT)":"";console.log(`[POLLING]   ${S+1}. ${y.key} ${I} -> ${y.url}`)})),b.missing_images&&b.missing_images.length>0&&console.log("[POLLING] ⏳ Still generating:",b.missing_images.join(", ")),a(b),i(b.images||[]),(b.status==="processing"||b.status==="success")&&u(null),b.status==="failure"&&(console.error("[POLLING] ❌ Generation failed:",b.message),u(b.message||"Generation failed"),l(!1)),b.status==="success"&&(console.log("✅".repeat(15)),console.log("[POLLING] ✅ ALL IMAGES GENERATED SUCCESSFULLY!"),console.log("[POLLING] Duration:",b.duration,"seconds"),console.log("[POLLING] Total images:",((v=b.images)==null?void 0:v.length)||0),console.log("[POLLING] Continue polling for new variants..."),console.log("✅".repeat(15)),l(!1))}catch(x){console.error("[POLLING] ❌ Exception:",x),u("Failed to fetch preview data")}};return console.log("🔄".repeat(15)),console.log("[POLLING] 🚀 POLLING STARTED"),console.log("[POLLING] Session ID:",r),console.log("[POLLING] Polling every",Wd/1e3,"seconds"),console.log("🔄".repeat(15)),m(),d.current&&clearInterval(d.current),d.current=setInterval(m,Wd),()=>{console.log("[usePreviewPolling] Cleaning up polling interval"),d.current&&(clearInterval(d.current),d.current=null)}},[r,t]),{previewData:s,images:n,isLoading:o,isComplete:h,error:c}},yr=r=>r.replace(/\w\S*/g,t=>t.charAt(0).toUpperCase()+t.substring(1).toLowerCase()),Or=(r,t)=>{const s=r.split(",").map(n=>n.trim()).filter(Boolean),a=(t||"").split(",").map(n=>n.trim().toLowerCase()).filter(Boolean);if(s.length===1){const n=yr(s[0]);return{title:`✨ ${n} is now the hero of this adventure!`,subtitle:`Does ${n} look adorable in the story? 😊`,strong:`Show it to someone who loves ${n}`,shareName:n}}else if(s.length===2){const n=yr(s[0]),i=yr(s[1]);return{title:`✨ ${n} and ${i} are now the hero of this adventure!`,subtitle:"Do they look adorable in the story? 😊",strong:`Show it to someone who loves ${n} and ${i}`,shareName:`${n} and ${i}`}}else{const n=yr(s[0]),i=a[0]==="boy"?"his":"her";return{title:`✨ ${n} and ${i} friends are now the hero of this adventure!`,subtitle:"Do they look adorable in the story? 😊",strong:`Show it to someone who loves ${n}`,shareName:n}}},qd=()=>{const{id:r}=Xr(),t=Jt(),s=_t(),{buildLink:a}=ht(),n=new URLSearchParams(t.search),i=n.get("sessionId"),o=n.get("payment_success")==="true",l=i||localStorage.getItem("session_id");p.useEffect(()=>{(async()=>{const w=t.state;if(!l&&(w!=null&&w.orderId)){const{data:P,error:_}=await de.from("orders").select("session_id").eq("order_id",w.orderId).maybeSingle();if(!_&&(P!=null&&P.session_id)){const R=String(P.session_id);try{localStorage.setItem("session_id",R)}catch{}s(t.pathname+`?sessionId=${encodeURIComponent(R)}`,{replace:!0})}}})()},[l,t.state]);const[c,u]=p.useState(o),[d,h]=p.useState(0),[m,g]=p.useState({}),[f,v]=p.useState({}),[x,j]=p.useState({}),[b,y]=p.useState(!1),[S,T]=p.useState(new Set([0])),[I,E]=p.useState(!1),[O,V]=p.useState(0),[J,U]=p.useState(!1),[Ge,Te]=p.useState(""),[Me,_e]=p.useState(!1),[Se,ue]=p.useState(!1),[re,Ne]=p.useState(null),[fe,qe]=p.useState({}),[pe,Xe]=p.useState({}),[ft,Ze]=p.useState("Scanning your child's photo to capture unique features…"),[ke,Ce]=p.useState(!1);p.useState(null);const[B,st]=p.useState(null),[Ye,Y]=p.useState(!1),ie=p.useRef(null),He=p.useRef(!1),Qe=["Scanning your child's photo to capture unique features…","Enhancing lighting, skin tones, and tiny details…","Designing a perfect background to match the story scene…","Adding finishing touches and harmonizing the artwork…","Rendering the magic shortly…"],lt=p.useRef(null),gt=p.useRef([]),we=p.useRef({}),Mt=p.useRef({}),Z=p.useRef(null),he=p.useRef(0),Be=p.useRef(null),[Fe,Pe]=p.useState({}),[K,z]=p.useState({});p.useEffect(()=>{if(!ke)return;const N=w=>{const P=w.target;Be.current&&!Be.current.contains(P)&&Ce(!1)};return document.addEventListener("mousedown",N,!0),document.addEventListener("touchstart",N,!0),()=>{document.removeEventListener("mousedown",N,!0),document.removeEventListener("touchstart",N,!0)}},[ke]),console.log("[PreviewPage SESSION] URL search params:",t.search),console.log("[PreviewPage SESSION] sessionIdFromUrl:",i),console.log("[PreviewPage SESSION] sessionId from localStorage:",localStorage.getItem("session_id")),console.log("[PreviewPage SESSION] Final sessionId:",l),p.useEffect(()=>{i?localStorage.setItem("session_id",i):l&&!i&&s(t.pathname+`?sessionId=${encodeURIComponent(l)}`,{replace:!0})},[l,i,s]),p.useEffect(()=>{if(l){console.log("[SESSION CHANGE] Loading data for session:",l),Pe({}),z({});try{const N=localStorage.getItem(`preview_variants_${l}`);if(N){const w=JSON.parse(N);console.log("[SESSION CHANGE] Loaded variants from localStorage:",Object.keys(w).length,"pages"),Pe(w)}else console.log("[SESSION CHANGE] No saved variants for this session")}catch(N){console.error("[SESSION CHANGE] Error loading variants:",N)}try{const N=localStorage.getItem(`preview_selected_${l}`);if(N){const w=JSON.parse(N);console.log("[SESSION CHANGE] Loaded selected variants from localStorage"),z(w)}}catch(N){console.error("[SESSION CHANGE] Error loading selected variants:",N)}try{const N=localStorage.getItem(`preview_payment_${l}`);N!==null&&(console.log("[SESSION CHANGE] Loaded payment status:",N),y(N==="true"))}catch(N){console.error("[SESSION CHANGE] Error loading payment status:",N)}}},[l]);const{previewData:ce,images:le,isComplete:rt,error:Ve}=$m(l,!0),Tt=Object.values(m).some(Boolean);p.useEffect(()=>{console.log("[POLLING STATE]",rt?"✅ COMPLETE":"🟢 ACTIVE"),console.log("[POLLING STATE] Backend images:",le.length),console.log("[POLLING STATE] Active regenerations:",Tt)},[rt,le.length,Tt]);const It=p.useRef(!1);p.useEffect(()=>{const N=new URLSearchParams(window.location.search),w=N.get("payment_success"),P=N.get("sessionId");if(w!=="true"||!P)return;const _="purchase_fired_"+P;if(sessionStorage.getItem(_))return;(async()=>{try{const A=sessionStorage.getItem("purchase_book_type"),L=sessionStorage.getItem("purchase_book_price"),D=sessionStorage.getItem("purchase_book_name")||"",q=L?Number.parseInt(L,10):NaN;typeof window.fbq=="function"&&A&&Number.isFinite(q)&&(window.fbq("track","Purchase",{value:q,currency:"INR",content_type:"product",num_items:1,...D&&{content_name:D},book_type:A}),sessionStorage.setItem(_,"true"),sessionStorage.removeItem("purchase_book_type"),sessionStorage.removeItem("purchase_book_price"),sessionStorage.removeItem("purchase_book_name"))}catch{}})()},[]);const Bt=jt.useRef({}),bt=jt.useRef({}),me=jt.useRef({}),Zt=N=>N.get("ETag")||N.get("Last-Modified")||N.get("Content-Length")||"",ns=async N=>{const w=Q[N];if(!w||!m[N])return;const P=Bt.current[N];P&&(clearInterval(P),delete Bt.current[N]);try{const L=await fetch(w,{method:"HEAD",cache:"no-store"});bt.current[N]=Zt(L.headers)||""}catch(L){console.warn("[REGENERATE] Initial HEAD failed",L);return}let _=0;const R=5,A=window.setInterval(async()=>{if(_++,_>=R||!m[N]){clearInterval(A),delete Bt.current[N];return}try{const L=await fetch(w,{method:"HEAD",cache:"no-store"}),D=Zt(L.headers)||"",q=bt.current[N];D&&q&&D!==q&&(console.log("[REGENERATE] Detected image content change for page",N),bt.current[N]=D,j(oe=>({...oe,[N]:Date.now()})),g(oe=>({...oe,[N]:!1})),clearInterval(A),delete Bt.current[N])}catch(L){console.warn("[REGENERATE] HEAD poll failed",L)}},2e3);Bt.current[N]=A};p.useEffect(()=>()=>{Object.values(Bt.current).forEach(clearInterval),Bt.current={}},[]);const X=t.state;let te=X==null?void 0:X.book;const[$,be]=p.useState(null),[ee,ne]=p.useState(!(X!=null&&X.book)&&!!l),[M,at]=p.useState(null);if(p.useEffect(()=>{(async()=>{try{if(console.log("[PreviewPage INIT] Starting loadBookFromSession with sessionId:",l),console.log("[PreviewPage INIT] book from location.state:",te),!l){console.warn("[PreviewPage INIT] No sessionId found, cannot load book"),ne(!1);return}ne(!0),console.log("[PreviewPage INIT] Querying sessions table for sessionId:",l);const{data:w,error:P}=await de.from("sessions").select("book_name, child_name, age, gender, age_group, latest_face_key, email_id").eq("session_id",l).maybeSingle();if(console.log("[PreviewPage INIT] Sessions query result:",{data:w,error:P}),P){console.error("[PreviewPage INIT] sessions lookup failed:",P.message),ne(!1);return}if(!w){console.warn("[PreviewPage INIT] No session data from RLS-protected query, trying Edge Function fallback...");try{const{data:_,error:R}=await de.functions.invoke("get-session-meta",{body:{session_id:l}});if(R||!_){console.error("[PreviewPage INIT] Edge Function fallback failed:",R),ne(!1);return}if(console.log("[PreviewPage INIT] Edge Function fallback successful:",_),typeof _.age=="number"&&(at({name:_.child_name||"",age:_.age,latest_face_key:_.latest_face_key||void 0,gender:_.gender||void 0,email_id:_.email_id||void 0}),console.log("[PreviewPage] Stored child data from fallback:",{name:_.child_name||"",age:_.age,latest_face_key:_.latest_face_key,gender:_.gender})),!te&&(_!=null&&_.book_name)){console.log("[PreviewPage INIT] Resolving book from fallback data:",_.book_name);const A=_.book_name.toLowerCase(),L=Ot.filter(q=>{var oe;return((oe=q.backendName)==null?void 0:oe.toLowerCase())===A});let D=L[0]||Ot.find(q=>q.title.toLowerCase()===A)||Ot.find(q=>q.title===_.book_name);if(L.length>1&&_.gender){const q=(_.gender||"").toLowerCase(),oe=L.find(G=>G.suitableFor.toLowerCase().includes(q));oe&&(D=oe)}D?(console.log("[PreviewPage INIT] Book resolved from fallback:",D.title),be(D),console.log("[PreviewPage] Clearing stale generation locks"),me.current={},g({})):console.warn("[PreviewPage INIT] Could not resolve book from fallback data")}ne(!1);return}catch(_){console.error("[PreviewPage INIT] Exception in Edge Function fallback:",_),ne(!1);return}}if(typeof w.age=="number"&&(at({name:w.child_name||"",age:w.age,latest_face_key:w.latest_face_key||void 0,gender:w.gender||void 0,email_id:w.email_id||void 0}),console.log("[PreviewPage] Stored child data for payment:",{name:w.child_name||"",age:w.age,latest_face_key:w.latest_face_key,gender:w.gender})),!te&&(w!=null&&w.book_name)){console.log("[PreviewPage INIT] Found book_name:",w.book_name),console.log("[PreviewPage INIT] Available bookSamples:",Ot.map(L=>L.title));const _=w.book_name.toLowerCase(),R=Ot.filter(L=>{var D;return((D=L.backendName)==null?void 0:D.toLowerCase())===_});let A=R[0]||Ot.find(L=>L.title.toLowerCase()===_)||Ot.find(L=>L.title===w.book_name);if(R.length>1&&w.gender){const L=(w.gender||"").toLowerCase(),D=R.find(q=>q.suitableFor.toLowerCase().includes(L));D&&(A=D)}A?(console.log("[PreviewPage INIT] Successfully matched book:",{title:A.title,backendName:A.backendName}),be(A)):console.error("[PreviewPage INIT] Could not match book_name to local catalog:",w.book_name)}else te?console.log("[PreviewPage INIT] Book already exists from location.state, skipping book resolution"):console.error("[PreviewPage INIT] Session data has no book_name");ne(!1)}catch(w){console.error("[PreviewPage INIT] Error loading book from session:",w),ne(!1)}})()},[l]),!te&&$&&(te=$),console.log("[PreviewPage RENDER CHECK] Final render check:",{isLoadingSession:ee,hasBook:!!te,bookTitle:te==null?void 0:te.title,sessionId:l,bookFromSession:!!$}),!te&&r){const N=parseInt(r);if(!isNaN(N))te=Ot.find(w=>w.id===N);else{const w=decodeURIComponent(r);te=Ot.find(P=>P.title===w)}}p.useEffect(()=>{if(!It.current&&le.length>=4&&!b&&(te!=null&&te.title)){It.current=!0;const N=te.title,w=te.category_tag||void 0;console.log("[META PIXEL] Firing Lead + PreviewGenerated for:",N),vw(N,w,l||void 0)}},[le.length,b,te==null?void 0:te.title,te==null?void 0:te.category_tag,l]);const ye=te?te.category_tag==="return_gift_books"&&(M!=null&&M.name)?10+2*M.name.split(",").filter(w=>w.trim()).length:te.pages:0;p.useEffect(()=>{if(He.current||ee||window.innerWidth>=1024)return;const N=window.setTimeout(()=>{ie.current&&!He.current&&(He.current=!0,ie.current.scrollIntoView({block:"start"}))},0),w=window.setTimeout(()=>{ie.current&&!He.current&&(He.current=!0,ie.current.scrollIntoView({block:"start"}))},400);return()=>{window.clearTimeout(N),window.clearTimeout(w)}},[ee,ye]);const tt=N=>localStorage.getItem(N)==="true",De=jt.useRef(tt(`preview_checked_${l}`)),St=jt.useRef(tt(`preview_triggered_${l}`)),Ae=jt.useRef(tt(`full_triggered_${l}`));p.useEffect(()=>{(async()=>{if(console.log("=".repeat(60)),console.log("[STAGE CHECK] Starting payment and generation flow"),console.log("[STAGE CHECK] sessionId:",l),console.log("[STAGE CHECK] hasCheckedPayment:",De.current),console.log("[STAGE CHECK] hasPayment:",b),console.log("[STAGE CHECK] hasTriggeredPreviewGen:",St.current),console.log("[STAGE CHECK] hasTriggeredFullGen:",Ae.current),console.log("=".repeat(60)),!l){console.warn("[STAGE CHECK] ❌ No sessionId, cannot proceed");return}let w=!1;if((X==null?void 0:X.paymentCompleted)===!0&&(console.log("[STAGE CHECK] ✅ Payment confirmed via navigation state (from drafts)"),y(!0),localStorage.setItem(`preview_payment_${l}`,"true"),De.current=!0,localStorage.setItem(`preview_checked_${l}`,"true"),w=!0),o&&!b&&!w&&(console.log("[STAGE CHECK] ✅ Payment confirmed via URL parameter"),y(!0),localStorage.setItem(`preview_payment_${l}`,"true"),De.current=!0,localStorage.setItem(`preview_checked_${l}`,"true"),w=!0),w&&console.log("[STAGE CHECK] 🚀 Trusted payment source - proceeding to full generation check"),De.current&&!o&&!w){console.log("[STAGE CHECK] ⏭️ Payment already checked, skipping");return}!b&&!w&&console.log("[STAGE CHECK] 🔄 Checking payment status");let P=w;if(!w){console.log("[PAYMENT CHECK] 🔍 Checking orders table for session_id...");try{const{data:_,error:R}=await de.from("orders").select("order_id, payment_status").eq("session_id",l).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(console.log("[PAYMENT CHECK] Orders query result:",{found:!!_,orderId:_==null?void 0:_.order_id,orderPaymentStatus:_==null?void 0:_.payment_status,error:R==null?void 0:R.message}),!R&&_){if(_.payment_status==="failed"||_.payment_status==="pending"){console.log("[PAYMENT CHECK] 🚫 Payment failed or still pending - forcing free preview mode"),y(!1),localStorage.setItem(`preview_payment_${l}`,"false"),De.current=!0,localStorage.setItem(`preview_checked_${l}`,"true");return}console.log("[PAYMENT CHECK] 📝 Order found! Checking payment_info table...");const{data:A,error:L}=await de.from("payment_info").select("payment_status").eq("order_id",_.order_id).maybeSingle();console.log("[PAYMENT CHECK] Payment info result:",{status:A==null?void 0:A.payment_status,error:L==null?void 0:L.message}),!L&&A&&A.payment_status==="Completed"?(console.log("✅".repeat(20)),console.log("[PAYMENT CHECK] ✅ PAYMENT COMPLETED!"),console.log("[PAYMENT CHECK] User has full access to all pages"),console.log("✅".repeat(20)),y(!0),localStorage.setItem(`preview_payment_${l}`,"true"),De.current=!0,localStorage.setItem(`preview_checked_${l}`,"true"),P=!0):(console.log("[PAYMENT CHECK] ⚠️ Payment not completed - user gets free preview only"),y(!1),localStorage.setItem(`preview_payment_${l}`,"false"))}else console.log("[PAYMENT CHECK] ⚠️ No order found for this session - free preview mode"),y(!1),localStorage.setItem(`preview_payment_${l}`,"false")}catch(_){console.error("[PAYMENT CHECK] ❌ Error checking payment status:",_)}if(!P&&(X!=null&&X.orderId)){console.log("[PAYMENT CHECK] 🔄 Fallback: Checking by orderId:",X.orderId);try{const{data:_,error:R}=await de.from("payment_info").select("payment_status").eq("order_id",X.orderId).maybeSingle();console.log("[PAYMENT CHECK] Fallback result:",{status:_==null?void 0:_.payment_status,error:R==null?void 0:R.message}),!R&&(_==null?void 0:_.payment_status)==="Completed"&&(console.log("[PAYMENT CHECK] ✅ Payment found via fallback orderId"),y(!0),localStorage.setItem(`preview_payment_${l}`,"true"),De.current=!0,localStorage.setItem(`preview_checked_${l}`,"true"),P=!0)}catch(_){console.error("[PAYMENT CHECK] ❌ Fallback check error:",_)}}!P&&(X!=null&&X.paymentCompleted)&&(console.log("[PAYMENT CHECK] ✅ Payment flag found from payment success page"),y(!0),localStorage.setItem(`preview_payment_${l}`,"true"),De.current=!0,localStorage.setItem(`preview_checked_${l}`,"true"),P=!0)}if(!P&&l&&!St.current){St.current=!0,localStorage.setItem(`preview_triggered_${l}`,"true"),console.log("🎬".repeat(20)),console.log("[PREVIEW STAGE] 🎬 NO PAYMENT FOUND - STARTING PREVIEW MODE"),console.log("[PREVIEW STAGE] Will generate first 4 pages only"),console.log("[PREVIEW STAGE] Pages: cover, title, page05_face, page05_text"),console.log("🎬".repeat(20)),g({0:!0,1:!0,2:!0,3:!0}),console.log("[PREVIEW STAGE] ⏳ Marked pages as generating - polling should start now");try{console.log("[PREVIEW STAGE] 📡 Sending batch generation request...");const _={session_id:l,regenerate:!1,pages:["05"]};console.log("[PREVIEW STAGE] Request body:",JSON.stringify(_,null,2));const R=await fetch(yt("/api/preview/generate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)});if(console.log("[PREVIEW STAGE] Response status:",R.status),R.ok){const A=await R.json();console.log("[PREVIEW STAGE] ✅ Batch generation started successfully!"),console.log("[PREVIEW STAGE] Response:",JSON.stringify(A,null,2)),console.log("[PREVIEW STAGE] 🔄 Polling will fetch images as they become available...")}else{const A=await R.text();console.error("[PREVIEW STAGE] ❌ Failed to start batch generation"),console.error("[PREVIEW STAGE] Status:",R.status),console.error("[PREVIEW STAGE] Error:",A),g({})}}catch(_){console.error("[PREVIEW STAGE] ❌ Exception during batch generation:",_),g({})}}if(P){console.log("[POST-PAYMENT STAGE] 🔍 Checking database generation status...");try{const{data:_,error:R}=await de.from("sessions").select("text_status, titles_status, preview_status").eq("session_id",l).single();R?console.error("[POST-PAYMENT STAGE] ❌ Error fetching session status:",R):(console.log("[POST-PAYMENT STAGE] 📊 Database statuses:"),console.log("[POST-PAYMENT STAGE]   preview_status:",_==null?void 0:_.preview_status),console.log("[POST-PAYMENT STAGE]   text_status:",_==null?void 0:_.text_status),console.log("[POST-PAYMENT STAGE]   titles_status:",_==null?void 0:_.titles_status));const A=(_==null?void 0:_.text_status)||"idle",L=(_==null?void 0:_.titles_status)||"idle",D=A==="idle"||A==="failed"||L==="idle"||L==="failed",q=Ae.current;if(console.log("[POST-PAYMENT STAGE] 🎯 Generation decision:"),console.log("[POST-PAYMENT STAGE]   Needs generation (DB idle/failed):",D),console.log("[POST-PAYMENT STAGE]   Already triggered (memory):",q),D&&(!q||A==="idle")){console.log("💎".repeat(20)),console.log("[POST-PAYMENT STAGE] 💎 PAYMENT COMPLETED - STARTING FULL BOOK GENERATION"),console.log("[POST-PAYMENT STAGE] Will generate ALL pages for the complete book"),console.log("[POST-PAYMENT STAGE] User has unlimited access to regenerate any page"),console.log("💎".repeat(20));const G=async(se=!1)=>{try{console.log(`[POST-PAYMENT STAGE] 📡 ${se?"RETRYING":"Calling"} /api/preview/generate-full endpoint...`);const Le={session_id:l,regenerate:!1};console.log("[POST-PAYMENT STAGE] Request body:",JSON.stringify(Le,null,2));const Ke=await fetch(yt("/api/preview/generate-full"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Le)});if(console.log("[POST-PAYMENT STAGE] Response status:",Ke.status),Ke.ok){const Ee=await Ke.json();return console.log("[POST-PAYMENT STAGE] ✅ Full book generation workflow started!"),console.log("[POST-PAYMENT STAGE] Response:",JSON.stringify(Ee,null,2)),Ee.message&&Ee.message.includes("started")?(console.log("[POST-PAYMENT STAGE] ✅ Confirmed: Backend has queued generation jobs"),console.log("[POST-PAYMENT STAGE] 🔄 Images will appear progressively as they generate (4-5 min total)"),console.log("[POST-PAYMENT STAGE] 🔄 Existing polling will automatically pick up new images"),!0):(console.warn("[POST-PAYMENT STAGE] ⚠️ Warning: API returned success but unclear if jobs queued"),console.warn("[POST-PAYMENT STAGE] Response structure:",Object.keys(Ee)),!1)}else{const Ee=await Ke.text();return console.error("[POST-PAYMENT STAGE] ❌ Failed to start full generation"),console.error("[POST-PAYMENT STAGE] Status:",Ke.status),console.error("[POST-PAYMENT STAGE] Error:",Ee),!1}}catch(Le){return console.error("[POST-PAYMENT STAGE] ❌ Exception during full book generation:",Le),!1}},ae={};for(let se=0;se<ye;se++)ae[se]=!0;g(ae),console.log("[POST-PAYMENT STAGE] ⏳ Marked all pages as generating - progress tracking enabled");const xe=await G(!1),ve=async()=>{try{const{data:se}=await de.from("sessions").select("text_status, titles_status").eq("session_id",l).single(),Le=(se==null?void 0:se.text_status)||"idle",Ke=(se==null?void 0:se.titles_status)||"idle";return console.log("[POST-PAYMENT STAGE] 🔎 Post-trigger status:",{text_status:Le,titles_status:Ke}),Le==="processing"||Le==="completed"||Ke==="processing"||Ke==="completed"}catch(se){return console.warn("[POST-PAYMENT STAGE] ⚠️ Post-trigger status check failed:",se),!1}};let dt=!1;if(xe&&(await new Promise(se=>setTimeout(se,1500)),dt=await ve()),dt)Ae.current=!0,localStorage.setItem(`full_triggered_${l}`,"true"),console.log("[POST-PAYMENT STAGE] ✅ Confirmed generation started via DB status; flag set");else{console.log("[POST-PAYMENT STAGE] 🔁 No progress detected, retrying in 2 seconds..."),await new Promise(Ke=>setTimeout(Ke,2e3));const se=await G(!0);let Le=!1;se&&(await new Promise(Ke=>setTimeout(Ke,1500)),Le=await ve()),Le?(Ae.current=!0,localStorage.setItem(`full_triggered_${l}`,"true"),console.log("[POST-PAYMENT STAGE] ✅ Progress detected after retry; flag set")):(console.error("[POST-PAYMENT STAGE] ❌ Still no progress after retry; clearing flag"),localStorage.removeItem(`full_triggered_${l}`),Ae.current=!1)}}else D?console.log("[POST-PAYMENT STAGE] ⏭️ Skipping trigger - already initiated in this session"):console.log("[POST-PAYMENT STAGE] ✅ Generation already in progress or completed (text_status:",A,", titles_status:",L,")")}catch(_){if(console.error("[POST-PAYMENT STAGE] ❌ Database check failed:",_),console.log("[POST-PAYMENT STAGE] ⚠️ Falling back to memory-based trigger check"),!Ae.current){console.log("[POST-PAYMENT STAGE] 📡 Triggering generation (fallback mode)...");try{const R=await fetch(yt("/api/preview/generate-full"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:l,regenerate:!1})});if(R.ok){const A=await R.json();console.log("[POST-PAYMENT STAGE] ✅ Fallback trigger succeeded:",A),Ae.current=!0,localStorage.setItem(`full_triggered_${l}`,"true")}}catch(R){console.error("[POST-PAYMENT STAGE] ❌ Fallback trigger failed:",R)}}}}De.current=!0,localStorage.setItem(`preview_checked_${l}`,"true"),console.log("=".repeat(60)),console.log("[STAGE CHECK] ✅ Payment check complete"),console.log("[STAGE CHECK] Payment found:",P),console.log("[STAGE CHECK] Preview generation triggered:",St.current),console.log("[STAGE CHECK] Full generation triggered:",Ae.current),console.log("=".repeat(60))})()},[l,X==null?void 0:X.paymentCompleted]),p.useEffect(()=>{(async()=>{if(l&&!Ge&&b)try{const{data:w,error:P}=await de.from("orders").select("email_id").eq("session_id",l).order("created_at",{ascending:!1}).limit(1).maybeSingle();w&&!P&&(Te(w.email_id),console.log("[PDF DOWNLOAD] User email loaded:",w.email_id))}catch(w){console.error("[PDF DOWNLOAD] Error fetching user email:",w)}})()},[l,Ge,b]),p.useEffect(()=>{if(te&&b){const N=S.size===ye;E(N)}},[S,te,b,ye]),p.useEffect(()=>{Object.keys(m).map(w=>parseInt(w)).filter(w=>m[w]&&!fe[w]).forEach(w=>{if(!we.current[w]){Mt.current[w]||(Mt.current[w]=Date.now());const P=Mt.current[w];Xe(_=>_[w]!==void 0&&_[w]>0?_:{..._,[w]:0}),we.current[w]=setInterval(()=>{const _=Date.now()-P,R=Math.min(95,_/18e4*100);Xe(A=>({...A,[w]:R}))},1e3)}}),Object.keys(we.current).forEach(w=>{const P=parseInt(w);!m[P]&&!fe[P]&&(we.current[P]&&(clearInterval(we.current[P]),delete we.current[P]),delete Mt.current[P])})},[m,fe]),p.useEffect(()=>(m[d]||fe[d]?Z.current||(he.current=0,Ze(Qe[0]),Z.current=setInterval(()=>{he.current=(he.current+1)%Qe.length,Ze(Qe[he.current])},15e3)):Z.current&&(clearInterval(Z.current),Z.current=null,he.current=0,Ze(Qe[0])),()=>{Z.current&&(clearInterval(Z.current),Z.current=null)}),[d,m,fe]),console.log("[PreviewPage RENDER] Rendering preview page for book:",te==null?void 0:te.title),console.log("[IMAGE MAPPING] Total backendImages count:",le.length),console.log("[IMAGE MAPPING] Full backendImages array:",JSON.stringify(le,null,2));const Q=[],$e={};p.useEffect(()=>{if(!le||le.length===0)return;console.log("[VARIANTS] Processing backend images for variants...");const N={};le.forEach(P=>{const _=P.key.match(/^((?:page\d{2}|cover)_face)(?:_variant(\d+))?$/);if(_){const R=_[1],A=_[2]?parseInt(_[2]):1;N[R]||(N[R]=[]),N[R].push({key:P.key,url:P.url,variantNum:A}),console.log("[VARIANTS] Found variant:",{baseKey:R,variantNum:A,url:P.url})}});const w=[];Pe(P=>{const _={...P};return Object.keys($e).forEach(R=>{var D;const A=parseInt(R),L=$e[A];if(L&&N[L]){const q=N[L],oe=P[A]||[],G=new Set(oe.map(se=>se.variantKey)),ae=[];q.forEach(se=>{G.has(se.key)||(ae.push({key:se.key,url:se.url}),console.log("[VARIANTS] NEW variant detected:",se.key,"for page",A))});const xe=[...oe],ve=fe[A];let dt=-1;if(ve&&typeof ve.expectedVariantIndex=="number"&&((D=xe[ve.expectedVariantIndex])==null?void 0:D.url)==="GENERATING"&&ae.length>0){const se=ae.shift();xe[ve.expectedVariantIndex]={url:se.url,timestamp:Date.now(),variantKey:se.key},dt=ve.expectedVariantIndex,w.push(A),console.log("[VARIANTS] Replaced placeholder at expected index",dt,"for page",A)}else if(ae.length>0){const se=xe.findIndex(Le=>Le.url==="GENERATING");if(se!==-1){const Le=ae.shift();xe[se]={url:Le.url,timestamp:Date.now(),variantKey:Le.key},dt=se,w.push(A),console.log("[VARIANTS] 🔄 REFRESH RECOVERY: Replaced GENERATING placeholder at index",se,"for page",A)}}if(ae.length>0){const se=ae.length;if(xe.push(...ae.map(Le=>({url:Le.url,timestamp:Date.now(),variantKey:Le.key}))),console.log("[VARIANTS] Appended",se,"new variant(s) to page",A),m[A]||fe[A]){const Le=xe.length-1;console.log("[VARIANTS] Page",A,"is regenerating, auto-selecting newest variant at index",Le),setTimeout(()=>{z(Ke=>({...Ke,[A]:Le}))},0)}}oe.length>0||xe.length>0?_[A]=xe:(q.sort((se,Le)=>se.variantNum-Le.variantNum),_[A]=q.map(se=>({url:se.url,timestamp:Date.now(),variantKey:se.key}))),console.log("[VARIANTS] Page",A,"now has",_[A].length,"total variants")}}),_}),w.length>0&&w.forEach(P=>{var R;g(A=>({...A,[P]:!1})),qe(A=>{const L={...A};return delete L[P],L}),Xe(A=>({...A,[P]:100})),we.current[P]&&(clearInterval(we.current[P]),delete we.current[P]);const _=((R=fe[P])==null?void 0:R.expectedVariantIndex)??0;z(A=>({...A,[P]:_})),console.log("[VARIANTS] Replaced placeholder for page",P,"at variant index",_),j(A=>({...A,[P]:Date.now()})),v(A=>{var L;return{...A,[P]:((L=Fe[P])==null?void 0:L.length)||0}}),me.current[P]=!1}),Pe(P=>(Object.keys(P).forEach(_=>{const R=parseInt(_);if(m[R]||fe[R]){const A=P[R];A&&A.length>0&&A[A.length-1].url!=="GENERATING"&&(console.log("[VARIANTS] Cleanup: Clearing regenerating state for page",R),g(L=>({...L,[R]:!1})),qe(L=>{const D={...L};return delete D[R],D}),Xe(L=>({...L,[R]:100})),we.current[R]&&(clearInterval(we.current[R]),delete we.current[R]),me.current[R]=!1)}}),P))},[le,$e]),p.useEffect(()=>{l&&Object.keys(Fe).length>0&&localStorage.setItem(`preview_variants_${l}`,JSON.stringify(Fe))},[Fe,l]),p.useEffect(()=>{l&&Object.keys(K).length>0&&localStorage.setItem(`preview_selected_${l}`,JSON.stringify(K))},[K,l]);const ts=(N,w)=>N==="alphabet_adventure"&&!w?["cover_face","title","page05_face","page06_face","page07_face","page08_face"]:N==="valentines"&&!w?["cover_face","title","page05_face","page05_text"]:w?[]:["cover_face","title","page05_face","page05_text","page06_face","page06_text"];if(b){console.log("[PAID MAPPING] Mapping all pages..."),console.log("[PAID MAPPING] backendImages count:",le.length),console.log("[PAID MAPPING] backendImages keys:",le.map(G=>G.key).join(", "));const N=le.some(G=>G.key==="cover_face"||G.key==="front"),w=le.some(G=>G.key==="title"),P=le.some(G=>G.key==="back"||G.key==="back_cover"),_=le.some(G=>G.key==="bridge_page"),R=Math.max(0,ye-1),A=Math.max(0,ye-2);if(N){const G=le.find(ae=>ae.key==="cover_face"||ae.key==="front");Q[0]=G.url,$e[0]=G.key,console.log("[PAID MAPPING] Mapped cover at index 0:",G.key)}if(w){const G=le.find(ae=>ae.key==="title");Q[1]=G.url,$e[1]=G.key,console.log("[PAID MAPPING] Mapped title at index 1:",G.key)}const L=new Set;le.forEach(G=>{const ae=(G.key||"").match(/page(\d{2})_(face|text)/);ae&&L.add(parseInt(ae[1],10))});const D=Array.from(L).sort((G,ae)=>G-ae);console.log("[PAID MAPPING] Page numbers found:",D.join(", "));const q=_?A-1:P?R-1:R;let oe=2;if(D.forEach(G=>{const ae=G.toString().padStart(2,"0"),xe=`page${ae}_face`,ve=`page${ae}_text`,dt=le.find(se=>se.key===xe);if(oe<=q&&(dt?(Q[oe]=dt.url,console.log("[PAID MAPPING] Mapped",xe,"at index",oe)):console.log("[PAID MAPPING] Reserved index",oe,"for",xe,"(not ready yet)"),$e[oe]=xe,oe++),(te==null?void 0:te.backendName)!=="alphabet_adventure"){const se=le.find(Le=>Le.key===ve);oe<=q&&(se?(Q[oe]=se.url,console.log("[PAID MAPPING] Mapped",ve,"at index",oe)):console.log("[PAID MAPPING] Reserved index",oe,"for",ve,"(not ready yet)"),$e[oe]=ve,oe++)}}),_){const G=le.find(ae=>ae.key==="bridge_page");Q[A]=G.url,$e[A]="bridge_page",console.log("[PAID MAPPING] Mapped bridge_page at index",A)}if(P){const G=le.find(ae=>ae.key==="back"||ae.key==="back_cover");Q[R]=G.url,$e[R]=G.key,console.log("[PAID MAPPING] Mapped back_cover at index",R)}console.log("[PAID MAPPING] Complete - mapped",Q.filter(Boolean).length,"images")}else{const N=ts((te==null?void 0:te.backendName)||"",b);console.log("[NEW PREVIEW MAPPING] Starting sequential mapping for preview..."),N.forEach((w,P)=>{$e[P]=w;const _=le.find(R=>R.key===w);_?(Q[P]=_.url,console.log(`[NEW PREVIEW MAPPING] Preview index ${P}: ${w} -> ${_.url}`)):console.log(`[NEW PREVIEW MAPPING] Preview index ${P}: ${w} -> NOT FOUND (reserved)`)}),console.log("[NEW PREVIEW MAPPING] Sequential mapping complete")}console.log("[IMAGE MAPPING] Final pageImages array length:",Q.length),console.log("[IMAGE MAPPING] Final pageImages:",Q),console.log("[IMAGE MAPPING] indexToKeyMap:",$e);const et=N=>b?!0:N>=0&&N<=3,ct=N=>{const w=$e[N],P=w&&w.includes("_face");if(b){if(P){const A=Q[N];return A&&(A.includes("_face")||A.includes("/face/"))?"backend":(ce==null?void 0:ce.status)==="failure"?"failed":"generating"}const R=is(N);return Q[N]||R!==null&&Q[R]?"backend":(ce==null?void 0:ce.status)==="failure"?"failed":"generating"}if(!et(N))return"locked";if(P){const R=Q[N];return R&&(R.includes("_face")||R.includes("/face/"))?"backend":(ce==null?void 0:ce.status)==="failure"?"failed":"generating"}const _=is(N);return Q[N]||_!==null&&Q[_]?"backend":(ce==null?void 0:ce.status)==="failure"?"failed":"generating"};p.useEffect(()=>{if(!(!te||ye===0)){for(let N=0;N<ye;N++){if(we.current[N]||Q[N]||!b&&N>3)continue;Mt.current[N]||(Mt.current[N]=Date.now());const w=Mt.current[N];Xe(P=>P[N]!==void 0&&P[N]>0?P:{...P,[N]:0}),we.current[N]=setInterval(()=>{const P=Date.now()-w,_=Math.min(95,P/18e4*100);Xe(R=>({...R,[N]:_}))},1e3)}Object.keys(we.current).forEach(N=>{const w=parseInt(N);Q[w]&&!m[w]&&!fe[w]&&(clearInterval(we.current[w]),delete we.current[w],delete Mt.current[w])})}},[te,ye,Q,b,m,fe]);const{region:zt}=ht(),Nt=(N,w)=>{const _=["front",...Array.from({length:ye-2},(oe,G)=>(G+1).toString()),"back"][N],R=te.imagePaths[0].split("/")[1],A=te.imagePaths[0].split(".").pop()||"jpeg",D=(te.imagePaths[te.imagePaths.length-1]||te.imagePaths[0]).split(".").pop()||"jpeg";let q;if(_==="front")q=`/${R}/front.${A}`;else if(_==="back")q=`/${R}/back.${D}`;else{const G=parseInt(_).toString().padStart(2,"0");q=`/${R}/Story_Images/page${G}.${w}`}return Rn(q,zt)},Ft=N=>{var L,D;if(!te)return[];let w=((L=te.imagePaths[0])==null?void 0:L.split("/")[1])||"",P=!1;if((te.id===101||te.id===102)&&(w=(((D=te.imagePaths[0])==null?void 0:D.split("/"))||[])[2]||(te.id===102?"boy_coupleBook":"girl_coupleBook"),P=!0),te.id===9){const q=N.toString().padStart(2,"0");return[`/boy_superhero/Story_Images/page${q}.jpg`,`/boy_superhero/Story_Images/page${q}.png`,`/boy_superhero/Story_Images/page${q}.jpeg`].map(G=>fa(G))}if(te.id===15||te.id===22){const q=N.toString().padStart(2,"0");return[`/school_of_magic/Story_Images/page${q}.jpg`,`/school_of_magic/Story_Images/page${q}.png`,`/school_of_magic/Story_Images/page${q}.jpeg`].map(G=>fa(G))}if(te.id===16){const q=N.toString().padStart(2,"0");return[`/deep_space_boy/Story_Images/page${q}.jpg`,`/deep_space_boy/Story_Images/page${q}.png`,`/deep_space_boy/Story_Images/page${q}.jpeg`].map(G=>fa(G))}const _=N,R=_.toString().padStart(2,"0");return[`/${w}/Story_Images/page${R}.jpg`,`/${w}/Story_Images/page${R}.png`,`/${w}/Story_Images/page${R}.jpeg`,`/${w}/${_}.jpg`,`/${w}/${_}.png`,`/${w}/${_}.jpeg`,`/${w}/page${R}.jpg`,`/${w}/page${R}.png`].map(q=>P?fa(q):Rn(q,zt))},Ct=N=>Ft(N)[0]||Nt(N,"jpg"),ss=N=>{const w=N.target,P=w.getAttribute("data-page-index");if(!P){console.error("[Image Fallback] No page index found on image");return}const _=parseInt(P),R=Ft(_),L=parseInt(w.getAttribute("data-fallback-index")||"0")+1;L<R.length?(console.log(`[Image Fallback] Page ${_}: Trying candidate ${L+1}/${R.length}:`,R[L]),w.setAttribute("data-fallback-index",L.toString()),w.src=R[L]):console.error(`[Image Fallback] Page ${_}: All ${R.length} candidates failed:`,R)},is=N=>N<2?null:N%2===0?N+1:N-1;p.useEffect(()=>{const N=w=>{if(w.key==="ArrowLeft")h(P=>Math.max(0,P-1));else if(w.key==="ArrowRight"){const P=d+1;P<ye&&(h(P),b&&T(_=>new Set([..._,P])))}};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[d,ye,b]),p.useEffect(()=>{Object.keys(m).forEach(N=>{const w=parseInt(N);if(m[w]){const _=(Fe[w]||[]).length,R=f[w]?typeof f[w]=="number"?f[w]:1:0;if(_>R){console.log("[REGENERATE] New variant detected for page",w,"- variant count increased from",R,"to",_),z(L=>({...L,[w]:_-1})),g(L=>({...L,[w]:!1})),v(L=>({...L,[w]:_})),j(L=>({...L,[w]:Date.now()})),me.current[w]=!1;const A=is(w);A!==null&&m[A]&&(g(L=>({...L,[A]:!1})),j(L=>({...L,[A]:Date.now()})))}}})},[Fe,m,f]),p.useEffect(()=>{!le||le.length===0||Object.keys(m).forEach(N=>{const w=parseInt(N);if(m[w]){const P=Q[w],_=!f[w];if(P&&_){console.log("[NEW PAGE] New page detected at index",w,P),g(A=>({...A,[w]:!1})),qe(A=>{const L={...A};return delete L[w],L}),Xe(A=>({...A,[w]:100})),we.current[w]&&(clearInterval(we.current[w]),delete we.current[w]),v(A=>({...A,[w]:P})),j(A=>({...A,[w]:Date.now()}));const R=is(w);R!==null&&m[R]&&(g(A=>({...A,[R]:!1})),v(A=>({...A,[R]:Q[R]||P})),j(A=>({...A,[R]:Date.now()})))}}})},[le,Q,m,f]);const aa=(N,w)=>{if(!N)return N;const P=x[w];if(!P)return N;const _=N.includes("?")?"&":"?";return`${N}${_}t=${P}`},Wt=N=>{console.log("[REGENERATE] Image loaded for page",N),g(P=>({...P,[N]:!1})),delete Mt.current[N];const w=pe[N]||0;if(w>0&&w<100){const P=Date.now(),_=1500,R=w,A=setInterval(()=>{const L=Date.now()-P,D=Math.min(L/_,1),q=R+(100-R)*D;Xe(oe=>({...oe,[N]:q})),D>=1&&(clearInterval(A),setTimeout(()=>{Xe(oe=>{const G={...oe};return delete G[N],G})},500))},50)}},W=async N=>{if(console.log("[REGENERATE-DEBUG] Button clicked for page:",N),console.log("[REGENERATE-DEBUG] generationLock:",me.current[N]),console.log("[REGENERATE-DEBUG] regeneratingPages:",m[N]),console.log("[REGENERATE-DEBUG] sessionId:",l),console.log("[REGENERATE-DEBUG] indexToKeyMap:",$e),me.current[N]){console.error("[REGENERATE-DEBUG] ❌ BLOCKED by generation lock"),alert("This page is already being regenerated. Please wait.");return}const w=$e[N];if(!w||!w.includes("_face")){alert("Variants are only available for face pages");return}const P=Fe[N]||[];if(P.length>=7){alert("Maximum 7 variants reached for this page");return}if(me.current[N]=!0,!l){alert("No session ID found"),me.current[N]=!1;return}console.log("[REGENERATE] Starting regeneration for pageIndex:",N);const _=$e[N];if(console.log("[REGENERATE] Image key from indexToKeyMap:",_),!_){console.error("[REGENERATE] Image key not found for pageIndex:",N),alert("Image key not found"),me.current[N]=!1;return}const R=_.match(/page(\d{2})/),A=_.toLowerCase().includes("cover");if(!R&&!A){console.error("[REGENERATE] Invalid page key format:",_),alert("Invalid page key format"),me.current[N]=!1;return}const L=R?R[1]:_;console.log("[REGENERATE] Extracted page key:",L);const D=P.length,q={url:"GENERATING",timestamp:Date.now(),variantKey:`${_}_variant_${D}_generating`};Pe(G=>({...G,[N]:[...P,q]})),z(G=>({...G,[N]:D})),v(G=>({...G,[N]:P.length})),g(G=>({...G,[N]:!0}));const oe=Date.now();qe(G=>({...G,[N]:{startTime:oe,expectedVariantIndex:D}})),Xe(G=>({...G,[N]:0})),we.current[N]&&clearInterval(we.current[N]),we.current[N]=setInterval(()=>{const G=Date.now()-oe,ae=Math.min(95,G/18e4*100);Xe(xe=>({...xe,[N]:ae}))},1e3),ns(N);try{const G=l;if(console.log("[REGENERATE] Using sessionId from state:",G),!G)throw new Error("No session_id found - cannot regenerate variant");const ae={session_id:G,page:L};console.log("[REGENERATE] Sending request to /api/preview/variant with session_id:",G,ae);const xe=await fetch(yt("/api/preview/variant"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ae)});if(!xe.ok)throw new Error("Variant request failed");const ve=await xe.json();if(!ve.status||ve.status!=="started"){g(se=>({...se,[N]:!1})),me.current[N]=!1,alert(ve.message||"Failed to start variant generation");return}console.log("[REGENERATE] Variant generation started, will add as new variant"),(async()=>{var Ke;const se=`${_}_variant${D+1}`,Le=["jpg","jpeg","png","webp"];console.log("[PROBE] Starting HEAD probe for variant:",se);for(let Ee=0;Ee<36;Ee++){await new Promise(ge=>setTimeout(ge,5e3));for(const ge of Le){const ut=`https://talesberry-s3-bucket.s3.ap-southeast-2.amazonaws.com/${G}/preview/${se}.${ge}`;try{if((await fetch(ut,{method:"HEAD",cache:"no-store"})).ok){console.log("[PROBE] ✅ Found variant file:",ut);const Vt=((Ke=ut.split("/").pop())==null?void 0:Ke.replace(/\.[^.]+$/,""))||se;Pe(pt=>{var xs;const Pt=[...pt[N]||[]];return((xs=Pt[D])==null?void 0:xs.url)==="GENERATING"&&(Pt[D]={url:ut,timestamp:Date.now(),variantKey:Vt}),{...pt,[N]:Pt}}),g(pt=>({...pt,[N]:!1})),qe(pt=>{const Pt={...pt};return delete Pt[N],Pt}),Xe(pt=>({...pt,[N]:100})),we.current[N]&&(clearInterval(we.current[N]),delete we.current[N]),me.current[N]=!1;return}}catch{}}console.log(`[PROBE] Attempt ${Ee+1}/36: Variant not found yet, retrying...`)}console.error("[PROBE] ❌ Variant file not found after 3 minutes"),g(Ee=>({...Ee,[N]:!1})),qe(Ee=>{const ge={...Ee};return delete ge[N],ge}),we.current[N]&&(clearInterval(we.current[N]),delete we.current[N]),me.current[N]=!1})().catch(se=>console.error("[PROBE] Error in probe:",se))}catch(G){console.error("Regenerate error:",G),g(ae=>({...ae,[N]:!1})),me.current[N]=!1,alert("Failed to regenerate page")}},fs=async(N,w)=>{console.log("[REGENERATE-NEW-FACE-DEBUG] Button clicked for page:",N),console.log("[REGENERATE-NEW-FACE-DEBUG] generationLock:",me.current[N]),console.log("[REGENERATE-NEW-FACE-DEBUG] file:",w.name);const P=Fe[N]||[];if(P.length>=7){alert("Maximum 7 variants reached for this page");return}if(me.current[N]){console.error("[REGENERATE-NEW-FACE-DEBUG] ❌ BLOCKED by generation lock"),alert("This page is already being regenerated. Please wait.");return}if(me.current[N]=!0,!l){alert("No session ID found"),me.current[N]=!1;return}const _=$e[N];if(!_||!_.includes("_face")){alert("Uploading a new face is only available on face pages"),me.current[N]=!1;return}console.log("[REGENERATE-NEW-FACE] Starting regeneration with new face for pageIndex:",N);const R=$e[N];if(console.log("[REGENERATE-NEW-FACE] Image key from indexToKeyMap:",R),!R){console.error("[REGENERATE-NEW-FACE] Image key not found for pageIndex:",N),alert("Image key not found"),me.current[N]=!1;return}const A=R.match(/page(\d{2})/),L=R.toLowerCase().includes("cover");if(!A&&!L){console.error("[REGENERATE-NEW-FACE] Invalid page key format:",R),alert("Invalid page key format"),me.current[N]=!1;return}const D=A?A[1]:R;console.log("[REGENERATE-NEW-FACE] Extracted page key:",D);const q=P.length,oe={url:"GENERATING",timestamp:Date.now(),variantKey:`${R}_variant_${q}_generating`};Pe(ae=>({...ae,[N]:[...P,oe]})),z(ae=>({...ae,[N]:q})),v(ae=>({...ae,[N]:P.length})),g(ae=>({...ae,[N]:!0}));const G=Date.now();qe(ae=>({...ae,[N]:{startTime:G,expectedVariantIndex:q}})),Xe(ae=>({...ae,[N]:0})),we.current[N]&&clearInterval(we.current[N]),we.current[N]=setInterval(()=>{const ae=Date.now()-G,xe=Math.min(95,ae/18e4*100);Xe(ve=>({...ve,[N]:xe}))},1e3),ns(N);try{const ae=l;if(console.log("[REGENERATE-NEW-FACE] Using sessionId from state:",ae),!ae)throw new Error("No session_id found - cannot regenerate variant with new face");const xe=R==="front"?"cover_face":R;console.log("[REGENERATE-NEW-FACE] Normalized key:",{original:R,normalized:xe});const ve=new FormData;ve.append("session_id",ae),ve.append("page",D),ve.append("page_key",xe),ve.append("face_image",w),console.log("[REGENERATE-NEW-FACE] Sending request to /api/preview/variant-new-face with session_id:",ae,{session_id:ae,page:D,face_image_name:w.name});const dt=await fetch(yt("/api/preview/variant-new-face"),{method:"POST",body:ve});if(!dt.ok)throw new Error("Variant-with-face request failed");const se=await dt.json();if(se.correlation_id&&console.log("[REGENERATE-NEW-FACE] 🔗 correlation_id:",se.correlation_id),!se.status||se.status!=="started"){g(Ke=>({...Ke,[N]:!1})),me.current[N]=!1,alert(se.message||"Failed to start variant generation");return}console.log("[REGENERATE-NEW-FACE] Variant generation with new face started, will add as new variant");const Le=async(Ke,Ee,ge)=>{console.log("[PROBE-NEW-FACE] ✅ Function started successfully with:",{sessionId:Ke,pageKey:Ee,variantIndex:ge});const ut=`${Ee}_variant${ge+1}`,mt=["jpg","jpeg","png","webp"],pt=Ee.includes("cover")?`front_variant${ge+1}`:null;console.log("[PROBE-NEW-FACE] Starting immediate HEAD probe for variant:",{expectedKey:ut,alternateKey:pt});for(let Pt=0;Pt<36;Pt++){Pt>0&&await new Promise(xs=>setTimeout(xs,5e3)),console.log(`[PROBE-NEW-FACE] 🔍 Attempt ${Pt+1}/36...`);for(const xs of mt){const Ps=`https://talesberry-s3-bucket.s3.ap-southeast-2.amazonaws.com/${Ke}/preview/${ut}.${xs}`;try{if((await fetch(Ps,{method:"HEAD",cache:"no-store"})).ok){console.log("[PROBE-NEW-FACE] ✅ Found variant file (primary key):",Ps),Pe(qt=>{var Ms;const Xt=[...qt[N]||[]];return((Ms=Xt[ge])==null?void 0:Ms.url)==="GENERATING"?Xt[ge]={url:Ps,timestamp:Date.now(),variantKey:ut}:Xt.push({url:Ps,timestamp:Date.now(),variantKey:ut}),{...qt,[N]:Xt}}),g(qt=>({...qt,[N]:!1})),qe(qt=>{const Xt={...qt};return delete Xt[N],Xt}),Xe(qt=>({...qt,[N]:100})),we.current[N]&&(clearInterval(we.current[N]),delete we.current[N]),me.current[N]=!1;return}}catch{}}if(pt)for(const xs of mt){const Ps=`https://talesberry-s3-bucket.s3.ap-southeast-2.amazonaws.com/${Ke}/preview/${pt}.${xs}`;try{if((await fetch(Ps,{method:"HEAD",cache:"no-store"})).ok){console.log("[PROBE-NEW-FACE] ✅ Found variant file (alternate key):",Ps),Pe(qt=>{var Ms;const Xt=[...qt[N]||[]];return((Ms=Xt[ge])==null?void 0:Ms.url)==="GENERATING"?Xt[ge]={url:Ps,timestamp:Date.now(),variantKey:pt.replace(`_variant${ge+1}`,"")}:Xt.push({url:Ps,timestamp:Date.now(),variantKey:pt.replace(`_variant${ge+1}`,"")}),{...qt,[N]:Xt}}),g(qt=>({...qt,[N]:!1})),qe(qt=>{const Xt={...qt};return delete Xt[N],Xt}),Xe(qt=>({...qt,[N]:100})),we.current[N]&&(clearInterval(we.current[N]),delete we.current[N]),me.current[N]=!1;return}}catch{}}console.log(`[PROBE-NEW-FACE] Attempt ${Pt+1}/36: Variant not found yet (tried ${pt?"both keys":"primary key"}), retrying...`)}console.error("[PROBE-NEW-FACE] ❌ Variant file not found after 3 minutes"),g(Pt=>({...Pt,[N]:!1})),qe(Pt=>{const xs={...Pt};return delete xs[N],xs}),we.current[N]&&(clearInterval(we.current[N]),delete we.current[N]),me.current[N]=!1};try{Le(ae,xe,q).catch(Ke=>console.error("[PROBE-NEW-FACE] ❌ Error in probe:",Ke))}catch(Ke){console.error("[PROBE-NEW-FACE] ❌ Synchronous error starting probe:",Ke)}}catch(ae){console.error("Regenerate with face error:",ae),g(xe=>({...xe,[N]:!1})),me.current[N]=!1,alert("Failed to regenerate page with new face")}},qa=N=>{var P,_;if(h(N),b&&T(R=>new Set([...R,N])),window.innerWidth<1024){if(!(!b&&N>=0&&N<=3)){st(N);return}return}const w=gt.current[N];if(w){const R=w.getBoundingClientRect(),A=((P=lt.current)==null?void 0:P.offsetParent)||((_=lt.current)==null?void 0:_.parentElement);if(A){const L=A.getBoundingClientRect(),D=R.height+12,q=Math.max(0,R.top-L.top-D);V(q)}else{const L=window.pageYOffset||document.documentElement.scrollTop,D=R.height+12,q=Math.max(0,R.top+L-D);V(q)}}},na=N=>{if(!N)return N;let w=N.trim();w=w.replace(/\[Boy\][''\u2019]s\s*/gi,""),w=w.replace(/\[Girl\][''\u2019]s\s*/gi,""),w=w.replace(/\[Boy\]\s*/gi,""),w=w.replace(/\[Girl\]\s*/gi,"");const P=/^([A-Za-z]+)[''\u2019]s\s+/;for(;P.test(w);)w=w.replace(P,"");if(/^[A-Za-z]+\s+and\s+/i.test(w)){const _=w.split(/\s+and\s+/i);_.length>1&&(w="and "+_.slice(1).join(" and "))}return w=w.replace(/^The\s+/i,""),w||N},Nr=async()=>{const N=(X==null?void 0:X.childName)||(M==null?void 0:M.name)||"",w=(X==null?void 0:X.childAge)||(M==null?void 0:M.age)||0;console.log("[ORDER] handleContinueToOrder called",{childName:N,childAge:w,previewData:X,sessionChildData:M});const P=((X==null?void 0:X.email)||(M==null?void 0:M.email_id)||"").trim().toLowerCase(),_=new URLSearchParams(window.location.search).get("testmode")==="true";if(P==="a@b.com"&&_){console.log("[PreviewPage] TEST BYPASS: Creating order for a@b.com");try{const R=(M==null?void 0:M.gender)||"Not specified",A=(X==null?void 0:X.childImage)||(M==null?void 0:M.latest_face_key)||"",L=(te==null?void 0:te.title)||"Test Book",{data:D,error:q}=await de.functions.invoke("create-razorpay-order",{body:{selectedBook:{title:L},childData:{name:N,age:String(w),language:(X==null?void 0:X.language)||"English",gender:R},childImage:A,sessionId:l,deliveryInfo:{firstName:"Test",lastName:"User",email:"a@b.com",phone:"9999999999",address:"Test Address",city:"Test City",state:"Test State",pincode:"000000",country:"India"},totalAmount:0,shippingCost:0,bookCost:0,currency:"INR",coverType:"hardcover",bookSize:"Standard"}});if(q)throw q;const oe=D==null?void 0:D.dbOrderId;console.log("[PreviewPage] TEST BYPASS: Order created with ID:",oe),oe&&(await de.from("payment_info").update({payment_status:"Completed",payment_ref_id:"TEST_BYPASS",updated_at:new Date().toISOString()}).eq("order_id",Number(oe)),await de.from("orders").update({payment_status:"completed",updated_at:new Date().toISOString()}).eq("order_id",Number(oe))),fetch(yt("/api/preview/generate-full"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:l,regenerate:!1})})}catch(R){console.warn("[PreviewPage] TEST BYPASS: Order/generation error:",R)}s(a("/preview")+`?payment_success=true&sessionId=${l}`);return}s(a("/print-options"),{state:{selectedBook:te,childData:{name:N,age:w,language:(X==null?void 0:X.language)||"English"},childImage:(X==null?void 0:X.childImage)||(M==null?void 0:M.latest_face_key)||"",sessionId:l}})},Ha=b&&Q.filter(N=>N).length===ye;p.useEffect(()=>{if(l){const N=localStorage.getItem(`printing_sent_timestamp_${l}`);if(N){const w=parseInt(N),P=60*1e3;Date.now()-w<P?Ne(w):localStorage.removeItem(`printing_sent_timestamp_${l}`)}}},[l]);const Os=()=>{if(!re)return!1;const N=60*1e3;return Date.now()-re<N},Ka=async()=>{try{if(console.log("[SEND FOR PRINTING] Sending print confirmation for session:",l),!l){alert("Session ID not found. Please try again.");return}_e(!0),ue(!0);const N={};Q.forEach((P,_)=>{if(P){const R=Fe[_],A=K[_]??0,L=R&&R[A]?R[A].url:P;L&&L!=="GENERATING"&&(N[_.toString()]=L)}}),console.log("[SEND FOR PRINTING] Sending pages:",N),fetch(yt("/api/orders/send-print-confirmation"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:l,pages:N})}).then(P=>{if(console.log("[SEND FOR PRINTING] API response status:",P.status),!P.ok)console.error("[SEND FOR PRINTING] API error:",P.status);else return P.json().then(_=>{console.log("[SEND FOR PRINTING] API success:",_)})}).catch(P=>{console.error("[SEND FOR PRINTING] Error:",P)}),await new Promise(P=>setTimeout(P,5e3)),_e(!1),ue(!1),U(!1);const w=Date.now();Ne(w),l&&localStorage.setItem(`printing_sent_timestamp_${l}`,w.toString())}catch(N){console.error("[SEND FOR PRINTING] Error:",N),_e(!1),ue(!1),U(!1),alert("Failed to send book for printing. Please try again.")}};return ee?e.jsxs("div",{className:"min-h-screen bg-white flex flex-col items-center justify-center",children:[e.jsx(Yt,{}),e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx(Ue,{className:"w-12 h-12 animate-spin text-primary-600 mx-auto"}),e.jsx("h2",{className:"text-xl font-semibold text-gray-800",children:"Loading your book preview..."}),e.jsx("p",{className:"text-gray-600",children:"Please wait while we prepare your personalized story"})]})]}):te?e.jsxs("div",{className:"min-h-screen bg-white md:pt-20",children:[e.jsx(Yt,{}),e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20am%20trying%20to%20create%20a%20book%20preview%20and%20i%20need%20some%20help%21",target:"_blank",rel:"noopener noreferrer","aria-label":"24x7 WhatsApp Support",className:`fixed bottom-4 right-4 z-50 inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
          px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,"data-track":"preview_whatsapp_support",children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),e.jsx("div",{className:"bg-white shadow-sm border-b mt-16",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-16",children:[!b&&e.jsxs("button",{onClick:()=>s(a(`/books/${te==null?void 0:te.id}/personalize`)),className:"flex items-center text-gray-600 hover:text-gray-800 transition-colors",children:[e.jsx(Ut,{className:"w-5 h-5 mr-1"}),"Back"]}),b&&e.jsx("div",{className:"w-16"}),e.jsx("h1",{className:"text-xl font-semibold text-gray-800",children:"Preview Your Story"}),e.jsx("div",{className:"w-16"})]})})}),l&&(()=>{const N=Q.filter(w=>w).length===ye;return e.jsx("div",{className:N?"bg-green-50 border-b border-green-200":"bg-blue-50 border-b border-blue-200",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3",children:e.jsxs("div",{className:"flex items-center space-x-3",children:[N?e.jsx("svg",{className:"w-5 h-5 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}):e.jsx(Ue,{className:"w-5 h-5 animate-spin text-blue-600"}),e.jsxs("div",{children:[e.jsx("p",{className:`text-sm font-medium ${N?"text-green-900":"text-blue-900"}`,children:N?"Your personalised book is ready!":"Generating your personalized book..."}),e.jsxs("p",{className:`text-xs ${N?"text-green-700":"text-blue-700"}`,children:[Q.filter(w=>w).length," of ",ye," pages ready"]})]})]})})})})(),Ve&&(ce==null?void 0:ce.status)==="failure"&&e.jsx("div",{className:"bg-red-50 border-b border-red-200",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3",children:e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("span",{className:"text-red-600",children:"❌"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-red-900",children:Ve}),(ce==null?void 0:ce.missing_images)&&ce.missing_images.length>0&&(()=>{const N=ce.missing_images.filter(w=>w==="cover"||w==="cover_text"?!1:w.includes("_")||w==="title"||w==="front"||w==="back");return N.length>0?e.jsxs("p",{className:"text-xs text-red-700 mt-1",children:["Missing: ",N.join(", ")]}):null})()]})]})})}),c&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl max-w-md w-full p-6 sm:p-8 animate-in fade-in zoom-in-95 duration-300",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-5",children:e.jsx("svg",{className:"w-9 h-9 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}),e.jsx("h2",{className:"text-xl font-bold text-gray-900 text-center mb-4",children:"Payment Successful! 🎉"}),e.jsxs("div",{className:"text-gray-700 text-sm leading-relaxed space-y-3 mb-6",children:[e.jsxs("p",{children:["The payment for your order is successful, and now ",e.jsx("span",{className:"font-bold text-green-700",children:"One Last Step"})," is needed."]}),e.jsxs("p",{children:["Kindly wait until entire book is generated and make sure you verify each page to your liking. Once done, click on ",e.jsx("span",{className:"font-semibold",children:"'Send for Printing'"})," button."]}),e.jsx("p",{className:"text-red-600 font-medium",children:"⚠️ Please note that no changes will be allowed after you click send for printing."})]}),e.jsx("button",{onClick:()=>u(!1),className:"w-full bg-green-600 hover:bg-green-700 text-white font-semibold py-3 px-6 rounded-xl transition-colors duration-200 text-base",children:"I Understand"})]})}),e.jsx("div",{className:"hidden md:block bg-white border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6",children:e.jsx("div",{className:"",children:e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:(()=>{var R;if((te==null?void 0:te.id)===101)return"I love you, because..";const w=(X==null?void 0:X.childName)||(M==null?void 0:M.name),P=na(te.title);if(((R=te==null?void 0:te.backendName)==null?void 0:R.toLowerCase())==="superhero"&&w)return`SuperHero ${w}`;if((te==null?void 0:te.category_tag)==="return_gift_books"&&w){const A=w.split(",")[0].trim();return`${A.charAt(0).toUpperCase()+A.slice(1).toLowerCase()}'s ${P}`}return w?`${w}'s ${P}`:P})()})})})}),b&&e.jsx("div",{className:"lg:hidden fixed bottom-0 left-0 right-0 z-50 px-4 py-4 bg-white border-t border-gray-200 shadow-[0_-4px_20px_rgba(0,0,0,0.1)]",children:Ha?e.jsx("button",{onClick:()=>{Os()||U(!0)},disabled:Os()||Me,className:`w-full px-6 py-4 rounded-xl font-semibold text-lg transition-all duration-300 transform shadow-lg ${Os()||Me?"bg-gray-400 text-gray-200 cursor-not-allowed":"bg-black text-white glow-button hover:bg-gray-800 hover:scale-[1.02]"}`,"data-gtm":"preview_send_for_printing_mobile_top","data-track":"send_for_printing_mobile_top",children:Me?e.jsxs("span",{className:"flex items-center justify-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),"Sending..."]}):Os()?"Printing Request Sent ✓":"✨ Final Step: Send for Printing"}):e.jsx("button",{disabled:!0,className:"w-full px-6 py-4 rounded-xl font-semibold text-lg bg-gray-300 text-gray-500 cursor-not-allowed",children:e.jsxs("span",{className:"flex items-center justify-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),"Send for Printing once all pages are ready"]})})}),!b&&B===null&&e.jsx("div",{className:"lg:hidden fixed bottom-0 left-0 right-0 z-40 px-4 py-3 bg-white border-t border-gray-200 shadow-[0_-4px_20px_rgba(0,0,0,0.1)]",children:e.jsxs("button",{onClick:Nr,className:"w-full px-6 py-3.5 bg-gradient-to-r from-primary-600 to-secondary-600 text-white font-semibold text-base rounded-xl hover:from-primary-700 hover:to-secondary-700 transition-all duration-300 shadow-lg","data-gtm":"preview_order_sticky_mobile","data-track":"order_sticky_mobile",children:["📚 Order ",yr((X==null?void 0:X.childName)||(M==null?void 0:M.name)||""),"'s Storybook"]})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:e.jsxs("div",{className:"flex flex-col lg:flex-row gap-8 items-start relative",children:[e.jsx("div",{className:"lg:w-80 order-2 lg:order-1",ref:ie,children:e.jsxs("div",{children:[e.jsx("h2",{className:"hidden lg:block text-lg font-semibold text-gray-800 mb-4",children:b?"Full Book Preview":"Free Preview Pages"}),e.jsxs("div",{className:"space-y-4",children:[!b&&e.jsx("div",{className:"lg:hidden space-y-4",style:{marginLeft:"-16px",marginRight:"-16px"},children:Array.from({length:Math.min(4,ye)}).map((N,w)=>{const P=ct(w),_=$e[w]||"",R=_.includes("_face")&&!_.includes("_text"),A=Fe[w]||[],L=K[w]||0,D=A[L],q=(D==null?void 0:D.url)==="GENERATING",oe=w===0?"Cover":`Page ${w}`,G=R&&P==="backend",ae=5,xe=A.length,ve=xe>=ae,dt=A.some(Ee=>Ee.url==="GENERATING"),se=G&&!ve&&!dt,Le=G?xe+(se||ve?1:0):1,Ke=Ee=>{const ge=document.getElementById(`mobile-scroll-${w}`);ge&&ge.scrollTo({left:Ee*ge.clientWidth,behavior:"smooth"})};return e.jsxs("div",{className:"relative",children:[e.jsx("div",{id:`mobile-scroll-${w}`,className:"flex overflow-x-auto snap-x snap-mandatory scrollbar-hide",style:{scrollbarWidth:"none",msOverflowStyle:"none",WebkitOverflowScrolling:"touch"},onScroll:Ee=>{const ge=Ee.currentTarget,ut=ge.clientWidth,mt=ge.scrollLeft,Vt=Math.round(mt/ut);z(pt=>({...pt,[w]:Vt})),Vt<A.length&&j(pt=>({...pt,[w]:Date.now()}))},children:(()=>{const Ee=[];if(G&&A.length>0)if(A.forEach((ge,ut)=>{const mt=ge.url==="GENERATING",Vt=ge.timestamp||x[w]||0,pt=mt?void 0:`${ge.url}${ge.url.includes("?")?"&":"?"}t=${Vt}`;Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-white overflow-hidden border border-gray-200",children:e.jsxs("div",{className:"relative w-full aspect-square",children:[mt?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-10 h-10 animate-spin text-primary-600 mb-3"}),e.jsxs("div",{className:"text-sm font-medium text-primary-800",children:["Generating variant ",ut+1,"..."]})]}):e.jsx("img",{src:pt,alt:`${oe} - Variant ${ut+1}`,className:`w-full h-full object-cover ${m[w]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(w)}),e.jsx("div",{className:"absolute bottom-2 left-2 bg-black bg-opacity-50 text-white text-xs px-2 py-0.5 rounded",children:oe})]})})},`slide-${w}-${ut}`))}),se){const ge=ae-xe;Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-gray-50 overflow-hidden border border-gray-200",children:e.jsxs("div",{className:"w-full aspect-square flex flex-col items-center justify-center px-6",children:[e.jsxs("button",{onClick:()=>{W(w),setTimeout(()=>{Ke(xe)},300)},disabled:m[w],className:"flex flex-col items-center gap-3 px-6 py-4 rounded-xl bg-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-gtm":"preview_generate_more_mobile",children:[e.jsx(Gs,{className:`w-8 h-8 text-primary-600 ${m[w]?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-800",children:"Generate more options"})]}),xe>1&&e.jsxs("p",{className:"text-xs text-gray-500 mt-3",children:["You can generate ",ge," more option",ge!==1?"s":""]})]})})},`slide-${w}-generate`))}else ve&&Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-gray-50 overflow-hidden border border-gray-200",children:e.jsx("div",{className:"w-full aspect-square flex flex-col items-center justify-center px-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl mb-3",children:"✅"}),e.jsxs("p",{className:"text-sm font-semibold text-gray-800",children:["You've generated ",ae," options"]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Swipe left to pick your favourite"})]})})})},`slide-${w}-maxed`));else Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-white overflow-hidden border border-gray-200",children:e.jsxs("div",{className:"relative w-full aspect-square",children:[(()=>{if(P==="generating"){const Pt=pe[w]||0;return e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-10 h-10 animate-spin text-primary-600 mb-3"}),e.jsx("div",{className:"text-sm font-medium text-primary-800 mb-2 px-6 text-center",children:ft}),e.jsx("div",{className:"w-3/4 bg-primary-200/50 rounded-full h-2 overflow-hidden mb-1",children:e.jsx("div",{className:"bg-gradient-to-r from-primary-500 to-secondary-500 h-full transition-all duration-1000 ease-out",style:{width:`${Pt}%`}})}),e.jsxs("div",{className:"text-xs text-primary-700 font-medium",children:[Math.round(Pt),"%"]})]})}if(P==="failed")return e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-red-50",children:e.jsxs("div",{className:"text-center px-4",children:[e.jsx("div",{className:"text-4xl mb-3",children:"❌"}),e.jsx("div",{className:"text-sm text-red-600",children:"Failed to generate"})]})});const ge=!!$e[w]&&$e[w].includes("_face"),ut=is(w);let mt;D&&!q?mt=D.url:ge?mt=Q[w]:mt=Q[w]||(ut!==null?Q[ut]:void 0);const Vt=(D==null?void 0:D.timestamp)||x[w]||(ut!==null?x[ut]:0)||0,pt=mt&&`${mt}${mt.includes("?")?"&":"?"}t=${Vt}`;return e.jsx("img",{src:pt,alt:oe,className:`w-full h-full object-cover ${m[w]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(w)},`mobile-preview-img-${w}-${Vt}`)})(),e.jsx("div",{className:"absolute bottom-2 left-2 bg-black bg-opacity-50 text-white text-xs px-2 py-0.5 rounded",children:oe})]})})},`slide-${w}-single`));return Ee})()}),Le>1&&e.jsxs(e.Fragment,{children:[L>0&&e.jsx("button",{onClick:()=>Ke(L-1),className:"absolute left-2 top-1/2 -translate-y-1/2 z-10 bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-1.5 shadow-md transition-all",children:e.jsx(Ut,{className:"w-5 h-5 text-gray-700"})}),L<Le-1&&e.jsx("button",{onClick:()=>Ke(L+1),className:"absolute right-2 top-1/2 -translate-y-1/2 z-10 bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-1.5 shadow-md transition-all",children:e.jsx(gs,{className:"w-5 h-5 text-gray-700"})})]}),Le>1&&e.jsx("div",{className:"flex items-center justify-center gap-2 mt-3",children:Array.from({length:Le}).map((Ee,ge)=>e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-200 ${ge===L||ge===Le-1&&L>=A.length?"bg-primary-600 scale-110":"bg-gray-300"}`},`dot-${w}-${ge}`))})]},`mobile-preview-${w}`)})}),!b&&ye>4&&e.jsx("div",{className:"lg:hidden",children:e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Array.from({length:ye-4}).map((N,w)=>{const P=w+4,_=P===ye-1?"Back":P===ye-2?"Bridge":`Page ${P}`;return e.jsx("div",{className:"relative rounded-lg overflow-hidden cursor-pointer shadow-sm",onClick:()=>st(P),children:e.jsxs("div",{className:"aspect-square relative",children:[e.jsx("img",{src:Ct(P),alt:`${_} - Locked`,className:"w-full h-full object-cover",onContextMenu:R=>R.preventDefault(),onError:ss,draggable:!1,"data-page-index":P,"data-fallback-index":"0",loading:"lazy"}),e.jsx("div",{className:"absolute inset-0 bg-black/20 flex items-center justify-center",children:e.jsxs("div",{className:"bg-black/80 rounded-md px-2 py-1 flex items-center gap-1",children:[e.jsx(vt,{className:"w-3 h-3 text-white"}),e.jsx("span",{className:"text-white text-[10px] font-medium",children:"Locked"})]})}),e.jsx("div",{className:"absolute bottom-1 left-1 bg-black/50 text-white text-[10px] px-1.5 py-0.5 rounded",children:_})]})},`mobile-locked-${P}`)})})}),b&&e.jsx("div",{className:"lg:hidden space-y-4",style:{marginLeft:"-16px",marginRight:"-16px"},children:Array.from({length:ye}).map((N,w)=>{const P=ct(w),_=$e[w]||"",R=_.includes("_face")&&!_.includes("_text"),A=Fe[w]||[],L=K[w]||0,D=A[L],q=(D==null?void 0:D.url)==="GENERATING",oe=w===0?"Cover":w===ye-1?"Back":w===ye-2?"Bridge":`Page ${w}`,G=R&&P==="backend",ae=5,xe=A.length,ve=xe>=ae,dt=A.some(Ee=>Ee.url==="GENERATING"),se=G&&!ve&&!dt,Le=G?xe+(se||ve?1:0):1,Ke=Ee=>{const ge=document.getElementById(`mobile-paid-scroll-${w}`);ge&&ge.scrollTo({left:Ee*ge.clientWidth,behavior:"smooth"})};return e.jsxs("div",{className:"relative",children:[e.jsx("div",{id:`mobile-paid-scroll-${w}`,className:"flex overflow-x-auto snap-x snap-mandatory scrollbar-hide",style:{scrollbarWidth:"none",msOverflowStyle:"none",WebkitOverflowScrolling:"touch"},onScroll:Ee=>{const ge=Ee.currentTarget,ut=ge.clientWidth,mt=ge.scrollLeft,Vt=Math.round(mt/ut);z(pt=>({...pt,[w]:Vt})),Vt<A.length&&j(pt=>({...pt,[w]:Date.now()}))},children:(()=>{const Ee=[];if(G&&A.length>0)if(A.forEach((ge,ut)=>{const mt=ge.url==="GENERATING",Vt=ge.timestamp||x[w]||0,pt=mt?void 0:`${ge.url}${ge.url.includes("?")?"&":"?"}t=${Vt}`;Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-white overflow-hidden border border-gray-200",children:e.jsxs("div",{className:"relative w-full aspect-square",children:[mt?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-10 h-10 animate-spin text-primary-600 mb-3"}),e.jsxs("div",{className:"text-sm font-medium text-primary-800",children:["Generating variant ",ut+1,"..."]})]}):e.jsx("img",{src:pt,alt:`${oe} - Variant ${ut+1}`,className:`w-full h-full object-cover ${m[w]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(w)}),e.jsx("div",{className:"absolute bottom-2 left-2 bg-black bg-opacity-50 text-white text-xs px-2 py-0.5 rounded",children:oe})]})})},`paid-slide-${w}-${ut}`))}),se){const ge=ae-xe;Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-gray-50 overflow-hidden border border-gray-200",children:e.jsxs("div",{className:"w-full aspect-square flex flex-col items-center justify-center px-6",children:[e.jsxs("button",{onClick:()=>{W(w),setTimeout(()=>Ke(xe),300)},disabled:m[w],className:"flex flex-col items-center gap-3 px-6 py-4 rounded-xl bg-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-gtm":"preview_generate_more_mobile_paid",children:[e.jsx(Gs,{className:`w-8 h-8 text-primary-600 ${m[w]?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-800",children:"Generate more options"})]}),xe>1&&e.jsxs("p",{className:"text-xs text-gray-500 mt-3",children:["You can generate ",ge," more option",ge!==1?"s":""]})]})})},`paid-slide-${w}-generate`))}else ve&&Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-gray-50 overflow-hidden border border-gray-200",children:e.jsx("div",{className:"w-full aspect-square flex flex-col items-center justify-center px-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl mb-3",children:"✅"}),e.jsxs("p",{className:"text-sm font-semibold text-gray-800",children:["You've generated ",ae," options"]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Swipe left to pick your favourite"})]})})})},`paid-slide-${w}-maxed`));else Ee.push(e.jsx("div",{className:"w-full flex-shrink-0 snap-center",children:e.jsx("div",{className:"relative bg-white overflow-hidden border border-gray-200",children:e.jsxs("div",{className:"relative w-full aspect-square",children:[(()=>{if(P==="generating"){const Pt=pe[w]||0;return e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-10 h-10 animate-spin text-primary-600 mb-3"}),e.jsx("div",{className:"text-sm font-medium text-primary-800 mb-2 px-6 text-center",children:ft}),e.jsx("div",{className:"w-3/4 bg-primary-200/50 rounded-full h-2 overflow-hidden mb-1",children:e.jsx("div",{className:"bg-gradient-to-r from-primary-500 to-secondary-500 h-full transition-all duration-1000 ease-out",style:{width:`${Pt}%`}})}),e.jsxs("div",{className:"text-xs text-primary-700 font-medium",children:[Math.round(Pt),"%"]})]})}if(P==="failed")return e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-red-50",children:e.jsxs("div",{className:"text-center px-4",children:[e.jsx("div",{className:"text-4xl mb-3",children:"❌"}),e.jsx("div",{className:"text-sm text-red-600",children:"Failed to generate"})]})});const ge=!!$e[w]&&$e[w].includes("_face"),ut=is(w);let mt;D&&!q?mt=D.url:ge?mt=Q[w]:mt=Q[w]||(ut!==null?Q[ut]:void 0);const Vt=(D==null?void 0:D.timestamp)||x[w]||(ut!==null?x[ut]:0)||0,pt=mt&&`${mt}${mt.includes("?")?"&":"?"}t=${Vt}`;return e.jsx("img",{src:pt,alt:oe,className:`w-full h-full object-cover ${m[w]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(w)},`mobile-paid-img-${w}-${Vt}`)})(),e.jsx("div",{className:"absolute bottom-2 left-2 bg-black bg-opacity-50 text-white text-xs px-2 py-0.5 rounded",children:oe})]})})},`paid-slide-${w}-single`));return Ee})()}),Le>1&&e.jsxs(e.Fragment,{children:[L>0&&e.jsx("button",{onClick:()=>Ke(L-1),className:"absolute left-2 top-1/2 -translate-y-1/2 z-10 bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-1.5 shadow-md transition-all",children:e.jsx(Ut,{className:"w-5 h-5 text-gray-700"})}),L<Le-1&&e.jsx("button",{onClick:()=>Ke(L+1),className:"absolute right-2 top-1/2 -translate-y-1/2 z-10 bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-1.5 shadow-md transition-all",children:e.jsx(gs,{className:"w-5 h-5 text-gray-700"})})]}),Le>1&&e.jsx("div",{className:"flex items-center justify-center gap-2 mt-3",children:Array.from({length:Le}).map((Ee,ge)=>e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-200 ${ge===L||ge===Le-1&&L>=A.length?"bg-primary-600 scale-110":"bg-gray-300"}`},`paid-dot-${w}-${ge}`))})]},`mobile-paid-preview-${w}`)})}),Array.from({length:Math.ceil(ye/2)}).map((N,w)=>{const P=w*2,_=P+1,R=_<ye;return e.jsx("div",{className:"relative bg-white rounded-lg shadow-xl overflow-hidden transition-transform duration-300 hover:scale-[1.02] hidden lg:block",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{ref:A=>gt.current[P]=A,className:`relative flex-1 cursor-pointer transition-all duration-300 ${d===P?"ring-2 ring-primary-500 ring-inset":"opacity-70 hover:opacity-100"}`,onClick:()=>qa(P),"data-gtm":"preview_thumb",children:e.jsx("div",{className:"aspect-square relative",children:(()=>{const A=ct(P);if(A==="locked")return e.jsxs("div",{className:"w-full h-full relative",children:[e.jsx("img",{src:Ct(P),alt:`Page ${P} - Locked`,className:"w-full h-full object-cover",onContextMenu:L=>L.preventDefault(),onError:ss,draggable:!1,"data-page-index":P,"data-fallback-index":"0"}),e.jsx("div",{className:"absolute inset-0 bg-black/20 flex items-center justify-center",children:e.jsxs("div",{className:"bg-black/80 rounded-md px-2 py-1 flex items-center gap-1",children:[e.jsx(vt,{className:"w-3 h-3 text-white"}),e.jsx("span",{className:"text-white text-[10px] font-medium",children:"Locked"})]})})]});if(A==="generating"){const L=pe[P]||0;return e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-4 h-4 animate-spin text-primary-600 mb-1"}),e.jsxs("div",{className:"text-[10px] font-medium text-primary-700",children:[Math.round(L),"%"]})]})}return A==="failed"?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-red-50",children:e.jsxs("div",{className:"text-center px-2",children:[e.jsx("div",{className:"text-2xl mb-2",children:"❌"}),e.jsx("div",{className:"text-xs text-red-600",children:"Failed to generate"})]})}):e.jsxs(e.Fragment,{children:[(()=>{var se,Le;const L=!!$e[P]&&$e[P].includes("_face"),D=is(P),q=Fe[P]||[],oe=K[P]||0,G=q[oe],ae=(G==null?void 0:G.url)==="GENERATING";let xe;G&&!ae?xe=G.url:L?xe=Q[P]:xe=Q[P]||(D!==null?Q[D]:void 0);const ve=(G==null?void 0:G.timestamp)||x[P]||(D!==null?x[D]:0)||0,dt=xe&&`${xe}${xe.includes("?")?"&":"?"}t=${ve}`;if(ae&&fe[P]){const Ke=pe[P]||0,Ee=((se=q[oe-1])==null?void 0:se.url)||((Le=q[0])==null?void 0:Le.url)||Q[P],ge=Ee&&Ee!=="GENERATING"?`${Ee}${Ee.includes("?")?"&":"?"}t=${ve}`:void 0;return e.jsxs("div",{className:"relative w-full h-full",children:[ge&&e.jsx("img",{src:ge,alt:P===0?"Cover":P===Q.length-1?"Back":`Page ${P}`,className:"w-full h-full object-cover blur-sm"}),e.jsxs("div",{className:"absolute inset-0 bg-black bg-opacity-40 flex flex-col items-center justify-center",children:[e.jsx(Ue,{className:"w-4 h-4 animate-spin text-white mb-1"}),e.jsxs("div",{className:"text-[10px] font-medium text-white",children:[Math.round(Ke),"%"]})]})]})}return e.jsx("img",{src:dt,alt:P===0?"Cover":P===Q.length-1?"Back":`Page ${P}`,className:`w-full h-full object-cover transition-all duration-300 ${m[P]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(P)},`thumb-${P}-${ve}`)})(),e.jsx("div",{className:"absolute bottom-1 right-1 bg-black bg-opacity-50 text-white text-xs px-1 py-0.5 rounded",children:P===0?"Cover":b?P===Q.length-1?"Back":P===Q.length-2?"Bridge":P:P})]})})()})}),R&&e.jsx("div",{className:"absolute left-1/2 top-0 bottom-0 w-1 transform -translate-x-1/2 bg-gradient-to-r from-transparent via-gray-400/30 to-transparent pointer-events-none z-10"}),R&&e.jsx("div",{ref:A=>gt.current[_]=A,className:`relative flex-1 cursor-pointer transition-all duration-300 border-l border-gray-200/50 ${d===_?"ring-2 ring-primary-500 ring-inset":"opacity-70 hover:opacity-100"}`,onClick:()=>qa(_),"data-gtm":"preview_thumb",children:e.jsx("div",{className:"aspect-square relative",children:(()=>{const A=ct(_);if(A==="locked")return e.jsxs("div",{className:"w-full h-full relative",children:[e.jsx("img",{src:Ct(_),alt:`Page ${_} - Locked`,className:"w-full h-full object-cover",onContextMenu:L=>L.preventDefault(),onError:ss,draggable:!1,"data-page-index":_,"data-fallback-index":"0"}),e.jsx("div",{className:"absolute inset-0 bg-black/20 flex items-center justify-center",children:e.jsxs("div",{className:"bg-black/80 rounded-md px-2 py-1 flex items-center gap-1",children:[e.jsx(vt,{className:"w-3 h-3 text-white"}),e.jsx("span",{className:"text-white text-[10px] font-medium",children:"Locked"})]})})]});if(A==="generating"){const L=pe[_]||0;return e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-4 h-4 animate-spin text-primary-600 mb-1"}),e.jsxs("div",{className:"text-[10px] font-medium text-primary-700",children:[Math.round(L),"%"]})]})}return A==="failed"?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-red-50",children:e.jsxs("div",{className:"text-center px-2",children:[e.jsx("div",{className:"text-2xl mb-2",children:"❌"}),e.jsx("div",{className:"text-xs text-red-600",children:"Failed to generate"})]})}):e.jsxs(e.Fragment,{children:[(()=>{var se,Le;const L=!!$e[_]&&$e[_].includes("_face"),D=is(_),q=Fe[_]||[],oe=K[_]||0,G=q[oe],ae=(G==null?void 0:G.url)==="GENERATING";let xe;G&&!ae?xe=G.url:L?xe=Q[_]:xe=Q[_]||(D!==null?Q[D]:void 0);const ve=(G==null?void 0:G.timestamp)||x[_]||(D!==null?x[D]:0)||0,dt=xe&&`${xe}${xe.includes("?")?"&":"?"}t=${ve}`;if(ae&&fe[_]){const Ke=pe[_]||0,Ee=((se=q[oe-1])==null?void 0:se.url)||((Le=q[0])==null?void 0:Le.url)||Q[_],ge=Ee&&Ee!=="GENERATING"?`${Ee}${Ee.includes("?")?"&":"?"}t=${ve}`:void 0;return e.jsxs("div",{className:"relative w-full h-full",children:[ge&&e.jsx("img",{src:ge,alt:_===0?"Cover":_===Q.length-1?"Back":`Page ${_}`,className:"w-full h-full object-cover blur-sm"}),e.jsxs("div",{className:"absolute inset-0 bg-black bg-opacity-40 flex flex-col items-center justify-center",children:[e.jsx(Ue,{className:"w-4 h-4 animate-spin text-white mb-1"}),e.jsxs("div",{className:"text-[10px] font-medium text-white",children:[Math.round(Ke),"%"]})]})]})}return e.jsx("img",{src:dt,alt:_===0?"Cover":_===Q.length-1?"Back":`Page ${_}`,className:`w-full h-full object-cover transition-all duration-300 ${m[_]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(_)},`thumb-${_}-${ve}`)})(),e.jsx("div",{className:"absolute bottom-1 right-1 bg-black bg-opacity-50 text-white text-xs px-1 py-0.5 rounded",children:_===0?"Cover":b?_===Q.length-1?"Back":_===Q.length-2?"Bridge":_:_})]})})()})})]})},`spread-${w}`)}).reduce((N,w,P)=>(N.push(w),P===1&&N.push(e.jsx("div",{className:"lg:hidden pt-1 pb-2 space-y-3 flex flex-col items-center",children:!b&&e.jsxs(e.Fragment,{children:[((X==null?void 0:X.childName)||(M==null?void 0:M.name))&&e.jsxs("div",{style:{background:"#FFF6F1",border:"1px solid #F2E2DA",boxShadow:"0 6px 20px rgba(0,0,0,0.05)",borderRadius:"14px",padding:"14px 16px",marginTop:"0px",textAlign:"center"},children:[(()=>{const _=(X==null?void 0:X.childName)||(M==null?void 0:M.name)||"",R=Or(_,M==null?void 0:M.gender);return e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{fontSize:"15px",fontWeight:600,color:"#3B2E2A",marginBottom:"6px"},children:R.title}),e.jsxs("p",{style:{fontSize:"13px",color:"#6B5E58",lineHeight:"1.5"},children:[R.subtitle,e.jsx("br",{}),e.jsx("strong",{children:R.strong})]})]})})(),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[e.jsxs("a",{href:`https://wa.me/?text=${encodeURIComponent(`Check out this personalised storybook starring ${Or((X==null?void 0:X.childName)||(M==null?void 0:M.name)||"",M==null?void 0:M.gender).shareName}! ✨ ${window.location.href}`)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 px-4 py-2 bg-[#25D366] hover:bg-[#20bd5a] text-white text-xs font-medium rounded-full transition-colors whitespace-nowrap",children:[e.jsx(gn,{size:14}),"Share on Whatsapp"]}),e.jsxs("button",{onClick:()=>{navigator.clipboard.writeText(window.location.href),Y(!0),setTimeout(()=>Y(!1),2e3)},className:"flex items-center gap-1.5 px-4 py-2 bg-[#F5F5F5] hover:bg-gray-200 text-[#444] text-xs font-medium rounded-full border border-[#E5E5E5] transition-colors whitespace-nowrap",children:[e.jsx(ni,{size:14}),Ye?"Copied!":"Copy Link"]})]})]}),e.jsxs("button",{style:{marginTop:"24px"},onClick:Nr,className:"w-full px-8 py-3.5 bg-gradient-to-r from-primary-600 to-secondary-600 text-white font-semibold text-base rounded-xl hover:from-primary-700 hover:to-secondary-700 transition-all duration-300 transform hover:scale-105 shadow-lg","data-gtm":"preview_choose_print_options_mobile","data-track":"choose_print_options_mobile",children:["📚 Order ",yr((X==null?void 0:X.childName)||(M==null?void 0:M.name)||""),"'s Storybook"]}),e.jsxs("p",{style:{fontSize:"12px",color:"#6B5E58",lineHeight:"1.6",textAlign:"left",marginTop:"10px"},children:["📦 Fully printed book delivered in 5–7 days",e.jsx("br",{}),"❤️ Loved by 2500+ families"]})]})},"mobile-next-step-button")),N),[])]})]})}),e.jsx("div",{ref:lt,className:"hidden lg:block flex-1 order-1 lg:order-2 lg:absolute lg:right-8 lg:w-[calc(50%-2rem)] lg:max-w-3xl lg:z-30 transition-all duration-300",style:{top:O>0?`${O}px`:void 0},children:e.jsxs("div",{className:"bg-white rounded-xl shadow-lg p-2 lg:p-3 h-full flex flex-col overflow-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 lg:mb-3",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800",children:d===0?"Cover Page":d===ye-1?"Back Cover":d===ye-2?"Bridge Page":`Page ${d}`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>h(Math.max(0,d-1)),disabled:d===0,className:"p-2 rounded-lg bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:e.jsx(Ut,{className:"w-5 h-5"})}),e.jsxs("span",{className:"text-sm text-gray-600 min-w-[80px] text-center",children:[d+1," of ",ye]}),e.jsx("button",{onClick:()=>{const N=Math.min(ye-1,d+1);h(N),b&&T(w=>new Set([...w,N]))},disabled:d===ye-1,className:"p-2 rounded-lg bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:e.jsx(gs,{className:"w-5 h-5"})})]})]}),e.jsxs("div",{className:"relative bg-gray-50 rounded-lg p-2 lg:p-4 flex flex-col items-center justify-center min-h-[400px] lg:min-h-[600px]",children:[(()=>{const N=Fe[d]||[],w=K[d]||0,P=ct(d),_=$e[d]||"";return _.includes("_face")&&!_.includes("_text")&&N.length>=1&&P==="backend"?e.jsxs("div",{className:"mb-2 bg-white rounded-full shadow-lg px-4 py-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-gray-600",children:N.length===1?"Variant:":"Variants:"}),N.map((R,A)=>{const L=R.url==="GENERATING";return e.jsx("button",{onClick:()=>{z(D=>({...D,[d]:A})),j(D=>({...D,[d]:Date.now()}))},className:`w-7 h-7 rounded-full flex items-center justify-center text-xs font-semibold transition-all ${w===A?"bg-primary-600 text-white shadow-md":L?"bg-yellow-100 text-yellow-600 animate-pulse":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:L?e.jsx(Ue,{className:"w-3 h-3 animate-spin"}):A+1},A)})]}):null})(),e.jsx("div",{className:"relative w-full max-w-md aspect-square",children:(()=>{var A,L;const N=ct(d),w=Fe[d]||[],P=K[d]||0,_=w[P];if((_==null?void 0:_.url)==="GENERATING"&&fe[d]){const D=pe[d]||0,q=((A=w[P-1])==null?void 0:A.url)||((L=w[0])==null?void 0:L.url)||Q[d];return e.jsxs("div",{className:"w-full h-full relative rounded-lg overflow-hidden",children:[q&&q!=="GENERATING"&&e.jsx("img",{src:q,alt:`Page ${d} - Generating`,className:"w-full h-full object-cover blur-md"}),e.jsxs("div",{className:"absolute inset-0 bg-black bg-opacity-40 flex flex-col items-center justify-center",children:[e.jsx(Ue,{className:"w-16 h-16 animate-spin text-white mb-4"}),e.jsxs("div",{className:"text-lg font-medium text-white mb-2",children:["Generating variant ",P+1,"..."]}),e.jsx("div",{className:"w-3/4 bg-gray-200 rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:"bg-primary-500 h-full transition-all duration-1000 ease-out",style:{width:`${D}%`}})}),e.jsxs("div",{className:"text-sm text-white mt-2",children:[Math.round(D),"% complete"]})]})]})}if(N==="locked")return e.jsxs("div",{className:"w-full h-full relative rounded-lg overflow-hidden shadow-lg",children:[e.jsx("img",{src:Ct(d),alt:`Page ${d} - Locked`,className:"w-full h-full object-cover",onContextMenu:D=>D.preventDefault(),onError:ss,draggable:!1,"data-page-index":d,"data-fallback-index":"0"}),e.jsx("div",{className:"absolute top-4 right-4",children:e.jsx(vt,{className:"w-8 h-8 text-black drop-shadow-lg"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4",children:e.jsx("div",{className:"bg-black/70 rounded-lg p-4 shadow-xl max-w-xs",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("div",{className:"text-lg font-bold mb-2",children:"Preview Locked"}),e.jsx("div",{className:"text-sm opacity-90",children:"Full book will be unlocked after your purchase. Click on Choose Print Options to move forward."})]})})})]});if(N==="generating"){const D=pe[d]||0;return e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50 rounded-lg shadow-lg",children:[e.jsx(Ue,{className:"w-16 h-16 animate-spin text-primary-600 mb-4"}),e.jsx("div",{className:"text-lg font-medium text-primary-800 mb-4 px-6 text-center",children:ft}),e.jsx("div",{className:"w-3/4 bg-primary-200/50 rounded-full h-3 overflow-hidden mb-2",children:e.jsx("div",{className:"bg-gradient-to-r from-primary-500 to-secondary-500 h-full transition-all duration-1000 ease-out",style:{width:`${D}%`}})}),e.jsxs("div",{className:"text-sm text-primary-700 font-medium",children:[Math.round(D),"%"]})]})}return N==="failed"?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-red-50 rounded-lg shadow-lg",children:e.jsxs("div",{className:"text-center px-6",children:[e.jsx("div",{className:"text-6xl mb-4",children:"❌"}),e.jsx("div",{className:"text-xl font-bold text-red-700 mb-2",children:"Generation Failed"}),e.jsx("div",{className:"text-red-600",children:"Failed to receive image from backend"})]})}):e.jsxs(e.Fragment,{children:[(()=>{const D=!!$e[d]&&$e[d].includes("_face");let q;if(w.length>0&&w[P])q=w[P].url;else{const G=is(d);q=D?Q[d]:Q[d]||(G!==null?Q[G]:void 0)}const oe=m[d]?aa(q,d):q;return e.jsx("img",{src:oe,alt:d===0?"Cover":d===Q.length-1?"Back":`Page ${d}`,className:`w-full h-full object-cover rounded-lg shadow-lg transition-all duration-300 ${m[d]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(d)},`main-${q}`)})(),(()=>{var oe,G,ae,xe;const D=$e[d]||"";return D.includes("_face")&&!D.includes("_text")?e.jsx("div",{className:"absolute top-1/2 right-4 transform -translate-y-1/2",children:e.jsxs("div",{className:"relative",ref:Be,children:[e.jsx("button",{onClick:ve=>{ve.stopPropagation(),Ce(!ke)},className:"bg-white hover:bg-gray-50 p-3 rounded-full shadow-xl transition-all duration-300 hover:scale-110 hover:shadow-2xl relative z-50","data-gtm":"preview_action_menu",children:e.jsx(Gs,{className:"w-6 h-6 text-gray-700"})}),ke&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40 bg-transparent",onClick:ve=>{ve.stopPropagation(),Ce(!1)}}),e.jsxs("div",{className:"absolute top-full right-0 mt-2 w-56 bg-gray-800 rounded-lg shadow-2xl z-50 overflow-hidden",onClick:ve=>ve.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{W(d),Ce(!1)},disabled:m[d]||(((oe=Fe[d])==null?void 0:oe.length)||0)>=7,className:"w-full flex items-center gap-3 px-4 py-3 text-white hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-gray-800","data-gtm":"preview_generate_variant","data-track":"preview_retry",children:[e.jsx(Gs,{className:`w-5 h-5 ${m[d]?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-medium",children:(((G=Fe[d])==null?void 0:G.length)||0)>=7?"Max variants reached":"Retry"})]}),e.jsxs("label",{className:`w-full flex items-center gap-3 px-4 py-3 text-white hover:bg-gray-700 transition-colors ${(((ae=Fe[d])==null?void 0:ae.length)||0)>=7||m[d]?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,"data-gtm":"preview_upload_new_face","data-track":"preview_new_face_upload",children:[e.jsx(Di,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm font-medium",children:"New Photo"}),e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png,image/heic,image/heif",className:"hidden",disabled:m[d]||(((xe=Fe[d])==null?void 0:xe.length)||0)>=7,onChange:ve=>{var se;const dt=(se=ve.target.files)==null?void 0:se[0];dt&&(fs(d,dt),Ce(!1),ve.target.value="")}})]})]})]})]})}):null})()]})})()})]}),!b&&((X==null?void 0:X.childName)||(M==null?void 0:M.name))&&e.jsxs("div",{style:{background:"#FFF6F1",border:"1px solid #F2E2DA",boxShadow:"0 6px 20px rgba(0,0,0,0.05)",borderRadius:"14px",padding:"14px 16px",marginTop:"0px",textAlign:"center"},children:[(()=>{const N=(X==null?void 0:X.childName)||(M==null?void 0:M.name)||"",w=Or(N,M==null?void 0:M.gender);return e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{fontSize:"15px",fontWeight:600,color:"#3B2E2A",marginBottom:"6px"},children:w.title}),e.jsxs("p",{style:{fontSize:"13px",color:"#6B5E58",lineHeight:"1.5"},children:[w.subtitle,e.jsx("br",{}),e.jsx("strong",{children:w.strong})]})]})})(),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[e.jsxs("a",{href:`https://wa.me/?text=${encodeURIComponent(`Check out this personalised storybook starring ${Or((X==null?void 0:X.childName)||(M==null?void 0:M.name)||"",M==null?void 0:M.gender).shareName}! ✨ ${window.location.href}`)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 px-4 py-2 bg-[#25D366] hover:bg-[#20bd5a] text-white text-xs font-medium rounded-full transition-colors whitespace-nowrap",children:[e.jsx(gn,{size:14}),"Share on Whatsapp"]}),e.jsxs("button",{onClick:()=>{navigator.clipboard.writeText(window.location.href),Y(!0),setTimeout(()=>Y(!1),2e3)},className:"flex items-center gap-1.5 px-4 py-2 bg-[#F5F5F5] hover:bg-gray-200 text-[#444] text-xs font-medium rounded-full border border-[#E5E5E5] transition-colors whitespace-nowrap",children:[e.jsx(ni,{size:14}),Ye?"Copied!":"Copy Link"]})]})]}),e.jsxs("div",{className:"mt-3 lg:mt-8 text-center space-y-3 lg:space-y-4",children:[b&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-blue-900",children:"Book Generation Progress"}),e.jsxs("span",{className:"text-sm text-blue-600",children:[Q.filter(N=>N).length,"/",ye," pages"]})]}),e.jsx("div",{className:"w-full bg-blue-200 rounded-full h-2",children:e.jsx("div",{className:"bg-blue-600 h-2 rounded-full transition-all duration-300",style:{width:`${Q.filter(N=>N).length/ye*100}%`}})})]}),b&&I?e.jsx("button",{onClick:Ka,className:"px-8 py-4 bg-gradient-to-r from-green-600 to-emerald-600 text-white font-semibold rounded-xl hover:from-green-700 hover:to-emerald-700 transition-all duration-300 transform hover:scale-105 shadow-lg",children:"Send for Printing"}):b?e.jsx("div",{className:"space-y-2",children:e.jsx("p",{className:"text-blue-600 font-semibold",children:"View all pages and regenerate as needed to complete your book."})}):e.jsxs("div",{className:"hidden lg:flex flex-col items-center w-full",children:[e.jsxs("button",{onClick:Nr,className:"px-10 py-3.5 bg-gradient-to-r from-primary-600 to-secondary-600 text-white font-semibold text-base rounded-xl hover:from-primary-700 hover:to-secondary-700 transition-all duration-300 transform hover:scale-105 shadow-lg","data-gtm":"preview_choose_print_options","data-track":"choose_print_options",children:["📚 Order ",yr((X==null?void 0:X.childName)||(M==null?void 0:M.name)||""),"'s Storybook"]}),e.jsxs("p",{style:{fontSize:"12px",color:"#6B5E58",lineHeight:"1.6",textAlign:"left",marginTop:"10px"},children:["📦 Fully printed book delivered in 5–7 days",e.jsx("br",{}),"❤️ Loved by 2500+ families"]})]}),b&&Ha&&e.jsx("div",{className:"flex gap-4 justify-center mt-6",children:e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:()=>!Os()&&U(!0),disabled:Me||Os(),className:`px-8 py-4 bg-gradient-to-r from-green-600 to-emerald-600 text-white text-base font-semibold rounded-xl transition-all duration-300 shadow-lg flex items-center justify-center gap-2 ${Me||Os()?"opacity-50 cursor-not-allowed":"hover:from-green-700 hover:to-emerald-700 transform hover:scale-105"}`,"data-track":"preview_send_for_printing",children:[Me&&!Se&&e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),Me&&!Se?"Sending...":"Send for Printing"]}),Os()&&e.jsxs("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-4 py-3 bg-gray-900 text-white text-sm rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50 shadow-xl",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold mb-1",children:"Your request is already being processed"}),e.jsx("div",{className:"text-xs text-gray-300",children:"Please check your email"})]}),e.jsx("div",{className:"absolute top-full left-1/2 -translate-x-1/2 -mt-1",children:e.jsx("div",{className:"border-8 border-transparent border-t-gray-900"})})]})]})})]})]})})]})}),J&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black bg-opacity-50 backdrop-blur-sm",onClick:()=>{Me&&ue(!1),U(!1)}}),e.jsx("div",{className:"relative bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 p-8 z-10",children:Me?e.jsxs("div",{className:"text-center space-y-6",children:[e.jsx("div",{className:"mx-auto w-20 h-20 bg-gradient-to-r from-green-100 to-emerald-100 rounded-full flex items-center justify-center",children:e.jsx(Ue,{className:"w-10 h-10 text-green-600 animate-spin"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-2xl font-bold text-gray-900",children:"Processing Your Request"}),e.jsx("p",{className:"text-gray-600 text-base leading-relaxed",children:"Your send for printing request is being processed, please wait for a moment! You will receive an email shortly with all the details."})]})]}):e.jsxs("div",{className:"text-center space-y-6",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-gradient-to-r from-green-100 to-emerald-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{className:"w-8 h-8 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"Ready to Send for Printing?"}),e.jsxs("p",{className:"text-gray-600 text-base leading-relaxed",children:["Looks like you are ready to send your book for printing. Note that"," ",e.jsx("span",{className:"font-semibold",children:"no further changes in the book will be possible"})," once you send the book for printing."]})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("button",{onClick:Ka,className:"w-full px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white font-semibold rounded-xl hover:from-green-700 hover:to-emerald-700 transition-all duration-300 transform hover:scale-105 shadow-lg",children:"I am good, send for print"}),e.jsx("button",{onClick:()=>U(!1),className:"w-full px-6 py-3 bg-gray-100 text-gray-700 font-semibold rounded-xl hover:bg-gray-200 transition-all duration-300",children:"Cancel and Go Back"})]})]})})]}),B!==null&&e.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-black/80",onClick:()=>st(null)}),e.jsxs("div",{className:"relative h-full flex flex-col items-center justify-center p-4",children:[e.jsx("button",{onClick:()=>st(null),className:"fixed top-4 right-4 z-[70] bg-white rounded-full p-2.5 shadow-lg border border-gray-200","aria-label":"Close preview",children:e.jsx(Cs,{className:"w-6 h-6 text-gray-800"})}),e.jsx("div",{className:"text-white text-lg font-semibold mb-4",children:B===0?"Cover Page":B===ye-1?"Back Cover":B===ye-2?"Bridge Page":`Page ${B}`}),(()=>{const N=Fe[B]||[],w=K[B]||0,P=ct(B),_=$e[B]||"";return _.includes("_face")&&!_.includes("_text")&&N.length>=1&&P==="backend"?e.jsxs("div",{className:"mb-4 bg-white rounded-full shadow-lg px-4 py-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-gray-600",children:N.length===1?"Variant:":"Variants:"}),N.map((R,A)=>{const L=R.url==="GENERATING";return e.jsx("button",{onClick:()=>{z(D=>({...D,[B]:A})),j(D=>({...D,[B]:Date.now()}))},className:`w-7 h-7 rounded-full flex items-center justify-center text-xs font-semibold transition-all ${w===A?"bg-primary-600 text-white shadow-md":L?"bg-yellow-100 text-yellow-600 animate-pulse":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:L?e.jsx(Ue,{className:"w-3 h-3 animate-spin"}):A+1},A)})]}):null})(),e.jsx("div",{className:"relative w-full max-w-md aspect-square",children:(()=>{var A,L;const N=ct(B),w=Fe[B]||[],P=K[B]||0,_=w[P];if((_==null?void 0:_.url)==="GENERATING"&&fe[B]){const D=pe[B]||0,q=((A=w[P-1])==null?void 0:A.url)||((L=w[0])==null?void 0:L.url)||Q[B];return e.jsxs("div",{className:"w-full h-full relative rounded-lg overflow-hidden",children:[q&&q!=="GENERATING"&&e.jsx("img",{src:q,alt:`Page ${B} - Generating`,className:"w-full h-full object-cover blur-md"}),e.jsxs("div",{className:"absolute inset-0 bg-black bg-opacity-40 flex flex-col items-center justify-center",children:[e.jsx(Ue,{className:"w-16 h-16 animate-spin text-white mb-4"}),e.jsxs("div",{className:"text-lg font-medium text-white mb-2",children:["Generating variant ",P+1,"..."]}),e.jsx("div",{className:"w-3/4 bg-gray-200 rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:"bg-primary-500 h-full transition-all duration-1000 ease-out",style:{width:`${D}%`}})}),e.jsxs("div",{className:"text-sm text-white mt-2",children:[Math.round(D),"% complete"]})]})]})}if(N==="locked")return e.jsxs("div",{className:"w-full h-full relative rounded-lg overflow-hidden shadow-lg",children:[e.jsx("img",{src:Ct(B),alt:`Page ${B} - Locked`,className:"w-full h-full object-cover",onContextMenu:D=>D.preventDefault(),onError:ss,draggable:!1,"data-page-index":B,"data-fallback-index":"0"}),e.jsx("div",{className:"absolute top-4 right-4",children:e.jsx(vt,{className:"w-8 h-8 text-black drop-shadow-lg"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4",children:e.jsx("div",{className:"bg-black/70 rounded-lg p-4 shadow-xl max-w-xs w-full",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("div",{className:"text-lg font-bold mb-2",children:"Preview Locked"}),e.jsx("div",{className:"text-sm opacity-90 mb-4",children:"Full book will be unlocked after your purchase."}),e.jsx("button",{onClick:()=>st(null),className:"w-full px-4 py-2.5 rounded-lg bg-white text-gray-900 font-semibold",children:"Go Back to Preview"})]})})})]});if(N==="generating"){const D=pe[B]||0;return e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50 rounded-lg shadow-lg",children:[e.jsx(Ue,{className:"w-16 h-16 animate-spin text-primary-600 mb-4"}),e.jsx("div",{className:"text-lg font-medium text-primary-800 mb-4 px-6 text-center",children:ft}),e.jsx("div",{className:"w-3/4 bg-primary-200/50 rounded-full h-3 overflow-hidden mb-2",children:e.jsx("div",{className:"bg-gradient-to-r from-primary-500 to-secondary-500 h-full transition-all duration-1000 ease-out",style:{width:`${D}%`}})}),e.jsxs("div",{className:"text-sm text-primary-700 font-medium",children:[Math.round(D),"%"]})]})}return N==="failed"?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-red-50 rounded-lg shadow-lg",children:e.jsxs("div",{className:"text-center px-6",children:[e.jsx("div",{className:"text-6xl mb-4",children:"❌"}),e.jsx("div",{className:"text-xl font-bold text-red-700 mb-2",children:"Generation Failed"}),e.jsx("div",{className:"text-red-600",children:"Failed to receive image from backend"})]})}):e.jsxs(e.Fragment,{children:[(()=>{const D=!!$e[B]&&$e[B].includes("_face");let q;if(w.length>0&&w[P])q=w[P].url;else{const G=is(B);q=D?Q[B]:Q[B]||(G!==null?Q[G]:void 0)}const oe=m[B]?aa(q,B):q;return e.jsx("img",{src:oe,alt:B===0?"Cover":B===Q.length-1?"Back":`Page ${B}`,className:`w-full h-full object-cover rounded-lg shadow-lg transition-all duration-300 ${m[B]?"blur-sm opacity-70":""}`,onLoad:()=>Wt(B)},`modal-${q}`)})(),((X==null?void 0:X.childName)||(M==null?void 0:M.name))&&e.jsxs("div",{style:{background:"#FFF6F1",border:"1px solid #F2E2DA",boxShadow:"0 6px 20px rgba(0,0,0,0.05)",borderRadius:"14px",padding:"14px 16px",marginTop:"0px",textAlign:"center"},children:[(()=>{const D=(X==null?void 0:X.childName)||(M==null?void 0:M.name)||"",q=Or(D,M==null?void 0:M.gender);return e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{fontSize:"15px",fontWeight:600,color:"#3B2E2A",marginBottom:"6px"},children:q.title}),e.jsxs("p",{style:{fontSize:"13px",color:"#6B5E58",lineHeight:"1.5"},children:[q.subtitle,e.jsx("br",{}),e.jsx("strong",{children:q.strong})]})]})})(),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[e.jsxs("a",{href:`https://wa.me/?text=${encodeURIComponent(`Check out this personalised storybook starring ${Or((X==null?void 0:X.childName)||(M==null?void 0:M.name)||"",M==null?void 0:M.gender).shareName}! ✨ ${window.location.href}`)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 px-4 py-2 bg-[#25D366] hover:bg-[#20bd5a] text-white text-xs font-medium rounded-full transition-colors whitespace-nowrap",children:[e.jsx(gn,{size:14}),"Share on Whatsapp"]}),e.jsxs("button",{onClick:()=>{navigator.clipboard.writeText(window.location.href),Y(!0),setTimeout(()=>Y(!1),2e3)},className:"flex items-center gap-1.5 px-4 py-2 bg-[#F5F5F5] hover:bg-gray-200 text-[#444] text-xs font-medium rounded-full border border-[#E5E5E5] transition-colors whitespace-nowrap",children:[e.jsx(ni,{size:14}),Ye?"Copied!":"Copy Link"]})]})]}),(()=>{var oe,G,ae,xe;const D=$e[B]||"";return D.includes("_face")&&!D.includes("_text")?e.jsx("div",{className:"absolute top-1/2 right-4 transform -translate-y-1/2",children:e.jsxs("div",{className:"relative",ref:Be,children:[e.jsx("button",{onClick:ve=>{ve.stopPropagation(),Ce(!ke)},className:"bg-white hover:bg-gray-50 p-3 rounded-full shadow-xl transition-all duration-300 hover:scale-110 hover:shadow-2xl relative z-50","data-gtm":"preview_action_menu_mobile",children:e.jsx(Gs,{className:"w-6 h-6 text-gray-700"})}),ke&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40 bg-transparent",onClick:ve=>{ve.stopPropagation(),Ce(!1)}}),e.jsxs("div",{className:"absolute top-full right-0 mt-2 w-56 bg-gray-800 rounded-lg shadow-2xl z-50 overflow-hidden",onClick:ve=>ve.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{W(B),Ce(!1)},disabled:m[B]||(((oe=Fe[B])==null?void 0:oe.length)||0)>=7,className:"w-full flex items-center gap-3 px-4 py-3 text-white hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-gray-800","data-gtm":"preview_generate_variant_mobile","data-track":"preview_retry_mobile",children:[e.jsx(Gs,{className:`w-5 h-5 ${m[B]?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-medium",children:(((G=Fe[B])==null?void 0:G.length)||0)>=7?"Max variants reached":"Retry"})]}),e.jsxs("label",{className:`w-full flex items-center gap-3 px-4 py-3 text-white hover:bg-gray-700 transition-colors ${(((ae=Fe[B])==null?void 0:ae.length)||0)>=7||m[B]?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,"data-gtm":"preview_upload_new_face_mobile","data-track":"preview_new_face_upload_mobile",children:[e.jsx(Di,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm font-medium",children:"New Photo"}),e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png,image/heic,image/heif",className:"hidden",disabled:m[B]||(((xe=Fe[B])==null?void 0:xe.length)||0)>=7,onChange:ve=>{var se;const dt=(se=ve.target.files)==null?void 0:se[0];dt&&(fs(B,dt),Ce(!1),ve.target.value="")}})]})]})]})]})}):null})()]})})()}),e.jsxs("div",{className:"flex items-center gap-4 mt-4",children:[e.jsx("button",{onClick:()=>{const N=Math.max(0,B-1);st(N),h(N),b&&T(w=>new Set([...w,N]))},disabled:B===0,className:"p-3 rounded-full bg-white/20 hover:bg-white/30 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:e.jsx(Ut,{className:"w-6 h-6 text-white"})}),e.jsxs("span",{className:"text-white text-sm min-w-[80px] text-center",children:[B+1," of ",ye]}),e.jsx("button",{onClick:()=>{const N=Math.min(ye-1,B+1);st(N),h(N),b&&T(w=>new Set([...w,N]))},disabled:B===ye-1,className:"p-3 rounded-full bg-white/20 hover:bg-white/30 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:e.jsx(gs,{className:"w-6 h-6 text-white"})})]})]})]})]}):(console.error("[PreviewPage RENDER] No book found, showing error state"),e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center pt-20",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-4",children:"Book Not Found"}),e.jsxs("p",{className:"text-gray-600 mb-4",children:["Session ID: ",l||"N/A"]}),e.jsx("button",{onClick:()=>s(a("/books")),className:"px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors",children:"Back to Books"})]})}))},tj=()=>{var g,f,v;const r=Jt(),t=_t(),{buildLink:s}=ht(),a=x=>{if(!x)return x;let j=x.trim();const b=/^([A-Za-z]+)['']s\s+/;for(;b.test(j);)j=j.replace(b,"");if(/^[A-Za-z]+\s+and\s+/i.test(j)){const y=j.split(/\s+and\s+/i);y.length>1&&(j="and "+y.slice(1).join(" and "))}return j||x},n=r.state,i=n==null?void 0:n.selectedBook;if(!i)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-4",children:"Cart is Empty"}),e.jsx("button",{onClick:()=>t(s("/books")),className:"px-6 py-3 bg-black text-white rounded-lg hover:bg-gray-800 transition-colors",children:"Browse Books"})]})});const o=((g=i==null?void 0:i.pricing)==null?void 0:g.large)||((f=i==null?void 0:i.pricing)==null?void 0:f.small)||{price:1,originalPrice:1},l=o.originalPrice||1,c=o.price||1,u=()=>{t(s("/delivery"),{state:n})},d=()=>{t(s("/books"))},h=()=>{t(s("/books"))},m=()=>{t(-1)};return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(Yt,{}),e.jsx("div",{className:"bg-white shadow-sm border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-16",children:[e.jsxs("div",{className:"flex items-center space-x-8",children:[e.jsx("h1",{className:"text-xl font-semibold text-gray-800",children:"Home"}),e.jsxs("nav",{className:"flex space-x-8",children:[e.jsx("span",{className:"text-gray-600",children:"Books"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("span",{className:"text-gray-600",children:"My Books"}),e.jsx("span",{className:"ml-1 w-5 h-5 bg-primary-600 text-white text-xs rounded-full flex items-center justify-center",children:"3"})]}),e.jsx("span",{className:"text-gray-600",children:"Support"})]})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx("span",{className:"text-sm text-gray-600",children:"🇮🇳 INR"})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(vu,{className:"w-5 h-5"}),e.jsx("span",{className:"w-5 h-5 bg-primary-600 text-white text-xs rounded-full flex items-center justify-center",children:"1"})]}),e.jsx("span",{className:"text-gray-600",children:"User"})]})]})})}),e.jsx("div",{className:"bg-white border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center space-x-8",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-primary-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"1"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-primary-600",children:"Cart"})]}),e.jsx("div",{className:"w-16 h-1 bg-gray-300 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-sm font-semibold",children:"2"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Delivery"})]}),e.jsx("div",{className:"w-16 h-1 bg-gray-300 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-sm font-semibold",children:"3"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Checkout"})]})]})})})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900 mb-8",children:"Your Cart"}),e.jsx("div",{className:"bg-white rounded-lg shadow-sm border p-6 mb-6",children:e.jsxs("div",{className:"flex items-start space-x-4",children:[e.jsx("div",{className:"w-20 h-28 flex-shrink-0 rounded-lg overflow-hidden",children:e.jsx("img",{src:i.images[0]?`/${i.images[0].split("/")[1]}/front.${i.images[0].split(".")[1]||"jpeg"}`:"/placeholder.md",alt:i.title,className:"w-full h-full object-cover",onError:x=>{x.currentTarget.src="/placeholder.md"}})}),e.jsx("div",{className:"flex-1",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:(v=n==null?void 0:n.childData)!=null&&v.name?`${n.childData.name}'s ${a(i.title)}`:i.title}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Hardcover | English"}),e.jsx("button",{onClick:m,className:"text-black hover:text-gray-700 text-sm font-medium mt-2",children:"Edit"})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs("span",{className:"text-lg font-semibold text-gray-900",children:["₹",c]}),e.jsx("button",{onClick:h,className:"text-gray-400 hover:text-gray-600",children:e.jsx(Cs,{className:"w-5 h-5"})})]})]})})]})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-gray-600 mb-4",children:"Add Another Personalised Book?"}),e.jsx("button",{onClick:d,className:"px-6 py-2 border border-black text-black rounded-lg hover:bg-gray-100 transition-colors",children:"Add Books"})]})]}),e.jsx("div",{className:"lg:col-span-1",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-6 sticky top-8",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-6",children:"Order Summary"}),e.jsx("div",{className:"space-y-4 mb-6",children:e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Books (1)"}),e.jsxs("div",{className:"text-right",children:[e.jsxs("span",{className:"text-gray-400 line-through text-sm",children:["₹",l]}),e.jsxs("span",{className:"text-gray-900 font-medium ml-2",children:["₹",c]})]})]})}),e.jsx("div",{className:"border-t pt-4 mb-6",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-lg font-semibold text-gray-900",children:"Total"}),e.jsxs("span",{className:"text-2xl font-bold text-primary-600",children:["₹",c]})]})}),e.jsx("button",{onClick:u,className:"w-full bg-black text-white py-3 px-4 rounded-lg hover:bg-gray-800 transition-colors font-semibold","data-track":"cart_continue",children:"Continue"})]})})]})})]})},Lm=p.createContext({user:null,session:null,loading:!0,signOut:async()=>{}}),Jn=()=>{const r=p.useContext(Lm);if(!r)throw new Error("useAuth must be used within an AuthProvider");return r},sj=({children:r})=>{const[t,s]=p.useState(null),[a,n]=p.useState(null),[i,o]=p.useState(!0);p.useEffect(()=>{const{data:{subscription:c}}=de.auth.onAuthStateChange((u,d)=>{n(d),s((d==null?void 0:d.user)??null),o(!1)});return de.auth.getSession().then(({data:{session:u}})=>{n(u),s((u==null?void 0:u.user)??null),o(!1)}),()=>c.unsubscribe()},[]);const l=async()=>{await de.auth.signOut()};return e.jsx(Lm.Provider,{value:{user:t,session:a,loading:i,signOut:l},children:r})},rj=[{id:1,name:"Rachel T.",location:"Singapore",content:"I ordered a TalesBerry book as a birthday gift for my niece, and it genuinely surprised all of us. Seeing her own face and name inside the story made it feel very special. The print quality was excellent and delivery was smooth.",rating:5,initial:"R"},{id:2,name:"Daniel K.",location:"Singapore",content:"This is one of those gifts that feels thoughtful without being complicated. The story was sweet, the illustrations were beautiful, and my son keeps asking us to read it again.",rating:5,initial:"D"},{id:3,name:"Mei Lin",location:"Singapore",content:"I was initially unsure how the personalization would turn out, but the final book exceeded expectations. It felt well crafted and not generic or artificial. A lovely keepsake.",rating:5,initial:"M"},{id:4,name:"Aarav and Neha",location:"United Kingdom",content:"We live abroad and wanted something meaningful to send to our daughter while we were travelling. TalesBerry turned out to be a wonderful choice and very emotional for our family.",rating:5,initial:"A"},{id:5,name:"Jason W.",location:"Singapore",content:"What I liked most was how easy the process was. Uploading the photo, choosing the story, and receiving the book was seamless. The end result felt premium and well finished.",rating:5,initial:"J"},{id:6,name:"Sophia L.",location:"Singapore",content:"This book has now become part of our bedtime routine. My daughter loves spotting herself in the illustrations and it has made reading time much more engaging.",rating:5,initial:"S"},{id:7,name:"Margaret P.",location:"Australia",content:"I gifted this to my grandson and he was absolutely thrilled. It is rare to find something that feels both modern and emotionally meaningful. I would happily recommend it.",rating:4.5,initial:"M"},{id:8,name:"Arjun S.",location:"Singapore",content:"The personalization is done very tastefully. It does not feel gimmicky or overdone. It feels like a real storybook with your child naturally at the centre of the story.",rating:5,initial:"A"},{id:9,name:"Emily R.",location:"Singapore",content:"I appreciated the attention to detail, especially the illustrations and print finish. It feels like something you would want to keep for years, not just a one time novelty.",rating:5,initial:"E"},{id:10,name:"Michael T.",location:"New Zealand",content:"We ordered this as a surprise gift and the reaction was priceless. It is one of those things children remember. Definitely different from the usual toys or gadgets.",rating:4.5,initial:"M"}],_l=()=>{const[r,t]=p.useState(new Set),[s,a]=p.useState(!1),[n,i]=p.useState(!0),o=p.useRef(null),l=h=>{t(m=>{const g=new Set(m);return g.has(h)?g.delete(h):g.add(h),g})},c=()=>{if(!o.current)return;const{scrollLeft:h,scrollWidth:m,clientWidth:g}=o.current;a(h>10),i(h<m-g-10)},u=h=>{if(!o.current)return;const m=o.current.clientWidth*.8;o.current.scrollBy({left:h==="left"?-m:m,behavior:"smooth"})},d=h=>{const m=Math.floor(h);return e.jsx("span",{className:"flex items-center gap-0.5",children:Array.from({length:m}).map((g,f)=>e.jsx(Pa,{className:"w-3 h-3 md:w-4 md:h-4",fill:"#facc15",stroke:"#facc15"},f))})};return e.jsx("section",{className:"bg-white pt-0 md:pt-4",children:e.jsxs("div",{className:"container mx-auto",children:[e.jsx("div",{className:"hidden md:block text-center mb-8 mt-3",children:e.jsx("p",{className:"text-xl font-semibold text-purple-800",children:"Loved by families across Singapore and around the world"})}),e.jsxs("div",{className:"relative",children:[s&&e.jsx("button",{onClick:()=>u("left"),className:"absolute left-0 md:-left-4 top-1/2 -translate-y-1/2 z-10 bg-white/80 backdrop-blur-sm rounded-full p-2 md:p-3 shadow-lg hover:bg-white transition-colors","aria-label":"Scroll left",children:e.jsx("svg",{className:"w-5 h-5 md:w-6 md:h-6 text-purple-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),n&&e.jsx("button",{onClick:()=>u("right"),className:"absolute right-0 md:-right-4 top-1/2 -translate-y-1/2 z-10 bg-white/80 backdrop-blur-sm rounded-full p-2 md:p-3 shadow-lg hover:bg-white transition-colors","aria-label":"Scroll right",children:e.jsx("svg",{className:"w-5 h-5 md:w-6 md:h-6 text-purple-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}),e.jsx("div",{ref:o,onScroll:c,className:"flex gap-2 md:gap-4 overflow-x-auto pb-2 md:pb-4 snap-x snap-mandatory scrollbar-thin scrollbar-thumb-purple-300 scrollbar-track-purple-100",children:rj.map((h,m)=>e.jsxs("div",{onClick:()=>l(m),className:"flex-shrink-0 w-[42%] md:w-80 bg-white border border-purple-200 rounded-xl p-2 md:p-4 shadow-sm hover:shadow-md transition-all cursor-pointer snap-start",children:[e.jsxs("div",{className:"md:hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-white font-bold text-sm flex-shrink-0",children:h.initial}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-purple-900 text-sm break-words",children:h.name}),e.jsx("p",{className:"text-xs text-gray-500",children:h.location})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 mb-2",children:[d(h.rating),e.jsxs("span",{children:[h.rating,"/5"]})]}),e.jsx("p",{className:`text-gray-700 text-xs leading-relaxed break-words ${r.has(m)?"":"line-clamp-1"}`,children:h.content})]}),e.jsxs("div",{className:"hidden md:block",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-800 flex items-center justify-center text-white font-bold text-lg",children:h.initial}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-purple-900 truncate",children:h.name}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[d(h.rating),e.jsxs("span",{children:[h.rating,"/5"]}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:h.location})]})]})]}),e.jsx("p",{className:`text-gray-700 text-sm leading-relaxed ${r.has(m)?"":"line-clamp-1"}`,children:h.content})]}),h.content.length>50&&e.jsx("button",{className:"text-purple-600 text-[10px] md:text-xs mt-1 md:mt-2 hover:text-purple-800 font-medium",children:r.has(m)?"Show less":"Read more"})]},h.id))})]})]})})},Ei=new Map,Om=()=>{const[r,t]=p.useState(!1),[s,a]=p.useState(null),[n,i]=p.useState(null),[o,l]=p.useState(!1),c=p.useRef(null),u=p.useRef(null);p.useEffect(()=>()=>{c.current&&clearTimeout(c.current),u.current&&u.current.abort()},[]);const d=p.useCallback(()=>{a(null)},[]),h=p.useCallback(()=>{l(!1)},[]),m=p.useCallback(g=>{c.current&&clearTimeout(c.current),u.current&&u.current.abort(),a(null);const f=g.replace(/\D/g,"");if(f.length!==6){f.length<6&&(i(null),l(!1));return}if(Ei.has(f)){const v=Ei.get(f);i(v),l(!0),t(!1);return}c.current=setTimeout(async()=>{t(!0),a(null),u.current=new AbortController;try{const v=await fetch(`https://www.onemap.gov.sg/api/common/elastic/search?searchVal=${f}&returnGeom=N&getAddrDetails=Y`,{signal:u.current.signal});if(!v.ok)throw new Error("Network error");const x=await v.json();if(x.found===0||!x.results||x.results.length===0)a("We couldn't find an address for this postal code. Please enter it manually."),i(null),l(!1);else{const j=x.results[0],b={blockNumber:j.BLK_NO||"",streetName:j.ROAD_NAME||"",buildingName:j.BUILDING!=="NIL"&&j.BUILDING||""};Ei.set(f,b),i(b),l(!0),a(null)}}catch(v){if(v.name==="AbortError")return;console.error("[useOneMapLookup] API error:",v),a("Unable to verify postal code. Please enter your address manually."),i(null),l(!1)}finally{t(!1)}},300)},[]);return{isLoading:r,error:s,addressData:n,isAutoFilled:o,lookupAddress:m,clearError:d,clearAutoFill:h}},aj=()=>{var Pe;const r=Jt(),t=_t(),{loading:s}=Jn(),{region:a,config:n,buildLink:i}=ht(),o=K=>{if(!K)return K;let z=K.trim();z=z.replace(/\[Boy\][''\u2019]s\s*/gi,""),z=z.replace(/\[Girl\][''\u2019]s\s*/gi,""),z=z.replace(/\[Boy\]\s*/gi,""),z=z.replace(/\[Girl\]\s*/gi,"");const ce=/^([A-Za-z]+)[''\u2019]s\s+/;for(;ce.test(z);)z=z.replace(ce,"");if(/^[A-Za-z]+\s+and\s+/i.test(z)){const le=z.split(/\s+and\s+/i);le.length>1&&(z="and "+le.slice(1).join(" and "))}return z=z.replace(/^The\s+/i,""),z||K},l=K=>{if(!K)return null;const z=K.match(/TB(\d+)OFF/);return z?parseInt(z[1],10):null},c=r.state,u=c==null?void 0:c.selectedBook,[d,h]=p.useState({firstName:"",lastName:"",email:"",phone:"",phoneCountryCode:a==="SG"?"+65":a==="US"?"+1":"+91",address:"",city:a==="SG"?"Singapore":"",state:"",pincode:"",country:n.country,unitNumber:"",blockNumber:"",streetName:"",buildingName:""}),{isLoading:m,error:g,addressData:f,isAutoFilled:v,lookupAddress:x,clearError:j,clearAutoFill:b}=Om();p.useEffect(()=>{a==="SG"&&f&&h(K=>({...K,blockNumber:f.blockNumber,streetName:f.streetName,buildingName:f.buildingName}))},[f,a]),p.useEffect(()=>{h(K=>({...K,country:n.country}))},[n.country]),p.useEffect(()=>{var le;c!=null&&c.coverType&&(localStorage.setItem("pending_order_cover_type",c.coverType),console.log("[DeliveryPage] Persisted coverType to localStorage:",c.coverType)),c!=null&&c.bookPrice&&(localStorage.setItem("pending_order_book_price",String(c.bookPrice)),console.log("[DeliveryPage] Persisted bookPrice to localStorage:",c.bookPrice));const K=(c==null?void 0:c.bookPrice)||n.bookPrice,z=(c==null?void 0:c.coverType)||localStorage.getItem("pending_order_cover_type")||void 0,ce=localStorage.getItem("session_id")||void 0;jw(K+n.shippingPrice,(u==null?void 0:u.title)||((le=c==null?void 0:c.selectedBook)==null?void 0:le.title)||void 0,z,ce)},[c==null?void 0:c.coverType,c==null?void 0:c.bookPrice,n.bookPrice,n.shippingPrice]),p.useEffect(()=>{(async()=>{const z=(c==null?void 0:c.sessionId)||localStorage.getItem("session_id");if(z){const{data:ce}=await de.from("sessions").select("email_id, whatsapp_number").eq("session_id",z).single();ce&&h(le=>{const rt={};if(ce.email_id&&typeof ce.email_id=="string"&&(rt.email=ce.email_id),ce.whatsapp_number&&typeof ce.whatsapp_number=="string"){let Ve=ce.whatsapp_number;Ve.startsWith("+65")?(rt.phoneCountryCode="+65",Ve=Ve.slice(3)):Ve.startsWith("+91")?(rt.phoneCountryCode="+91",Ve=Ve.slice(3)):Ve.startsWith("+1")&&Ve.length>=12?(rt.phoneCountryCode="+1",Ve=Ve.slice(2)):Ve.startsWith("65")&&Ve.length===10?(rt.phoneCountryCode="+65",Ve=Ve.slice(2)):Ve.startsWith("91")&&Ve.length===12?(rt.phoneCountryCode="+91",Ve=Ve.slice(2)):Ve.startsWith("1")&&Ve.length===11&&(rt.phoneCountryCode="+1",Ve=Ve.slice(1)),rt.phone=Ve}return{...le,...rt}})}})()},[c==null?void 0:c.sessionId]);const[y,S]=p.useState({}),[T,I]=p.useState(!1),[E,O]=p.useState(!1),[V,J]=p.useState(!1),[U,Ge]=p.useState(""),[Te,Me]=p.useState(!1),[_e,Se]=p.useState(""),[ue,re]=p.useState(null),[Ne,fe]=p.useState(""),[qe,pe]=p.useState(!1),Xe=()=>{const K=d.phone.replace(/\D/g,""),z=n.phoneValidation.test(K),ce=d.firstName.trim()&&d.lastName.trim()&&d.email.trim()&&/\S+@\S+\.\S+/.test(d.email)&&d.phone.trim()&&z&&d.pincode.trim();return a==="SG"?ce&&d.streetName.trim()&&d.unitNumber.trim():a==="IN"||a==="US"?ce&&d.address.trim()&&d.city.trim()&&d.state.trim():ce&&d.address.trim()};p.useEffect(()=>{(()=>{if(document.getElementById("razorpay-checkout-js"))return;const z=document.createElement("script");z.id="razorpay-checkout-js",z.src="https://checkout.razorpay.com/v1/checkout.js",z.async=!0,z.onload=()=>{console.log("Razorpay Checkout script loaded successfully")},z.onerror=()=>{console.error("Failed to load Razorpay Checkout script")},document.head.appendChild(z)})()},[]);const ft=async()=>{const K=a==="SG"?8:10;if(U.length!==K){alert(`Please enter a valid ${K}-digit WhatsApp number`);return}const z=(c==null?void 0:c.sessionId)||localStorage.getItem("session_id");if(!z){alert("Session not found. Please try again.");return}Me(!0);try{const{data:ce,error:le}=await de.from("coupon_codes").select("*").eq("session_id",z).eq("status","active").gt("expires_at",new Date().toISOString()).order("created_at",{ascending:!1}).limit(1);if(le)throw console.error("Error checking existing coupons:",le),new Error("Failed to check existing coupons");if(ce&&ce.length>0){const It=ce[0];J(!1);const Bt=document.createElement("div");Bt.className="fixed top-4 right-4 bg-blue-600 text-white px-6 py-4 rounded-lg shadow-xl z-50 flex items-center gap-3 animate-fade-in",Bt.innerHTML=`
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div>
            <div class="font-semibold">You already have an active coupon!</div>
            <div class="text-sm opacity-90">Code: ${It.coupon_code}</div>
            <div class="text-xs opacity-75 mt-1">Use this code to get your discount</div>
          </div>
        `,document.body.appendChild(Bt),setTimeout(()=>Bt.remove(),6e3),Se(It.coupon_code),Me(!1);return}const rt=d.email||localStorage.getItem("user_email")||"",Tt=await(await fetch(yt("/api/generate_coupon"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({phone_number:U,session_id:z,email:rt})})).json();if(Tt.success){J(!1);const It=document.createElement("div");It.className="fixed top-4 right-4 bg-green-600 text-white px-6 py-4 rounded-lg shadow-xl z-50 flex items-center gap-3 animate-fade-in",It.innerHTML=`
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
          </svg>
          <div>
            <div class="font-semibold">Discount code sent to WhatsApp!</div>
            <div class="text-sm opacity-90">Code: ${Tt.coupon_code}</div>
          </div>
        `,document.body.appendChild(It),setTimeout(()=>It.remove(),5e3)}else throw new Error(Tt.error||"Failed to send discount code")}catch(ce){console.error("Error sending discount:",ce),alert("Failed to send discount code. Please try again.")}finally{Me(!1)}},Ze=async()=>{if(!_e.trim()){fe("Please enter a coupon code");return}const K=(c==null?void 0:c.sessionId)||localStorage.getItem("session_id");if(!K){fe("Session not found");return}pe(!0),fe("");try{const z=ue?lt+we+ue.discountAmount:lt+we,ce=d.email||localStorage.getItem("user_email")||"",rt=await(await fetch(yt("/api/apply_coupon"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({coupon_code:_e.trim(),session_id:K,total_price:z,user_email:ce})})).json();if(rt.valid){re({code:_e.trim(),discountAmount:rt.discount_amount});const Ve=document.createElement("div");Ve.className="fixed top-4 right-4 bg-green-600 text-white px-6 py-4 rounded-lg shadow-xl z-50";const Tt=l(_e.trim());Ve.textContent=Tt?`🎉 ${Tt}% discount applied!`:"🎉 Discount applied!",document.body.appendChild(Ve),setTimeout(()=>Ve.remove(),3e3)}else fe(rt.error||"Invalid or expired coupon code")}catch(z){console.error("Error applying coupon:",z),fe("Failed to apply coupon. Please try again.")}finally{pe(!1)}},ke=()=>{re(null),Se(""),fe("")},Ce=async()=>{if(!Xe()){alert("Please fill in all required delivery information before proceeding to payment.");return}I(!0);try{const{supabase:K}=await ta(async()=>{const{supabase:bt}=await Promise.resolve().then(()=>Fv);return{supabase:bt}},void 0);let z=(c==null?void 0:c.sessionId)||localStorage.getItem("session_id");(!z||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(z))&&(console.warn("[DeliveryPage] Invalid or missing session_id, generating new one"),z=crypto.randomUUID(),localStorage.setItem("session_id",z)),console.log("[DeliveryPage] Using session_id:",z),console.log("=== RAZORPAY ORDER REQUEST ==="),console.log("Region config currency:",n.currency),console.log("Region config:",n),console.log("Total amount:",Z),console.log("[DeliveryPage] childData being sent:",JSON.stringify(c.childData));const{data:le,error:rt}=await K.functions.invoke("create-razorpay-order",{body:{selectedBook:u,childData:{...c.childData,gender:c.gender||"Not specified"},childImage:c.childImage,sessionId:z,deliveryInfo:{firstName:d.firstName,lastName:d.lastName,email:d.email,phone:d.phone,address:a==="SG"?[d.unitNumber,d.blockNumber,d.streetName,d.buildingName].filter(Boolean).join(", "):d.address,city:a==="SG"?"Singapore":d.city,state:a==="SG"?"":d.state,pincode:d.pincode,country:d.country},totalAmount:Z,shippingCost:we,bookCost:lt,currency:n.currency,couponCode:(ue==null?void 0:ue.code)||null,discountAmount:(ue==null?void 0:ue.discountAmount)||0,originalAmount:ue?lt+we:null,coverType:ie,bookSize:(c==null?void 0:c.bookSize)||"8.75x8.75 inch"}});if(rt)throw console.error("Error from create-razorpay-order function:",rt),new Error("Failed to initiate payment");if(!(le!=null&&le.razorpayOrderId)||!(le!=null&&le.razorpayKeyId))throw new Error("Invalid response from server");console.log("Razorpay order created:",le.razorpayOrderId);const Ve=new URLSearchParams(window.location.search).get("testmode")==="true";if(d.email.trim().toLowerCase()==="a@b.com"&&Ve){console.log("[DeliveryPage] TEST BYPASS: Skipping Razorpay for a@b.com"),O(!0),Be();try{await K.from("payment_info").update({payment_status:"Completed",payment_ref_id:"TEST_BYPASS",updated_at:new Date().toISOString()}).eq("order_id",Number(le.dbOrderId)),await K.from("orders").update({payment_status:"completed",updated_at:new Date().toISOString()}).eq("order_id",Number(le.dbOrderId)),console.log("[DeliveryPage] TEST BYPASS: Payment marked completed")}catch(bt){console.warn("[DeliveryPage] TEST BYPASS: DB update warning:",bt)}try{fetch(yt("/api/preview/generate-full"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:z,regenerate:!1})})}catch(bt){console.warn("[DeliveryPage] TEST BYPASS: Generation trigger failed:",bt)}localStorage.removeItem("pending_order_cover_type"),localStorage.removeItem("pending_order_book_price"),I(!1),t(i("/preview")+`?payment_success=true&sessionId=${z}`);return}if(!window.Razorpay)throw new Error("Razorpay SDK not loaded");const Tt=()=>{const bt=d.phone.replace(/\D/g,"");return a==="SG"?`+65${bt}`:a==="US"?`+1${bt}`:`+91${bt}`},It={key:le.razorpayKeyId,amount:le.amount,currency:le.currency,name:"TalesBerry",description:`${c.childData.name}'s ${u.title}`,order_id:le.razorpayOrderId,prefill:{name:`${d.firstName} ${d.lastName}`,email:d.email,contact:Tt()},theme:{color:"#8B5CF6"},handler:async function(bt){console.log("Payment successful:",bt),O(!0);try{const{error:me}=await K.functions.invoke("verify-razorpay-payment",{body:{razorpay_order_id:bt.razorpay_order_id,razorpay_payment_id:bt.razorpay_payment_id,razorpay_signature:bt.razorpay_signature,dbOrderId:le.dbOrderId}});if(me)throw console.error("Payment verification failed:",me),new Error("Payment verification failed");console.log("[DeliveryPage] Payment verified successfully");try{await K.functions.invoke("create-user-account-from-order",{body:{orderId:Number(le.dbOrderId)}}),console.log("[DeliveryPage] User account created/updated")}catch(Zt){console.warn("[DeliveryPage] create-user-account warning:",Zt)}try{await K.from("orders").update({payment_status:"completed",updated_at:new Date().toISOString()}).eq("order_id",Number(le.dbOrderId)),console.log("[DeliveryPage] Order status updated to completed")}catch(Zt){console.warn("[DeliveryPage] Order update warning:",Zt)}try{console.log("[DeliveryPage] Triggering full generation for session:",z),fetch(yt("/api/preview/generate-full"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:z,regenerate:!1})})}catch(Zt){console.warn("[DeliveryPage] Generation trigger failed (non-blocking):",Zt)}localStorage.removeItem("pending_order_cover_type"),localStorage.removeItem("pending_order_book_price"),console.log("[DeliveryPage] Cleared pending order data from localStorage"),t(i("/preview")+`?payment_success=true&sessionId=${z}`)}catch(me){console.error("Error verifying payment:",me),alert("Payment verification failed. Please contact support.")}},modal:{ondismiss:function(){console.log("Payment modal closed by user")}}};Be(),new window.Razorpay(It).open(),I(!1)}catch(K){console.error("Error creating order:",K),alert(`Failed to create order: ${K.message}`),I(!1)}};if(s)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 to-secondary-50 flex items-center justify-center",children:e.jsx("div",{className:"text-center",children:e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-4",children:"Loading..."})})});if(E)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 to-secondary-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-16 w-16 border-b-4 border-primary-600 mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-2",children:"Payment Successful!"}),e.jsx("p",{className:"text-gray-600",children:"Preparing your personalized book..."})]})});if(!u)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 to-secondary-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-4",children:"No Order Found"}),e.jsx("button",{onClick:()=>t(i("/books")),className:"px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors",children:"Browse Books"})]})});const B=K=>{const{name:z,value:ce}=K.target;let le=ce;if((z==="firstName"||z==="lastName")&&(le=ce.replace(/[^a-zA-Z\s]/g,"")),z==="phone"){const rt=a==="SG"?8:10;le=ce.replace(/\D/g,"").slice(0,rt)}z==="pincode"&&(le=ce.replace(/\D/g,"").slice(0,6),a==="SG"&&x(le)),a==="SG"&&(z==="blockNumber"||z==="streetName"||z==="buildingName")&&b(),h(rt=>({...rt,[z]:le})),y[z]&&S(rt=>({...rt,[z]:""})),z==="pincode"&&a==="SG"&&j()},st=()=>{t(i("/print-options"),{state:{selectedBook:c==null?void 0:c.selectedBook,childData:c==null?void 0:c.childData,childImage:c==null?void 0:c.childImage,sessionId:c==null?void 0:c.sessionId,gender:c==null?void 0:c.gender}})},Ye=()=>{if(c!=null&&c.coverType)return c.coverType;const K=localStorage.getItem("pending_order_cover_type");return K==="softcover"||K==="hardcover"?K:"hardcover"},Y=()=>{if(c!=null&&c.bookPrice)return c.bookPrice;const K=localStorage.getItem("pending_order_book_price");return K?parseFloat(K):null},ie=Ye(),He=ie==="softcover",lt=Y()||(He?n.softCoverPrice:n.bookPrice),gt=He?a==="IN"?1699:34.99:a==="IN"?2199:54.99,we=n.shippingPrice,Mt=lt+we,Z=ue?Mt-ue.discountAmount:Mt,he=(u==null?void 0:u.title)||((Pe=c==null?void 0:c.selectedBook)==null?void 0:Pe.title)||"",Be=()=>{try{sessionStorage.setItem("purchase_book_type",ie),sessionStorage.setItem("purchase_book_price",String(Z)),sessionStorage.setItem("purchase_book_name",he)}catch{}},Fe=c.childData.name?`${c.childData.name}'s ${o(u.title)}`:o(u.title);return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(Yt,{}),e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20am%20on%20the%20checkout%20page%20and%20need%20some%20help%21",target:"_blank",rel:"noopener noreferrer","aria-label":"24x7 WhatsApp Support",className:`fixed bottom-24 right-4 z-30 lg:bottom-4 inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
          px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,"data-track":"delivery_whatsapp_support",children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),e.jsx("div",{className:"bg-white border-b",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-2 pb-0 md:py-6",children:[e.jsx("div",{className:"flex items-center justify-between mb-4 md:mb-4",children:e.jsxs("button",{onClick:st,className:"flex items-center text-gray-600 hover:text-gray-800 transition-colors",children:[e.jsx(Ut,{className:"w-5 h-5 mr-1"}),"Back to Print Options"]})}),e.jsx("div",{className:"hidden md:flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center space-x-8",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-primary-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Book Details"})]}),e.jsx("div",{className:"w-16 h-1 bg-primary-600 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-primary-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Personalization"})]}),e.jsx("div",{className:"w-16 h-1 bg-primary-600 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-primary-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Preview"})]}),e.jsx("div",{className:"w-16 h-1 bg-primary-600 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-primary-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"4"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-primary-600",children:"Checkout"})]})]})})]})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-4 pb-8 lg:py-8",children:e.jsxs("div",{className:"flex flex-col lg:grid lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"order-0 lg:hidden",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-900 mb-3 px-1",children:a==="SG"?"Loved by families across Singapore and around the world":"Customer Love 💖"}),a==="SG"?e.jsx(_l,{}):e.jsx(kl,{})]}),e.jsx("div",{className:"order-1 lg:order-none lg:col-span-1 lg:col-start-3 lg:row-start-1",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-3 lg:p-6 lg:sticky lg:top-8",children:[e.jsx("h2",{className:"text-lg lg:text-xl font-semibold text-gray-900 mb-3 lg:mb-6",children:"Order Summary"}),e.jsxs("div",{className:"space-y-2 lg:space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-start gap-3 pb-2 lg:pb-4 border-b",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 leading-tight mt-1",children:Fe}),e.jsxs("p",{className:"text-sm text-gray-500 mt-1",children:[He?"Soft Cover":"Hard Cover"," • ",(c==null?void 0:c.bookSize)||"8.75x8.75 inch"]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-gray-500 line-through text-sm",children:Gt(a,gt)}),e.jsx("div",{className:"text-sm text-gray-900",children:Gt(a,lt)})]})]}),e.jsx("div",{className:"space-y-1 py-2 lg:space-y-2 lg:py-4",children:e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Shipping"}),e.jsx("span",{className:"text-gray-900",children:Gt(a,we)})]})}),ue?e.jsx("div",{className:"border-t pt-2 lg:pt-3",children:e.jsxs("div",{className:"flex justify-between items-center bg-green-50 border border-green-200 rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-green-900",children:ue.code}),e.jsx("div",{className:"text-xs text-green-700",children:l(ue.code)?`${l(ue.code)}% discount applied`:"Discount applied"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-900",children:["-",Gt(a,ue.discountAmount)]}),e.jsx("button",{onClick:ke,className:"text-red-600 hover:text-red-700 text-xs underline",children:"Remove"})]})]})}):e.jsxs("div",{className:"border-t pt-2 lg:pt-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:_e,onChange:K=>Se(K.target.value.toUpperCase()),placeholder:"Discount code",className:"flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500"}),e.jsx("button",{onClick:Ze,disabled:qe,className:"px-4 py-2 bg-primary-600 text-white rounded-lg text-sm font-medium hover:bg-primary-700 disabled:opacity-50",children:qe?"Applying...":"Apply"})]}),Ne&&e.jsx("p",{className:"text-red-500 text-xs mt-1",children:Ne})]}),e.jsx("div",{className:"border-t pt-2 lg:pt-3",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-lg font-semibold text-gray-900",children:"Total"}),e.jsxs("div",{className:"text-right",children:[ue&&e.jsx("div",{className:"text-sm text-gray-500 line-through",children:Gt(a,Mt)}),e.jsx("span",{className:"text-xl font-bold text-gray-900",children:Gt(a,Z)})]})]})})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 mb-3 mt-3 lg:mb-6 lg:mt-6",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(ya,{className:"w-4 h-4 text-blue-600 mr-2"}),e.jsx("span",{className:"text-xs text-blue-800",children:"Estimate delivery: We ship within 7-10 business days"})]})})]})}),e.jsx("div",{className:"order-2 lg:order-none lg:col-span-2 lg:col-start-1 lg:row-start-1",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-4 md:p-6",children:[e.jsx("h1",{className:"text-lg lg:text-xl font-semibold text-gray-900 mb-6",children:"Delivery Information"}),e.jsxs("div",{className:"flex items-center mb-4 md:mb-6",children:[e.jsx(xa,{className:"w-5 h-5 md:w-6 md:h-6 text-primary-600 mr-2"}),e.jsx("h2",{className:"text-lg md:text-xl font-semibold text-gray-900",children:"Shipping Address"})]}),e.jsxs("form",{className:"space-y-4 md:space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-2 gap-3 md:gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:[e.jsx(Gi,{className:"w-3 h-3 md:w-4 md:h-4 inline mr-1"}),"First Name *"]}),e.jsx("input",{type:"text",name:"firstName",value:d.firstName,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.firstName?"border-red-500":"border-gray-300"}`,placeholder:"First name"}),y.firstName&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.firstName})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"Last Name *"}),e.jsx("input",{type:"text",name:"lastName",value:d.lastName,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.lastName?"border-red-500":"border-gray-300"}`,placeholder:"Last name"}),y.lastName&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.lastName})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:[e.jsx(Ma,{className:"w-3 h-3 md:w-4 md:h-4 inline mr-1"}),"Email Address *"]}),e.jsx("input",{type:"email",name:"email",value:d.email,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.email?"border-red-500":"border-gray-300"}`,placeholder:"example@gmail.com"}),y.email&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.email})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:[e.jsx(On,{className:"w-3 h-3 md:w-4 md:h-4 inline mr-1"}),"Phone Number *"]}),e.jsxs("div",{className:"flex",children:[e.jsx("span",{className:"flex items-center justify-center px-3 py-2 md:px-4 md:py-3 border border-r-0 rounded-l-lg text-sm md:text-base bg-gray-50 border-gray-300 text-gray-700 font-medium",children:a==="SG"?"+65":a==="US"?"+1":"+91"}),e.jsx("input",{type:"tel",name:"phone",value:d.phone,onChange:B,maxLength:d.phoneCountryCode==="+65"?8:10,className:`flex-1 px-3 py-2 md:px-4 md:py-3 border rounded-r-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.phone?"border-red-500":"border-gray-300"}`,placeholder:d.phoneCountryCode==="+65"?"8xxx xxxx":"98xxxxxxxx"})]}),y.phone&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.phone})]})]}),a==="SG"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:[e.jsx(xa,{className:"w-3 h-3 md:w-4 md:h-4 inline mr-1"}),"Postal Code *"]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"text",name:"pincode",value:d.pincode,onChange:B,maxLength:6,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base pr-10 ${g?"border-red-300":v?"border-green-300 bg-green-50":"border-gray-300"}`,placeholder:"Enter 6-digit postal code"}),m&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsx(Ue,{className:"w-4 h-4 animate-spin text-gray-400"})}),v&&!m&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsx(Sa,{className:"w-4 h-4 text-green-500"})})]}),g&&e.jsx("p",{className:"text-amber-600 text-xs md:text-sm mt-1",children:g}),v&&e.jsx("p",{className:"text-green-600 text-xs mt-1",children:"Address found and auto-filled"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"Block Number"}),e.jsx("input",{type:"text",name:"blockNumber",value:d.blockNumber,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${v&&d.blockNumber?"bg-green-50 border-green-200":"border-gray-300"}`,placeholder:"Block no."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"Street Name *"}),e.jsx("input",{type:"text",name:"streetName",value:d.streetName,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${v&&d.streetName?"bg-green-50 border-green-200":"border-gray-300"}`,placeholder:"Street name"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"Building Name"}),e.jsx("input",{type:"text",name:"buildingName",value:d.buildingName,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${v&&d.buildingName?"bg-green-50 border-green-200":"border-gray-300"}`,placeholder:"Building name (optional)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"Unit Number *"}),e.jsx("input",{type:"text",name:"unitNumber",value:d.unitNumber,onChange:B,className:"w-full px-3 py-2 md:px-4 md:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base",placeholder:"e.g. #12-34"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"City"}),e.jsx("input",{type:"text",value:"Singapore",disabled:!0,className:"w-full px-3 py-2 md:px-4 md:py-3 border border-gray-200 rounded-lg bg-gray-100 cursor-not-allowed text-gray-600 text-sm md:text-base"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"Country"}),e.jsx("input",{type:"text",value:"Singapore",disabled:!0,className:"w-full px-3 py-2 md:px-4 md:py-3 border border-gray-200 rounded-lg bg-gray-100 cursor-not-allowed text-gray-600 text-sm md:text-base"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:[e.jsx(xa,{className:"w-3 h-3 md:w-4 md:h-4 inline mr-1"}),"Address *"]}),e.jsx("textarea",{name:"address",value:d.address,onChange:K=>B(K),className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.address?"border-red-500":"border-gray-300"}`,rows:3,placeholder:"Street address, apartment, suite, etc."}),y.address&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.address})]}),a==="IN"&&e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"City *"}),e.jsx("input",{type:"text",name:"city",value:d.city,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.city?"border-red-500":"border-gray-300"}`,placeholder:"City"}),y.city&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.city})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"State *"}),e.jsx("input",{type:"text",name:"state",value:d.state,onChange:B,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.state?"border-red-500":"border-gray-300"}`,placeholder:"State"}),y.state&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.state})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:[n.postalCodeLabel," *"]}),e.jsx("input",{type:"text",name:"pincode",value:d.pincode,onChange:B,maxLength:6,className:`w-full px-3 py-2 md:px-4 md:py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm md:text-base ${y.pincode?"border-red-500":"border-gray-300"}`,placeholder:n.postalCodePlaceholder}),y.pincode&&e.jsx("p",{className:"text-red-500 text-xs md:text-sm mt-1",children:y.pincode})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs md:text-sm font-medium text-gray-700 mb-1 md:mb-2",children:"Country *"}),e.jsx("input",{type:"text",name:"country",value:d.country,disabled:!0,className:"w-full px-3 py-2 md:px-4 md:py-3 border border-gray-300 rounded-lg bg-gray-100 cursor-not-allowed text-sm md:text-base"})]})]})]})]}),e.jsxs("div",{className:"hidden lg:block bg-white rounded-xl shadow-lg border-2 border-primary-100 p-6 text-center mt-6",children:[e.jsx("h3",{className:"text-lg lg:text-xl font-semibold text-gray-900 mb-3",children:"Complete Your Order"}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4",children:e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(ya,{className:"w-4 h-4 text-blue-600 mr-2"}),e.jsx("span",{className:"text-xs text-blue-800",children:"Estimate delivery: We ship within 7-10 business days"})]})}),e.jsx("p",{className:"text-gray-600 mb-4 text-sm",children:"Secure payment powered by Razorpay"}),Xe()?e.jsx("div",{className:"w-full",children:e.jsx("button",{onClick:Ce,disabled:T,className:"w-full bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white font-bold py-3 px-6 rounded-xl text-base shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105 disabled:opacity-70 disabled:cursor-not-allowed disabled:transform-none","data-gtm":"delivery_pay_now","data-track":"delivery_pay_now",children:T?e.jsxs("span",{className:"flex items-center justify-center",children:[e.jsxs("svg",{className:"animate-spin -ml-1 mr-3 h-5 w-5 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Processing..."]}):`Pay ${Gt(a,Z)} Now`})}):e.jsx("div",{className:"w-full",children:e.jsx("button",{onClick:()=>alert("Please fill in all required delivery information above before proceeding to payment."),className:"w-full bg-gray-400 text-white font-bold py-3 px-6 rounded-xl text-base cursor-not-allowed",disabled:!0,children:"Complete Delivery Info First"})}),e.jsxs("div",{className:"mt-4 space-y-1",children:[e.jsxs("p",{className:"text-xs text-gray-500 flex items-center justify-start",children:[e.jsx("svg",{className:"w-3 h-3 mr-1 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 616 0z",clipRule:"evenodd"})}),"256-bit SSL encrypted payment"]}),e.jsx("p",{className:"text-xs text-gray-500 font-bold",children:"No returns on personalised books"})]})]})]})}),e.jsx("div",{className:"order-3 lg:hidden",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-6",children:[e.jsx("h2",{className:"text-lg lg:text-xl font-semibold text-gray-900 mb-6",children:"Complete Your Order"}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 mb-6 mt-6",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(ya,{className:"w-4 h-4 text-blue-600 mr-2"}),e.jsx("span",{className:"text-xs text-blue-800",children:"Estimate delivery: We ship within 7-10 business days"})]})}),e.jsx("p",{className:"text-gray-600 mb-4 text-sm",children:"Secure payment powered by Razorpay"}),Xe()?e.jsx("div",{className:"w-full",children:e.jsx("button",{onClick:Ce,disabled:T,className:"w-full bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white font-bold py-3 px-6 rounded-xl text-base shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105 disabled:opacity-70 disabled:cursor-not-allowed disabled:transform-none","data-gtm":"delivery_pay_now","data-track":"delivery_pay_now",children:T?e.jsxs("span",{className:"flex items-center justify-center",children:[e.jsxs("svg",{className:"animate-spin -ml-1 mr-3 h-5 w-5 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Processing..."]}):`Pay ${Gt(a,Z)} Now`})}):e.jsx("div",{className:"w-full",children:e.jsx("button",{onClick:()=>alert("Please fill in all required delivery information above before proceeding to payment."),className:"w-full bg-gray-400 text-white font-bold py-3 px-6 rounded-xl text-base cursor-not-allowed",disabled:!0,children:"Complete Delivery Info First"})}),e.jsxs("div",{className:"mt-4 space-y-1",children:[e.jsxs("p",{className:"text-xs text-gray-500 flex items-center justify-start",children:[e.jsx("svg",{className:"w-3 h-3 mr-1 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z",clipRule:"evenodd"})}),"256-bit SSL encrypted payment"]}),e.jsx("p",{className:"text-xs text-gray-500 font-bold",children:"No returns on personalised books"})]})]})})]})}),V&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e.jsx("div",{className:"absolute inset-0 bg-black bg-opacity-50 backdrop-blur-sm",onClick:()=>!Te&&J(!1)}),e.jsxs("div",{className:"relative bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 p-8 z-10",children:[e.jsx("button",{onClick:()=>!Te&&J(!1),className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600",disabled:Te,children:e.jsx(Cs,{className:"w-6 h-6"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("svg",{className:"w-8 h-8 text-green-600",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})})}),e.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Get Your 5% Discount"}),e.jsx("p",{className:"text-gray-600 text-sm",children:"Enter your WhatsApp number to receive your discount code, eBook PDF, and connect with our support team."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"WhatsApp Number *"}),e.jsx("input",{type:"tel",value:U,onChange:K=>{const z=a==="SG"?8:10,ce=K.target.value.replace(/\D/g,"");ce.length<=z&&Ge(ce)},placeholder:a==="SG"?"81234567":"9876543210",maxLength:a==="SG"?8:10,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500",disabled:Te}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"10-digit mobile number (no country code)"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>J(!1),disabled:Te,className:"flex-1 px-6 py-3 border-2 border-gray-300 text-gray-700 font-semibold rounded-xl hover:bg-gray-50 transition-all duration-300 disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:ft,disabled:U.length!==10||Te,className:"flex-1 px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white font-semibold rounded-xl hover:from-green-700 hover:to-emerald-700 transition-all duration-300 transform hover:scale-105 shadow-lg disabled:opacity-50 disabled:transform-none flex items-center justify-center gap-2",children:Te?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),"Sending..."]}):"Send My Discount"})]})]})]})]})]})},nj=()=>{var T,I;const r=Jt(),t=_t(),{region:s,config:a,buildLink:n}=ht(),i=r.state,[o,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState(!1),[m,g]=p.useState(!1),f=p.useRef({hardcover:null,softcover:null});p.useEffect(()=>{const E=()=>g(window.innerWidth<768);return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),p.useEffect(()=>{window.scrollTo(0,0)},[]);const v=[{id:"hardcover",title:"Hard Cover",description:["Premium laminated hard cover binding","Thick 300 GSM cover page with hard cover for durability","Inner pages of 220 GSM.","Lasts for years of reading","Perfect for gifting"],video:"https://d38picfcqfcfl0.cloudfront.net/website_media/hardcover.mp4",price:a.bookPrice},{id:"softcover",title:"Soft Cover",description:["Flexible soft cover binding","Lightweight and easy to hold","Great for everyday reading with 220 GSM inner pages","Budget-friendly option"],video:"https://d38picfcqfcfl0.cloudfront.net/website_media/softcover.mp4",price:a.softCoverPrice}],x=E=>{const O=f.current[E];O&&m&&(c===E?(O.pause(),u(null)):(Object.entries(f.current).forEach(([V,J])=>{V!==E&&J&&J.pause()}),O.currentTime=0,O.muted=!0,O.play().catch(console.error),u(E)))},j=E=>{if(m)return;const O=f.current[E];O&&(O.currentTime=0,O.muted=!0,O.play().catch(console.error),u(E))},b=E=>{if(m)return;const O=f.current[E];O&&(O.pause(),O.currentTime=0),c===E&&u(null)},y=()=>{if(!o||!i)return;h(!0);const E=v.find(O=>O.id===o);t(n("/delivery"),{state:{selectedBook:i.selectedBook,childData:i.childData,childImage:i.childImage,sessionId:i.sessionId||localStorage.getItem("session_id"),gender:i.gender,coverType:o,bookSize:"8.75x8.75 inch",bookPrice:(E==null?void 0:E.price)||a.bookPrice}})},S=()=>{var E;(E=i==null?void 0:i.selectedBook)!=null&&E.id?t(n(`/preview?sessionId=${i.sessionId}`),{state:{selectedBook:i.selectedBook,childData:i.childData,childImage:i.childImage,sessionId:i.sessionId,gender:i.gender}}):t(-1)};return i!=null&&i.selectedBook?e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 via-secondary-50 to-primary-100 pb-32 md:pb-12",children:[e.jsx(Yt,{}),e.jsxs("div",{className:"max-w-4xl mx-auto px-4",children:[e.jsxs("button",{onClick:S,className:"flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6 transition-colors",children:[e.jsx(Ut,{className:"w-5 h-5"}),e.jsx("span",{children:"Back to Preview"})]}),e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-2xl md:text-4xl font-bold text-gray-900 mb-3",children:"Would you like a HardCover Book or a SoftCover book?"}),e.jsx("p",{className:"text-lg text-gray-600",children:"See below 'sample videos' to decide."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-6 mb-8",children:v.map(E=>e.jsxs("div",{onClick:()=>{var O;l(E.id),ww(E.id,E.price,((O=i==null?void 0:i.selectedBook)==null?void 0:O.title)||void 0,localStorage.getItem("session_id")||void 0)},onMouseEnter:()=>j(E.id),onMouseLeave:()=>b(E.id),className:`
                relative bg-white rounded-2xl overflow-hidden cursor-pointer transition-all duration-300 shadow-lg
                ${o===E.id?"ring-4 ring-primary-500 shadow-xl transform scale-[1.02]":"hover:shadow-xl hover:scale-[1.01]"}
              `,children:[e.jsxs("div",{className:"relative aspect-square bg-gray-100 overflow-hidden",onClick:O=>{m&&(O.stopPropagation(),x(E.id))},children:[e.jsx("video",{ref:O=>{f.current[E.id]=O},className:"w-full h-full object-cover",src:E.video,muted:!0,loop:!0,playsInline:!0,preload:"metadata"}),m&&c!==E.id&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20",children:e.jsx("div",{className:"w-16 h-16 bg-white/90 rounded-full flex items-center justify-center",children:e.jsx("svg",{className:"w-8 h-8 text-primary-600 ml-1",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})}),m&&c===E.id&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/60 text-white text-xs px-2 py-1 rounded",children:"Tap to pause"})]}),e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:`
                      w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all flex-shrink-0
                      ${o===E.id?"border-primary-500 bg-primary-500":"border-gray-300 bg-white"}
                    `,children:o===E.id&&e.jsx(Sa,{className:"w-4 h-4 text-white"})}),e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:E.title}),e.jsx("span",{className:`ml-auto flex-shrink-0 px-2.5 py-0.5 rounded-full text-xs font-semibold ${E.id==="hardcover"?"bg-amber-100 text-amber-700":"bg-emerald-100 text-emerald-700"}`,children:E.id==="hardcover"?"Premium Quality":"Value Pick"})]}),e.jsx("ul",{className:"space-y-2 mb-4",children:E.description.map((O,V)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-gray-600",children:[e.jsx(Sa,{className:"w-4 h-4 text-green-500 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:O})]},V))}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary-600",children:Gt(s,E.price)}),e.jsx("span",{className:"text-sm text-gray-500",children:"+ shipping"})]})]})]},E.id))}),e.jsxs("div",{className:"hidden md:block text-center",children:[e.jsx("button",{onClick:y,disabled:!o||d,className:`
              px-12 py-4 rounded-xl font-semibold text-lg transition-all duration-300 shadow-lg
              ${o?"bg-gradient-to-r from-primary-600 to-secondary-600 text-white hover:from-primary-700 hover:to-secondary-700 transform hover:scale-105":"bg-gray-200 text-gray-500 cursor-not-allowed"}
            `,children:d?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),"Processing..."]}):"Place Order"}),!o&&e.jsx("p",{className:"text-sm text-gray-500 mt-3",children:"Please select a print option to continue"})]})]}),e.jsxs("div",{className:"fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 md:hidden z-50 shadow-[0_-4px_20px_rgba(0,0,0,0.1)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Selected:"}),e.jsx("p",{className:"font-semibold text-gray-900",children:o?(T=v.find(E=>E.id===o))==null?void 0:T.title:"None selected"})]}),o&&e.jsx("p",{className:"text-xl font-bold text-primary-600",children:Gt(s,((I=v.find(E=>E.id===o))==null?void 0:I.price)||0)})]}),e.jsx("button",{onClick:y,disabled:!o||d,className:`
            w-full py-4 rounded-xl font-semibold text-lg transition-all
            ${o?"bg-gradient-to-r from-primary-600 to-secondary-600 text-white":"bg-gray-200 text-gray-500 cursor-not-allowed"}
          `,children:d?e.jsxs("span",{className:"flex items-center justify-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),"Processing..."]}):"Place Order"})]})]}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 via-secondary-50 to-primary-100 pt-20 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800 mb-4",children:"Session expired"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Please start the book creation process again."}),e.jsx("button",{onClick:()=>t(n("/")),className:"px-6 py-3 bg-primary-600 text-white rounded-xl hover:bg-primary-700 transition-colors",children:"Go to Home"})]})})},ij=(r,t="IN")=>Ss[t].shippingPrice,oj=()=>{var f,v;const r=Jt(),t=_t(),{buildLink:s}=ht(),a=r.state,n=x=>{if(!x)return x;let j=x.trim();const b=/^([A-Za-z]+)['']s\s+/;for(;b.test(j);)j=j.replace(b,"");if(/^[A-Za-z]+\s+and\s+/i.test(j)){const y=j.split(/\s+and\s+/i);y.length>1&&(j="and "+y.slice(1).join(" and "))}return j||x};if(p.useEffect(()=>{(()=>{if(document.getElementById("razorpay-embed-btn-js")){window.__rzp__&&window.__rzp__.init&&window.__rzp__.init();return}const j=document.createElement("script");j.id="razorpay-embed-btn-js",j.src="https://cdn.razorpay.com/static/embed_btn/bundle.js",j.defer=!0,j.onload=()=>{console.log("Razorpay script loaded successfully"),window.__rzp__&&window.__rzp__.init&&window.__rzp__.init()},j.onerror=()=>{console.error("Failed to load Razorpay script")},document.body.appendChild(j)})()},[]),!(a!=null&&a.selectedBook))return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 to-secondary-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-4",children:"Session Expired"}),e.jsx("button",{onClick:()=>t(s("/books")),className:"px-6 py-3 bg-black text-white rounded-lg hover:bg-gray-800 transition-colors",children:"Browse Books"})]})});const{selectedBook:i,childData:o,deliveryInfo:l}=a,u=(((f=i==null?void 0:i.pricing)==null?void 0:f.large)||((v=i==null?void 0:i.pricing)==null?void 0:v.small)||{price:1,originalPrice:1}).price,d=l.state?ij(l.state):0,m=u+d+0,g=()=>{t(s("/delivery"),{state:a})};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 to-secondary-50",children:[e.jsx(Yt,{}),e.jsx("div",{className:"bg-white shadow-sm border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-16",children:[e.jsxs("div",{className:"flex items-center space-x-8",children:[e.jsx("h1",{className:"text-xl font-semibold text-gray-800",children:"Home"}),e.jsxs("nav",{className:"flex space-x-8",children:[e.jsx("span",{className:"text-gray-600",children:"Books"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("span",{className:"text-gray-600",children:"My Books"}),e.jsx("span",{className:"ml-1 w-5 h-5 bg-primary-600 text-white text-xs rounded-full flex items-center justify-center",children:"3"})]}),e.jsx("span",{className:"text-gray-600",children:"Support"})]})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx("span",{className:"text-sm text-gray-600",children:"🇮🇳 INR"})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(vu,{className:"w-5 h-5"}),e.jsx("span",{className:"w-5 h-5 bg-primary-600 text-white text-xs rounded-full flex items-center justify-center",children:"1"})]}),e.jsx("span",{className:"text-gray-600",children:"User"})]})]})})}),e.jsx("div",{className:"bg-white border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center space-x-8",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-green-500 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-green-600",children:"Cart"})]}),e.jsx("div",{className:"w-16 h-1 bg-green-500 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-green-500 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-green-600",children:"Delivery"})]}),e.jsx("div",{className:"w-16 h-1 bg-primary-600 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-primary-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"3"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-primary-600",children:"Checkout"})]})]})})})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[e.jsxs("button",{onClick:g,className:"flex items-center text-black hover:text-gray-700 mb-6",children:[e.jsx(Ut,{className:"w-5 h-5 mr-1"}),"Back to Delivery"]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx("div",{children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-6",children:"Delivery Information"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"font-medium text-gray-900",children:[l.firstName," ",l.lastName]}),e.jsx("p",{className:"text-gray-600",children:l.address}),l.apartment&&e.jsx("p",{className:"text-gray-600",children:l.apartment}),e.jsxs("p",{className:"text-gray-600",children:[l.city,", ",l.state," ",l.pincode]}),e.jsx("p",{className:"text-gray-600",children:l.country}),e.jsx("p",{className:"text-gray-600",children:l.phone}),e.jsx("p",{className:"text-gray-600",children:l.email})]}),e.jsx("button",{onClick:g,className:"mt-4 text-black hover:text-gray-700 text-sm font-medium",children:"Edit Delivery Information"})]})}),e.jsx("div",{children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-6",children:"Order Summary"}),e.jsxs("div",{className:"flex items-start space-x-4 mb-6",children:[e.jsx("div",{className:"w-16 h-20 flex-shrink-0 rounded-lg overflow-hidden",children:e.jsx("img",{src:i.images[0]?`/${i.images[0].split("/")[1]}/front.${i.images[0].split(".")[1]||"jpeg"}`:"/placeholder.md",alt:i.title,className:"w-full h-full object-cover",onError:x=>{x.currentTarget.src="/placeholder.md"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium text-gray-900 text-sm",children:o!=null&&o.name?`${o.name}'s ${n(i.title)}`:i.title}),e.jsx("p",{className:"text-xs text-gray-600 mt-1",children:"Hardcover • English • Qty: 1"})]})]}),e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Subtotal"}),e.jsxs("span",{className:"text-gray-900",children:["₹",u]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Shipping Charges (Basis Your Address)"}),e.jsxs("span",{className:"text-gray-900",children:["₹",d]})]}),e.jsx("div",{className:"border-t pt-2",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-base font-semibold text-gray-900",children:"Total"}),e.jsxs("span",{className:"text-lg font-bold text-primary-600",children:["₹",m]})]})})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(ya,{className:"w-4 h-4 text-blue-600 mr-2"}),e.jsx("span",{className:"text-xs text-blue-800",children:"Estimated delivery: 7-10 business days"})]})})]})})]}),e.jsx("div",{className:"mt-12 max-w-md mx-auto",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-lg border-2 border-primary-100 p-8 text-center",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Complete Your Order"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Secure payment powered by Razorpay"}),e.jsx("div",{className:"w-full",children:e.jsx("div",{className:"razorpay-embed-btn w-full","data-url":"https://rzp.io/rzp/19jIoKH","data-text":"Pay Now","data-color":"#6366F1","data-size":"large",children:e.jsxs("button",{className:"w-full bg-black hover:bg-gray-800 text-white font-bold py-4 px-8 rounded-xl text-lg shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105",children:["Pay ₹",m," Now"]})})}),e.jsxs("div",{className:"mt-6 space-y-2",children:[e.jsxs("p",{className:"text-xs text-gray-500 flex items-center justify-center",children:[e.jsx("svg",{className:"w-4 h-4 mr-1 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z",clipRule:"evenodd"})}),"256-bit SSL encrypted payment"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"No returns on personalized books"})]})]})})]})]})},lj=()=>{const r=_t(),[t]=To(),{buildLink:s}=ht(),[a,n]=p.useState(3),[i,o]=p.useState(t.get("razorpay_payment_id")||t.get("payment_id")||t.get("razorpay_payment_link_id")),[l,c]=p.useState(t.get("order_id")||t.get("razorpay_payment_link_reference_id")||t.get("razorpay_order_id")||t.get("payment_link_reference_id"));return p.useEffect(()=>{(async()=>{let d=t.get("razorpay_payment_id")||t.get("payment_id")||t.get("razorpay_payment_link_id")||void 0,h=t.get("order_id")||t.get("razorpay_payment_link_reference_id")||t.get("razorpay_order_id")||t.get("payment_link_reference_id")||void 0,m=t.get("session_id")||localStorage.getItem("session_id")||void 0;if(!h&&m){const{data:g}=await de.from("orders").select("order_id").eq("session_id",m).order("created_at",{ascending:!1}).limit(1).maybeSingle();g!=null&&g.order_id&&(h=String(g.order_id))}if(!h){const{data:g}=await de.from("orders").select("order_id, session_id").order("created_at",{ascending:!1}).limit(1).maybeSingle();g&&(h=String(g.order_id),m=m||g.session_id)}if(h&&c(h),d&&o(d),!h){console.error("[PaymentSuccess] Missing order ID after all fallbacks");return}try{try{await de.functions.invoke("verify-payment",{body:{orderId:Number(h),paymentId:d}})}catch(x){console.warn("[PaymentSuccess] verify-payment function warning:",x)}try{await de.functions.invoke("create-user-account-from-order",{body:{orderId:Number(h)}})}catch(x){console.warn("[PaymentSuccess] create-user-account-from-order warning:",x)}const{error:g}=await de.from("orders").update({payment_status:"completed",updated_at:new Date().toISOString()}).eq("order_id",Number(h));if(g&&console.warn("[PaymentSuccess] Order update warning:",g),!m){const{data:x}=await de.from("orders").select("session_id").eq("order_id",Number(h)).maybeSingle();m=(x==null?void 0:x.session_id)||void 0}const f=()=>{m?(localStorage.removeItem(`preview_checked_${m}`),localStorage.removeItem(`preview_payment_${m}`),console.log("[PaymentSuccess] Cleared stale payment flags for session:",m),console.log("[PaymentSuccess] Redirecting with sessionId and payment_success flag"),r(s(`/preview?payment_success=true&sessionId=${m}`))):(console.log("[PaymentSuccess] No sessionId found, redirecting to login"),r(s("/login")))},v=setInterval(()=>{n(x=>x<=1?(clearInterval(v),f(),0):x-1)},1e3)}catch(g){console.error("[PaymentSuccess] Error verifying payment:",g)}})()},[r,t,s]),e.jsxs("div",{className:"min-h-screen bg-white flex items-center justify-center",children:[e.jsx(Yt,{}),e.jsx("div",{className:"max-w-md mx-auto text-center p-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-8",children:[e.jsx("div",{className:"mx-auto w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mb-6",children:e.jsx(Ro,{className:"w-12 h-12 text-green-600"})}),e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Payment Successful!"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Thank you for your payment. Your order has been confirmed and you can now continue creating your personalized book."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"Payment ID"}),e.jsx("p",{className:"font-mono text-sm",children:i||"N/A"})]}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"Order ID"}),e.jsx("p",{className:"font-mono text-sm",children:l||"N/A"})]}),e.jsx("div",{className:"text-center text-gray-600",children:e.jsxs("p",{children:["Redirecting to your book preview in ",a," seconds..."]})}),e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsx("p",{className:"text-sm text-blue-800",children:"📚 Payment successful! You now have access to all pages. You can generate and regenerate any page of your personalized book."})})]})]})})]})},cj=()=>{const r=_t(),[t]=To(),{buildLink:s}=ht(),[a,n]=p.useState(5),i=t.get("order_id"),o=t.get("error");p.useEffect(()=>{const d=setInterval(()=>{n(h=>h<=1?(clearInterval(d),r(s("/delivery")),0):h-1)},1e3);return()=>clearInterval(d)},[r,s]);const l=()=>{r(s("/delivery"))},c=()=>{r(s("/"))},u=()=>{const d=t.get("session_id")||localStorage.getItem("session_id");r(s(d?`/preview?sessionId=${d}`:"/"))};return e.jsxs("div",{className:"min-h-screen bg-white flex items-center justify-center",children:[e.jsx(Yt,{}),e.jsx("div",{className:"max-w-md mx-auto text-center p-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-8",children:[e.jsx("div",{className:"mx-auto w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-6",children:e.jsx(Yp,{className:"w-12 h-12 text-red-600"})}),e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Payment Failed"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Unfortunately, your payment could not be processed. Please try again or contact our support team if the issue persists."}),o&&e.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mb-6",children:e.jsxs("div",{className:"text-sm text-red-600",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Error:"})," ",o]}),i&&e.jsxs("p",{children:[e.jsx("strong",{children:"Order ID:"})," ",i]})]})}),e.jsxs("div",{className:"flex items-center justify-center space-x-2 mb-6",children:[e.jsx(mu,{className:"w-5 h-5 text-gray-600"}),e.jsxs("span",{className:"text-gray-600 font-medium",children:["Redirecting to Delivery in ",a," seconds..."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:l,className:"w-full bg-gradient-to-r from-primary-600 to-secondary-600 text-white font-semibold py-3 px-6 rounded-lg hover:from-primary-700 hover:to-secondary-700 transition-all duration-300 flex items-center justify-center",children:[e.jsx(Gs,{className:"w-4 h-4 mr-2"}),"Try Again"]}),e.jsx("button",{onClick:u,className:"w-full bg-purple-600 text-white font-semibold py-3 px-6 rounded-lg hover:bg-purple-700 transition-all duration-300",children:"View Free Preview Instead"}),e.jsx("button",{onClick:c,className:"w-full bg-gray-100 text-gray-700 font-semibold py-3 px-6 rounded-lg hover:bg-gray-200 transition-all duration-300",children:"Go to Home"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-4",children:"If you continue to experience issues, please contact our support team."})]})})]})},Mm=p.createContext({user:null,loading:!0,login:async()=>({success:!1}),logout:()=>{},isAuthenticated:!1}),Qs=()=>{const r=p.useContext(Mm);if(!r)throw new Error("useCustomAuth must be used within a CustomAuthProvider");return r},Bm=({children:r})=>{const[t,s]=p.useState(null),[a,n]=p.useState(!0);p.useEffect(()=>{i()},[]);const i=async()=>{try{const c=localStorage.getItem("custom_session_token");if(!c){n(!1);return}const{data:u,error:d}=await de.rpc("validate_session_token",{p_session_token:c});if(d||!u||u.length===0){localStorage.removeItem("custom_session_token"),n(!1);return}const h=localStorage.getItem("custom_user_data");if(h){const m=JSON.parse(h);s(m),await de.rpc("set_user_email_config",{p_email:m.email_id})}else{localStorage.removeItem("custom_session_token"),n(!1);return}}catch(c){console.error("Error checking session:",c),localStorage.removeItem("custom_session_token"),localStorage.removeItem("custom_user_data")}finally{n(!1)}},o=async(c,u)=>{try{n(!0),console.log("🔐 Starting login process for:",c,u);const{data:d,error:h}=await de.rpc("login_user_flexible",{p_email:c,p_mobile:u});if(console.log("🔍 RPC login_user response:",{userData:d,verifyError:h}),h)return console.error("❌ Login verification error:",h),{success:!1,error:`Login verification failed: ${h.message}`};if(!d||d.length===0)return console.log("❌ No user data returned - invalid credentials"),{success:!1,error:"Invalid email and mobile number combination"};const m=d[0];console.log("✅ User found:",m);const g=Math.random().toString(36).substring(2)+Date.now().toString(36),f=new Date;f.setDate(f.getDate()+30),console.log("🎫 Creating session with token:",g);const{error:v}=await de.from("user_sessions").insert({user_id:m.user_id,session_token:g,expires_at:f.toISOString()});if(v)return console.error("❌ Session creation error:",v),{success:!1,error:`Failed to create session: ${v.message}`};localStorage.setItem("custom_session_token",g);const x={id:m.user_id,email_id:m.email_id,mobile_number:m.mobile_number,first_name:m.first_name,last_name:m.last_name};return localStorage.setItem("custom_user_data",JSON.stringify(x)),localStorage.removeItem("talesberry_my_story_ids"),s(x),await de.rpc("set_user_email_config",{p_email:x.email_id}),console.log("🎉 Login successful!"),{success:!0}}catch(d){return console.error("💥 Login error:",d),{success:!1,error:"Login failed. Please try again."}}finally{n(!1)}},l=async()=>{try{const c=localStorage.getItem("custom_session_token");c&&await de.from("user_sessions").delete().eq("session_token",c)}catch(c){console.error("Logout error:",c)}finally{localStorage.removeItem("custom_session_token"),localStorage.removeItem("custom_user_data"),s(null)}};return e.jsx(Mm.Provider,{value:{user:t,loading:a,login:o,logout:l,isAuthenticated:!!t},children:r})},dj=()=>{const r=_t(),{buildLink:t}=ht(),{user:s,loading:a,logout:n,isAuthenticated:i}=Qs(),[o,l]=p.useState([]),[c,u]=p.useState(!0),[d,h]=p.useState(null),m=b=>{if(!b)return b;let y=b.trim();const S=/^([A-Za-z]+)['']s\s+/;for(;S.test(y);)y=y.replace(S,"");if(/^[A-Za-z]+\s+and\s+/i.test(y)){const T=y.split(/\s+and\s+/i);T.length>1&&(y="and "+T.slice(1).join(" and "))}return y||b};p.useEffect(()=>{if(!a){if(!i){r(t("/login"),{state:{from:t("/drafts")}});return}g()}},[a,i,r,t]);const g=async()=>{if(s)try{u(!0);const b=localStorage.getItem("custom_session_token");if(!b){console.warn("[DraftPage] No session token found."),l([]);return}const{data:y,error:S}=await de.rpc("get_user_drafts_by_session",{p_session_token:b});if(S){console.error("Error fetching draft books (RPC):",S),l([]);return}const T=(y||[]).map(I=>({order_id:I.order_id,book_name:I.book_name||"Unknown Book",child_name:I.child_name,child_age:I.child_age,order_date:I.order_date||new Date().toISOString(),payment_status:I.payment_status,order_total_amount:I.order_total_amount||0,child_face_url:I.child_face_url,session_id:I.session_id||null,book_cover_url:I.book_cover_url||I.child_face_url}));l(T)}catch(b){console.error("Error fetching draft books:",b)}finally{u(!1)}},f=async b=>{try{h(b.order_id),console.log("[DraftPage] Triggering full book generation for order:",b.order_id);const y=b.book_name||"",S=Ot.find(I=>{var E;return I.title.toLowerCase()===y.toLowerCase()||((E=I.backendName)==null?void 0:E.toLowerCase())===y.toLowerCase()});let T=b.session_id||null;if(!T){const{data:I,error:E}=await de.from("orders").select("session_id").eq("order_id",b.order_id).maybeSingle();!E&&(I!=null&&I.session_id)&&(T=String(I.session_id))}if(T){try{localStorage.setItem("session_id",String(T))}catch{}r(t(`/preview?sessionId=${encodeURIComponent(T)}`),{state:{book:S,orderId:b.order_id,childName:b.child_name,childAge:b.child_age.toString(),childImage:b.child_face_url,paymentCompleted:!0}})}else console.warn("[DraftPage] No session_id found for order",b.order_id),r(t("/preview"),{state:{book:S,orderId:b.order_id,childName:b.child_name,childAge:b.child_age.toString(),childImage:b.child_face_url,paymentCompleted:!0}})}catch(y){console.error("[DraftPage] Failed to continue to preview:",y)}finally{setTimeout(()=>h(null),1500)}},v=async b=>{if(confirm("Are you sure you want to delete this draft? This action cannot be undone."))try{await de.from("payment_info").delete().eq("order_id",b),await de.from("customer_info").delete().eq("order_id",b),await de.from("orders").delete().eq("order_id",b),g()}catch(y){console.error("Error deleting draft:",y),alert("Failed to delete draft. Please try again.")}},x=b=>b?new Date(b).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}):"Unknown",j=()=>{n(),r(t("/"))};return a||c?e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading your drafts..."})]})}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(Yt,{}),e.jsx("div",{className:"bg-white shadow-sm border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"My Drafts"}),e.jsxs("p",{className:"text-gray-600 mt-2",children:["Welcome back, ",(s==null?void 0:s.first_name)||"User","! Continue working on your personalized books"]})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:"bg-primary-100 px-4 py-2 rounded-lg",children:e.jsxs("span",{className:"text-primary-700 font-medium",children:[o.length," Books in Progress"]})}),e.jsxs("button",{onClick:j,className:"flex items-center text-gray-600 hover:text-gray-800 transition-colors px-3 py-2 rounded-lg hover:bg-gray-100",children:[e.jsx(Lo,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"mx-auto w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-6",children:e.jsx(Hl,{className:"w-12 h-12 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"No Drafts Yet"}),e.jsx("p",{className:"text-gray-600 mb-8 max-w-md mx-auto",children:"You haven't started creating any personalized books yet. Once you make a payment for a book, it will appear here."}),e.jsx("button",{onClick:()=>r(t("/books")),className:"bg-gradient-to-r from-primary-600 to-secondary-600 text-white font-semibold py-3 px-6 rounded-lg hover:from-primary-700 hover:to-secondary-700 transition-all duration-300",children:"Browse Books"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:o.map(b=>e.jsxs("div",{className:"bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden hover:shadow-xl transition-shadow duration-300",children:[e.jsxs("div",{className:"aspect-square bg-gradient-to-br from-primary-100 to-secondary-100 relative",children:[e.jsx("img",{src:b.book_cover_url||b.child_face_url,alt:"",role:"presentation","aria-hidden":"true",className:"w-full h-full object-cover opacity-0 transition-opacity duration-300",onLoad:y=>y.currentTarget.classList.remove("opacity-0"),onError:y=>{y.currentTarget.src="/human.png"}}),e.jsx("div",{className:"absolute top-3 right-3 bg-green-500 text-white px-2 py-1 rounded-full text-xs font-medium",children:"Paid"})]}),e.jsxs("div",{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-2",children:[b.child_name,"'s ",b.book_name?m(b.book_name):"Story"]}),e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsxs("div",{className:"flex items-center text-sm text-gray-600",children:[e.jsx(Lp,{className:"w-4 h-4 mr-2"}),"Started: ",x(b.order_date)]}),e.jsxs("div",{className:"flex items-center text-sm text-gray-600",children:[e.jsx(Hl,{className:"w-4 h-4 mr-2"}),"Age: ",b.child_age," years"]}),e.jsxs("div",{className:"flex items-center text-sm text-gray-600",children:[e.jsx(Mi,{className:"w-4 h-4 mr-2"}),"Amount: ₹",b.order_total_amount||0]})]}),e.jsxs("div",{className:"flex space-x-3",children:[e.jsxs("button",{onClick:()=>f(b),disabled:d===b.order_id,className:`flex-1 bg-primary-600 text-white py-2 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center ${d===b.order_id?"opacity-60 cursor-not-allowed":"hover:bg-primary-700"}`,children:[e.jsx(pu,{className:"w-4 h-4 mr-2"}),d===b.order_id?"Opening…":"Continue"]}),e.jsx("button",{onClick:()=>v(b.order_id),className:"bg-red-100 text-red-600 py-2 px-4 rounded-lg hover:bg-red-200 transition-colors duration-200 flex items-center justify-center",children:e.jsx(Oo,{className:"w-4 h-4"})})]})]})]},b.order_id))}),e.jsx("div",{className:"mt-12 bg-blue-50 border border-blue-200 rounded-xl p-6",children:e.jsxs("div",{className:"flex items-start space-x-4",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center",children:e.jsx(Mi,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-blue-900 mb-2",children:"How Drafts Work"}),e.jsxs("ul",{className:"text-blue-800 text-sm space-y-1",children:[e.jsx("li",{children:"• Books appear here after you make a successful payment"}),e.jsx("li",{children:"• You can generate all pages and customize your book"}),e.jsx("li",{children:'• Once complete, use "Send for Printing" to finalize your order'}),e.jsx("li",{children:"• Completed books will be removed from drafts and sent for production"})]})]})]})})]})]})},uj=()=>{const r=_t(),t=Jt(),{buildLink:s}=ht(),{login:a,loading:n,isAuthenticated:i}=Qs(),[o,l]=p.useState({email:"",mobile:""}),[c,u]=p.useState({}),[d,h]=p.useState("");p.useEffect(()=>{var x;if(i){const j=((x=t.state)==null?void 0:x.from)||s("/drafts");r(j,{replace:!0})}},[i,r,t.state,s]);const m=x=>{const{name:j,value:b}=x.target;l(y=>({...y,[j]:b})),c[j]&&u(y=>({...y,[j]:""})),d&&h("")},g=()=>{const x={};return o.email.trim()?/\S+@\S+\.\S+/.test(o.email)||(x.email="Please enter a valid email address"):x.email="Email is required",o.mobile.trim()?/^\d{10}$/.test(o.mobile.replace(/\D/g,""))||(x.mobile="Please enter a valid 10-digit mobile number"):x.mobile="Mobile number is required",u(x),Object.keys(x).length===0},f=async x=>{var b;if(x.preventDefault(),!g())return;const j=await a(o.email,o.mobile.replace(/\D/g,""));if(j.success){const y=((b=t.state)==null?void 0:b.from)||s("/drafts");r(y,{replace:!0})}else h(j.error||"Login failed")},v=()=>{r(s("/"))};return n?e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading..."})]})}):e.jsxs("div",{className:"min-h-screen bg-white flex items-center justify-center px-4",children:[e.jsx(Yt,{}),e.jsxs("div",{className:"max-w-md w-full",children:[e.jsxs("button",{onClick:v,className:"flex items-center text-gray-600 hover:text-gray-800 transition-colors mb-6",children:[e.jsx(Io,{className:"w-5 h-5 mr-1"}),"Back to Home"]}),e.jsxs("div",{className:"bg-white rounded-xl shadow-lg p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-primary-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Gp,{className:"w-8 h-8 text-primary-600"})}),e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Login to Your Account"}),e.jsx("p",{className:"text-gray-600",children:"Enter your email and mobile number to access your drafts"})]}),e.jsxs("form",{onSubmit:f,className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[e.jsx(Ma,{className:"w-4 h-4 inline mr-1"}),"Email Address"]}),e.jsx("input",{type:"email",name:"email",value:o.email,onChange:m,className:`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 ${c.email?"border-red-500":"border-gray-300"}`,placeholder:"Enter your email address"}),c.email&&e.jsx("p",{className:"text-red-500 text-sm mt-1",children:c.email})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[e.jsx(On,{className:"w-4 h-4 inline mr-1"}),"Mobile Number"]}),e.jsx("input",{type:"tel",name:"mobile",value:o.mobile,onChange:m,className:`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 ${c.mobile?"border-red-500":"border-gray-300"}`,placeholder:"Enter your mobile number"}),c.mobile&&e.jsx("p",{className:"text-red-500 text-sm mt-1",children:c.mobile})]}),d&&e.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:e.jsx("p",{className:"text-red-600 text-sm",children:d})}),e.jsx("button",{type:"submit",disabled:n,className:"w-full bg-black text-white font-semibold py-3 px-6 rounded-lg hover:bg-gray-800 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed",children:n?"Logging in...":"Login"})]}),e.jsxs("div",{className:"mt-6 bg-blue-50 border border-blue-200 rounded-lg p-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-blue-900 mb-2",children:"How to Login"}),e.jsxs("ul",{className:"text-blue-800 text-xs space-y-1",children:[e.jsx("li",{children:"• Use the same email and mobile number you provided during checkout"}),e.jsx("li",{children:"• Your account was created automatically when you made your first purchase"}),e.jsx("li",{children:"• Contact support if you're having trouble accessing your account"})]})]})]})]})]})},hj=()=>{const[r,t]=p.useState(null),[s,a]=p.useState(""),[n,i]=p.useState(""),[o,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(""),m=f=>{var x;const v=(x=f.target.files)==null?void 0:x[0];v&&t(v)},g=async()=>{if(!r||!s||!n||!o||!c||!d){alert("Please fill in all required fields");return}const f=new FormData;f.append("faceImage",r),f.append("email",s),f.append("language",n),f.append("childsName",o),f.append("childsAge",c),f.append("gender",d),console.log("Sending data to the API...");try{const v=await fetch(yt("/api/personalize"),{method:"POST",body:f});if(v.ok){const x=await v.json();console.log("API responded successfully:",x),alert(`Success! Your order ID is ${x.order_id}. Image URL: ${x.image_url}`)}else{console.error("API call failed with status:",v.status);const x=await v.json();console.error("API response:",x),alert(`Error: ${x.message}`)}}catch(v){console.error("An error occurred during the API call:",v),alert("A network error occurred. Please try again.")}};return e.jsxs("div",{style:{fontFamily:"sans-serif",backgroundColor:"#f7f7f7",padding:"20px",color:"#333",minHeight:"100vh"},children:[e.jsx(Yt,{}),e.jsxs("div",{style:{maxWidth:"800px",margin:"auto",background:"#fff",padding:"30px",borderRadius:"8px",boxShadow:"0 4px 6px rgba(0,0,0,0.1)"},children:[e.jsx("h2",{style:{textAlign:"center",color:"#555",marginBottom:"30px"},children:"Personalize Your Book"}),e.jsxs("div",{style:{border:"2px dashed #ddd",padding:"20px",textAlign:"center",borderRadius:"8px",marginBottom:"20px"},children:[e.jsx("input",{type:"file",id:"faceImageInput",name:"faceImage",style:{display:"none"},accept:"image/jpeg,image/jpg,image/png,image/heic,image/heif",required:!0,onChange:m}),e.jsx("label",{htmlFor:"faceImageInput",style:{backgroundColor:"#ae3071",color:"white",padding:"10px 20px",borderRadius:"5px",cursor:"pointer",display:"inline-block",fontWeight:"bold"},children:"Choose Image"}),r&&e.jsxs("p",{style:{marginTop:"10px",color:"#555"},children:["Selected: ",r.name]}),e.jsx("p",{style:{marginTop:"10px",fontSize:"12px",color:"#888"},children:"Photo Formats and Dimensions Information"})]}),e.jsxs("div",{style:{marginBottom:"15px"},children:[e.jsx("label",{style:{display:"block",marginBottom:"5px",fontWeight:"bold"},children:"Your Email"}),e.jsx("input",{type:"email",placeholder:"Enter your email address",required:!0,value:s,onChange:f=>a(f.target.value),style:{width:"100%",padding:"10px",border:"1px solid #ccc",borderRadius:"5px",boxSizing:"border-box"}})]}),e.jsxs("div",{style:{marginBottom:"15px"},children:[e.jsx("label",{style:{display:"block",marginBottom:"5px",fontWeight:"bold"},children:"Language"}),e.jsxs("select",{required:!0,value:n,onChange:f=>i(f.target.value),style:{width:"100%",padding:"10px",border:"1px solid #ccc",borderRadius:"5px",boxSizing:"border-box"},children:[e.jsx("option",{value:"",children:"Select Language"}),e.jsx("option",{value:"english",children:"English"}),e.jsx("option",{value:"hindi",children:"Hindi"}),e.jsx("option",{value:"tamil",children:"Tamil"})]})]}),e.jsx("div",{style:{marginBottom:"15px"},children:e.jsxs("div",{style:{display:"flex",gap:"20px"},children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{style:{display:"block",marginBottom:"5px",fontWeight:"bold"},children:"Child's first name"}),e.jsx("input",{type:"text",placeholder:"Enter child's name",required:!0,value:o,onChange:f=>l(f.target.value),style:{width:"100%",padding:"10px",border:"1px solid #ccc",borderRadius:"5px",boxSizing:"border-box"}})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{style:{display:"block",marginBottom:"5px",fontWeight:"bold"},children:"Child's age"}),e.jsx("input",{type:"number",placeholder:"Enter age",required:!0,value:c,onChange:f=>u(f.target.value),style:{width:"100%",padding:"10px",border:"1px solid #ccc",borderRadius:"5px",boxSizing:"border-box"}})]})]})}),e.jsxs("div",{style:{marginBottom:"15px"},children:[e.jsx("label",{style:{display:"block",marginBottom:"5px",fontWeight:"bold"},children:"Child's gender"}),e.jsxs("select",{required:!0,value:d,onChange:f=>h(f.target.value),style:{width:"100%",padding:"10px",border:"1px solid #ccc",borderRadius:"5px",boxSizing:"border-box"},children:[e.jsx("option",{value:"",disabled:!0,children:"Select gender"}),e.jsx("option",{value:"boy",children:"Boy"}),e.jsx("option",{value:"girl",children:"Girl"})]})]}),e.jsx("button",{type:"button",onClick:g,className:"w-full bg-black text-white py-4 rounded-lg font-bold hover:bg-gray-800 transition-colors",children:"Continue to Preview"})]})]})},mj=()=>{const[r,t]=p.useState(0);return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"FAQ | TalesBerry Personalised Children's Books"}),e.jsx("link",{rel:"canonical",href:"https://www.talesberry.com/faq"}),e.jsx("meta",{name:"description",content:"Find answers to common questions about TalesBerry personalised children's books, ordering, customization, delivery, and printing."})]}),e.jsx("div",{className:"min-h-screen pt-20 pb-12 bg-gradient-to-br from-purple-50 via-blue-50 to-pink-50",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsx("h1",{className:"section-title text-center mb-8",children:"Frequently Asked Questions"}),e.jsx("div",{className:"max-w-3xl mx-auto",children:Yn.map((s,a)=>e.jsxs("div",{className:"mb-4",children:[e.jsxs("button",{onClick:()=>t(r===a?-1:a),className:"w-full flex items-center justify-between p-4 bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow",children:[e.jsx("span",{className:"text-left font-medium text-purple-900",children:s.question}),r===a?e.jsx(qr,{className:"w-5 h-5 text-purple-600 flex-shrink-0"}):e.jsx(Us,{className:"w-5 h-5 text-purple-600 flex-shrink-0"})]}),e.jsx(ks,{children:r===a&&e.jsx(Ie.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:e.jsx("div",{className:"p-4 bg-purple-50 rounded-b-lg",children:e.jsx("p",{className:"text-gray-700",children:s.answer})})})})]},a))})]})})]})},pj=()=>e.jsxs(e.Fragment,{children:[e.jsx(as,{children:e.jsx("meta",{name:"robots",content:"noindex, nofollow"})}),e.jsx("div",{className:"min-h-screen pt-20 pb-12 bg-gradient-to-br from-purple-50 via-blue-50 to-pink-50",children:e.jsxs("div",{className:"container mx-auto px-4 max-w-4xl",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("span",{className:"text-4xl mb-4 block",children:"🔒"}),e.jsx("h1",{className:"text-3xl font-bold text-purple-900 mb-4",children:"Privacy Policy"}),e.jsx("p",{className:"text-gray-700",children:"Your privacy is our priority. This policy explains how we protect and handle your personal information at TalesBerry."})]}),e.jsx("p",{className:"text-gray-700 mb-8 text-center",children:"At TalesBerry, your privacy matters to us. This Privacy Policy explains how we collect, use, disclose, and protect your personal information when you use our platform."}),e.jsxs("div",{className:"bg-white rounded-xl p-6 shadow-lg space-y-6",children:[e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"📋"})," 1. Information We Collect"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"Child's name, age and gender"}),e.jsx("li",{children:"One Uploaded image of the child"}),e.jsx("li",{children:"Parent or guardian's email address and Mobile number"}),e.jsx("li",{children:"Order details including delivery and payment status (via Razorpay)"})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🎯"})," 2. How We Use Your Information"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"To generate and personalise the storybook and illustrations"}),e.jsx("li",{children:"To process your order and provide delivery updates"}),e.jsx("li",{children:"To ensure secure payment and fraud prevention"}),e.jsx("li",{children:"To improve user experience, design, and performance"}),e.jsx("li",{children:"To comply with legal and regulatory requirements"})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"⚖️"})," 3. Legal Basis for Processing"]}),e.jsx("p",{className:"text-gray-700",children:"We process your personal data based on your consent, our legitimate interests in providing a seamless experience, and in some cases, to fulfil contractual obligations related to your order."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"💾"})," 4. Data Retention"]}),e.jsx("p",{className:"text-gray-700",children:"We retain the photo uploaded for a maximum of 30 days to process your order and provide after-sales support. After that, the photos are removed from our systems."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🤝"})," 5. Sharing with Third Parties"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"Payment processors (e.g. Razorpay)"}),e.jsx("li",{children:"Cloud hosting and image generation services"})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🔐"})," 6. Your Rights"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"Access your personal data"}),e.jsx("li",{children:"Request correction or deletion"}),e.jsx("li",{children:"Withdraw consent at any time"})]}),e.jsxs("p",{className:"text-gray-700 mt-2",children:["Contact us at ",e.jsx("a",{href:"mailto:support@talesberry.com",className:"text-purple-600 hover:underline",children:"support@talesberry.com"}),"."]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🛡️"})," 7. Data Security"]}),e.jsx("p",{className:"text-gray-700",children:"We implement strict security measures including encryption, secure file storage, and limited access to personal data. We never sell or rent your data to third parties."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"👶"})," 8. Children's Privacy"]}),e.jsx("p",{className:"text-gray-700",children:"Talesberry is intended for parents and guardians. We do not knowingly collect personal data directly from children. All information must be submitted by a consenting adult."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🌍"})," 9. International Data Transfers"]}),e.jsx("p",{className:"text-gray-700",children:"If you are accessing Talesberry from outside India, please note that your data may be transferred to and processed in a location where our infrastructure or partners are located."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"📝"})," 10. Changes to This Policy"]}),e.jsx("p",{className:"text-gray-700",children:"We may revise this Privacy Policy from time to time. Updates will be posted here with a revised 'Effective Date.' Please check back regularly."})]}),e.jsx("div",{className:"pt-4 border-t border-gray-200",children:e.jsx("p",{className:"text-gray-600 font-medium",children:"Effective Date: Oct 25th, 2025"})})]})]})})]}),gj=()=>{const[r,t]=p.useState(0),[s,a]=p.useState(null),[n,i]=p.useState(null),o=p.useRef(null),l=50,c=[{icon:e.jsx(qp,{className:"w-8 h-8 text-purple-500"}),title:"Isolated AI Processing",description:"Photo processing runs in isolated, containerized AI environments with strict access controls. Each request is handled independently to prevent data leakage across users.",bgColor:"from-indigo-50 to-indigo-100"},{icon:e.jsx(vt,{className:"w-8 h-8 text-blue-500"}),title:"Secure Cloud Infrastructure",description:"Our systems operate on secure cloud infrastructure with encrypted data transfer and restricted network access, following modern cloud security best practices.",bgColor:"from-blue-50 to-blue-100"},{icon:e.jsx(bu,{className:"w-8 h-8 text-green-500"}),title:"Controlled AI Providers",description:"We use carefully selected AI and cloud service providers strictly for processing your order. Your data is never used for training public models or shared beyond production needs.",bgColor:"from-green-50 to-green-100"},{icon:e.jsx(Bp,{className:"w-8 h-8 text-purple-600"}),title:"Data Minimization & Deletion",description:"Uploaded photos are retained only as long as required to generate and deliver your book, after which they are scheduled for secure deletion from our systems.",bgColor:"from-purple-50 to-purple-100"}],u=m=>{i(null),a(m.targetTouches[0].clientX)},d=m=>{i(m.targetTouches[0].clientX)},h=()=>{if(!s||!n)return;const m=s-n,g=m>l,f=m<-l;g&&r<c.length-1&&t(v=>v+1),f&&r>0&&t(v=>v-1)};return e.jsx("section",{className:"py-6 sm:py-16 bg-gradient-to-r from-purple-50 via-white to-blue-50 mobile-container",children:e.jsxs("div",{className:"container mx-auto",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx(Ie.h2,{className:"section-title",initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.2},children:"Privacy and Data Security"}),e.jsx(Ie.p,{className:"section-description",initial:{opacity:0,y:-5},animate:{opacity:1,y:0},transition:{delay:.3},children:"We take the security of your data seriously. Your photos are processed with the highest level of protection."})]}),e.jsxs("div",{className:"md:hidden",children:[e.jsx("div",{className:"relative overflow-hidden mx-auto max-w-md",ref:o,onTouchStart:u,onTouchMove:d,onTouchEnd:h,children:e.jsx("div",{className:"flex transition-transform duration-300 ease-in-out",style:{transform:`translateX(-${r*100}%)`},children:c.map((m,g)=>e.jsx("div",{className:"w-full flex-shrink-0 px-3",children:e.jsx(Ie.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},transition:{delay:g*.1},className:`bg-gradient-to-br ${m.bgColor} p-6 rounded-xl shadow-md border border-white/50 h-full`,children:e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsx("div",{className:"bg-white p-3 rounded-full shadow-inner mb-4",children:m.icon}),e.jsx("h3",{className:"text-lg font-bold mb-2 text-gray-800",children:m.title}),e.jsx("p",{className:"text-gray-700",children:m.description})]})})},g))})}),e.jsx("div",{className:"flex justify-center mt-4 space-x-2",children:c.map((m,g)=>e.jsx("button",{onClick:()=>t(g),className:`w-3 h-3 rounded-full transition-colors ${g===r?"bg-black":"bg-gray-300"}`,"aria-label":`Go to privacy feature ${g+1}`},g))}),e.jsx("p",{className:"text-center text-sm text-gray-500 mt-3",children:"Swipe to see all privacy features"})]}),e.jsx("div",{className:"hidden md:grid md:grid-cols-4 gap-6",children:c.map((m,g)=>e.jsx(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:g*.1},className:`bg-gradient-to-br ${m.bgColor} p-6 rounded-xl shadow-md border border-white/50 hover:shadow-lg transition-shadow duration-300 h-full`,children:e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsx("div",{className:"bg-white p-3 rounded-full shadow-inner mb-4",children:m.icon}),e.jsx("h3",{className:"text-lg font-bold mb-2 text-gray-800",children:m.title}),e.jsx("p",{className:"text-gray-700",children:m.description})]})},g))})]})})},un=(r,t,s)=>{r&&(s?s.then(()=>{r.pause(),console.log(`Video ${t} safely paused`)}).catch(()=>{r.pause(),console.log(`Video ${t} paused after failed play attempt`)}):(r.pause(),console.log(`Video ${t} paused directly (no pending promise)`)))},fj=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),xj=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,yj=r=>{r&&(r.preload="auto",r.setAttribute("playsinline",""),r.setAttribute("webkit-playsinline",""),r.addEventListener("loadedmetadata",()=>{console.log("Video metadata loaded, ready for streaming playback")}),r.addEventListener("waiting",()=>{console.log("Video buffering, might need quality reduction")}),r.addEventListener("canplay",()=>{console.log("Video can start playing now with available data")}))},bj=({video:r,index:t,onVideoHover:s,onVideoLeave:a,videoRef:n,playingState:i,isMobile:o=!1,isMuted:l,onToggleMute:c})=>{const[u,d]=jt.useState(!1),[h,m]=jt.useState(0),g="relative w-full aspect-[4/7] rounded-xl overflow-hidden shadow-2xl cursor-pointer",f=o?{onClick:()=>{console.log(`Mobile: Video ${t} clicked`),s(t)}}:{onMouseEnter:()=>s(t),onMouseLeave:()=>a(t)};return p.useEffect(()=>{const v=n.current[t];v&&(yj(v),v.playsInline=!0,v.setAttribute("webkit-playsinline","true"),v.setAttribute("x5-playsinline","true"),v.muted=!0,v.preload="metadata","webkitEnterFullscreen"in v&&(console.log("iOS detected, applying specific settings"),v.muted=!0),v.onwaiting=()=>{console.log(`Video ${t} waiting for data`),d(!0)},v.oncanplay=()=>{console.log(`Video ${t} can play now`),d(!1)},v.onprogress=()=>{if(v.buffered.length>0){const x=v.buffered.end(0),j=v.duration||1,b=Math.round(x/j*100);m(b)}},v.load())},[n,t,o]),e.jsxs("div",{className:g,...f,children:[e.jsxs("div",{className:"absolute inset-0 w-full h-[80%] bg-white flex items-center justify-center border-2 border-primary-100",children:[!i&&e.jsx("img",{src:r.thumbnailPath,alt:r.title,className:"w-full h-full object-contain absolute inset-0",loading:"lazy",decoding:"async"}),e.jsx("video",{ref:v=>{v&&(n.current[t]=v,v.onplay=()=>console.log(`Video ${t} play event triggered at ${new Date().toISOString()}`),v.onpause=()=>console.log(`Video ${t} pause event triggered at ${new Date().toISOString()}`),v.onwaiting=()=>{console.log(`Video ${t} waiting for data at ${new Date().toISOString()}`),d(!0)},v.oncanplay=()=>{console.log(`Video ${t} can play now at ${new Date().toISOString()}`),d(!1)},v.onstalled=()=>console.log(`Video ${t} playback stalled at ${new Date().toISOString()}`),v.onerror=()=>{var x;return console.error(`Video ${t} error event: ${((x=v.error)==null?void 0:x.code)||"unknown"} at ${new Date().toISOString()}`)},v.onloadeddata=()=>console.log(`Video ${t} data loaded at ${new Date().toISOString()}`),v.onresize=()=>console.log(`Video ${t} resized to ${v.videoWidth}x${v.videoHeight}`),v.onprogress=()=>{if(v.buffered.length>0){const x=v.buffered.end(0),j=v.duration||1,b=Math.round(x/j*100);m(b),console.log(`Video ${t} buffered: ${b}%`)}})},src:r.mp4Path,className:"w-full h-full object-contain",playsInline:!0,"webkit-playsinline":"true","x5-playsinline":"true",muted:l,loop:!0,preload:"metadata",style:{display:i?"block":"none"}}),i&&u&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black bg-opacity-30 z-10",children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx(jn,{className:"w-8 h-8 text-white animate-spin"}),e.jsx("div",{className:"mt-2 bg-gray-800 w-32 h-1.5 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary-500 transition-all duration-300",style:{width:`${h}%`}})}),e.jsxs("p",{className:"text-xs text-white mt-1",children:[h,"% loaded"]})]})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i?o&&!u?e.jsx("div",{className:"bg-primary-500/40 rounded-full p-3 shadow-lg",children:e.jsx(yu,{className:"w-6 h-6 text-white"})}):null:e.jsx("div",{className:"bg-primary-500/80 rounded-full p-3 shadow-lg",children:e.jsx(Ca,{className:"w-6 h-6 text-white"})})}),i&&!u&&e.jsx("div",{className:"absolute bottom-4 right-4 z-10",onClick:v=>{v.stopPropagation(),c(t)},children:e.jsx("div",{className:"bg-primary-500/80 rounded-full p-2 shadow-lg",children:l?e.jsx(Nu,{className:"w-5 h-5 text-white"}):e.jsx(ju,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 h-[20%] bg-white p-3",children:[e.jsx("h3",{className:"text-base font-semibold text-primary-900 mb-1 truncate",children:r.title}),e.jsx("p",{className:"text-xs text-primary-800/90 line-clamp-2",children:r.description})]})]},r.id)},vj=({video:r,index:t,onVideoHover:s,onVideoLeave:a,videoRefs:n,playingState:i,isMobile:o,isMuted:l,onToggleMute:c})=>e.jsx("div",{className:`video-container ${o?"w-[300px]":"w-[350px]"}`,"data-index":t,style:{minHeight:o?"300px":"400px"},children:e.jsx(bj,{video:r,index:t,onVideoHover:s,onVideoLeave:a,videoRef:n,playingState:i,isMobile:o,isMuted:l,onToggleMute:c})},r.id),wj=(r,t=!1)=>{const s=p.useRef([]),[a,n]=p.useState([]),[i,o]=p.useState([]),l=p.useRef([]),c=p.useRef(!1),u=t||fj(),d=xj();p.useEffect(()=>(s.current=Array(r).fill(null),l.current=Array(r).fill(void 0),n(Array(r).fill(!1)),o(Array(r).fill(!0)),console.log(`VideoGrid initialized with ${r} videos, mobile: ${u}`),()=>{s.current.forEach((x,j)=>{x&&un(x,j,l.current[j])})}),[r,u]);const h=p.useCallback(x=>{s.current.forEach((j,b)=>{(x===void 0||b!==x)&&j&&(un(j,b,l.current[b]),n(y=>{const S=[...y];return S[b]=!1,S}))})},[]),m=p.useCallback(x=>{if(c.current){console.log(`Ignoring tap while processing for video ${x}`);return}c.current=!0;try{const j=s.current[x];if(!j){console.error(`No video element found for index ${x}`);return}console.log(`Mobile: Manual play/pause for video ${x}`),a[x]?(un(j,x,l.current[x]),n(b=>{const y=[...b];return y[x]=!1,y})):(h(x),j.currentTime=0,j.muted=!0,n(b=>{const y=[...b];return y[x]=!0,y}),setTimeout(()=>{var b;s.current[x]&&(l.current[x]=s.current[x].play(),(b=l.current[x])==null||b.then(()=>{console.log(`Video ${x} manual play successful`),setTimeout(()=>{if(s.current[x])try{s.current[x].muted=!1,o(y=>{const S=[...y];return S[x]=!1,S}),console.log(`Video ${x} unmuted after successful play`)}catch(y){console.warn(`Couldn't unmute video ${x}:`,y)}},300)}).catch(y=>{console.error(`Manual play failed for video ${x}:`,y),n(S=>{const T=[...S];return T[x]=!1,T})}))},50))}finally{setTimeout(()=>{c.current=!1},300)}},[h,a]),g=p.useCallback(x=>{if(!s.current[x])return;const j=s.current[x],b=j.muted;try{j.muted=!b,j.volume=1,o(y=>{const S=[...y];return S[x]=!b,S}),console.log(`Video ${x} muted state changed to: ${!b}`)}catch(y){console.warn(`Failed to toggle mute for video ${x}:`,y)}},[]),f=p.useCallback(x=>{var j;if(s.current[x])if(u)m(x);else{h(x);const b=s.current[x];b.currentTime=0,b.volume=1,b.muted=!0,console.log(`Desktop: Attempting to play video ${x}`),l.current[x]=b.play(),(j=l.current[x])==null||j.then(()=>{n(y=>{const S=[...y];return S[x]=!0,S}),console.log(`Desktop: Video ${x} started playing successfully`),setTimeout(()=>{try{s.current[x]&&(s.current[x].muted=!1,o(y=>{const S=[...y];return S[x]=!1,S}),console.log(`Desktop: Unmuted video ${x} after successful play`))}catch(y){console.warn(`Couldn't unmute desktop video ${x}:`,y)}},300)}).catch(y=>{console.error(`Desktop play error for video ${x}:`,y),n(S=>{const T=[...S];return T[x]=!1,T})})}},[u,h,m]),v=p.useCallback(x=>{if(!u&&s.current[x]){const j=s.current[x];un(j,x,l.current[x]),n(b=>{const y=[...b];return y[x]=!1,y}),console.log(`Desktop: Video ${x} paused on mouse leave`)}},[u]);return{videoRefs:s,playingStates:a,mutedStates:i,effectiveMobile:u,isIOS:d,playPromiseRefs:l,pauseAllVideos:h,playVideoManually:m,handleToggleMute:g,handleVideoHover:f,handleVideoLeave:v}},jj=r=>{p.useEffect(()=>{if(r){console.log("iOS device detected, applying iOS-specific workarounds");const t=()=>{console.log("First user interaction detected on iOS, priming videos"),document.removeEventListener("touchstart",t)};return document.addEventListener("touchstart",t),()=>{document.removeEventListener("touchstart",t)}}},[r])},Nj=({videos:r,isMobile:t=!1})=>{const s=p.useRef(null),{videoRefs:a,playingStates:n,mutedStates:i,effectiveMobile:o,isIOS:l,handleToggleMute:c,handleVideoHover:u,handleVideoLeave:d}=wj(r.length,t);return jj(l),e.jsx("div",{ref:s,className:"overflow-x-auto pb-10 -mx-4 px-4",children:e.jsx("div",{className:"flex space-x-6",style:{width:"max-content"},children:r.map((h,m)=>e.jsx(vj,{video:h,index:m,onVideoHover:u,onVideoLeave:d,videoRefs:a,playingState:n[m]||!1,isMobile:o,isMuted:i[m],onToggleMute:c},h.id))})})},kj=({videos:r})=>{const[t,s]=p.useState(null),[a,n]=p.useState(!0),[i,o]=p.useState(!1),l=p.useRef(null),c=d=>{s(d),n(!0),o(!0)},u=()=>{l.current&&l.current.pause(),s(null)};return p.useEffect(()=>{t&&l.current&&(l.current.muted=a,l.current.play().catch(console.error))},[t]),p.useEffect(()=>{l.current&&(l.current.muted=a)},[a]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto -mx-4 px-4 pb-4 scroll-smooth",style:{WebkitOverflowScrolling:"touch"},children:e.jsx("div",{className:"flex gap-3",style:{width:"max-content"},children:r.map(d=>e.jsxs("div",{className:"relative w-28 aspect-[3/4] rounded-lg overflow-hidden shadow-md cursor-pointer active:scale-95 transition-transform flex-shrink-0",onClick:()=>c(d),children:[e.jsx("img",{src:d.thumbnailPath,alt:d.title,className:"w-full h-full object-cover",loading:"lazy"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20",children:e.jsx("div",{className:"bg-black/60 rounded-full p-2",children:e.jsx(Ca,{className:"w-4 h-4 text-white",fill:"white"})})}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2",children:e.jsx("p",{className:"text-white text-[10px] font-medium line-clamp-2 leading-tight",children:d.title})})]},d.id))})}),e.jsx(ks,{children:t&&e.jsx(Ie.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4",onClick:u,children:e.jsxs(Ie.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.8,opacity:0},className:"relative w-full max-w-sm",onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"relative aspect-[4/7] rounded-xl overflow-hidden bg-black",children:[e.jsx("button",{onClick:u,className:"absolute top-3 right-3 p-2 bg-black/70 rounded-full z-20",children:e.jsx(Cs,{className:"w-5 h-5 text-white"})}),e.jsx("video",{ref:l,src:t.mp4Path,className:"w-full h-full object-contain",playsInline:!0,loop:!0,muted:a,onWaiting:()=>o(!0),onCanPlay:()=>o(!1),onLoadedData:()=>o(!1)}),i&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30",children:e.jsx(jn,{className:"w-8 h-8 text-white animate-spin"})}),e.jsx("button",{onClick:d=>{d.stopPropagation(),n(!a)},className:"absolute bottom-4 right-4 p-2 bg-black/60 rounded-full",children:a?e.jsx(Nu,{className:"w-5 h-5 text-white"}):e.jsx(ju,{className:"w-5 h-5 text-white"})})]}),e.jsxs("div",{className:"mt-3 text-center",children:[e.jsx("h3",{className:"text-white font-semibold text-lg",children:t.title}),e.jsx("p",{className:"text-white/70 text-sm mt-1",children:t.description})]})]})})})]})},_j=[{id:1,title:"Eka's Alphabet Adventure",description:"A magical journey through ABCs with your little hero!",mp4Path:"/videos/2.mp4",thumbnailPath:"/thumbnails/2.png"},{id:2,title:"Tiny toes in the Jungle",description:"Saanjh learns to love nature and animals after her tiny toes went to the Jungle!",mp4Path:"/videos/3.mp4",thumbnailPath:"/thumbnails/3.png"},{id:3,title:"Vihaan's and The Wise Turtle",description:"Vihaan wants to be wise, and Turtle teaches him beautiful life morals from kindness to Courage!",mp4Path:"/videos/4.mp4",thumbnailPath:"/thumbnails/4.png"},{id:4,title:"The Moonlight Adventure",description:"The baby goes on a ride with Luna the Moon, and enjoys her ride in nature's lap before returning to mother.",mp4Path:"/videos/6.mp4",thumbnailPath:"/thumbnails/6.png"}],Sj=r=>_j,Cj=()=>{const{buildLink:r,region:t}=ht(),[s,a]=p.useState(!1),n=p.useMemo(()=>Sj(),[t]);return p.useEffect(()=>{const i=()=>{a(window.innerWidth<768)};return i(),window.addEventListener("resize",i),()=>window.removeEventListener("resize",i)},[]),e.jsx("section",{className:"py-6 md:py-20 bg-white",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-8 md:mb-12",children:[e.jsx("h2",{className:"section-title",children:"Books Sample Videos"}),e.jsxs("p",{className:"section-description mt-3",children:["A meaningful way for grandparents and family to gift something lasting."," ",e.jsx("a",{href:r("/personalised-books-as-gifts"),className:"text-black hover:text-gray-700 font-medium transition-colors whitespace-nowrap",children:"Learn why →"})]})]}),e.jsx("div",{className:"max-w-6xl mx-auto",children:s?e.jsx(kj,{videos:n}):e.jsx(Nj,{videos:n})})]})})},Pj=()=>{const[r,t]=p.useState(0);return e.jsx("section",{className:"pt-6 pb-4 md:pt-20 md:pb-12 bg-white",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsx("h2",{className:"section-title text-center",children:"Frequently Asked Questions"}),e.jsx("div",{className:"max-w-3xl mx-auto",children:Yn.map((s,a)=>{const n=r===a;return e.jsxs("div",{className:"mb-4",children:[e.jsxs("button",{onClick:()=>t(n?-1:a),className:"w-full flex items-center justify-between p-4 bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow","aria-expanded":n,children:[e.jsx("h3",{className:"text-left font-medium text-gray-900 text-base",children:s.question}),e.jsx(Us,{className:`w-5 h-5 text-black flex-shrink-0 transition-transform duration-300 ${n?"rotate-180":""}`})]}),e.jsx("div",{className:`overflow-hidden transition-all duration-300 ease-in-out ${n?"max-h-[1000px] opacity-100":"max-h-0 opacity-0"}`,children:e.jsx("div",{className:"p-4 bg-gray-50 rounded-b-lg",children:e.jsx("p",{className:"text-gray-700",children:s.answer})})})]},a)})})]})})},hn=({title:r,value:t,subtitle:s,icon:a,trend:n})=>e.jsx("div",{className:"bg-white rounded-lg shadow-md p-6 border border-gray-200",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-gray-600 mb-1",children:r}),e.jsx("h3",{className:"text-3xl font-bold text-gray-900",children:t}),s&&e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s}),n&&e.jsxs("div",{className:`flex items-center mt-2 text-sm ${n.isPositive?"text-green-600":"text-red-600"}`,children:[e.jsx("span",{children:n.isPositive?"↑":"↓"}),e.jsxs("span",{className:"ml-1",children:[Math.abs(n.value),"%"]})]})]}),a&&e.jsx("div",{className:"text-primary-500 opacity-80",children:a})]})}),Ej=({steps:r})=>{var s;const t=((s=r[0])==null?void 0:s.count)||1;return e.jsx("div",{className:"space-y-4",children:r.map((a,n)=>{const i=a.count/t*100,o=n>0?r[n-1].count-a.count:0,l=n>0?(o/r[n-1].count*100).toFixed(1):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"font-medium text-gray-700",children:[n+1,". ",a.name.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase())]}),e.jsxs("span",{className:"text-gray-600",children:[a.count," (",a.percentage.toFixed(1),"%)"]})]}),e.jsx("div",{className:"relative h-12 bg-gray-100 rounded-lg overflow-hidden",children:e.jsx("div",{className:`absolute inset-y-0 left-0 bg-gradient-to-r from-primary-500 to-primary-600 
                           flex items-center justify-end pr-4 text-white font-semibold text-sm
                           transition-all duration-500`,style:{width:`${i}%`},children:i>20&&`${a.count}`})}),n>0&&o>0&&e.jsxs("p",{className:`text-xs ${parseFloat(l.toString())>30?"text-red-600 font-semibold":"text-orange-600"}`,children:["↓ ",o," users dropped (",l,"% drop-off)",parseFloat(l.toString())>30&&" 🔴 High drop-off!"]})]},a.name)})})},Tj=({events:r})=>{const[t,s]=p.useState("all"),[a,n]=p.useState(""),i=r.filter(l=>{const c=t==="all"||l.event_category===t,u=a===""||l.event_name.toLowerCase().includes(a.toLowerCase())||l.page_url.toLowerCase().includes(a.toLowerCase());return c&&u}),o=["all",...Array.from(new Set(r.map(l=>l.event_category)))];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col md:flex-row gap-4",children:[e.jsx("input",{type:"text",placeholder:"Search events...",value:a,onChange:l=>n(l.target.value),className:"flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"}),e.jsx("select",{value:t,onChange:l=>s(l.target.value),className:"px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500",children:o.map(l=>e.jsx("option",{value:l,children:l==="all"?"All Categories":l.replace(/_/g," ")},l))})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full bg-white border border-gray-200 rounded-lg",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Time"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Event"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Category"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Page"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Book"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-200",children:i.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"px-6 py-8 text-center text-gray-500",children:"No events found"})}):i.map(l=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-900",children:new Date(l.created_at).toLocaleString()}),e.jsx("td",{className:"px-6 py-4 text-sm text-gray-900",children:l.event_name.replace(/_/g," ")}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm",children:e.jsx("span",{className:"px-2 py-1 text-xs font-medium rounded-full bg-primary-100 text-primary-800",children:l.event_category})}),e.jsx("td",{className:"px-6 py-4 text-sm text-gray-500",children:l.page_url}),e.jsx("td",{className:"px-6 py-4 text-sm text-gray-500",children:l.book_name||"-"})]},l.id))})]})})]})},Aj=({excludedSessionIds:r})=>{const[t,s]=p.useState([]);p.useEffect(()=>{if(r.length===0)return;a();const n=de.channel("analytics-changes").on("postgres_changes",{event:"INSERT",schema:"public",table:"analytics_events"},o=>{const l=o.new;l.session_id&&!r.includes(l.session_id)&&s(c=>[l,...c].slice(0,20))}).subscribe(),i=setInterval(a,1e4);return()=>{de.removeChannel(n),clearInterval(i)}},[r]);const a=async()=>{const{data:n}=await de.from("analytics_events").select("id, event_name, page_url, created_at, book_name, session_id").not("session_id","in",`(${r.join(",")})`).order("created_at",{ascending:!1}).limit(20);n&&s(n)};return e.jsxs("div",{className:"bg-white rounded-lg shadow-md p-6 border border-gray-200",children:[e.jsxs("h3",{className:"text-lg font-semibold text-gray-900 mb-4 flex items-center",children:[e.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse mr-2"}),"Live Activity Feed"]}),e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:t.length===0?e.jsx("p",{className:"text-gray-500 text-center py-4",children:"Waiting for events..."}):t.map(n=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors",children:[e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap mt-1",children:n.created_at?new Date(n.created_at).toLocaleTimeString():"Just now"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:n.event_name.replace(/_/g," ")}),e.jsxs("p",{className:"text-xs text-gray-500 truncate",children:[n.page_url,n.book_name&&` • ${n.book_name}`]})]})]},n.id))})]})},Hd=["vimalpjangid@gmail.com","pavi.venki@gmail.com"],Ij=()=>{const{session:r,loading:t,signOut:s}=Jn(),[a,n]=p.useState(!1),[i,o]=p.useState(!0),[l,c]=p.useState("24h"),[u,d]=p.useState([]),[h,m]=p.useState({totalVisitors:0,totalPageViews:0,totalEvents:0,activeUsers:0}),[g,f]=p.useState([]),[v,x]=p.useState([]),[j,b]=p.useState([]);p.useEffect(()=>{t||(async()=>{if(!(r!=null&&r.user)){o(!1);return}const{data:J}=await de.from("user_roles").select("role").eq("user_id",r.user.id).eq("role","admin").maybeSingle();n(!!J),o(!1)})()},[r,t]),p.useEffect(()=>{a&&(async()=>{const{data:J}=await de.from("sessions").select("session_id").in("email_id",Hd),{data:U}=await de.from("orders").select("session_id").in("email_id",Hd),Ge=new Set;J==null||J.forEach(Te=>{Te.session_id&&Ge.add(Te.session_id)}),U==null||U.forEach(Te=>{Te.session_id&&Ge.add(Te.session_id)}),d(Array.from(Ge))})()},[a]),p.useEffect(()=>{if(!a)return;S(),T(),I(),E();const V=setInterval(()=>{S(),E()},3e4);return()=>clearInterval(V)},[a,l,u]);const y=()=>{const V=new Date;switch(l){case"24h":return new Date(V.getTime()-24*60*60*1e3).toISOString();case"7d":return new Date(V.getTime()-7*24*60*60*1e3).toISOString();case"30d":return new Date(V.getTime()-30*24*60*60*1e3).toISOString();default:return new Date(V.getTime()-24*60*60*1e3).toISOString()}},S=async()=>{const V=y();let J=de.from("analytics_page_views").select("session_id").eq("page_url","/").gte("created_at",V);u.length>0&&(J=J.not("session_id","in",`(${u.join(",")})`));const{data:U}=await J,Ge=U?new Set(U.map(fe=>fe.session_id)).size:0;let Te=de.from("analytics_page_views").select("*",{count:"exact",head:!0}).gte("created_at",V);u.length>0&&(Te=Te.not("session_id","in",`(${u.join(",")})`));const{count:Me}=await Te;let _e=de.from("analytics_events").select("*",{count:"exact",head:!0}).gte("created_at",V);u.length>0&&(_e=_e.not("session_id","in",`(${u.join(",")})`));const{count:Se}=await _e,ue=new Date(Date.now()-5*60*1e3).toISOString();let re=de.from("analytics_events").select("session_id",{count:"exact",head:!0}).gte("created_at",ue);u.length>0&&(re=re.not("session_id","in",`(${u.join(",")})`));const{count:Ne}=await re;m({totalVisitors:Ge||0,totalPageViews:Me||0,totalEvents:Se||0,activeUsers:Ne||0})},T=async()=>{const V=y(),J=["Homepage_loaded","Home_Create_Free_Preview","Home_Books_Collection","Home_Create_Free_Preview_mainCTA","Personalize_page_loaded","Personalize_Choose_Image","Personalize_See_Book_Preview","Preview_page_loaded","Preview_Retry","Preview_New_Photo","Preview_Place_Order","DeliveryPage_loaded","DeliveryPage_PayNow","Payment_screen_loaded","Preview_redirected_Loaded","Preview_redirected_ebook_pdf_download","Preview_redirected_send_for_printing"];let U=de.from("analytics_funnel_steps").select("step_name, session_id").gte("created_at",V).in("step_name",J);u.length>0&&(U=U.not("session_id","in",`(${u.join(",")})`));const{data:Ge}=await U;if(!Ge)return;const Te=Ge.reduce((re,Ne)=>(re[Ne.step_name]=(re[Ne.step_name]||0)+1,re),{}),Me=J.find(re=>(Te[re]??0)>0),Se=(Me?Te[Me]:0)||Math.max(0,...Object.values(Te)),ue=J.filter(re=>(Te[re]??0)>0).map(re=>({name:re,count:Te[re]??0,percentage:Se?(Te[re]??0)/Se*100:0}));f(ue)},I=async()=>{const V=y();let J=de.from("analytics_events").select("event_name, event_category").eq("event_category","button_click").gte("created_at",V);u.length>0&&(J=J.not("session_id","in",`(${u.join(",")})`));const{data:U}=await J;if(!U)return;const Ge=U.reduce((Me,_e)=>(Me[_e.event_name]=(Me[_e.event_name]||0)+1,Me),{}),Te=Object.entries(Ge).map(([Me,_e])=>({name:Me,count:_e})).sort((Me,_e)=>_e.count-Me.count).slice(0,10);x(Te)},E=async()=>{let V=de.from("analytics_events").select("*").order("created_at",{ascending:!1}).limit(100);u.length>0&&(V=V.not("session_id","in",`(${u.join(",")})`));const{data:J}=await V;J&&b(J)};if(t||i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"}),e.jsx("p",{className:"mt-4 text-gray-600",children:"Loading..."})]})});if(!r||!a)return e.jsx(Jm,{to:"/admin-login",replace:!0});const O=async()=>{await s()};return e.jsxs("div",{className:"min-h-screen bg-gray-50 py-8",children:[e.jsx(Yt,{}),e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"mb-8 flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"Analytics Dashboard"}),e.jsx("p",{className:"text-gray-600 mt-2",children:"Track user behavior and conversion metrics"})]}),e.jsxs("button",{onClick:O,className:"flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors font-medium",children:[e.jsx(Lo,{size:18}),"Logout"]})]}),e.jsxs("div",{className:"mb-6 flex gap-2",children:[e.jsx("button",{onClick:()=>c("24h"),className:`px-4 py-2 rounded-lg font-medium transition-colors ${l==="24h"?"bg-primary-600 text-white":"bg-white text-gray-700 hover:bg-gray-100"}`,children:"Last 24 Hours"}),e.jsx("button",{onClick:()=>c("7d"),className:`px-4 py-2 rounded-lg font-medium transition-colors ${l==="7d"?"bg-primary-600 text-white":"bg-white text-gray-700 hover:bg-gray-100"}`,children:"Last 7 Days"}),e.jsx("button",{onClick:()=>c("30d"),className:`px-4 py-2 rounded-lg font-medium transition-colors ${l==="30d"?"bg-primary-600 text-white":"bg-white text-gray-700 hover:bg-gray-100"}`,children:"Last 30 Days"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8",children:[e.jsx(hn,{title:"Total Visitors",value:h.totalVisitors,subtitle:"Unique sessions",icon:e.jsx(wu,{size:32})}),e.jsx(hn,{title:"Page Views",value:h.totalPageViews,subtitle:"Total views",icon:e.jsx(pu,{size:32})}),e.jsx(hn,{title:"Button Clicks",value:h.totalEvents,subtitle:"Total interactions",icon:e.jsx(Vp,{size:32})}),e.jsx(hn,{title:"Active Now",value:h.activeUsers,subtitle:"Last 5 minutes",icon:e.jsx(Kp,{size:32})})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-md p-6 mb-8 border border-gray-200",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-6",children:"Conversion Funnel"}),g.length===0?e.jsx("p",{className:"text-gray-500 text-center py-8",children:"No funnel data available yet"}):e.jsx(Ej,{steps:g})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8",children:[e.jsxs("div",{className:"bg-white rounded-lg shadow-md p-6 border border-gray-200",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Top Button Clicks"}),v.length===0?e.jsx("p",{className:"text-gray-500 text-center py-4",children:"No events yet"}):e.jsx("div",{className:"space-y-3",children:v.map((V,J)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700",children:V.name.replace(/_/g," ")}),e.jsxs("span",{className:"text-sm font-bold text-primary-600",children:[V.count," clicks"]})]},J))})]}),e.jsx(Aj,{excludedSessionIds:u})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-md p-6 border border-gray-200",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Recent Events"}),e.jsx(Tj,{events:j})]})]})]})},Rj=()=>{const[r,t]=p.useState(""),[s,a]=p.useState(""),[n,i]=p.useState(""),[o,l]=p.useState(!1),c=_t(),{session:u}=Jn();p.useEffect(()=>{u&&c("/analytics")},[u,c]);const d=async h=>{h.preventDefault(),i(""),l(!0);try{const{data:m,error:g}=await de.auth.signInWithPassword({email:r,password:s});if(g)throw g;m.session&&c("/analytics")}catch(m){i(m.message||"Failed to login")}finally{l(!1)}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-background via-background to-primary/5 px-4",children:[e.jsx(Yt,{}),e.jsx("div",{className:"w-full max-w-md",children:e.jsxs("div",{className:"bg-card border border-border rounded-2xl shadow-xl p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("img",{src:"/talesberry-logo.png",alt:"TalesBerry",className:"h-12 mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Admin Login"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-2",children:"Access analytics dashboard"})]}),n&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive px-4 py-3 rounded-lg mb-6 text-sm",children:n}),e.jsxs("form",{onSubmit:d,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-foreground mb-2",children:"Email Address"}),e.jsx("input",{id:"email",type:"email",value:r,onChange:h=>t(h.target.value),required:!0,className:"w-full px-4 py-3 bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 text-foreground",placeholder:"admin@talesberry.com"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-foreground mb-2",children:"Password"}),e.jsx("input",{id:"password",type:"password",value:s,onChange:h=>a(h.target.value),required:!0,className:"w-full px-4 py-3 bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 text-foreground",placeholder:"Enter your password"})]}),e.jsx("button",{type:"submit",disabled:o,className:"w-full bg-black text-white py-3 rounded-lg font-semibold hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:o?"Signing in...":"Sign In"})]}),e.jsx("div",{className:"mt-6 text-center",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is an admin-only area. Customer login is separate."})})]})})]})},$j=()=>e.jsxs(e.Fragment,{children:[e.jsx(as,{children:e.jsx("meta",{name:"robots",content:"noindex, nofollow"})}),e.jsx("div",{className:"min-h-screen pt-20 pb-12 bg-gradient-to-br from-purple-50 via-blue-50 to-pink-50",children:e.jsxs("div",{className:"container mx-auto px-4 max-w-4xl",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("span",{className:"text-4xl mb-4 block",children:"🔒"}),e.jsx("h1",{className:"text-3xl font-bold text-purple-900 mb-4",children:"Privacy Policy"})]}),e.jsx("p",{className:"text-gray-700 mb-8 text-center",children:"At TalesBerry, your privacy matters to us. This Privacy Policy explains how we collect, use, disclose, and protect your personal information when you use our platform."}),e.jsxs("div",{className:"bg-white rounded-xl p-6 shadow-lg space-y-6",children:[e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"📋"})," 1. Information We Collect"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"Child's name, age and gender"}),e.jsx("li",{children:"One Uploaded image of the child"}),e.jsx("li",{children:"Parent or guardian's email address and Mobile number"}),e.jsx("li",{children:"Order details including delivery and payment status (via Razorpay)"})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🎯"})," 2. How We Use Your Information"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"To generate and personalise the storybook and illustrations"}),e.jsx("li",{children:"To process your order and provide delivery updates"}),e.jsx("li",{children:"To ensure secure payment and fraud prevention"}),e.jsx("li",{children:"To improve user experience, design, and performance"}),e.jsx("li",{children:"To comply with legal and regulatory requirements"})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"⚖️"})," 3. Legal Basis for Processing"]}),e.jsx("p",{className:"text-gray-700",children:"We process your personal data based on your consent, our legitimate interests in providing a seamless experience, and in some cases, to fulfil contractual obligations related to your order."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"💾"})," 4. Data Retention"]}),e.jsx("p",{className:"text-gray-700",children:"We retain the photo uploaded for a maximum of 30 days to process your order and provide after-sales support. After that, the photos are removed from our systems."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🤝"})," 5. Sharing with Third Parties"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"Payment processors (e.g. Razorpay)"}),e.jsx("li",{children:"Cloud hosting and image generation services"})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🔐"})," 6. Your Rights"]}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-2",children:[e.jsx("li",{children:"Access your personal data"}),e.jsx("li",{children:"Request correction or deletion"}),e.jsx("li",{children:"Withdraw consent at any time"})]}),e.jsxs("p",{className:"text-gray-700 mt-2",children:["Contact us at"," ",e.jsx("a",{href:"mailto:support@talesberry.com",className:"text-purple-600 hover:underline",children:"support@talesberry.com"}),"."]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🛡️"})," 7. Data Security"]}),e.jsx("p",{className:"text-gray-700",children:"We implement strict security measures including encryption, secure file storage, and limited access to personal data. We never sell or rent your data to third parties."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"👶"})," 8. Children's Privacy"]}),e.jsx("p",{className:"text-gray-700",children:"Talesberry is intended for parents and guardians. We do not knowingly collect personal data directly from children. All information must be submitted by a consenting adult."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"🌍"})," 9. International Data Transfers"]}),e.jsx("p",{className:"text-gray-700",children:"If you are accessing Talesberry from outside India, please note that your data may be transferred to and processed in a location where our infrastructure or partners are located."})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-purple-900 mb-3 flex items-center gap-2",children:[e.jsx("span",{children:"📝"})," 10. Changes to This Policy"]}),e.jsx("p",{className:"text-gray-700",children:"We may revise this Privacy Policy from time to time. Updates will be posted here with a revised 'Effective Date.' Please check back regularly."})]}),e.jsx("div",{className:"pt-4 border-t border-gray-200",children:e.jsx("p",{className:"text-gray-600 font-medium",children:"Effective Date: Oct 25th, 2025"})})]})]})})]}),Lj=()=>{const{buildLink:r}=ht();return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"Why Choose a Personalised Book for Children | TalesBerry"}),e.jsx("meta",{name:"description",content:"Discover why personalised books make meaningful gifts for children — supporting reading, confidence, and lasting memories."}),e.jsx("link",{rel:"canonical",href:"https://www.talesberry.com/why-personalised-books"})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-purple-50 via-white to-pink-50",children:e.jsx("div",{className:"container mx-auto px-4 py-12 md:py-20",children:e.jsxs("article",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-purple-900 mb-8 leading-tight",children:"Why choose a personalised book as a gift for children?"}),e.jsxs("section",{className:"mb-10",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold text-purple-800 mb-4",children:"A gift that feels personal and meaningful"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"Personalised books place the child at the center of the story, creating a stronger emotional connection than most traditional gifts. Seeing their name and story details helps children feel recognised and valued."})]}),e.jsxs("section",{className:"mb-10",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold text-purple-800 mb-4",children:"Encourages reading and learning naturally"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"Children engage more deeply with stories that feel familiar. Personalised books often encourage repeat reading, helping build vocabulary, confidence, and early reading habits."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold text-purple-800 mb-4",children:"A keepsake children return to over time"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"Unlike many short-lived gifts, personalised books are often kept and revisited for years. They become part of a child's memory rather than something quickly forgotten."})]}),e.jsx("div",{className:"mt-12",children:e.jsx(es,{to:r("/books"),className:"inline-flex items-center text-lg font-medium text-purple-600 hover:text-purple-700 transition-colors",children:"Explore personalised storybooks →"})})]})})})]})},Oj=()=>{const{buildLink:r}=ht();return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"Personalised Books as Gifts | Birthday & Family Gifting Ideas – TalesBerry"}),e.jsx("meta",{name:"description",content:"Learn why personalised books are a popular gift choice for birthdays, grandparents, and special family moments."}),e.jsx("link",{rel:"canonical",href:"https://www.talesberry.com/personalised-books-as-gifts"})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-purple-50 via-white to-pink-50",children:e.jsx("div",{className:"container mx-auto px-4 py-12 md:py-20",children:e.jsxs("article",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-purple-900 mb-8 leading-tight",children:"Personalised books as meaningful gifts"}),e.jsxs("section",{className:"mb-10",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold text-purple-800 mb-4",children:"Ideal for birthdays and special occasions"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"Many people choose personalised books for birthdays when they want to give something thoughtful and different. These books stand out by creating a personal connection rather than offering a generic experience."})]}),e.jsxs("section",{className:"mb-10",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold text-purple-800 mb-4",children:"A popular gift from grandparents to grandchildren"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"Grandparents often choose personalised books as gifts because they feel emotionally meaningful. A personalised story allows them to celebrate their bond with the child in a lasting way."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold text-purple-800 mb-4",children:"Designed to be remembered"}),e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"Personalised books are often kept long after the occasion has passed. They serve as keepsakes that children associate with family, love, and shared moments."})]}),e.jsx("div",{className:"mt-12",children:e.jsx(es,{to:r("/books"),className:"inline-flex items-center text-lg font-medium text-purple-600 hover:text-purple-700 transition-colors",children:"Browse personalised books →"})})]})})})]})},Zn=r=>r==="SG"?{price:15,shipping:5,currencySymbol:"S$"}:r==="US"?{price:15,shipping:8,currencySymbol:"$"}:{price:299,shipping:100,currencySymbol:"₹"},Mj=[{id:"boys",gender:"boys",title:"Boy's Sticker Pack",description:"Personalized Sticker Packs For Your Little Boy",ageRange:"2 - 10",gradient:"from-cyan-100 via-blue-50 to-teal-100",accentColor:"blue"},{id:"girls",gender:"girls",title:"Girl's Sticker Pack",description:"Personalized Sticker Packs For Your Little Girl",ageRange:"2 - 10",gradient:"from-pink-100 via-purple-50 to-pink-100",accentColor:"pink"}],Bj=()=>{const r=_t(),{buildLink:t,region:s}=ht(),a=Zn(s),n=a.currencySymbol,i=a.price,o=l=>{r(t(`/stickers/${l}/personalize`))};return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs(as,{children:[e.jsx("title",{children:"Personalized Stickers for Kids | TalesBerry"}),e.jsx("meta",{name:"description",content:"Create personalized sticker packs featuring your child's face. 2 sheets with 20 stickers each. Perfect for lunch boxes, notebooks, and more!"})]}),e.jsxs("div",{className:"relative overflow-hidden pt-6 md:pt-16 pb-12",children:[e.jsx("div",{className:"absolute inset-0 bg-white"}),e.jsx("div",{className:"relative max-w-7xl mx-auto px-4 text-center",children:e.jsxs(Ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.6},children:[e.jsxs("div",{className:"inline-flex items-center gap-2 bg-purple-100 text-purple-700 px-4 py-2 rounded-full text-sm font-medium mb-4",children:[e.jsx(Ba,{className:"w-4 h-4"}),e.jsx("span",{children:"New Product"})]}),e.jsx("h1",{className:"text-4xl md:text-5xl font-bold text-purple-900 mb-4",children:"Personalized Stickers"}),e.jsx("p",{className:"text-lg md:text-xl text-gray-600 max-w-2xl mx-auto mb-6",children:"Turn your child into the star of their own sticker collection! Each pack includes 2 sheets with 14 personalised stickers and 50+ total stickers."}),e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-center gap-2 md:gap-4 text-sm text-gray-500",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-4 h-4 text-green-500 flex-shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),e.jsx("span",{children:"2 Sheets"})]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-4 h-4 text-green-500 flex-shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),e.jsx("span",{children:"14 Personalised Stickers"})]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-4 h-4 text-green-500 flex-shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),e.jsx("span",{children:"High Quality Print"})]})]})]})})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 pb-20",children:[e.jsx("div",{className:"grid md:grid-cols-2 gap-8",children:Mj.map((l,c)=>e.jsx(Ie.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.5,delay:c*.1},className:"group",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg overflow-hidden hover:shadow-xl transition-all duration-300 border border-gray-100",children:[e.jsx("div",{className:`relative h-72 md:h-80 bg-gradient-to-br ${l.gradient} p-6 flex items-center justify-center`,children:s==="IN"?e.jsxs("div",{className:"grid grid-cols-2 gap-3 w-full h-full",children:[e.jsx("img",{src:`${ot}/${l.gender==="boys"?"stickers_thumbnail_boy":"stickers_thumbnail_girl"}/1.jpg`,alt:`${l.gender==="boys"?"Boy":"Girl"} sticker sample 1`,className:"w-full h-full object-cover rounded-xl shadow-lg"}),e.jsx("img",{src:`${ot}/${l.gender==="boys"?"stickers_thumbnail_boy":"stickers_thumbnail_girl"}/2.jpg`,alt:`${l.gender==="boys"?"Boy":"Girl"} sticker sample 2`,className:"w-full h-full object-cover rounded-xl shadow-lg"})]}):e.jsxs("div",{className:"relative w-full h-full",children:[e.jsx("div",{className:`absolute top-4 left-4 w-20 h-20 rounded-2xl bg-white/80 shadow-lg flex items-center justify-center transform -rotate-6 ${l.accentColor==="pink"?"border-2 border-pink-200":"border-2 border-blue-200"}`,children:e.jsx("span",{className:"text-3xl",children:"⭐"})}),e.jsx("div",{className:`absolute top-8 right-8 w-24 h-24 rounded-2xl bg-white/80 shadow-lg flex items-center justify-center transform rotate-6 ${l.accentColor==="pink"?"border-2 border-pink-200":"border-2 border-blue-200"}`,children:e.jsx("span",{className:"text-4xl",children:l.gender==="girls"?"👧":"👦"})}),e.jsx("div",{className:`absolute bottom-12 left-12 w-16 h-16 rounded-xl bg-white/80 shadow-lg flex items-center justify-center transform rotate-12 ${l.accentColor==="pink"?"border-2 border-pink-200":"border-2 border-blue-200"}`,children:e.jsx("span",{className:"text-2xl",children:"🎨"})}),e.jsx("div",{className:`absolute bottom-8 right-16 w-20 h-20 rounded-2xl bg-white/80 shadow-lg flex items-center justify-center transform -rotate-12 ${l.accentColor==="pink"?"border-2 border-pink-200":"border-2 border-blue-200"}`,children:e.jsx("span",{className:"text-3xl",children:l.gender==="girls"?"🌸":"🚀"})}),e.jsx("div",{className:`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-28 h-28 rounded-full bg-white shadow-xl flex items-center justify-center ${l.accentColor==="pink"?"border-4 border-pink-300":"border-4 border-blue-300"}`,children:e.jsx("span",{className:"text-5xl",children:l.gender==="girls"?"💖":"💙"})})]})}),e.jsxs("div",{className:"p-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:l.title}),e.jsx("p",{className:"text-gray-600 mb-3",children:l.description}),e.jsxs("p",{className:"text-sm text-gray-500 mb-4",children:["Age: ",l.ageRange]}),e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("div",{className:"text-2xl font-bold text-purple-600",children:[n,i,e.jsx("span",{className:"text-sm font-normal text-gray-500 ml-1",children:"+ shipping"})]})}),e.jsx("button",{onClick:()=>o(l.gender),className:"w-full py-3 px-6 rounded-xl font-semibold text-white transition-all duration-300 transform hover:scale-[1.02] bg-black hover:bg-gray-800",children:"Personalise"})]})]})},l.id))}),e.jsxs(Ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.3},className:"mt-12 bg-white rounded-2xl p-8 shadow-lg border border-gray-100",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900 mb-4 text-center",children:"What's Included?"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 text-center",children:[e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-3",children:e.jsx("span",{className:"text-2xl",children:"📄"})}),e.jsx("h4",{className:"font-semibold text-gray-900 mb-1",children:"2 Sticker Sheets"}),e.jsx("p",{className:"text-sm text-gray-600",children:"High-quality printed sheets"})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"w-12 h-12 bg-pink-100 rounded-full flex items-center justify-center mx-auto mb-3",children:e.jsx("span",{className:"text-2xl",children:"🌟"})}),e.jsx("h4",{className:"font-semibold text-gray-900 mb-1",children:"14 Personalised Stickers"}),e.jsx("p",{className:"text-sm text-gray-600",children:"50+ total stickers"})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3",children:e.jsx("span",{className:"text-2xl",children:"✨"})}),e.jsx("h4",{className:"font-semibold text-gray-900 mb-1",children:"Premium Quality"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Durable & waterproof stickers"})]})]})]})]})]})},Fj=()=>{const{gender:r}=Xr(),t=_t(),{region:s,buildLink:a}=ht(),[n,i]=p.useState(null),[o,l]=p.useState(""),[c,u]=p.useState(r==="girls"?"Girl":"Boy"),[d,h]=p.useState(""),[m,g]=p.useState(""),[f,v]=p.useState(s==="SG"?"+65":s==="US"?"+1":"+91"),[x,j]=p.useState(!1),[b,y]=p.useState(null),[S,T]=p.useState(!1),[I,E]=p.useState(!1),[O,V]=p.useState(null),[J,U]=p.useState(!1),[Ge,Te]=p.useState({x:0,y:0}),[Me,_e]=p.useState(1),[Se,ue]=p.useState(null),[re,Ne]=p.useState(null),[fe,qe]=p.useState(!1),pe=Zn(s),Xe=pe.currencySymbol,ft=pe.price,Ze=[`${ot}/stickers_thumbnail_boy/1.jpg`,`${ot}/stickers_thumbnail_boy/2.jpg`];p.useEffect(()=>{s==="IN"&&re&&qe(!0)},[re,s]),p.useEffect(()=>{u(r==="girls"?"Girl":"Boy")},[r]);const ke=he=>{var Fe;const Be=(Fe=he.target.files)==null?void 0:Fe[0];if(Be){if(!Be.type.match(/^image\/(jpeg|jpg|png)$/)){alert("Please upload a JPG or PNG image only.");return}if(Be.size>10*1024*1024){alert("Image size must be less than 10MB.");return}const Pe=new Image;Pe.onload=()=>{if(Pe.width<100||Pe.height<100){alert("Image resolution must be at least 100 × 100 pixels.");return}if(Pe.width>6e3||Pe.height>6e3){alert("Image resolution must be less than 6000 × 6000 pixels.");return}i(Be),V(URL.createObjectURL(Be)),U(!0),Ne(null)},Pe.src=URL.createObjectURL(Be)}},Ce=he=>new Promise((Be,Fe)=>{const Pe=new Image;Pe.addEventListener("load",()=>Be(Pe)),Pe.addEventListener("error",K=>Fe(K)),Pe.src=he}),B=async(he,Be)=>{const Fe=await Ce(he),Pe=document.createElement("canvas"),K=Pe.getContext("2d");if(!K)throw new Error("Canvas context not available");return Pe.width=Be.width,Pe.height=Be.height,K.drawImage(Fe,Be.x,Be.y,Be.width,Be.height,0,0,Be.width,Be.height),new Promise((z,ce)=>{Pe.toBlob(le=>{le?z(le):ce(new Error("Canvas is empty"))},"image/jpeg",.95)})},st=async()=>{if(!(!O||!Se||!n))try{const he=await B(O,Se),Be=new File([he],n.name,{type:"image/jpeg"});Ne(Be),U(!1),O&&URL.revokeObjectURL(O)}catch(he){console.error("Error cropping image:",he),alert("Failed to crop image. Please try again.")}},Ye=()=>{Ne(null),i(null),O&&URL.revokeObjectURL(O),V(null)},Y=he=>new Promise((Be,Fe)=>{const Pe=new Image,K=URL.createObjectURL(he);Pe.onload=()=>{try{const z=document.createElement("canvas");z.width=Pe.naturalWidth,z.height=Pe.naturalHeight;const ce=z.getContext("2d");if(!ce)return URL.revokeObjectURL(K),Fe(new Error("Canvas not supported"));ce.drawImage(Pe,0,0);const le=z.toDataURL("image/jpeg",.92);URL.revokeObjectURL(K),Be(le)}catch(z){URL.revokeObjectURL(K),Fe(z)}},Pe.onerror=()=>{URL.revokeObjectURL(K);const z=new FileReader;z.onload=()=>Be(z.result),z.onerror=ce=>Fe(ce),z.readAsDataURL(he)},Pe.src=K}),ie=async()=>{if(!re){alert("Please upload a photo of your child.");return}if(!d){alert("Please enter your email address.");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)){alert("Please enter a valid email address.");return}const Be=f==="+91",Fe=f==="+1",Pe=m==null?void 0:m.trim();if(Be&&!Pe){alert("Please enter your WhatsApp number.");return}if(Pe){let K,z;if(Be?(K=/^[6-9]\d{9}$/,z="Please enter a valid 10-digit WhatsApp number starting with 6-9."):Fe?(K=/^\d{10}$/,z="Please enter a valid 10-digit phone number."):(K=/^\d{8}$/,z="Please enter a valid 8-digit WhatsApp number."),!K.test(Pe)){alert(z);return}}if(!o){alert("Please select your child's age.");return}if(!S){alert("Please accept the consent checkbox to continue.");return}j(!0),y(null);try{const K=await fetch(yt("/api/sessions/create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({book_name:`stickers_${r}`,child_name:"TalesBerry",gender:r==="girls"?"girl":"boy",age:parseInt(o),hairstyle_preference:"wavy hair",email_id:d,whatsapp_number:m,consent_given:!0,consent_text_version:"v1.0"})});if(!K.ok)throw new Error("Failed to create session");const ce=(await K.json()).session_id;localStorage.setItem("session_id",ce);let rt=(await Y(re)).trim();/^data:image\/(jpeg|jpg|png);base64,/i.test(rt)||(rt=`data:${(re==null?void 0:re.type)||"image/jpeg"};base64,`+rt.replace(/^data:[^,]*,/,""));const Tt=await fetch(yt("/api/faces/upload-and-validate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:ce,face_image_base64:rt,filename:re.name})});let It;try{It=await Tt.json()}catch{const Zt=await Tt.text().catch(()=>"");throw new Error(Zt||"Invalid server response")}if(!Tt.ok||It.status!=="uploaded_and_validated")throw new Error(It.message||"Face validation failed");const Bt=await fetch(yt("/api/text/generate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:ce,preview_mode:!0})}),bt=await Bt.json();!Bt.ok||bt.status!=="started"?console.warn("[Stickers] Generation may not have started properly:",bt):console.log("[Stickers] Generation started successfully"),t(a(`/stickers/${r}/preview?sessionId=${encodeURIComponent(ce)}`),{state:{productType:"stickers",gender:r,childAge:o,childGender:c,email:d,whatsappNumber:m,sessionId:ce,faceImageUrl:It.face_image_url,faceImageKey:It.face_image_key,price:ft,currencySymbol:Xe}})}catch(K){y(K instanceof Error?K.message:"An error occurred. Please try again.")}},He=()=>{j(!1),y(null),i(null),Ne(null),O&&URL.revokeObjectURL(O),V(null)},Qe=r==="girls"?"Girl's Sticker Pack":"Boy's Sticker Pack",lt=r==="girls"?"from-pink-100 via-purple-50 to-pink-100":"from-cyan-100 via-blue-50 to-teal-100",gt=()=>e.jsxs("div",{className:"bg-white rounded-2xl p-4 shadow-sm border border-gray-100 mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-900 mb-3",children:"See the kids on their stickers!"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Ze.map((he,Be)=>e.jsx("div",{className:"relative aspect-[3/4] rounded-xl overflow-hidden bg-gray-100",children:e.jsx("img",{src:he,alt:`Sticker sample ${Be+1}`,className:"w-full h-full object-contain",loading:"eager"})},Be))})]}),we=()=>e.jsxs("div",{className:"mb-4",children:[s==="IN"&&e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("span",{className:"w-6 h-6 rounded-full bg-purple-500 text-white flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-xl font-bold text-gray-900",children:"Start Personalisation"})]}),s!=="IN"&&e.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-3",children:"Upload Photo"}),!J&&!re?e.jsx("div",{className:"border-2 border-dashed border-purple-300 rounded-2xl p-4 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"w-14 h-14 mx-auto bg-purple-100 rounded-full flex items-center justify-center",children:e.jsx($t,{className:"w-8 h-8 text-purple-500"})})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-3",children:"Upload a photo of your child"}),e.jsxs("label",{className:"inline-block",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:ke,className:"hidden"}),e.jsxs("span",{className:"bg-black text-white px-8 py-3 rounded-full font-medium cursor-pointer hover:bg-gray-800 transition-colors inline-flex items-center",children:["Choose Image",e.jsx($t,{className:"ml-2 w-4 h-4"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsx("button",{type:"button",onClick:()=>E(!0),className:"text-gray-900 underline text-sm font-medium hover:text-purple-600 transition-colors",children:"Image Guidelines"})}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected and safe"})]})]})}):J?e.jsxs("div",{className:"border-2 border-solid border-purple-300 rounded-2xl bg-white overflow-hidden",children:[e.jsx("div",{className:"relative w-full h-[350px] sm:h-[450px]",children:e.jsx(As,{image:O,crop:Ge,zoom:Me,aspect:1,onCropChange:Te,onZoomChange:_e,onCropComplete:(he,Be)=>{ue(Be)},cropShape:"rect",showGrid:!0})}),e.jsxs("div",{className:"p-4 border-t border-gray-200",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Zoom"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Me,onChange:he=>_e(Number(he.target.value)),className:"w-full"})]}),e.jsxs("div",{className:"flex gap-4 justify-center",children:[e.jsx("button",{onClick:()=>{U(!1),V(null),i(null),O&&URL.revokeObjectURL(O)},className:"px-6 py-2 border border-gray-300 rounded-full hover:bg-gray-50 transition-colors",children:"Change Image"}),e.jsx("button",{onClick:st,className:"px-6 py-2 bg-black text-white rounded-full hover:bg-gray-800 transition-colors",children:"Crop & Continue"})]})]})]}):e.jsx("div",{className:"border-2 border-solid border-purple-300 rounded-2xl p-4 bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mb-4",children:e.jsx("img",{src:URL.createObjectURL(re),alt:"Cropped preview",className:"w-32 h-32 object-cover rounded-lg mx-auto border-2 border-gray-200"})}),e.jsx("div",{className:"text-green-600 font-medium mb-3",children:"✓ Image cropped and ready"}),e.jsxs("button",{onClick:Ye,className:"text-black hover:text-gray-700 text-sm font-medium flex items-center gap-2 mx-auto",children:[e.jsx($t,{className:"w-4 h-4"}),"Change Image"]})]})})]}),Mt=()=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6",children:[e.jsxs("div",{className:`w-full px-4 py-4 flex items-center justify-between ${re?"bg-gray-50 cursor-pointer hover:bg-gray-100":"bg-gray-100 cursor-not-allowed opacity-70"} transition-colors`,onClick:()=>{re&&qe(!fe)},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${re?"bg-purple-500 text-white":"bg-gray-300 text-gray-600"}`,children:"2"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Personalisation Details"}),!re&&e.jsx("span",{className:"text-xs text-gray-500",children:"(Upload image first)"})]}),re&&(fe?e.jsx(qr,{className:"w-5 h-5 text-gray-500"}):e.jsx(Us,{className:"w-5 h-5 text-gray-500"}))]}),fe&&re&&e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:d,onChange:he=>h(he.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Email for receiving the soft copy",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"WhatsApp Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("select",{value:f,onChange:he=>{v(he.target.value),g("")},className:"w-24 px-2 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"+91",children:"+91"}),e.jsx("option",{value:"+65",children:"+65"}),e.jsx("option",{value:"+1",children:"+1"})]}),e.jsx("input",{type:"tel",value:m,onChange:he=>{const Be=f==="+65"?8:10;g(he.target.value.replace(/\D/g,"").slice(0,Be))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"10 digit number",maxLength:10,required:!0})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's age *"}),e.jsxs("select",{value:o,onChange:he=>l(he.target.value),className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select age"}),[2,3,4,5,6,7,8,9,10].map(he=>e.jsx("option",{value:he.toString(),children:he},he))]})]}),e.jsx("div",{className:"pt-2",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:S,onChange:he=>T(he.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:["I confirm, I am the parent or legal guardian of this child (or I have the necessary permission from the parent of this child), I am over 18, and I consent to providing these details for creating personalized stickers in accordance with the"," ",e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsxs("div",{className:"pt-4",children:[e.jsx(wt,{onClick:ie,disabled:x||!re||!d||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)||!o||!S,className:"w-full py-4 text-lg",children:"See Sticker Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]})]})]}),Z=()=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg p-6 lg:p-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-6",children:"Personalize Your Stickers"}),e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Upload Child's Photo *"}),J&&O?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"relative h-72 bg-gray-900 rounded-lg overflow-hidden",children:e.jsx(As,{image:O,crop:Ge,zoom:Me,aspect:1,onCropChange:Te,onZoomChange:_e,onCropComplete:(he,Be)=>ue(Be)})}),e.jsxs("div",{className:"mt-4 flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Zoom:"}),e.jsx("input",{type:"range",min:1,max:3,step:.1,value:Me,onChange:he=>_e(Number(he.target.value)),className:"w-32"})]}),e.jsx(wt,{onClick:st,children:"Confirm Crop"})]})]}):re?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:URL.createObjectURL(re),alt:"Cropped",className:"w-40 h-40 object-cover rounded-lg border-2 border-purple-200"}),e.jsx("button",{onClick:Ye,className:"mt-2 text-sm text-purple-600 hover:text-purple-700 underline",children:"Change Photo"})]}):e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-purple-400 transition-colors",children:[e.jsx($t,{className:"w-10 h-10 mx-auto text-gray-400 mb-3"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Click to upload a clear face photo"}),e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png",onChange:ke,className:"hidden",id:"photo-upload"}),e.jsx("label",{htmlFor:"photo-upload",className:"inline-block px-4 py-2 bg-black text-white rounded-lg cursor-pointer hover:bg-gray-800 transition-colors font-medium",children:"Choose Photo"}),e.jsx("button",{type:"button",onClick:()=>E(!0),className:"block mx-auto mt-3 text-sm text-black hover:text-gray-700 underline",children:"View Photo Guidelines"})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Email ID *"}),e.jsx("input",{type:"email",value:d,onChange:he=>h(he.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:"Your email address",required:!0})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"WhatsApp Number (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("select",{value:f,onChange:he=>{v(he.target.value),g("")},className:"w-24 px-2 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"+91",children:"+91"}),e.jsx("option",{value:"+65",children:"+65"}),e.jsx("option",{value:"+1",children:"+1"})]}),e.jsx("input",{type:"tel",value:m,onChange:he=>{const Be=f==="+65"?8:10;g(he.target.value.replace(/\D/g,"").slice(0,Be))},className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",placeholder:f==="+65"?"8 digit number":"10 digit number",maxLength:f==="+65"?8:10})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Child's Age *"}),e.jsxs("select",{value:o,onChange:he=>l(he.target.value),className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500",children:[e.jsx("option",{value:"",children:"Select age"}),[2,3,4,5,6,7,8,9,10].map(he=>e.jsx("option",{value:he.toString(),children:he},he))]})]}),e.jsx("div",{className:"pt-4 mb-6",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:S,onChange:he=>T(he.target.checked),className:"mt-1 w-4 h-4 accent-purple-500 rounded border-gray-300 focus:ring-purple-500"}),e.jsxs("span",{className:"text-sm text-gray-600 leading-relaxed",children:["I confirm, I am the parent or legal guardian of this child (or I have the necessary permission from the parent of this child), I am over 18, and I consent to providing these details for creating personalized stickers in accordance with the"," ",e.jsx("a",{href:"https://talesberry.com/policies/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-700 underline",children:"Privacy Policy"}),"."]})]})}),e.jsx(wt,{onClick:ie,disabled:x||!re||!d||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)||!o||!S,className:"w-full py-4 text-lg",children:"Continue to Preview"}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2 text-gray-500 text-sm",children:[e.jsx(vt,{className:"w-4 h-4"}),e.jsx("span",{children:"Your data is protected"})]})]});return s==="IN"?e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(Yt,{}),e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20need%20help%20with%20my%20sticker%20order!",target:"_blank",rel:"noopener noreferrer","aria-label":"24x7 WhatsApp Support",className:`fixed bottom-4 right-4 z-50 inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
            px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 pt-16",children:[e.jsx("div",{className:"text-center mb-4",children:e.jsx("h1",{className:"text-2xl font-bold text-purple-900",children:Qe})}),gt(),we(),Mt()]}),e.jsx(Po,{isOpen:x,error:b,onRetry:He}),I&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",onClick:()=>E(!1),children:e.jsxs("div",{className:"relative max-w-2xl w-full",children:[e.jsx("button",{onClick:()=>E(!1),className:"absolute -top-10 right-0 text-white hover:text-gray-300 transition-colors","aria-label":"Close guidelines",children:e.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),e.jsx("img",{src:"/photo_guidelines.jpg",alt:"Photo upload guidelines",className:"w-full h-auto rounded-lg shadow-2xl",onClick:he=>he.stopPropagation()})]})})]}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(Yt,{}),e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20need%20help%20with%20my%20sticker%20order!",target:"_blank",rel:"noopener noreferrer","aria-label":"24x7 WhatsApp Support",className:`fixed bottom-4 right-4 z-50 inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
          px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 py-8",children:[e.jsx("div",{className:"hidden lg:block mb-12",children:e.jsxs("div",{className:"flex items-center justify-between max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-500 text-white rounded-full flex items-center justify-center text-sm font-medium",children:"✓"}),e.jsx("span",{className:"ml-3 text-purple-700 font-medium",children:"Select Product"})]}),e.jsx("div",{className:"flex-1 h-1 mx-4 bg-purple-200 rounded",children:e.jsx("div",{className:"h-full w-1/2 bg-purple-500 rounded"})}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-500 text-white rounded-full flex items-center justify-center text-sm font-medium",children:"2"}),e.jsx("span",{className:"ml-3 text-purple-700 font-medium",children:"Personalize"})]}),e.jsx("div",{className:"flex-1 h-1 mx-4 bg-gray-200 rounded"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-200 text-gray-500 rounded-full flex items-center justify-center text-sm font-medium",children:"3"}),e.jsx("span",{className:"ml-3 text-gray-500",children:"Preview & Order"})]})]})}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-8 items-start",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg overflow-hidden",children:[e.jsx("div",{className:`h-48 bg-gradient-to-br ${lt} flex items-center justify-center`,children:e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-6xl",children:r==="girls"?"💖":"💙"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-800 mt-4",children:Qe})]})}),e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"space-y-3 text-sm text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),e.jsx("span",{children:"2 Sticker Sheets"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),e.jsx("span",{children:"20 Unique Stickers"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),e.jsx("span",{children:"Premium Quality Print"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),e.jsx("span",{children:"Personalized with Child's Face"})]})]})})]}),Z()]})]}),e.jsx(Po,{isOpen:x,error:b,onRetry:He}),I&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",onClick:()=>E(!1),children:e.jsxs("div",{className:"relative max-w-2xl w-full",children:[e.jsx("button",{onClick:()=>E(!1),className:"absolute -top-10 right-0 text-white hover:text-gray-300 transition-colors","aria-label":"Close guidelines",children:e.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),e.jsx("img",{src:"/photo_guidelines.jpg",alt:"Photo upload guidelines",className:"w-full h-auto rounded-lg shadow-2xl",onClick:he=>he.stopPropagation()})]})})]})},Dj=()=>{var Zt,ns,X,te;const{gender:r}=Xr(),t=Jt(),s=_t(),{region:a,buildLink:n}=ht(),i=new URLSearchParams(t.search),o=i.get("sessionId"),l=i.get("payment_success")==="true",c=t.state,u=o||(c==null?void 0:c.sessionId)||localStorage.getItem("session_id"),[d,h]=p.useState(0),[m,g]=p.useState(!1),[f,v]=p.useState(0),[x,j]=p.useState(l),[b,y]=p.useState(!1),[S,T]=p.useState(!1),[I,E]=p.useState(!1),[O,V]=p.useState(null),[J,U]=p.useState({}),[Ge,Te]=p.useState({}),[Me,_e]=p.useState({}),[Se,ue]=p.useState({}),[re,Ne]=p.useState({}),[fe,qe]=p.useState(!1),pe=p.useRef(null),Xe=p.useRef([]),ft=p.useRef(null),Ze=p.useRef({}),ke=p.useRef({}),Ce=14,B=2;p.useEffect(()=>{if(!fe)return;const $=be=>{const ee=be.target;ft.current&&!ft.current.contains(ee)&&qe(!1)};return document.addEventListener("mousedown",$,!0),document.addEventListener("touchstart",$,!0),()=>{document.removeEventListener("mousedown",$,!0),document.removeEventListener("touchstart",$,!0)}},[fe]),p.useEffect(()=>{if(x){const $=setTimeout(()=>{j(!1)},8e3);return()=>clearTimeout($)}},[x]),p.useEffect(()=>{l&&u&&(console.log("[StickerPreviewPage] Payment success detected from URL"),localStorage.setItem(`sticker_preview_payment_${u}`,"true"),localStorage.setItem(`sticker_preview_checked_${u}`,"true"),g(!0))},[l,u]),p.useEffect(()=>{if(!u)return;(async()=>{const be=localStorage.getItem(`sticker_preview_payment_${u}`),ee=localStorage.getItem(`sticker_preview_checked_${u}`);if(be==="true"){console.log("[StickerPreviewPage] Payment found in localStorage cache"),g(!0);return}if(!ee)try{console.log("[StickerPreviewPage] Checking payment status from DB for session:",u);const{data:ne}=await de.from("orders").select("payment_status").eq("session_id",u).order("created_at",{ascending:!1}).limit(1);ne&&ne.length>0&&ne[0].payment_status==="completed"&&(console.log("[StickerPreviewPage] Payment found in DB, unlocking all stickers"),localStorage.setItem(`sticker_preview_payment_${u}`,"true"),g(!0)),localStorage.setItem(`sticker_preview_checked_${u}`,"true")}catch(ne){console.warn("[StickerPreviewPage] Error checking payment status:",ne)}})()},[u]),p.useEffect(()=>{if(u){const $=localStorage.getItem(`sticker_printing_sent_timestamp_${u}`);if($){const be=parseInt($),ee=60*1e3;Date.now()-be<ee?V(be):localStorage.removeItem(`sticker_printing_sent_timestamp_${u}`)}}},[u]),p.useEffect(()=>{o?localStorage.setItem("session_id",o):u&&!o&&s(t.pathname+`?sessionId=${encodeURIComponent(u)}`,{replace:!0})},[u,o,s,t.pathname]);const{previewData:st,images:Ye,isLoading:Y,error:ie}=$m(u,!0);p.useEffect(()=>{if(!Ye||Ye.length===0)return;console.log("[STICKER-VARIANTS] Processing backend images for variants...",Ye.length);const $={};Ye.forEach(ee=>{const ne=ee.key.match(/^(sticker_\d+)(?:_variant(\d+))?$/);if(ne){const M=ne[1],at=ne[2]?parseInt(ne[2]):1;$[M]||($[M]=[]),$[M].push({key:ee.key,url:ee.url,variantNum:at}),console.log("[STICKER-VARIANTS] Found variant:",{baseKey:M,variantNum:at,key:ee.key})}});const be=[];ue(ee=>{const ne={...ee};return Object.keys($).forEach(M=>{var ts;const at=M.match(/sticker_(\d+)/);if(!at)return;const ye=parseInt(at[1])-1,tt=$[M],De=ee[ye]||[],St=new Set(De.map(et=>et.variantKey)),Ae=[];if(tt.forEach(et=>{St.has(et.key)||(Ae.push(et),console.log("[STICKER-VARIANTS] NEW variant detected:",et.key,"for page",ye))}),Ae.length===0)return;const Q=[...De],$e=Ge[ye];if($e&&typeof $e.expectedVariantIndex=="number"&&((ts=Q[$e.expectedVariantIndex])==null?void 0:ts.url)==="GENERATING"&&Ae.length>0){const et=Ae.shift();Q[$e.expectedVariantIndex]={url:et.url,timestamp:Date.now(),variantKey:et.key},be.push(ye),console.log("[STICKER-VARIANTS] Replaced placeholder at expected index",$e.expectedVariantIndex,"for page",ye)}else if(Ae.length>0){const et=Q.findIndex(ct=>ct.url==="GENERATING");if(et!==-1){const ct=Ae.shift();Q[et]={url:ct.url,timestamp:Date.now(),variantKey:ct.key},be.push(ye),console.log("[STICKER-VARIANTS] Replaced GENERATING placeholder at index",et,"for page",ye)}}Ae.forEach(et=>{Q.push({url:et.url,timestamp:Date.now(),variantKey:et.key})}),Q.sort((et,ct)=>{const zt=et.variantKey.match(/_variant(\d+)/)?parseInt(et.variantKey.match(/_variant(\d+)/)[1]):1,Nt=ct.variantKey.match(/_variant(\d+)/)?parseInt(ct.variantKey.match(/_variant(\d+)/)[1]):1;return zt-Nt}),ne[ye]=Q}),ne}),be.length>0&&be.forEach(ee=>{U(ne=>({...ne,[ee]:!1})),Te(ne=>{const M={...ne};return delete M[ee],M}),_e(ne=>({...ne,[ee]:100})),Ze.current[ee]&&(clearInterval(Ze.current[ee]),delete Ze.current[ee]),ke.current[ee]=!1})},[Ye,Ge]),p.useEffect(()=>{u&&Object.keys(Se).length>0&&localStorage.setItem(`sticker_preview_variants_${u}`,JSON.stringify(Se))},[Se,u]),p.useEffect(()=>{u&&Object.keys(re).length>0&&localStorage.setItem(`sticker_preview_selected_${u}`,JSON.stringify(re))},[re,u]),p.useEffect(()=>{if(u)try{const $=localStorage.getItem(`sticker_preview_variants_${u}`);if($){const ee=JSON.parse($);console.log("[STICKER-VARIANTS] Loaded variants from localStorage:",Object.keys(ee).length,"pages"),ue(ee)}const be=localStorage.getItem(`sticker_preview_selected_${u}`);if(be){const ee=JSON.parse(be);console.log("[STICKER-VARIANTS] Loaded selected indices from localStorage:",ee),Ne(ee)}}catch($){console.error("[STICKER-VARIANTS] Error loading from localStorage:",$)}},[u]);const He=a==="SG"?"S$":"₹",Qe=a==="SG"?15:399,lt=$=>{const be=`sticker_${$+1}`,ee=Ye.find(ne=>ne.key===be);return(ee==null?void 0:ee.url)||null},gt=Array.from({length:Ce},($,be)=>({index:be,isLocked:!m&&be>=B,label:`Sticker ${be+1}`,imageUrl:m||be<B?lt(be):null})),we=$=>{var ee,ne;h($),window.innerWidth<1024&&window.scrollTo({top:0,behavior:"smooth"});const be=Xe.current[$];if(be){const M=be.getBoundingClientRect(),at=((ee=pe.current)==null?void 0:ee.offsetParent)||((ne=pe.current)==null?void 0:ne.parentElement);if(at){const ye=at.getBoundingClientRect(),tt=M.height+12,De=Math.max(0,M.top-ye.top-tt);v(De)}}},Mt=()=>{s(n("/stickers/delivery"),{state:{productType:"stickers",gender:r,childAge:c==null?void 0:c.childAge,childGender:c==null?void 0:c.childGender,email:c==null?void 0:c.email,sessionId:u,faceImageUrl:c==null?void 0:c.faceImageUrl,price:Qe,currencySymbol:He}})},Z=()=>{s(n(`/stickers/${r}/personalize`))},he=()=>{if(!O)return!1;const $=60*1e3;return Date.now()-O<$},Be=async()=>{try{if(console.log("[SEND FOR PRINTING - STICKERS] Sending print confirmation for session:",u),!u){alert("Session ID not found. Please try again.");return}T(!0),E(!0);const $={};gt.forEach((ee,ne)=>{const M=Se[ne]||[],at=re[ne]||0,ye=M[at],tt=(ye==null?void 0:ye.url)||ee.imageUrl;tt&&tt!=="GENERATING"&&($[ne.toString()]=tt)}),console.log("[SEND FOR PRINTING - STICKERS] Sending pages:",$),fetch(yt("/api/orders/send-print-confirmation"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:u,pages:$,product_type:"stickers"})}).then(ee=>{if(console.log("[SEND FOR PRINTING - STICKERS] API response status:",ee.status),!ee.ok)console.error("[SEND FOR PRINTING - STICKERS] API error:",ee.status);else return ee.json().then(ne=>{console.log("[SEND FOR PRINTING - STICKERS] API success:",ne)})}).catch(ee=>{console.error("[SEND FOR PRINTING - STICKERS] Error:",ee)}),await new Promise(ee=>setTimeout(ee,5e3)),T(!1),E(!1),y(!1);const be=Date.now();V(be),u&&localStorage.setItem(`sticker_printing_sent_timestamp_${u}`,be.toString())}catch($){console.error("[SEND FOR PRINTING - STICKERS] Error:",$),T(!1),E(!1),y(!1),alert("Failed to send stickers for printing. Please try again.")}},Fe=async $=>{if(console.log("[REGENERATE-STICKER] Button clicked for sticker:",$),ke.current[$]){alert("This sticker is already being regenerated. Please wait.");return}const be=Se[$]||[];if(be.length>=7){alert("Maximum 7 variants reached for this sticker");return}if(ke.current[$]=!0,!u){alert("No session ID found"),ke.current[$]=!1;return}const ee=`sticker_${$+1}`;console.log("[REGENERATE-STICKER] Starting regeneration for:",ee);const ne=be.map(tt=>tt.variantKey).filter(Boolean);console.log("[REGENERATE-STICKER] Existing variant keys:",ne);const M=be.length,at={url:"GENERATING",timestamp:Date.now(),variantKey:`temp_${Date.now()}`};ue(tt=>({...tt,[$]:[...be,at]})),Ne(tt=>({...tt,[$]:M})),U(tt=>({...tt,[$]:!0}));const ye=Date.now();Te(tt=>({...tt,[$]:{startTime:ye,expectedVariantIndex:M}})),_e(tt=>({...tt,[$]:0})),Ze.current[$]&&clearInterval(Ze.current[$]),Ze.current[$]=setInterval(()=>{const tt=Date.now()-ye,De=Math.min(95,tt/18e4*100);_e(St=>({...St,[$]:De}))},1e3);try{const tt={session_id:u,page:ee};console.log("[REGENERATE-STICKER] Sending request to /api/preview/variant:",tt);const De=await fetch(yt("/api/preview/variant"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(tt)});if(!De.ok)throw new Error("Variant request failed");const St=await De.json();if(!St.status||St.status!=="started"){U(Q=>({...Q,[$]:!1})),ke.current[$]=!1,alert(St.message||"Failed to start variant generation");return}console.log("[REGENERATE-STICKER] Variant generation started, polling preview API for new variant..."),(async()=>{var $e;const Q=`sticker_${$+1}_variant`;for(let ts=0;ts<36;ts++){await new Promise(et=>setTimeout(et,5e3));try{const et=await fetch(yt(`/api/preview/${u}?t=${Date.now()}`),{cache:"no-store"});if(!et.ok)continue;const zt=($e=(await et.json()).images)==null?void 0:$e.filter(Nt=>Nt.key.startsWith(Q)&&!ne.includes(Nt.key));if(zt&&zt.length>0){const Nt=zt[0];console.log("[POLL] Found new variant:",Nt.key,Nt.url),ue(Ft=>{var ss;const Ct=[...Ft[$]||[]];return((ss=Ct[M])==null?void 0:ss.url)==="GENERATING"&&(Ct[M]={url:Nt.url,timestamp:Date.now(),variantKey:Nt.key}),{...Ft,[$]:Ct}}),U(Ft=>({...Ft,[$]:!1})),Te(Ft=>{const Ct={...Ft};return delete Ct[$],Ct}),_e(Ft=>({...Ft,[$]:100})),Ze.current[$]&&(clearInterval(Ze.current[$]),delete Ze.current[$]),ke.current[$]=!1;return}}catch(et){console.error("[POLL] Error fetching preview:",et)}}console.error("[POLL] Variant not found after 3 minutes"),U(ts=>({...ts,[$]:!1})),Te(ts=>{const et={...ts};return delete et[$],et}),Ze.current[$]&&(clearInterval(Ze.current[$]),delete Ze.current[$]),ke.current[$]=!1})().catch(console.error)}catch(tt){console.error("[REGENERATE-STICKER] Error:",tt),U(De=>({...De,[$]:!1})),ke.current[$]=!1,alert("Failed to regenerate sticker")}},Pe=async($,be)=>{console.log("[REGENERATE-NEW-FACE-STICKER] Button clicked for sticker:",$);const ee=Se[$]||[];if(ee.length>=7){alert("Maximum 7 variants reached for this sticker");return}if(ke.current[$]){alert("This sticker is already being regenerated. Please wait.");return}if(ke.current[$]=!0,!u){alert("No session ID found"),ke.current[$]=!1;return}const ne=`sticker_${$+1}`;console.log("[REGENERATE-NEW-FACE-STICKER] Starting with new face for:",ne);const M=ee.map(De=>De.variantKey).filter(Boolean);console.log("[REGENERATE-NEW-FACE-STICKER] Existing variant keys:",M);const at=ee.length,ye={url:"GENERATING",timestamp:Date.now(),variantKey:`temp_${Date.now()}`};ue(De=>({...De,[$]:[...ee,ye]})),Ne(De=>({...De,[$]:at})),U(De=>({...De,[$]:!0}));const tt=Date.now();Te(De=>({...De,[$]:{startTime:tt,expectedVariantIndex:at}})),_e(De=>({...De,[$]:0})),Ze.current[$]&&clearInterval(Ze.current[$]),Ze.current[$]=setInterval(()=>{const De=Date.now()-tt,St=Math.min(95,De/18e4*100);_e(Ae=>({...Ae,[$]:St}))},1e3);try{const De=new FormData;De.append("session_id",u),De.append("page",ne),De.append("page_key",ne),De.append("face_image",be),console.log("[REGENERATE-NEW-FACE-STICKER] Sending request...");const St=await fetch(yt("/api/preview/variant-new-face"),{method:"POST",body:De});if(!St.ok)throw new Error("Variant with new face request failed");const Ae=await St.json();if(!Ae.status||Ae.status!=="started"){U($e=>({...$e,[$]:!1})),ke.current[$]=!1,alert(Ae.message||"Failed to start variant generation");return}console.log("[REGENERATE-NEW-FACE-STICKER] Generation started, polling preview API for new variant..."),(async()=>{var ts;const $e=`sticker_${$+1}_variant`;for(let et=0;et<36;et++){await new Promise(ct=>setTimeout(ct,5e3));try{const ct=await fetch(yt(`/api/preview/${u}?t=${Date.now()}`),{cache:"no-store"});if(!ct.ok)continue;const Nt=(ts=(await ct.json()).images)==null?void 0:ts.filter(Ft=>Ft.key.startsWith($e)&&!M.includes(Ft.key));if(Nt&&Nt.length>0){const Ft=Nt[0];console.log("[POLL-NEW-FACE] Found new variant:",Ft.key,Ft.url),ue(Ct=>{var is;const ss=[...Ct[$]||[]];return((is=ss[at])==null?void 0:is.url)==="GENERATING"&&(ss[at]={url:Ft.url,timestamp:Date.now(),variantKey:Ft.key}),{...Ct,[$]:ss}}),U(Ct=>({...Ct,[$]:!1})),Te(Ct=>{const ss={...Ct};return delete ss[$],ss}),_e(Ct=>({...Ct,[$]:100})),Ze.current[$]&&(clearInterval(Ze.current[$]),delete Ze.current[$]),ke.current[$]=!1;return}}catch(ct){console.error("[POLL-NEW-FACE] Error fetching preview:",ct)}}console.error("[POLL-NEW-FACE] Variant not found after 3 minutes"),U(et=>({...et,[$]:!1})),Te(et=>{const ct={...et};return delete ct[$],ct}),Ze.current[$]&&(clearInterval(Ze.current[$]),delete Ze.current[$]),ke.current[$]=!1})().catch(console.error)}catch(De){console.error("[REGENERATE-NEW-FACE-STICKER] Error:",De),U(St=>({...St,[$]:!1})),ke.current[$]=!1,alert("Failed to regenerate sticker with new face")}},K=$=>{var M;const be=Se[$]||[],ee=re[$]||0,ne=be[ee];if(ne&&ne.url!=="GENERATING")return ne.url;if((ne==null?void 0:ne.url)==="GENERATING"&&ee>0){const at=be[ee-1];if(at&&at.url!=="GENERATING")return at.url}if((ne==null?void 0:ne.url)==="GENERATING"&&be.length>0){const at=be.find(ye=>ye.url!=="GENERATING");if(at)return at.url}return((M=gt[$])==null?void 0:M.imageUrl)||null},z=$=>{const be=Se[$]||[],ee=re[$]||0,ne=be[ee];return(ne==null?void 0:ne.url)==="GENERATING"&&!!Ge[$]};if(!u)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-4",children:"Preview Not Available"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Please start the personalization process first."}),e.jsx("button",{onClick:()=>s(n("/stickers")),className:"px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors",children:"Go to Stickers"})]})});const ce=r==="girls"?"Girl's Sticker Pack":"Boy's Sticker Pack",le=r==="girls"?"from-pink-200 via-purple-100 to-pink-200":"from-cyan-200 via-blue-100 to-teal-200",rt=gt[d],Ve=rt.isLocked,Tt=rt.imageUrl,It=!Ve&&!Tt&&Y,Bt=gt.filter($=>!$.isLocked&&$.imageUrl).length,bt=gt.filter($=>$.imageUrl).length,me=m&&bt===Ce;return e.jsxs("div",{className:"min-h-screen bg-white md:pt-20",children:[e.jsx(Yt,{}),e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20need%20help%20with%20my%20sticker%20preview!",target:"_blank",rel:"noopener noreferrer","aria-label":"24x7 WhatsApp Support",className:`fixed bottom-4 right-4 z-50 inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
          px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),x&&e.jsx("div",{className:"fixed top-4 left-1/2 transform -translate-x-1/2 z-50",children:e.jsxs("div",{className:"bg-green-500 text-white px-6 py-4 rounded-lg shadow-xl flex items-center gap-3 max-w-md animate-in fade-in slide-in-from-top-4 duration-300",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Payment Successful!"}),e.jsx("p",{className:"text-sm",children:"All stickers unlocked. Generating your complete pack..."})]}),e.jsx("button",{onClick:()=>j(!1),className:"flex-shrink-0 ml-4 text-white hover:text-gray-200 transition-colors",children:e.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),e.jsx("div",{className:"hidden md:block bg-white border-b",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:ce}),e.jsx("p",{className:"text-gray-600 text-sm mt-1",children:m?`${bt} of ${Ce} sticker designs generated`:`Preview ${B} of ${Ce} sticker designs`})]}),e.jsxs("button",{onClick:Z,className:"flex items-center text-gray-600 hover:text-gray-800 transition-colors",children:[e.jsx(Ut,{className:"w-5 h-5 mr-1"}),"Back"]})]})})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:e.jsxs("div",{className:"flex flex-col lg:flex-row gap-8 items-start relative",children:[e.jsx("div",{className:"lg:w-80 order-2 lg:order-1",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-lg p-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:m?"Your Stickers":"Sticker Preview"}),m?e.jsx("div",{className:`mb-4 p-3 rounded-lg ${me?"bg-green-100 border border-green-200":"bg-blue-100 border border-blue-200"}`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[me?e.jsx("svg",{className:"w-4 h-4 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}):e.jsx(Ue,{className:"w-4 h-4 animate-spin text-blue-600"}),e.jsx("span",{className:`text-sm font-medium ${me?"text-green-900":"text-blue-900"}`,children:me?"All stickers ready!":`${bt}/${Ce} generated`})]})}):Y&&Bt<B&&e.jsxs("div",{className:"mb-4 p-3 bg-primary-100 border border-primary-200 rounded-lg flex items-center gap-2",children:[e.jsx(Ue,{className:"w-4 h-4 text-primary-600 animate-spin"}),e.jsx("span",{className:"text-primary-800 text-sm font-medium",children:"Generating preview..."})]}),ie&&(st==null?void 0:st.status)==="failure"&&e.jsx("div",{className:"mb-4 p-3 bg-red-100 border border-red-200 rounded-lg",children:e.jsxs("p",{className:"text-red-800 text-sm font-medium",children:["Error: ",ie]})}),e.jsx("div",{className:"space-y-4",children:Array.from({length:Math.ceil(Ce/2)}).map(($,be)=>{const ee=be*2,ne=ee+1,M=ne<Ce;return e.jsx("div",{className:"relative bg-white rounded-lg shadow-xl overflow-hidden transition-transform duration-300 hover:scale-[1.02]",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{ref:at=>Xe.current[ee]=at,className:`relative flex-1 cursor-pointer transition-all duration-300 ${d===ee?"ring-2 ring-primary-500 ring-inset":"opacity-70 hover:opacity-100"}`,onClick:()=>we(ee),children:e.jsxs("div",{className:"aspect-square relative",children:[gt[ee].isLocked?e.jsx("div",{className:`w-full h-full bg-gradient-to-br ${le} flex items-center justify-center`,children:e.jsxs("div",{className:"bg-black/80 rounded-md px-2 py-1 flex items-center gap-1",children:[e.jsx(vt,{className:"w-3 h-3 text-white"}),e.jsx("span",{className:"text-white text-[10px] font-medium",children:"Locked"})]})}):gt[ee].imageUrl?e.jsx("img",{src:gt[ee].imageUrl,alt:`Sticker ${ee+1}`,className:"w-full h-full object-cover"}):e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-4 h-4 animate-spin text-primary-600 mb-1"}),e.jsx("div",{className:"text-[10px] font-medium text-primary-700",children:"Loading..."})]}),e.jsx("div",{className:"absolute bottom-1 right-1 bg-black bg-opacity-50 text-white text-xs px-1 py-0.5 rounded",children:ee+1})]})}),M&&e.jsx("div",{className:"absolute left-1/2 top-0 bottom-0 w-1 transform -translate-x-1/2 bg-gradient-to-r from-transparent via-gray-400/30 to-transparent pointer-events-none z-10"}),M&&e.jsx("div",{ref:at=>Xe.current[ne]=at,className:`relative flex-1 cursor-pointer transition-all duration-300 border-l border-gray-200/50 ${d===ne?"ring-2 ring-primary-500 ring-inset":"opacity-70 hover:opacity-100"}`,onClick:()=>we(ne),children:e.jsxs("div",{className:"aspect-square relative",children:[gt[ne].isLocked?e.jsx("div",{className:`w-full h-full bg-gradient-to-br ${le} flex items-center justify-center`,children:e.jsxs("div",{className:"bg-black/80 rounded-md px-2 py-1 flex items-center gap-1",children:[e.jsx(vt,{className:"w-3 h-3 text-white"}),e.jsx("span",{className:"text-white text-[10px] font-medium",children:"Locked"})]})}):gt[ne].imageUrl?e.jsx("img",{src:gt[ne].imageUrl,alt:`Sticker ${ne+1}`,className:"w-full h-full object-cover"}):e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50",children:[e.jsx(Ue,{className:"w-4 h-4 animate-spin text-primary-600 mb-1"}),e.jsx("div",{className:"text-[10px] font-medium text-primary-700",children:"Loading..."})]}),e.jsx("div",{className:"absolute bottom-1 right-1 bg-black bg-opacity-50 text-white text-xs px-1 py-0.5 rounded",children:ne+1})]})})]})},`spread-${be}`)})})]})}),e.jsx("div",{ref:pe,className:"flex-1 order-1 lg:order-2 lg:absolute lg:right-8 lg:w-[calc(50%-2rem)] lg:max-w-3xl lg:z-30 transition-all duration-300",style:{top:f>0?`${f}px`:void 0},children:e.jsxs("div",{className:"bg-white rounded-xl shadow-lg p-2 lg:p-3 h-full flex flex-col overflow-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 lg:mb-3",children:[e.jsxs("h2",{className:"text-xl font-semibold text-gray-800",children:["Sticker ",d+1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>h(Math.max(0,d-1)),disabled:d===0,className:"p-2 rounded-lg bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:e.jsx(Ut,{className:"w-5 h-5"})}),e.jsxs("span",{className:"text-sm text-gray-600 min-w-[80px] text-center",children:[d+1," of ",Ce]}),e.jsx("button",{onClick:()=>h(Math.min(Ce-1,d+1)),disabled:d===Ce-1,className:"p-2 rounded-lg bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:e.jsx(gs,{className:"w-5 h-5"})})]})]}),e.jsxs("div",{className:"relative bg-gray-50 rounded-lg p-2 lg:p-4 flex flex-col items-center justify-center min-h-[400px] lg:min-h-[600px]",children:[(()=>{const $=Se[d]||[],be=re[d]||0,ee=K(d);return $.length>=1&&!Ve&&ee?e.jsxs("div",{className:"mb-2 bg-white rounded-full shadow-lg px-4 py-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-gray-600",children:$.length===1?"Variant:":"Variants:"}),$.map((ne,M)=>{const at=ne.url==="GENERATING";return e.jsx("button",{onClick:()=>{Ne(ye=>({...ye,[d]:M}))},className:`w-7 h-7 rounded-full flex items-center justify-center text-xs font-semibold transition-all ${be===M?"bg-primary-600 text-white shadow-md":at?"bg-yellow-100 text-yellow-600 animate-pulse":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:at?e.jsx(Ue,{className:"w-3 h-3 animate-spin"}):M+1},M)})]}):null})(),e.jsx("div",{className:"relative w-full max-w-md aspect-square",children:z(d)?e.jsxs("div",{className:"w-full h-full relative rounded-lg overflow-hidden",children:[(()=>{var ne,M;const $=Se[d]||[],be=re[d]||0,ee=((ne=$[be-1])==null?void 0:ne.url)||((M=$[0])==null?void 0:M.url)||Tt;return ee&&ee!=="GENERATING"?e.jsx("img",{src:ee,alt:"Generating...",className:"w-full h-full object-cover blur-md"}):null})(),e.jsxs("div",{className:"absolute inset-0 bg-black bg-opacity-40 flex flex-col items-center justify-center",children:[e.jsx(Ue,{className:"w-16 h-16 animate-spin text-white mb-4"}),e.jsxs("div",{className:"text-lg font-medium text-white mb-2",children:["Generating variant ",(re[d]||0)+1,"..."]}),e.jsx("div",{className:"w-3/4 bg-gray-200 rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:"bg-primary-500 h-full transition-all duration-1000 ease-out",style:{width:`${Me[d]||0}%`}})}),e.jsxs("div",{className:"text-sm text-white mt-2",children:[Math.round(Me[d]||0),"% complete"]})]})]}):It?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50 rounded-lg shadow-lg",children:[e.jsx(Ue,{className:"w-16 h-16 animate-spin text-primary-600 mb-4"}),e.jsxs("div",{className:"text-lg font-medium text-primary-800 mb-4 px-6 text-center",children:["Generating sticker ",d+1,"..."]}),e.jsx("p",{className:"text-sm text-primary-600",children:"This usually takes 30-60 seconds"})]}):Ve?e.jsxs("div",{className:`w-full h-full relative rounded-lg overflow-hidden shadow-lg bg-gradient-to-br ${le}`,children:[e.jsx("div",{className:"absolute top-4 right-4",children:e.jsx(vt,{className:"w-8 h-8 text-black drop-shadow-lg"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center p-4",children:e.jsx("div",{className:"bg-black/70 rounded-lg p-4 shadow-xl max-w-xs",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("div",{className:"text-lg font-bold mb-2",children:"Sticker Locked"}),e.jsx("div",{className:"text-sm opacity-90",children:"Full sticker pack will be unlocked after your purchase."})]})})})]}):K(d)?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:K(d),alt:`Sticker ${d+1}`,className:`w-full h-full object-cover rounded-lg shadow-lg transition-all duration-300 ${J[d]?"blur-sm opacity-70":""}`}),e.jsx("div",{className:"absolute top-1/2 right-4 transform -translate-y-1/2",children:e.jsxs("div",{className:"relative",ref:ft,children:[e.jsx("button",{onClick:$=>{$.stopPropagation(),qe(!fe)},className:"bg-white hover:bg-gray-50 p-3 rounded-full shadow-xl transition-all duration-300 hover:scale-110 hover:shadow-2xl relative z-50",children:e.jsx(Gs,{className:"w-6 h-6 text-gray-700"})}),fe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40 bg-transparent",onClick:$=>{$.stopPropagation(),qe(!1)}}),e.jsxs("div",{className:"absolute top-full right-0 mt-2 w-56 bg-gray-800 rounded-lg shadow-2xl z-50 overflow-hidden",onClick:$=>$.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{Fe(d),qe(!1)},disabled:J[d]||(((Zt=Se[d])==null?void 0:Zt.length)||0)>=7,className:"w-full flex items-center gap-3 px-4 py-3 text-white hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-gray-800",children:[e.jsx(Gs,{className:`w-5 h-5 ${J[d]?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-medium",children:(((ns=Se[d])==null?void 0:ns.length)||0)>=7?"Max variants reached":"Retry"})]}),e.jsxs("label",{className:`w-full flex items-center gap-3 px-4 py-3 text-white hover:bg-gray-700 transition-colors ${(((X=Se[d])==null?void 0:X.length)||0)>=7||J[d]?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:[e.jsx(Di,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm font-medium",children:"New Photo"}),e.jsx("input",{type:"file",accept:"image/jpeg,image/jpg,image/png,image/heic,image/heif",className:"hidden",disabled:J[d]||(((te=Se[d])==null?void 0:te.length)||0)>=7,onChange:$=>{var ee;const be=(ee=$.target.files)==null?void 0:ee[0];be&&(Pe(d,be),qe(!1),$.target.value="")}})]})]})]})]})})]}):e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-primary-100 via-secondary-50 to-primary-50 rounded-lg shadow-lg",children:[e.jsx(Ue,{className:"w-12 h-12 animate-spin text-primary-600 mb-4"}),e.jsx("p",{className:"text-primary-700 font-medium",children:"Loading sticker..."})]})}),e.jsx("div",{className:"mt-6 text-center",children:m?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-gray-600 mb-4",children:me?"All stickers generated! Click below to send for printing.":"Please wait while we generate all your stickers..."}),me&&e.jsx("div",{className:"flex gap-4 justify-center",children:e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:()=>!he()&&y(!0),disabled:S||he(),className:`px-8 py-4 bg-gradient-to-r from-green-600 to-emerald-600 text-white text-base font-semibold rounded-xl transition-all duration-300 shadow-lg flex items-center justify-center gap-2 ${S||he()?"opacity-50 cursor-not-allowed":"hover:from-green-700 hover:to-emerald-700 transform hover:scale-105"}`,children:[S&&!I&&e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),S&&!I?"Sending...":"Send for Printing"]}),he()&&e.jsxs("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-4 py-3 bg-gray-900 text-white text-sm rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50 shadow-xl",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold mb-1",children:"Your request is already being processed"}),e.jsx("div",{className:"text-xs text-gray-300",children:"Please check your email"})]}),e.jsx("div",{className:"absolute top-full left-1/2 -translate-x-1/2 -mt-1",children:e.jsx("div",{className:"border-8 border-transparent border-t-gray-900"})})]})]})})]}):e.jsx("button",{onClick:Mt,className:"px-8 py-4 bg-gradient-to-r from-primary-600 to-secondary-600 text-white font-semibold rounded-xl hover:from-primary-700 hover:to-secondary-700 transition-all duration-300 transform hover:scale-105 shadow-lg",children:"Place Order"})})]})]})})]})}),b&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black bg-opacity-50 backdrop-blur-sm",onClick:()=>{S&&E(!1),y(!1)}}),e.jsx("div",{className:"relative bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 p-8 z-10",children:S?e.jsxs("div",{className:"text-center space-y-6",children:[e.jsx("div",{className:"mx-auto w-20 h-20 bg-gradient-to-r from-green-100 to-emerald-100 rounded-full flex items-center justify-center",children:e.jsx(Ue,{className:"w-10 h-10 text-green-600 animate-spin"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-2xl font-bold text-gray-900",children:"Processing Your Request"}),e.jsx("p",{className:"text-gray-600 text-base leading-relaxed",children:"Your send for printing request is being processed, please wait for a moment! You will receive an email shortly with all the details."})]})]}):e.jsxs("div",{className:"text-center space-y-6",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-gradient-to-r from-green-100 to-emerald-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{className:"w-8 h-8 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"Ready to Send for Printing?"}),e.jsx("p",{className:"text-gray-600 text-base leading-relaxed",children:"Your stickers are ready! Once you send for printing, we'll start preparing your order."})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("button",{onClick:Be,className:"w-full px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white font-semibold rounded-xl hover:from-green-700 hover:to-emerald-700 transition-all duration-300 transform hover:scale-105 shadow-lg",children:"I am good, send for print"}),e.jsx("button",{onClick:()=>y(!1),className:"w-full px-6 py-3 bg-gray-100 text-gray-700 font-semibold rounded-xl hover:bg-gray-200 transition-all duration-300",children:"Cancel and Go Back"})]})]})})]})]})},Gj=()=>{const r=Jt(),t=_t(),{region:s,config:a,buildLink:n}=ht(),i=r.state,[o,l]=p.useState({firstName:"",lastName:"",email:(i==null?void 0:i.email)||"",phone:"",phoneCountryCode:s==="SG"?"+65":s==="US"?"+1":"+91",address:"",city:s==="SG"?"Singapore":"",state:"",pincode:"",country:a.country,unitNumber:"",blockNumber:"",streetName:"",buildingName:""}),{isLoading:c,error:u,addressData:d,isAutoFilled:h,lookupAddress:m,clearError:g,clearAutoFill:f}=Om();p.useEffect(()=>{s==="SG"&&d&&l(ke=>({...ke,blockNumber:d.blockNumber,streetName:d.streetName,buildingName:d.buildingName}))},[d,s]);const[v,x]=p.useState({}),[j,b]=p.useState(!1),[y,S]=p.useState(!1),[T,I]=p.useState(""),[E,O]=p.useState(null),[V,J]=p.useState(""),[U,Ge]=p.useState(!1),Te=ke=>{if(!ke)return null;const Ce=ke.match(/TB(\d+)OFF/);return Ce?parseInt(Ce[1],10):null};p.useEffect(()=>{l(ke=>({...ke,country:a.country}))},[a.country]),p.useEffect(()=>{(()=>{if(document.getElementById("razorpay-checkout-js"))return;const Ce=document.createElement("script");Ce.id="razorpay-checkout-js",Ce.src="https://checkout.razorpay.com/v1/checkout.js",Ce.async=!0,document.head.appendChild(Ce)})()},[]);const Me=Zn(s),_e=Me.price,Se=Me.shipping,ue=_e+Se,re=E?ue-E.discountAmount:ue,Ne=async()=>{if(!T.trim()){J("Please enter a coupon code");return}const ke=(i==null?void 0:i.sessionId)||localStorage.getItem("session_id");if(!ke){J("Session not found");return}Ge(!0),J("");try{const Ce=E?_e+Se+E.discountAmount:_e+Se,B=o.email||localStorage.getItem("user_email")||"",Ye=await(await fetch(yt("/api/apply_coupon"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({coupon_code:T.trim(),session_id:ke,total_price:Ce,user_email:B})})).json();if(Ye.valid){O({code:T.trim(),discountAmount:Ye.discount_amount});const Y=document.createElement("div");Y.className="fixed top-4 right-4 bg-green-600 text-white px-6 py-4 rounded-lg shadow-xl z-50";const ie=Te(T.trim());Y.textContent=ie?`🎉 ${ie}% discount applied!`:"🎉 Discount applied!",document.body.appendChild(Y),setTimeout(()=>Y.remove(),3e3)}else J(Ye.error||"Invalid or expired coupon code")}catch(Ce){console.error("Error applying coupon:",Ce),J("Failed to apply coupon. Please try again.")}finally{Ge(!1)}},fe=()=>{O(null),I(""),J("")},qe=()=>{const ke=o.phone.replace(/\D/g,""),Ce=a.phoneValidation.test(ke),B=o.firstName.trim()&&o.lastName.trim()&&o.email.trim()&&/\S+@\S+\.\S+/.test(o.email)&&o.phone.trim()&&Ce&&o.pincode.trim();return s==="SG"?B&&o.streetName.trim()&&o.unitNumber.trim():s==="IN"||s==="US"?B&&o.address.trim()&&o.city.trim()&&o.state.trim():B&&o.address.trim()},pe=ke=>{const{name:Ce,value:B}=ke.target;let st=B;if((Ce==="firstName"||Ce==="lastName")&&(st=B.replace(/[^a-zA-Z\s]/g,"")),Ce==="phone"){const Ye=s==="SG"?8:10;st=B.replace(/\D/g,"").slice(0,Ye)}Ce==="pincode"&&(st=B.replace(/\D/g,"").slice(0,6),s==="SG"&&m(st)),s==="SG"&&(Ce==="blockNumber"||Ce==="streetName"||Ce==="buildingName")&&f(),l(Ye=>({...Ye,[Ce]:st})),v[Ce]&&x(Ye=>({...Ye,[Ce]:""})),Ce==="pincode"&&s==="SG"&&g()},Xe=()=>{t(n(`/stickers/${i==null?void 0:i.gender}/preview`),{state:i})},ft=async()=>{if(!qe()){alert("Please fill in all required delivery information before proceeding to payment.");return}b(!0);try{let ke=(i==null?void 0:i.sessionId)||localStorage.getItem("session_id");(!ke||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(ke))&&(ke=crypto.randomUUID(),localStorage.setItem("session_id",ke));const{data:B,error:st}=await de.functions.invoke("create-razorpay-order",{body:{selectedBook:{title:`${(i==null?void 0:i.gender)==="girls"?"Girl's":"Boy's"} Sticker Pack`,backendName:`stickers_${i==null?void 0:i.gender}`},childData:{name:"",age:(i==null?void 0:i.childAge)||"3",language:"English"},childImage:(i==null?void 0:i.faceImageUrl)||"",sessionId:ke,deliveryInfo:{firstName:o.firstName,lastName:o.lastName,email:o.email,phone:o.phone,address:s==="SG"?[o.unitNumber,o.blockNumber,o.streetName,o.buildingName].filter(Boolean).join(", "):o.address,city:s==="SG"?"Singapore":o.city,state:s==="SG"?"":o.state,pincode:o.pincode,country:o.country},totalAmount:re,shippingCost:Se,bookCost:_e,currency:a.currency,couponCode:(E==null?void 0:E.code)||null,discountAmount:(E==null?void 0:E.discountAmount)||0,originalAmount:E?ue:null,coverType:"stickers",bookSize:"Sticker Sheets"}});if(st)throw console.error("Error from create-razorpay-order function:",st),new Error("Failed to initiate payment");if(!(B!=null&&B.razorpayOrderId)||!(B!=null&&B.razorpayKeyId))throw new Error("Invalid response from server");if(!window.Razorpay)throw new Error("Razorpay SDK not loaded");const Ye=(i==null?void 0:i.gender)==="girls"?"Girl's Sticker Pack":"Boy's Sticker Pack",Y={key:B.razorpayKeyId,amount:B.amount,currency:B.currency,name:"TalesBerry",description:Ye,order_id:B.razorpayOrderId,prefill:{name:`${o.firstName} ${o.lastName}`,email:o.email,contact:o.phone},theme:{color:"#8B5CF6"},handler:async function(He){console.log("[StickerDeliveryPage] Payment successful:",He),S(!0);try{const{error:Qe}=await de.functions.invoke("verify-razorpay-payment",{body:{razorpay_order_id:He.razorpay_order_id,razorpay_payment_id:He.razorpay_payment_id,razorpay_signature:He.razorpay_signature,dbOrderId:B.dbOrderId}});if(Qe)throw console.error("[StickerDeliveryPage] Payment verification failed:",Qe),new Error("Payment verification failed");console.log("[StickerDeliveryPage] Payment verified successfully");try{await de.functions.invoke("create-user-account-from-order",{body:{orderId:Number(B.dbOrderId)}}),console.log("[StickerDeliveryPage] User account created/updated")}catch(gt){console.warn("[StickerDeliveryPage] create-user-account warning:",gt)}try{await de.from("orders").update({payment_status:"completed",updated_at:new Date().toISOString()}).eq("order_id",Number(B.dbOrderId)),console.log("[StickerDeliveryPage] Order status updated to completed")}catch(gt){console.warn("[StickerDeliveryPage] Order update warning:",gt)}try{console.log("[StickerDeliveryPage] Triggering full generation for session:",ke),fetch(yt("/api/preview/generate-full"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:ke,regenerate:!1})})}catch(gt){console.warn("[StickerDeliveryPage] Generation trigger failed (non-blocking):",gt)}const lt=(i==null?void 0:i.gender)||"boys";t(n(`/stickers/${lt}/preview`)+`?sessionId=${ke}&payment_success=true`)}catch(Qe){console.error("[StickerDeliveryPage] Payment verification error:",Qe),t(n("/payment-failure"),{state:{orderId:B.dbOrderId}})}},modal:{ondismiss:function(){b(!1)}}};new window.Razorpay(Y).open(),b(!1)}catch(ke){console.error("Order creation error:",ke),alert("Failed to create order. Please try again."),b(!1)}};if(y)return e.jsx("div",{className:"fixed inset-0 bg-white z-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ue,{className:"w-16 h-16 text-purple-600 animate-spin mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-2",children:"Payment Successful!"}),e.jsx("p",{className:"text-gray-600",children:"Preparing your sticker order..."})]})});if(!i)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-4",children:"No Order Found"}),e.jsx("button",{onClick:()=>t(n("/stickers")),className:"px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors",children:"Browse Stickers"})]})});const Ze=i.gender==="girls"?"Girl's Sticker Pack":"Boy's Sticker Pack";return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(Yt,{}),e.jsxs("a",{href:"https://wa.me/918951920012?text=Hi%20TalesBerry%2C%20I%20need%20help%20with%20my%20sticker%20order%20checkout!",target:"_blank",rel:"noopener noreferrer","aria-label":"24x7 WhatsApp Support",className:`fixed bottom-4 right-4 z-50 inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#20BA5A] text-white
          px-4 py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 font-semibold transform hover:scale-105`,children:[e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"})}),e.jsx("span",{className:"whitespace-nowrap",children:"Need Help?"})]}),e.jsx("div",{className:"bg-white border-b",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-2 pb-0 md:py-6",children:[e.jsx("div",{className:"flex items-center justify-between mb-4 md:mb-4",children:e.jsxs("button",{onClick:Xe,className:"flex items-center text-gray-600 hover:text-gray-800 transition-colors",children:[e.jsx(Ut,{className:"w-5 h-5 mr-1"}),"Back to Preview"]})}),e.jsx("div",{className:"hidden md:flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center space-x-8",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Select Product"})]}),e.jsx("div",{className:"w-16 h-1 bg-purple-600 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Personalize"})]}),e.jsx("div",{className:"w-16 h-1 bg-purple-600 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"✓"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-gray-600",children:"Preview"})]}),e.jsx("div",{className:"w-16 h-1 bg-purple-600 rounded-full"}),e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:"w-8 h-8 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:"4"}),e.jsx("span",{className:"ml-2 text-sm font-medium text-purple-600",children:"Checkout"})]})]})})]})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-4 pb-8 lg:py-8",children:[e.jsxs("div",{className:"flex flex-col lg:grid lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"order-0 lg:hidden",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-900 mb-3 px-1",children:s==="SG"?"Loved by families across Singapore and around the world":"Customer Love 💖"}),s==="SG"?e.jsx(_l,{}):e.jsx(kl,{})]}),e.jsx("div",{className:"order-1 lg:order-none lg:col-span-1 lg:col-start-3 lg:row-start-1",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-3 lg:p-6 lg:sticky lg:top-8",children:[e.jsx("h2",{className:"text-lg lg:text-xl font-semibold text-gray-900 mb-3 lg:mb-6",children:"Order Summary"}),e.jsxs("div",{className:"space-y-2 lg:space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-start gap-3 pb-2 lg:pb-4 border-b",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 leading-tight mt-1",children:Ze}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"2 Sheets • 20 Stickers"})]}),e.jsx("div",{className:"text-right shrink-0",children:e.jsx("div",{className:"text-sm text-gray-900",children:Gt(s,_e)})})]}),e.jsx("div",{className:"space-y-1 py-2 lg:space-y-2 lg:py-4",children:e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Shipping"}),e.jsx("span",{className:"text-gray-900",children:Gt(s,Se)})]})}),E?e.jsx("div",{className:"border-t pt-2 lg:pt-3",children:e.jsxs("div",{className:"flex justify-between items-center bg-green-50 border border-green-200 rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-green-900",children:E.code}),e.jsx("div",{className:"text-xs text-green-700",children:Te(E.code)?`${Te(E.code)}% discount applied`:"Discount applied"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-900",children:["-",Gt(s,E.discountAmount)]}),e.jsx("button",{onClick:fe,className:"text-red-600 hover:text-red-700 text-xs underline",children:"Remove"})]})]})}):e.jsxs("div",{className:"border-t pt-2 lg:pt-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:T,onChange:ke=>I(ke.target.value.toUpperCase()),placeholder:"Discount code",className:"flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"}),e.jsx("button",{onClick:Ne,disabled:U,className:"px-4 py-2 bg-purple-600 text-white rounded-lg text-sm font-medium hover:bg-purple-700 disabled:opacity-50",children:U?"Applying...":"Apply"})]}),V&&e.jsx("p",{className:"text-red-500 text-xs mt-1",children:V})]}),e.jsx("div",{className:"border-t pt-2 lg:pt-3",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-base lg:text-lg font-bold text-gray-900",children:"Total"}),e.jsxs("div",{className:"text-right",children:[E&&e.jsx("div",{className:"text-sm text-gray-500 line-through",children:Gt(s,ue)}),e.jsx("span",{className:"text-lg lg:text-2xl font-bold text-purple-600",children:Gt(s,re)})]})]})}),e.jsx("div",{className:"hidden lg:block pt-4",children:e.jsx("button",{onClick:ft,disabled:!qe()||j,className:`w-full py-4 rounded-xl font-bold text-lg transition-all duration-300 ${qe()&&!j?"bg-gradient-to-r from-purple-600 to-pink-600 text-white hover:from-purple-700 hover:to-pink-700 shadow-lg hover:shadow-xl":"bg-gray-300 text-gray-500 cursor-not-allowed"}`,children:j?e.jsxs("span",{className:"flex items-center justify-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),"Processing..."]}):"Pay Now"})})]})]})}),e.jsx("div",{className:"order-2 lg:order-none lg:col-span-2 lg:col-start-1 lg:row-start-1",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-4 lg:p-8",children:[e.jsxs("h2",{className:"text-lg lg:text-xl font-semibold text-gray-900 mb-4 lg:mb-6 flex items-center gap-2",children:[e.jsx(ya,{className:"w-5 h-5 text-purple-600"}),"Delivery Information"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 lg:gap-6",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(Gi,{className:"w-4 h-4 inline mr-1"}),"First Name *"]}),e.jsx("input",{type:"text",name:"firstName",value:o.firstName,onChange:pe,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"Enter first name"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(Gi,{className:"w-4 h-4 inline mr-1"}),"Last Name *"]}),e.jsx("input",{type:"text",name:"lastName",value:o.lastName,onChange:pe,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"Enter last name"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(Ma,{className:"w-4 h-4 inline mr-1"}),"Email *"]}),e.jsx("input",{type:"email",name:"email",value:o.email,onChange:pe,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"Enter email"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(On,{className:"w-4 h-4 inline mr-1"}),"Phone *"]}),e.jsx("input",{type:"tel",name:"phone",value:o.phone,onChange:pe,maxLength:s==="SG"?8:10,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:s==="SG"?"8 digit number":"10 digit number"})]}),s==="SG"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(xa,{className:"w-4 h-4 inline mr-1"}),"Postal Code *"]}),e.jsxs("div",{className:"relative max-w-xs",children:[e.jsx("input",{type:"text",name:"pincode",value:o.pincode,onChange:pe,maxLength:6,className:`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent pr-10 ${u?"border-red-300":h?"border-green-300 bg-green-50":"border-gray-300"}`,placeholder:"Enter 6-digit postal code"}),c&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsx(Ue,{className:"w-4 h-4 animate-spin text-gray-400"})}),h&&!c&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsx(Sa,{className:"w-4 h-4 text-green-500"})})]}),u&&e.jsx("p",{className:"text-amber-600 text-xs mt-1",children:u}),h&&e.jsx("p",{className:"text-green-600 text-xs mt-1",children:"Address found and auto-filled"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Block Number"}),e.jsx("input",{type:"text",name:"blockNumber",value:o.blockNumber,onChange:pe,className:`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent ${h&&o.blockNumber?"bg-green-50 border-green-200":"border-gray-300"}`,placeholder:"Block no."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Street Name *"}),e.jsx("input",{type:"text",name:"streetName",value:o.streetName,onChange:pe,className:`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent ${h&&o.streetName?"bg-green-50 border-green-200":"border-gray-300"}`,placeholder:"Street name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Building Name"}),e.jsx("input",{type:"text",name:"buildingName",value:o.buildingName,onChange:pe,className:`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent ${h&&o.buildingName?"bg-green-50 border-green-200":"border-gray-300"}`,placeholder:"Building name (optional)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Unit Number *"}),e.jsx("input",{type:"text",name:"unitNumber",value:o.unitNumber,onChange:pe,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"e.g. #12-34"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"City"}),e.jsx("input",{type:"text",value:"Singapore",disabled:!0,className:"w-full px-4 py-3 border border-gray-200 rounded-lg bg-gray-100 cursor-not-allowed text-gray-600"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Country"}),e.jsx("input",{type:"text",value:"Singapore",disabled:!0,className:"w-full px-4 py-3 border border-gray-200 rounded-lg bg-gray-100 cursor-not-allowed text-gray-600"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(xa,{className:"w-4 h-4 inline mr-1"}),"Address *"]}),e.jsx("textarea",{name:"address",value:o.address,onChange:pe,rows:2,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"Enter full address"})]}),s==="IN"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"City *"}),e.jsx("input",{type:"text",name:"city",value:o.city,onChange:pe,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"Enter city"})]}),s==="IN"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"State *"}),e.jsx("input",{type:"text",name:"state",value:o.state,onChange:pe,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"Enter state"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"PIN Code *"}),e.jsx("input",{type:"text",name:"pincode",value:o.pincode,onChange:pe,maxLength:6,className:"w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"6 digit PIN code"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Country"}),e.jsx("input",{type:"text",name:"country",value:o.country,readOnly:!0,className:"w-full px-4 py-3 border border-gray-200 rounded-lg bg-gray-50 text-gray-600"})]})]})]})]})})]}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-white border-t p-4 lg:hidden z-40",children:e.jsx("button",{onClick:ft,disabled:!qe()||j,className:`w-full py-4 rounded-xl font-bold text-lg transition-all duration-300 ${qe()&&!j?"bg-gradient-to-r from-purple-600 to-pink-600 text-white shadow-lg":"bg-gray-300 text-gray-500 cursor-not-allowed"}`,children:j?e.jsxs("span",{className:"flex items-center justify-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 animate-spin"}),"Processing..."]}):`Pay ${Gt(s,re)}`})})]})]})},Uj={enter:r=>({rotateY:r>0?90:-90,opacity:0,scale:.95,transformOrigin:r>0?"left center":"right center"}),center:{rotateY:0,opacity:1,scale:1,transformOrigin:"center center"},exit:r=>({rotateY:r>0?-90:90,opacity:0,scale:.95,transformOrigin:r>0?"left center":"right center"})},Vj={type:"tween",duration:.45,ease:[.25,.46,.45,.94]},zj=()=>{const[r,t]=p.useState(!1);return p.useEffect(()=>{const s=()=>t(window.innerWidth<768);return s(),window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[]),r},Wj=()=>{const[r,t]=p.useState(!1);return p.useEffect(()=>{const s=()=>t(window.innerWidth>window.innerHeight);return s(),window.addEventListener("resize",s),window.addEventListener("orientationchange",s),()=>{window.removeEventListener("resize",s),window.removeEventListener("orientationchange",s)}},[]),r},Ti=({page:r,childName:t,compact:s})=>r.type==="image"?e.jsx("div",{className:"absolute inset-0 bg-gray-100",children:r.content?e.jsx("img",{src:r.content,alt:`Chapter ${r.chapter} illustration`,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-400 text-sm",children:"Illustration unavailable"})}):e.jsx("div",{className:`absolute inset-0 overflow-y-auto ${s?"p-3 sm:p-4":"p-8 sm:p-12"}`,children:e.jsxs("div",{className:"max-w-xl mx-auto",children:[e.jsxs("span",{className:`text-purple-600 font-medium mb-2 block ${s?"text-xs":"text-sm mb-4"}`,children:["Chapter ",r.chapter]}),e.jsx("div",{className:`prose font-serif text-gray-700 leading-relaxed ${s?"prose-sm":"prose-lg"}`,style:{fontFamily:"'Quicksand', 'Comic Neue', sans-serif"},children:r.content.split(`

`).map((a,n)=>e.jsx("p",{className:s?"mb-2 text-sm":"mb-4 text-lg sm:text-xl",children:a.replace(/\{childName\}/g,t)},n))})]})}),Kd=()=>e.jsxs("div",{className:"absolute bottom-0 right-0 pointer-events-none",style:{width:50,height:50},children:[e.jsx("div",{style:{position:"absolute",bottom:0,right:0,width:0,height:0,borderStyle:"solid",borderWidth:"0 0 50px 50px",borderColor:"transparent transparent #e8e4df transparent",borderRadius:"0 0 12px 0"}}),e.jsx("div",{style:{position:"absolute",bottom:0,right:0,width:0,height:0,borderStyle:"solid",borderWidth:"0 0 45px 45px",borderColor:"transparent transparent #f5f3f0 transparent",filter:"drop-shadow(-2px -2px 3px rgba(0,0,0,0.12))",borderRadius:"0 0 12px 0"}}),e.jsx("div",{style:{position:"absolute",bottom:0,right:0,width:34,height:34,background:"linear-gradient(315deg, rgba(255,255,255,0.9) 0%, rgba(220,215,210,0.4) 100%)",clipPath:"polygon(100% 0%, 100% 100%, 0% 100%)",borderRadius:"0 0 12px 0"}})]}),Wa=({isOpen:r,onClose:t,storyTitle:s,pages:a,childName:n,storyId:i,maxPages:o,onLoginRequired:l,progress:c,status:u})=>{const[d,h]=p.useState(0),[m,g]=p.useState(0),[f,v]=p.useState(!1),[x,j]=p.useState(!1),b=p.useRef(null),y=p.useRef(null),S=zj(),T=Wj(),I=S?2:1,E=Math.ceil(a.length/I),O=o!==void 0&&o>0;p.useEffect(()=>{if(r&&S&&!T){j(!0);const Ne=setTimeout(()=>j(!1),3e3);return()=>clearTimeout(Ne)}},[r,S,T]);const V=p.useCallback(()=>{const Ne=d+1,fe=Ne*I;if(O&&fe>=o){l==null||l();return}Ne<E&&(g(1),h(Ne))},[d,I,E,O,o,l]),J=p.useCallback(()=>{d>0&&(g(-1),h(d-1))},[d]),U=Ne=>{Ne.key==="ArrowRight"&&V(),Ne.key==="ArrowLeft"&&J(),Ne.key==="Escape"&&t()},Ge=Ne=>{b.current=Ne.touches[0].clientX,y.current=Ne.touches[0].clientY},Te=Ne=>{if(b.current===null||y.current===null)return;const fe=Ne.changedTouches[0].clientX-b.current,qe=Ne.changedTouches[0].clientY-y.current;b.current=null,y.current=null,Math.abs(fe)>50&&Math.abs(fe)>Math.abs(qe)*1.5&&(fe<0?V():J())},Me=async()=>{if(!i)return;const Ne=`${window.location.origin}/story/${i}`,fe={title:s,text:`Check out "${s}" — a personalized story created on TalesBerry! 📖✨`,url:Ne};try{navigator.share?await navigator.share(fe):(await navigator.clipboard.writeText(`${fe.text}
${Ne}`),v(!0),setTimeout(()=>v(!1),2500))}catch{console.log("Share cancelled")}},_e=d*I,Se=a.slice(_e,_e+I),ue=d===E-1,re=_e+1;return e.jsx(ks,{children:r&&e.jsxs(Ie.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 bg-gradient-to-br from-amber-50 to-orange-50",onKeyDown:U,tabIndex:0,style:{perspective:1200},children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 z-10 px-3 py-2 sm:px-4 sm:py-3 bg-white/80 backdrop-blur-sm border-b border-amber-200",children:e.jsxs("div",{className:"max-w-5xl mx-auto flex items-center justify-between",children:[e.jsxs("button",{onClick:t,className:"flex items-center gap-1.5 text-gray-600 hover:text-gray-800 transition-colors",children:[e.jsx(fu,{className:"w-4 h-4 sm:w-5 sm:h-5"}),e.jsx("span",{className:"hidden sm:inline text-sm",children:"Back"})]}),e.jsx("h1",{className:"text-sm sm:text-lg font-serif font-semibold text-gray-800 truncate max-w-[120px] sm:max-w-none",children:s}),e.jsxs("div",{className:"flex items-center gap-2",children:[u&&u!=="completed"&&c!==void 0&&c<100&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-yellow-100 text-yellow-800 rounded-full text-xs font-medium animate-pulse",children:[e.jsx("div",{className:"w-2 h-2 bg-yellow-500 rounded-full"}),c,"%"]}),i&&e.jsxs("button",{onClick:Me,className:"flex items-center gap-1 px-2 py-1 sm:px-3 sm:py-1.5 bg-purple-100 text-purple-700 rounded-full text-xs sm:text-sm font-medium hover:bg-purple-200 transition-colors",children:[e.jsx(gn,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Share"})]}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-500",children:[re,"–",Math.min(_e+I,a.length)," / ",a.length]})]})]})}),e.jsx(ks,{children:x&&S&&!T&&e.jsxs(Ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},className:"absolute top-14 left-1/2 -translate-x-1/2 z-20 bg-gray-800 text-white px-4 py-2 rounded-lg shadow-lg text-xs font-medium flex items-center gap-2",children:[e.jsx(Wp,{className:"w-4 h-4"}),"Rotate for best reading experience"]})}),e.jsx(ks,{children:f&&e.jsx(Ie.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"absolute top-14 left-1/2 -translate-x-1/2 z-20 bg-green-600 text-white px-4 py-2 rounded-lg shadow-lg text-sm font-medium",children:"Link copied! 📋"})}),e.jsx("div",{className:"absolute top-12 bottom-14 left-2 right-2 sm:top-16 sm:bottom-20 sm:left-4 sm:right-4 flex items-center justify-center",onTouchStart:Ge,onTouchEnd:Te,style:{perspective:1200},children:e.jsx("div",{className:`relative ${S?"w-full":"max-w-3xl w-full mx-auto"}`,style:S?{width:"100%",paddingBottom:"50%"}:{maxHeight:"80vh",height:"100%"},children:e.jsx(ks,{mode:"wait",custom:m,children:e.jsxs(Ie.div,{custom:m,variants:Uj,initial:"enter",animate:"center",exit:"exit",transition:Vj,className:"bg-white rounded-xl sm:rounded-2xl shadow-2xl",style:{transformStyle:"preserve-3d",position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},children:[S&&Se.length===2?e.jsxs("div",{className:"absolute inset-0 flex",children:[e.jsxs("div",{className:"w-1/2 h-full border-r border-gray-200 relative overflow-hidden",children:[e.jsx(Ti,{page:Se[0],childName:n,compact:!0}),e.jsx("div",{className:"absolute bottom-1.5 left-2 text-[10px] text-gray-400 z-10",children:_e+1})]}),e.jsxs("div",{className:"w-1/2 h-full relative overflow-hidden",children:[e.jsx(Ti,{page:Se[1],childName:n,compact:!0}),e.jsx("div",{className:"absolute bottom-1.5 right-2 text-[10px] text-gray-400 z-10",children:_e+2}),!ue&&e.jsx(Kd,{})]})]}):e.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-xl sm:rounded-2xl",children:[e.jsx(Ti,{page:Se[0],childName:n}),!ue&&e.jsx(Kd,{}),e.jsx("div",{className:"absolute bottom-3 right-4 text-xs text-gray-400 font-medium",children:_e+1})]}),S&&Se.length===2&&e.jsx("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 h-full w-[3px] pointer-events-none z-10",style:{background:"linear-gradient(to right, rgba(0,0,0,0.08), rgba(0,0,0,0.02), rgba(0,0,0,0.08))"}})]},d)})})}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 px-3 py-2 sm:px-4 sm:py-4 bg-white/80 backdrop-blur-sm border-t border-amber-200",children:e.jsxs("div",{className:"max-w-5xl mx-auto flex items-center justify-between",children:[e.jsxs("button",{onClick:J,disabled:d===0,className:`flex items-center gap-1 px-3 py-1.5 rounded-xl transition-colors text-sm ${d===0?"text-gray-300 cursor-not-allowed":"text-gray-700 hover:bg-amber-100"}`,children:[e.jsx(Ut,{className:"w-4 h-4 sm:w-5 sm:h-5"}),e.jsx("span",{className:"hidden sm:inline",children:"Previous"})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto max-w-[180px] sm:max-w-none",children:Array.from({length:E}).map((Ne,fe)=>{const qe=fe*I,pe=O&&qe>=o;return e.jsx("button",{onClick:()=>{if(pe){l==null||l();return}g(fe>d?1:-1),h(fe)},className:`w-2 h-2 rounded-full transition-colors flex-shrink-0 ${fe===d?"bg-purple-600":pe?"bg-gray-200":"bg-gray-300 hover:bg-gray-400"}`},fe)})}),e.jsxs("button",{onClick:V,disabled:ue,className:`flex items-center gap-1 px-3 py-1.5 rounded-xl transition-colors text-sm ${ue?"text-gray-300 cursor-not-allowed":"text-gray-700 hover:bg-amber-100"}`,children:[e.jsx("span",{className:"hidden sm:inline",children:"Next"}),e.jsx(gs,{className:"w-4 h-4 sm:w-5 sm:h-5"})]})]})}),e.jsx("button",{onClick:t,className:"absolute top-12 right-2 sm:top-20 sm:right-4 p-1.5 sm:p-2 bg-white/80 backdrop-blur-sm rounded-full shadow-md hover:bg-white transition-colors z-10",children:e.jsx(Cs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-600"})})]})})},Sl=({src:r,title:t,alt:s,className:a=""})=>e.jsxs("div",{className:`relative w-full h-full ${a}`,children:[e.jsx("img",{src:r,alt:s||t,className:"w-full h-full object-cover"}),e.jsx("img",{src:"/talesberry-cover-logo.png",alt:"TalesBerry",className:"absolute bottom-2 right-3 sm:bottom-3 sm:right-4 w-6 h-6 sm:w-8 sm:h-8 object-contain opacity-80 z-10"})]}),qj=r=>{try{const t=JSON.parse(localStorage.getItem("talesberry_my_story_ids")||"[]");t.includes(r)||(t.unshift(r),localStorage.setItem("talesberry_my_story_ids",JSON.stringify(t)))}catch{localStorage.setItem("talesberry_my_story_ids",JSON.stringify([r]))}},Hj=({onPublishChange:r})=>{const[t,s]=p.useState([]),[a,n]=p.useState(!0),[i,o]=p.useState(null),[l,c]=p.useState(new Set),u=i&&t.find(y=>y.id===i)||null,{user:d}=Qs();p.useEffect(()=>{d?m().then(()=>g()):n(!1)},[d]);const h=jt.useRef(new Set);p.useEffect(()=>{if(!t.some(T=>T.status!=="completed"&&T.status!=="error"&&T.pages.length>0)||!d)return;const S=setInterval(async()=>{var T;await g();for(const I of t){const E=(T=I.status)==null?void 0:T.match(/^batch_(\d+)_complete$/);if(E){const V=parseInt(E[1])+1,J=`${I.id}_batch_${V}`;!h.current.has(J)&&V<=4&&(h.current.add(J),de.functions.invoke("generate-story-flow",{body:{storyId:I.id,batch:V}}).catch(U=>console.error(`Batch ${V} invoke failed for ${I.id}:`,U)))}}},5e3);return()=>clearInterval(S)},[t,d]);const m=async()=>{if(d)try{const y=JSON.parse(localStorage.getItem("talesberry_my_story_ids")||"[]");if(y.length===0)return;await de.rpc("claim_stories_for_user",{p_user_id:d.id,p_story_ids:y})}catch(y){console.error("Failed to claim orphaned stories:",y)}},g=async()=>{if(d)try{const{data:y,error:S}=await de.from("custom_stories").select("id, story_title, child_name, status, progress, pages, created_at, is_published").eq("user_id",d.id).order("created_at",{ascending:!1});!S&&y&&s(y.map(T=>({...T,pages:Array.isArray(T.pages)?T.pages:[]})))}catch(y){console.error("Failed to fetch stories:",y)}finally{n(!1)}},f=async(y,S)=>{if(S.stopPropagation(),!confirm("Are you sure you want to delete this story? This cannot be undone."))return;const{error:T}=await de.from("custom_stories").delete().eq("id",y);T||s(I=>I.filter(E=>E.id!==y))},v=async(y,S)=>{if(S.stopPropagation(),!d)return;const T=!y.is_published,{error:I}=await de.rpc("toggle_story_publish",{p_story_id:y.id,p_user_id:d.id,p_published:T});I||(s(E=>E.map(O=>O.id===y.id?{...O,is_published:T}:O)),r==null||r())},x=y=>y.status==="completed"&&y.pages.some(S=>S.type==="image"&&(!S.content||S.content.trim()==="")),j=async(y,S)=>{S.stopPropagation(),c(T=>new Set(T).add(y));try{await de.functions.invoke("generate-story-flow",{body:{storyId:y,repair:!0}}),await g()}catch(T){console.error("Repair failed:",T)}finally{c(T=>{const I=new Set(T);return I.delete(y),I})}};if(a)return e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ue,{className:"w-6 h-6 animate-spin text-purple-400"})});const b=t.filter(y=>y.pages.length>0);return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"pb-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-800 mb-6 text-center",children:"📖 My Stories"}),b.length===0?e.jsxs("div",{className:"text-center py-12 bg-white rounded-xl shadow-sm",children:[e.jsx(Ls,{className:"w-12 h-12 text-purple-300 mx-auto mb-3"}),e.jsx("p",{className:"text-gray-500",children:"You haven't created any stories yet."}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"Create your first story above!"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 gap-3 sm:gap-4",children:b.map(y=>{var E;const S=(E=y.pages.find(O=>O.type==="image"))==null?void 0:E.content,T=y.status==="completed",I=Math.floor(y.pages.filter(O=>O.type==="image").length);return e.jsxs(Ie.div,{whileHover:{scale:1.03},className:"bg-white rounded-xl shadow-md overflow-hidden hover:shadow-lg transition-shadow group relative",children:[e.jsxs("button",{onClick:()=>o(y.id),className:"w-full text-left",children:[e.jsxs("div",{className:"aspect-[4/3] bg-purple-50 relative overflow-hidden",children:[S?e.jsx(Sl,{src:S,title:y.story_title||`${y.child_name}'s Story`}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Ls,{className:"w-12 h-12 text-purple-300"})}),!T&&e.jsxs("div",{className:"absolute top-2 right-2 bg-yellow-400 text-yellow-900 text-xs font-medium px-2 py-0.5 rounded-full",children:[y.progress||0,"%"]}),y.is_published&&e.jsxs("div",{className:"absolute top-2 left-2 bg-green-500 text-white text-xs font-medium px-2 py-0.5 rounded-full flex items-center gap-1",children:[e.jsx(Fi,{className:"w-3 h-3"})," Published"]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"font-semibold text-gray-800 text-sm truncate",children:y.story_title||`${y.child_name}'s Story`}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[I," chapter",I!==1?"s":""," · ",y.child_name]})]})]}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity",children:[x(y)&&e.jsx("button",{onClick:O=>j(y.id,O),disabled:l.has(y.id),className:"p-1.5 rounded-full bg-orange-100 text-orange-600 hover:bg-orange-200 transition-colors",title:"Repair missing illustrations",children:e.jsx(Gs,{className:`w-4 h-4 ${l.has(y.id)?"animate-spin":""}`})}),e.jsx("button",{onClick:O=>v(y,O),className:`p-1.5 rounded-full transition-colors ${y.is_published?"bg-green-100 text-green-600 hover:bg-green-200":"bg-gray-100 text-gray-500 hover:bg-purple-100 hover:text-purple-600"}`,title:y.is_published?"Unpublish from Storyhouse":"Publish to Storyhouse",children:y.is_published?e.jsx(Fp,{className:"w-4 h-4"}):e.jsx(Fi,{className:"w-4 h-4"})}),e.jsx("button",{onClick:O=>f(y.id,O),className:"p-1.5 rounded-full bg-gray-100 text-gray-500 hover:bg-red-100 hover:text-red-600 transition-colors",title:"Delete story",children:e.jsx(Oo,{className:"w-4 h-4"})})]})]},y.id)})})]}),u&&e.jsx(Wa,{isOpen:!!u,onClose:()=>o(null),storyTitle:u.story_title||"Your Story",pages:u.pages,childName:u.child_name,storyId:u.id,progress:u.progress??void 0,status:u.status})]})};function Kj(){const[r,t]=p.useState(null),[s,a]=p.useState(!1),[n,i]=p.useState(null),o=p.useRef(null),l=p.useRef(0),c=p.useRef(new Set),{user:u}=Qs(),d=()=>`custom-story-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,h=p.useCallback(async(f,v)=>{a(!0),c.current=new Set,l.current=0,o.current=null;try{const x=d(),j=crypto.randomUUID();let b=null;if(v){const S=v.name.split(".").pop()||"jpg",T=`custom-stories/${j}/child-face.${S}`,{error:I}=await de.storage.from("user-uploads").upload(T,v,{contentType:v.type,upsert:!0});if(I)console.error("Child photo upload failed:",I);else{const{data:E}=await de.storage.from("user-uploads").createSignedUrl(T,604800);b=(E==null?void 0:E.signedUrl)||null}}const{error:y}=await de.from("custom_stories").insert({id:j,session_id:x,child_name:f.childName,child_age:f.age,child_gender:f.gender,fascinations:f.fascinations,favorite_food:f.favoriteFood,people_pets:f.peoplePets,personality:f.personality,learning_goals:f.learningGoals,language:f.language||"English",art_style:f.artStyle||"Storybook Watercolor",status:"pending",progress:0,user_id:(u==null?void 0:u.id)||null,child_face_url:b||null});if(y)throw new Error(`Failed to create story record: ${y.message}`);qj(j),t({id:j,status:"pending",currentStep:"starting",progress:0,storyTitle:null,pages:[],errorMessage:null}),de.functions.invoke("generate-story-flow",{body:{storyId:j,profile:f,batch:0,childFaceUrl:b}}).then(({error:S})=>{S&&console.error("Edge function invoke error (batch 0):",S)}).catch(S=>console.error("Edge function invoke failed:",S)),m(j)}catch(x){console.error("Story generation error:",x),t({id:"",status:"error",currentStep:"failed",progress:0,storyTitle:null,pages:[],errorMessage:x instanceof Error?x.message:"Failed to start story generation"})}finally{a(!1)}},[]),m=p.useCallback(f=>{n&&clearInterval(n);const v=setInterval(async()=>{var x;try{const{data:j,error:b}=await de.from("custom_stories").select("*").eq("id",f).single();if(b){console.error("Polling error:",b);return}if(j){let y=[];Array.isArray(j.pages)&&(y=j.pages);const S=j.updated_at;if(S===o.current){if(l.current+=1,l.current>=90){t({id:j.id,status:"error",currentStep:"failed",progress:j.progress||0,storyTitle:j.story_title,pages:y,errorMessage:"Story generation timed out. Please try again."}),clearInterval(v),i(null);return}}else l.current=0,o.current=S;const T=(x=j.status)==null?void 0:x.match(/^batch_(\d+)_complete$/);if(T){const E=parseInt(T[1])+1;!c.current.has(E)&&E<=4&&(c.current.add(E),de.functions.invoke("generate-story-flow",{body:{storyId:f,batch:E}}).catch(O=>console.error(`Batch ${E} invoke failed:`,O)))}t({id:j.id,status:j.status,currentStep:j.current_step||"processing",progress:j.progress||0,storyTitle:j.story_title,pages:y,errorMessage:j.error_message}),(j.status==="completed"||j.status==="error")&&(clearInterval(v),i(null))}}catch(j){console.error("Polling fetch error:",j)}},2e3);i(v)},[n]);p.useEffect(()=>()=>{n&&clearInterval(n)},[n]);const g=p.useCallback(()=>{n&&(clearInterval(n),i(null)),t(null),c.current=new Set,l.current=0,o.current=null},[n]);return{storyData:r,isLoading:s,startStoryGeneration:h,resetStory:g}}const Yj={narrative:{label:"Crafting your story...",icon:e.jsx(Ls,{className:"w-5 h-5"})},character_reference:{label:"Creating character design...",icon:e.jsx(Ba,{className:"w-5 h-5"})},generating_pages:{label:"Illustrating pages...",icon:e.jsx(xu,{className:"w-5 h-5"})},done:{label:"Story complete!",icon:e.jsx(Ro,{className:"w-5 h-5"})}},Jj=({isOpen:r,onClose:t,status:s,currentStep:a,progress:n,errorMessage:i,onViewStory:o,pagesReady:l=0,onPreviewPages:c})=>{const d=a.startsWith("generating_page_")?{label:`Illustrating page ${a.replace("generating_page_","")} of 10...`,icon:e.jsx(xu,{className:"w-5 h-5"})}:Yj[a]||{label:"Processing...",icon:e.jsx(Ue,{className:"w-5 h-5 animate-spin"})};return e.jsx(ks,{children:r&&e.jsx(Ie.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50",onClick:s==="completed"||s==="error"?t:void 0,children:e.jsxs(Ie.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.95,opacity:0},onClick:h=>h.stopPropagation(),className:"bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-800",children:s==="completed"?"Story Ready!":s==="error"?"Generation Failed":"Creating Your Story"}),(s==="completed"||s==="error")&&e.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600",children:e.jsx(Cs,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"px-6 py-8",children:s==="error"?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Mi,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-gray-600 mb-2",children:"Something went wrong while creating your story."}),e.jsx("p",{className:"text-sm text-gray-500 mb-6",children:i||"Please try again."}),e.jsx("button",{onClick:t,className:"w-full py-3 bg-purple-600 hover:bg-purple-700 text-white rounded-xl font-medium transition-colors",children:"Try Again"})]}):s==="completed"?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Ro,{className:"w-8 h-8 text-green-600"})}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Your personalized story is ready to read!"}),e.jsx("button",{onClick:o,className:"w-full py-3 bg-purple-600 hover:bg-purple-700 text-white rounded-xl font-medium transition-colors",children:"View Story"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex justify-center mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-24 h-24 bg-purple-100 rounded-full flex items-center justify-center",children:e.jsx(Ie.div,{animate:{rotate:360},transition:{duration:8,repeat:1/0,ease:"linear"},children:e.jsx(Ba,{className:"w-12 h-12 text-purple-600"})})}),e.jsx(Ie.div,{className:"absolute -top-2 -right-2 w-8 h-8 bg-yellow-400 rounded-full flex items-center justify-center",animate:{scale:[1,1.2,1]},transition:{duration:2,repeat:1/0},children:e.jsx("span",{className:"text-lg",children:"✨"})})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-4 text-purple-700",children:[d.icon,e.jsx("span",{className:"font-medium",children:d.label})]}),e.jsx("div",{className:"w-full bg-gray-200 rounded-full h-3 mb-2",children:e.jsx(Ie.div,{className:"bg-gradient-to-r from-purple-500 to-pink-500 h-3 rounded-full",initial:{width:0},animate:{width:`${n}%`},transition:{duration:.5}})}),e.jsxs("p",{className:"text-center text-sm text-gray-500",children:[n,"% complete"]}),l>0&&c&&e.jsxs("button",{onClick:c,className:"w-full mt-4 py-2.5 border-2 border-purple-200 text-purple-600 rounded-xl font-medium hover:bg-purple-50 transition-colors",children:["Preview ",Math.floor(l/2)," pages so far →"]}),e.jsx("p",{className:"text-center text-xs text-gray-400 mt-4",children:"This may take a few minutes. We're crafting something special!"})]})})]})})})},Fm=r=>r?`talesberry_child_profiles_${r}`:"talesberry_child_profiles",Ai=r=>{try{const t=localStorage.getItem(Fm(r));return t?JSON.parse(t):[]}catch{return[]}},Yd=(r,t)=>{localStorage.setItem(Fm(t),JSON.stringify(r))},Zj=[{emoji:"🦕",label:"Dinos"},{emoji:"🚀",label:"Space"},{emoji:"🚗",label:"Vehicles"},{emoji:"🧚",label:"Fairies"},{emoji:"🐾",label:"Animals"},{emoji:"🦸",label:"Superheroes"},{emoji:"🏰",label:"Castles"},{emoji:"🌊",label:"Ocean"}],Xj=[{emoji:"🍕",label:"Pizza"},{emoji:"🍦",label:"Ice Cream"},{emoji:"🍝",label:"Pasta"},{emoji:"🍎",label:"Fruits"}],Qj=[{emoji:"🦉",label:"Shy Observer"},{emoji:"🦋",label:"Social Butterfly"},{emoji:"🦁",label:"Brave Explorer"},{emoji:"🤡",label:"Silly Jester"}],e1=[{emoji:"❤️",label:"Kindness"},{emoji:"🤝",label:"Sharing"},{emoji:"🪥",label:"Brushing Teeth"},{emoji:"😴",label:"Sleeping on time"},{emoji:"⚔️",label:"Bravery"}],t1=[{emoji:"🇬🇧",label:"English"},{emoji:"🇮🇳",label:"Hindi"},{emoji:"🇮🇳",label:"Tamil"}],s1=[{emoji:"🎨",label:"Storybook Watercolor",desc:"Soft, warm watercolor illustrations"},{emoji:"✨",label:"Hyper Realistic",desc:"Photo-realistic detailed art"},{emoji:"🌈",label:"Cartoonish Fun",desc:"Bright, playful cartoon style"},{emoji:"🌸",label:"Soft Pastel",desc:"Gentle pastel tones and dreamy feel"},{emoji:"⚡",label:"HD Anime",desc:"High-quality anime-inspired art"},{emoji:"📖",label:"Classic Illustration",desc:"Timeless hand-drawn book art"}],r1=({isOpen:r,onClose:t,initialTheme:s})=>{var Ye;const{user:a}=Qs(),[n,i]=p.useState(()=>Ai(a==null?void 0:a.id)),[o,l]=p.useState(()=>Ai(a==null?void 0:a.id).length===0?"create":"select"),[c,u]=p.useState(0),[d,h]=p.useState({childName:"",age:5,gender:"",fascinations:[],favoriteFood:"",peoplePets:"",personality:[],learningGoals:[]}),[m,g]=p.useState({language:"English",artStyle:"Storybook Watercolor"}),[f,v]=p.useState(null),[x,j]=p.useState(null),b=p.useRef(null),{storyData:y,isLoading:S,startStoryGeneration:T,resetStory:I}=Kj(),[E,O]=p.useState(!1),[V,J]=p.useState(!1),U=5;p.useEffect(()=>{if(s&&r){const ie={"Space Explorer":["Space"],"Jungle Safari":["Animals"],"Underwater Quest":["Ocean"],"Magic Kingdom":["Fairies","Castles"]}[s];ie&&h(He=>({...He,fascinations:ie}))}},[s,r]),p.useEffect(()=>{if(r){const Y=Ai(a==null?void 0:a.id);i(Y),s?(l("create"),u(0)):(l(Y.length===0?"create":"select"),u(0))}},[r]);const Ge=Y=>{h({childName:Y.childName,age:Y.age,gender:Y.gender,fascinations:Y.fascinations,favoriteFood:Y.favoriteFood,peoplePets:Y.peoplePets,personality:Y.personality,learningGoals:Y.learningGoals}),l("create"),u(4)},Te=Y=>{const ie=n.filter(He=>He.id!==Y);Yd(ie,a==null?void 0:a.id),i(ie),ie.length===0&&(l("create"),u(0))},Me=()=>{h({childName:"",age:5,gender:"",fascinations:[],favoriteFood:"",peoplePets:"",personality:[],learningGoals:[]}),g({language:"English",artStyle:"Storybook Watercolor"}),v(null),j(null),l("create"),u(0)},_e=()=>{c<U-1&&u(c+1)},Se=()=>{c>0?u(c-1):n.length>0&&l("select")},ue=(Y,ie)=>{h(He=>{const Qe=He[Y],lt=Qe.includes(ie)?Qe.filter(gt=>gt!==ie):[...Qe,ie];return{...He,[Y]:lt}})},re=async()=>{const Y=n.findIndex(Qe=>Qe.childName.toLowerCase()===d.childName.toLowerCase()),ie={...d,id:Y>=0?n[Y].id:`profile-${Date.now()}`,createdAt:Y>=0?n[Y].createdAt:new Date().toISOString()},He=Y>=0?n.map((Qe,lt)=>lt===Y?ie:Qe):[...n,ie];Yd(He,a==null?void 0:a.id),i(He),console.log("Creating story with profile:",d,"prefs:",m,"hasPhoto:",!!f),O(!0),await T({...d,language:m.language,artStyle:m.artStyle},f||void 0)},Ne=()=>{O(!1),J(!0)},fe=()=>{J(!1),I(),u(0),l(n.length>0?"select":"create"),t()},qe=()=>{O(!1),(y==null?void 0:y.status)==="error"&&I()},pe=()=>e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[Array.from({length:U}).map((Y,ie)=>e.jsx("div",{className:`w-2 h-2 rounded-full transition-colors ${ie===c?"bg-purple-600":"bg-gray-300"}`},ie)),e.jsxs("span",{className:"text-sm text-gray-500 ml-2",children:["Step ",c+1,"/",U]})]}),Xe=()=>e.jsxs("div",{className:"px-6 py-8",children:[e.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-3xl",children:"👶"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-800 text-center mb-2",children:"Who's the story for?"}),e.jsx("p",{className:"text-gray-500 text-center mb-6",children:"Select a profile or create a new one"}),e.jsx("div",{className:"space-y-3 mb-6",children:n.map(Y=>e.jsxs("div",{className:"flex items-center gap-3 p-4 border-2 border-gray-200 rounded-xl hover:border-purple-400 cursor-pointer transition-all group",onClick:()=>Ge(Y),children:[e.jsx("div",{className:"w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx("span",{className:"text-2xl",children:Y.gender==="boy"?"👦":"👧"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-800 truncate",children:Y.childName}),e.jsxs("p",{className:"text-sm text-gray-500",children:["Age ",Y.age," · ",Y.fascinations.slice(0,2).join(", "),Y.fascinations.length>2?"…":""]})]}),e.jsx("button",{onClick:ie=>{ie.stopPropagation(),Te(Y.id)},className:"opacity-0 group-hover:opacity-100 text-gray-400 hover:text-red-500 transition-all p-1",children:e.jsx(Oo,{className:"w-4 h-4"})})]},Y.id))}),e.jsxs("button",{onClick:Me,className:"w-full py-3 px-6 rounded-xl border-2 border-dashed border-gray-300 text-gray-600 font-medium hover:border-purple-400 hover:text-purple-600 transition-colors flex items-center justify-center gap-2",children:[e.jsx(zp,{className:"w-5 h-5"})," Create New Profile"]})]}),ft=()=>e.jsxs("div",{className:"text-center px-6 py-8",children:[e.jsx("div",{className:"w-20 h-20 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx("span",{className:"text-4xl",children:"🧩"})}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold text-gray-800 mb-4",children:"Stories that know your child."}),e.jsx("p",{className:"text-gray-600 mb-8 max-w-md mx-auto",children:"Did you know personalized stories increase engagement by 3x? Tell us about their world once, and we'll weave their favorites into every adventure."}),e.jsx("button",{onClick:_e,className:"w-full bg-purple-600 hover:bg-purple-700 text-white font-semibold py-4 px-8 rounded-xl transition-colors",children:"Build Profile"})]}),Ze=()=>e.jsxs("div",{className:"px-6 py-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-800 text-center mb-2",children:"About Your Child"}),e.jsx("p",{className:"text-gray-500 text-center mb-6",children:"Let's personalize this story for them"}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["Child's Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:d.childName,onChange:Y=>h({...d,childName:Y.target.value}),placeholder:"Enter your child's name",className:"w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent outline-none"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["Age: ",d.age," years"]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-sm text-gray-500",children:"2"}),e.jsx("input",{type:"range",min:"2",max:"10",value:d.age,onChange:Y=>h({...d,age:parseInt(Y.target.value)}),className:"flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-purple-600"}),e.jsx("span",{className:"text-sm text-gray-500",children:"10"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:"Gender"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("button",{onClick:()=>h({...d,gender:"boy"}),className:`py-3 px-4 rounded-xl border-2 transition-all flex items-center justify-center gap-2 ${d.gender==="boy"?"border-purple-600 bg-purple-600 text-white":"border-gray-200 hover:border-purple-300"}`,children:[e.jsx("span",{children:"👦"})," Boy"]}),e.jsxs("button",{onClick:()=>h({...d,gender:"girl"}),className:`py-3 px-4 rounded-xl border-2 transition-all flex items-center justify-center gap-2 ${d.gender==="girl"?"border-purple-600 bg-purple-600 text-white":"border-gray-200 hover:border-purple-300"}`,children:[e.jsx("span",{children:"👧"})," Girl"]})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["Child's Photo ",e.jsx("span",{className:"text-gray-400 text-xs",children:"(optional — makes illustrations look like your child!)"})]}),e.jsx("input",{ref:b,type:"file",accept:"image/jpeg,image/jpg,image/png,image/webp",className:"hidden",onChange:Y=>{var He;const ie=(He=Y.target.files)==null?void 0:He[0];if(ie){v(ie);const Qe=new FileReader;Qe.onload=lt=>{var gt;return j((gt=lt.target)==null?void 0:gt.result)},Qe.readAsDataURL(ie)}}}),x?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:x,alt:"Child preview",className:"w-20 h-20 rounded-xl object-cover border-2 border-purple-200"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{onClick:()=>{var Y;return(Y=b.current)==null?void 0:Y.click()},className:"text-sm text-purple-600 hover:text-purple-700 font-medium",children:"Change photo"}),e.jsx("button",{onClick:()=>{v(null),j(null)},className:"text-sm text-gray-400 hover:text-red-500",children:"Remove"})]})]}):e.jsxs("button",{onClick:()=>{var Y;return(Y=b.current)==null?void 0:Y.click()},className:"w-full py-4 rounded-xl border-2 border-dashed border-gray-300 hover:border-purple-300 transition-colors flex items-center justify-center gap-2 text-gray-500 hover:text-purple-600",children:[e.jsx(Op,{className:"w-5 h-5"})," Upload a clear face photo"]}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"A clear, front-facing photo works best. JPG/PNG only."})]})]})]}),ke=()=>e.jsxs("div",{className:"px-6 py-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-800 text-center mb-2",children:"Tap what they love"}),e.jsxs("p",{className:"text-gray-500 text-center mb-6",children:["We'll weave these into ",d.childName||"their","'s adventures"]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:["Fascinations ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Zj.map(({emoji:Y,label:ie})=>e.jsxs("button",{onClick:()=>ue("fascinations",ie),className:`py-2 px-4 rounded-full border-2 transition-all flex items-center gap-2 ${d.fascinations.includes(ie)?"border-purple-600 bg-purple-50 text-purple-700":"border-gray-200 hover:border-purple-300"}`,children:[e.jsx("span",{children:Y})," ",ie]},ie))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:"Favorite Food"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Xj.map(({emoji:Y,label:ie})=>e.jsxs("button",{onClick:()=>h({...d,favoriteFood:ie}),className:`py-2 px-4 rounded-full border-2 transition-all flex items-center gap-2 ${d.favoriteFood===ie?"border-purple-600 bg-purple-50 text-purple-700":"border-gray-200 hover:border-purple-300"}`,children:[e.jsx("span",{children:Y})," ",ie]},ie))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["People/Pets ",e.jsx("span",{className:"text-gray-400 text-xs",children:"(optional)"})]}),e.jsx("input",{type:"text",value:d.peoplePets,onChange:Y=>h({...d,peoplePets:Y.target.value}),placeholder:"e.g., Grandma, Max the Dog",className:"w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent outline-none"})]})]})]}),Ce=()=>e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-gray-800 text-center mb-2",children:[d.childName||"Child","'s Personality"]}),e.jsx("p",{className:"text-gray-500 text-center mb-6",children:"Help us match the story to their spirit"}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:"Personality"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Qj.map(({emoji:Y,label:ie})=>e.jsxs("button",{onClick:()=>ue("personality",ie),className:`py-2 px-4 rounded-full border-2 transition-all flex items-center gap-2 ${d.personality.includes(ie)?"border-purple-600 bg-purple-50 text-purple-700":"border-gray-200 hover:border-purple-300"}`,children:[e.jsx("span",{children:Y})," ",ie]},ie))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:"Learning Goals"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e1.map(({emoji:Y,label:ie})=>e.jsxs("button",{onClick:()=>ue("learningGoals",ie),className:`py-2 px-4 rounded-full border-2 transition-all flex items-center gap-2 ${d.learningGoals.includes(ie)?"border-purple-600 bg-purple-50 text-purple-700":"border-gray-200 hover:border-purple-300"}`,children:[e.jsx("span",{children:Y})," ",ie]},ie))})]})]})]}),B=()=>e.jsxs("div",{className:"px-6 py-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-800 text-center mb-2",children:"Story Preferences"}),e.jsx("p",{className:"text-gray-500 text-center mb-6",children:"Choose language and visual style for this story"}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:["Story Language ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:t1.map(({emoji:Y,label:ie})=>e.jsxs("button",{onClick:()=>g(He=>({...He,language:ie})),className:`py-3 px-3 rounded-xl border-2 transition-all flex flex-col items-center gap-1 text-sm ${m.language===ie?"border-purple-600 bg-purple-50 text-purple-700":"border-gray-200 hover:border-purple-300"}`,children:[e.jsx("span",{className:"text-lg",children:Y}),ie]},ie))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:["Art Style ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:s1.map(({emoji:Y,label:ie,desc:He})=>e.jsxs("button",{onClick:()=>g(Qe=>({...Qe,artStyle:ie})),className:`py-3 px-3 rounded-xl border-2 transition-all text-left ${m.artStyle===ie?"border-purple-600 bg-purple-50":"border-gray-200 hover:border-purple-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{children:Y}),e.jsx("span",{className:"font-medium text-sm text-gray-800",children:ie})]}),e.jsx("p",{className:"text-xs text-gray-500",children:He})]},ie))})]})]})]}),st=()=>c===0?null:e.jsxs("div",{className:"px-6 pb-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("button",{onClick:Se,className:"flex-1 py-3 px-6 rounded-xl border-2 border-gray-200 text-gray-700 font-medium hover:border-gray-300 transition-colors flex items-center justify-center gap-2",children:[e.jsx(Io,{className:"w-4 h-4"})," Back"]}),c<U-1?e.jsxs("button",{onClick:_e,className:"flex-1 py-3 px-6 rounded-xl bg-purple-600 text-white font-medium hover:bg-purple-700 transition-colors flex items-center justify-center gap-2",children:["Continue ",e.jsx(Bi,{className:"w-4 h-4"})]}):e.jsxs("button",{onClick:re,disabled:S||!d.childName||!d.gender,className:"flex-1 py-3 px-6 rounded-xl bg-purple-600 text-white font-medium hover:bg-purple-700 transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:["Create Story ",e.jsx(Bi,{className:"w-4 h-4"})]})]}),e.jsx("button",{onClick:t,className:"w-full text-center text-gray-500 hover:text-gray-700 mt-3 text-sm",children:"Skip for now"})]});return e.jsxs(e.Fragment,{children:[e.jsx(ks,{children:r&&!V&&e.jsx(Ie.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50",onClick:t,children:e.jsxs(Ie.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.95,opacity:0},onClick:Y=>Y.stopPropagation(),className:"bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto relative",children:[e.jsx("button",{onClick:t,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 z-10",children:e.jsx(Cs,{className:"w-6 h-6"})}),e.jsx(ks,{mode:"wait",children:e.jsxs(Ie.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.2},children:[o==="select"&&Xe(),o==="create"&&c===0&&ft(),o==="create"&&c===1&&Ze(),o==="create"&&c===2&&ke(),o==="create"&&c===3&&Ce(),o==="create"&&c===4&&B()]},o==="select"?"select":`create-${c}`)}),o==="create"&&st(),o==="create"&&pe(),e.jsx("div",{className:"h-4"})]})})}),e.jsx(Jj,{isOpen:E,onClose:qe,status:(y==null?void 0:y.status)||"pending",currentStep:(y==null?void 0:y.currentStep)||"starting",progress:(y==null?void 0:y.progress)||0,errorMessage:(y==null?void 0:y.errorMessage)||void 0,onViewStory:Ne,pagesReady:((Ye=y==null?void 0:y.pages)==null?void 0:Ye.length)||0,onPreviewPages:Ne}),y&&e.jsx(Wa,{isOpen:V,onClose:fe,storyTitle:y.storyTitle||"Your Story",pages:y.pages,childName:d.childName,storyId:y.id})]})},Xn=({isOpen:r,onClose:t,onSuccess:s})=>{const[a,n]=p.useState(""),[i,o]=p.useState(""),[l,c]=p.useState(!1),[u,d]=p.useState(""),{login:h}=Qs(),m=()=>{n(""),o(""),d(""),c(!1)},g=()=>{m(),t()},f=x=>{const j=x.target.value.replace(/\D/g,"");j.length<=10&&o(j)},v=async x=>{if(x.preventDefault(),!a||!a.includes("@")){d("Please enter a valid email address");return}if(i.length!==10){d("Please enter a valid 10-digit mobile number");return}c(!0),d("");try{if((await h(a.trim().toLowerCase(),i)).success){m(),s();return}const{data:b,error:y}=await de.functions.invoke("create-user-account",{body:{email:a.trim().toLowerCase(),mobile:i}});if(y||!(b!=null&&b.success)){d("Something went wrong. Please try again."),c(!1);return}const S=await h(a.trim().toLowerCase(),i);S.success?(m(),s()):(d(S.error||"Login failed after account creation. Please try again."),c(!1))}catch(j){d(j.message||"Something went wrong. Please try again."),c(!1)}};return e.jsx(ks,{children:r&&e.jsx(Ie.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50",onClick:g,children:e.jsxs(Ie.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.95,opacity:0},onClick:x=>x.stopPropagation(),className:"bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden relative",children:[e.jsx("button",{onClick:g,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 z-10",children:e.jsx(Cs,{className:"w-6 h-6"})}),e.jsxs("div",{className:"px-6 py-8",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-3xl",children:"📖"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-800 mb-1",children:"Welcome to TalesBerry"}),e.jsx("p",{className:"text-gray-500 text-sm",children:"Enter your details to create stories for your child"})]}),e.jsxs("form",{onSubmit:v,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:[e.jsx(Ma,{className:"w-4 h-4 inline mr-1.5 -mt-0.5"}),"Email Address"]}),e.jsx("input",{type:"email",value:a,onChange:x=>{n(x.target.value),d("")},placeholder:"your@email.com",className:"w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 outline-none transition-all"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:[e.jsx(On,{className:"w-4 h-4 inline mr-1.5 -mt-0.5"}),"Mobile Number"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex items-center px-3 py-3 bg-gray-100 border border-gray-300 rounded-xl text-gray-600 font-medium text-sm min-w-[60px] justify-center",children:"+91"}),e.jsx("input",{type:"tel",value:i,onChange:f,placeholder:"10-digit number",inputMode:"numeric",maxLength:10,className:"flex-1 px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 outline-none transition-all"})]})]}),u&&e.jsx("p",{className:"text-red-500 text-sm bg-red-50 px-3 py-2 rounded-lg",children:u}),e.jsx("button",{type:"submit",disabled:l||!a||i.length!==10,className:"w-full py-3 px-6 rounded-xl bg-purple-600 text-white font-medium hover:bg-purple-700 transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:l?e.jsx(Ue,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Continue ",e.jsx(Bi,{className:"w-4 h-4"})]})})]}),e.jsx("p",{className:"text-center text-xs text-gray-400 mt-4",children:"We'll use this to save your stories. No spam, ever."})]})]})})})},Jd=({inline:r=!1,refreshKey:t=0})=>{const[s,a]=p.useState([]),[n,i]=p.useState(!0),[o,l]=p.useState(null),[c,u]=p.useState(!1),[d,h]=p.useState(null),{user:m}=Qs();p.useEffect(()=>{g()},[t]);const g=async()=>{try{const{data:x,error:j}=await de.from("custom_stories").select("id, story_title, child_name, child_age, pages, created_at, art_style, language").eq("is_published",!0).eq("status","completed").order("created_at",{ascending:!1}).limit(50);!j&&x&&a(x.map(b=>({...b,pages:Array.isArray(b.pages)?b.pages:[]})))}catch(x){console.error("Failed to fetch published stories:",x)}finally{i(!1)}},f=x=>{l(x)},v=()=>{u(!1),d&&(l(d),h(null))};return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ue,{className:"w-6 h-6 animate-spin text-purple-400"})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:r?"pb-8":"max-w-5xl mx-auto px-4 pb-16",children:[!r&&e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-bold text-gray-800 mb-2",children:"📚 StoryHouse Collection"}),e.jsx("p",{className:"text-gray-500",children:"Stories published by other kids for everyone to enjoy"})]}),r&&e.jsx("h2",{className:"text-2xl font-bold text-gray-800 mb-6 text-center",children:"📚 StoryHouse Collection"}),s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ls,{className:"w-12 h-12 text-purple-300 mx-auto mb-3"}),e.jsx("p",{className:"text-gray-500",children:"No stories published yet. Be the first to share!"})]}):e.jsx("div",{className:r?"grid grid-cols-2 sm:grid-cols-2 gap-3 sm:gap-4":"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 sm:gap-4",children:s.map((x,j)=>{var y;const b=(y=x.pages.find(S=>S.type==="image"))==null?void 0:y.content;return e.jsxs(Ie.button,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:j*.04},whileHover:{scale:1.03},whileTap:{scale:.98},onClick:()=>f(x),className:"bg-white rounded-xl shadow-md overflow-hidden text-left hover:shadow-lg transition-shadow group",children:[e.jsx("div",{className:"aspect-[4/3] bg-purple-50 relative overflow-hidden",children:b?e.jsx(Sl,{src:b,title:x.story_title||`${x.child_name}'s Story`}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Ls,{className:"w-10 h-10 text-purple-300"})})}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"font-semibold text-gray-800 text-sm truncate",children:x.story_title||`${x.child_name}'s Story`}),e.jsxs("p",{className:"text-xs text-purple-600 font-medium mt-1",children:["✍️ by ",x.child_name,", Age ",x.child_age]}),x.language&&x.language!=="English"&&e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:x.language}),x.art_style&&e.jsx("span",{className:"inline-block mt-1 text-xs bg-purple-50 text-purple-600 px-2 py-0.5 rounded-full",children:x.art_style})]})]},x.id)})})]}),o&&e.jsx(Wa,{isOpen:!!o,onClose:()=>l(null),storyTitle:o.story_title||"Story",pages:o.pages,childName:o.child_name,storyId:o.id,maxPages:m?void 0:2,onLoginRequired:()=>{l(null),h(o),u(!0)}}),e.jsx(Xn,{isOpen:c,onClose:()=>{u(!1),h(null)},onSuccess:v})]})},a1=[{title:"Space Explorer",description:"Blast off to distant galaxies and discover new planets!",image:"/story_tiles/space_explorer.jpg"},{title:"Jungle Safari",description:"Trek through wild jungles and befriend amazing animals!",image:"/story_tiles/jungle_safari.jpg"},{title:"Underwater Quest",description:"Dive deep into the ocean and uncover hidden treasures!",image:"/story_tiles/underwater_quest.jpg"},{title:"Magic Kingdom",description:"Enter an enchanted kingdom full of fairies and wonder!",image:"/story_tiles/magic_kingdom.jpg"}],n1=()=>{const[r,t]=p.useState(!1),[s,a]=p.useState(),[n,i]=p.useState(!1),[o,l]=p.useState(null),[c,u]=p.useState(0),{user:d,logout:h}=Qs(),m=p.useCallback(()=>{u(j=>j+1)},[]),g=(j,b)=>{if(!d){l({type:j,theme:b}),i(!0);return}a(j==="tile"?b:void 0),t(!0)},f=()=>{i(!1),o&&(o.type==="tile"?a(o.theme):a(void 0),t(!0),l(null))},v=()=>{t(!1),a(void 0)},x=async()=>{await h()};return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"Custom Storybooks | Create Stories Based on Your Child's Interests | TalesBerry"}),e.jsx("link",{rel:"canonical",href:"https://www.talesberry.com/custom-storybooks"}),e.jsx("meta",{name:"description",content:"Create personalized storybooks tailored to your child's interests and learning goals. Build their unique character profile and watch their story come to life."})]}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-purple-50 to-white relative overflow-hidden",children:[d&&e.jsxs("div",{className:"absolute top-4 right-4 z-10 flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-gray-600 hidden sm:inline",children:d.email_id}),e.jsxs("button",{onClick:x,className:"flex items-center gap-1.5 px-3 py-1.5 bg-white/80 backdrop-blur-sm rounded-full text-sm text-gray-600 hover:text-red-600 hover:bg-red-50 transition-colors shadow-sm",children:[e.jsx(Lo,{className:"w-4 h-4"})," Sign out"]})]}),e.jsx("div",{className:"absolute top-20 left-10 w-16 h-10 bg-purple-100 rounded-full opacity-60"}),e.jsx("div",{className:"absolute top-16 left-24 w-12 h-8 bg-pink-100 rounded-full opacity-50"}),e.jsx("div",{className:"absolute top-24 right-16 w-20 h-12 bg-blue-100 rounded-full opacity-60"}),e.jsx("div",{className:"absolute top-20 right-32 w-14 h-9 bg-yellow-100 rounded-full opacity-50"}),e.jsx(Ie.div,{initial:{rotate:-15,opacity:0},animate:{rotate:-15,opacity:1},transition:{delay:.3},className:"absolute top-32 left-8 md:left-16 text-4xl md:text-5xl",children:"✨"}),e.jsx(Ie.div,{initial:{rotate:15,opacity:0},animate:{rotate:15,opacity:1},transition:{delay:.5},className:"absolute top-40 right-8 md:right-20 text-4xl md:text-5xl",children:"📖"}),e.jsxs("div",{className:"container mx-auto px-4 pt-8 md:pt-16 pb-12",children:[e.jsxs(Ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.6},className:"text-center mb-8 md:mb-12",children:[e.jsxs("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold text-gray-800 leading-tight",children:["Create Stories Based on",e.jsx("br",{}),e.jsx("span",{className:"text-purple-600",children:"Your Child's World"})]}),e.jsx("p",{className:"mt-4 text-lg md:text-xl text-gray-600 max-w-2xl mx-auto",children:"Pick a story idea below, or create your own adventure from scratch!"})]}),e.jsx(Ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.6,delay:.2},className:"grid grid-cols-2 md:grid-cols-4 gap-4 max-w-4xl mx-auto mb-10",children:a1.map((j,b)=>e.jsxs(Ie.button,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3+b*.1},whileHover:{scale:1.03,y:-4},whileTap:{scale:.97},onClick:()=>g("tile",j.title),className:"relative rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-shadow aspect-[4/5] group",children:[e.jsx("img",{src:j.image,alt:j.title,className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-4 text-left",children:[e.jsx("h3",{className:"font-bold text-white text-sm md:text-base mb-1",children:j.title}),e.jsx("p",{className:"text-xs text-white/80 leading-relaxed",children:j.description})]})]},j.title))}),e.jsx(Ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.6,delay:.6},className:"text-center",children:e.jsx("button",{onClick:()=>g("create"),className:"bg-black hover:bg-gray-800 text-white font-semibold py-4 px-10 md:px-14 rounded-full text-lg md:text-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105",children:"Create Your Own Story ✨"})})]})]}),d?e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-8 grid grid-cols-1 md:grid-cols-2 gap-8",children:[e.jsx(Hj,{onPublishChange:m}),e.jsx(Jd,{inline:!0,refreshKey:c})]}):e.jsx(Jd,{}),e.jsx(r1,{isOpen:r,onClose:v,initialTheme:s}),e.jsx(Xn,{isOpen:n,onClose:()=>{i(!1),l(null)},onSuccess:f})]})},i1=()=>{const{storyId:r}=Xr(),[t,s]=p.useState(!0),[a,n]=p.useState(null),[i,o]=p.useState(""),[l,c]=p.useState(""),[u,d]=p.useState([]),[h,m]=p.useState(null),[g,f]=p.useState(!1),{user:v}=Jn();return p.useEffect(()=>{if(!r)return;(async()=>{var j;try{const{data:b,error:y}=await de.from("custom_stories").select("story_title, child_name, pages, status, is_published, user_id").eq("id",r).single();if(y||!b){n("Story not found. It may have been removed.");return}if(b.status!=="completed"){n("This story is still being created. Check back soon!");return}o(b.story_title||`${b.child_name}'s Story`),c(b.child_name);const S=Array.isArray(b.pages)?b.pages:[];d(S);const T=(j=S.find(I=>I.type==="image"))==null?void 0:j.content;m(T||null)}catch{n("Failed to load story.")}finally{s(!1)}})()},[r]),t?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-amber-50 to-orange-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ue,{className:"w-10 h-10 animate-spin text-purple-500 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading story..."})]})}):a?e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-amber-50 to-orange-50 p-4",children:[e.jsx(as,{children:e.jsx("title",{children:"Story Not Found | TalesBerry"})}),e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-20 h-20 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx("span",{className:"text-4xl",children:"📖"})}),e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-3",children:a}),e.jsx("a",{href:"/custom-storybooks",className:"inline-block mt-4 px-6 py-3 bg-purple-600 text-white rounded-xl font-medium hover:bg-purple-700 transition-colors",children:"Create Your Own Story"})]})]}):v?e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsxs("title",{children:[i," | TalesBerry"]}),e.jsx("link",{rel:"canonical",href:`https://www.talesberry.com/story/${r}`}),e.jsx("meta",{name:"description",content:`Read "${i}" — a personalized story created on TalesBerry for ${l}.`})]}),e.jsx(Wa,{isOpen:!0,onClose:()=>window.location.href="/custom-storybooks",storyTitle:i,pages:u,childName:l,storyId:r})]}):e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsxs("title",{children:[i," | TalesBerry"]}),e.jsx("link",{rel:"canonical",href:`https://www.talesberry.com/story/${r}`}),e.jsx("meta",{name:"description",content:`Read "${i}" — a personalized story on TalesBerry.`})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-amber-50 to-orange-50 flex items-center justify-center p-4",children:e.jsxs("div",{className:"max-w-md w-full text-center",children:[h&&e.jsxs("div",{className:"relative rounded-2xl overflow-hidden shadow-xl mb-6 aspect-[4/3]",children:[e.jsx(Sl,{src:h,title:i}),e.jsx("div",{className:"absolute inset-0 bg-black/30 flex items-center justify-center",children:e.jsx("div",{className:"bg-white/90 rounded-full p-4",children:e.jsx(vt,{className:"w-8 h-8 text-purple-600"})})})]}),e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-2",children:i}),e.jsx("p",{className:"text-gray-500 mb-6",children:"Sign in to read the full story"}),e.jsx("button",{onClick:()=>f(!0),className:"px-8 py-3 bg-purple-600 text-white rounded-xl font-medium hover:bg-purple-700 transition-colors",children:"Sign in to Read"}),e.jsx("a",{href:"/custom-storybooks",className:"block mt-4 text-purple-600 hover:underline text-sm",children:"Or create your own story →"})]})}),e.jsx(Xn,{isOpen:g,onClose:()=>f(!1),onSuccess:()=>f(!1)})]})},o1=()=>{const[r,t]=p.useState([]),[s,a]=p.useState(!0),[n,i]=p.useState(null),[o,l]=p.useState(!1),[c,u]=p.useState(null),{user:d}=Qs();p.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:f,error:v}=await de.from("custom_stories").select("id, story_title, child_name, child_age, pages, created_at, art_style, language").eq("is_published",!0).eq("status","completed").order("created_at",{ascending:!1}).limit(50);!v&&f&&t(f.map(x=>({...x,pages:Array.isArray(x.pages)?x.pages:[]})))}catch(f){console.error("Failed to fetch published stories:",f)}finally{a(!1)}},m=f=>{d?i(f):(u(f),l(!0))},g=()=>{l(!1),c&&(i(c),u(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"Storyhouse | Read Published Stories | TalesBerry"}),e.jsx("link",{rel:"canonical",href:"https://www.talesberry.com/storyhouse"}),e.jsx("meta",{name:"description",content:"Browse and read published personalized children's stories created by parents on TalesBerry."})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-amber-50 to-white",children:e.jsxs("div",{className:"container mx-auto px-4 pt-8 pb-16",children:[e.jsxs(Ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"text-center mb-10",children:[e.jsx("h1",{className:"text-3xl md:text-5xl font-bold text-gray-800 mb-3",children:"📚 The Storyhouse"}),e.jsx("p",{className:"text-lg text-gray-600 max-w-xl mx-auto",children:"Discover magical stories created by other kids"})]}),s?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ue,{className:"w-8 h-8 animate-spin text-purple-400"})}):r.length===0?e.jsxs("div",{className:"text-center py-16 text-gray-500",children:[e.jsx(Ls,{className:"w-16 h-16 mx-auto mb-4 text-gray-300"}),e.jsx("p",{className:"text-xl font-medium",children:"No stories published yet"}),e.jsx("p",{className:"mt-2",children:"Be the first to publish a story!"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-5",children:r.map((f,v)=>{var j;const x=(j=f.pages.find(b=>b.type==="image"))==null?void 0:j.content;return e.jsxs(Ie.button,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:v*.05},whileHover:{scale:1.03},whileTap:{scale:.98},onClick:()=>m(f),className:"bg-white rounded-xl shadow-md overflow-hidden text-left hover:shadow-lg transition-shadow group",children:[e.jsxs("div",{className:"aspect-[4/3] bg-purple-50 relative overflow-hidden",children:[x?e.jsx("img",{src:x,alt:f.story_title||"Story",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Ls,{className:"w-12 h-12 text-purple-300"})}),!d&&e.jsx("div",{className:"absolute inset-0 bg-black/20 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"bg-white/90 rounded-full p-2",children:e.jsx(vt,{className:"w-5 h-5 text-purple-600"})})})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"font-semibold text-gray-800 text-sm truncate",children:f.story_title||`${f.child_name}'s Story`}),e.jsxs("p",{className:"text-xs text-purple-600 font-medium mt-1",children:["✍️ by ",f.child_name,", Age ",f.child_age]}),f.language&&f.language!=="English"&&e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:f.language}),f.art_style&&e.jsx("span",{className:"inline-block mt-1.5 text-xs bg-purple-50 text-purple-600 px-2 py-0.5 rounded-full",children:f.art_style})]})]},f.id)})})]})}),n&&e.jsx(Wa,{isOpen:!!n,onClose:()=>i(null),storyTitle:n.story_title||"Story",pages:n.pages,childName:n.child_name,storyId:n.id}),e.jsx(Xn,{isOpen:o,onClose:()=>{l(!1),u(null)},onSuccess:g})]})},Zd=r=>r.replace(/^\[Girl\]'s\s+/i,"").replace(/^\[Boy\]'s\s+/i,"").replace(/^\[Girl\]\s*&\s*/i,"").replace(/^\[Boy\]\s*&\s*/i,""),l1=()=>Ot.filter(r=>{var t,s;return!r.hidden&&r.ageRange!=="18-99 years"&&!((t=r.specialTag)!=null&&t.includes("For Parents"))&&!((s=r.specialTag)!=null&&s.includes("For Partners"))}),c1=()=>{const r=_t(),{buildLink:t,region:s}=ht(),a=l1(),n=Zn(s),i=c=>{const u=document.getElementById(c);u&&u.scrollIntoView({behavior:"smooth"})},o=c=>{const u=Ot.find(d=>d.id===c);r(t(`/books/${c}/personalize`),{state:{selectedBook:u}})},l=c=>{r(t(`/stickers/${c}/personalize`))};return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"Kids Personalised Books & Stickers | TalesBerry"}),e.jsx("meta",{name:"description",content:"Explore our collection of personalised children's books and stickers. Create magical stories featuring your child as the hero."})]}),e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx("section",{className:"py-8 md:py-12",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsx("div",{className:"text-center mb-8",children:e.jsx("h1",{className:"text-2xl md:text-3xl font-bold text-foreground",children:"Kids Personalised Collection"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:gap-6 max-w-3xl mx-auto",children:[e.jsxs(Ie.button,{onClick:()=>i("kids-books-section"),whileHover:{scale:1.02},whileTap:{scale:.98},className:"relative overflow-hidden rounded-xl md:rounded-2xl aspect-[3/4] md:aspect-square",children:[e.jsx("img",{src:"/gifts/kids.png",alt:"Kids Personalised Books",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-black/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-3 md:bottom-4 left-3 md:left-4 right-3 md:right-4",children:[e.jsx("span",{className:"inline-block px-2 py-0.5 md:px-3 md:py-1 bg-purple-500 text-white text-xs md:text-sm font-medium rounded-full mb-1.5 md:mb-2",children:"Books"}),e.jsx("h2",{className:"text-white font-bold text-sm md:text-lg leading-tight",children:"Kids Personalised Books"})]})]}),e.jsxs(Ie.button,{onClick:()=>i("kids-stickers-section"),whileHover:{scale:1.02},whileTap:{scale:.98},className:"relative overflow-hidden rounded-xl md:rounded-2xl aspect-[3/4] md:aspect-square",children:[e.jsxs("div",{className:"w-full h-full grid grid-cols-2 gap-1",children:[e.jsx("img",{src:`${ot}/stickers_thumbnail_boy/1.jpg`,alt:"Kids Personalised Stickers",className:"w-full h-full object-cover"}),e.jsx("img",{src:`${ot}/stickers_thumbnail_boy/2.jpg`,alt:"Kids Personalised Stickers",className:"w-full h-full object-cover"})]}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-black/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-3 md:bottom-4 left-3 md:left-4 right-3 md:right-4",children:[e.jsx("span",{className:"inline-block px-2 py-0.5 md:px-3 md:py-1 bg-pink-500 text-white text-xs md:text-sm font-medium rounded-full mb-1.5 md:mb-2",children:"Stickers"}),e.jsx("h2",{className:"text-white font-bold text-sm md:text-lg leading-tight",children:"Kids Personalised Stickers"})]})]})]})]})}),e.jsx("section",{id:"kids-books-section",className:"py-12 md:py-16 bg-white/50",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-bold text-foreground mb-3",children:"Kids Personalised Books"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mx-auto",children:"Choose from our magical collection of storybooks. Each book features your child as the main character!"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6",children:a.map((c,u)=>e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:u*.05},className:"bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition-shadow cursor-pointer",onClick:()=>o(c.id),children:[e.jsx("div",{className:"relative w-full aspect-square",children:e.jsx($s,{imagePath:c.imagePaths[0],alt:Zd(c.title),className:"w-full h-full object-cover",loading:"lazy",decoding:"async"})}),e.jsxs("div",{className:"p-3 md:p-4",children:[e.jsx("h3",{className:"text-sm md:text-base font-semibold text-foreground mb-2 min-h-[2.5rem] flex items-center leading-tight",children:Zd(c.title)}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-semibold ${c.suitableFor.toLowerCase().includes("boy")?"bg-blue-500 text-white":c.suitableFor.toLowerCase().includes("girl")?"bg-pink-500 text-white":"bg-orange-500 text-white"}`,children:c.suitableFor.toLowerCase().includes("boy")&&!c.suitableFor.toLowerCase().includes("girl")?"Boys":c.suitableFor.toLowerCase().includes("girl")&&!c.suitableFor.toLowerCase().includes("boy")?"Girls":c.suitableFor}),e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full text-xs",children:c.ageRange})]}),e.jsx("button",{className:"w-full bg-black text-white font-medium px-4 py-2 rounded-full text-sm shadow-sm active:opacity-80 transition-opacity",onClick:d=>{d.stopPropagation(),o(c.id)},children:"Personalise"})]})]},c.id))})]})}),e.jsx("section",{id:"kids-stickers-section",className:"py-12 md:py-16",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-bold text-foreground mb-3",children:"Kids Personalised Stickers"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mx-auto",children:"Fun personalised sticker sheets featuring your child's face. Perfect for school supplies, water bottles, and more!"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:gap-6 max-w-2xl mx-auto",children:[e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.1},className:"bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition-shadow cursor-pointer",onClick:()=>l("boys"),children:[e.jsx("div",{className:"relative w-full aspect-square bg-gradient-to-br from-blue-100 to-cyan-100 flex items-center justify-center",children:e.jsx("div",{className:"text-center",children:e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 bg-blue-500 rounded-full flex items-center justify-center mx-auto",children:e.jsx(Kl,{className:"w-8 h-8 md:w-10 md:h-10 text-white"})})})}),e.jsxs("div",{className:"p-3 md:p-4",children:[e.jsx("h3",{className:"text-sm md:text-base font-semibold text-foreground mb-2 min-h-[2.5rem] flex items-center leading-tight",children:"Boy's Sticker Pack"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[e.jsx("span",{className:"px-2 py-0.5 bg-blue-500 text-white rounded-full text-xs font-semibold",children:"Boys"}),e.jsxs("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full text-xs",children:[n.currencySymbol,n.price]})]}),e.jsx("button",{onClick:c=>{c.stopPropagation(),l("boys")},className:"w-full bg-black text-white font-medium px-4 py-2 rounded-full text-sm shadow-sm active:opacity-80 transition-opacity",children:"Personalise"})]})]}),e.jsxs(Ie.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.15},className:"bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition-shadow cursor-pointer",onClick:()=>l("girls"),children:[e.jsx("div",{className:"relative w-full aspect-square bg-gradient-to-br from-pink-100 to-purple-100 flex items-center justify-center",children:e.jsx("div",{className:"text-center",children:e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 bg-pink-500 rounded-full flex items-center justify-center mx-auto",children:e.jsx(Kl,{className:"w-8 h-8 md:w-10 md:h-10 text-white"})})})}),e.jsxs("div",{className:"p-3 md:p-4",children:[e.jsx("h3",{className:"text-sm md:text-base font-semibold text-foreground mb-2 min-h-[2.5rem] flex items-center leading-tight",children:"Girl's Sticker Pack"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[e.jsx("span",{className:"px-2 py-0.5 bg-pink-500 text-white rounded-full text-xs font-semibold",children:"Girls"}),e.jsxs("span",{className:"px-2 py-0.5 bg-pink-100 text-pink-700 rounded-full text-xs",children:[n.currencySymbol,n.price]})]}),e.jsx("button",{onClick:c=>{c.stopPropagation(),l("girls")},className:"w-full bg-black text-white font-medium px-4 py-2 rounded-full text-sm shadow-sm active:opacity-80 transition-opacity",children:"Personalise"})]})]})]})]})})]})]})},d1=()=>e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"bg-white pt-6 pb-2 md:pt-10 md:pb-4",children:e.jsx("div",{className:"max-w-3xl mx-auto px-4 text-center md:text-left",children:e.jsx("p",{className:"text-lg text-gray-700 leading-relaxed",children:"TalesBerry creates personalised children's storybooks where your child becomes the main character in a magical adventure. Using AI, we transform your child's photo into beautifully illustrated books, making reading more engaging, personal, and memorable."})})}),e.jsx("section",{className:"py-8 md:py-14 bg-white",children:e.jsxs("div",{className:"max-w-4xl mx-auto px-4 text-center md:text-left",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold mb-6 text-gray-900",children:"What is TalesBerry?"}),e.jsx("p",{className:"text-gray-700 mb-4 leading-relaxed",children:"TalesBerry is a platform that creates personalised books for kids using their name and photo. Each story is uniquely generated so that your child becomes the hero of their own adventure — complete with their appearance, age, and personality woven into every page."}),e.jsx("p",{className:"text-gray-700 mb-4 leading-relaxed",children:"These custom storybooks are perfect as personalised gifts for birthdays, return gifts, and special occasions, while also helping children build confidence and a love for reading. Unlike generic children's books, every page is crafted around your child."}),e.jsx("p",{className:"text-gray-700 leading-relaxed",children:"Each book is printed on premium 220 GSM paper with vibrant, glossy laminated covers — designed to be a lasting keepsake that children treasure for years."})]})})]}),u1=[{icon:Ls,title:"Builds Reading Habits",description:"Children are far more likely to pick up a book when they see themselves as the main character. Personalised storybooks turn reluctant readers into eager ones."},{icon:$o,title:"Creates Emotional Connection",description:"Seeing their own name and face in a story creates a deep emotional bond with the narrative, making each reading session a cherished memory."},{icon:Ba,title:"Boosts Confidence",description:"When children see themselves as the hero overcoming challenges, it nurtures self-belief and shows them they can achieve anything they set their mind to."},{icon:$p,title:"Sparks Imagination",description:"Custom storybooks transport children into worlds built around them — fuelling creativity, curiosity, and a lifelong love of storytelling."}],h1=()=>e.jsx("section",{className:"py-10 md:py-16 bg-gray-50",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4",children:[e.jsx("h2",{className:"text-2xl md:text-3xl font-semibold mb-8 text-gray-900 text-center",children:"Why Personalised Books Are Powerful for Children"}),e.jsx("ul",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:u1.map(r=>e.jsx("li",{className:"bg-white rounded-xl p-6 shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center",children:e.jsx(r.icon,{className:"w-5 h-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900 mb-1",children:r.title}),e.jsx("p",{className:"text-gray-600 text-sm leading-relaxed",children:r.description})]})]})},r.title))})]})}),m1={"@context":"https://schema.org","@type":"HowTo",name:"How to Create a Personalised Storybook for Your Child",description:"Create a personalised children's storybook in 5 easy steps with TalesBerry. Upload a photo, preview for free, and get a premium printed book delivered to your door.",step:[{"@type":"HowToStep",position:1,name:"Tell us about your child",text:"Share their name, gender, and one clear photo to get started."},{"@type":"HowToStep",position:2,name:"Instant sample preview",text:"Get a free preview of the first 4 pages to see the quality of the personalisation."},{"@type":"HowToStep",position:3,name:"Place Order to unlock full book",text:"Once you make a purchase, the full book is unlocked with options to regenerate page variants."},{"@type":"HowToStep",position:4,name:"Send for printing",text:"Review the complete book and send it for printing when you're fully satisfied."},{"@type":"HowToStep",position:5,name:"Delivered to your door",text:"Your storybook is printed on premium 220GSM glossy paper and shipped to your doorstep in about 7 business days."}]},p1=()=>e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"How to Create a Personalised Storybook | TalesBerry"}),e.jsx("meta",{name:"description",content:"Learn how to create a personalised children's storybook in 5 easy steps. Upload a photo, get a free preview, and receive a premium printed book at your doorstep."}),e.jsx("link",{rel:"canonical",href:"https://www.talesberry.com/how-it-works"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(m1)})]}),e.jsx(Nm,{standalone:!0})]}),g1=()=>{const r=window.location.pathname.startsWith("/sg"),{region:t}=ht(),s=r?"https://www.talesberry.com/sg":"https://www.talesberry.com/",a={"@context":"https://schema.org","@type":"FAQPage",mainEntity:Yn.map(i=>({"@type":"Question",name:i.question,acceptedAnswer:{"@type":"Answer",text:i.answer}}))},n={"@context":"https://schema.org","@type":"Organization",name:"TalesBerry",url:"https://www.talesberry.com",description:"TalesBerry creates personalised children's storybooks where your child becomes the hero of their own adventure.",sameAs:["https://www.instagram.com/talesberry","https://www.facebook.com/talesberry"]};return e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsx("title",{children:"Personalised Children's Books | TalesBerry"}),e.jsx("link",{rel:"canonical",href:s}),e.jsx("meta",{name:"description",content:"Create personalised children's storybooks with your child as the hero. A meaningful gift that builds reading habits and lasting memories."}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(a)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})]}),e.jsx(ew,{}),(t==="SG"||t==="US")&&e.jsx(_l,{}),e.jsx(aw,{}),e.jsx(Nm,{}),e.jsx(gj,{}),e.jsx(Cj,{}),e.jsx(d1,{}),e.jsx(h1,{}),e.jsx(Pj,{}),e.jsx(iw,{})]})},xt=({children:r})=>e.jsx("div",{className:"pt-20",children:r}),Xd=()=>e.jsxs(su,{children:[e.jsx(nt,{path:"/",element:e.jsx(g1,{})}),e.jsx(nt,{path:"/how-it-works",element:e.jsx(xt,{children:e.jsx(p1,{})})}),e.jsx(nt,{path:"/create",element:e.jsx(xt,{children:e.jsx(dw,{})})}),e.jsx(nt,{path:"/kids",element:e.jsx(xt,{children:e.jsx(c1,{})})}),e.jsx(nt,{path:"/books",element:e.jsx(xt,{children:e.jsx(pw,{})})}),e.jsx(nt,{path:"/books-for-parents",element:e.jsx(xt,{children:e.jsx(gw,{})})}),e.jsx(nt,{path:"/stickers",element:e.jsx(xt,{children:e.jsx(Bj,{})})}),e.jsx(nt,{path:"/stickers/:gender/personalize",element:e.jsx(xt,{children:e.jsx(Fj,{})})}),e.jsx(nt,{path:"/stickers/:gender/preview",element:e.jsx(xt,{children:e.jsx(Dj,{})})}),e.jsx(nt,{path:"/stickers/delivery",element:e.jsx(xt,{children:e.jsx(Gj,{})})}),e.jsx(nt,{path:"/custom-storybooks",element:e.jsx(xt,{children:e.jsx(n1,{})})}),e.jsx(nt,{path:"/story/:storyId",element:e.jsx(i1,{})}),e.jsx(nt,{path:"/storyhouse",element:e.jsx(xt,{children:e.jsx(o1,{})})}),e.jsx(nt,{path:"/books/:id",element:e.jsx(xt,{children:e.jsx(Nw,{})})}),e.jsx(nt,{path:"/books/:id/personalize",element:e.jsx(xt,{children:e.jsx(ej,{})})}),e.jsx(nt,{path:"/books/:id/preview",element:e.jsx(xt,{children:e.jsx(qd,{})})}),e.jsx(nt,{path:"/preview",element:e.jsx(qd,{})}),e.jsx(nt,{path:"/cart",element:e.jsx(xt,{children:e.jsx(tj,{})})}),e.jsx(nt,{path:"/print-options",element:e.jsx(xt,{children:e.jsx(nj,{})})}),e.jsx(nt,{path:"/delivery",element:e.jsx(xt,{children:e.jsx(aj,{})})}),e.jsx(nt,{path:"/checkout",element:e.jsx(xt,{children:e.jsx(oj,{})})}),e.jsx(nt,{path:"/payment-success",element:e.jsx(xt,{children:e.jsx(lj,{})})}),e.jsx(nt,{path:"/payment-failure",element:e.jsx(xt,{children:e.jsx(cj,{})})}),e.jsx(nt,{path:"/drafts",element:e.jsx(xt,{children:e.jsx(dj,{})})}),e.jsx(nt,{path:"/login",element:e.jsx(xt,{children:e.jsx(uj,{})})}),e.jsx(nt,{path:"/generate",element:e.jsx(xt,{children:e.jsx(hj,{})})}),e.jsx(nt,{path:"/faq",element:e.jsx(xt,{children:e.jsx(mj,{})})}),e.jsx(nt,{path:"/terms",element:e.jsx(xt,{children:e.jsx(pj,{})})}),e.jsx(nt,{path:"/policies/privacy-policy",element:e.jsx(xt,{children:e.jsx($j,{})})}),e.jsx(nt,{path:"/why-personalised-books",element:e.jsx(xt,{children:e.jsx(Lj,{})})}),e.jsx(nt,{path:"/personalised-books-as-gifts",element:e.jsx(xt,{children:e.jsx(Oj,{})})}),e.jsx(nt,{path:"/admin-login",element:e.jsx(Rj,{})}),e.jsx(nt,{path:"/analytics",element:e.jsx(xt,{children:e.jsx(Ij,{})})}),e.jsx(nt,{path:"*",element:e.jsx(xt,{children:e.jsx("div",{className:"text-center py-20",children:e.jsx("h1",{className:"text-2xl",children:"Page not found"})})})})]}),Cl=()=>{let r=localStorage.getItem("analytics_session_id");return r||(r=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,localStorage.setItem("analytics_session_id",r)),r},f1=async(r,t="general",s={})=>{try{const a=Cl(),n=window.location.pathname+window.location.search,{error:i}=await de.from("analytics_events").insert({event_name:r,event_category:t,session_id:a,page_url:n,metadata:s,book_id:s.book_id||null,book_name:s.book_name||null});if(i)throw i}catch(a){console.error("Analytics tracking error:",a)}},x1=async(r,t,s)=>{try{const a=Cl();await de.from("analytics_page_views").insert({session_id:a,page_url:r,page_title:t,referrer_url:s||document.referrer||null})}catch(a){console.error("Page view tracking error:",a)}},Qd=async(r,t={})=>{try{await f1(r,"button_click",t)}catch(s){console.error("Failed to track button click:",s)}},Eo=async(r,t)=>{try{const s=Cl();await de.from("analytics_funnel_steps").insert({session_id:s,step_name:r,step_order:t,completed:!0})}catch(s){console.error("Funnel tracking error:",s)}},y1=(r,t)=>r==="/"?{name:"Homepage_loaded",order:1}:r==="/personalize"||/^\/books\/[^/]+\/personalize$/.test(r)?{name:"Personalize_page_loaded",order:3}:r==="/preview"||/^\/books\/[^/]+\/preview$/.test(r)?t==="/payment-success"?{name:"Preview_redirected_Loaded",order:11}:{name:"Preview_page_loaded",order:6}:r==="/delivery"?{name:"DeliveryPage_loaded",order:8}:r==="/payment-success"?{name:"Payment_screen_loaded",order:10}:null,b1=()=>{const r=Jt(),t=p.useRef(Date.now()),s=p.useRef("");p.useEffect(()=>{const a=r.pathname;if(a.startsWith("/analytics")||a.startsWith("/admin"))return;const n=document.title||a;x1(a,n,s.current);const i=y1(a,s.current);return i&&Eo(i.name,i.order),t.current=Date.now(),s.current=a,()=>{}},[r.pathname])},eu={home_create_free_preview:{name:"Home_Create_Free_Preview",order:2},home_books_collection:{name:"Home_Books_Collection",order:2},home_create_free_preview_maincta:{name:"Home_Create_Free_Preview_mainCTA",order:2},mobile_personalize_modal_open:{name:"Mobile_Personalize_Modal_Open",order:3},mobile_modal_upload_image:{name:"Mobile_Modal_Upload_Image",order:4},mobile_modal_continue_to_details:{name:"Mobile_Modal_Continue_Details",order:4.5},mobile_modal_see_book_preview:{name:"Mobile_Modal_See_Book_Preview",order:5},personalize_choose_image:{name:"Personalize_Choose_Image",order:4},personalize_see_book_preview:{name:"Personalize_See_Book_Preview",order:5},preview_retry:{name:"Preview_Retry",order:7},preview_new_face_upload:{name:"Preview_New_Photo",order:7},place_order:{name:"Preview_Place_Order",order:7},preview_place_order:{name:"Preview_Place_Order",order:7},delivery_pay_now:{name:"DeliveryPage_PayNow",order:9},preview_ebook_pdf_download:{name:"Preview_redirected_ebook_pdf_download",order:12},preview_send_for_printing:{name:"Preview_redirected_send_for_printing",order:12}},v1=()=>{p.useEffect(()=>{const r=s=>{const a=window.location.pathname;if(a.startsWith("/analytics")||a.startsWith("/admin"))return;const n=s.target,i=n.closest("[data-track]")||n,o=i.getAttribute("data-track");if(o){const l={},c=i.getAttribute("data-book-id")||n.getAttribute("data-book-id"),u=i.getAttribute("data-book-name")||n.getAttribute("data-book-name");c&&(l.book_id=c),u&&(l.book_name=u),Qd(o,l);const d=eu[o.toLowerCase()];d&&Eo(d.name,d.order)}};document.addEventListener("click",r,!0);const t=s=>{const a=s.target;if(!a)return;const n=a.closest("[data-track]")||a,i=n.getAttribute("data-track");if(!i||i.toLowerCase()!=="preview_new_face_upload")return;const o={},l=n.getAttribute("data-book-id")||a.getAttribute("data-book-id"),c=n.getAttribute("data-book-name")||a.getAttribute("data-book-name");l&&(o.book_id=l),c&&(o.book_name=c),Qd(i,o);const u=eu[i.toLowerCase()];u&&Eo(u.name,u.order)};return document.addEventListener("change",t,!0),()=>{document.removeEventListener("click",r,!0),document.removeEventListener("change",t,!0)}},[])},w1=()=>e.jsxs("div",{className:"fixed inset-0 bg-background flex flex-col items-center justify-center z-50",children:[e.jsx("img",{src:"/talesberry-logo.png",alt:"Talesberry",className:"h-12 md:h-16 mb-6 animate-pulse"}),e.jsx("div",{className:"w-8 h-8 border-3 border-primary/30 border-t-primary rounded-full animate-spin"})]}),j1=()=>{const r=Jt(),t=_t(),s=r.pathname.replace(/^\/us/,"")||"/";return p.useEffect(()=>{t(`${s}${r.search}${r.hash}`,{replace:!0})},[s,r.search,r.hash,t]),null},N1=()=>{const r=Jt();return p.useEffect(()=>{window.scrollTo(0,0)},[r.pathname]),null},k1=()=>{const r=Jt(),t=`${r.pathname}${r.search}${r.hash}`;return p.useEffect(()=>{const s=window,a=Date.now(),n=s.__fbqLastPageView;(n==null?void 0:n.key)===t&&a-n.timestamp<1500||(s.__fbqLastPageView={key:t,timestamp:a},typeof window.fbq=="function"&&window.fbq("track","PageView"))},[t]),null},_1=()=>{const{isLoading:r}=ht();return r?e.jsx(w1,{}):e.jsxs("div",{className:"font-sans",children:[e.jsx(Jv,{}),e.jsx("main",{className:"overflow-x-hidden relative z-0",children:e.jsxs(su,{children:[e.jsx(nt,{path:"/*",element:e.jsx(Xd,{})}),e.jsx(nt,{path:"/sg/*",element:e.jsx(Xd,{})}),e.jsx(nt,{path:"/us/*",element:e.jsx(j1,{})})]})}),e.jsx(Zv,{})]})},S1=()=>(b1(),v1(),null);function C1(){return p.useEffect(()=>{const r=()=>{document.documentElement.style.setProperty("--vh",`${window.innerHeight*.01}px`)};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e.jsx(Zm,{children:e.jsx(Bm,{children:e.jsxs(zv,{children:[e.jsx(k1,{}),e.jsx(N1,{}),e.jsx(S1,{}),e.jsx(Xv,{}),e.jsx(_1,{})]})})})}const tu=window.localStorage.getItem("path");tu&&(window.localStorage.removeItem("path"),window.history.replaceState(null,"",tu));nu(document.getElementById("root")).render(e.jsx(p.StrictMode,{children:e.jsx(hu,{children:e.jsx(sj,{children:e.jsx(Bm,{children:e.jsx(C1,{})})})})}));