@chaibuilder/pages 0.10.13 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var Lr=Object.defineProperty;var Rn=e=>{throw TypeError(e)};var Br=(e,s,n)=>s in e?Lr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var et=(e,s,n)=>Br(e,typeof s!="symbol"?s+"":s,n),Gn=(e,s,n)=>s.has(e)||Rn("Cannot "+n);var te=(e,s,n)=>(Gn(e,s,"read from private field"),n?n.call(e):s.get(e)),fe=(e,s,n)=>s.has(e)?Rn("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),he=(e,s,n,a)=>(Gn(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),f=require("lodash-es"),x=require("react"),pe=require("jotai"),U=require("@tanstack/react-query"),W=require("sonner"),$=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),ut=require("date-fns"),S=require("lucide-react"),Mr=require("compressorjs"),Ws=require("react-diff-view"),ca=require("@chaibuilder/runtime"),ws=require("zod"),Or=require("react-dropzone"),Rr=require("@chaibuilder/sdk/web-blocks");function Gr(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const be=Gr(x),Se={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},R={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_REVISION_DATA:"GET_REVISION_DATA",GET_PAGE_DATA:"GET_PAGE_DATA",GET_COMPARE_DATA:"GET_COMPARE_DATA",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"};let Fr=0;function Fn(e,s){const n=`atom${++Fr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Ur,a.write=qr),s&&(a.write=s),a}function Ur(e){return e(this)}function qr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const $r=Symbol(""),zr=e=>typeof(e==null?void 0:e.then)=="function";function Vr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,h)=>{var d,m;const j=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return h}a=p}return r},y=(m=(d=e())==null?void 0:d.getItem(u))!=null?m:null;return zr(y)?y.then(j):j(y)},setItem:(u,h)=>{var d;return(d=e())==null?void 0:d.setItem(u,JSON.stringify(h,void 0))},removeItem:u=>{var h;return(h=e())==null?void 0:h.removeItem(u)}},l=u=>(h,d,m)=>u(h,j=>{let y;try{y=JSON.parse(j||"")}catch{y=m}d(y)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,h)=>{if(!(e()instanceof window.Storage))return()=>{};const d=m=>{m.storageArea===e()&&m.key===u&&h(m.newValue)};return window.addEventListener("storage",d),()=>{window.removeEventListener("storage",d)}}),o&&(i.subscribe=l(o)),i}const Kr=Vr();function ua(e,s,n=Kr,a){const r=Fn(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Fn(l=>l(r),(l,o,u)=>{const h=typeof u=="function"?u(l(r)):u;return h===$r?(o(r,s),n.removeItem(e)):h instanceof Promise?h.then(d=>(o(r,d),n.setItem(e,d))):(o(r,h),n.setItem(e,h))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const da="__logged_in_user",Hr=ua(da,null),Oe=()=>{const[e,s]=pe.useAtom(Hr),n=x.useCallback(()=>{s(null),localStorage.removeItem(da)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},pn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)});let gt=null;function Qr(){const{user:e,setUser:s,logout:n}=Oe(),a=Ms(),r=qe("getAccessToken",!1),i=async()=>{if(r===!1&&e&&!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken")))try{const l=await pn(a,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!l.ok){n(),window.location.reload();return}const o=await l.json();if(f.has(o,"id")&&f.has(o,"email")&&f.has(o,"accessToken")&&f.has(o,"refreshToken"))return s(o),o;n(),window.location.reload()}catch{n(),window.location.reload()}};return U.useMutation({mutationFn:async()=>{if(gt)return await gt;gt=i();try{return await gt}finally{gt=null}},onSuccess:()=>{}})}function Wr(){return gt}const ha=()=>{const{user:e,setUser:s}=Oe(),{mutateAsync:n}=Qr(),a=60,r=x.useCallback(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const o=Math.floor(Date.now()/1e3);return e.expiresAt-o<=a},[e]),l=qe("getAccessToken",async()=>{if(!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken"))){if(r()){const o=Wr();if(o){const h=await o;return h&&s(h),(h==null?void 0:h.accessToken)||""}const u=await n();return u&&s(u),(u==null?void 0:u.accessToken)||""}return(e==null?void 0:e.accessToken)||""}});return{getAccessToken:x.useCallback(async()=>{try{return await l()}catch{return""}},[l])}},Z=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ha();return x.useCallback(async(n,a,r={})=>{const i=await s();if(!i)return null;try{const l=f.get(a,"action","").toLowerCase(),o=await pn(n+(l?`?action=${l}`:""),a,{...r,Authorization:`Bearer ${i}`});if(o.status===401)return console.log("401 Response",o),e(),window.location.reload(),null;if(!o.ok){const u=await o.json();throw console.error(`API Error (${o.status}):`,u),{status:o.status,statusText:o.statusText,...u,message:u.error||u.message||`Server error: ${o.status}`}}return await o.json()}catch(l){throw console.error("API request failed:",a,l),l}},[e,s])},ma=()=>{const e=oe(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[R.GET_DRAFT_PAGE]})}})},fa=()=>{const e=oe(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[R.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||W.toast.success("Website settings updated successfully.")},onError:a=>{W.toast.error("Failed to update website settings",{description:a.message})}})},Jr=()=>{const e=oe(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[R.GET_WEBSITE_DATA]}),W.toast.success("Website data updated successfully.")},onError:a=>{W.toast.error("Failed to update website data",{description:a.message})}})};function Pe(){const[e,s]=x.useState(new URLSearchParams(window.location.search));return x.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Yr=pe.atom({}),xa=()=>pe.useAtom(Yr),Xr=()=>{const[e]=Pe(),s=e.get("page"),n=x.useRef(""),{mutate:a}=ma();x.useEffect(()=>{!f.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},qe=(e,s)=>{const[n]=xa();return x.useMemo(()=>f.get(n,e,s),[n,e,s])},oe=()=>qe("apiUrl","/chai/api"),Ms=()=>qe("usersApiUrl","/chai/users"),cs=()=>qe("assetsApiUrl","/chai/assets"),Zr=()=>qe("supabaseInstance",null),Ue=e=>{const s=oe(),[n]=Pe(),a=e??n.get("page"),r=Z();return U.useQuery({queryKey:[R.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:R.GET_LANGUAGE_PAGES,data:{id:a}});return f.reverse(f.sortBy(i,"primaryPage"))},enabled:!!a})},Ve=()=>{const e=oe(),s=Z();return U.useQuery({queryKey:[R.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:R.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},ga=e=>{const{fallbackLang:s}=$.useLanguages(),{data:n}=Ve(),{data:a,isFetching:r}=Ue(),i=x.useMemo(()=>{const l={[s]:!0};return f.each(f.get(n,"languages"),o=>{const u=f.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||f.isEmpty(e)||e&&i[e]},yn=()=>{const e=U.useQueryClient(),{data:s}=U.useQuery({queryKey:[R.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:x.useCallback(a=>{e.setQueryData([R.AI_CONTEXT],a)},[e]),aiContext:s}},ei=pe.atom(null),pa=()=>pe.useAtom(ei),jn=()=>{const[e]=pa();return(e==null?void 0:e.slug)||""};function ti(e,s){const[n,a]=x.useState(e);return x.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const si=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=$.useLanguages(),{data:r}=ke(),i=r==null?void 0:r.pageType,l=oe(),o=Z(),{data:u,isFetching:h}=U.useQuery({queryKey:[R.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await o(l,{action:R.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),d=x.useMemo(()=>n===""?u.filter(m=>m.lang===""||m.lang===a):u.filter(m=>m.lang===n),[n,a,u]);return{allLangPages:u,data:d,isFetching:h}},ya=()=>{const{selectedLang:e,fallbackLang:s}=$.useLanguages(),[n,a]=pa(),[r,i]=x.useState(""),l=ti(r,500),{allLangPages:o,data:u,isFetching:h}=si({query:l}),d=x.useCallback(y=>a(y),[a]),m=x.useCallback(y=>i(y),[i]),j=x.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),p=e.length===0,g=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,w=o.filter(E=>(E==null?void 0:E.primaryPage)===g||E.id===g).find(E=>p?E.lang===e||E.lang===s:E.lang===e);a(w||n)},[n,e,o,a,s]);return{isPending:h,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:o,updateDynamicPage:d,updateSearchQuery:m,onChangeLanguage:j}},We=()=>{const{data:e}=Ve();return x.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},dt=()=>{const e=Z(),s=oe();return U.useQuery({queryKey:[R.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:R.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},ni=e=>{const s=Z(),n=oe(),a=We();return U.useQuery({queryKey:[R.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:R.GET_WEBSITE_PAGES,data:{lang:e}})||[];return f.keyBy(f.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})},ai=pe.atom({lastSaved:void 0}),Os=()=>pe.useAtom(ai),ke=()=>{const[e]=Pe(),s=e.get("page"),[n]=ja(),{data:a,isFetching:r}=dt();return{data:x.useMemo(()=>({...f.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},Je=()=>{const[e]=Pe(),s=e.get("lang")??"",{data:n,isFetching:a}=Ue();return{data:x.useMemo(()=>f.find(n,{lang:s})||{},[n,s]),isFetching:a}},ri=pe.atom({}),ja=()=>pe.useAtom(ri),va=()=>{const{data:e}=Je(),s=jn(),n=e==null?void 0:e.slug,a=n?window.location.origin+(n.endsWith("/")?n.slice(0,-1):n):window.location.origin;return s?a+s:a};class ba{constructor(s,n,a,r){et(this,"channelId");et(this,"supabase");et(this,"channel",null);et(this,"userId",null);et(this,"clientId",null);et(this,"pageId",null);et(this,"callback");var i,l,o,u,h,d;this.userId=a,this.supabase=s,this.clientId=this.getClientId(),this.channelId=`WEBSITE:${n}`,this.callback=r,this.channel=this.supabase.channel(this.channelId,{config:{presence:{key:this.clientId}}}),(d=(h=(u=(o=(l=(i=this.channel)==null?void 0:i.on("presence",{event:"sync"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:l.on("presence",{event:"leave"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:o.on("presence",{event:"join"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:u.on("broadcast",{event:"TAKE_OVER_REQUESTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUESTED",m)))==null?void 0:h.on("broadcast",{event:"TAKE_OVER_REQUEST_ACCEPTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUEST_ACCEPTED",m)))==null||d.on("broadcast",{event:"TAKE_OVER_REQUEST_REJECTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUEST_REJECTED",m)).subscribe()}getClientId(){return crypto.randomUUID()}getOnlineUsers({pageId:s,userId:n}){var i;const a=(i=this.channel)==null?void 0:i.presenceState();let r=Object.values(a||{}).map(l=>l[0]).filter(Boolean);return s?r=r.filter(l=>l.pageId===s):n&&(r=r.filter(l=>l.userId===n)),r.sort((l,o)=>l.onlineAt-o.onlineAt)}getPageOwner(){const s=this.getOnlineUsers({pageId:this.pageId});return s.length>0?s[0]:null}getPageUserMapping(){const s=this.getOnlineUsers({}),n=f.groupBy(s,"pageId"),a={};return Object.keys(n).forEach(r=>{var l;const i=(l=f.minBy(n[r],"onlineAt"))==null?void 0:l.userId;i!==this.userId&&(a[r]=i)}),a}onReceiveEvent(s,n){if(!this.pageId)return;const a=this.getPageOwner();if(!a||a.clientId===this.clientId?this.callback("USER_JOINED",{isActiveInOtherTab:!1}):this.callback("PAGE_LOCKED",{isActiveInOtherTab:(a==null?void 0:a.userId)===this.userId&&(a==null?void 0:a.clientId)!==this.clientId}),n.targetClientId===this.clientId)switch(s){case"TAKE_OVER_REQUESTED":this.callback("TAKE_OVER_REQUESTED",{requestedBy:n==null?void 0:n.userId,requestingClientId:n==null?void 0:n.senderClientId,isRequestedFromAnotherTab:(n==null?void 0:n.senderClientId)!==this.clientId&&(n==null?void 0:n.userId)===this.userId});break;case"TAKE_OVER_REQUEST_ACCEPTED":this.channel.track({pageId:this.pageId,userId:this.userId,clientId:this.clientId,onlineAt:a?a.onlineAt-10:+new Date}),this.callback("TAKE_OVER_REQUEST_ACCEPTED",{isTakingOverFromAnotherTab:(n==null?void 0:n.senderClientId)!==this.clientId&&(n==null?void 0:n.userId)===this.userId});break;case"TAKE_OVER_REQUEST_REJECTED":this.callback("TAKE_OVER_REQUEST_REJECTED");break}}async joinPage(s){var n;this.pageId=s,(n=this.channel)==null||n.track({pageId:this.pageId,userId:this.userId,clientId:this.clientId,onlineAt:+new Date})}async leavePage(){var s;this.channel&&((s=this.channel)==null||s.untrack())}async sendEvent(s,n){var a,r;if(this.channel){const i={pageId:this.pageId,userId:this.userId,senderClientId:this.clientId};s==="TAKE_OVER_REQUESTED"?i.targetClientId=(a=this.getPageOwner())==null?void 0:a.clientId:(s==="TAKE_OVER_REQUEST_ACCEPTED"||s==="TAKE_OVER_REQUEST_REJECTED")&&(i.targetClientId=n==null?void 0:n.requestingClientId),await((r=this.channel)==null?void 0:r.send({event:s,payload:i,type:"broadcast"}))}}}const Ke=e=>{const s=Ms(),n=Z();return U.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:R.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!f.isEmpty(e)})},ii=pe.atom(void 0),li=pe.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),oi=pe.atom(""),ci=pe.atom(null),vn=pe.atom({}),wa=()=>pe.useAtom(vn),Ye=()=>{const[e]=Pe(),s=e.get("page"),{user:n}=Oe(),[a,r]=pe.useAtom(ii),[i,l]=pe.useAtom(li),[o,u]=pe.useAtom(ci),[h,d]=pe.useAtom(oi),[m]=pe.useAtom(vn);return x.useMemo(()=>({pageLock:i,pageToUser:m,lockingStatus:h,realtimeInstance:o,setPageLock:l,setCurrentEditor:r,setLockingStatus:d,setRealtimeInstance:u,realtimePageLockEnabled:!!o,currentEditor:o?m[s||""]:a,isLocked:o?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a}),[s,n==null?void 0:n.id,i,h,a,o,l,r,d,u,m])},ui=()=>{const e=Zr(),{data:s}=ke(),{user:n}=Oe(),a=s==null?void 0:s.id,{data:r}=Ve(),{pageLock:i,setPageLock:l,setLockingStatus:o,realtimeInstance:u,setRealtimeInstance:h}=Ye(),[,d]=pe.useAtom(vn),m=x.useRef(!1),j=x.useRef(i),y=x.useRef(!1);return x.useEffect(()=>{if(n!=null&&n.id&&e&&!u&&(r!=null&&r.appKey)&&!y.current){y.current=!0;const p=async(v,w)=>{var E,P;switch(v){case"UPDATE_ONLINE_USERS":d((w==null?void 0:w.pageToUser)||{});break;case"PAGE_LOCKED":l({...j==null?void 0:j.current,requestedBy:"",status:"locked",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"USER_JOINED":if(((E=j==null?void 0:j.current)==null?void 0:E.status)==="editing")return;((P=j==null?void 0:j.current)==null?void 0:P.status)==="locked"&&o("can_edit_now"),l({...j==null?void 0:j.current,requestedBy:"",status:"editing",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":l({...j==null?void 0:j.current,requestingClientId:w==null?void 0:w.requestingClientId,requestedBy:w!=null&&w.isRequestedFromAnotherTab?"ANOTHER_TAB":w==null?void 0:w.requestedBy});break;case"TAKE_OVER_REQUEST_ACCEPTED":w!=null&&w.isTakingOverFromAnotherTab||(o("take_over_request_accepted"),W.toast.success("Your Page Take Over Request Accepted",{position:"top-center"})),l({...j==null?void 0:j.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":o("take_over_request_rejected"),l({...j==null?void 0:j.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},g=new ba(e,r==null?void 0:r.appKey,n==null?void 0:n.id,p);h(g)}},[h,e,r==null?void 0:r.appKey]),x.useEffect(()=>{j.current=i},[i]),x.useEffect(()=>{if(!(!u||!a||!(n!=null&&n.id)||m.current))return m.current=!0,u==null||u.joinPage(a),()=>{u&&m.current&&(m.current=!1,j.current={requestedBy:"",status:"checking",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1},o(""),l(j.current),u==null||u.leavePage())}},[a,u]),i==null?void 0:i.status},Sa=()=>{const{data:e}=ke(),{user:s}=Oe(),n=e==null?void 0:e.id,{pageLock:a,setPageLock:r,realtimeInstance:i}=Ye(),{savePageAsync:l}=$.useSavePage(),o=x.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(r({...a,isTakeOverRequested:!0}),i==null||i.sendEvent("TAKE_OVER_REQUESTED"))},[i,n,s==null?void 0:s.id,r,a]),u=x.useCallback(async()=>{!i||!n||!(s!=null&&s.id)||(await l(),i==null||i.sendEvent("TAKE_OVER_REQUEST_ACCEPTED",{requestingClientId:a==null?void 0:a.requestingClientId}),r({requestedBy:"",status:"locked",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1}))},[n,i,s==null?void 0:s.id,r,l,a]),h=x.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(i==null||i.sendEvent("TAKE_OVER_REQUEST_REJECTED",{requestingClientId:a==null?void 0:a.requestingClientId}),r({...a,requestedBy:"",status:"editing",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1}))},[n,i,s==null?void 0:s.id,r,a]);return{pageLock:a,acceptTakeOver:u,rejectTakeOver:h,requestTakeOver:o}},Na=()=>{const[e]=Pe(),s=e.get("page"),n=oe(),{setAiContext:a}=yn(),{setCurrentEditor:r}=Ye(),[,i]=Os(),[,l]=ja(),o=Z();return U.useQuery({queryKey:[R.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await o(n,{action:R.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const h=u.blocks??[],d=f.find(h,{_type:"@chai/ai-context"});return a(f.get(d,"_value","")||""),i(m=>({...m,lastSaved:u.lastSaved})),l(f.get(u,"metadata",{})),h},enabled:!!s})},bn=()=>{const{data:e}=ke(),{data:s}=Je(),n=oe(),a=Z(),r=We(),i=jn();return U.useQuery({queryKey:[R.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:R.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})},us=({children:e})=>t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen flex-col items-center justify-center bg-black/20",children:e}),Ea=({fullScreen:e=!0})=>{const s=t.jsxs("div",{className:"flex flex-row gap-2",children:[t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-purple-500"}),t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-cyan-500 [animation-delay:-.3s]"}),t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-pink-500 [animation-delay:-.5s]"})]});return e?t.jsx(us,{children:s}):t.jsx("div",{className:"flex h-full w-full items-center justify-center",children:s})},di=({currentEditor:e})=>{const{user:s}=Oe(),{data:n}=Ke(e);return!n||!e||e===(s==null?void 0:s.id)?null:t.jsx("span",{className:"ml-2 flex items-center gap-1 text-xs font-light text-gray-500",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(S.LockIcon,{className:"h-3 w-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},hi=({userId:e})=>{const{data:s}=Ke(e);return(s==null?void 0:s.name)||"Unknown"};function mi({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,realtimePageLockEnabled:i,isRequestRejected:l,isFetchingUserInfo:o}){const[u,h]=x.useState(!1),[d,m]=x.useState(!1),j=()=>{h(!0),setTimeout(()=>{h(!1)},15e3),m(!1),r()};return t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl",children:[t.jsx(S.LockKeyhole,{className:"h-8 w-8 rounded-md bg-sky-500/20 p-1.5 text-sky-500"}),"Page is locked for editing"]})}),t.jsx(c.CardContent,{className:"w-md grid w-full pt-2",children:t.jsxs("div",{children:[t.jsxs("div",{className:"relative mx-auto flex w-96 items-center space-x-4 rounded-md border border-green-500 px-2 pb-2 pt-4",children:[t.jsx("div",{className:"absolute -top-2.5 left-3 w-max rounded-full bg-green-500 px-3 py-1 text-xs font-medium leading-3 text-white",children:"Locked By"}),e&&!o?t.jsx("img",{src:e,alt:s,className:"h-14 w-14 rounded-full border border-gray-300"}):t.jsx(S.UserIcon,{className:"h-14 w-14 flex-shrink-0 rounded-full bg-gradient-to-br from-purple-400 to-pink-500 p-2 text-white"}),t.jsxs("div",{className:o?"space-y-1.5":"space-y-0",children:[o?t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"}):t.jsx("span",{className:"truncate font-medium text-black",children:s}),n&&!o?t.jsx("p",{className:"truncate text-sm text-muted-foreground",children:n}):t.jsx(c.Skeleton,{className:"h-4 w-60 rounded"}),a&&!o?t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",ut.formatDistanceToNow(new Date(a),{addSuffix:!0})]}):t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{className:"py-4 text-center text-gray-600",children:["This page is currently being edited by ",t.jsx("span",{className:"font-bold",children:s}),".",t.jsx("br",{}),i&&t.jsxs(t.Fragment,{children:[" ",t.jsx("br",{})," You can either wait until they finish editing or"," ",i?"request to":""," take over the page."]})]})}),l&&t.jsxs("div",{className:"mt-4 flex w-full items-center justify-center gap-x-2 rounded border border-red-500 bg-red-50 p-2 text-center font-medium text-red-500",children:[t.jsx(S.Info,{className:"h-5 w-5"})," Page take over request is rejected"]})]})}),t.jsx(c.CardFooter,{children:i?t.jsxs(c.Button,{disabled:u,onClick:j,className:"w-full",variant:"destructive",children:[t.jsx(S.KeyIcon,{className:"h-5 w-5"}),u?"Page take is requested.":l?"Request take over again":"Request take over"]}):t.jsxs(c.AlertDialog,{open:d,onOpenChange:m,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(S.AlertTriangleIcon,{className:"h-5 w-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:j,children:"Yes, Take Over"})]})]})]})})]})})}const ys=({isChecking:e,lockingStatus:s,onContinue:n})=>{const[a,r]=x.useState(!1),i=s==="page_is_active_in_other_tab",l=(s==null?void 0:s.length)>0,{pageLock:o,acceptTakeOver:u,rejectTakeOver:h}=Sa(),d=()=>{r(!0),l||i?n():u(),setTimeout(()=>{r(!1)},3e3)};return x.useEffect(()=>{(o==null?void 0:o.requestedBy)==="ANOTHER_TAB"&&u()},[o,u]),(o==null?void 0:o.requestedBy)==="ANOTHER_TAB"?null:e?t.jsx(Ea,{}):t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl font-medium",children:[a?t.jsx(S.Loader,{className:"h-6 w-6 animate-spin text-gray-500"}):i?t.jsx(S.TableIcon,{className:"h-6 w-6 text-green-500"}):l?t.jsx(S.CheckCircle,{className:"h-6 w-6 text-green-500"}):t.jsx(S.Target,{className:"h-6 w-6 text-green-500"}),i?"Page is active in other tab":l?"You can edit the page now.":"Page take over request"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:i?t.jsx("p",{children:'You are already editing this page in another tab. To continue editing here, click on "Continue editing here".'}):l?t.jsx("p",{children:"This page is released by other user you can continue editing now."}):t.jsxs("p",{children:[t.jsxs("b",{children:[" ",t.jsx(hi,{userId:o==null?void 0:o.requestedBy})]})," ","has requested to take over this page.",t.jsx("br",{})," If you accept, your unsaved changes will be saved."]})})}),t.jsxs(c.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(c.Button,{disabled:a,onClick:d,className:l?"":"bg-green-500 hover:bg-green-600",children:i?t.jsxs(t.Fragment,{children:[t.jsx(S.Edit,{className:"h-5 w-5"})," Continue editing here"]}):l?t.jsxs(t.Fragment,{children:[t.jsx(S.Edit,{className:"h-5 w-5"})," Continue to edit"]}):t.jsxs(t.Fragment,{children:[t.jsx(S.Check,{className:"h-5 w-5"})," Accept"]})}),!l&&t.jsxs(c.Button,{variant:"outline",onClick:h,children:[t.jsx(S.X,{className:"h-5 w-5"})," Reject"]})]})]})})},fi=()=>{const{pageLock:e,requestTakeOver:s}=Sa(),{isLocked:n,currentEditor:a,lockingStatus:r,setLockingStatus:i,realtimePageLockEnabled:l}=Ye(),{data:o,isFetching:u}=Ke(a),[h]=Pe(),d=h.get("page"),{mutate:m}=ma(),{isFetching:j}=Na(),[y]=Os(),p=U.useQueryClient(),g=x.useCallback(()=>{l?s():m({id:d})},[d,m,s,l]);return d?l&&(e==null?void 0:e.status)==="checking"?t.jsx(ys,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):l&&(e!=null&&e.requestedBy)?t.jsx(ys,{lockingStatus:"",onContinue:()=>{}}):(l?e.status!=="locked":!n||j)?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(ys,{lockingStatus:r,onContinue:()=>{p.invalidateQueries({queryKey:[R.GET_DRAFT_PAGE]}),i("")}}):null:l&&(e!=null&&e.isActiveInOtherTab)?t.jsx(ys,{lockingStatus:"page_is_active_in_other_tab",onContinue:s}):t.jsx(mi,{...o,isFetchingUserInfo:u,name:(o==null?void 0:o.name)||"Unknown User",email:(o==null?void 0:o.email)||"",lastSaved:(y==null?void 0:y.lastSaved)||"",onTakeOver:g,realtimePageLockEnabled:l,isRequestRejected:r==="take_over_request_rejected"}):null},xi=()=>{const[e,s]=Pe(),n=e.get("lang"),a=ga(n),{setSelectedLang:r}=$.useLanguages(),i=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),h=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",h),s(o),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=f.get(Se,n);return t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(S.LockIcon,{className:"h-6 w-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(c.CardFooter,{children:t.jsx(c.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},gi=e=>{const s=oe(),n=Z();return U.useMutation({mutationFn:async a=>n(s,{action:R.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),W.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},pi=e=>{const s=oe(),n=Z();return U.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:R.GET_LIBRARY_ITEM,data:{id:e}})}catch(a){throw console.error(a),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},yi=e=>{const s=oe(),n=Z();return U.useMutation({mutationFn:async a=>n(s,{action:R.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),W.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},ji=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=x.useState(!1),u=$.useUpdateBlocksPropsRealtime(),h=yi(()=>{u([e],{_libBlockId:void 0}),W.toast.success("Block deleted successfully"),o(!1),a()}),d=()=>{o(!0),h.mutate(s)},m=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:j=>j.preventDefault(),disabled:l,children:[t.jsx(S.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:j=>!j&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:i||m}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:d,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},vi=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=x.useState(!1);return t.jsx(ji,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{o(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>o(!0),children:[t.jsx(S.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},bi=()=>{const e=oe(),s=Z(),n=U.useQueryClient(),{data:a=[],isLoading:r,error:i}=U.useQuery({queryKey:["library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:o}=U.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return s(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:["library-groups"]}),W.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),W.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:o}},wi=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),[r,i]=x.useState(""),l=x.useRef(null),{groups:o}=bi(),[u,h]=x.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),d=x.useMemo(()=>[...o,...u.filter(y=>!o.some(p=>p.id===y.id))],[o,u]),m=()=>{const y=r.trim();if(!y)return;const p={id:y,name:y};h(g=>[...g,p]),s(p.id),i(""),a(!1)};x.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const j=y=>{y.key==="Enter"&&(y.preventDefault(),m())};return x.useEffect(()=>{e&&!d.some(y=>y.id===e)&&s("")},[e,d,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:j}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:m,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!o.some(p=>p.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(S.Plus,{className:"h-4 w-4"})})]})},Js=3*1024*1024;function nn(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function Ca(e){return new Promise((s,n)=>{if(e.size<=Js){s(e);return}new Mr(e,{quality:.8,maxWidth:2048,maxHeight:2048,convertSize:Js,success(a){s(a)},error(a){W.toast.error(`Failed to compress image. Image size is ${nn(e.size)}, which exceeds the maximum allowed size of ${nn(Js)}.`),n(a)}})})}const Si=10*1024*1024,Ni=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),r=x.useRef(null),i=x.useCallback(async u=>{var d;const h=(d=u.target.files)==null?void 0:d[0];if(h){if(h.size>Si){W.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(h.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);let m=h;h.type.startsWith("image/")&&(m=await Ca(h));const j=new FileReader;j.onloadend=()=>{s(j.result),a(!1)},j.readAsDataURL(m)}catch(m){console.error("Error reading file:",m),a(!1),W.toast.error("Failed to process image",{description:m instanceof Error?m.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},o=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(S.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(S.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"aspect-video h-[200px] max-h-[200px] overflow-hidden rounded-md border",children:t.jsx("img",{src:e,alt:"Preview",className:"h-full w-full object-contain"})})]})},ve={...$.PERMISSIONS,ADD_PAGE:"add_page",EDIT_PAGE:"edit_page",EDIT_SLUG:"edit_slug",DELETE_PAGE:"delete_page",CHANGE_PAGE_TYPE:"change_page_type",PUBLISH_PAGE:"publish_page",UNPUBLISH_PAGE:"unpublish_page",MARK_AS_TEMPLATE:"mark_as_template",UNMARK_AS_TEMPLATE:"unmark_as_template",ADD_PARTIAL:"add_partial",EDIT_PARTIAL:"edit_partial",DELETE_PARTIAL:"delete_partial",PUBLISH_PARTIAL:"publish_partial",UNPUBLISH_PARTIAL:"unpublish_partial",EDIT_SEO:"edit_seo",RESTORE_REVISION:"restore_revision",DELETE_REVISION:"delete_revision",PUBLISH_THEME:"publish_theme",EDIT_SETTINGS:"edit_settings",ADD_LIBRARY_BLOCK:"create_library_block",ADD_LIBRARY_TEMPLATE:"add_library_template",EDIT_LIBRARY_BLOCK:"edit_library_block",EDIT_LIBRARY_TEMPLATE:"edit_library_template",DELETE_LIBRARY_BLOCK:"delete_library_block",DELETE_LIBRARY_TEMPLATE:"delete_library_template",ADD_MEDIA:"add_media",EDIT_MEDIA:"edit_media",DELETE_MEDIA:"delete_media"},Ei=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=$.usePartailBlocksStore(),i=s.find(C=>C._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=x.useMemo(()=>s.some(C=>C._type==="PartialBlock"||C._type==="GlobalBlock"),[s]),h=x.useMemo(()=>{let C=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let T=r(M.partialBlockId);M._parent&&(T==null?void 0:T.length)>0&&(T=T.map(B=>(f.isEmpty(B._parent)&&f.set(B,"_parent",M._parent),B))),C=[...C,...T]}else C.push(M);return C},[s,r]),[d,m]=x.useState(""),[j,y]=x.useState(""),[p,g]=x.useState(""),[v,w]=x.useState(""),[E,P]=x.useState({}),[D,A]=x.useState(!1),[I,O]=x.useState(o),[Y,ee]=x.useState(!1),{hasPermission:L}=$.usePermissions(),q=L(ve.DELETE_LIBRARY_BLOCK),F=$.useUpdateBlocksPropsRealtime(),z=()=>{F([a],{_libBlockId:void 0}),W.toast.success("Block delinked from library"),n()},{data:G,isLoading:Q,isError:ae}=pi(l);x.useEffect(()=>{ae&&o&&(ee(!0),O(!1))},[ae,o]),x.useEffect(()=>{G&&!Q&&(m(G.name||""),y(G.group||""),g(G.description||""),w(G.preview||""),O(!1))},[G,Q]),x.useEffect(()=>{const C=d.trim().length>=2,M=j.trim()!=="";A(C&&M)},[d,j]);const je=()=>{const C={};return d.trim()?d.length<2&&(C.name="Name must be at least 2 characters"):C.name="Name is required",j||(C.group="Group is required"),P(C),Object.keys(C).length===0},{resetLibrary:Ne}=$.useLibraryBlocks({id:""}),ce=gi(C=>{o||F([a],{_libBlockId:C.id}),W.toast.success(`Block ${o?"updated":"saved"} successfully`),Ne(C.library),n()}),N=async C=>{if(C.preventDefault(),!je())return;const M=h.map(T=>(f.has(T,"_libBlockId")&&delete T._libBlockId,T));ce.mutate({name:d.trim(),group:j,blocks:M,description:p.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...o?{id:l}:{}})},b=ce.isPending;return I||Q?t.jsx("div",{className:"flex items-center justify-center p-8",children:t.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):Y?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:z,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(S.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:N,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:E.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:d,onChange:C=>m(C.target.value),className:E.name?"border-destructive":""}),E.name&&t.jsx("p",{className:"text-xs text-destructive",children:E.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:E.group?"text-destructive":"",children:"Group"}),t.jsx(wi,{value:j,onChange:y}),E.group&&t.jsx("p",{className:"text-xs text-destructive",children:E.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:C=>g(C.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Ni,{value:v,onChange:w})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&q&&t.jsx(vi,{blockId:a,libBlockId:l,blockName:d,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:b,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:b||!D,children:b?"Saving...":o?"Update Block":"Save Block"})]})]})]})},le={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},Ci={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ce=()=>{const e=oe(),s=Z();return U.useQuery({queryKey:[R.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:R.GET_PAGE_TYPES})})},Ta=e=>{const{data:s}=Ce();return x.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Ti=()=>{const e=oe(),s=Z();return U.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:R.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Aa=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>await n(e,{action:R.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=f.find(a,{key:i.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";W.toast.success(l)},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:f.get(Ci,r.message,r.message)})}})},wn=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Je(),{data:r}=Ce();return U.useMutation({mutationFn:async i=>await n(e,{action:R.UPDATE_PAGE,data:i}),onSuccess:(i,l)=>{(a==null?void 0:a.id)===(l==null?void 0:l.id)&&s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES]}),l&&(l!=null&&l.primaryPage||l!=null&&l.seo)?(s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,l==null?void 0:l.primaryPage]}),s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})},onError:(i,l)=>{const o=f.find(r,{key:l.pageType});W.toast.error(`Failed to update ${o!=null&&o.hasSlug?"page":o.name}.`,{description:i.message})}})},Ai=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:R.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){W.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},ki=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:R.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]});const l=f.find(a,{key:i.pageType});W.toast.success(l!=null&&l.hasSlug?le.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Sn=()=>{const e=oe(),s=Z(),n=U.useQueryClient(),{data:a}=ke(),{savePageAsync:r}=$.useSavePage();return U.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:R.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[R.GET_CHANGES]}),n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),W.toast.error("Failed to publish pages.")}})},Pi=()=>{const e=oe(),s=Z(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>{var r;return s(e,{action:R.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),W.toast.success("Page marked as template successfully.")},onError:()=>{W.toast.error("Failed to mark page as template.")}})},Ii=()=>{const e=oe(),s=Z(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>s(e,{action:R.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),W.toast.success("Page unmarked as template successfully.")},onError:()=>{W.toast.error("Failed to unmark page as template.")}})},_i=()=>{const e=oe(),s=Z(),n=U.useQueryClient();return U.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:R.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{W.toast.success(le.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})},onError:()=>{W.toast.error("Failed to change slug")}})};var Nn={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!s.OffscreenCanvas)return!1;var N=new OffscreenCanvas(1,1),b=N.getContext("2d");b.fillRect(0,0,1,1);var C=N.transferToImageBitmap();try{b.createPattern(C,"no-repeat")}catch{return!1}return!0}();function u(){}function h(N){var b=n.exports.Promise,C=b!==void 0?b:s.Promise;return typeof C=="function"?new C(N):(N(u,u),null)}var d=function(N,b){return{transform:function(C){if(N)return C;if(b.has(C))return b.get(C);var M=new OffscreenCanvas(C.width,C.height),T=M.getContext("2d");return T.drawImage(C,0,0),b.set(C,M),M},clear:function(){b.clear()}}}(o,new Map),m=function(){var N=Math.floor(16.666666666666668),b,C,M={},T=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(b=function(B){var H=Math.random();return M[H]=requestAnimationFrame(function V(J){T===J||T+N-1<J?(T=J,delete M[H],B()):M[H]=requestAnimationFrame(V)}),H},C=function(B){M[B]&&cancelAnimationFrame(M[B])}):(b=function(B){return setTimeout(B,N)},C=function(B){return clearTimeout(B)}),{frame:b,cancel:C}}(),j=function(){var N,b,C={};function M(T){function B(H,V){T.postMessage({options:H||{},callback:V})}T.init=function(V){var J=V.transferControlToOffscreen();T.postMessage({canvas:J},[J])},T.fire=function(V,J,re){if(b)return B(V,null),b;var K=Math.random().toString(36).slice(2);return b=h(function(ie){function me(xe){xe.data.callback===K&&(delete C[K],T.removeEventListener("message",me),b=null,d.clear(),re(),ie())}T.addEventListener("message",me),B(V,K),C[K]=me.bind(null,{data:{callback:K}})}),b},T.reset=function(){T.postMessage({reset:!0});for(var V in C)C[V](),delete C[V]}}return function(){if(N)return N;if(!a&&i){var T=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
1
+ "use strict";var Lr=Object.defineProperty;var Rn=e=>{throw TypeError(e)};var Br=(e,s,n)=>s in e?Lr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var et=(e,s,n)=>Br(e,typeof s!="symbol"?s+"":s,n),Gn=(e,s,n)=>s.has(e)||Rn("Cannot "+n);var te=(e,s,n)=>(Gn(e,s,"read from private field"),n?n.call(e):s.get(e)),fe=(e,s,n)=>s.has(e)?Rn("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),he=(e,s,n,a)=>(Gn(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),f=require("lodash-es"),x=require("react"),pe=require("jotai"),U=require("@tanstack/react-query"),W=require("sonner"),$=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),ut=require("date-fns"),S=require("lucide-react"),Mr=require("compressorjs"),Ws=require("react-diff-view"),ca=require("@chaibuilder/runtime"),ws=require("zod"),Or=require("react-dropzone"),Rr=require("@chaibuilder/sdk/web-blocks");function Gr(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const be=Gr(x),Se={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},R={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_REVISION_DATA:"GET_REVISION_DATA",GET_PAGE_DATA:"GET_PAGE_DATA",GET_COMPARE_DATA:"GET_COMPARE_DATA",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"};let Fr=0;function Fn(e,s){const n=`atom${++Fr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Ur,a.write=qr),s&&(a.write=s),a}function Ur(e){return e(this)}function qr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const $r=Symbol(""),zr=e=>typeof(e==null?void 0:e.then)=="function";function Vr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,h)=>{var d,m;const j=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return h}a=p}return r},y=(m=(d=e())==null?void 0:d.getItem(u))!=null?m:null;return zr(y)?y.then(j):j(y)},setItem:(u,h)=>{var d;return(d=e())==null?void 0:d.setItem(u,JSON.stringify(h,void 0))},removeItem:u=>{var h;return(h=e())==null?void 0:h.removeItem(u)}},l=u=>(h,d,m)=>u(h,j=>{let y;try{y=JSON.parse(j||"")}catch{y=m}d(y)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,h)=>{if(!(e()instanceof window.Storage))return()=>{};const d=m=>{m.storageArea===e()&&m.key===u&&h(m.newValue)};return window.addEventListener("storage",d),()=>{window.removeEventListener("storage",d)}}),o&&(i.subscribe=l(o)),i}const Kr=Vr();function ua(e,s,n=Kr,a){const r=Fn(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Fn(l=>l(r),(l,o,u)=>{const h=typeof u=="function"?u(l(r)):u;return h===$r?(o(r,s),n.removeItem(e)):h instanceof Promise?h.then(d=>(o(r,d),n.setItem(e,d))):(o(r,h),n.setItem(e,h))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const da="__logged_in_user",Hr=ua(da,null),Oe=()=>{const[e,s]=pe.useAtom(Hr),n=x.useCallback(()=>{s(null),localStorage.removeItem(da)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},pn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)});let gt=null;function Qr(){const{user:e,setUser:s,logout:n}=Oe(),a=Ms(),r=qe("getAccessToken",!1),i=async()=>{if(r===!1&&e&&!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken")))try{const l=await pn(a,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!l.ok){n(),window.location.reload();return}const o=await l.json();if(f.has(o,"id")&&f.has(o,"email")&&f.has(o,"accessToken")&&f.has(o,"refreshToken"))return s(o),o;n(),window.location.reload()}catch{n(),window.location.reload()}};return U.useMutation({mutationFn:async()=>{if(gt)return await gt;gt=i();try{return await gt}finally{gt=null}},onSuccess:()=>{}})}function Wr(){return gt}const ha=()=>{const{user:e,setUser:s}=Oe(),{mutateAsync:n}=Qr(),a=60,r=x.useCallback(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const o=Math.floor(Date.now()/1e3);return e.expiresAt-o<=a},[e]),l=qe("getAccessToken",async()=>{if(!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken"))){if(r()){const o=Wr();if(o){const h=await o;return h&&s(h),(h==null?void 0:h.accessToken)||""}const u=await n();return u&&s(u),(u==null?void 0:u.accessToken)||""}return(e==null?void 0:e.accessToken)||""}});return{getAccessToken:x.useCallback(async()=>{try{return await l()}catch{return""}},[l])}},Z=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ha();return x.useCallback(async(n,a,r={})=>{const i=await s();if(!i)return null;try{const l=f.get(a,"action","").toLowerCase(),o=await pn(n+(l?`?action=${l}`:""),a,{...r,Authorization:`Bearer ${i}`});if(o.status===401)return console.log("401 Response",o),e(),window.location.reload(),null;if(!o.ok){const u=await o.json();throw console.error(`API Error (${o.status}):`,u),{status:o.status,statusText:o.statusText,...u,message:u.error||u.message||`Server error: ${o.status}`}}return await o.json()}catch(l){throw console.error("API request failed:",a,l),l}},[e,s])},ma=()=>{const e=oe(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[R.GET_DRAFT_PAGE]})}})},fa=()=>{const e=oe(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[R.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||W.toast.success("Website settings updated successfully.")},onError:a=>{W.toast.error("Failed to update website settings",{description:a.message})}})},Jr=()=>{const e=oe(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[R.GET_WEBSITE_DATA]}),W.toast.success("Website data updated successfully.")},onError:a=>{W.toast.error("Failed to update website data",{description:a.message})}})};function Pe(){const[e,s]=x.useState(new URLSearchParams(window.location.search));return x.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Yr=pe.atom({}),xa=()=>pe.useAtom(Yr),Xr=()=>{const[e]=Pe(),s=e.get("page"),n=x.useRef(""),{mutate:a}=ma();x.useEffect(()=>{!f.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},qe=(e,s)=>{const[n]=xa();return x.useMemo(()=>f.get(n,e,s),[n,e,s])},oe=()=>qe("apiUrl","/chai/api"),Ms=()=>qe("usersApiUrl","/chai/users"),cs=()=>qe("assetsApiUrl","/chai/assets"),Zr=()=>qe("supabaseInstance",null),Ue=e=>{const s=oe(),[n]=Pe(),a=e??n.get("page"),r=Z();return U.useQuery({queryKey:[R.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:R.GET_LANGUAGE_PAGES,data:{id:a}});return f.reverse(f.sortBy(i,"primaryPage"))},enabled:!!a})},Ve=()=>{const e=oe(),s=Z();return U.useQuery({queryKey:[R.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:R.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},ga=e=>{const{fallbackLang:s}=$.useLanguages(),{data:n}=Ve(),{data:a,isFetching:r}=Ue(),i=x.useMemo(()=>{const l={[s]:!0};return f.each(f.get(n,"languages"),o=>{const u=f.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||f.isEmpty(e)||e&&i[e]},yn=()=>{const e=U.useQueryClient(),{data:s}=U.useQuery({queryKey:[R.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:x.useCallback(a=>{e.setQueryData([R.AI_CONTEXT],a)},[e]),aiContext:s}},ei=pe.atom(null),pa=()=>pe.useAtom(ei),jn=()=>{const[e]=pa();return(e==null?void 0:e.slug)||""};function ti(e,s){const[n,a]=x.useState(e);return x.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const si=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=$.useLanguages(),{data:r}=ke(),i=r==null?void 0:r.pageType,l=oe(),o=Z(),{data:u,isFetching:h}=U.useQuery({queryKey:[R.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await o(l,{action:R.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),d=x.useMemo(()=>n===""?u.filter(m=>m.lang===""||m.lang===a):u.filter(m=>m.lang===n),[n,a,u]);return{allLangPages:u,data:d,isFetching:h}},ya=()=>{const{selectedLang:e,fallbackLang:s}=$.useLanguages(),[n,a]=pa(),[r,i]=x.useState(""),l=ti(r,500),{allLangPages:o,data:u,isFetching:h}=si({query:l}),d=x.useCallback(y=>a(y),[a]),m=x.useCallback(y=>i(y),[i]),j=x.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),p=e.length===0,g=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,w=o.filter(E=>(E==null?void 0:E.primaryPage)===g||E.id===g).find(E=>p?E.lang===e||E.lang===s:E.lang===e);a(w||n)},[n,e,o,a,s]);return{isPending:h,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:o,updateDynamicPage:d,updateSearchQuery:m,onChangeLanguage:j}},We=()=>{const{data:e}=Ve();return x.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},dt=()=>{const e=Z(),s=oe();return U.useQuery({queryKey:[R.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:R.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},ni=e=>{const s=Z(),n=oe(),a=We();return U.useQuery({queryKey:[R.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:R.GET_WEBSITE_PAGES,data:{lang:e}})||[];return f.keyBy(f.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})},ai=pe.atom({lastSaved:void 0}),Os=()=>pe.useAtom(ai),ke=()=>{const[e]=Pe(),s=e.get("page"),[n]=ja(),{data:a,isFetching:r}=dt();return{data:x.useMemo(()=>({...f.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},Je=()=>{const[e]=Pe(),s=e.get("lang")??"",{data:n,isFetching:a}=Ue();return{data:x.useMemo(()=>f.find(n,{lang:s})||{},[n,s]),isFetching:a}},ri=pe.atom({}),ja=()=>pe.useAtom(ri),va=()=>{const{data:e}=Je(),s=jn(),n=e==null?void 0:e.slug,a=n?window.location.origin+(n.endsWith("/")?n.slice(0,-1):n):window.location.origin;return s?a+s:a};class ba{constructor(s,n,a,r){et(this,"channelId");et(this,"supabase");et(this,"channel",null);et(this,"userId",null);et(this,"clientId",null);et(this,"pageId",null);et(this,"callback");var i,l,o,u,h,d;this.userId=a,this.supabase=s,this.clientId=this.getClientId(),this.channelId=`WEBSITE:${n}`,this.callback=r,this.channel=this.supabase.channel(this.channelId,{config:{presence:{key:this.clientId}}}),(d=(h=(u=(o=(l=(i=this.channel)==null?void 0:i.on("presence",{event:"sync"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:l.on("presence",{event:"leave"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:o.on("presence",{event:"join"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:u.on("broadcast",{event:"TAKE_OVER_REQUESTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUESTED",m)))==null?void 0:h.on("broadcast",{event:"TAKE_OVER_REQUEST_ACCEPTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUEST_ACCEPTED",m)))==null||d.on("broadcast",{event:"TAKE_OVER_REQUEST_REJECTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUEST_REJECTED",m)).subscribe()}getClientId(){return crypto.randomUUID()}getOnlineUsers({pageId:s,userId:n}){var i;const a=(i=this.channel)==null?void 0:i.presenceState();let r=Object.values(a||{}).map(l=>l[0]).filter(Boolean);return s?r=r.filter(l=>l.pageId===s):n&&(r=r.filter(l=>l.userId===n)),r.sort((l,o)=>l.onlineAt-o.onlineAt)}getPageOwner(){const s=this.getOnlineUsers({pageId:this.pageId});return s.length>0?s[0]:null}getPageUserMapping(){const s=this.getOnlineUsers({}),n=f.groupBy(s,"pageId"),a={};return Object.keys(n).forEach(r=>{var l;const i=(l=f.minBy(n[r],"onlineAt"))==null?void 0:l.userId;i!==this.userId&&(a[r]=i)}),a}onReceiveEvent(s,n){if(!this.pageId)return;const a=this.getPageOwner();if(!a||a.clientId===this.clientId?this.callback("USER_JOINED",{isActiveInOtherTab:!1}):this.callback("PAGE_LOCKED",{isActiveInOtherTab:(a==null?void 0:a.userId)===this.userId&&(a==null?void 0:a.clientId)!==this.clientId}),n.targetClientId===this.clientId)switch(s){case"TAKE_OVER_REQUESTED":this.callback("TAKE_OVER_REQUESTED",{requestedBy:n==null?void 0:n.userId,requestingClientId:n==null?void 0:n.senderClientId,isRequestedFromAnotherTab:(n==null?void 0:n.senderClientId)!==this.clientId&&(n==null?void 0:n.userId)===this.userId});break;case"TAKE_OVER_REQUEST_ACCEPTED":this.channel.track({pageId:this.pageId,userId:this.userId,clientId:this.clientId,onlineAt:a?a.onlineAt-10:+new Date}),this.callback("TAKE_OVER_REQUEST_ACCEPTED",{isTakingOverFromAnotherTab:(n==null?void 0:n.senderClientId)!==this.clientId&&(n==null?void 0:n.userId)===this.userId});break;case"TAKE_OVER_REQUEST_REJECTED":this.callback("TAKE_OVER_REQUEST_REJECTED");break}}async joinPage(s){var n;this.pageId=s,(n=this.channel)==null||n.track({pageId:this.pageId,userId:this.userId,clientId:this.clientId,onlineAt:+new Date})}async leavePage(){var s;this.channel&&((s=this.channel)==null||s.untrack())}async sendEvent(s,n){var a,r;if(this.channel){const i={pageId:this.pageId,userId:this.userId,senderClientId:this.clientId};s==="TAKE_OVER_REQUESTED"?i.targetClientId=(a=this.getPageOwner())==null?void 0:a.clientId:(s==="TAKE_OVER_REQUEST_ACCEPTED"||s==="TAKE_OVER_REQUEST_REJECTED")&&(i.targetClientId=n==null?void 0:n.requestingClientId),await((r=this.channel)==null?void 0:r.send({event:s,payload:i,type:"broadcast"}))}}}const Ke=e=>{const s=Ms(),n=Z();return U.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:R.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!f.isEmpty(e)})},ii=pe.atom(void 0),li=pe.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),oi=pe.atom(""),ci=pe.atom(null),vn=pe.atom({}),wa=()=>pe.useAtom(vn),Ye=()=>{const[e]=Pe(),s=e.get("page"),{user:n}=Oe(),[a,r]=pe.useAtom(ii),[i,l]=pe.useAtom(li),[o,u]=pe.useAtom(ci),[h,d]=pe.useAtom(oi),[m]=pe.useAtom(vn);return x.useMemo(()=>({pageLock:i,pageToUser:m,lockingStatus:h,realtimeInstance:o,setPageLock:l,setCurrentEditor:r,setLockingStatus:d,setRealtimeInstance:u,realtimePageLockEnabled:!!o,currentEditor:o?m[s||""]:a,isLocked:o?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a}),[s,n==null?void 0:n.id,i,h,a,o,l,r,d,u,m])},ui=()=>{const e=Zr(),{data:s}=ke(),{user:n}=Oe(),a=s==null?void 0:s.id,{data:r}=Ve(),{pageLock:i,setPageLock:l,setLockingStatus:o,realtimeInstance:u,setRealtimeInstance:h}=Ye(),[,d]=pe.useAtom(vn),m=x.useRef(!1),j=x.useRef(i),y=x.useRef(!1);return x.useEffect(()=>{if(n!=null&&n.id&&e&&!u&&(r!=null&&r.appKey)&&!y.current){y.current=!0;const p=async(v,w)=>{var E,P;switch(v){case"UPDATE_ONLINE_USERS":d((w==null?void 0:w.pageToUser)||{});break;case"PAGE_LOCKED":l({...j==null?void 0:j.current,requestedBy:"",status:"locked",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"USER_JOINED":if(((E=j==null?void 0:j.current)==null?void 0:E.status)==="editing")return;((P=j==null?void 0:j.current)==null?void 0:P.status)==="locked"&&o("can_edit_now"),l({...j==null?void 0:j.current,requestedBy:"",status:"editing",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":l({...j==null?void 0:j.current,requestingClientId:w==null?void 0:w.requestingClientId,requestedBy:w!=null&&w.isRequestedFromAnotherTab?"ANOTHER_TAB":w==null?void 0:w.requestedBy});break;case"TAKE_OVER_REQUEST_ACCEPTED":w!=null&&w.isTakingOverFromAnotherTab||(o("take_over_request_accepted"),W.toast.success("Your Page Take Over Request Accepted",{position:"top-center"})),l({...j==null?void 0:j.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":o("take_over_request_rejected"),l({...j==null?void 0:j.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},g=new ba(e,r==null?void 0:r.appKey,n==null?void 0:n.id,p);h(g)}},[h,e,r==null?void 0:r.appKey]),x.useEffect(()=>{j.current=i},[i]),x.useEffect(()=>{if(!(!u||!a||!(n!=null&&n.id)||m.current))return m.current=!0,u==null||u.joinPage(a),()=>{u&&m.current&&(m.current=!1,j.current={requestedBy:"",status:"checking",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1},o(""),l(j.current),u==null||u.leavePage())}},[a,u]),i==null?void 0:i.status},Sa=()=>{const{data:e}=ke(),{user:s}=Oe(),n=e==null?void 0:e.id,{pageLock:a,setPageLock:r,realtimeInstance:i}=Ye(),{savePageAsync:l}=$.useSavePage(),o=x.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(r({...a,isTakeOverRequested:!0}),i==null||i.sendEvent("TAKE_OVER_REQUESTED"))},[i,n,s==null?void 0:s.id,r,a]),u=x.useCallback(async()=>{!i||!n||!(s!=null&&s.id)||(await l(),i==null||i.sendEvent("TAKE_OVER_REQUEST_ACCEPTED",{requestingClientId:a==null?void 0:a.requestingClientId}),r({requestedBy:"",status:"locked",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1}))},[n,i,s==null?void 0:s.id,r,l,a]),h=x.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(i==null||i.sendEvent("TAKE_OVER_REQUEST_REJECTED",{requestingClientId:a==null?void 0:a.requestingClientId}),r({...a,requestedBy:"",status:"editing",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1}))},[n,i,s==null?void 0:s.id,r,a]);return{pageLock:a,acceptTakeOver:u,rejectTakeOver:h,requestTakeOver:o}},Na=()=>{const[e]=Pe(),s=e.get("page"),n=oe(),{setAiContext:a}=yn(),{setCurrentEditor:r}=Ye(),[,i]=Os(),[,l]=ja(),[,o]=$.useIsPageLoaded(),u=Z();return U.useQuery({queryKey:[R.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r(""),o(!1);const h=await u(n,{action:R.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(h.currentEditor);const d=h.blocks??[],m=f.find(d,{_type:"@chai/ai-context"});return a(f.get(m,"_value","")||""),i(j=>({...j,lastSaved:h.lastSaved})),l(f.get(h,"metadata",{})),setTimeout(()=>o(!0),500),d},enabled:!!s})},bn=()=>{const{data:e}=ke(),{data:s}=Je(),n=oe(),a=Z(),r=We(),i=jn();return U.useQuery({queryKey:[R.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:R.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})},us=({children:e})=>t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen flex-col items-center justify-center bg-black/20",children:e}),Ea=({fullScreen:e=!0})=>{const s=t.jsxs("div",{className:"flex flex-row gap-2",children:[t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-purple-500"}),t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-cyan-500 [animation-delay:-.3s]"}),t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-pink-500 [animation-delay:-.5s]"})]});return e?t.jsx(us,{children:s}):t.jsx("div",{className:"flex h-full w-full items-center justify-center",children:s})},di=({currentEditor:e})=>{const{user:s}=Oe(),{data:n}=Ke(e);return!n||!e||e===(s==null?void 0:s.id)?null:t.jsx("span",{className:"ml-2 flex items-center gap-1 text-xs font-light text-gray-500",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(S.LockIcon,{className:"h-3 w-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},hi=({userId:e})=>{const{data:s}=Ke(e);return(s==null?void 0:s.name)||"Unknown"};function mi({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,realtimePageLockEnabled:i,isRequestRejected:l,isFetchingUserInfo:o}){const[u,h]=x.useState(!1),[d,m]=x.useState(!1),j=()=>{h(!0),setTimeout(()=>{h(!1)},15e3),m(!1),r()};return t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl",children:[t.jsx(S.LockKeyhole,{className:"h-8 w-8 rounded-md bg-sky-500/20 p-1.5 text-sky-500"}),"Page is locked for editing"]})}),t.jsx(c.CardContent,{className:"w-md grid w-full pt-2",children:t.jsxs("div",{children:[t.jsxs("div",{className:"relative mx-auto flex w-96 items-center space-x-4 rounded-md border border-green-500 px-2 pb-2 pt-4",children:[t.jsx("div",{className:"absolute -top-2.5 left-3 w-max rounded-full bg-green-500 px-3 py-1 text-xs font-medium leading-3 text-white",children:"Locked By"}),e&&!o?t.jsx("img",{src:e,alt:s,className:"h-14 w-14 rounded-full border border-gray-300"}):t.jsx(S.UserIcon,{className:"h-14 w-14 flex-shrink-0 rounded-full bg-gradient-to-br from-purple-400 to-pink-500 p-2 text-white"}),t.jsxs("div",{className:o?"space-y-1.5":"space-y-0",children:[o?t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"}):t.jsx("span",{className:"truncate font-medium text-black",children:s}),n&&!o?t.jsx("p",{className:"truncate text-sm text-muted-foreground",children:n}):t.jsx(c.Skeleton,{className:"h-4 w-60 rounded"}),a&&!o?t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",ut.formatDistanceToNow(new Date(a),{addSuffix:!0})]}):t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{className:"py-4 text-center text-gray-600",children:["This page is currently being edited by ",t.jsx("span",{className:"font-bold",children:s}),".",t.jsx("br",{}),i&&t.jsxs(t.Fragment,{children:[" ",t.jsx("br",{})," You can either wait until they finish editing or"," ",i?"request to":""," take over the page."]})]})}),l&&t.jsxs("div",{className:"mt-4 flex w-full items-center justify-center gap-x-2 rounded border border-red-500 bg-red-50 p-2 text-center font-medium text-red-500",children:[t.jsx(S.Info,{className:"h-5 w-5"})," Page take over request is rejected"]})]})}),t.jsx(c.CardFooter,{children:i?t.jsxs(c.Button,{disabled:u,onClick:j,className:"w-full",variant:"destructive",children:[t.jsx(S.KeyIcon,{className:"h-5 w-5"}),u?"Page take is requested.":l?"Request take over again":"Request take over"]}):t.jsxs(c.AlertDialog,{open:d,onOpenChange:m,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(S.AlertTriangleIcon,{className:"h-5 w-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:j,children:"Yes, Take Over"})]})]})]})})]})})}const ys=({isChecking:e,lockingStatus:s,onContinue:n})=>{const[a,r]=x.useState(!1),i=s==="page_is_active_in_other_tab",l=(s==null?void 0:s.length)>0,{pageLock:o,acceptTakeOver:u,rejectTakeOver:h}=Sa(),d=()=>{r(!0),l||i?n():u(),setTimeout(()=>{r(!1)},3e3)};return x.useEffect(()=>{(o==null?void 0:o.requestedBy)==="ANOTHER_TAB"&&u()},[o,u]),(o==null?void 0:o.requestedBy)==="ANOTHER_TAB"?null:e?t.jsx(Ea,{}):t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl font-medium",children:[a?t.jsx(S.Loader,{className:"h-6 w-6 animate-spin text-gray-500"}):i?t.jsx(S.TableIcon,{className:"h-6 w-6 text-green-500"}):l?t.jsx(S.CheckCircle,{className:"h-6 w-6 text-green-500"}):t.jsx(S.Target,{className:"h-6 w-6 text-green-500"}),i?"Page is active in other tab":l?"You can edit the page now.":"Page take over request"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:i?t.jsx("p",{children:'You are already editing this page in another tab. To continue editing here, click on "Continue editing here".'}):l?t.jsx("p",{children:"This page is released by other user you can continue editing now."}):t.jsxs("p",{children:[t.jsxs("b",{children:[" ",t.jsx(hi,{userId:o==null?void 0:o.requestedBy})]})," ","has requested to take over this page.",t.jsx("br",{})," If you accept, your unsaved changes will be saved."]})})}),t.jsxs(c.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(c.Button,{disabled:a,onClick:d,className:l?"":"bg-green-500 hover:bg-green-600",children:i?t.jsxs(t.Fragment,{children:[t.jsx(S.Edit,{className:"h-5 w-5"})," Continue editing here"]}):l?t.jsxs(t.Fragment,{children:[t.jsx(S.Edit,{className:"h-5 w-5"})," Continue to edit"]}):t.jsxs(t.Fragment,{children:[t.jsx(S.Check,{className:"h-5 w-5"})," Accept"]})}),!l&&t.jsxs(c.Button,{variant:"outline",onClick:h,children:[t.jsx(S.X,{className:"h-5 w-5"})," Reject"]})]})]})})},fi=()=>{const{pageLock:e,requestTakeOver:s}=Sa(),{isLocked:n,currentEditor:a,lockingStatus:r,setLockingStatus:i,realtimePageLockEnabled:l}=Ye(),{data:o,isFetching:u}=Ke(a),[h]=Pe(),d=h.get("page"),{mutate:m}=ma(),{isFetching:j}=Na(),[y]=Os(),p=U.useQueryClient(),g=x.useCallback(()=>{l?s():m({id:d})},[d,m,s,l]);return d?l&&(e==null?void 0:e.status)==="checking"?t.jsx(ys,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):l&&(e!=null&&e.requestedBy)?t.jsx(ys,{lockingStatus:"",onContinue:()=>{}}):(l?e.status!=="locked":!n||j)?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(ys,{lockingStatus:r,onContinue:()=>{p.invalidateQueries({queryKey:[R.GET_DRAFT_PAGE]}),i("")}}):null:l&&(e!=null&&e.isActiveInOtherTab)?t.jsx(ys,{lockingStatus:"page_is_active_in_other_tab",onContinue:s}):t.jsx(mi,{...o,isFetchingUserInfo:u,name:(o==null?void 0:o.name)||"Unknown User",email:(o==null?void 0:o.email)||"",lastSaved:(y==null?void 0:y.lastSaved)||"",onTakeOver:g,realtimePageLockEnabled:l,isRequestRejected:r==="take_over_request_rejected"}):null},xi=()=>{const[e,s]=Pe(),n=e.get("lang"),a=ga(n),{setSelectedLang:r}=$.useLanguages(),i=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),h=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",h),s(o),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=f.get(Se,n);return t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(S.LockIcon,{className:"h-6 w-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(c.CardFooter,{children:t.jsx(c.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},gi=e=>{const s=oe(),n=Z();return U.useMutation({mutationFn:async a=>n(s,{action:R.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),W.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},pi=e=>{const s=oe(),n=Z();return U.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:R.GET_LIBRARY_ITEM,data:{id:e}})}catch(a){throw console.error(a),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},yi=e=>{const s=oe(),n=Z();return U.useMutation({mutationFn:async a=>n(s,{action:R.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),W.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},ji=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=x.useState(!1),u=$.useUpdateBlocksPropsRealtime(),h=yi(()=>{u([e],{_libBlockId:void 0}),W.toast.success("Block deleted successfully"),o(!1),a()}),d=()=>{o(!0),h.mutate(s)},m=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:j=>j.preventDefault(),disabled:l,children:[t.jsx(S.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:j=>!j&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:i||m}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:d,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},vi=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=x.useState(!1);return t.jsx(ji,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{o(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>o(!0),children:[t.jsx(S.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},bi=()=>{const e=oe(),s=Z(),n=U.useQueryClient(),{data:a=[],isLoading:r,error:i}=U.useQuery({queryKey:["library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:o}=U.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return s(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:["library-groups"]}),W.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),W.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:o}},wi=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),[r,i]=x.useState(""),l=x.useRef(null),{groups:o}=bi(),[u,h]=x.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),d=x.useMemo(()=>[...o,...u.filter(y=>!o.some(p=>p.id===y.id))],[o,u]),m=()=>{const y=r.trim();if(!y)return;const p={id:y,name:y};h(g=>[...g,p]),s(p.id),i(""),a(!1)};x.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const j=y=>{y.key==="Enter"&&(y.preventDefault(),m())};return x.useEffect(()=>{e&&!d.some(y=>y.id===e)&&s("")},[e,d,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:j}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:m,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!o.some(p=>p.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(S.Plus,{className:"h-4 w-4"})})]})},Js=3*1024*1024;function nn(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function Ca(e){return new Promise((s,n)=>{if(e.size<=Js){s(e);return}new Mr(e,{quality:.8,maxWidth:2048,maxHeight:2048,convertSize:Js,success(a){s(a)},error(a){W.toast.error(`Failed to compress image. Image size is ${nn(e.size)}, which exceeds the maximum allowed size of ${nn(Js)}.`),n(a)}})})}const Si=10*1024*1024,Ni=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),r=x.useRef(null),i=x.useCallback(async u=>{var d;const h=(d=u.target.files)==null?void 0:d[0];if(h){if(h.size>Si){W.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(h.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);let m=h;h.type.startsWith("image/")&&(m=await Ca(h));const j=new FileReader;j.onloadend=()=>{s(j.result),a(!1)},j.readAsDataURL(m)}catch(m){console.error("Error reading file:",m),a(!1),W.toast.error("Failed to process image",{description:m instanceof Error?m.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},o=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(S.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(S.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"aspect-video h-[200px] max-h-[200px] overflow-hidden rounded-md border",children:t.jsx("img",{src:e,alt:"Preview",className:"h-full w-full object-contain"})})]})},ve={...$.PERMISSIONS,ADD_PAGE:"add_page",EDIT_PAGE:"edit_page",EDIT_SLUG:"edit_slug",DELETE_PAGE:"delete_page",CHANGE_PAGE_TYPE:"change_page_type",PUBLISH_PAGE:"publish_page",UNPUBLISH_PAGE:"unpublish_page",MARK_AS_TEMPLATE:"mark_as_template",UNMARK_AS_TEMPLATE:"unmark_as_template",ADD_PARTIAL:"add_partial",EDIT_PARTIAL:"edit_partial",DELETE_PARTIAL:"delete_partial",PUBLISH_PARTIAL:"publish_partial",UNPUBLISH_PARTIAL:"unpublish_partial",EDIT_SEO:"edit_seo",RESTORE_REVISION:"restore_revision",DELETE_REVISION:"delete_revision",PUBLISH_THEME:"publish_theme",EDIT_SETTINGS:"edit_settings",ADD_LIBRARY_BLOCK:"create_library_block",ADD_LIBRARY_TEMPLATE:"add_library_template",EDIT_LIBRARY_BLOCK:"edit_library_block",EDIT_LIBRARY_TEMPLATE:"edit_library_template",DELETE_LIBRARY_BLOCK:"delete_library_block",DELETE_LIBRARY_TEMPLATE:"delete_library_template",ADD_MEDIA:"add_media",EDIT_MEDIA:"edit_media",DELETE_MEDIA:"delete_media"},Ei=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=$.usePartailBlocksStore(),i=s.find(C=>C._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=x.useMemo(()=>s.some(C=>C._type==="PartialBlock"||C._type==="GlobalBlock"),[s]),h=x.useMemo(()=>{let C=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let T=r(M.partialBlockId);M._parent&&(T==null?void 0:T.length)>0&&(T=T.map(B=>(f.isEmpty(B._parent)&&f.set(B,"_parent",M._parent),B))),C=[...C,...T]}else C.push(M);return C},[s,r]),[d,m]=x.useState(""),[j,y]=x.useState(""),[p,g]=x.useState(""),[v,w]=x.useState(""),[E,P]=x.useState({}),[D,A]=x.useState(!1),[I,O]=x.useState(o),[Y,ee]=x.useState(!1),{hasPermission:L}=$.usePermissions(),q=L(ve.DELETE_LIBRARY_BLOCK),F=$.useUpdateBlocksPropsRealtime(),z=()=>{F([a],{_libBlockId:void 0}),W.toast.success("Block delinked from library"),n()},{data:G,isLoading:Q,isError:ae}=pi(l);x.useEffect(()=>{ae&&o&&(ee(!0),O(!1))},[ae,o]),x.useEffect(()=>{G&&!Q&&(m(G.name||""),y(G.group||""),g(G.description||""),w(G.preview||""),O(!1))},[G,Q]),x.useEffect(()=>{const C=d.trim().length>=2,M=j.trim()!=="";A(C&&M)},[d,j]);const je=()=>{const C={};return d.trim()?d.length<2&&(C.name="Name must be at least 2 characters"):C.name="Name is required",j||(C.group="Group is required"),P(C),Object.keys(C).length===0},{resetLibrary:Ne}=$.useLibraryBlocks({id:""}),ce=gi(C=>{o||F([a],{_libBlockId:C.id}),W.toast.success(`Block ${o?"updated":"saved"} successfully`),Ne(C.library),n()}),N=async C=>{if(C.preventDefault(),!je())return;const M=h.map(T=>(f.has(T,"_libBlockId")&&delete T._libBlockId,T));ce.mutate({name:d.trim(),group:j,blocks:M,description:p.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...o?{id:l}:{}})},b=ce.isPending;return I||Q?t.jsx("div",{className:"flex items-center justify-center p-8",children:t.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):Y?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:z,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(S.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:N,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:E.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:d,onChange:C=>m(C.target.value),className:E.name?"border-destructive":""}),E.name&&t.jsx("p",{className:"text-xs text-destructive",children:E.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:E.group?"text-destructive":"",children:"Group"}),t.jsx(wi,{value:j,onChange:y}),E.group&&t.jsx("p",{className:"text-xs text-destructive",children:E.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:C=>g(C.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Ni,{value:v,onChange:w})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&q&&t.jsx(vi,{blockId:a,libBlockId:l,blockName:d,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:b,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:b||!D,children:b?"Saving...":o?"Update Block":"Save Block"})]})]})]})},le={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},Ci={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ce=()=>{const e=oe(),s=Z();return U.useQuery({queryKey:[R.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:R.GET_PAGE_TYPES})})},Ta=e=>{const{data:s}=Ce();return x.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Ti=()=>{const e=oe(),s=Z();return U.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:R.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Aa=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>await n(e,{action:R.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=f.find(a,{key:i.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";W.toast.success(l)},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:f.get(Ci,r.message,r.message)})}})},wn=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Je(),{data:r}=Ce();return U.useMutation({mutationFn:async i=>await n(e,{action:R.UPDATE_PAGE,data:i}),onSuccess:(i,l)=>{(a==null?void 0:a.id)===(l==null?void 0:l.id)&&s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES]}),l&&(l!=null&&l.primaryPage||l!=null&&l.seo)?(s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,l==null?void 0:l.primaryPage]}),s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})},onError:(i,l)=>{const o=f.find(r,{key:l.pageType});W.toast.error(`Failed to update ${o!=null&&o.hasSlug?"page":o.name}.`,{description:i.message})}})},Ai=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:R.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){W.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},ki=()=>{const e=oe(),s=U.useQueryClient(),n=Z(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:R.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]});const l=f.find(a,{key:i.pageType});W.toast.success(l!=null&&l.hasSlug?le.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Sn=()=>{const e=oe(),s=Z(),n=U.useQueryClient(),{data:a}=ke(),{savePageAsync:r}=$.useSavePage();return U.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:R.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[R.GET_CHANGES]}),n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),W.toast.error("Failed to publish pages.")}})},Pi=()=>{const e=oe(),s=Z(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>{var r;return s(e,{action:R.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),W.toast.success("Page marked as template successfully.")},onError:()=>{W.toast.error("Failed to mark page as template.")}})},Ii=()=>{const e=oe(),s=Z(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>s(e,{action:R.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),W.toast.success("Page unmarked as template successfully.")},onError:()=>{W.toast.error("Failed to unmark page as template.")}})},_i=()=>{const e=oe(),s=Z(),n=U.useQueryClient();return U.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:R.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{W.toast.success(le.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]})},onError:()=>{W.toast.error("Failed to change slug")}})};var Nn={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!s.OffscreenCanvas)return!1;var N=new OffscreenCanvas(1,1),b=N.getContext("2d");b.fillRect(0,0,1,1);var C=N.transferToImageBitmap();try{b.createPattern(C,"no-repeat")}catch{return!1}return!0}();function u(){}function h(N){var b=n.exports.Promise,C=b!==void 0?b:s.Promise;return typeof C=="function"?new C(N):(N(u,u),null)}var d=function(N,b){return{transform:function(C){if(N)return C;if(b.has(C))return b.get(C);var M=new OffscreenCanvas(C.width,C.height),T=M.getContext("2d");return T.drawImage(C,0,0),b.set(C,M),M},clear:function(){b.clear()}}}(o,new Map),m=function(){var N=Math.floor(16.666666666666668),b,C,M={},T=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(b=function(B){var H=Math.random();return M[H]=requestAnimationFrame(function V(J){T===J||T+N-1<J?(T=J,delete M[H],B()):M[H]=requestAnimationFrame(V)}),H},C=function(B){M[B]&&cancelAnimationFrame(M[B])}):(b=function(B){return setTimeout(B,N)},C=function(B){return clearTimeout(B)}),{frame:b,cancel:C}}(),j=function(){var N,b,C={};function M(T){function B(H,V){T.postMessage({options:H||{},callback:V})}T.init=function(V){var J=V.transferControlToOffscreen();T.postMessage({canvas:J},[J])},T.fire=function(V,J,re){if(b)return B(V,null),b;var K=Math.random().toString(36).slice(2);return b=h(function(ie){function me(xe){xe.data.callback===K&&(delete C[K],T.removeEventListener("message",me),b=null,d.clear(),re(),ie())}T.addEventListener("message",me),B(V,K),C[K]=me.bind(null,{data:{callback:K}})}),b},T.reset=function(){T.postMessage({reset:!0});for(var V in C)C[V](),delete C[V]}}return function(){if(N)return N;if(!a&&i){var T=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
2
2
  `);try{N=new Worker(URL.createObjectURL(new Blob([T])))}catch(B){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",B),null}M(N)}return N}}(),y={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function p(N,b){return b?b(N):N}function g(N){return N!=null}function v(N,b,C){return p(N&&g(N[b])?N[b]:y[b],C)}function w(N){return N<0?0:Math.floor(N)}function E(N,b){return Math.floor(Math.random()*(b-N))+N}function P(N){return parseInt(N,16)}function D(N){return N.map(A)}function A(N){var b=String(N).replace(/[^0-9a-f]/gi,"");return b.length<6&&(b=b[0]+b[0]+b[1]+b[1]+b[2]+b[2]),{r:P(b.substring(0,2)),g:P(b.substring(2,4)),b:P(b.substring(4,6))}}function I(N){var b=v(N,"origin",Object);return b.x=v(b,"x",Number),b.y=v(b,"y",Number),b}function O(N){N.width=document.documentElement.clientWidth,N.height=document.documentElement.clientHeight}function Y(N){var b=N.getBoundingClientRect();N.width=b.width,N.height=b.height}function ee(N){var b=document.createElement("canvas");return b.style.position="fixed",b.style.top="0px",b.style.left="0px",b.style.pointerEvents="none",b.style.zIndex=N,b}function L(N,b,C,M,T,B,H,V,J){N.save(),N.translate(b,C),N.rotate(B),N.scale(M,T),N.arc(0,0,1,H,V,J),N.restore()}function q(N){var b=N.angle*(Math.PI/180),C=N.spread*(Math.PI/180);return{x:N.x,y:N.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:N.startVelocity*.5+Math.random()*N.startVelocity,angle2D:-b+(.5*C-Math.random()*C),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:N.color,shape:N.shape,tick:0,totalTicks:N.ticks,decay:N.decay,drift:N.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:N.gravity*3,ovalScalar:.6,scalar:N.scalar,flat:N.flat}}function F(N,b){b.x+=Math.cos(b.angle2D)*b.velocity+b.drift,b.y+=Math.sin(b.angle2D)*b.velocity+b.gravity,b.velocity*=b.decay,b.flat?(b.wobble=0,b.wobbleX=b.x+10*b.scalar,b.wobbleY=b.y+10*b.scalar,b.tiltSin=0,b.tiltCos=0,b.random=1):(b.wobble+=b.wobbleSpeed,b.wobbleX=b.x+10*b.scalar*Math.cos(b.wobble),b.wobbleY=b.y+10*b.scalar*Math.sin(b.wobble),b.tiltAngle+=.1,b.tiltSin=Math.sin(b.tiltAngle),b.tiltCos=Math.cos(b.tiltAngle),b.random=Math.random()+2);var C=b.tick++/b.totalTicks,M=b.x+b.random*b.tiltCos,T=b.y+b.random*b.tiltSin,B=b.wobbleX+b.random*b.tiltCos,H=b.wobbleY+b.random*b.tiltSin;if(N.fillStyle="rgba("+b.color.r+", "+b.color.g+", "+b.color.b+", "+(1-C)+")",N.beginPath(),l&&b.shape.type==="path"&&typeof b.shape.path=="string"&&Array.isArray(b.shape.matrix))N.fill(je(b.shape.path,b.shape.matrix,b.x,b.y,Math.abs(B-M)*.1,Math.abs(H-T)*.1,Math.PI/10*b.wobble));else if(b.shape.type==="bitmap"){var V=Math.PI/10*b.wobble,J=Math.abs(B-M)*.1,re=Math.abs(H-T)*.1,K=b.shape.bitmap.width*b.scalar,ie=b.shape.bitmap.height*b.scalar,me=new DOMMatrix([Math.cos(V)*J,Math.sin(V)*J,-Math.sin(V)*re,Math.cos(V)*re,b.x,b.y]);me.multiplySelf(new DOMMatrix(b.shape.matrix));var xe=N.createPattern(d.transform(b.shape.bitmap),"no-repeat");xe.setTransform(me),N.globalAlpha=1-C,N.fillStyle=xe,N.fillRect(b.x-K/2,b.y-ie/2,K,ie),N.globalAlpha=1}else if(b.shape==="circle")N.ellipse?N.ellipse(b.x,b.y,Math.abs(B-M)*b.ovalScalar,Math.abs(H-T)*b.ovalScalar,Math.PI/10*b.wobble,0,2*Math.PI):L(N,b.x,b.y,Math.abs(B-M)*b.ovalScalar,Math.abs(H-T)*b.ovalScalar,Math.PI/10*b.wobble,0,2*Math.PI);else if(b.shape==="star")for(var _=Math.PI/2*3,se=4*b.scalar,Ee=8*b.scalar,Le=b.x,X=b.y,_e=5,Be=Math.PI/_e;_e--;)Le=b.x+Math.cos(_)*Ee,X=b.y+Math.sin(_)*Ee,N.lineTo(Le,X),_+=Be,Le=b.x+Math.cos(_)*se,X=b.y+Math.sin(_)*se,N.lineTo(Le,X),_+=Be;else N.moveTo(Math.floor(b.x),Math.floor(b.y)),N.lineTo(Math.floor(b.wobbleX),Math.floor(T)),N.lineTo(Math.floor(B),Math.floor(H)),N.lineTo(Math.floor(M),Math.floor(b.wobbleY));return N.closePath(),N.fill(),b.tick<b.totalTicks}function z(N,b,C,M,T){var B=b.slice(),H=N.getContext("2d"),V,J,re=h(function(K){function ie(){V=J=null,H.clearRect(0,0,M.width,M.height),d.clear(),T(),K()}function me(){a&&!(M.width===r.width&&M.height===r.height)&&(M.width=N.width=r.width,M.height=N.height=r.height),!M.width&&!M.height&&(C(N),M.width=N.width,M.height=N.height),H.clearRect(0,0,M.width,M.height),B=B.filter(function(xe){return F(H,xe)}),B.length?V=m.frame(me):ie()}V=m.frame(me),J=ie});return{addFettis:function(K){return B=B.concat(K),re},canvas:N,promise:re,reset:function(){V&&m.cancel(V),J&&J()}}}function G(N,b){var C=!N,M=!!v(b||{},"resize"),T=!1,B=v(b,"disableForReducedMotion",Boolean),H=i&&!!v(b||{},"useWorker"),V=H?j():null,J=C?O:Y,re=N&&V?!!N.__confetti_initialized:!1,K=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,ie;function me(_,se,Ee){for(var Le=v(_,"particleCount",w),X=v(_,"angle",Number),_e=v(_,"spread",Number),Be=v(_,"startVelocity",Number),$s=v(_,"decay",Number),zs=v(_,"gravity",Number),Vs=v(_,"drift",Number),ms=v(_,"colors",D),Ks=v(_,"ticks",Number),fs=v(_,"shapes"),Hs=v(_,"scalar"),Qs=!!v(_,"flat"),Ot=I(_),mt=Le,Ze=[],xs=N.width*Ot.x,gs=N.height*Ot.y;mt--;)Ze.push(q({x:xs,y:gs,angle:X,spread:_e,startVelocity:Be,color:ms[mt%ms.length],shape:fs[E(0,fs.length)],ticks:Ks,decay:$s,gravity:zs,drift:Vs,scalar:Hs,flat:Qs}));return ie?ie.addFettis(Ze):(ie=z(N,Ze,J,se,Ee),ie.promise)}function xe(_){var se=B||v(_,"disableForReducedMotion",Boolean),Ee=v(_,"zIndex",Number);if(se&&K)return h(function(Be){Be()});C&&ie?N=ie.canvas:C&&!N&&(N=ee(Ee),document.body.appendChild(N)),M&&!re&&J(N);var Le={width:N.width,height:N.height};V&&!re&&V.init(N),re=!0,V&&(N.__confetti_initialized=!0);function X(){if(V){var Be={getBoundingClientRect:function(){if(!C)return N.getBoundingClientRect()}};J(Be),V.postMessage({resize:{width:Be.width,height:Be.height}});return}Le.width=Le.height=null}function _e(){ie=null,M&&(T=!1,s.removeEventListener("resize",X)),C&&N&&(document.body.contains(N)&&document.body.removeChild(N),N=null,re=!1)}return M&&!T&&(T=!0,s.addEventListener("resize",X,!1)),V?V.fire(_,Le,_e):me(_,Le,_e)}return xe.reset=function(){V&&V.reset(),ie&&ie.reset()},xe}var Q;function ae(){return Q||(Q=G(null,{useWorker:!0,resize:!0})),Q}function je(N,b,C,M,T,B,H){var V=new Path2D(N),J=new Path2D;J.addPath(V,new DOMMatrix(b));var re=new Path2D;return re.addPath(J,new DOMMatrix([Math.cos(H)*T,Math.sin(H)*T,-Math.sin(H)*B,Math.cos(H)*B,C,M])),re}function Ne(N){if(!l)throw new Error("path confetti are not supported in this browser");var b,C;typeof N=="string"?b=N:(b=N.path,C=N.matrix);var M=new Path2D(b),T=document.createElement("canvas"),B=T.getContext("2d");if(!C){for(var H=1e3,V=H,J=H,re=0,K=0,ie,me,xe=0;xe<H;xe+=2)for(var _=0;_<H;_+=2)B.isPointInPath(M,xe,_,"nonzero")&&(V=Math.min(V,xe),J=Math.min(J,_),re=Math.max(re,xe),K=Math.max(K,_));ie=re-V,me=K-J;var se=10,Ee=Math.min(se/ie,se/me);C=[Ee,0,0,Ee,-Math.round(ie/2+V)*Ee,-Math.round(me/2+J)*Ee]}return{type:"path",path:b,matrix:C}}function ce(N){var b,C=1,M="#000000",T='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof N=="string"?b=N:(b=N.text,C="scalar"in N?N.scalar:C,T="fontFamily"in N?N.fontFamily:T,M="color"in N?N.color:M);var B=10*C,H=""+B+"px "+T,V=new OffscreenCanvas(B,B),J=V.getContext("2d");J.font=H;var re=J.measureText(b),K=Math.ceil(re.actualBoundingBoxRight+re.actualBoundingBoxLeft),ie=Math.ceil(re.actualBoundingBoxAscent+re.actualBoundingBoxDescent),me=2,xe=re.actualBoundingBoxLeft+me,_=re.actualBoundingBoxAscent+me;K+=me+me,ie+=me+me,V=new OffscreenCanvas(K,ie),J=V.getContext("2d"),J.font=H,J.fillStyle=M,J.fillText(b,xe,_);var se=1/C;return{type:"bitmap",bitmap:V.transferToImageBitmap(),matrix:[se,0,0,se,-K*se/2,-ie*se/2]}}n.exports=function(){return ae().apply(this,arguments)},n.exports.reset=function(){ae().reset()},n.exports.create=G,n.exports.shapeFromPath=Ne,n.exports.shapeFromText=ce})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Nn,!1);const Di=Nn.exports;Nn.exports.create;const Li={particleCount:350,spread:120,origin:{y:.6},angle:90},Bi={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Ut=e=>{let s=Bi[e];s||(s={});const n={...Li,...s};Di(n)},Mi=()=>{const[e]=$.useTheme(),{mutate:s,isPending:n}=Sn(),{mutateAsync:a,isPending:r}=fa(),i=()=>{a({settings:{theme:e}})},l=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{Ut("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"flex items-center justify-center gap-x-3 border-t bg-white py-3",children:[t.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(c.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},ds=pe.atom(null),Oi=e=>{if(!e)return{base:e,extension:null};const s=e.lastIndexOf(".");if(s<=0)return{base:e,extension:null};const n=e.substring(s);return{base:e.substring(0,s),extension:n}},nt=e=>{if(!e)return e;const{base:s}=Oi(e);return s};function Ri(e,s){const n=(e||"").split("/").filter(Boolean);let a="",r=!0;if(s.slug==="/"){const i=n.pop()||"";if(Se[i])r=!0;else{a=i;const l=n.pop()||"";r=!!Se[l]}}else if(s.parent)n.length&&(a=n.pop()||"");else if(n.length){a=n.pop()||"";const i=n.pop()||"";r=!!Se[i]}return{initSlug:a,prefix:r}}const Gi=e=>e&&nt(e),Un=(e,s)=>{const n=nt(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function En({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[o,u]=x.useState(e),[h,d]=x.useState(null);x.useEffect(()=>{u(e)},[e]);const m=j=>{const p=j.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),g=(p.match(/\./g)||[]).length,v=g<=1;g>1?d("Invalid slug. Only one dot (.) is allowed in the slug"):d(null),r&&r(v),u(p),s(p)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"mb-1 flex items-center",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent: ",t.jsx("span",{className:"font-mono text-gray-900",children:Gi(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:o,onChange:m,placeholder:n,className:h?"border-red-500":""}),h&&t.jsx("div",{className:"mt-1 text-xs text-red-500",children:h})]}),l&&l!=="undefined"&&t.jsx("div",{className:"mt-1 flex items-center",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug: ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const ka=({edit:e,lang:s,languages:n,name:a,setLang:r,setName:i,primaryPageObject:l})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",children:le.LANGUAGE}),t.jsxs("select",{value:e?"":s,disabled:e||!n.length,onChange:o=>{const u=o.target.value;r(u),!e&&(f.startsWith(a,l==null?void 0:l.name)||a.length===0)&&i(`${l==null?void 0:l.name} - ${Se[u]}`)},className:"col-span-3 flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",children:[t.jsx("option",{value:"",disabled:!0,children:e?Se[s]||s:n.length?le.CHOOSE_LANGUAGE:le.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(o=>t.jsx("option",{value:o,children:Se[o]||o},o))]})]}),Pa=({lang:e,name:s,setName:n,parentHasSelectedLanguagePage:a})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"name",children:le.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?le.ENTER_PAGE_NAME:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),Fi=({dynamic:e,isNonSlugPageType:s,isRootPage:n,lang:a,useLanguagePrefix:r,setUseLanguagePrefix:i,isHomePage:l,parentSlug:o,parentHasSelectedLanguagePage:u,slug:h,setSlug:d,setIsSlugValid:m,getSlug:j})=>s?null:t.jsxs("div",{className:"space-y-1",children:[n&&a&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:r,onChange:y=>i(y.target.checked),className:"rounded border-gray-300"}),t.jsxs(c.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",a]}),") as slug prefix"]})]}),t.jsx(c.Label,{htmlFor:"slug",children:le.SLUG}),e?t.jsx(c.Alert,{variant:"default",className:"p-2 text-xs font-medium italic text-muted-foreground",children:"This page will use dynamic slug as defined in primary page"}):t.jsx(En,{disabled:!a||!u,value:h,onChange:d,placeholder:a?l&&r?"Leave empty for home page":le.ENTER_PAGE_SLUG:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:o,onValidationChange:m,fullSlug:j()})]}),Ia=({parentHasSelectedLanguagePage:e,name:s,lang:n,slug:a,edit:r,id:i,primaryPageObject:l,pages:o,isNonSlugPageType:u,isHomePage:h,useLanguagePrefix:d,isSlugValid:m,isPending:j})=>{const y=j||!s||!n||o.some(p=>(r?p.id!==i:!0)&&p.parent===(l==null?void 0:l.id)&&p.lang===n)||!u&&!(h&&d)&&(!m||!a);return t.jsx(c.DialogFooter,{children:e?t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{type:"submit",disabled:y&&!l.dynamic,children:j?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?le.UPDATING:le.ADDING]}):r?le.UPDATE:le.ADD_NEW_LANGUAGE}),o.some(p=>(r?p.id!==i:!0)&&p.parent===(l==null?void 0:l.id)&&p.lang===n)&&t.jsx("p",{className:"mt-2 text-xs text-red-500",children:"A page for this language already exists."})]}):n&&t.jsx(c.Alert,{variant:"destructive",children:t.jsxs("p",{className:"mx-auto w-5/6 text-center",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:Se[n]})," page in the parent to add here."]})})})},Ui=({onSubmit:e,edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o,parentHasSelectedLanguagePage:u,id:h,pages:d,isNonSlugPageType:m,isHomePage:j,useLanguagePrefix:y,slug:p,isSlugValid:g,isPending:v})=>t.jsxs("form",{onSubmit:e,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ka,{edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o}),t.jsx(Pa,{lang:n,name:r,setName:l,parentHasSelectedLanguagePage:u})]}),t.jsx(Ia,{parentHasSelectedLanguagePage:u,name:r,lang:n,slug:p,edit:s,id:h,primaryPageObject:o,pages:d,isNonSlugPageType:m,isHomePage:j,useLanguagePrefix:y,isSlugValid:g,isPending:v})]}),qi=({loading:e,onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:h,isNonSlugPageType:d,isRootPage:m,useLanguagePrefix:j,setUseLanguagePrefix:y,isHomePage:p,parentSlug:g,slug:v,setSlug:w,isSlugValid:E,setIsSlugValid:P,getSlug:D,isPending:A,id:I,pages:O})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(S.Loader,{className:"animate-spin"})}):d?t.jsx(Ui,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:h,id:I,pages:O,isNonSlugPageType:d,isHomePage:p,useLanguagePrefix:j,slug:v,isSlugValid:E,isPending:A}):t.jsxs("form",{onSubmit:s,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ka,{edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u}),t.jsx(Pa,{lang:a,name:i,setName:o,parentHasSelectedLanguagePage:h}),t.jsx(Fi,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:d,isRootPage:m,lang:a,useLanguagePrefix:j,setUseLanguagePrefix:y,isHomePage:p,parentSlug:g,parentHasSelectedLanguagePage:h,slug:v,setSlug:w,isSlugValid:E,setIsSlugValid:P,getSlug:D})]}),t.jsx(Ia,{parentHasSelectedLanguagePage:h,name:i,lang:a,slug:v,edit:n,id:I,primaryPageObject:u,pages:O,isNonSlugPageType:d,isHomePage:p,useLanguagePrefix:j,isSlugValid:E,isPending:A})]}),$i=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:l=[]}=dt(),o=x.useMemo(()=>l.find(K=>K.id===a),[l,a]),[u,h]=x.useState(""),[d,m]=x.useState(""),[j,y]=x.useState(""),[p,g]=x.useState(!0),[v,w]=x.useState(!0),{mutate:E,isPending:P}=Aa(),{mutate:D,isPending:A}=wn(),I=P||A,{data:O,isFetching:Y}=Ve(),ee=We(),{data:L,isFetching:q}=Ue(a),{data:F=[],isFetching:z}=Ue(o==null?void 0:o.parent),{data:G=[],isFetching:Q}=Ce(),{setSelectedLang:ae}=$.useLanguages(),[,je]=Pe(),[,Ne]=$.useSidebarActivePanel(),ce=Y||q||z||Q,N=x.useMemo(()=>f.filter(O==null?void 0:O.languages,K=>!f.find(L,{lang:K})),[O,L]),b=x.useMemo(()=>G.find(K=>K.key===(o==null?void 0:o.pageType)),[G,o==null?void 0:o.pageType]),C=!(b!=null&&b.hasSlug),M=(o==null?void 0:o.slug)==="/";x.useEffect(()=>{if(!r&&o&&i&&(m(i),h(`${o.name} - ${Se[i]}`)),!r||!o)return;const K=L==null?void 0:L.find(_=>_.id===e);if(!K)return;h(K.name),m(K.lang);const ie=K.slug||"",{initSlug:me,prefix:xe}=Ri(ie,o);y(me),w(xe)},[r,e,L,o,i]),x.useEffect(()=>{if(i)m(i);else if((N==null?void 0:N.length)===1&&!r){const K=N[0];if(!K||!Se[K])return;m(K),(!u||u===(o==null?void 0:o.name))&&h(`${o==null?void 0:o.name} - ${Se[K]}`)}},[i,N,r,u,o]);const{parentSlug:T,isRootPage:B}=x.useMemo(()=>{if(M||!d)return{parentSlug:void 0,isRootPage:!(o!=null&&o.parent)};if(!(o!=null&&o.parent))return{parentSlug:v?`/${d}`:void 0,isRootPage:!0};const K=F==null?void 0:F.find(ie=>ie.lang===d);return{parentSlug:K==null?void 0:K.slug,isRootPage:!1}},[o==null?void 0:o.parent,F,v,d,M]),H=x.useMemo(()=>B?!0:!!(F!=null&&F.some(K=>(K==null?void 0:K.lang)===d)),[d,F,B]),V=()=>{let K="";return B?K=`/${v?[d,j].filter(Boolean).join("/"):j}`:K=`${nt(T)}/${j}`,K.replace(/\/{2,}/g,"/").replace(/\/$/,"")},J=K=>{const ie=new URLSearchParams(window.location.search);ee&&K===ee?ie.delete("lang"):ie.set("lang",K),je(ie),window.dispatchEvent(new PopStateEvent("popstate"))},re=K=>{K.preventDefault();const ie={name:u,lang:d,primaryPage:o==null?void 0:o.id,slug:C?"":V(),pageType:o==null?void 0:o.pageType,...r&&{id:e}},me=()=>{!r&&d&&(ae(d),J(d)),Ne("outline"),n()};r?D(ie,{onSuccess:me}):E(ie,{onSuccess:me})};return t.jsx(c.Dialog,{open:s,onOpenChange:n,children:t.jsxs(c.DialogContent,{className:"text-slate-600 sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:r?le.EDIT_LANGUAGE:le.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:le.ENTER_LANGUAGE_DETAILS})]}),t.jsx(qi,{id:e,pages:l,loading:ce,onSubmit:re,edit:r,lang:d,languages:N,name:u,setLang:m,setName:h,primaryPageObject:o,parentHasSelectedLanguagePage:H,isNonSlugPageType:C,isRootPage:B,useLanguagePrefix:v,setUseLanguagePrefix:w,isHomePage:M,parentSlug:T,slug:j,setSlug:y,isSlugValid:p,setIsSlugValid:g,getSlug:V,isPending:I})]})})};function zi({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=x.useState(null),o=x.useRef(null),[u,h]=x.useState(a+e);x.useEffect(()=>{h(a+e)},[e,a]);const d=y=>{const p=y.target.value;if(!p.startsWith(a)){const D=p.replace(a,""),A=a+D;h(A),s(D);return}const v=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),w=(v.match(/\./g)||[]).length,E=w<=1;w>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(E);const P=a+v;h(P),s(v)},m=()=>{if(o.current){const y=o.current;setTimeout(()=>{const p=a.length;y.setSelectionRange(p,p)},0)}},j=y=>{const p=y.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const v=a.length;p.setSelectionRange(v,v)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:o,value:u,onChange:d,onFocus:m,onClick:j,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const Cs=({children:e,onWheel:s,...n})=>{const a=r=>{try{r.preventDefault();const i=r.currentTarget;i.scrollTop+=r.deltaY}catch{r.preventDefault()}s&&s(r)};return t.jsx(c.CommandList,{...n,onWheel:a,children:e})},Ys=(...e)=>e.filter(Boolean).join(" ");function Vi({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage",currentPage:i}){const[l,o]=x.useState(!1),[u,h]=x.useState(""),d=$.useChaiFeatureFlag("enable-add-page-dropdown");d||(a="w-full rounded-md border border-gray-300 px-3 py-2");const m=x.useMemo(()=>!e||e.length===0?[]:e.filter(E=>!f.isEmpty(E.slug)).filter(E=>E.slug!=="/").sort((E,P)=>E.slug.localeCompare(P.slug)),[e]),j=x.useMemo(()=>{if(!u.trim())return m;const w=u.toLowerCase();return m.filter(E=>E.name.toLowerCase().includes(w)||E.slug.toLowerCase().includes(w))},[m,u]),y=w=>Math.max(0,(w.match(/\//g)||[]).length-1),p=w=>"    ".repeat(w),g=w=>{if(w==="/")return"/";const E=w.split("/").filter(Boolean);if(E.length<=1){const P=E[0]||"";return`/${nt(P)}`}return`/${nt(E[E.length-1])}`},v=()=>{if(!s||s==="none")return"None";const w=m.find(E=>E.id===s);return w?`${w.name} (${g(w.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),d?t.jsxs(c.Popover,{open:l,onOpenChange:o,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{id:r,variant:"outline",role:"combobox",className:Ys("w-full justify-between",a),"data-testid":"parent-page-selector",children:[v(),t.jsx(S.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"relative border-none py-2",children:t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(S.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"h-8 pl-8 text-xs",value:u,onChange:w=>h(w.target.value)})]})})}),t.jsxs(Cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No pages found."}),t.jsxs(c.CommandGroup,{children:[t.jsxs(c.CommandItem,{value:"none",onSelect:()=>{n(""),o(!1),h("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(S.Check,{className:Ys("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),j.map(w=>{const E=p(y(w.slug)),P=g(w.slug),D=t.jsxs("span",{className:"flex items-center text-sm",children:[E,w.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",P,")"]})]});return t.jsxs(c.CommandItem,{value:w.id,onSelect:()=>{n(w.id),o(!1),h("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:D}),t.jsx(S.Check,{className:Ys("mr-2 h-4 w-4 shrink-0",s===w.id?"opacity-100":"opacity-0")})]},w.id)})]})]})]})})]}):t.jsxs("select",{id:r,value:s||"none",onChange:w=>n(w.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),m.map(w=>{const E=y(w.slug),P=E>0?p(E):"",D=g(w.slug);return(i==null?void 0:i.id)===w.id||w.slug.startsWith(i==null?void 0:i.slug)?null:t.jsxs("option",{value:w.id,children:[P,w.name," (",D,")"]},w.id)})]})]})}const Ki=(...e)=>e.filter(Boolean).join(" "),Hi=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=x.useState(""),[l,o]=x.useState(!1),[u,h]=x.useState(""),d=$.useChaiFeatureFlag("enable-add-page-dropdown");if(x.useEffect(()=>{if(s){const g=e.find(v=>v.id===s);i((g==null?void 0:g.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex h-fit items-center justify-center text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const m={};e.forEach(g=>{const v=g.libraryName;m[v]||(m[v]=[]),m[v].push(g)});const j=Object.entries(m).reduce((g,[v,w])=>{const E=w.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())||v.toLowerCase().includes(u.toLowerCase()));return E.length>0&&(g[v]=E),g},{}),y=e.find(g=>g.id===s),p=y?f.startCase(y.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[d?t.jsxs(c.Popover,{open:l,onOpenChange:o,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[p,t.jsx(S.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(S.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search templates...",className:"h-8 pl-8 text-xs",value:u,onChange:g=>h(g.target.value)})]})}),t.jsxs(Cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(j).map(([g,v])=>t.jsx(c.CommandGroup,{heading:g,children:v.map(w=>t.jsxs(c.CommandItem,{value:w.id,onSelect:()=>{n(w.id),o(!1),h("")},className:"flex cursor-pointer items-center justify-between",children:[f.startCase(w.name),t.jsx(S.Check,{className:Ki("mr-2 h-4 w-4",s===w.id?"opacity-100":"opacity-0")})]},w.id))},g))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:g=>n(g.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(m).map(([g,v])=>t.jsx("optgroup",{label:g,children:v.map(w=>t.jsx("option",{value:w.id,children:f.startCase(w.name)},w.id))},g))]}),r&&t.jsxs("div",{className:"mt-3 overflow-hidden rounded border",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:r,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"border-t bg-gray-50 p-2 text-xs text-gray-500",children:"Template preview"})]})]})},Qi=()=>{const e=oe(),s=Z();return U.useQuery({queryKey:[R.GET_LIBRARIES],queryFn:async()=>await s(e,{action:R.GET_LIBRARIES})||[]})},Wi=e=>{const s=oe(),n=Z();return U.useQuery({queryKey:[R.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:R.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?f.filter(a,{pageType:e}):a)||[]}})},Ji=e=>{const{data:s=[],isLoading:n}=Wi(e),{data:a=[],isLoading:r}=Qi(),i=x.useMemo(()=>n||r?[]:s.map(o=>{const u=f.find(a,{id:o.library});return{...o,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=x.useMemo(()=>f.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},Rs=()=>{const[,e]=Pe();return x.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},qt=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:"",metaOther:""},jsonLD:{},metaOther:{}};e!=null&&e.defaultSeo&&(f.has(e.defaultSeo,s)&&f.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};e!=null&&e.defaultJSONLD&&(f.has(e.defaultJSONLD,s)&&f.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],f.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,f.set(n,"seo.jsonLD",JSON.stringify(a))));let r={};return e!=null&&e.defaultMetaTags&&(f.has(e.defaultMetaTags,s)&&f.isObject(e.defaultMetaTags[s])?(r=e.defaultMetaTags[s],f.set(n,"seo.metaOther",JSON.stringify(r))):(r=e.defaultMetaTags,f.set(n,"seo.metaOther",JSON.stringify(r)))),{seo:n.seo,jsonLD:n.jsonLD,metaOther:r}},rt=(...e)=>e.filter(Boolean).join(" ");function Yi({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var xs,gs;const r=Rs(),i=!!(e!=null&&e.id),{data:l}=dt(),{mutate:o,isPending:u}=Aa(),{mutate:h,isPending:d}=wn(),[m,j]=x.useState(null),[y,p]=x.useState(!0),[g,v]=x.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:w}=$.usePermissions(),E=w(ve.CHANGE_PAGE_TYPE),[P,D]=x.useState(!1),[A,I]=x.useState(""),{selectedLang:O,fallbackLang:Y}=$.useLanguages(),ee=O||Y,[L,q]=x.useState(""),[F,z]=x.useState(!1),G=x.useMemo(()=>{const k=s.find(ue=>ue.key===g);return(k==null?void 0:k.hasSlug)===!1},[g,s]),[Q,ae]=x.useState((e==null?void 0:e.parent)??""),[je,Ne]=x.useState((e==null?void 0:e.name)??""),[ce,N]=x.useState((e==null?void 0:e.dynamic)??!1),[b,C]=x.useState(ce?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[M,T]=x.useState((e==null?void 0:e.dynamicSlugCustom)??""),[B,H]=x.useState(!0),[V,J]=x.useState(!1),[re,K]=x.useState(""),{data:ie,isLoading:me}=Ji(g),xe=u||d,_=$.useChaiFeatureFlag("enable-add-page-dropdown"),se=x.useMemo(()=>!i||!(e!=null&&e.id)||!l?null:l.find(k=>k.id===e.id),[i,e==null?void 0:e.id,l]),Ee=(se==null?void 0:se.online)||!1,Le=x.useMemo(()=>!i||!(e!=null&&e.id)||!l?!1:l.some(k=>k.parent===e.id),[i,e==null?void 0:e.id,l]),X=s.find(k=>k.key===g),_e=k=>{if(i&&g!==k){I(k),D(!0),q(""),z(!1);return}v(k),q(""),z(!1)},Be=()=>{v(A),D(!1),N(!1)},$s=k=>{N(k),k?C(""):T("")},zs=k=>{if(ae(k),k&&k!=="none"){const ue=l==null?void 0:l.find(De=>De.id===k),Ge=(ue==null?void 0:ue.slug)||"";if(b.startsWith(Ge)){const De=b.slice(Ge.length).replace(/^\/+/,"");C(De)}else C(b.replace(/^\/+/,""))}else C(b?`${b}`:"")},Vs=k=>{K(k)},ms=()=>je.trim()?ce&&!f.isEmpty(b)?(j("Slug must be empty when using dynamic slug"),!1):ce&&!B?(j("Dynamic slug is invalid"),!1):!0:(W.toast.error("Name is required"),!1),Ks=()=>{const k={pageType:X==null?void 0:X.key,name:je,slug:"",hasSlug:!1};i?h({id:e==null?void 0:e.id,name:je},{onSuccess:()=>{W.toast.success((X==null?void 0:X.name)+" updated successfully"),n()}}):o(k,{onSuccess:ue=>{n(),r(ue.page.id,a)}})},fs=(k,ue)=>{if(!k.trim()&&!ce)return j("Child page slug is required"),!1;const Ge=nt(ue),De=Un(Ge,k);return Object.keys(Se).some(ps=>De===`/${ps}`||(De==null?void 0:De.startsWith(`/${ps}/`)))?(j("Slugs cannot start with a language code for primary page"),!1):!0},Hs=(k,ue)=>{const Ge=nt(ue),De=Un(Ge,k),Re={pageType:g,name:je,slug:De.replace(/\/$/,""),parent:Q,dynamic:ce,hasSlug:!0,template:re||void 0,tracking:{},seo:{},jsonLD:{}};if(ce&&(Re.dynamicSlugCustom=M),i){const Fe=f.pick(Re,["pageType","parent","name","slug","dynamic","dynamicSlugCustom"]);h({id:e==null?void 0:e.id,...Fe},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}})}else{const Fe=f.find(s,{key:g});Fe!=null&&Fe.trackingDefault&&(Re.tracking=Fe.trackingDefault);const{seo:ps,jsonLD:_r}=qt(Fe,ee);f.set(Re,"seo",ps),f.set(Re,"jsonLD",_r),o(Re,{onSuccess:Dr=>{n(),r(Dr.page.id,a)}})}},Qs=()=>{const k={pageType:g,name:je,slug:b===""?"/":`/${b.replace(/\/$/,"")}`,template:re||void 0,parent:null,tracking:{}};if(i)h({id:e==null?void 0:e.id,...k},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}});else{const ue=f.find(s,{key:g});ue!=null&&ue.trackingDefault&&(k.tracking=ue.trackingDefault);const{seo:Ge,jsonLD:De}=qt(ue,ee);f.set(k,"seo",Ge),f.set(k,"jsonLD",De),o(k,{onSuccess:Re=>{var Fe;(Fe=Re==null?void 0:Re.page)!=null&&Fe.id&&r(Re.page.id,a),n()}})}},Ot=k=>{if(k.preventDefault(),j(null),!!ms()){if(!(X!=null&&X.hasSlug)){Ks();return}if(Q&&Q!=="none"){const ue=l==null?void 0:l.find(De=>De.id===Q),Ge=(ue==null?void 0:ue.slug)||"";if(!fs(b,Ge))return;Hs(b,Ge)}else Qs()}},{pagesType:mt,partialsType:Ze}=x.useMemo(()=>{const k=ue=>L?ue.name.toLowerCase().includes(L.toLowerCase())||ue.key.toLowerCase().includes(L.toLowerCase()):!0;return{pagesType:s.filter(ue=>ue.hasSlug!==!1&&k(ue)),partialsType:s.filter(ue=>ue.hasSlug===!1&&k(ue))}},[s,L]);return X!=null&&X.hasSlug?t.jsxs("form",{onSubmit:Ot,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),_?t.jsxs(c.Popover,{open:F,onOpenChange:z,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:rt("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(X==null?void 0:X.name)||"Select page type",t.jsx(S.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(S.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:L,onChange:k=>q(k.target.value)})]})}),t.jsxs(Cs,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),i?G?t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(k=>t.jsxs(c.CommandItem,{value:k.key,onSelect:()=>_e(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(S.Check,{className:rt("mr-2 h-4 w-4",g===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:mt.map(k=>t.jsxs(c.CommandItem,{value:k.key,onSelect:()=>_e(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(S.Check,{className:rt("mr-2 h-4 w-4",g===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsxs(t.Fragment,{children:[mt.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:mt.map(k=>t.jsxs(c.CommandItem,{value:k.key,onSelect:()=>_e(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(S.Check,{className:rt("mr-2 h-4 w-4",g===k.key?"opacity-100":"opacity-0")})]},k.key))}),Ze.length>0&&t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(k=>t.jsxs(c.CommandItem,{value:k.key,onSelect:()=>_e(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(S.Check,{className:rt("mr-2 h-4 w-4",g===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:g,disabled:i&&!E,onChange:k=>_e(k.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!E?"cursor-not-allowed text-gray-500":""}`,children:i?G?t.jsx("optgroup",{label:"Partials",children:s.filter(k=>k.hasSlug===!1).map(k=>t.jsx("option",{value:k.key,children:k.name},k.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(k=>k.hasSlug!==!1).map(k=>t.jsx("option",{value:k.key,children:k.name},k.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(k=>k.hasSlug!==!1).map(k=>t.jsx("option",{value:k.key,children:k.name},k.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(k=>k.hasSlug===!1).map(k=>t.jsx("option",{value:k.key,children:k.name},k.key))})]})}),P&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>D(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]})]}),!i&&(X==null?void 0:X.hasSlug)&&ie.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(Hi,{templates:ie,selectedTemplateId:re,onSelectTemplate:Vs,isLoading:me})]}),t.jsx(Vi,{pages:l,selectedParentId:Q,onChange:zs,currentPage:e}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:je,onChange:k=>Ne(k.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(X==null?void 0:X.dynamicSegments)&&Q&&Q!=="none"&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("input",{type:"checkbox",id:"useDynamicSlug",checked:ce,onChange:k=>$s(k.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ce&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(zi,{value:M,onChange:T,dynamicPattern:(X==null?void 0:X.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:H})})})]}),(!(X!=null&&X.dynamicSegments)||!ce)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(En,{value:b,onChange:k=>{var ue;C(k),i&&k!==(((ue=e==null?void 0:e.slug)==null?void 0:ue.split("/").pop())||"")?J(!!(Ee||Le)):J(!1)},placeholder:Q&&Q!=="none"?"Enter page slug":g==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:Q&&Q!=="none"?(gs=l==null?void 0:l.find(k=>k.id===Q))==null?void 0:gs.slug:void 0,onValidationChange:p}),m&&t.jsx("p",{className:"text-xs text-red-500",children:m}),V&&t.jsx("div",{className:"mt-4 rounded-md border border-amber-200 bg-amber-50 p-3",children:t.jsxs("div",{className:"flex items-start space-x-2",children:[t.jsx("div",{className:"flex-shrink-0",children:t.jsx("svg",{className:"h-5 w-5 text-amber-400",viewBox:"0 0 20 20",fill:"currentColor",children:t.jsx("path",{fillRule:"evenodd",d:"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})})}),t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"text-sm font-medium text-amber-800",children:"Slug Change Warning"}),t.jsx("div",{className:"mt-1 text-sm text-amber-700",children:t.jsx("p",{children:"The previous URL and any child pages will become inaccessible. You may want to set up a redirect to avoid broken links."})})]})]})})]}),t.jsx(c.Button,{disabled:xe||!y&&(!(X!=null&&X.dynamicSegments)||!ce)||ce&&!B,type:"submit",className:"w-full",children:i?xe?"Updating...":"Update page":xe?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Ot,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),_?t.jsxs(c.Popover,{open:F,onOpenChange:z,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:rt("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(X==null?void 0:X.name)||"Select page type",t.jsx(S.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(S.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:L,onChange:k=>q(k.target.value)})]})}),t.jsxs(Cs,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(k=>t.jsxs(c.CommandItem,{value:k.key,onSelect:()=>{_e(k.key),z(!1)},className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(S.Check,{className:rt("mr-2 h-4 w-4",g===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:g,disabled:i&&!E,onChange:k=>_e(k.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!E?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(k=>k.hasSlug===!1).map(k=>t.jsx("option",{value:k.key,children:k.name},k.key))})}),P&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>D(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(xs=s.find(k=>k.key===g))==null?void 0:xs.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:je,onChange:k=>Ne(k.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:xe,type:"submit",className:"w-full",children:i?xe?"Updating...":"Update "+(X==null?void 0:X.name):xe?"Creating...":"Create "+(X==null?void 0:X.name)})]})}const Cn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Ce(),r=!!(e!=null&&e.id);return console.log(e),t.jsx(c.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsxs(c.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(c.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(Yi,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function Gs({page:e,onClose:s}){const[,n]=Pe(),{mutate:a,isPending:r}=Ai(),{data:i}=Ce(),{setSelectedLang:l,fallbackLang:o}=$.useLanguages(),[,u]=$.useSidebarActivePanel(),h=()=>{r||a(e,{onSuccess:()=>{e!=null&&e.primaryPage?(window.history.replaceState({},"",`/?page=${e.primaryPage}`),n(new URLSearchParams({page:e.primaryPage}))):(window.history.replaceState({},"","/"),n(new URLSearchParams)),window.dispatchEvent(new PopStateEvent("popstate")),l(o),u("outline"),s()}})},d=i==null?void 0:i.find(m=>m.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",d!=null&&d.hasSlug?(d==null?void 0:d.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:f.get(Se,e.lang,e.lang)})]})]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:r,onClick:h,children:r?"Deleting...":"Delete"})]})]})})}const Xi=()=>{const e=oe(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const l={pageId:a,name:r};return i&&(l.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),W.toast.success("Page duplicated successfully")},onError:a=>{W.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Tn=({page:e,onClose:s,closePanel:n=()=>{}})=>{const{mutate:a,isPending:r}=Xi(),[i,l]=x.useState(null),[o,u]=x.useState(`${e.name} (Copy)`),h=Rs(),d=f.isEmpty(e.slug),[m,j]=x.useState(d?"":`${e.slug.split("/").pop()}-copy`),y=d?"":f.initial(e.slug.split("/")).join("/"),[p,g]=x.useState(!1),v=w=>{if(w.preventDefault(),!o.trim()){l("Name is required");return}if(!d&&!m.trim()){l("Slug is required");return}l(null),g(!0);const E={pageId:e.id,name:o};d||(E.slug=`${y}/${m}`),a(E,{onSuccess:P=>{g(!1),s(),h(P.id,n)},onError:P=>{g(!1),P.code==="SLUG_EXISTS"?l("A page with this slug already exists. Please choose a different slug."):P.code==="INVALID_SLUG"?l("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):P.code==="PERMISSION_DENIED"?l("You don't have permission to duplicate this page."):l(P.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Duplicate Page"}),t.jsx(c.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!d&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:v,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:o,onChange:w=>u(w.target.value),required:!0})]}),!d&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(En,{value:m,onChange:w=>j(w),parentSlug:y,onValidationChange:w=>{l(w?null:"Invalid slug")}})]}),i&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(S.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:i})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:!o.trim()||!d&&!m.trim()||r||p,children:r||p?"Duplicating...":"Duplicate"})]})]})]})})},Zi=1*1024*1024,An=({page:e,onClose:s})=>{const[n,a]=x.useState(!1),[r,i]=x.useState(""),[l,o]=x.useState(""),[u,h]=x.useState(!1),d=x.useRef(null),m=Pi(),{data:j}=Ce(),y=j==null?void 0:j.find(P=>P.key===e.pageType),p=(y==null?void 0:y.name)||f.startCase(e.pageType),g=x.useCallback(P=>{var A;const D=(A=P.target.files)==null?void 0:A[0];if(D){if(D.size>Zi){W.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(D.size/1024).toFixed(2)}KB.`}),d.current&&(d.current.value="");return}try{h(!0);const I=new FileReader;I.onloadend=()=>{o(I.result),h(!1)},I.readAsDataURL(D)}catch(I){console.error("Error reading file:",I),h(!1),W.toast.error("Failed to process image",{description:I instanceof Error?I.message:"Unknown error"})}}},[]),v=()=>{o(""),d.current&&(d.current.value="")},w=()=>{var P;(P=d.current)==null||P.click()},E=()=>{a(!0),m.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(S.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:f.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(S.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:P=>i(P.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:d,onChange:g,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:w,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(S.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:v,children:t.jsx(S.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:P=>{P.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:E,children:"Mark as template"})]})]})})},kn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:o,isLanguagePage:u})=>{const{hasPermission:h}=$.usePermissions(),{data:d}=Ce(),m=x.useMemo(()=>f.find(d,{key:e.pageType}),[d,e.pageType]),j=x.useMemo(()=>!!e.isTemplate,[e.isTemplate]),y=x.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!h(ve.EDIT_PAGE)&&!h(ve.DELETE_PAGE)&&!h(ve.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:g=>g.stopPropagation(),children:o}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[h(ve.ADD_PAGE)&&!u&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:g=>{g.stopPropagation(),s(e)},children:[t.jsx(S.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),h(ve.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:g=>{g.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(S.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&h(ve.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:g=>{g.stopPropagation(),a(e)},children:[t.jsx(S.Power,{className:"size-3"}),le.UNPUBLISH]}),h(ve.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:g=>{g.stopPropagation(),r(e)},children:[t.jsx(S.Trash,{className:"size-3"}),le.DELETE]}),h(ve.MARK_AS_TEMPLATE)&&y&&!u&&t.jsx(t.Fragment,{children:j?t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:g=>{g.stopPropagation(),l(e)},children:[t.jsx(S.SquareLibrary,{className:"size-3"}),le.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:g=>{g.stopPropagation(),i(e)},children:[t.jsx(S.SquareLibrary,{className:"size-3"}),le.MARK_AS_TEMPLATE]})})]})]})},Pn=({page:e,onClose:s})=>{const[n,a]=x.useState(!1),r=Ii(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Unmark as template"}),t.jsx(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},hs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=ki(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[le.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:r,children:a?le.UPDATING:le.UNPUBLISH})]})]})})},el=ua("expandedPagesState",[]),In=e=>f.flatMap(e,s=>[s,...s.children?In(s.children):[]]),tl=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const l=[...r,i.id];if(i.id===s)return l;if(i.children&&i.children.length>0){const o=n(i.children,l);if(o)return o}}return null};return n(e)||[]},_a=(e,s)=>{if(!s)return[];const n=In(e),a=f.find(n,r=>r.id===s);if(a){if(a.parent)return[..._a(e,a.parent),s];const r=tl(e,s);if(!f.isEmpty(r))return r}return[s]},sl=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(o=>s.add(o)),i.children&&!f.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},Bt=e=>{const[s,n]=pe.useAtom(el),a=e?f.includes(s,e):!1,r=x.useCallback(()=>{n(h=>a?f.filter(h,d=>d!==e):[...h,e])},[n,a,e]),i=x.useCallback((h,d)=>{if(!d||f.isEmpty(h))return;const m=In(h),j=_a(m,d);if(!Array.isArray(j)||f.isEmpty(j))return;const y=j.slice(0,-1);f.isEmpty(y)||n(p=>f.uniq([...p,...y]))},[n]),l=x.useCallback(h=>{if(f.isEmpty(h))return;const d=sl(h);f.isEmpty(d)||n(m=>f.union(m,d))},[n]),o=x.useCallback(h=>{if(f.isEmpty(h))return;const d=f.flatMap(h,m=>{const j=y=>[y.id,...y.children?f.flatMap(y.children,j):[]];return j(m)});n(d)},[n]),u=x.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:o,collapseAll:u}},qn=(e,s)=>!e||!Array.isArray(e)?[]:f.isEmpty(s)?e:f.compact(f.filter(e,n=>{const a=f.toLower(s);return f.includes(f.toLower((n==null?void 0:n.name)||""),a)||f.includes(f.toLower((n==null?void 0:n.slug)||""),a)})),nl=(e,s)=>{const n=new Set,a=f.keyBy(e,"id");return s.forEach(r=>{let i=r;for(;i.parent&&a[i.parent];)n.add(i.parent),i=a[i.parent]}),Array.from(n).map(r=>a[r])},an=(e,s,n)=>f.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?an(a.children,s,n):[]};const r=a.children&&a.children.some(i=>f.includes(f.toLower(i.name||""),f.toLower(s))||f.includes(f.toLower(i.slug||""),f.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?an(a.children,s,n):[]}}),al=e=>{if(!e||!e.length)return[];const s={};e.forEach(a=>{s[a.id]={...a,children:[]}});const n=[];return Object.values(s).forEach(a=>{a.parent&&s[a.parent]?s[a.parent].children.push(a):n.push(a)}),n},Da=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Da(n.children):[]})),La=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=f.compact(f.filter(e,{pageType:n}))),f.isEmpty(s))r=qn(r,s);else{const d=qn(r,s),m=nl(e,d);r=f.uniqBy([...d,...m],"id")}const i=Da(al(r)),l=an(i,s,a),o=f.filter(l,d=>a(d.pageType)).sort((d,m)=>(d.name||"").localeCompare(m.name||"")),u=f.filter(l,d=>!a(d.pageType));let h=[];if(n==="all"){const d=f.keyBy(u,"pageType");h=Object.values(f.mapValues(d,(m,j)=>({...m,id:j,name:f.startCase(j),isPartialGroup:!0,children:l.filter(y=>y.pageType===j)})))}else h=u.sort((d,m)=>(d.name||"").localeCompare(m.name||""));return[...o,...h]},rl=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:h,hasChildren:d,isExpanded:m,onToggleExpand:j})=>{const y=Rs(),{data:p}=Ce(),[,g]=$.useSidebarActivePanel(),v=x.useMemo(()=>f.find(p,{key:s.pageType}),[p,s.pageType]),w=x.useMemo(()=>{const A=f.get(s,"slug",""),I=e?nt(e):"",O=I?A.replace(I,""):A;return O||"/"},[s,e]),E=x.useMemo(()=>!!s.isTemplate,[s.isTemplate]),P=x.useCallback(()=>{g("outline"),y(f.get(s,"id"),a)},[y,a,s,g]),D=x.useCallback(A=>{A.stopPropagation(),j()},[j]);return t.jsxs("div",{onClick:s.isPartialGroup?D:P,className:`flex cursor-pointer items-center justify-between rounded p-1.5 px-3 py-1.5 leading-none ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("button",{onClick:D,disabled:!d,className:`flex h-5 w-4 items-center justify-center text-gray-400 transition-colors hover:text-gray-500 ${d?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(S.ChevronRight,{size:16,className:`h-5 w-4 transition-transform duration-200 ${m?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",children:t.jsx(S.StarsIcon,{className:"h-4 w-4 text-yellow-400"})}):v!=null&&v.icon?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:v.icon}}):v!=null&&v.hasSlug?t.jsx(S.File,{className:"h-4 w-4 stroke-[1] text-slate-500"}):t.jsx(S.Globe,{className:"h-4 w-4 stroke-[1] text-slate-500"}),!s.isPartialGroup&&t.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"truncate font-light leading-none text-slate-800",children:s.name}),v!=null&&v.hasSlug?t.jsxs(c.Badge,{variant:"outline",className:`ml-2 max-w-full rounded-full border py-px text-xs font-normal leading-tight text-gray-400 ${n?"border-gray-300":"border-gray-200"}`,children:[w,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[f.endsWith(w,"/")?`${v==null?void 0:v.dynamicSlug}`:`/${v==null?void 0:v.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(c.Badge,{variant:"outline",className:`ml-2 max-w-full rounded-full border py-px text-xs font-normal leading-tight text-gray-400 ${n?"border-gray-300":"border-gray-200"}`,children:v==null?void 0:v.name}),E&&t.jsx(c.Badge,{variant:"outline",className:"ml-2 border border-blue-200 bg-blue-50 py-0 text-xs font-normal text-blue-500",children:"Template"})]}),!s.isPartialGroup&&t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(di,{currentEditor:s.currentEditor}),t.jsx(kn,{page:s,setDuplicatePage:h,setAddEditPage:l,setUnpublishPage:r,setDeletePage:i,setMarkAsTemplate:o,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"m-0 cursor-pointer rounded p-0.5 duration-100 hover:bg-white",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4",onClick:A=>A.stopPropagation()})})})]})]})},il=({close:e})=>{const[,s]=x.useState([]),[n,a]=x.useState(null),[r,i]=x.useState(""),[l,o]=x.useState(""),[u,h]=x.useState(null),d=T=>l?String(f.get(T,"name","")).toLowerCase().includes(l.toLowerCase())||String(f.get(T,"key","")).toLowerCase().includes(l.toLowerCase()):!0,[m,j]=x.useState(null),[y,p]=x.useState(null),[g,v]=x.useState(null),[w,E]=x.useState(null),{data:P,isFetching:D}=dt(),[A,I]=x.useState(""),{hasPermission:O}=$.usePermissions(),{updateForSelectedPage:Y,expandPagesOnSearch:ee,expandAll:L,collapseAll:q}=Bt(null),[F,z]=Pe(),G=F.get("page"),Q=x.useRef(null),{data:ae}=Ce(),je=$.useChaiFeatureFlag("enable-add-page-dropdown"),Ne=x.useCallback(T=>{var B;return(B=f.find(ae,{key:T}))==null?void 0:B.hasSlug},[ae]);x.useEffect(()=>{if(!f.isEmpty(A))return;const T=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(ae)&&T&&(f.find(ae,{key:T})?I(T):I("all"))},[ae,A]);const ce=T=>{I(T),sessionStorage.setItem("pageTypeFilter",T),o("")},N=x.useCallback(T=>{const H=new URLSearchParams(window.location.search).get("lang"),V=new URLSearchParams({page:T});H&&V.set("lang",H),window.history.pushState({},"",`?${V.toString()}`),z(V),window.dispatchEvent(new PopStateEvent("popstate")),e()},[z,e]);x.useEffect(()=>{if(G&&!D){const T=f.find(P,{id:G});T&&(T!=null&&T.pageType)?s(B=>[...B,T==null?void 0:T.pageType]):(window.history.replaceState(null,"","/"),z(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[P,G,D,z]);const b=x.useMemo(()=>P?La(P,r,A,Ne):[],[P,r,A,Ne]);x.useEffect(()=>{G&&!D&&!f.isEmpty(b)&&(Y(b,G),Q.current&&Q.current.scrollIntoView({behavior:"smooth",block:"end"}))},[G,D,b,Y]),x.useEffect(()=>{!f.isEmpty(r)&&!f.isEmpty(b)&&ee(b)},[r,b,ee]);const C=x.useCallback(()=>{L(b)},[L,b]),M=x.useCallback(()=>{q()},[q]);return t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsxs("div",{className:"flex h-full flex-col space-y-6",children:[t.jsxs("div",{className:"flex items-center justify-between gap-1",children:[t.jsxs("div",{className:"item-center relative flex flex-1 gap-x-4",children:[t.jsx(S.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"pl-9 pr-24 text-xs font-medium leading-none text-gray-700 placeholder:text-gray-400",value:r,onChange:T=>i(T.target.value)}),!f.isEmpty(A)&&t.jsxs(c.Select,{value:A,onValueChange:ce,children:[t.jsx(c.SelectTrigger,{className:`${A==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} absolute right-1.5 top-1.5 -mt-px h-max w-max min-w-[120px] whitespace-nowrap p-0 py-1 pl-2 pr-1 text-xs text-gray-600 shadow-none ring-0 focus:ring-0`,children:t.jsx(c.SelectValue,{placeholder:"Select page type"})}),t.jsxs(c.SelectContent,{align:"end",children:[je&&t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(S.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:l,onChange:T=>o(T.target.value),onKeyDown:T=>T.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!f.isEmpty(f.filter(ae,T=>T.hasSlug&&d(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Pages"}),f.map([...f.filter(ae,T=>T.hasSlug&&d(T))].sort((T,B)=>f.get(T,"name","").localeCompare(f.get(B,"name",""))),T=>t.jsx(c.SelectItem,{value:f.get(T,"key"),children:f.get(T,"name")},f.get(T,"key")))]}),!f.isEmpty(f.filter(ae,T=>!T.hasSlug&&d(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Partials"}),f.map([...f.filter(ae,T=>!T.hasSlug&&d(T))].sort((T,B)=>f.get(T,"name","").localeCompare(f.get(B,"name",""))),T=>t.jsx(c.SelectItem,{value:f.get(T,"key"),children:f.get(T,"name")},f.get(T,"key")))]}),f.isEmpty(f.filter(ae,d))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})]}),t.jsxs("div",{className:"flex gap-1",children:[t.jsx(c.Button,{variant:"outline",size:"icon",onClick:C,className:"p-1 text-gray-500",children:t.jsx(S.ChevronsUpDown,{})}),t.jsx(c.Button,{variant:"outline",size:"icon",onClick:M,className:"p-1 text-gray-500",children:t.jsx(S.ChevronsDownUp,{})})]})]}),D?t.jsx("div",{className:"space-y-2",children:f.map([...Array(5).keys()],T=>t.jsx("div",{className:"h-9 w-full animate-pulse rounded bg-gray-200"},T))}):f.isEmpty(b)?t.jsxs("div",{className:"flex h-[70vh] flex-col items-center justify-center gap-y-1 text-sm font-medium text-slate-500",children:[t.jsx(S.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"h-[70vh] space-y-2 overflow-y-auto text-sm text-slate-700",children:f.map(b,T=>{const B=T.id===G;return t.jsx("div",{ref:B?Q:null,children:t.jsx(Ba,{item:T,currentPage:G,close:e,setUnpublishPage:j,setDeletePage:h,setAddEditPage:p,setMarkAsTemplate:v,setUnmarkAsTemplate:E,setDuplicatePage:a,level:0})},`page-item-${T.id}`)})})]}),O(ve.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex gap-x-2 text-sm",onClick:()=>{p({slug:"",name:"",pageType:A==="all"?"page":A})},children:[t.jsx(S.Plus,{className:"h-4 w-4"})," Add New"]}),y&&t.jsx(Cn,{closePanel:e,editPage:N,addEditPage:y,setAddEditPage:p}),u&&t.jsx(Gs,{page:u,onClose:()=>h(null)}),m&&t.jsx(hs,{page:m,onClose:()=>j(null)}),g&&t.jsx(An,{page:g,onClose:()=>v(null)}),w&&t.jsx(Pn,{page:w,onClose:()=>E(null)}),n&&t.jsx(Tn,{page:n,onClose:()=>a(null),closePanel:e})]})},Ba=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:h,level:d=0})=>{const m=!f.isEmpty(e==null?void 0:e.children),{isExpanded:j,toggleExpanded:y}=Bt(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(rl,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:h,hasChildren:m,isExpanded:j,onToggleExpand:y}),m&&j&&t.jsx("div",{className:"bg-white pl-6 pt-2",children:f.map(f.get(e,"children",[]),p=>t.jsx(Ba,{item:p,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:d+1},p.id||`child-${d}-${p.key}`))})]},e.id||`level-${d}-${e.key}`)},ll=({selectedPageType:e,setSelectedPageType:s})=>{const[n,a]=x.useState(""),{data:r}=Ce(),i=o=>{if(!n)return!0;const u=n.toLowerCase(),h=d=>String(f.get(o,d,"")).toLowerCase().includes(u);return h("name")||h("key")},l=r.find(o=>o.key===e);return t.jsxs(c.Select,{onValueChange:s,value:e,children:[t.jsx(c.SelectTrigger,{className:`${e==="all"?"bg-gray-100/30 hover:bg-gray-100":"gap-x-1 border bg-gray-100/30 hover:bg-gray-100"} h-9 w-max min-w-[150px] overflow-hidden whitespace-nowrap rounded p-0 px-2 py-1 text-xs text-gray-600 shadow-none ring-0 focus:ring-0 [&>svg]:hidden`,children:t.jsxs("div",{className:"flex w-full items-center justify-between gap-x-1.5",children:[t.jsx("span",{className:"max-w-[150px] overflow-hidden truncate whitespace-nowrap font-medium leading-tight",children:(l==null?void 0:l.name)||"All"}),t.jsx(S.ListFilter,{className:`${e!=="all"?"fill-sky-50 text-sky-500":""} pointer-events-none h-4 w-4 text-muted-foreground hover:bg-blue-300`})]})}),t.jsxs(c.SelectContent,{children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white pb-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(S.Search,{strokeWidth:2,className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 w-full rounded border pl-8 text-xs shadow-none",value:n,onChange:o=>a(o.target.value),onKeyDown:o=>o.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"}),!f.isEmpty(f.filter(r,o=>o.hasSlug&&i(o)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Pages"}),f.map([...f.filter(r,o=>o.hasSlug&&i(o))].sort((o,u)=>f.get(o,"name","").localeCompare(f.get(u,"name",""))),o=>t.jsx(c.SelectItem,{value:f.get(o,"key"),children:f.get(o,"name")},f.get(o,"key")))]}),!f.isEmpty(f.filter(r,o=>!o.hasSlug&&i(o)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Partials"}),f.map([...f.filter(r,o=>!o.hasSlug&&i(o))].sort((o,u)=>f.get(o,"name","").localeCompare(f.get(u,"name",""))),o=>t.jsx(c.SelectItem,{value:f.get(o,"key"),children:f.get(o,"name")},f.get(o,"key")))]}),f.isEmpty(f.filter(r,i))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})},ol=({search:e,setSearch:s})=>t.jsxs("div",{className:"relative flex h-9 flex-1 items-center gap-2 rounded-md border px-2.5",children:[t.jsx("label",{htmlFor:"page-search-input",className:"sr-only",children:"Search Pages"}),t.jsx(S.Search,{className:`${e?"fill-sky-50 text-sky-500":""} pointer-events-none h-4 w-4 text-muted-foreground`,"aria-hidden":"true"}),t.jsx(c.Input,{id:"page-search-input",placeholder:"Search pages",value:e,onChange:n=>s(n.target.value),className:"border-none px-1.5 shadow-none outline-none ring-0 transition-none focus:outline-none focus:ring-0 focus-visible:ring-0",autoComplete:"off"})]}),cl=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Bt(null);return t.jsxs("div",{className:"flex gap-1",children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"icon",onClick:()=>s(e),className:"rounded p-1 text-gray-500",children:t.jsx(S.ChevronsUpDown,{})})}),t.jsx(c.TooltipContent,{children:"Expand All"})]}),t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{disabled:a.length===0,variant:"outline",size:"icon",onClick:()=>n(),className:"rounded p-1 text-gray-500",children:t.jsx(S.ChevronsDownUp,{})})}),t.jsx(c.TooltipContent,{children:"Collapse All"})]})]})},Ma=({languages:e,selectedLanguage:s,setSelectedLanguage:n})=>{const a=We();return t.jsx("div",{className:"scrollbar-hide flex gap-1 overflow-x-auto pb-1",children:e.map(r=>t.jsxs(c.Button,{variant:s===r?"default":"outline",size:"sm",className:`h-6 flex-shrink-0 whitespace-nowrap rounded px-3 text-xs font-normal ${s===r?"bg-black text-white hover:bg-black":"text-gray-500"}`,onClick:()=>n(r.toLowerCase()),children:[r===a&&t.jsx(S.Star,{size:4,className:`p-0.5 ${s===a?"fill-white":"fill-black"}`}),Se[r]||""]},r))})},$n=()=>{const e=U.useQueryClient();return t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"ghost",onClick:()=>e.invalidateQueries({queryKey:[R.GET_WEBSITE_PAGES]}),className:"mt-1 h-6 w-6",children:t.jsx(S.RefreshCw,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Refresh pages list"})]})},ul=({pages:e,search:s,setSearch:n,languages:a,onAddPage:r,selectedLanguage:i,setSelectedLanguage:l,selectedPageType:o,setSelectedPageType:u,showUntranslatedPages:h,setShowUntranslatedPages:d})=>{const m=a.length>1;return t.jsxs("div",{className:"space-y-3 border-b border-b-gray-200 px-4 pb-1",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(ll,{selectedPageType:o,setSelectedPageType:u}),t.jsx(ol,{search:s,setSearch:n}),t.jsx(cl,{pages:e}),t.jsxs(c.Button,{variant:"default",onClick:r,className:"rounded px-3 font-normal",children:[t.jsx(S.Plus,{strokeWidth:2,className:"stroke-white stroke-[3]"}),t.jsx("span",{className:"font-normal text-white",children:"Add Page"})]}),!m&&t.jsx($n,{})]}),m?t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(Ma,{languages:a,selectedLanguage:i,setSelectedLanguage:j=>{l(j),d(h&&(a==null?void 0:a[0])!==i)}}),t.jsxs("div",{className:"flex items-center gap-x-2",children:[(a==null?void 0:a[0])!==i&&t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",onClick:()=>d(!h),className:"h-6 rounded px-3 py-1 text-xs font-normal",children:h?t.jsx(S.FilterXIcon,{}):t.jsx(S.Filter,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Toggle Untranslated Pages"})]}),t.jsx($n,{})]})]}):t.jsx("div",{className:"flex items-center justify-between gap-2"})]})};function ct({children:e,content:s,side:n="bottom",delayDuration:a=700,showTooltip:r=!0}){return r?t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{delayDuration:a,children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:e}),t.jsx(c.TooltipContent,{side:n,sideOffset:10,children:t.jsx("p",{children:s})})]})}):e}const dl=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Bt(e==null?void 0:e.id);return t.jsx("button",{onClick:i=>{i.stopPropagation(),n()},disabled:!((a=e==null?void 0:e.children)!=null&&a.length),className:`flex h-[calc(100%-2px)] w-5 items-center justify-center rounded text-gray-400 transition-colors hover:bg-gray-200 hover:px-1 hover:text-gray-500 ${(r=e==null?void 0:e.children)!=null&&r.length?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(S.ChevronRight,{size:12,className:`stroke-[4] transition-transform duration-200 ${s?"rotate-90":""}`})})},hl=({page:e,pageType:s})=>t.jsx("div",{className:"flex h-full items-center justify-center gap-x-1",children:e.dynamic?t.jsx(S.StarsIcon,{size:12,className:"text-yellow-400"}):s!=null&&s.icon?t.jsx("div",{className:"flex h-4 max-h-4 w-4 max-w-4 items-center justify-center stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:s.icon}}):s!=null&&s.hasSlug?t.jsx(S.File,{size:12,className:"stroke-[1] text-slate-500"}):t.jsx(S.Globe,{size:12,className:"stroke-[1] text-slate-500"})}),ml=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),fl=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i,showUntranslatedPages:l})=>{const[o]=wa(),u=We(),h=n===e.id,d=!!e.isTemplate,m=x.useMemo(()=>f.find(s,{key:e.pageType}),[s,e.pageType]),j=o==null?void 0:o[e.id],{data:y}=Ke(j),p=y?y==null?void 0:y.name:null;let g=f.get(r,e==null?void 0:e.id);g=f.get(g,"lang")===i?g:null;const v=i===u||!!g,w=(g==null?void 0:g.name)||(e==null?void 0:e.name)||"No name";let E=(g==null?void 0:g.slug)||(e==null?void 0:e.slug)||"";const P=E+(e!=null&&e.dynamic?`/${m.dynamicSlug}`:"")+(e!=null&&e.dynamicSlugCustom?`${e.dynamicSlugCustom}`:"");if(E.startsWith("/")&&!l){const A=E.split("/").pop();E=E.endsWith(A)&&e.dynamic?"":`/${A}`}const D=x.useMemo(()=>{const A="flex h-7 min-w-0 flex-1 cursor-pointer select-none items-center gap-x-1.5 rounded px-px text-xs duration-300 border-[1px]",I=`${h?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return v?`${A} ${I} ${p?"opacity-60":""}`:`${A} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[v,h,p]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&v&&a("select",e==null?void 0:e.id),className:D,children:[t.jsx(dl,{page:e}),!e.isPartialGroup&&t.jsx(ml,{isOnline:g?g.online:e.online}),t.jsx(hl,{page:e,pageType:m}),t.jsx(ct,{content:w,side:"top",showTooltip:w.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:w})}),(E||e.dynamic)&&t.jsx(ct,{content:P,side:"top",showTooltip:!0,children:t.jsxs("span",{className:"max-w-[40%] truncate font-mono text-xs text-muted-foreground",children:[E,e.dynamic&&(m==null?void 0:m.dynamicSlug)&&t.jsxs("span",{className:"text-xs text-gray-500",children:["/",m.dynamicSlug,e.dynamicSlugCustom]})]})}),d&&t.jsx(ct,{content:"Template",side:"top",children:t.jsx("span",{className:"text-blue-500",children:t.jsx(S.NotepadText,{size:16})})}),!e.isPartialGroup&&v&&!p?t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(kn,{isLanguagePage:!!g,page:g||e,setDuplicatePage:A=>a("duplicate",A),setAddEditPage:A=>a("edit",g||A),setUnpublishPage:A=>a("unpublish",A),setDeletePage:A=>a("delete",g||A),setMarkAsTemplate:A=>a("markAsTemplate",A),setUnmarkAsTemplate:A=>a("unmarkAsTemplate",A),children:t.jsx("div",{className:"m-0 cursor-pointer rounded border border-transparent p-0.5 duration-100 hover:border-gray-400 hover:bg-white",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4",onClick:A=>A.stopPropagation()})})})}):p?t.jsx("span",{className:"duration absolute right-1.5 top-1/2 -translate-y-1/2 text-xs text-gray-500",children:t.jsx(S.Lock,{className:"h-3.5 w-3.5 fill-red-200 text-red-500"})}):null]}),t.jsx(t.Fragment,{children:p&&t.jsxs("button",{className:"absolute right-0 top-0 flex h-full items-center gap-x-1 rounded bg-red-50 px-2 py-0.5 text-xs font-light text-red-500 opacity-0 group-hover:opacity-100",children:[t.jsx(S.Edit,{size:12,className:"stroke-[3]"})," ",t.jsx("span",{className:"font-medium",children:p})," is editing this page"]})}),t.jsx(t.Fragment,{children:!v&&!e.isPartialGroup&&!p&&t.jsxs("button",{onClick:A=>{A.stopPropagation(),a("addLanguagePage",{language:i,page:e})},className:"absolute left-1/2 top-1 flex -translate-x-1/2 items-center gap-x-1 rounded bg-blue-500 px-2 py-0.5 text-xs text-white opacity-0 duration-200 hover:bg-blue-700 group-hover:opacity-100",children:[t.jsx(S.Plus,{size:12,className:"stroke-[3]"})," ",t.jsxs("span",{className:"text-[10px]",children:["Add ",f.get(Se,i)," Page"]})]})})]})},Oa=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o})=>{const{expandedPages:u}=Bt();return t.jsx("div",{className:"space-y-0.5",style:{paddingLeft:`${s*10}px`},children:e.map(h=>t.jsxs(t.Fragment,{children:[t.jsx(fl,{page:h,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o}),h.children&&h.children.length>0&&(u==null?void 0:u.includes(h.id))&&t.jsx(Oa,{pages:h.children,tier:s+1,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o})]},h.id))})},xl=({close:e})=>{const{languages:s,setSelectedLang:n}=$.useLanguages(),{data:a}=Ce(),{data:r,isFetching:i}=dt(),[l,o]=Pe(),{updateForSelectedPage:u,expandPagesOnSearch:h}=Bt(null),d=We(),m=l.get("page"),[j,y]=x.useState(""),[p,g]=x.useState(null),[v,w]=x.useState(null),[E,P]=x.useState(null),[D,A]=x.useState(null),[I,O]=x.useState(""),[Y,ee]=x.useState(null),[L,q]=x.useState(null),[F,z]=x.useState(d),[G,Q]=x.useState(!1),[,ae]=pe.useAtom(ds),je=G&&F!==d,{data:Ne,isFetching:ce}=ni(F),N=x.useCallback(T=>{var B;return(B=f.find(a,{key:T}))==null?void 0:B.hasSlug},[a]),b=x.useMemo(()=>r?je?f.filter(r,T=>!(Ne!=null&&Ne[T.id])):La(r,j,I,N):[],[r,N,j,I,Ne,je]);x.useEffect(()=>{if(!f.isEmpty(I))return;const T=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(a)&&T&&(f.find(a,{key:T})?O(T):O("all"))},[a,I]),x.useEffect(()=>{m&&!i&&(f.find(r,{id:m})||(window.history.replaceState(null,"","/"),o(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate"))))},[r,m,i,o]),x.useEffect(()=>{m&&!i&&!f.isEmpty(b)&&u(b,m)},[m,i,b,u]),x.useEffect(()=>{!f.isEmpty(j)&&!f.isEmpty(b)&&h(b)},[j,b,h]);const C=x.useCallback(T=>{const B=new URLSearchParams({page:T});F!==d&&B.set("lang",F),n(F),window.history.pushState({},"",`?${B.toString()}`),o(B),window.dispatchEvent(new PopStateEvent("popstate")),e()},[e,o,F,n,d]),M=(T,B)=>{var H;if(B)switch(T){case"add":w(B);break;case"select":C(B);break;case"edit":F!==d?ae({edit:!0,id:B==null?void 0:B.id,primaryPage:B==null?void 0:B.primaryPage}):w(B);break;case"delete":g(B);break;case"unpublish":P(B);break;case"markAsTemplate":A(B);break;case"unmarkAsTemplate":q(B);break;case"duplicate":ee(B);break;case"addLanguagePage":ae({edit:!1,primaryPage:((H=B==null?void 0:B.page)==null?void 0:H.id)||"",preselectedLang:(B==null?void 0:B.language)||F});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(ul,{pages:b,search:j,setSearch:y,languages:[d,...s],selectedLanguage:F,setSelectedLanguage:z,selectedPageType:I,setSelectedPageType:O,onAddPage:T=>M("add",T),showUntranslatedPages:je,setShowUntranslatedPages:Q}),t.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-6 pt-2",children:i||ce?t.jsx("div",{className:"space-y-2",children:f.map([...Array(15).keys()],T=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},T))}):f.isEmpty(b)?t.jsxs("div",{className:"flex h-[70vh] flex-col items-center justify-center gap-y-1 text-sm font-medium text-slate-500",children:[t.jsx(S.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx(Oa,{tier:0,pages:b,pageTypes:a,currentPage:m||"",onClickAction:M,languagePages:Ne,selectedLanguage:F,showUntranslatedPages:je})})]}),v&&t.jsx(Cn,{closePanel:e,editPage:C,addEditPage:v,setAddEditPage:w}),p&&t.jsx(Gs,{page:p,onClose:()=>g(null)}),E&&t.jsx(hs,{page:E,onClose:()=>P(null)}),D&&t.jsx(An,{page:D,onClose:()=>A(null)}),L&&t.jsx(Pn,{page:L,onClose:()=>q(null)}),Y&&t.jsx(Tn,{page:Y,onClose:()=>ee(null),closePanel:e})]})},gl=()=>{const e=qe("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:x.createElement(e,{})}):null},pl=()=>{const[e]=Pe(),s=e.get("page"),{data:n,isFetching:a}=ke(),[r,i]=x.useState(!1),{savePage:l}=$.useSavePage(),o=!!s&&!f.isEmpty(n),u=!s||!a&&f.isEmpty(n)||r,h=$.useChaiFeatureFlag("enable-old-page-manager");return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsx("div",{className:"relative",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",className:"flex w-full items-center space-x-2 py-1",onClick:()=>{l(),i(!0)},children:t.jsx(S.LogsIcon,{className:"h-4 w-4"})},"template-viewer")}),t.jsx(c.TooltipContent,{side:"right",children:t.jsx("p",{children:"Open pages manager"})})]})})}),t.jsx(c.Sheet,{open:u,onOpenChange:d=>!d&&o&&i(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`${h?"w-full !max-w-screen-md":"!min-w-[50vh] !max-w-[800px] p-0"} z-50 border-border ${o?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:`mb-3 ${h?"":"px-4 pt-4"}`,children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-primary text-primary-foreground",children:t.jsx(S.Folder,{className:"h-4 w-4"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs font-normal text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:`${u?"h-[calc(100vh-80px)] overflow-y-auto":"h-[calc(100vh-70px)] overflow-y-auto"}`,children:h?t.jsx(il,{close:()=>i(!1)}):u&&t.jsx(xl,{close:()=>i(!1)})})]})})]})},_n=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=$.useLanguages(),l=f.isEmpty(r)?n:r,[,o]=Pe(),{isLocked:u}=Ye();x.useEffect(()=>{const v=new URLSearchParams(window.location.search),w=v.get("lang");w&&(a.includes(w)?i(w):(v.delete("lang"),o(v),i("")))},[a,o,i]);const[,h]=pe.useAtom(ds),{data:d}=ke(),{data:m}=Ve(),{data:j}=Ue(),y=x.useMemo(()=>{const v=f.compact(f.map(f.get(m,"languages"),w=>{const E=f.find(j,{lang:w});return{key:w,value:f.get(Se,w,w),isLangPageAdded:!!E}})).filter(Boolean);return[{key:n,value:f.get(Se,n),isLangPageAdded:!0},...v]},[n,j,m]),p=v=>{if(document.querySelector('[data-panel-id="seo"]')){const E=new CustomEvent("seo-language-switch-check",{detail:{fromLang:l,toLang:v,switchHandler:()=>g(v)}});window.dispatchEvent(E);return}g(v)},g=v=>{i(v);const w=new URLSearchParams(window.location.search);v===n?w.delete("lang"):w.set("lang",v);const E=w.toString(),P=`${window.location.pathname}${E?`?${E}`:""}`;window.history.pushState({},"",P),o(w),window.dispatchEvent(new PopStateEvent("popstate"))};return f.isEmpty(a)?null:u?t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"ml-px h-max cursor-not-allowed gap-2 py-1.5 opacity-50",children:[t.jsx(S.Languages,{className:"h-4 w-4"}),f.get(Se,l,l),t.jsx(S.ChevronDown,{className:"h-4 w-4"})]}):t.jsx(t.Fragment,{children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{disabled:!!u,variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(S.Languages,{className:"h-4 w-4"}),f.get(Se,l,l),t.jsx(S.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[f.map(y.filter(v=>v.isLangPageAdded),v=>t.jsxs(c.DropdownMenuItem,{className:$.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",v.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>p(v.key),children:[t.jsx("div",{className:"text-slate-600",children:v.value}),v.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(S.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},v.value)),e&&!f.isEmpty(y.filter(v=>!v.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{d&&h({edit:!1,primaryPage:d.id})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(S.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]})})};function yl(){const[e,s]=pe.useAtom(ds);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(gl,{}),t.jsx(pl,{}),e&&t.jsx($i,{isOpen:!0,id:e==null?void 0:e.id,edit:!!(e!=null&&e.id),primaryPage:e==null?void 0:e.primaryPage,preselectedLang:e==null?void 0:e.preselectedLang,onClose:()=>s(null)})]})}function jl(e,s){const n=oe(),a=Z();return U.useQuery({queryKey:["revision-comparison",e.uid,s.uid],queryFn:async()=>{if(!e.uid||!s.uid)throw new Error("Both revision IDs are required for comparison");const r=o=>o==="draft"||o==="live"?o:"revision",i=o=>f.replace(o.uid,`${o.label}:`,"");return await a(n,{action:R.GET_COMPARE_DATA,data:{versions:{version1:{type:r(e.label),id:i(e)},version2:{type:r(s.label),id:i(s)}}}})},enabled:!!e.uid&&!!s.uid,gcTime:0,staleTime:0})}const vl=({version:e})=>{const s=e==null?void 0:e.item,{data:n}=Ke(s==null?void 0:s.currentEditor),a=e.label==="live",r=e.label==="draft";return t.jsxs("span",{className:`flex items-center gap-x-2 rounded border bg-white px-2 text-xs shadow-lg ${a?"border-green-500/30":r?"border-amber-500/30":"border-purple-500/30"}`,children:[t.jsx("div",{className:"h-full items-center rounded px-1.5 py-0.5 font-medium capitalize"+(a?" bg-green-500 text-green-50":r?" bg-amber-500 text-amber-50":" bg-purple-500 text-purple-50"),children:e.label}),t.jsxs("div",{className:"py-1 text-xs font-light leading-none text-gray-800",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-light opacity-90",children:r?"Currently editing":"Published by"}),!r&&t.jsx("span",{className:"pl-1 font-medium",children:(n==null?void 0:n.name)||"Unknown"})]}),t.jsx("div",{className:"text-[10px] leading-tight",children:ut.formatDate(s.createdAt,"dd MMM yyyy, h:mm a")})]})]})},zn=({version:e})=>t.jsx(vl,{version:e});function bl(e,s,n="data.json"){const a=JSON.stringify(e,null,2),r=JSON.stringify(s,null,2),i=a.split(`
3
3
  `),l=r.split(`
4
4
  `);let o=`--- a/${n}
@@ -10,4 +10,4 @@
10
10
  `);h=m.length,d=m[m.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:h,column:d,position:u}}}},jo=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,o=new RegExp(yo(l),"g");a=a.replace(o,r)}),a},vo=(e,s)=>{if(!e)return"";let n=JSON.stringify(e,null,2);const a=/{{([^{}]+)}}/g;let r;for(;(r=a.exec(n))!==null;){const i=r[1],l=f.get(s,i,null);n=n.replace(r[0],l)}return n},ln=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:l="json-input",pageData:o={},handleFieldInsert:u})=>{const[h,d]=x.useState("edit"),[m,j]=x.useState(null),[y,p]=x.useState(""),g=x.useRef(null),v=D=>{if(a)return;const A=D.target.value;s(A)},w=D=>{if(D.key==="Tab"){D.preventDefault();const A=D.currentTarget,I=A.selectionStart,O=A.selectionEnd;if(I!==O){const ee=e.substring(I,O).split(`
11
11
  `);if(D.shiftKey){const q=ee.map(z=>z.startsWith(" ")?z.substring(2):z).join(`
12
12
  `),F=e.substring(0,I)+q+e.substring(O);s(F),setTimeout(()=>{A.selectionStart=I,A.selectionEnd=I+q.length},0)}else{const q=ee.map(z=>` ${z}`).join(`
13
- `),F=e.substring(0,I)+q+e.substring(O);s(F),setTimeout(()=>{A.selectionStart=I,A.selectionEnd=I+q.length},0)}}else{const Y=e.substring(0,I)+" "+e.substring(O);s(Y),setTimeout(()=>{A.selectionStart=A.selectionEnd=I+2},0)}}};x.useEffect(()=>{const D=Qn(e);if(D.isValid)if(j(null),D.parsed){const A=vo(D.parsed,o);p(A)}else p("");else j(D.error),p("")},[e,o]);const E=()=>{const D=Qn(e);if(D.isValid&&D.parsed){const A=jo(D.parsed,D.placeholders);s(A)}},P=()=>{m!=null&&m.position&&g.current&&(g.current.focus(),g.current.setSelectionRange(m.position,m.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(c.Tabs,{value:h,onValueChange:d,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(c.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(S.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||m!==null,children:[t.jsx(S.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),h==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(He,{dataType:"value",data:o??{},onSelect:D=>u&&u(D,l)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:E,disabled:!e.trim()||n||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:g,id:l,name:l,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:v,onKeyDown:w,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),m&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(S.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(c.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:m.message}),m.line&&m.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",m.line,", column ",m.column]}),t.jsx(c.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:P,children:"Show position"})]})]})]}),t.jsxs(c.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(c.Textarea,{rows:i,value:y,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]})]})})},Wn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},bo=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),o=`{{${s}}}`,u=i+""+o+l,h=n+0+o.length;return{value:u,newCursorPos:h}},Ua=()=>{const{t:e}=$.useTranslation(),[,s]=$.useSidebarActivePanel(),{data:n}=ke(),{data:a}=bn(),{data:r,isFetching:i}=xo(),l=r==null?void 0:r.seo,o=x.useRef(null),u=n==null?void 0:n.id,h=n==null?void 0:n.pageType,d=Ta(h),{selectedLang:m,fallbackLang:j}=$.useLanguages(),y=m||j,p=$.useChaiFeatureFlag("enable-seo-meta-tab"),[g,v]=x.useState(!1),[w,E]=x.useState(!1),[P,D]=x.useState(!1),[A,I]=x.useState(null),[O,Y]=x.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",metaOther:"{}",...l}),ee=x.useRef({}),{mutate:L,isPending:q}=wn(),F=q||g||w,{hasPermission:z}=$.usePermissions(),G=z(ve.EDIT_SEO);x.useEffect(()=>{if(!i&&l&&u){const C={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",metaOther:"",...l};Y(C),ee.current[y]=C}},[i,l,y,u]),x.useEffect(()=>{const C=M=>{const{fromLang:T,toLang:B,switchHandler:H}=M.detail,V=ee.current[y];(V?!f.isEqual(V,O):!1)?(I({fromLang:T,toLang:B,switchHandler:H}),D(!0)):H()};return window.addEventListener("seo-language-switch-check",C),()=>{window.removeEventListener("seo-language-switch-check",C)}},[u,O,y]);const Q=async()=>{if(!(!d||!y))try{v(!0);const C=qt(d,y),M={...O,keyword:f.get(C,"seo.keyword",""),title:f.get(C,"seo.title",""),description:f.get(C,"seo.description",""),cononicalUrl:f.get(C,"seo.canonicalUrl",""),noIndex:f.get(C,"seo.noIndex",!1),noFollow:f.get(C,"seo.noFollow",!1),ogTitle:f.get(C,"seo.ogTitle",""),ogDescription:f.get(C,"seo.ogDescription","")};Y(M),W.toast.success(e("SEO fields reset to defaults"))}catch(C){W.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",C)}finally{v(!1)}},ae=async()=>{if(!(!d||!y))try{E(!0);const C=qt(d,y),M={...O,jsonLD:f.get(C,"seo.jsonLD","")};Y(M),W.toast.success(e("JSON-LD reset to default"))}catch(C){W.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",C)}finally{E(!1)}},je=async()=>{if(!(!d||!y))try{v(!0);const C=qt(d,y),M={...O,ogTitle:f.get(C,"seo.ogTitle",""),ogDescription:f.get(C,"seo.ogDescription",""),ogImage:f.get(C,"seo.ogImage",""),ogImageId:f.get(C,"seo.ogImageId",""),metaOther:f.get(C,"seo.metaOther","{}")};Y(M),W.toast.success(e("Meta Tag fields reset to defaults"))}catch(C){W.toast.error(e("Failed to reset Meta Tag fields")),console.error("Reset Meta Tag error:",C)}finally{v(!1)}},Ne=async()=>{L({id:r==null?void 0:r.id,seo:O,primaryPage:u},{onSuccess:()=>{console.log("SEO & JSON-LD updated successfully",O),ee.current[y]=O,W.toast.success("SEO & JSON-LD updated successfully")}})},ce=(C,M)=>{const T=document.getElementById(M);if(T){const{value:B,newCursorPos:H}=bo(T,C);o.current={id:M,position:H},T.tagName.toLowerCase()==="input"?(T.value=B,Y(re=>({...re,[T.name]:B})),T.focus(),T.setSelectionRange(H,H),[0,10,50,100,200].forEach(re=>{setTimeout(()=>{const K=document.getElementById(M);K&&(K.focus(),K.setSelectionRange(H,H))},re)})):(Y(J=>({...J,[T.name]:B})),requestAnimationFrame(()=>{const J=document.getElementById(M);J&&(J.focus(),J.setSelectionRange(H,H),setTimeout(()=>{const re=document.getElementById(M);re&&(re.focus(),re.setSelectionRange(H,H))},50))}))}},N=C=>{const M={...O,[C.target.name]:C.target.name==="noIndex"||C.target.name==="noFollow"?C.target.checked:C.target.value};Y(M)},b=C=>M=>{f.isEmpty(M.fieldValue)||N({target:{name:C,value:typeof M.fieldValue=="string"?M.fieldValue.replace(/^"(.*)"$/,"$1"):M.fieldValue}}),M.error&&W.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:M.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!G&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm",children:t.jsx(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"no-scrollbar flex-grow overflow-y-auto px-2 pb-20",children:[t.jsxs("div",{className:"mb-4 flex w-full items-center justify-between rounded-md bg-gray-100 px-2 py-1 text-left text-sm",children:[t.jsxs("span",{children:[t.jsx("div",{className:"font-medium",children:r==null?void 0:r.name}),t.jsx("span",{className:"font-mono text-xs leading-tight text-gray-500",children:r==null?void 0:r.slug})]}),t.jsx(_n,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(c.TabsList,{className:`mb-4 grid w-full ${p?"grid-cols-3":"grid-cols-2"}`,children:[t.jsx(c.TabsTrigger,{value:"seo",children:e("SEO Fields")}),p&&t.jsx(c.TabsTrigger,{value:"opengraph",children:e("Meta Tags")}),t.jsx(c.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(c.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[G&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:Q,disabled:F||!G||!d,children:e(g?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:O.keyword,onChange:N,disabled:F||!G,placeholder:e("Enter keyword"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("title"),field:"title"}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:O.title,onChange:N,disabled:F||!G,placeholder:e("Enter SEO title"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("description"),field:"description"}),G&&t.jsx(He,{data:a??{},onSelect:C=>ce(C,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:O.description,onChange:N,disabled:F||!G,placeholder:e("Enter SEO description"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:O.canonicalUrl,onChange:N,disabled:F||!G,placeholder:e("Enter Canonical URL"),readOnly:!G})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:O.noIndex,onChange:N,disabled:F||!G,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:O.noFollow,onChange:N,disabled:F||!G,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to follow links on this page.")})]})]})}),t.jsx(c.TabsContent,{value:p?"opengraph":"seo",children:t.jsxs("div",{className:"space-y-4",children:[G&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:je,disabled:F||!G||!d,children:e(g?"Resetting...":"Reset to Default")})}),t.jsxs("div",{children:[t.jsx("h3",{className:"mb-4 font-semibold text-slate-700",children:e("Open Graph")}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("ogTitle"),field:"ogTitle"}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:O.ogTitle,onChange:N,disabled:F||!G,placeholder:e("Enter OG title"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("ogDescription"),field:"ogDescription"}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:O.ogDescription,onChange:N,disabled:F||!G,placeholder:e("Enter OG description"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>{Y({...O,ogImage:`{{${C}}}`,ogImageId:""})}})]}),t.jsx(Bs,{assetId:O.ogImageId,assetUrl:O.ogImage,onChange:C=>{Y({...O,ogImage:C.url,ogImageId:C.id})},disabled:F||!G,placeholder:e("Select OG image"),className:"mb-2"})]}),p&&t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"metaOther",children:e("Meta Tags")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(ft,{keyword:O.keyword,onComplete:b("metaOther"),field:"metaOther"})})]}),t.jsx(ln,{id:"metaOther",value:O.metaOther,onChange:C=>{N({target:{name:"metaOther",value:C}})},placeholder:e("Enter Meta Tags JSON"),disabled:F||!G,readOnly:!G,pageData:a||{},rows:8,handleFieldInsert:ce})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[G&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:ae,disabled:F||!G||!d,children:e(w?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(ft,{keyword:O.keyword,onComplete:b("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(ln,{id:"jsonLD",value:O.jsonLD,onChange:C=>{N({target:{name:"jsonLD",value:C}})},placeholder:e("Enter JSON-LD"),disabled:F||!G,readOnly:!G,pageData:a||{},rows:12,handleFieldInsert:ce})]})]})})]})})]}),G&&t.jsxs("div",{className:"fixed bottom-0 left-0 right-0 flex w-full flex-shrink-0 items-center justify-between border-t bg-background p-4",children:[Wn(O.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:e("Invalid JSON. Please check.")}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(c.Button,{onClick:Ne,disabled:!Wn(O==null?void 0:O.jsonLD)||(ee.current[y]?f.isEqual(ee.current[y],O):!1)||F||!G,children:e(q?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(po,{isOpen:P,onClose:()=>{D(!1),I(null)},onSave:async()=>{A&&(await Ne(),A.switchHandler(),D(!1),I(null))},onDiscard:()=>{if(A){const C=ee.current[y];C&&Y(C),A.switchHandler(),D(!1),I(null)}},isSaving:q,fromLanguage:(A==null?void 0:A.fromLang)||y,toLanguage:(A==null?void 0:A.toLang)||""})]})};Ua.displayName="SeoPanel";const qa="seo",wo=({isActive:e,show:s})=>{const{data:n}=ke(),a=Ta(n==null?void 0:n.pageType);return!f.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},So={id:qa,label:"SEO",panel:Ua,button:wo,position:"top",width:600,view:"modal"},on={},Ss=(e,s)=>{f.has(on,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),f.set(on,e,{id:e,...s})},No=()=>f.values(on),Eo=()=>{var i;const e=No(),[s,n]=x.useState(((i=e[0])==null?void 0:i.id)||""),a=e.find(l=>l.id===s),r=a==null?void 0:a.panel;return t.jsxs("div",{className:"flex h-full gap-4",children:[t.jsx("div",{className:"no-scrollbar max-w-[25%] overflow-y-auto border-r pr-2",children:t.jsx("div",{className:"space-y-1",children:e.map(l=>{const o=l.id===s,u=l.button;return t.jsx("div",{className:"mb-1",children:t.jsx(u,{isActive:o,onClick:()=>n(l.id)})},l.id)})})}),t.jsx("div",{className:"no-scrollbar flex-1 overflow-y-auto",children:t.jsx(x.Suspense,{fallback:t.jsx("div",{className:"flex items-center justify-center h-full",children:"Loading..."}),children:r?t.jsx(r,{}):t.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:t.jsx("p",{children:"Select a setting from the sidebar or register settings using registerChaiSiteSetting"})})})})]})},Co="site-settings",To=({isActive:e,show:s})=>$.useChaiFeatureFlag("enable-site-settings")?t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsx(S.Settings,{className:"h-4 w-4"})}):null,Ao={id:Co,label:"Site Settings",panel:Eo,button:To,position:"bottom",width:800,view:"modal"},ko="user-info",Po=()=>{const{user:e,logout:s}=Oe(),n=qe("onLogout",f.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(S.User,{className:"h-4 w-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto space-y-2 p-4",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),f.isFunction(n)&&n()},children:"Logout"})]})]})]})]})]}):null},Io={id:ko,label:"User Info",button:Po,position:"bottom"},_o=()=>{$.registerChaiSidebarPanel(qa,So),$.registerChaiSidebarPanel(Fa,fo),$.registerChaiSidebarPanel("site-settings",Ao),$.registerChaiSidebarPanel("user-info",Io)};var ne={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Jn(this.context.count)},getNextContextId(){return Jn(this.context.count++)}};function Jn(e){const s=String(e),n=s.length-1;return ne.context.id+(n?String.fromCharCode(96+n):"")+s}function Rt(e){ne.context=e}var $a=!1,Do=(e,s)=>e===s,Ts=Symbol("solid-proxy"),za=typeof Proxy=="function",Dn=Symbol("solid-track"),As={equals:Do},Va=Za,Xe=1,ks=2,Ka={owned:null,cleanups:null,context:null,owner:null},Xs={},de=null,Zs=null,Lo=null,ge=null,Ie=null,Qe=null,Fs=0;function tt(e,s){const n=ge,a=de,r=e.length===0,i=s===void 0?a:s,l=r?Ka:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Ae(()=>Kt(l)));de=l,ge=null;try{return ze(o,!0)}finally{ge=n,de=a}}function we(e,s){s=s?Object.assign({},As,s):As;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Xa(n,r));return[Ya.bind(n),a]}function Ha(e,s,n){const a=Us(e,s,!0,Xe);Mt(a)}function st(e,s,n){const a=Us(e,s,!1,Xe);Mt(a)}function Ln(e,s,n){Va=Ho;const a=Us(e,s,!1,Xe);(!n||!n.render)&&(a.user=!0),Qe?Qe.push(a):Mt(a)}function Te(e,s,n){n=n?Object.assign({},As,n):As;const a=Us(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Mt(a),Ya.bind(a)}function Bo(e){return e&&typeof e=="object"&&"then"in e}function Mo(e,s,n){let a,r,i;a=!0,r=e,i={};let l=null,o=Xs,u=null,h=!1,d="initialValue"in i,m=typeof a=="function"&&Te(a);const j=new Set,[y,p]=(i.storage||we)(i.initialValue),[g,v]=we(void 0),[w,E]=we(void 0,{equals:!1}),[P,D]=we(d?"ready":"unresolved");ne.context&&(u=ne.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:ne.load&&ne.has(u)&&(o=ne.load(u)));function A(L,q,F,z){return l===L&&(l=null,z!==void 0&&(d=!0),(L===o||q===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(z,{value:q})),o=Xs,I(q,F)),q}function I(L,q){ze(()=>{q===void 0&&p(()=>L),D(q!==void 0?"errored":d?"ready":"unresolved"),v(q);for(const F of j.keys())F.decrement();j.clear()},!1)}function O(){const L=zo,q=y(),F=g();if(F!==void 0&&!l)throw F;return ge&&ge.user,q}function Y(L=!0){if(L!==!1&&h)return;h=!1;const q=m?m():a;if(q==null||q===!1){A(l,Ae(y));return}let F;const z=o!==Xs?o:Ae(()=>{try{return r(q,{value:y(),refetching:L})}catch(G){F=G}});if(F!==void 0){A(l,void 0,Ns(F),q);return}else if(!Bo(z))return A(l,z,void 0,q),z;return l=z,"v"in z?(z.s===1?A(l,z.v,void 0,q):A(l,void 0,Ns(z.v),q),z):(h=!0,queueMicrotask(()=>h=!1),ze(()=>{D(d?"refreshing":"pending"),E()},!1),z.then(G=>A(z,G,void 0,q),G=>A(z,void 0,Ns(G),q)))}Object.defineProperties(O,{state:{get:()=>P()},error:{get:()=>g()},loading:{get(){const L=P();return L==="pending"||L==="refreshing"}},latest:{get(){if(!d)return O();const L=g();if(L&&!l)throw L;return y()}}});let ee=de;return m?Ha(()=>(ee=de,Y(!1))):Y(!1),[O,{refetch:L=>Wa(ee,()=>Y(L)),mutate:p}]}function Oo(e){return ze(e,!1)}function Ae(e){if(ge===null)return e();const s=ge;ge=null;try{return e()}finally{ge=s}}function Ro(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let o;if(a){o=Array(e.length);for(let h=0;h<e.length;h++)o[h]=e[h]()}else o=e();if(i)return i=!1,l;const u=Ae(()=>s(o,r,l));return r=o,u}}function Qa(e){Ln(()=>Ae(e))}function Dt(e){return de===null||(de.cleanups===null?de.cleanups=[e]:de.cleanups.push(e)),e}function Yn(){return de}function Wa(e,s){const n=de,a=ge;de=e,ge=null;try{return ze(s,!0)}catch(r){Bn(r)}finally{de=n,ge=a}}function Go(e){const s=ge,n=de;return Promise.resolve().then(()=>{ge=s,de=n;let a;return ze(e,!1),ge=de=null,a?a.done:void 0})}var[Fo,sd]=we(!1);function Uo(){return[Fo,Go]}function qo(e,s){const n=Symbol("context");return{id:n,Provider:Qo(n),defaultValue:e}}function $o(e){let s;return de&&de.context&&(s=de.context[e.id])!==void 0?s:e.defaultValue}function Ja(e){const s=Te(e),n=Te(()=>cn(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var zo;function Ya(){if(this.sources&&this.state)if(this.state===Xe)Mt(this);else{const e=Ie;Ie=null,ze(()=>Is(this),!1),Ie=e}if(ge){const e=this.observers?this.observers.length:0;ge.sources?(ge.sources.push(this),ge.sourceSlots.push(e)):(ge.sources=[this],ge.sourceSlots=[e]),this.observers?(this.observers.push(ge),this.observerSlots.push(ge.sources.length-1)):(this.observers=[ge],this.observerSlots=[ge.sources.length-1])}return this.value}function Xa(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&ze(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=Zs&&Zs.running;l&&Zs.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Ie.push(i):Qe.push(i),i.observers&&er(i)),l||(i.state=Xe)}if(Ie.length>1e6)throw Ie=[],new Error},!1)),s}function Mt(e){if(!e.fn)return;Kt(e);const s=Fs;Vo(e,e.value,s)}function Vo(e,s,n){let a;const r=de,i=ge;ge=de=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Xe,e.owned&&e.owned.forEach(Kt),e.owned=null),e.updatedAt=n+1,Bn(l)}finally{ge=i,de=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Xa(e,a):e.value=a,e.updatedAt=n)}function Us(e,s,n,a=Xe,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:de,context:de?de.context:null,pure:n};return de===null||de!==Ka&&(de.owned?de.owned.push(i):de.owned=[i]),i}function Ps(e){if(e.state===0)return;if(e.state===ks)return Is(e);if(e.suspense&&Ae(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<Fs);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Xe)Mt(e);else if(e.state===ks){const a=Ie;Ie=null,ze(()=>Is(e,s[0]),!1),Ie=a}}function ze(e,s){if(Ie)return e();let n=!1;s||(Ie=[]),Qe?n=!0:Qe=[],Fs++;try{const a=e();return Ko(n),a}catch(a){n||(Qe=null),Ie=null,Bn(a)}}function Ko(e){if(Ie&&(Za(Ie),Ie=null),e)return;const s=Qe;Qe=null,s.length&&ze(()=>Va(s),!1)}function Za(e){for(let s=0;s<e.length;s++)Ps(e[s])}function Ho(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:Ps(a)}if(ne.context){if(ne.count){ne.effects||(ne.effects=[]),ne.effects.push(...e.slice(0,n));return}Rt()}for(ne.effects&&(ne.done||!ne.count)&&(e=[...ne.effects,...e],n+=ne.effects.length,delete ne.effects),s=0;s<n;s++)Ps(e[s])}function Is(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===Xe?a!==s&&(!a.updatedAt||a.updatedAt<Fs)&&Ps(a):r===ks&&Is(a,s)}}}function er(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ks,n.pure?Ie.push(n):Qe.push(n),n.observers&&er(n))}}function Kt(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),l=n.observerSlots.pop();a<r.length&&(i.sourceSlots[l]=a,r[a]=i,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Kt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Kt(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function Ns(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Bn(e,s=de){throw Ns(e)}function cn(e){if(typeof e=="function"&&!e.length)return cn(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=cn(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Qo(e,s){return function(a){let r;return st(()=>r=Ae(()=>(de.context={...de.context,[e]:a.value},Ja(()=>a.children))),void 0),r}}var un=Symbol("fallback");function _s(e){for(let s=0;s<e.length;s++)e[s]()}function Wo(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return Dt(()=>_s(i)),()=>{let u=e()||[],h=u.length,d,m;return u[Dn],Ae(()=>{let y,p,g,v,w,E,P,D,A;if(h===0)l!==0&&(_s(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[un],r[0]=tt(I=>(i[0]=I,n.fallback())),l=1);else if(l===0){for(r=new Array(h),m=0;m<h;m++)a[m]=u[m],r[m]=tt(j);l=h}else{for(g=new Array(h),v=new Array(h),o&&(w=new Array(h)),E=0,P=Math.min(l,h);E<P&&a[E]===u[E];E++);for(P=l-1,D=h-1;P>=E&&D>=E&&a[P]===u[D];P--,D--)g[D]=r[P],v[D]=i[P],o&&(w[D]=o[P]);for(y=new Map,p=new Array(D+1),m=D;m>=E;m--)A=u[m],d=y.get(A),p[m]=d===void 0?-1:d,y.set(A,m);for(d=E;d<=P;d++)A=a[d],m=y.get(A),m!==void 0&&m!==-1?(g[m]=r[d],v[m]=i[d],o&&(w[m]=o[d]),m=p[m],y.set(A,m)):i[d]();for(m=E;m<h;m++)m in g?(r[m]=g[m],i[m]=v[m],o&&(o[m]=w[m],o[m](m))):r[m]=tt(j);r=r.slice(0,l=h),a=u.slice(0)}return r});function j(y){if(i[m]=y,o){const[p,g]=we(m);return o[m]=g,s(u[m],p)}return s(u[m])}}}function Jo(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return Dt(()=>_s(i)),()=>{const h=e()||[],d=h.length;return h[Dn],Ae(()=>{if(d===0)return o!==0&&(_s(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[un],r[0]=tt(j=>(i[0]=j,n.fallback())),o=1),r;for(a[0]===un&&(i[0](),i=[],a=[],r=[],o=0),u=0;u<d;u++)u<a.length&&a[u]!==h[u]?l[u](()=>h[u]):u>=a.length&&(r[u]=tt(m));for(;u<a.length;u++)i[u]();return o=l.length=i.length=d,a=h.slice(0),r=r.slice(0,o)});function m(j){i[u]=j;const[y,p]=we(h[u]);return l[u]=p,s(y,u)}}}function Mn(e,s){return Ae(()=>e(s||{}))}function js(){return!0}var dn={get(e,s,n){return s===Ts?n:e.get(s)},has(e,s){return s===Ts?!0:e.has(s)},set:js,deleteProperty:js,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:js,deleteProperty:js}},ownKeys(e){return e.keys()}};function en(e){return(e=typeof e=="function"?e():e)?e:{}}function Yo(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function On(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&Ts in o,e[l]=typeof o=="function"?(s=!0,Te(o)):o}if(za&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=en(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in en(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(en(e[o])));return[...new Set(l)]}},dn);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let h=u.length-1;h>=0;h--){const d=u[h];if(d==="__proto__"||d==="constructor")continue;const m=Object.getOwnPropertyDescriptor(o,d);if(!a[d])a[d]=m.get?{enumerable:!0,configurable:!0,get:Yo.bind(n[d]=[m.get.bind(o)])}:m.value!==void 0?m:void 0;else{const j=n[d];j&&(m.get?j.push(m.get.bind(o)):m.value!==void 0&&j.push(()=>m.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const o=i[l],u=a[o];u&&u.get?Object.defineProperty(r,o,u):r[o]=u?u.value:void 0}return r}function tr(e,...s){if(za&&Ts in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(o){return l.includes(o)?e[o]:void 0},has(o){return l.includes(o)&&o in e},keys(){return l.filter(o=>o in e)}},dn));return i.push(new Proxy({get(l){return r.has(l)?void 0:e[l]},has(l){return r.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!r.has(l))}},dn)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let o=!1,u=0;for(const h of s)h.includes(r)&&(o=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;o||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function sr(e){let s,n;const a=r=>{const i=ne.context;if(i){const[o,u]=we();ne.count||(ne.count=0),ne.count++,(n||(n=e())).then(h=>{!ne.done&&Rt(i),ne.count--,u(()=>h.default),Rt()}),s=o}else if(!s){const[o]=Mo(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Te(()=>(l=s())?Ae(()=>{if(!i||ne.done)return l(r);const o=ne.context;Rt(i);const u=l(r);return Rt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Xo=0;function Zo(){return ne.context?ne.getNextContextId():`cl-${Xo++}`}var nr=e=>`Stale read from <${e}>.`;function ec(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(Wo(()=>e.each,e.children,s||void 0))}function tc(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(Jo(()=>e.each,e.children,s||void 0))}function sc(e){const s=e.keyed,n=Te(()=>e.when,void 0,void 0),a=s?n:Te(n,void 0,{equals:(r,i)=>!r==!i});return Te(()=>{const r=a();if(r){const i=e.children;return typeof i=="function"&&i.length>0?Ae(()=>i(s?r:()=>{if(!Ae(a))throw nr("Show");return n()})):i}return e.fallback},void 0,void 0)}function nc(e){const s=Ja(()=>e.children),n=Te(()=>{const a=s(),r=Array.isArray(a)?a:[a];let i=()=>{};for(let l=0;l<r.length;l++){const o=l,u=r[l],h=i,d=Te(()=>h()?void 0:u.when,void 0,void 0),m=u.keyed?d:Te(d,void 0,{equals:(j,y)=>!j==!y});i=()=>h()||(m()?[o,d,u]:void 0)}return i});return Te(()=>{const a=n()();if(!a)return e.fallback;const[r,i,l]=a,o=l.children;return typeof o=="function"&&o.length>0?Ae(()=>o(l.keyed?i():()=>{var h;if(((h=Ae(n)())==null?void 0:h[0])!==r)throw nr("Match");return i()})):o},void 0,void 0)}function ac(e){return e}var rc=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","hidden","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected"],ic=new Set(["className","value","readOnly","noValidate","formNoValidate","isMap","noModule","playsInline",...rc]),lc=new Set(["innerHTML","textContent","innerText","children"]),oc=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),cc=Object.assign(Object.create(null),{class:"className",novalidate:{$:"noValidate",FORM:1},formnovalidate:{$:"formNoValidate",BUTTON:1,INPUT:1},ismap:{$:"isMap",IMG:1},nomodule:{$:"noModule",SCRIPT:1},playsinline:{$:"playsInline",VIDEO:1},readonly:{$:"readOnly",INPUT:1,TEXTAREA:1}});function uc(e,s){const n=cc[e];return typeof n=="object"?n[s]?n.$:void 0:n}var dc=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),hc=new Set(["altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","hkern","image","line","linearGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tref","tspan","use","view","vkern"]),mc={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},fc=e=>Te(()=>e());function xc(e,s,n){let a=n.length,r=s.length,i=a,l=0,o=0,u=s[r-1].nextSibling,h=null;for(;l<r||o<i;){if(s[l]===n[o]){l++,o++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const d=i<a?o?n[o-1].nextSibling:n[i-o]:u;for(;o<i;)e.insertBefore(n[o++],d)}else if(i===o)for(;l<r;)(!h||!h.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[o]===s[r-1]){const d=s[--r].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--i],d),s[r]=n[i]}else{if(!h){h=new Map;let m=o;for(;m<i;)h.set(n[m],m++)}const d=h.get(s[l]);if(d!=null)if(o<d&&d<i){let m=l,j=1,y;for(;++m<r&&m<i&&!((y=h.get(s[m]))==null||y!==d+j);)j++;if(j>d-o){const p=s[l];for(;o<d;)e.insertBefore(n[o++],p)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var zt="_$DX_DELEGATE";function ar(e,s,n,a={}){let r;return tt(i=>{r=i,s===document?e():Ls(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function gc(e,s,n,a){let r;const i=()=>{const o=document.createElement("template");return o.innerHTML=e,o.content.firstChild},l=()=>(r||(r=i())).cloneNode(!0);return l.cloneNode=l,l}function rr(e,s=window.document){const n=s[zt]||(s[zt]=new Set);for(let a=0,r=e.length;a<r;a++){const i=e[a];n.has(i)||(n.add(i),s.addEventListener(i,ur))}}function pc(e=window.document){if(e[zt]){for(let s of e[zt].keys())e.removeEventListener(s,ur);delete e[zt]}}function Ds(e,s,n){ht(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function yc(e,s,n,a){ht(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function jc(e,s,n){ht(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function ir(e,s){ht(e)||(s==null?e.removeAttribute("class"):e.className=s)}function lr(e,s,n,a){if(a)Array.isArray(n)?(e[`$$${s}`]=n[0],e[`$$${s}Data`]=n[1]):e[`$$${s}`]=n;else if(Array.isArray(n)){const r=n[0];e.addEventListener(s,n[0]=i=>r.call(e,n[1],i))}else e.addEventListener(s,n,typeof n!="function"&&n)}function vc(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const o=r[i];!o||o==="undefined"||s[o]||(Xn(e,o,!1),delete n[o])}for(i=0,l=a.length;i<l;i++){const o=a[i],u=!!s[o];!o||o==="undefined"||n[o]===u||!u||(Xn(e,o,!0),n[o]=u)}return n}function bc(e,s,n){if(!s)return n?Ds(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function or(e,s={},n,a){const r={};return a||st(()=>r.children=Ht(e,s.children,r.children)),st(()=>typeof s.ref=="function"&&cr(s.ref,e)),st(()=>wc(e,s,n,!0,r,!0)),r}function cr(e,s,n){return Ae(()=>e(s,n))}function Ls(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Ht(e,s,a,n);st(r=>Ht(e,s(),r,n),a)}function wc(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=Zn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=Zn(e,l,o,r[l],n,i,s)}}function Sc(e){let s,n;return!ht()||!(s=ne.registry.get(n=Ec()))?e():(ne.completed&&ne.completed.add(s),ne.registry.delete(n),s)}function ht(e){return!!ne.context&&!ne.done&&(!e||e.isConnected)}function Nc(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Xn(e,s,n){const a=s.trim().split(/\s+/);for(let r=0,i=a.length;r<i;r++)e.classList.toggle(a[r],n)}function Zn(e,s,n,a,r,i,l){let o,u,h,d,m;if(s==="style")return bc(e,n,a);if(s==="classList")return vc(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const j=s.slice(3);a&&e.removeEventListener(j,a,typeof a!="function"&&a),n&&e.addEventListener(j,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const j=s.slice(10);a&&e.removeEventListener(j,a,!0),n&&e.addEventListener(j,n,!0)}else if(s.slice(0,2)==="on"){const j=s.slice(2).toLowerCase(),y=dc.has(j);if(!y&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(j,p)}(y||n)&&(lr(e,j,n,y),y&&rr([j]))}else if(s.slice(0,5)==="attr:")Ds(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")jc(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(h=lc.has(s))||!r&&((d=uc(s,e.tagName))||(u=ic.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(m)s=s.slice(5),u=!0;else if(ht(e))return n;s==="class"||s==="className"?ir(e,n):o&&!u&&!h?e[Nc(s)]=n:e[d||s]=n}else{const j=r&&s.indexOf(":")>-1&&mc[s.split(":")[0]];j?yc(e,j,s,n):Ds(e,oc[s]||s,n)}return n}function ur(e){if(ne.registry&&ne.events&&ne.events.find(([u,h])=>h===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const h=s[`${n}Data`];if(h!==void 0?u.call(s,h,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},o=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),ne.registry&&!ne.done&&(ne.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let h=0;h<u.length-2&&(s=u[h],!!l());h++){if(s._$host){s=s._$host,o();break}if(s.parentNode===r)break}}else o();i(a)}function Ht(e,s,n,a,r){const i=ht(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let h=0;h<n.length;h++){const d=n[h];d.nodeType===8&&d.data.slice(0,2)==="!$"?d.remove():u.push(d)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,o=a!==void 0;if(e=o&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(o){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=xt(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(i)return n;n=xt(e,n,a)}else{if(l==="function")return st(()=>{let u=s();for(;typeof u=="function";)u=u();n=Ht(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],h=n&&Array.isArray(n);if(hn(u,s,n,r))return st(()=>n=Ht(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let d=u[0];if(d.parentNode!==e)return n;const m=[d];for(;(d=d.nextSibling)!==a;)m.push(d);return n=m}if(u.length===0){if(n=xt(e,n,a),o)return n}else h?n.length===0?ea(e,u,a):xc(e,n,u):(n&&xt(e),ea(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=o?[s]:s;if(Array.isArray(n)){if(o)return n=xt(e,n,a,s);xt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function hn(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let o=s[i],u=n&&n[e.length],h;if(!(o==null||o===!0||o===!1))if((h=typeof o)=="object"&&o.nodeType)e.push(o);else if(Array.isArray(o))r=hn(e,o,u)||r;else if(h==="function")if(a){for(;typeof o=="function";)o=o();r=hn(e,Array.isArray(o)?o:[o],Array.isArray(u)?u:[u])||r}else e.push(o),r=!0;else{const d=String(o);u&&u.nodeType===3&&u.data===d?e.push(u):e.push(document.createTextNode(d))}}return r}function ea(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function xt(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const o=s[l];if(r!==o){const u=o.parentNode===e;!i&&!l?u?e.replaceChild(r,o):e.insertBefore(r,n):u&&o.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function Ec(){return ne.getNextContextId()}var Cc="http://www.w3.org/2000/svg";function dr(e,s=!1){return s?document.createElementNS(Cc,e):document.createElement(e)}function Tc(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Yn();let i,l=!!ne.context;return Ln(()=>{l&&(Yn().user=l=!1),i||(i=Wa(r,()=>Te(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,h]=we(!1),d=()=>h(!0);tt(m=>Ls(o,()=>u()?m():i(),null)),Dt(d)}else{const u=dr(e.isSVG?"g":"div",e.isSVG),h=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),Ls(h,i),o.appendChild(u),e.ref&&e.ref(u),Dt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function Ac(e,s){const n=Te(e);return Te(()=>{const a=n();switch(typeof a){case"function":return Ae(()=>a(s));case"string":const r=hc.has(a),i=ne.context?Sc():dr(a,r);return or(i,s,r),i}})}function kc(e){const[,s]=tr(e,["component"]);return Ac(()=>e.component,s)}var Pc=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,s){this.keyToValue.set(e,s),this.valueToKey.set(s,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},hr=class{constructor(e){this.generateIdentifier=e,this.kv=new Pc}register(e,s){this.kv.getByValue(e)||(s||(s=this.generateIdentifier(e)),this.kv.set(s,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},Ic=class extends hr{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,s){typeof s=="object"?(s.allowProps&&this.classToAllowedProps.set(e,s.allowProps),super.register(e,s.identifier)):super.register(e,s)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function _c(e){if("values"in Object)return Object.values(e);const s=[];for(const n in e)e.hasOwnProperty(n)&&s.push(e[n]);return s}function Dc(e,s){const n=_c(e);if("find"in n)return n.find(s);const a=n;for(let r=0;r<a.length;r++){const i=a[r];if(s(i))return i}}function Lt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Es(e,s){return e.indexOf(s)!==-1}function ta(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Lc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Dc(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Bc=e=>Object.prototype.toString.call(e).slice(8,-1),mr=e=>typeof e>"u",Mc=e=>e===null,Qt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,mn=e=>Qt(e)&&Object.keys(e).length===0,at=e=>Array.isArray(e),Oc=e=>typeof e=="string",Rc=e=>typeof e=="number"&&!isNaN(e),Gc=e=>typeof e=="boolean",Fc=e=>e instanceof RegExp,Wt=e=>e instanceof Map,Jt=e=>e instanceof Set,fr=e=>Bc(e)==="Symbol",Uc=e=>e instanceof Date&&!isNaN(e.valueOf()),qc=e=>e instanceof Error,sa=e=>typeof e=="number"&&isNaN(e),$c=e=>Gc(e)||Mc(e)||mr(e)||Rc(e)||Oc(e)||fr(e),zc=e=>typeof e=="bigint",Vc=e=>e===1/0||e===-1/0,Kc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Hc=e=>e instanceof URL,xr=e=>e.replace(/\./g,"\\."),tn=e=>e.map(String).map(xr).join("."),Vt=e=>{const s=[];let n="";for(let r=0;r<e.length;r++){let i=e.charAt(r);if(i==="\\"&&e.charAt(r+1)==="."){n+=".",r++;continue}if(i==="."){s.push(n),n="";continue}n+=i}const a=n;return s.push(a),s};function $e(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var gr=[$e(mr,"undefined",()=>null,()=>{}),$e(zc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),$e(Uc,"Date",e=>e.toISOString(),e=>new Date(e)),$e(qc,"Error",(e,s)=>{const n={name:e.name,message:e.message};return s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n},(e,s)=>{const n=new Error(e.message);return n.name=e.name,n.stack=e.stack,s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n}),$e(Fc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),$e(Jt,"set",e=>[...e.values()],e=>new Set(e)),$e(Wt,"map",e=>[...e.entries()],e=>new Map(e)),$e(e=>sa(e)||Vc(e),"number",e=>sa(e)?"NaN":e>0?"Infinity":"-Infinity",Number),$e(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),$e(Hc,"URL",e=>e.toString(),e=>new URL(e))];function qs(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var pr=qs((e,s)=>fr(e)?!!s.symbolRegistry.getIdentifier(e):!1,(e,s)=>["symbol",s.symbolRegistry.getIdentifier(e)],e=>e.description,(e,s,n)=>{const a=n.symbolRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown symbol");return a}),Qc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),yr=qs(Kc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Qc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function jr(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var vr=qs(jr,(e,s)=>["class",s.classRegistry.getIdentifier(e.constructor)],(e,s)=>{const n=s.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};const a={};return n.forEach(r=>{a[r]=e[r]}),a},(e,s,n)=>{const a=n.classRegistry.getValue(s[1]);if(!a)throw new Error(`Trying to deserialize unknown class '${s[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(a.prototype),e)}),br=qs((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Wc=[vr,pr,br,yr],na=(e,s)=>{const n=ta(Wc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=ta(gr,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},wr={};gr.forEach(e=>{wr[e.annotation]=e});var Jc=(e,s,n)=>{if(at(s))switch(s[0]){case"symbol":return pr.untransform(e,s,n);case"class":return vr.untransform(e,s,n);case"custom":return br.untransform(e,s,n);case"typed-array":return yr.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=wr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},pt=(e,s)=>{if(s>e.size)throw new Error("index out of bounds");const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function Sr(e){if(Es(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Es(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Es(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Yc=(e,s)=>{Sr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Jt(e))e=pt(e,+a);else if(Wt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=pt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},fn=(e,s,n)=>{if(Sr(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(at(a)){const o=+l;a=a[o]}else if(Qt(a))a=a[l];else if(Jt(a)){const o=+l;a=pt(a,o)}else if(Wt(a)){if(i===s.length-2)break;const u=+l,h=+s[++i]==0?"key":"value",d=pt(a,u);switch(h){case"key":a=d;break;case"value":a=a.get(d);break}}}const r=s[s.length-1];if(at(a)?a[+r]=n(a[+r]):Qt(a)&&(a[r]=n(a[r])),Jt(a)){const i=pt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Wt(a)){const i=+s[s.length-2],l=pt(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(l);a.set(u,a.get(l)),u!==l&&a.delete(l);break}case"value":{a.set(l,n(a.get(l)));break}}}return e};function xn(e,s,n=[]){if(!e)return;if(!at(e)){Lt(e,(i,l)=>xn(i,s,[...n,...Vt(l)]));return}const[a,r]=e;r&&Lt(r,(i,l)=>{xn(i,s,[...n,...Vt(l)])}),s(a,n)}function Xc(e,s,n){return xn(s,(a,r)=>{e=fn(e,r,i=>Jc(i,a,n))}),e}function Zc(e,s){function n(a,r){const i=Yc(e,Vt(r));a.map(Vt).forEach(l=>{e=fn(e,l,()=>i)})}if(at(s)){const[a,r]=s;a.forEach(i=>{e=fn(e,Vt(i),()=>e)}),r&&Lt(r,n)}else Lt(s,n);return e}var eu=(e,s)=>Qt(e)||at(e)||Wt(e)||Jt(e)||jr(e,s);function tu(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function su(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(o=>o.map(String)).sort((o,u)=>o.length-u.length));const[i,...l]=r;i.length===0?a=l.map(tn):n[tn(i)]=l.map(tn)}),a?mn(n)?[a]:[a,n]:mn(n)?void 0:n}var Nr=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=$c(e);if(!o){tu(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!eu(e,n)){const y=na(e,n),p=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,p),p}if(Es(i,e))return{transformedValue:null};const u=na(e,n),h=(u==null?void 0:u.value)??e,d=at(h)?[]:{},m={};Lt(h,(y,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const g=Nr(y,s,n,a,[...r,p],[...i,e],l);d[p]=g.transformedValue,at(g.annotations)?m[p]=g.annotations:Qt(g.annotations)&&Lt(g.annotations,(v,w)=>{m[xr(p)+"."+w]=v})});const j=mn(m)?{transformedValue:d,annotations:u?[u.type]:void 0}:{transformedValue:d,annotations:u?[u.type,m]:m};return o||l.set(e,j),j};function Er(e){return Object.prototype.toString.call(e).slice(8,-1)}function aa(e){return Er(e)==="Array"}function nu(e){if(Er(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function au(e,s,n,a,r){const i={}.propertyIsEnumerable.call(a,s)?"enumerable":"nonenumerable";i==="enumerable"&&(e[s]=n),r&&i==="nonenumerable"&&Object.defineProperty(e,s,{value:n,enumerable:!1,writable:!0,configurable:!0})}function gn(e,s={}){if(aa(e))return e.map(r=>gn(r,s));if(!nu(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(aa(s.props)&&!s.props.includes(i))return r;const l=e[i],o=gn(l,s);return au(r,i,o,e,s.nonenumerable),r},{})}var ye=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Ic,this.symbolRegistry=new hr(s=>s.description??""),this.customTransformerRegistry=new Lc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Nr(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=su(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=gn(s);return n!=null&&n.values&&(a=Xc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Zc(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};ye.defaultInstance=new ye;ye.serialize=ye.defaultInstance.serialize.bind(ye.defaultInstance);ye.deserialize=ye.defaultInstance.deserialize.bind(ye.defaultInstance);ye.stringify=ye.defaultInstance.stringify.bind(ye.defaultInstance);ye.parse=ye.defaultInstance.parse.bind(ye.defaultInstance);ye.registerClass=ye.defaultInstance.registerClass.bind(ye.defaultInstance);ye.registerSymbol=ye.defaultInstance.registerSymbol.bind(ye.defaultInstance);ye.registerCustom=ye.defaultInstance.registerCustom.bind(ye.defaultInstance);ye.allowErrorProps=ye.defaultInstance.allowErrorProps.bind(ye.defaultInstance);var Cr=ye.serialize,ru=ye.stringify;function iu(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function lu(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function ou({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function cu({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function uu(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var du=(e,s=!1)=>{const{json:n}=Cr(e);return JSON.stringify(n,null,s?2:void 0)},vs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,hu=(e,s)=>e.queryHash.localeCompare(s.queryHash),Tr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,mu=(e,s)=>vs(e)===vs(s)?Tr(e,s):vs(e)>vs(s)?1:-1,fu={status:mu,"query hash":hu,"last updated":Tr},bs=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Ar=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,xu=(e,s)=>bs(e)===bs(s)?Ar(e,s):bs(e)>bs(s)?1:-1,gu={status:xu,"last updated":Ar},pu=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),yu=()=>{const[e,s]=we("dark");return Qa(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=r=>{s(r.matches?"dark":"light")};n.addEventListener("change",a),Dt(()=>n.removeEventListener("change",a))}),e},Gt=(e,s,n)=>{if(s.length===0)return n;if(e instanceof Map){const a=new Map(e);if(s.length===1)return a.set(s[0],n),a;const[r,...i]=s;return a.set(r,Gt(a.get(r),i,n)),a}if(e instanceof Set){const a=Gt(Array.from(e),s,n);return new Set(a)}if(Array.isArray(e)){const a=[...e];if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Gt(a[r],i,n),a}if(e instanceof Object){const a={...e};if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Gt(a[r],i,n),a}return e},Ft=(e,s)=>{if(e instanceof Map){const n=new Map(e);if(s.length===1)return n.delete(s[0]),n;const[a,...r]=s;return n.set(a,Ft(n.get(a),r)),n}if(e instanceof Set){const n=Ft(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,l)=>l.toString()!==s[0]);const[a,...r]=s;return n[a]=Ft(n[a],r),n}if(e instanceof Object){const n={...e};if(s.length===1)return delete n[s[0]],n;const[a,...r]=s;return n[a]=Ft(n[a],r),n}return e},kr=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},yt,Yt,Xt,Zt,lt,es,jt,vt,bt,wt,St,ts,Nt,ss,la,ju=(la=class{constructor(e){fe(this,yt);fe(this,Yt);fe(this,Xt);fe(this,Zt);fe(this,lt,!1);fe(this,es);fe(this,jt);fe(this,vt);fe(this,bt);fe(this,wt);fe(this,St);fe(this,ts);fe(this,Nt);fe(this,ss);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:h,shadowDOMTarget:d,hideDisabledQueries:m}=e;he(this,yt,we(s)),he(this,Xt,n),he(this,Zt,a),he(this,Yt,r),he(this,es,h),he(this,jt,d),he(this,vt,we(i)),he(this,bt,we(l)),he(this,wt,we(o)),he(this,St,we(u)),he(this,ts,we(m))}setButtonPosition(e){te(this,vt)[1](e)}setPosition(e){te(this,bt)[1](e)}setInitialIsOpen(e){te(this,wt)[1](e)}setErrorTypes(e){te(this,St)[1](e)}setClient(e){te(this,yt)[1](e)}mount(e){if(te(this,lt))throw new Error("Devtools is already mounted");const s=ar(()=>{const n=this,[a]=te(this,vt),[r]=te(this,bt),[i]=te(this,wt),[l]=te(this,St),[o]=te(this,ts),[u]=te(this,yt);let h;return te(this,Nt)?h=te(this,Nt):(h=sr(()=>Promise.resolve().then(()=>require("./LNWAZHJI-D60PWCOP.cjs"))),he(this,Nt,h)),kr(te(this,es),te(this,jt)),Mn(h,On({get queryFlavor(){return te(n,Xt)},get version(){return te(n,Zt)},get onlineManager(){return te(n,Yt)},get shadowDOMTarget(){return te(n,jt)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get hideDisabledQueries(){return o()}}))},e);he(this,lt,!0),he(this,ss,s)}unmount(){var e;if(!te(this,lt))throw new Error("Devtools is not mounted");(e=te(this,ss))==null||e.call(this),he(this,lt,!1)}},yt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,lt=new WeakMap,es=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,ts=new WeakMap,Nt=new WeakMap,ss=new WeakMap,la),Et,ns,as,rs,ot,is,Ct,Tt,At,kt,Pt,ls,It,_t,os,oa,vu=(oa=class{constructor(e){fe(this,Et);fe(this,ns);fe(this,as);fe(this,rs);fe(this,ot,!1);fe(this,is);fe(this,Ct);fe(this,Tt);fe(this,At);fe(this,kt);fe(this,Pt);fe(this,ls);fe(this,It);fe(this,_t);fe(this,os);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:h,shadowDOMTarget:d,onClose:m,hideDisabledQueries:j}=e;he(this,Et,we(s)),he(this,as,n),he(this,rs,a),he(this,ns,r),he(this,is,h),he(this,Ct,d),he(this,Tt,we(i)),he(this,At,we(l)),he(this,kt,we(o)),he(this,Pt,we(u)),he(this,ls,we(j)),he(this,It,we(m))}setButtonPosition(e){te(this,Tt)[1](e)}setPosition(e){te(this,At)[1](e)}setInitialIsOpen(e){te(this,kt)[1](e)}setErrorTypes(e){te(this,Pt)[1](e)}setClient(e){te(this,Et)[1](e)}setOnClose(e){te(this,It)[1](()=>e)}mount(e){if(te(this,ot))throw new Error("Devtools is already mounted");const s=ar(()=>{const n=this,[a]=te(this,Tt),[r]=te(this,At),[i]=te(this,kt),[l]=te(this,Pt),[o]=te(this,ls),[u]=te(this,Et),[h]=te(this,It);let d;return te(this,_t)?d=te(this,_t):(d=sr(()=>Promise.resolve().then(()=>require("./MWZ6AO7Z-CuNpzMOf.cjs"))),he(this,_t,d)),kr(te(this,is),te(this,Ct)),Mn(d,On({get queryFlavor(){return te(n,as)},get version(){return te(n,rs)},get onlineManager(){return te(n,ns)},get shadowDOMTarget(){return te(n,Ct)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get hideDisabledQueries(){return o()},get onClose(){return h()}}))},e);he(this,ot,!0),he(this,os,s)}unmount(){var e;if(!te(this,ot))throw new Error("Devtools is not mounted");(e=te(this,os))==null||e.call(this),he(this,ot,!1)}},Et=new WeakMap,ns=new WeakMap,as=new WeakMap,rs=new WeakMap,ot=new WeakMap,is=new WeakMap,Ct=new WeakMap,Tt=new WeakMap,At=new WeakMap,kt=new WeakMap,Pt=new WeakMap,ls=new WeakMap,It=new WeakMap,_t=new WeakMap,os=new WeakMap,oa);function bu(e){const s=U.useQueryClient(e.client),n=be.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u,hideDisabledQueries:h}=e,[d]=be.useState(new ju({client:s,queryFlavor:"React Query",version:"5",onlineManager:U.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u,hideDisabledQueries:h}));return be.useEffect(()=>{d.setClient(s)},[s,d]),be.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),be.useEffect(()=>{r&&d.setPosition(r)},[r,d]),be.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),be.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),be.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{dir:"ltr",className:"tsqd-parent-container",ref:n})}function wu(e){const s=U.useQueryClient(e.client),n=be.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i,hideDisabledQueries:l}=e,[o]=be.useState(new vu({client:s,queryFlavor:"React Query",version:"5",onlineManager:U.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose,hideDisabledQueries:l}));return be.useEffect(()=>{o.setClient(s)},[s,o]),be.useEffect(()=>{o.setOnClose(e.onClose??(()=>{}))},[e.onClose,o]),be.useEffect(()=>{o.setErrorTypes(a||[])},[a,o]),be.useEffect(()=>(n.current&&o.mount(n.current),()=>{o.unmount()}),[o]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var Su=process.env.NODE_ENV!=="development"?function(){return null}:bu;process.env.NODE_ENV;const Nu=()=>{$.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),$.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),$.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"}),$.registerChaiFeatureFlag("enable-old-page-manager",{description:"Switch to older page manager"}),$.registerChaiFeatureFlag("enable-site-settings",{description:"Site settings"}),$.registerChaiFeatureFlag("enable-seo-meta-tab",{description:"Enable SEO Meta tab"})},Eu=()=>{const e=oe(),s=Z();return U.useQuery({queryKey:[R.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:R.GET_COLLECTIONS})})},Cu=()=>{const{data:e}=ke(),{data:s}=Je(),{data:n}=Ve(),a=oe(),r=Z(),i=x.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return U.useMutation({mutationFn:async({block:l})=>r(a,{action:R.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},Pr=()=>{const e=Rs();return x.useCallback(({pageId:s})=>{e(s)},[e])},Tu=x.createContext(null),sn={didCatch:!1,error:null};class Au extends x.Component{constructor(s){super(s),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=sn}static getDerivedStateFromError(s){return{didCatch:!0,error:s}}resetErrorBoundary(){const{error:s}=this.state;if(s!==null){for(var n,a,r=arguments.length,i=new Array(r),l=0;l<r;l++)i[l]=arguments[l];(n=(a=this.props).onReset)===null||n===void 0||n.call(a,{args:i,reason:"imperative-api"}),this.setState(sn)}}componentDidCatch(s,n){var a,r;(a=(r=this.props).onError)===null||a===void 0||a.call(r,s,n)}componentDidUpdate(s,n){const{didCatch:a}=this.state,{resetKeys:r}=this.props;if(a&&n.error!==null&&ku(s.resetKeys,r)){var i,l;(i=(l=this.props).onReset)===null||i===void 0||i.call(l,{next:r,prev:s.resetKeys,reason:"keys"}),this.setState(sn)}}render(){const{children:s,fallbackRender:n,FallbackComponent:a,fallback:r}=this.props,{didCatch:i,error:l}=this.state;let o=s;if(i){const u={error:l,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")o=n(u);else if(a)o=x.createElement(a,u);else if(r!==void 0)o=r;else throw l}return x.createElement(Tu.Provider,{value:{didCatch:i,error:l,resetErrorBoundary:this.resetErrorBoundary}},o)}}function ku(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==s.length||e.some((n,a)=>!Object.is(n,s[a]))}const Pu=()=>{const e=cs(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>{const r=a.map(async l=>n(e,{action:R.UPLOAD_ASSET,data:l}));return await Promise.all(r)},onSuccess:a=>{var r;if(a!=null&&a.some(i=>i.error))throw new Error(((r=a==null?void 0:a.find(i=>i.error))==null?void 0:r.error)||"Failed to upload asset");{s.invalidateQueries({queryKey:[R.GET_ASSETS]});const i=a==null?void 0:a.length;W.toast.success(`${i===1?"Asset":i+" Assets"} uploaded successfully`)}},onError:()=>{W.toast.error("Failed to upload asset")}})},Iu=()=>{const e=cs(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[R.GET_ASSETS]}),W.toast.success("Asset deleted successfully")},onError:()=>{W.toast.error("Failed to delete asset")}})},_u=()=>{const e=cs(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[R.GET_ASSETS]}),W.toast.success("Asset updated successfully")},onError:()=>{W.toast.error("Failed to update asset")}})},Du=(e={})=>{const s=cs(),n=Z(),{search:a,page:r=1,limit:i=30}=e;return U.useQuery({queryKey:[R.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:R.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},Lu=e=>{const s=cs(),n=Z();return U.useQuery({queryKey:[R.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:R.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Bu(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function ra(e){if(!e)return"N/A";const s=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(s)}function ia(e,s){let n=e,a=s==null?void 0:s.description;return(!a||typeof a!="string")&&(a=""),(!n||typeof n!="string")&&(n=""),n!==a}const Mu=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,j,y;const{data:i,isLoading:l,isError:o}=Lu(e||""),[u,h]=x.useState(""),d=async(p,g)=>{try{await navigator.clipboard.writeText(p),W.toast.success(`${g} copied to clipboard`)}catch(v){W.toast.error(`Failed to copy ${g}`,{description:v==null?void 0:v.message})}};return x.useEffect(()=>{i!=null&&i.description&&h(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(S.Loader,{className:"h-8 w-8 animate-spin"})}):o||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(S.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(S.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>d(i.url,"Asset URL"),disabled:r,children:[t.jsx(S.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(S.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((m=i.metadata)==null?void 0:m.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((j=i.metadata)==null?void 0:j.format)||i.type,capitalize:!0},{label:"Size",value:Bu(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:ra(i.createdAt)},{label:"Updated",value:ra(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(p.value,p.label),children:t.jsx(S.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,g)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},g))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>h(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!ia(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!ia(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(S.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})};function Ou({currentPage:e,totalPages:s,onPageChange:n,pageRangeDisplayed:a=3,showPageInput:r=!0,className:i=""}){const[l,o]=x.useState(String(e)),u=x.useMemo(()=>{const p=Math.floor(a/2);let g=Math.max(1,e-p),v=Math.min(s,e+p);v-g+1<a&&(g===1?v=Math.min(s,g+a-1):v===s&&(g=Math.max(1,v-a+1)));const w=[];g>1&&(w.push(1),g>2&&w.push("..."));for(let E=g;E<=v;E++)w.push(E);return v<s&&(v<s-1&&w.push("..."),w.push(s)),w},[e,s,a]),h=p=>{p!==e&&p>=1&&p<=s&&(n(p),o(String(p)))},d=()=>{e>1&&h(e-1)},m=()=>{e<s&&h(e+1)},j=()=>{const p=Number(l);!isNaN(p)&&p>=1&&p<=s&&h(p)},y=p=>{p.key==="Enter"&&j()};return s<=1?null:t.jsxs("div",{className:`flex flex-wrap items-center justify-center gap-3 ${i}`,children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:d,disabled:e===1,className:"px-2 py-1 text-sm hover:bg-gray-50",children:[t.jsx(S.ChevronLeft,{className:" h-4 w-4"}),"Previous"]}),t.jsx("div",{className:"flex items-center gap-2",children:u.map((p,g)=>{if(p==="...")return t.jsx("span",{className:"px-2 text-muted-foreground",children:"..."},`ellipsis-${g}`);const v=p,w=v===e;return t.jsx(c.Button,{variant:w?"default":"outline",size:"sm",onClick:()=>h(v),className:w?"border-blue-600 bg-blue-600 px-3 py-1 text-sm text-white":"border px-3 py-1 text-sm hover:bg-gray-50 hover:text-black",children:v},v)})}),t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:m,disabled:e===s,className:"px-2 py-1 text-sm hover:bg-gray-50",children:["Next",t.jsx(S.ChevronRight,{className:" h-4 w-4"})]})]}),r&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Go to"}),t.jsx(c.Input,{type:"number",min:1,max:s,value:l,onChange:p=>{const g=p.target.value.replace(/[^\d]/g,"");o(g)},onKeyDown:y,className:"h-8 w-16 px-2 py-1"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:j,disabled:l===""||Number(l)<1||Number(l)>s,children:"Go"})]})]})}const Ru=x.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs"))),Gu=10*1024*1024,Fu=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAssets:a,isUploadingAsset:r,onUploaded:i})=>{const[l,o]=x.useState(()=>{const p=localStorage.getItem("chai_optimize_images");return p!==null?p==="true":!0});x.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,h=x.useCallback(async p=>{try{const v=p.map(async P=>{let D=P;return P.type.startsWith("image/")&&(D=await Ca(P)),new Promise((A,I)=>{const O=new FileReader;O.readAsDataURL(D),O.onload=async()=>{A({file:O.result,folderId:void 0,name:P.name,optimize:l})},O.onerror=()=>I(null)})}),w=await Promise.all(v),E=await a(w);return(E==null?void 0:E.length)===1&&i(E[0]),E}catch(g){return Promise.reject(g)}},[a,l,i]),d=p=>{const g=[];let v=0;return p.forEach(w=>{w.size>Gu?v++:g.push(w)}),v>0&&W.toast.error(`${v===1&&p.length===1?"File":v+(v===1?" file":" files")} exceed the maximum size limit of 10MB.`),f.isEmpty(g)?[]:h(g)},{getRootProps:m,getInputProps:j,isDragActive:y}=Or.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},disabled:e||r,multiple:!0});return t.jsx("div",{className:`flex h-[60px] w-full flex-col items-center justify-center rounded-lg border-2 border-dashed border-slate-300 p-0 py-2 hover:border-black/50 ${u?"pointer-events-none bg-gray-100 opacity-90":"bg-gray-100 hover:border-black/50 hover:bg-gray-100"}`,children:t.jsxs("div",{...m(),className:$.mergeClasses("flex h-max w-full cursor-pointer flex-col justify-center rounded-lg text-center",u?"items-start":"items-center",y?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...j()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 leading-tight",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(S.Loader,{className:"h-4 w-4 animate-spin text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs font-light text-muted-foreground",children:["Please wait while we ",e?"update":"upload"," your file..."]})]})]})}):t.jsxs("div",{className:"flex w-full items-center justify-between px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex items-center justify-between gap-2 leading-tight",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full border border-indigo-500 bg-indigo-100 p-2",children:t.jsx(S.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"cursor-pointer text-indigo-500 hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs font-light text-muted-foreground",children:[t.jsxs("span",{className:"",children:["Accepted file types: ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size: ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange:p=>{o(p)},onClick:p=>{p.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`flex cursor-help items-center text-amber-500 ${l?"invisible":""}`,children:t.jsx(S.AlertTriangle,{className:"mr-1 h-4 w-4"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-xs text-white",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Ir({close:e,onSelect:s,mode:n="image",assetId:a}){const l=x.useMemo(()=>[n],[n]),[o,u]=x.useState(null),[h,d]=x.useState(null),[m,j]=x.useState(null),[y,p]=x.useState({show:!1,file:""}),[g,v]=x.useState(!1),[w,E]=x.useState(a?"details":"grid"),[P,D]=x.useState(""),[A,I]=x.useState(""),[O,Y]=x.useState(1),[ee]=x.useState(30),[L,q]=x.useState([]);x.useEffect(()=>{a&&(u(a),E("details"))},[a]),x.useEffect(()=>{const _=setTimeout(()=>{D(A),Y(1)},300);return()=>clearTimeout(_)},[A]);const{data:F,isLoading:z}=Du({search:P.toLowerCase().trim(),page:O,limit:ee}),G=(F==null?void 0:F.assets)||[],Q=(F==null?void 0:F.total)||0,ae=Math.ceil(Q/ee);x.useEffect(()=>{z||ae<=0||Y(_=>_>ae?ae:_<1?1:_)},[z,ae]);const je=(G==null?void 0:G.length)>0,{mutate:Ne}=Iu(),{mutateAsync:ce,isPending:N}=Pu(),{mutate:b,isPending:C}=_u(),M=x.useCallback(_=>{const se=Math.min(Math.max(1,_),Math.max(1,ae));se!==O&&Y(se)},[ae,O]),T=_=>{I(_.target.value)},B=x.useCallback(_=>{q(se=>f.find(se,{id:_.id})?[]:[_])},[!1]),H=x.useCallback(()=>{q([])},[]),V=_=>{(_==null?void 0:_.length)!==0&&(s(f.pick(f.first(_||L),["id","url","width","height","description"])),e())},J=async _=>{d(_)},re=async()=>{h&&(j(h==null?void 0:h.id),await Ne(h.id,{onSuccess:()=>{j(null),d(null)},onError:()=>{j(null)}}),d(null))},K=_=>{u(_.id),E("details")},ie=async(_,se)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";se?(await ce([{file:_,folderId:void 0,name:y.name||"",optimize:Ee}]),p({show:!1,file:""})):(await b({id:y.id||"",file:_}),p({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},me=x.useCallback(_=>{q([_])},[]),xe=x.useCallback(_=>{M(_)},[M]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-[80vh] max-h-[1232px] w-[80vw] max-w-[1232px] flex-col space-y-4",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),w==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Fu,{maxFileSize:10,allowedTypes:l,uploadAssets:ce,isUpdatingAsset:C,isUploadingAsset:N,onUploaded:me}),t.jsxs("div",{className:"relative flex flex-1 flex-col gap-y-3 overflow-hidden rounded-lg border p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2",children:[t.jsx(S.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${A.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:T,value:A,className:"pl-8"})]}),L.length>0?t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("div",{className:"flex items-center gap-2",children:[L.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>H(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>V(L),disabled:L.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:z?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"})]}):!z&&!je?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center rounded-lg border",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(S.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-lg text-muted-foreground",children:"No assets found"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:P.length>0?"No assets found for your search: "+P:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:G==null?void 0:G.map(_=>t.jsxs("div",{className:$.mergeClasses("group relative flex max-h-[180px] max-w-[180px] cursor-pointer flex-col justify-between overflow-hidden rounded-lg border-2 transition-all",L.some(se=>se.id===_.id)?"border-blue-500":"hover:border-black/90",m&&(h==null?void 0:h.id)===_.id?"pointer-events-none opacity-50":"",m===_.id?"pointer-events-none opacity-50":""),onClick:()=>B(_),onDoubleClick:()=>V([_]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===_.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(S.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,_.type==="image"?t.jsx("img",{src:`${_.thumbnailUrl||"/placeholder.svg"}?v=${(_==null?void 0:_.updatedAt)||_.createdAt}`,alt:_.name,className:`h-full min-h-[80px] w-full object-contain ${L.some(se=>se.id===_.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex h-full items-center justify-center",children:[t.jsx(S.Film,{className:"h-12 w-12 text-muted-foreground"}),_.thumbnailUrl&&t.jsx("img",{src:`${_.thumbnailUrl||"/placeholder.svg"}?v=${(_==null?void 0:_.updatedAt)||_.createdAt}`,alt:_.name,className:"absolute inset-0 h-full w-full object-cover"})]})]}),t.jsxs("div",{className:"flex items-end justify-between border-t-[1px] border-black/10 bg-white px-2 py-1",children:[t.jsx("div",{className:"truncate text-xs leading-tight",title:_.name,children:_.name}),t.jsx("div",{className:"flex items-center justify-between whitespace-nowrap text-[9px] font-light text-muted-foreground",children:t.jsx("span",{children:nn((_==null?void 0:_.size)||0)})})]}),!L.some(se=>se.id===_.id)&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),K(_)},children:t.jsx(S.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),navigator.clipboard.writeText(_.url),W.toast.success("Asset URL copied to clipboard")},children:t.jsx(S.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),p({id:_.id,show:!0,file:_.url,name:_.name})},children:t.jsx(S.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),J(_)},children:t.jsx(S.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),L.some(se=>se.id===_.id)&&t.jsx("div",{className:"absolute right-1 top-1 h-max rounded-full border border-white bg-blue-500 p-1",children:t.jsx(S.Check,{className:"h-3 w-3 text-white",strokeWidth:5})})]},_.id))})}),ae>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 border-t bg-white p-4",children:t.jsx(Au,{fallback:t.jsx("div",{className:"text-red-500",children:"Error loading pagination"}),children:t.jsx(Ou,{currentPage:O,totalPages:ae,onPageChange:xe,pageRangeDisplayed:3,showPageInput:!0})})})]})]}):t.jsx(Mu,{assetId:o||a||"",onBack:()=>{E("grid"),u(null)},onEdit:_=>{p({id:_.id,show:!0,file:_.url,name:_.name})},onSave:async _=>{if(o){v(!0);try{const se=G.find(Ee=>Ee.id===o);se&&await b(f.merge(se,{description:_}))}finally{v(!1)}}},isSaving:g})]}),y.show&&t.jsx(x.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(S.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Ru,{imageUrl:y.file,onSave:ie,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),h&&t.jsx(c.Dialog,{open:!!h,onOpenChange:()=>d(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',h.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>d(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:re,children:"Delete"})]})]})})]})}const Uu=Object.freeze(Object.defineProperty({__proto__:null,default:Ir},Symbol.toStringTag,{value:"Module"})),Bs=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,o]=x.useState(!1),u=()=>{i||o(!0)},h=()=>{o(!1)},d=y=>{const p=Array.isArray(y)?y[0]:y;p!=null&&p.url&&n(f.pick(p,["url","id"])),o(!1)},m=()=>{n({url:"",id:""})},j=(s==null?void 0:s.startsWith("{{"))&&(s==null?void 0:s.endsWith("}}"));return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative overflow-hidden rounded-md border",children:[j?t.jsx("div",{className:"flex h-12 items-center bg-gray-100 px-4",children:t.jsx("p",{className:"text-xs text-gray-500",children:s})}):t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"h-auto max-h-[100px] w-full bg-gray-100 object-contain"}),t.jsxs("div",{className:"absolute right-2 top-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8 rounded-full bg-white text-red-500",onClick:m,disabled:i,children:j?t.jsx(S.X,{className:"h-4 w-4"}):t.jsx(S.Trash2,{className:"h-4 w-4"})}),!j&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(S.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex cursor-pointer items-center justify-center rounded-md border border-dashed p-6 ${i?"cursor-not-allowed opacity-50":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(S.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(c.Dialog,{open:l,onOpenChange:o,children:t.jsxs(c.DialogContent,{className:"h-fit w-full max-w-7xl overflow-hidden p-0",children:[t.jsxs(c.DialogHeader,{className:"hidden border-b px-4 py-2",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:h,children:t.jsx(S.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"h-full flex-1 p-4",children:t.jsx(Ir,{close:h,onSelect:d,mode:"image",assetId:e})})]})})]})},qu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),$u=()=>{const[e,s]=x.useState({logoUrl:"",logoId:"",faviconUrl:"",faviconId:""}),[n,a]=x.useState(!1),r=()=>{a(!0),setTimeout(()=>{a(!1),console.log("Branding settings saved:",e)},1e3)};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Branding Settings"}),t.jsxs("div",{className:"rounded space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Logo"}),t.jsx(Bs,{assetId:e.logoId,assetUrl:e.logoUrl,onChange:i=>{s({...e,logoUrl:i.url,logoId:i.id})},placeholder:"Select logo image",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 200x50px"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Favicon"}),t.jsx(Bs,{assetId:e.faviconId,assetUrl:e.faviconUrl,onChange:i=>{s({...e,faviconUrl:i.url,faviconId:i.id})},placeholder:"Select favicon",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 32x32px"})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:r,disabled:n,className:"w-full",children:n?"Saving...":"Save Branding Settings"})})]})]})},zu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),Vu=()=>{const[e,s]=x.useState({contactEmail:"",contactPhone:"",contactAddress:""}),[n,a]=x.useState([]),[r,i]=x.useState({isOpen:!1,platform:"",url:"",customName:""}),[l,o]=x.useState(!1),u=[{value:"facebook",label:"Facebook"},{value:"twitter",label:"Twitter"},{value:"linkedin",label:"LinkedIn"},{value:"instagram",label:"Instagram"},{value:"youtube",label:"YouTube"},{value:"other",label:"Other"}],h=g=>s(v=>({...v,[g.target.name]:g.target.value})),d=()=>{const{platform:g,url:v,customName:w}=r;if(!v.trim()||!g)return;const E=g==="other"?w:g;E.trim()&&(a(P=>[...P,{platform:E,url:v,isCustom:g==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=g=>a(v=>v.filter((w,E)=>E!==g)),j=()=>i({isOpen:!1,platform:"",url:"",customName:""}),y=()=>{o(!0);const g={};n.forEach(w=>{g[w.platform.toLowerCase().replace(/\s+/g,"_")]=w.url});const v={...e,socialLinks:g};setTimeout(()=>{o(!1),console.log("Contact & Social settings saved:",v),s({contactEmail:"",contactPhone:"",contactAddress:""}),a([]),i({isOpen:!1,platform:"",url:"",customName:""})},1e3)},p=e.contactEmail.trim()||e.contactPhone.trim()||e.contactAddress.trim();return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Contact & Social Settings"}),t.jsxs("div",{className:"space-y-4 rounded",children:[t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Email"}),t.jsx("input",{type:"email",name:"contactEmail",value:e.contactEmail,onChange:h,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"contact@example.com"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Phone"}),t.jsx("input",{type:"tel",name:"contactPhone",value:e.contactPhone,onChange:h,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"+1 (555) 123-4567"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Address"}),t.jsx("textarea",{name:"contactAddress",value:e.contactAddress,onChange:h,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"Enter your business address",rows:3})]})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("h3",{className:"text-md font-medium text-gray-900",children:"Links"}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>i(g=>({...g,isOpen:!0})),className:"text-sm",children:"Add Link"})]}),r.isOpen&&t.jsxs("div",{className:"space-y-3 rounded border bg-gray-50 p-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Platform"}),t.jsxs("select",{value:r.platform,onChange:g=>i(v=>({...v,platform:g.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",children:[t.jsx("option",{value:"",children:"Select platform"}),u.map(g=>t.jsx("option",{value:g.value,children:g.label},g.value))]})]}),r.platform==="other"&&t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Platform Name"}),t.jsx("input",{type:"text",value:r.customName,onChange:g=>i(v=>({...v,customName:g.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"e.g., TikTok, Discord, Snapchat"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"URL"}),t.jsx("input",{type:"url",value:r.url,onChange:g=>i(v=>({...v,url:g.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"https://platform.com/yourprofile"})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{type:"button",onClick:d,disabled:!r.platform||!r.url.trim()||r.platform==="other"&&!r.customName.trim(),className:"flex-1",children:"Save Link"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:j,className:"flex-1",children:"Cancel"})]})]}),n.length>0&&t.jsx("div",{className:"space-y-2",children:n.map((g,v)=>t.jsxs("div",{className:"flex items-center justify-between rounded border p-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-sm font-medium capitalize",children:g.platform}),t.jsx("p",{className:"max-w-xs truncate text-xs text-gray-500",children:g.url})]}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m(v),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},v))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:y,disabled:!p||l,className:"w-full",children:l?"Saving...":"Save Contact & Social Settings"})})]})]})},Ku=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),Hu=()=>{const[e,s]=x.useState({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),[n,a]=x.useState([]),[r,i]=x.useState(""),[l,o]=x.useState(!1),u=y=>{const{name:p,value:g}=y.target;s(v=>({...v,[p]:g}))},h=()=>{r.trim()&&(a(y=>[...y,{id:Date.now().toString(),content:r}]),i(""))},d=y=>{a(p=>p.filter(g=>g.id!==y))},m=()=>{o(!0);const y={...e,customTrackingScripts:n.map(p=>p.content)};setTimeout(()=>{o(!1),console.log("Analytics & Tracking settings saved:",y),s({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),a([])},1e3)},j=Object.values(e).some(y=>y.trim())||n.length>0;return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Analytics & Tracking Settings"}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Google Analytics ID"}),t.jsx("input",{type:"text",name:"googleAnalyticsId",value:e.googleAnalyticsId,onChange:u,placeholder:"UA-XXXXXXXXX-X",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Google Tag Manager ID"}),t.jsx("input",{type:"text",name:"googleTagManagerId",value:e.googleTagManagerId,onChange:u,placeholder:"GTM-XXXXXX",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Meta Pixel ID"}),t.jsx("input",{type:"text",name:"metaPixelId",value:e.metaPixelId,onChange:u,placeholder:"XXXXXXXXXX",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("div",{className:"mb-2 flex items-center justify-between",children:t.jsx("label",{className:"text-sm font-medium",children:"Custom Tracking Scripts"})}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("textarea",{value:r,onChange:y=>i(y.target.value),placeholder:"Paste your tracking script code",className:"input-border min-h-[80px] w-full rounded px-3 py-2 font-mono text-sm",rows:4}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Add custom tracking scripts (e.g., Hotjar, Mixpanel, etc.)"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:h,disabled:!r.trim(),children:"Add Script"})]})]})]}),n.length>0&&t.jsx("div",{className:"mb-3 space-y-2",children:n.map(y=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"flex-1 overflow-hidden rounded border bg-gray-50 p-2",children:t.jsx("code",{className:"block max-h-20 overflow-auto text-xs",children:y.content.length>100?`${y.content.substring(0,100)}...`:y.content})}),t.jsx(c.Button,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>d(y.id),children:"Remove"})]},y.id))}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:m,disabled:!j||l,className:"w-full",children:l?"Saving...":"Save Settings"})})]})]})},Qu=()=>{Ss("branding",{label:"Branding",button:qu,panel:$u}),Ss("contact-social",{label:"Contact & Social",button:zu,panel:Vu}),Ss("analytics-tracking",{label:"Analytics & Tracking",button:Ku,panel:Hu})},Wu=x.lazy(()=>Promise.resolve().then(()=>Uu));Nu();Rr.loadWebBlocks();$.registerChaiTopBar(Zl);_o();Qu();$.registerChaiMediaManager(Wu);$.registerChaiSaveToLibrary(Ei);const Ju=e=>{const s=x.useRef([]),[n]=Pe(),a=n.get("page"),{data:r}=ke(),{data:i={role:"",permissions:null}}=Ga();no(),ui();const{data:l,isFetching:o}=Na(),{blocks:u}=so(l),{data:h}=Ce(),{mutateAsync:d}=fa(),m=eo(),{onSave:j}=ao(),{getPartialBlocks:y,getPartialBlockBlocks:p}=ro(),{aiContext:g,setAiContext:v}=yn(),{mutateAsync:w}=Ti(),[E,P]=x.useState(!1),{data:D}=Ve(),A=We(),{data:I}=bn(),{data:O}=Eu(),{mutateAsync:Y}=Cu(),ee=Pr();Xr(),x.useEffect(()=>{const z=()=>{document.hidden?P(!0):P(!1)};return window.addEventListener("visibilitychange",z),()=>window.removeEventListener("visibilitychange",z)},[]),s.current=u;const L=x.useMemo(()=>{const z={};return i&&(z.permissions=f.get(i,"permissions",null),z.role=f.get(i,"role","user")),z},[i]),q=x.useCallback(async(z,G)=>await w({pageType:z,query:G}),[w]),F=x.useMemo(()=>f.get(D,"theme",{})||{},[D]);return t.jsxs(t.Fragment,{children:[t.jsx($.ChaiBuilderEditor,{gotoPage:ee,collections:O??[],getBlockAsyncProps:Y,pageExternalData:I,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:A,languages:(D==null?void 0:D.languages)||[],brandingOptions:(D==null?void 0:D.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!E&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:y,blocks:o?[]:u,theme:f.cloneDeep(F),pageTypes:h,searchPageTypeItems:q,saveAiContextCallback:async z=>{if(!a)return!0;const G=s.current,Q={_type:"@chai/ai-context",_value:f.isString(z)?z:""},ae=[...G,Q];return await j({page:a,blocks:ae}),v(z),!0},aiContext:g,askAiCallBack:m,onSave:async({blocks:z,theme:G,needTranslations:Q})=>{if(!a)return!0;s.current=z;const ae={_type:"@chai/ai-context",_value:f.isString(g)?g:""},je=[...z,ae];return await j({page:a,blocks:je,needTranslations:Q}),s.current=je,f.isEqual(G,F)||await d({settings:{theme:G}}),!0},themePanelComponent:Mi,...L}),t.jsxs("div",{children:[t.jsx(fi,{}),t.jsx(xi,{})]})]})},Yu=new U.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Xu=e=>{const{isLoggedIn:s}=Oe(),[,n]=xa(),[a,r]=x.useState(!1);return x.useEffect(()=>(n(f.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","getAccessToken","supabaseInstance"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?t.jsxs(U.QueryClientProvider,{client:Yu,children:[s?t.jsx(Ju,{...e}):t.jsx(co,{}),t.jsx(Su,{})]}):t.jsx("div",{})},Zu=()=>{const e=oe(),s=Z(),{data:n}=Je(),a=U.useQueryClient();return U.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:R.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[R.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},ed=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ha();return x.useCallback(async({url:n,method:a="GET",body:r={},headers:i={}})=>{const l=await s();if(!l)throw new Error("No auth token");if(!n)throw new Error("URL is required");try{const o=await fetch(n,{method:a,headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`,...i},body:JSON.stringify(r)});if(o.status===401)return console.log("Session expired",o),await e(),window.location.reload(),null;if(o.status===400)throw new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",o),o}},[e,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Dn;exports.ChaiBuilderPages=Xu;exports.ChaiBuilderPagesRealtime=ba;exports.Dynamic=kc;exports.For=ec;exports.ImagePicker=Bs;exports.Index=tc;exports.LanguageSwitcher=_n;exports.Match=ac;exports.NestedPathSelector=He;exports.PermissionChecker=Me;exports.Portal=Tc;exports.Show=sc;exports.SmartJsonInput=ln;exports.Switch=nc;exports.addEventListener=lr;exports.batch=Oo;exports.className=ir;exports.clearDelegatedEvents=pc;exports.convertRemToPixels=pu;exports.createComponent=Mn;exports.createComputed=Ha;exports.createContext=qo;exports.createEffect=Ln;exports.createMemo=Te;exports.createRenderEffect=st;exports.createRoot=tt;exports.createSignal=we;exports.createUniqueId=Zo;exports.delegateEvents=rr;exports.deleteNestedDataByPath=Ft;exports.displayValue=du;exports.getMutationStatusColor=cu;exports.getPreferredColorScheme=yu;exports.getQueryStatusColor=ou;exports.getQueryStatusColorByLabel=uu;exports.getQueryStatusLabel=iu;exports.getSidedProp=lu;exports.insert=Ls;exports.memo=fc;exports.mergeProps=On;exports.mutationSortFns=gu;exports.on=Ro;exports.onCleanup=Dt;exports.onMount=Qa;exports.registerChaiSiteSetting=Ss;exports.registerLoginComponent=oo;exports.serialize=Cr;exports.setAttribute=Ds;exports.sortFns=fu;exports.splitProps=tr;exports.spread=or;exports.stringify=ru;exports.template=gc;exports.untrack=Ae;exports.updateNestedDataByPath=Gt;exports.use=cr;exports.useActivePage=Je;exports.useBuilderPageData=bn;exports.useChaiAuth=Oe;exports.useChaiFetch=ed;exports.useChaiUserInfo=Ke;exports.useContext=$o;exports.useCurrentPage=ke;exports.useFallbackLang=We;exports.useFetch=Z;exports.useGotoPage=Pr;exports.useLanguagePages=Ue;exports.usePageTypes=Ce;exports.useTransition=Uo;exports.useUpdateActivePageMetadata=Zu;exports.useUserRoleAndPermissions=Ga;exports.useWebsitePages=dt;exports.useWebsiteSetting=Ve;
13
+ `),F=e.substring(0,I)+q+e.substring(O);s(F),setTimeout(()=>{A.selectionStart=I,A.selectionEnd=I+q.length},0)}}else{const Y=e.substring(0,I)+" "+e.substring(O);s(Y),setTimeout(()=>{A.selectionStart=A.selectionEnd=I+2},0)}}};x.useEffect(()=>{const D=Qn(e);if(D.isValid)if(j(null),D.parsed){const A=vo(D.parsed,o);p(A)}else p("");else j(D.error),p("")},[e,o]);const E=()=>{const D=Qn(e);if(D.isValid&&D.parsed){const A=jo(D.parsed,D.placeholders);s(A)}},P=()=>{m!=null&&m.position&&g.current&&(g.current.focus(),g.current.setSelectionRange(m.position,m.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(c.Tabs,{value:h,onValueChange:d,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(c.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(S.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||m!==null,children:[t.jsx(S.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),h==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(He,{dataType:"value",data:o??{},onSelect:D=>u&&u(D,l)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:E,disabled:!e.trim()||n||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:g,id:l,name:l,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:v,onKeyDown:w,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),m&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(S.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(c.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:m.message}),m.line&&m.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",m.line,", column ",m.column]}),t.jsx(c.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:P,children:"Show position"})]})]})]}),t.jsxs(c.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(c.Textarea,{rows:i,value:y,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]})]})})},Wn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},bo=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),o=`{{${s}}}`,u=i+""+o+l,h=n+0+o.length;return{value:u,newCursorPos:h}},Ua=()=>{const{t:e}=$.useTranslation(),[,s]=$.useSidebarActivePanel(),{data:n}=ke(),{data:a}=bn(),{data:r,isFetching:i}=xo(),l=r==null?void 0:r.seo,o=x.useRef(null),u=n==null?void 0:n.id,h=n==null?void 0:n.pageType,d=Ta(h),{selectedLang:m,fallbackLang:j}=$.useLanguages(),y=m||j,p=$.useChaiFeatureFlag("enable-seo-meta-tab"),[g,v]=x.useState(!1),[w,E]=x.useState(!1),[P,D]=x.useState(!1),[A,I]=x.useState(null),[O,Y]=x.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",metaOther:"{}",...l}),ee=x.useRef({}),{mutate:L,isPending:q}=wn(),F=q||g||w,{hasPermission:z}=$.usePermissions(),G=z(ve.EDIT_SEO);x.useEffect(()=>{if(!i&&l&&u){const C={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",metaOther:"",...l};Y(C),ee.current[y]=C}},[i,l,y,u]),x.useEffect(()=>{const C=M=>{const{fromLang:T,toLang:B,switchHandler:H}=M.detail,V=ee.current[y];(V?!f.isEqual(V,O):!1)?(I({fromLang:T,toLang:B,switchHandler:H}),D(!0)):H()};return window.addEventListener("seo-language-switch-check",C),()=>{window.removeEventListener("seo-language-switch-check",C)}},[u,O,y]);const Q=async()=>{if(!(!d||!y))try{v(!0);const C=qt(d,y),M={...O,keyword:f.get(C,"seo.keyword",""),title:f.get(C,"seo.title",""),description:f.get(C,"seo.description",""),cononicalUrl:f.get(C,"seo.canonicalUrl",""),noIndex:f.get(C,"seo.noIndex",!1),noFollow:f.get(C,"seo.noFollow",!1),ogTitle:f.get(C,"seo.ogTitle",""),ogDescription:f.get(C,"seo.ogDescription","")};Y(M),W.toast.success(e("SEO fields reset to defaults"))}catch(C){W.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",C)}finally{v(!1)}},ae=async()=>{if(!(!d||!y))try{E(!0);const C=qt(d,y),M={...O,jsonLD:f.get(C,"seo.jsonLD","")};Y(M),W.toast.success(e("JSON-LD reset to default"))}catch(C){W.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",C)}finally{E(!1)}},je=async()=>{if(!(!d||!y))try{v(!0);const C=qt(d,y),M={...O,ogTitle:f.get(C,"seo.ogTitle",""),ogDescription:f.get(C,"seo.ogDescription",""),ogImage:f.get(C,"seo.ogImage",""),ogImageId:f.get(C,"seo.ogImageId",""),metaOther:f.get(C,"seo.metaOther","{}")};Y(M),W.toast.success(e("Meta Tag fields reset to defaults"))}catch(C){W.toast.error(e("Failed to reset Meta Tag fields")),console.error("Reset Meta Tag error:",C)}finally{v(!1)}},Ne=async()=>{L({id:r==null?void 0:r.id,seo:O,primaryPage:u},{onSuccess:()=>{console.log("SEO & JSON-LD updated successfully",O),ee.current[y]=O,W.toast.success("SEO & JSON-LD updated successfully")}})},ce=(C,M)=>{const T=document.getElementById(M);if(T){const{value:B,newCursorPos:H}=bo(T,C);o.current={id:M,position:H},T.tagName.toLowerCase()==="input"?(T.value=B,Y(re=>({...re,[T.name]:B})),T.focus(),T.setSelectionRange(H,H),[0,10,50,100,200].forEach(re=>{setTimeout(()=>{const K=document.getElementById(M);K&&(K.focus(),K.setSelectionRange(H,H))},re)})):(Y(J=>({...J,[T.name]:B})),requestAnimationFrame(()=>{const J=document.getElementById(M);J&&(J.focus(),J.setSelectionRange(H,H),setTimeout(()=>{const re=document.getElementById(M);re&&(re.focus(),re.setSelectionRange(H,H))},50))}))}},N=C=>{const M={...O,[C.target.name]:C.target.name==="noIndex"||C.target.name==="noFollow"?C.target.checked:C.target.value};Y(M)},b=C=>M=>{f.isEmpty(M.fieldValue)||N({target:{name:C,value:typeof M.fieldValue=="string"?M.fieldValue.replace(/^"(.*)"$/,"$1"):M.fieldValue}}),M.error&&W.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:M.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!G&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm",children:t.jsx(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"no-scrollbar flex-grow overflow-y-auto px-2 pb-20",children:[t.jsxs("div",{className:"mb-4 flex w-full items-center justify-between rounded-md bg-gray-100 px-2 py-1 text-left text-sm",children:[t.jsxs("span",{children:[t.jsx("div",{className:"font-medium",children:r==null?void 0:r.name}),t.jsx("span",{className:"font-mono text-xs leading-tight text-gray-500",children:r==null?void 0:r.slug})]}),t.jsx(_n,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(c.TabsList,{className:`mb-4 grid w-full ${p?"grid-cols-3":"grid-cols-2"}`,children:[t.jsx(c.TabsTrigger,{value:"seo",children:e("SEO Fields")}),p&&t.jsx(c.TabsTrigger,{value:"opengraph",children:e("Meta Tags")}),t.jsx(c.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(c.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[G&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:Q,disabled:F||!G||!d,children:e(g?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:O.keyword,onChange:N,disabled:F||!G,placeholder:e("Enter keyword"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("title"),field:"title"}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:O.title,onChange:N,disabled:F||!G,placeholder:e("Enter SEO title"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("description"),field:"description"}),G&&t.jsx(He,{data:a??{},onSelect:C=>ce(C,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:O.description,onChange:N,disabled:F||!G,placeholder:e("Enter SEO description"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:O.canonicalUrl,onChange:N,disabled:F||!G,placeholder:e("Enter Canonical URL"),readOnly:!G})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:O.noIndex,onChange:N,disabled:F||!G,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:O.noFollow,onChange:N,disabled:F||!G,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to follow links on this page.")})]})]})}),t.jsx(c.TabsContent,{value:p?"opengraph":"seo",children:t.jsxs("div",{className:"space-y-4",children:[G&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:je,disabled:F||!G||!d,children:e(g?"Resetting...":"Reset to Default")})}),t.jsxs("div",{children:[t.jsx("h3",{className:"mb-4 font-semibold text-slate-700",children:e("Open Graph")}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("ogTitle"),field:"ogTitle"}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:O.ogTitle,onChange:N,disabled:F||!G,placeholder:e("Enter OG title"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ft,{keyword:O.keyword,onComplete:b("ogDescription"),field:"ogDescription"}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>ce(C,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:O.ogDescription,onChange:N,disabled:F||!G,placeholder:e("Enter OG description"),readOnly:!G})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")}),G&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>{Y({...O,ogImage:`{{${C}}}`,ogImageId:""})}})]}),t.jsx(Bs,{assetId:O.ogImageId,assetUrl:O.ogImage,onChange:C=>{Y({...O,ogImage:C.url,ogImageId:C.id})},disabled:F||!G,placeholder:e("Select OG image"),className:"mb-2"})]}),p&&t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"metaOther",children:e("Meta Tags")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(ft,{keyword:O.keyword,onComplete:b("metaOther"),field:"metaOther"})})]}),t.jsx(ln,{id:"metaOther",value:O.metaOther,onChange:C=>{N({target:{name:"metaOther",value:C}})},placeholder:e("Enter Meta Tags JSON"),disabled:F||!G,readOnly:!G,pageData:a||{},rows:8,handleFieldInsert:ce})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[G&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:ae,disabled:F||!G||!d,children:e(w?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(ft,{keyword:O.keyword,onComplete:b("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(ln,{id:"jsonLD",value:O.jsonLD,onChange:C=>{N({target:{name:"jsonLD",value:C}})},placeholder:e("Enter JSON-LD"),disabled:F||!G,readOnly:!G,pageData:a||{},rows:12,handleFieldInsert:ce})]})]})})]})})]}),G&&t.jsxs("div",{className:"fixed bottom-0 left-0 right-0 flex w-full flex-shrink-0 items-center justify-between border-t bg-background p-4",children:[Wn(O.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:e("Invalid JSON. Please check.")}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(c.Button,{onClick:Ne,disabled:!Wn(O==null?void 0:O.jsonLD)||(ee.current[y]?f.isEqual(ee.current[y],O):!1)||F||!G,children:e(q?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(po,{isOpen:P,onClose:()=>{D(!1),I(null)},onSave:async()=>{A&&(await Ne(),A.switchHandler(),D(!1),I(null))},onDiscard:()=>{if(A){const C=ee.current[y];C&&Y(C),A.switchHandler(),D(!1),I(null)}},isSaving:q,fromLanguage:(A==null?void 0:A.fromLang)||y,toLanguage:(A==null?void 0:A.toLang)||""})]})};Ua.displayName="SeoPanel";const qa="seo",wo=({isActive:e,show:s})=>{const{data:n}=ke(),a=Ta(n==null?void 0:n.pageType);return!f.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},So={id:qa,label:"SEO",panel:Ua,button:wo,position:"top",width:600,view:"modal"},on={},Ss=(e,s)=>{f.has(on,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),f.set(on,e,{id:e,...s})},No=()=>f.values(on),Eo=()=>{var i;const e=No(),[s,n]=x.useState(((i=e[0])==null?void 0:i.id)||""),a=e.find(l=>l.id===s),r=a==null?void 0:a.panel;return t.jsxs("div",{className:"flex h-full gap-4",children:[t.jsx("div",{className:"no-scrollbar max-w-[25%] overflow-y-auto border-r pr-2",children:t.jsx("div",{className:"space-y-1",children:e.map(l=>{const o=l.id===s,u=l.button;return t.jsx("div",{className:"mb-1",children:t.jsx(u,{isActive:o,onClick:()=>n(l.id)})},l.id)})})}),t.jsx("div",{className:"no-scrollbar flex-1 overflow-y-auto",children:t.jsx(x.Suspense,{fallback:t.jsx("div",{className:"flex items-center justify-center h-full",children:"Loading..."}),children:r?t.jsx(r,{}):t.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:t.jsx("p",{children:"Select a setting from the sidebar or register settings using registerChaiSiteSetting"})})})})]})},Co="site-settings",To=({isActive:e,show:s})=>$.useChaiFeatureFlag("enable-site-settings")?t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsx(S.Settings,{className:"h-4 w-4"})}):null,Ao={id:Co,label:"Site Settings",panel:Eo,button:To,position:"bottom",width:800,view:"modal"},ko="user-info",Po=()=>{const{user:e,logout:s}=Oe(),n=qe("onLogout",f.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(S.User,{className:"h-4 w-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto space-y-2 p-4",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),f.isFunction(n)&&n()},children:"Logout"})]})]})]})]})]}):null},Io={id:ko,label:"User Info",button:Po,position:"bottom"},_o=()=>{$.registerChaiSidebarPanel(qa,So),$.registerChaiSidebarPanel(Fa,fo),$.registerChaiSidebarPanel("site-settings",Ao),$.registerChaiSidebarPanel("user-info",Io)};var ne={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Jn(this.context.count)},getNextContextId(){return Jn(this.context.count++)}};function Jn(e){const s=String(e),n=s.length-1;return ne.context.id+(n?String.fromCharCode(96+n):"")+s}function Rt(e){ne.context=e}var $a=!1,Do=(e,s)=>e===s,Ts=Symbol("solid-proxy"),za=typeof Proxy=="function",Dn=Symbol("solid-track"),As={equals:Do},Va=Za,Xe=1,ks=2,Ka={owned:null,cleanups:null,context:null,owner:null},Xs={},de=null,Zs=null,Lo=null,ge=null,Ie=null,Qe=null,Fs=0;function tt(e,s){const n=ge,a=de,r=e.length===0,i=s===void 0?a:s,l=r?Ka:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Ae(()=>Kt(l)));de=l,ge=null;try{return ze(o,!0)}finally{ge=n,de=a}}function we(e,s){s=s?Object.assign({},As,s):As;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Xa(n,r));return[Ya.bind(n),a]}function Ha(e,s,n){const a=Us(e,s,!0,Xe);Mt(a)}function st(e,s,n){const a=Us(e,s,!1,Xe);Mt(a)}function Ln(e,s,n){Va=Ho;const a=Us(e,s,!1,Xe);(!n||!n.render)&&(a.user=!0),Qe?Qe.push(a):Mt(a)}function Te(e,s,n){n=n?Object.assign({},As,n):As;const a=Us(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Mt(a),Ya.bind(a)}function Bo(e){return e&&typeof e=="object"&&"then"in e}function Mo(e,s,n){let a,r,i;a=!0,r=e,i={};let l=null,o=Xs,u=null,h=!1,d="initialValue"in i,m=typeof a=="function"&&Te(a);const j=new Set,[y,p]=(i.storage||we)(i.initialValue),[g,v]=we(void 0),[w,E]=we(void 0,{equals:!1}),[P,D]=we(d?"ready":"unresolved");ne.context&&(u=ne.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:ne.load&&ne.has(u)&&(o=ne.load(u)));function A(L,q,F,z){return l===L&&(l=null,z!==void 0&&(d=!0),(L===o||q===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(z,{value:q})),o=Xs,I(q,F)),q}function I(L,q){ze(()=>{q===void 0&&p(()=>L),D(q!==void 0?"errored":d?"ready":"unresolved"),v(q);for(const F of j.keys())F.decrement();j.clear()},!1)}function O(){const L=zo,q=y(),F=g();if(F!==void 0&&!l)throw F;return ge&&ge.user,q}function Y(L=!0){if(L!==!1&&h)return;h=!1;const q=m?m():a;if(q==null||q===!1){A(l,Ae(y));return}let F;const z=o!==Xs?o:Ae(()=>{try{return r(q,{value:y(),refetching:L})}catch(G){F=G}});if(F!==void 0){A(l,void 0,Ns(F),q);return}else if(!Bo(z))return A(l,z,void 0,q),z;return l=z,"v"in z?(z.s===1?A(l,z.v,void 0,q):A(l,void 0,Ns(z.v),q),z):(h=!0,queueMicrotask(()=>h=!1),ze(()=>{D(d?"refreshing":"pending"),E()},!1),z.then(G=>A(z,G,void 0,q),G=>A(z,void 0,Ns(G),q)))}Object.defineProperties(O,{state:{get:()=>P()},error:{get:()=>g()},loading:{get(){const L=P();return L==="pending"||L==="refreshing"}},latest:{get(){if(!d)return O();const L=g();if(L&&!l)throw L;return y()}}});let ee=de;return m?Ha(()=>(ee=de,Y(!1))):Y(!1),[O,{refetch:L=>Wa(ee,()=>Y(L)),mutate:p}]}function Oo(e){return ze(e,!1)}function Ae(e){if(ge===null)return e();const s=ge;ge=null;try{return e()}finally{ge=s}}function Ro(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let o;if(a){o=Array(e.length);for(let h=0;h<e.length;h++)o[h]=e[h]()}else o=e();if(i)return i=!1,l;const u=Ae(()=>s(o,r,l));return r=o,u}}function Qa(e){Ln(()=>Ae(e))}function Dt(e){return de===null||(de.cleanups===null?de.cleanups=[e]:de.cleanups.push(e)),e}function Yn(){return de}function Wa(e,s){const n=de,a=ge;de=e,ge=null;try{return ze(s,!0)}catch(r){Bn(r)}finally{de=n,ge=a}}function Go(e){const s=ge,n=de;return Promise.resolve().then(()=>{ge=s,de=n;let a;return ze(e,!1),ge=de=null,a?a.done:void 0})}var[Fo,sd]=we(!1);function Uo(){return[Fo,Go]}function qo(e,s){const n=Symbol("context");return{id:n,Provider:Qo(n),defaultValue:e}}function $o(e){let s;return de&&de.context&&(s=de.context[e.id])!==void 0?s:e.defaultValue}function Ja(e){const s=Te(e),n=Te(()=>cn(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var zo;function Ya(){if(this.sources&&this.state)if(this.state===Xe)Mt(this);else{const e=Ie;Ie=null,ze(()=>Is(this),!1),Ie=e}if(ge){const e=this.observers?this.observers.length:0;ge.sources?(ge.sources.push(this),ge.sourceSlots.push(e)):(ge.sources=[this],ge.sourceSlots=[e]),this.observers?(this.observers.push(ge),this.observerSlots.push(ge.sources.length-1)):(this.observers=[ge],this.observerSlots=[ge.sources.length-1])}return this.value}function Xa(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&ze(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=Zs&&Zs.running;l&&Zs.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Ie.push(i):Qe.push(i),i.observers&&er(i)),l||(i.state=Xe)}if(Ie.length>1e6)throw Ie=[],new Error},!1)),s}function Mt(e){if(!e.fn)return;Kt(e);const s=Fs;Vo(e,e.value,s)}function Vo(e,s,n){let a;const r=de,i=ge;ge=de=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Xe,e.owned&&e.owned.forEach(Kt),e.owned=null),e.updatedAt=n+1,Bn(l)}finally{ge=i,de=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Xa(e,a):e.value=a,e.updatedAt=n)}function Us(e,s,n,a=Xe,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:de,context:de?de.context:null,pure:n};return de===null||de!==Ka&&(de.owned?de.owned.push(i):de.owned=[i]),i}function Ps(e){if(e.state===0)return;if(e.state===ks)return Is(e);if(e.suspense&&Ae(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<Fs);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Xe)Mt(e);else if(e.state===ks){const a=Ie;Ie=null,ze(()=>Is(e,s[0]),!1),Ie=a}}function ze(e,s){if(Ie)return e();let n=!1;s||(Ie=[]),Qe?n=!0:Qe=[],Fs++;try{const a=e();return Ko(n),a}catch(a){n||(Qe=null),Ie=null,Bn(a)}}function Ko(e){if(Ie&&(Za(Ie),Ie=null),e)return;const s=Qe;Qe=null,s.length&&ze(()=>Va(s),!1)}function Za(e){for(let s=0;s<e.length;s++)Ps(e[s])}function Ho(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:Ps(a)}if(ne.context){if(ne.count){ne.effects||(ne.effects=[]),ne.effects.push(...e.slice(0,n));return}Rt()}for(ne.effects&&(ne.done||!ne.count)&&(e=[...ne.effects,...e],n+=ne.effects.length,delete ne.effects),s=0;s<n;s++)Ps(e[s])}function Is(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===Xe?a!==s&&(!a.updatedAt||a.updatedAt<Fs)&&Ps(a):r===ks&&Is(a,s)}}}function er(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ks,n.pure?Ie.push(n):Qe.push(n),n.observers&&er(n))}}function Kt(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),l=n.observerSlots.pop();a<r.length&&(i.sourceSlots[l]=a,r[a]=i,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Kt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Kt(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function Ns(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Bn(e,s=de){throw Ns(e)}function cn(e){if(typeof e=="function"&&!e.length)return cn(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=cn(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Qo(e,s){return function(a){let r;return st(()=>r=Ae(()=>(de.context={...de.context,[e]:a.value},Ja(()=>a.children))),void 0),r}}var un=Symbol("fallback");function _s(e){for(let s=0;s<e.length;s++)e[s]()}function Wo(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return Dt(()=>_s(i)),()=>{let u=e()||[],h=u.length,d,m;return u[Dn],Ae(()=>{let y,p,g,v,w,E,P,D,A;if(h===0)l!==0&&(_s(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[un],r[0]=tt(I=>(i[0]=I,n.fallback())),l=1);else if(l===0){for(r=new Array(h),m=0;m<h;m++)a[m]=u[m],r[m]=tt(j);l=h}else{for(g=new Array(h),v=new Array(h),o&&(w=new Array(h)),E=0,P=Math.min(l,h);E<P&&a[E]===u[E];E++);for(P=l-1,D=h-1;P>=E&&D>=E&&a[P]===u[D];P--,D--)g[D]=r[P],v[D]=i[P],o&&(w[D]=o[P]);for(y=new Map,p=new Array(D+1),m=D;m>=E;m--)A=u[m],d=y.get(A),p[m]=d===void 0?-1:d,y.set(A,m);for(d=E;d<=P;d++)A=a[d],m=y.get(A),m!==void 0&&m!==-1?(g[m]=r[d],v[m]=i[d],o&&(w[m]=o[d]),m=p[m],y.set(A,m)):i[d]();for(m=E;m<h;m++)m in g?(r[m]=g[m],i[m]=v[m],o&&(o[m]=w[m],o[m](m))):r[m]=tt(j);r=r.slice(0,l=h),a=u.slice(0)}return r});function j(y){if(i[m]=y,o){const[p,g]=we(m);return o[m]=g,s(u[m],p)}return s(u[m])}}}function Jo(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return Dt(()=>_s(i)),()=>{const h=e()||[],d=h.length;return h[Dn],Ae(()=>{if(d===0)return o!==0&&(_s(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[un],r[0]=tt(j=>(i[0]=j,n.fallback())),o=1),r;for(a[0]===un&&(i[0](),i=[],a=[],r=[],o=0),u=0;u<d;u++)u<a.length&&a[u]!==h[u]?l[u](()=>h[u]):u>=a.length&&(r[u]=tt(m));for(;u<a.length;u++)i[u]();return o=l.length=i.length=d,a=h.slice(0),r=r.slice(0,o)});function m(j){i[u]=j;const[y,p]=we(h[u]);return l[u]=p,s(y,u)}}}function Mn(e,s){return Ae(()=>e(s||{}))}function js(){return!0}var dn={get(e,s,n){return s===Ts?n:e.get(s)},has(e,s){return s===Ts?!0:e.has(s)},set:js,deleteProperty:js,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:js,deleteProperty:js}},ownKeys(e){return e.keys()}};function en(e){return(e=typeof e=="function"?e():e)?e:{}}function Yo(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function On(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&Ts in o,e[l]=typeof o=="function"?(s=!0,Te(o)):o}if(za&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=en(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in en(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(en(e[o])));return[...new Set(l)]}},dn);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let h=u.length-1;h>=0;h--){const d=u[h];if(d==="__proto__"||d==="constructor")continue;const m=Object.getOwnPropertyDescriptor(o,d);if(!a[d])a[d]=m.get?{enumerable:!0,configurable:!0,get:Yo.bind(n[d]=[m.get.bind(o)])}:m.value!==void 0?m:void 0;else{const j=n[d];j&&(m.get?j.push(m.get.bind(o)):m.value!==void 0&&j.push(()=>m.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const o=i[l],u=a[o];u&&u.get?Object.defineProperty(r,o,u):r[o]=u?u.value:void 0}return r}function tr(e,...s){if(za&&Ts in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(o){return l.includes(o)?e[o]:void 0},has(o){return l.includes(o)&&o in e},keys(){return l.filter(o=>o in e)}},dn));return i.push(new Proxy({get(l){return r.has(l)?void 0:e[l]},has(l){return r.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!r.has(l))}},dn)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let o=!1,u=0;for(const h of s)h.includes(r)&&(o=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;o||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function sr(e){let s,n;const a=r=>{const i=ne.context;if(i){const[o,u]=we();ne.count||(ne.count=0),ne.count++,(n||(n=e())).then(h=>{!ne.done&&Rt(i),ne.count--,u(()=>h.default),Rt()}),s=o}else if(!s){const[o]=Mo(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Te(()=>(l=s())?Ae(()=>{if(!i||ne.done)return l(r);const o=ne.context;Rt(i);const u=l(r);return Rt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Xo=0;function Zo(){return ne.context?ne.getNextContextId():`cl-${Xo++}`}var nr=e=>`Stale read from <${e}>.`;function ec(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(Wo(()=>e.each,e.children,s||void 0))}function tc(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(Jo(()=>e.each,e.children,s||void 0))}function sc(e){const s=e.keyed,n=Te(()=>e.when,void 0,void 0),a=s?n:Te(n,void 0,{equals:(r,i)=>!r==!i});return Te(()=>{const r=a();if(r){const i=e.children;return typeof i=="function"&&i.length>0?Ae(()=>i(s?r:()=>{if(!Ae(a))throw nr("Show");return n()})):i}return e.fallback},void 0,void 0)}function nc(e){const s=Ja(()=>e.children),n=Te(()=>{const a=s(),r=Array.isArray(a)?a:[a];let i=()=>{};for(let l=0;l<r.length;l++){const o=l,u=r[l],h=i,d=Te(()=>h()?void 0:u.when,void 0,void 0),m=u.keyed?d:Te(d,void 0,{equals:(j,y)=>!j==!y});i=()=>h()||(m()?[o,d,u]:void 0)}return i});return Te(()=>{const a=n()();if(!a)return e.fallback;const[r,i,l]=a,o=l.children;return typeof o=="function"&&o.length>0?Ae(()=>o(l.keyed?i():()=>{var h;if(((h=Ae(n)())==null?void 0:h[0])!==r)throw nr("Match");return i()})):o},void 0,void 0)}function ac(e){return e}var rc=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","hidden","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected"],ic=new Set(["className","value","readOnly","noValidate","formNoValidate","isMap","noModule","playsInline",...rc]),lc=new Set(["innerHTML","textContent","innerText","children"]),oc=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),cc=Object.assign(Object.create(null),{class:"className",novalidate:{$:"noValidate",FORM:1},formnovalidate:{$:"formNoValidate",BUTTON:1,INPUT:1},ismap:{$:"isMap",IMG:1},nomodule:{$:"noModule",SCRIPT:1},playsinline:{$:"playsInline",VIDEO:1},readonly:{$:"readOnly",INPUT:1,TEXTAREA:1}});function uc(e,s){const n=cc[e];return typeof n=="object"?n[s]?n.$:void 0:n}var dc=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),hc=new Set(["altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","hkern","image","line","linearGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tref","tspan","use","view","vkern"]),mc={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},fc=e=>Te(()=>e());function xc(e,s,n){let a=n.length,r=s.length,i=a,l=0,o=0,u=s[r-1].nextSibling,h=null;for(;l<r||o<i;){if(s[l]===n[o]){l++,o++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const d=i<a?o?n[o-1].nextSibling:n[i-o]:u;for(;o<i;)e.insertBefore(n[o++],d)}else if(i===o)for(;l<r;)(!h||!h.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[o]===s[r-1]){const d=s[--r].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--i],d),s[r]=n[i]}else{if(!h){h=new Map;let m=o;for(;m<i;)h.set(n[m],m++)}const d=h.get(s[l]);if(d!=null)if(o<d&&d<i){let m=l,j=1,y;for(;++m<r&&m<i&&!((y=h.get(s[m]))==null||y!==d+j);)j++;if(j>d-o){const p=s[l];for(;o<d;)e.insertBefore(n[o++],p)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var zt="_$DX_DELEGATE";function ar(e,s,n,a={}){let r;return tt(i=>{r=i,s===document?e():Ls(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function gc(e,s,n,a){let r;const i=()=>{const o=document.createElement("template");return o.innerHTML=e,o.content.firstChild},l=()=>(r||(r=i())).cloneNode(!0);return l.cloneNode=l,l}function rr(e,s=window.document){const n=s[zt]||(s[zt]=new Set);for(let a=0,r=e.length;a<r;a++){const i=e[a];n.has(i)||(n.add(i),s.addEventListener(i,ur))}}function pc(e=window.document){if(e[zt]){for(let s of e[zt].keys())e.removeEventListener(s,ur);delete e[zt]}}function Ds(e,s,n){ht(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function yc(e,s,n,a){ht(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function jc(e,s,n){ht(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function ir(e,s){ht(e)||(s==null?e.removeAttribute("class"):e.className=s)}function lr(e,s,n,a){if(a)Array.isArray(n)?(e[`$$${s}`]=n[0],e[`$$${s}Data`]=n[1]):e[`$$${s}`]=n;else if(Array.isArray(n)){const r=n[0];e.addEventListener(s,n[0]=i=>r.call(e,n[1],i))}else e.addEventListener(s,n,typeof n!="function"&&n)}function vc(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const o=r[i];!o||o==="undefined"||s[o]||(Xn(e,o,!1),delete n[o])}for(i=0,l=a.length;i<l;i++){const o=a[i],u=!!s[o];!o||o==="undefined"||n[o]===u||!u||(Xn(e,o,!0),n[o]=u)}return n}function bc(e,s,n){if(!s)return n?Ds(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function or(e,s={},n,a){const r={};return a||st(()=>r.children=Ht(e,s.children,r.children)),st(()=>typeof s.ref=="function"&&cr(s.ref,e)),st(()=>wc(e,s,n,!0,r,!0)),r}function cr(e,s,n){return Ae(()=>e(s,n))}function Ls(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Ht(e,s,a,n);st(r=>Ht(e,s(),r,n),a)}function wc(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=Zn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=Zn(e,l,o,r[l],n,i,s)}}function Sc(e){let s,n;return!ht()||!(s=ne.registry.get(n=Ec()))?e():(ne.completed&&ne.completed.add(s),ne.registry.delete(n),s)}function ht(e){return!!ne.context&&!ne.done&&(!e||e.isConnected)}function Nc(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Xn(e,s,n){const a=s.trim().split(/\s+/);for(let r=0,i=a.length;r<i;r++)e.classList.toggle(a[r],n)}function Zn(e,s,n,a,r,i,l){let o,u,h,d,m;if(s==="style")return bc(e,n,a);if(s==="classList")return vc(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const j=s.slice(3);a&&e.removeEventListener(j,a,typeof a!="function"&&a),n&&e.addEventListener(j,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const j=s.slice(10);a&&e.removeEventListener(j,a,!0),n&&e.addEventListener(j,n,!0)}else if(s.slice(0,2)==="on"){const j=s.slice(2).toLowerCase(),y=dc.has(j);if(!y&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(j,p)}(y||n)&&(lr(e,j,n,y),y&&rr([j]))}else if(s.slice(0,5)==="attr:")Ds(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")jc(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(h=lc.has(s))||!r&&((d=uc(s,e.tagName))||(u=ic.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(m)s=s.slice(5),u=!0;else if(ht(e))return n;s==="class"||s==="className"?ir(e,n):o&&!u&&!h?e[Nc(s)]=n:e[d||s]=n}else{const j=r&&s.indexOf(":")>-1&&mc[s.split(":")[0]];j?yc(e,j,s,n):Ds(e,oc[s]||s,n)}return n}function ur(e){if(ne.registry&&ne.events&&ne.events.find(([u,h])=>h===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const h=s[`${n}Data`];if(h!==void 0?u.call(s,h,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},o=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),ne.registry&&!ne.done&&(ne.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let h=0;h<u.length-2&&(s=u[h],!!l());h++){if(s._$host){s=s._$host,o();break}if(s.parentNode===r)break}}else o();i(a)}function Ht(e,s,n,a,r){const i=ht(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let h=0;h<n.length;h++){const d=n[h];d.nodeType===8&&d.data.slice(0,2)==="!$"?d.remove():u.push(d)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,o=a!==void 0;if(e=o&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(o){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=xt(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(i)return n;n=xt(e,n,a)}else{if(l==="function")return st(()=>{let u=s();for(;typeof u=="function";)u=u();n=Ht(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],h=n&&Array.isArray(n);if(hn(u,s,n,r))return st(()=>n=Ht(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let d=u[0];if(d.parentNode!==e)return n;const m=[d];for(;(d=d.nextSibling)!==a;)m.push(d);return n=m}if(u.length===0){if(n=xt(e,n,a),o)return n}else h?n.length===0?ea(e,u,a):xc(e,n,u):(n&&xt(e),ea(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=o?[s]:s;if(Array.isArray(n)){if(o)return n=xt(e,n,a,s);xt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function hn(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let o=s[i],u=n&&n[e.length],h;if(!(o==null||o===!0||o===!1))if((h=typeof o)=="object"&&o.nodeType)e.push(o);else if(Array.isArray(o))r=hn(e,o,u)||r;else if(h==="function")if(a){for(;typeof o=="function";)o=o();r=hn(e,Array.isArray(o)?o:[o],Array.isArray(u)?u:[u])||r}else e.push(o),r=!0;else{const d=String(o);u&&u.nodeType===3&&u.data===d?e.push(u):e.push(document.createTextNode(d))}}return r}function ea(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function xt(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const o=s[l];if(r!==o){const u=o.parentNode===e;!i&&!l?u?e.replaceChild(r,o):e.insertBefore(r,n):u&&o.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function Ec(){return ne.getNextContextId()}var Cc="http://www.w3.org/2000/svg";function dr(e,s=!1){return s?document.createElementNS(Cc,e):document.createElement(e)}function Tc(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Yn();let i,l=!!ne.context;return Ln(()=>{l&&(Yn().user=l=!1),i||(i=Wa(r,()=>Te(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,h]=we(!1),d=()=>h(!0);tt(m=>Ls(o,()=>u()?m():i(),null)),Dt(d)}else{const u=dr(e.isSVG?"g":"div",e.isSVG),h=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),Ls(h,i),o.appendChild(u),e.ref&&e.ref(u),Dt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function Ac(e,s){const n=Te(e);return Te(()=>{const a=n();switch(typeof a){case"function":return Ae(()=>a(s));case"string":const r=hc.has(a),i=ne.context?Sc():dr(a,r);return or(i,s,r),i}})}function kc(e){const[,s]=tr(e,["component"]);return Ac(()=>e.component,s)}var Pc=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,s){this.keyToValue.set(e,s),this.valueToKey.set(s,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},hr=class{constructor(e){this.generateIdentifier=e,this.kv=new Pc}register(e,s){this.kv.getByValue(e)||(s||(s=this.generateIdentifier(e)),this.kv.set(s,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},Ic=class extends hr{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,s){typeof s=="object"?(s.allowProps&&this.classToAllowedProps.set(e,s.allowProps),super.register(e,s.identifier)):super.register(e,s)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function _c(e){if("values"in Object)return Object.values(e);const s=[];for(const n in e)e.hasOwnProperty(n)&&s.push(e[n]);return s}function Dc(e,s){const n=_c(e);if("find"in n)return n.find(s);const a=n;for(let r=0;r<a.length;r++){const i=a[r];if(s(i))return i}}function Lt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Es(e,s){return e.indexOf(s)!==-1}function ta(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Lc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Dc(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Bc=e=>Object.prototype.toString.call(e).slice(8,-1),mr=e=>typeof e>"u",Mc=e=>e===null,Qt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,mn=e=>Qt(e)&&Object.keys(e).length===0,at=e=>Array.isArray(e),Oc=e=>typeof e=="string",Rc=e=>typeof e=="number"&&!isNaN(e),Gc=e=>typeof e=="boolean",Fc=e=>e instanceof RegExp,Wt=e=>e instanceof Map,Jt=e=>e instanceof Set,fr=e=>Bc(e)==="Symbol",Uc=e=>e instanceof Date&&!isNaN(e.valueOf()),qc=e=>e instanceof Error,sa=e=>typeof e=="number"&&isNaN(e),$c=e=>Gc(e)||Mc(e)||mr(e)||Rc(e)||Oc(e)||fr(e),zc=e=>typeof e=="bigint",Vc=e=>e===1/0||e===-1/0,Kc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Hc=e=>e instanceof URL,xr=e=>e.replace(/\./g,"\\."),tn=e=>e.map(String).map(xr).join("."),Vt=e=>{const s=[];let n="";for(let r=0;r<e.length;r++){let i=e.charAt(r);if(i==="\\"&&e.charAt(r+1)==="."){n+=".",r++;continue}if(i==="."){s.push(n),n="";continue}n+=i}const a=n;return s.push(a),s};function $e(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var gr=[$e(mr,"undefined",()=>null,()=>{}),$e(zc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),$e(Uc,"Date",e=>e.toISOString(),e=>new Date(e)),$e(qc,"Error",(e,s)=>{const n={name:e.name,message:e.message};return s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n},(e,s)=>{const n=new Error(e.message);return n.name=e.name,n.stack=e.stack,s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n}),$e(Fc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),$e(Jt,"set",e=>[...e.values()],e=>new Set(e)),$e(Wt,"map",e=>[...e.entries()],e=>new Map(e)),$e(e=>sa(e)||Vc(e),"number",e=>sa(e)?"NaN":e>0?"Infinity":"-Infinity",Number),$e(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),$e(Hc,"URL",e=>e.toString(),e=>new URL(e))];function qs(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var pr=qs((e,s)=>fr(e)?!!s.symbolRegistry.getIdentifier(e):!1,(e,s)=>["symbol",s.symbolRegistry.getIdentifier(e)],e=>e.description,(e,s,n)=>{const a=n.symbolRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown symbol");return a}),Qc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),yr=qs(Kc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Qc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function jr(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var vr=qs(jr,(e,s)=>["class",s.classRegistry.getIdentifier(e.constructor)],(e,s)=>{const n=s.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};const a={};return n.forEach(r=>{a[r]=e[r]}),a},(e,s,n)=>{const a=n.classRegistry.getValue(s[1]);if(!a)throw new Error(`Trying to deserialize unknown class '${s[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(a.prototype),e)}),br=qs((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Wc=[vr,pr,br,yr],na=(e,s)=>{const n=ta(Wc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=ta(gr,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},wr={};gr.forEach(e=>{wr[e.annotation]=e});var Jc=(e,s,n)=>{if(at(s))switch(s[0]){case"symbol":return pr.untransform(e,s,n);case"class":return vr.untransform(e,s,n);case"custom":return br.untransform(e,s,n);case"typed-array":return yr.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=wr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},pt=(e,s)=>{if(s>e.size)throw new Error("index out of bounds");const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function Sr(e){if(Es(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Es(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Es(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Yc=(e,s)=>{Sr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Jt(e))e=pt(e,+a);else if(Wt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=pt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},fn=(e,s,n)=>{if(Sr(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(at(a)){const o=+l;a=a[o]}else if(Qt(a))a=a[l];else if(Jt(a)){const o=+l;a=pt(a,o)}else if(Wt(a)){if(i===s.length-2)break;const u=+l,h=+s[++i]==0?"key":"value",d=pt(a,u);switch(h){case"key":a=d;break;case"value":a=a.get(d);break}}}const r=s[s.length-1];if(at(a)?a[+r]=n(a[+r]):Qt(a)&&(a[r]=n(a[r])),Jt(a)){const i=pt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Wt(a)){const i=+s[s.length-2],l=pt(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(l);a.set(u,a.get(l)),u!==l&&a.delete(l);break}case"value":{a.set(l,n(a.get(l)));break}}}return e};function xn(e,s,n=[]){if(!e)return;if(!at(e)){Lt(e,(i,l)=>xn(i,s,[...n,...Vt(l)]));return}const[a,r]=e;r&&Lt(r,(i,l)=>{xn(i,s,[...n,...Vt(l)])}),s(a,n)}function Xc(e,s,n){return xn(s,(a,r)=>{e=fn(e,r,i=>Jc(i,a,n))}),e}function Zc(e,s){function n(a,r){const i=Yc(e,Vt(r));a.map(Vt).forEach(l=>{e=fn(e,l,()=>i)})}if(at(s)){const[a,r]=s;a.forEach(i=>{e=fn(e,Vt(i),()=>e)}),r&&Lt(r,n)}else Lt(s,n);return e}var eu=(e,s)=>Qt(e)||at(e)||Wt(e)||Jt(e)||jr(e,s);function tu(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function su(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(o=>o.map(String)).sort((o,u)=>o.length-u.length));const[i,...l]=r;i.length===0?a=l.map(tn):n[tn(i)]=l.map(tn)}),a?mn(n)?[a]:[a,n]:mn(n)?void 0:n}var Nr=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=$c(e);if(!o){tu(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!eu(e,n)){const y=na(e,n),p=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,p),p}if(Es(i,e))return{transformedValue:null};const u=na(e,n),h=(u==null?void 0:u.value)??e,d=at(h)?[]:{},m={};Lt(h,(y,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const g=Nr(y,s,n,a,[...r,p],[...i,e],l);d[p]=g.transformedValue,at(g.annotations)?m[p]=g.annotations:Qt(g.annotations)&&Lt(g.annotations,(v,w)=>{m[xr(p)+"."+w]=v})});const j=mn(m)?{transformedValue:d,annotations:u?[u.type]:void 0}:{transformedValue:d,annotations:u?[u.type,m]:m};return o||l.set(e,j),j};function Er(e){return Object.prototype.toString.call(e).slice(8,-1)}function aa(e){return Er(e)==="Array"}function nu(e){if(Er(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function au(e,s,n,a,r){const i={}.propertyIsEnumerable.call(a,s)?"enumerable":"nonenumerable";i==="enumerable"&&(e[s]=n),r&&i==="nonenumerable"&&Object.defineProperty(e,s,{value:n,enumerable:!1,writable:!0,configurable:!0})}function gn(e,s={}){if(aa(e))return e.map(r=>gn(r,s));if(!nu(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(aa(s.props)&&!s.props.includes(i))return r;const l=e[i],o=gn(l,s);return au(r,i,o,e,s.nonenumerable),r},{})}var ye=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Ic,this.symbolRegistry=new hr(s=>s.description??""),this.customTransformerRegistry=new Lc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Nr(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=su(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=gn(s);return n!=null&&n.values&&(a=Xc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Zc(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};ye.defaultInstance=new ye;ye.serialize=ye.defaultInstance.serialize.bind(ye.defaultInstance);ye.deserialize=ye.defaultInstance.deserialize.bind(ye.defaultInstance);ye.stringify=ye.defaultInstance.stringify.bind(ye.defaultInstance);ye.parse=ye.defaultInstance.parse.bind(ye.defaultInstance);ye.registerClass=ye.defaultInstance.registerClass.bind(ye.defaultInstance);ye.registerSymbol=ye.defaultInstance.registerSymbol.bind(ye.defaultInstance);ye.registerCustom=ye.defaultInstance.registerCustom.bind(ye.defaultInstance);ye.allowErrorProps=ye.defaultInstance.allowErrorProps.bind(ye.defaultInstance);var Cr=ye.serialize,ru=ye.stringify;function iu(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function lu(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function ou({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function cu({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function uu(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var du=(e,s=!1)=>{const{json:n}=Cr(e);return JSON.stringify(n,null,s?2:void 0)},vs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,hu=(e,s)=>e.queryHash.localeCompare(s.queryHash),Tr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,mu=(e,s)=>vs(e)===vs(s)?Tr(e,s):vs(e)>vs(s)?1:-1,fu={status:mu,"query hash":hu,"last updated":Tr},bs=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Ar=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,xu=(e,s)=>bs(e)===bs(s)?Ar(e,s):bs(e)>bs(s)?1:-1,gu={status:xu,"last updated":Ar},pu=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),yu=()=>{const[e,s]=we("dark");return Qa(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=r=>{s(r.matches?"dark":"light")};n.addEventListener("change",a),Dt(()=>n.removeEventListener("change",a))}),e},Gt=(e,s,n)=>{if(s.length===0)return n;if(e instanceof Map){const a=new Map(e);if(s.length===1)return a.set(s[0],n),a;const[r,...i]=s;return a.set(r,Gt(a.get(r),i,n)),a}if(e instanceof Set){const a=Gt(Array.from(e),s,n);return new Set(a)}if(Array.isArray(e)){const a=[...e];if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Gt(a[r],i,n),a}if(e instanceof Object){const a={...e};if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Gt(a[r],i,n),a}return e},Ft=(e,s)=>{if(e instanceof Map){const n=new Map(e);if(s.length===1)return n.delete(s[0]),n;const[a,...r]=s;return n.set(a,Ft(n.get(a),r)),n}if(e instanceof Set){const n=Ft(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,l)=>l.toString()!==s[0]);const[a,...r]=s;return n[a]=Ft(n[a],r),n}if(e instanceof Object){const n={...e};if(s.length===1)return delete n[s[0]],n;const[a,...r]=s;return n[a]=Ft(n[a],r),n}return e},kr=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},yt,Yt,Xt,Zt,lt,es,jt,vt,bt,wt,St,ts,Nt,ss,la,ju=(la=class{constructor(e){fe(this,yt);fe(this,Yt);fe(this,Xt);fe(this,Zt);fe(this,lt,!1);fe(this,es);fe(this,jt);fe(this,vt);fe(this,bt);fe(this,wt);fe(this,St);fe(this,ts);fe(this,Nt);fe(this,ss);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:h,shadowDOMTarget:d,hideDisabledQueries:m}=e;he(this,yt,we(s)),he(this,Xt,n),he(this,Zt,a),he(this,Yt,r),he(this,es,h),he(this,jt,d),he(this,vt,we(i)),he(this,bt,we(l)),he(this,wt,we(o)),he(this,St,we(u)),he(this,ts,we(m))}setButtonPosition(e){te(this,vt)[1](e)}setPosition(e){te(this,bt)[1](e)}setInitialIsOpen(e){te(this,wt)[1](e)}setErrorTypes(e){te(this,St)[1](e)}setClient(e){te(this,yt)[1](e)}mount(e){if(te(this,lt))throw new Error("Devtools is already mounted");const s=ar(()=>{const n=this,[a]=te(this,vt),[r]=te(this,bt),[i]=te(this,wt),[l]=te(this,St),[o]=te(this,ts),[u]=te(this,yt);let h;return te(this,Nt)?h=te(this,Nt):(h=sr(()=>Promise.resolve().then(()=>require("./LNWAZHJI-BjCzrU9R.cjs"))),he(this,Nt,h)),kr(te(this,es),te(this,jt)),Mn(h,On({get queryFlavor(){return te(n,Xt)},get version(){return te(n,Zt)},get onlineManager(){return te(n,Yt)},get shadowDOMTarget(){return te(n,jt)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get hideDisabledQueries(){return o()}}))},e);he(this,lt,!0),he(this,ss,s)}unmount(){var e;if(!te(this,lt))throw new Error("Devtools is not mounted");(e=te(this,ss))==null||e.call(this),he(this,lt,!1)}},yt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,lt=new WeakMap,es=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,ts=new WeakMap,Nt=new WeakMap,ss=new WeakMap,la),Et,ns,as,rs,ot,is,Ct,Tt,At,kt,Pt,ls,It,_t,os,oa,vu=(oa=class{constructor(e){fe(this,Et);fe(this,ns);fe(this,as);fe(this,rs);fe(this,ot,!1);fe(this,is);fe(this,Ct);fe(this,Tt);fe(this,At);fe(this,kt);fe(this,Pt);fe(this,ls);fe(this,It);fe(this,_t);fe(this,os);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:h,shadowDOMTarget:d,onClose:m,hideDisabledQueries:j}=e;he(this,Et,we(s)),he(this,as,n),he(this,rs,a),he(this,ns,r),he(this,is,h),he(this,Ct,d),he(this,Tt,we(i)),he(this,At,we(l)),he(this,kt,we(o)),he(this,Pt,we(u)),he(this,ls,we(j)),he(this,It,we(m))}setButtonPosition(e){te(this,Tt)[1](e)}setPosition(e){te(this,At)[1](e)}setInitialIsOpen(e){te(this,kt)[1](e)}setErrorTypes(e){te(this,Pt)[1](e)}setClient(e){te(this,Et)[1](e)}setOnClose(e){te(this,It)[1](()=>e)}mount(e){if(te(this,ot))throw new Error("Devtools is already mounted");const s=ar(()=>{const n=this,[a]=te(this,Tt),[r]=te(this,At),[i]=te(this,kt),[l]=te(this,Pt),[o]=te(this,ls),[u]=te(this,Et),[h]=te(this,It);let d;return te(this,_t)?d=te(this,_t):(d=sr(()=>Promise.resolve().then(()=>require("./MWZ6AO7Z-DL2N4k7z.cjs"))),he(this,_t,d)),kr(te(this,is),te(this,Ct)),Mn(d,On({get queryFlavor(){return te(n,as)},get version(){return te(n,rs)},get onlineManager(){return te(n,ns)},get shadowDOMTarget(){return te(n,Ct)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get hideDisabledQueries(){return o()},get onClose(){return h()}}))},e);he(this,ot,!0),he(this,os,s)}unmount(){var e;if(!te(this,ot))throw new Error("Devtools is not mounted");(e=te(this,os))==null||e.call(this),he(this,ot,!1)}},Et=new WeakMap,ns=new WeakMap,as=new WeakMap,rs=new WeakMap,ot=new WeakMap,is=new WeakMap,Ct=new WeakMap,Tt=new WeakMap,At=new WeakMap,kt=new WeakMap,Pt=new WeakMap,ls=new WeakMap,It=new WeakMap,_t=new WeakMap,os=new WeakMap,oa);function bu(e){const s=U.useQueryClient(e.client),n=be.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u,hideDisabledQueries:h}=e,[d]=be.useState(new ju({client:s,queryFlavor:"React Query",version:"5",onlineManager:U.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u,hideDisabledQueries:h}));return be.useEffect(()=>{d.setClient(s)},[s,d]),be.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),be.useEffect(()=>{r&&d.setPosition(r)},[r,d]),be.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),be.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),be.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{dir:"ltr",className:"tsqd-parent-container",ref:n})}function wu(e){const s=U.useQueryClient(e.client),n=be.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i,hideDisabledQueries:l}=e,[o]=be.useState(new vu({client:s,queryFlavor:"React Query",version:"5",onlineManager:U.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose,hideDisabledQueries:l}));return be.useEffect(()=>{o.setClient(s)},[s,o]),be.useEffect(()=>{o.setOnClose(e.onClose??(()=>{}))},[e.onClose,o]),be.useEffect(()=>{o.setErrorTypes(a||[])},[a,o]),be.useEffect(()=>(n.current&&o.mount(n.current),()=>{o.unmount()}),[o]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var Su=process.env.NODE_ENV!=="development"?function(){return null}:bu;process.env.NODE_ENV;const Nu=()=>{$.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),$.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),$.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"}),$.registerChaiFeatureFlag("enable-old-page-manager",{description:"Switch to older page manager"}),$.registerChaiFeatureFlag("enable-site-settings",{description:"Site settings"}),$.registerChaiFeatureFlag("enable-seo-meta-tab",{description:"Enable SEO Meta tab"})},Eu=()=>{const e=oe(),s=Z();return U.useQuery({queryKey:[R.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:R.GET_COLLECTIONS})})},Cu=()=>{const{data:e}=ke(),{data:s}=Je(),{data:n}=Ve(),a=oe(),r=Z(),i=x.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return U.useMutation({mutationFn:async({block:l})=>r(a,{action:R.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},Pr=()=>{const e=Rs();return x.useCallback(({pageId:s})=>{e(s)},[e])},Tu=x.createContext(null),sn={didCatch:!1,error:null};class Au extends x.Component{constructor(s){super(s),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=sn}static getDerivedStateFromError(s){return{didCatch:!0,error:s}}resetErrorBoundary(){const{error:s}=this.state;if(s!==null){for(var n,a,r=arguments.length,i=new Array(r),l=0;l<r;l++)i[l]=arguments[l];(n=(a=this.props).onReset)===null||n===void 0||n.call(a,{args:i,reason:"imperative-api"}),this.setState(sn)}}componentDidCatch(s,n){var a,r;(a=(r=this.props).onError)===null||a===void 0||a.call(r,s,n)}componentDidUpdate(s,n){const{didCatch:a}=this.state,{resetKeys:r}=this.props;if(a&&n.error!==null&&ku(s.resetKeys,r)){var i,l;(i=(l=this.props).onReset)===null||i===void 0||i.call(l,{next:r,prev:s.resetKeys,reason:"keys"}),this.setState(sn)}}render(){const{children:s,fallbackRender:n,FallbackComponent:a,fallback:r}=this.props,{didCatch:i,error:l}=this.state;let o=s;if(i){const u={error:l,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")o=n(u);else if(a)o=x.createElement(a,u);else if(r!==void 0)o=r;else throw l}return x.createElement(Tu.Provider,{value:{didCatch:i,error:l,resetErrorBoundary:this.resetErrorBoundary}},o)}}function ku(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==s.length||e.some((n,a)=>!Object.is(n,s[a]))}const Pu=()=>{const e=cs(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>{const r=a.map(async l=>n(e,{action:R.UPLOAD_ASSET,data:l}));return await Promise.all(r)},onSuccess:a=>{var r;if(a!=null&&a.some(i=>i.error))throw new Error(((r=a==null?void 0:a.find(i=>i.error))==null?void 0:r.error)||"Failed to upload asset");{s.invalidateQueries({queryKey:[R.GET_ASSETS]});const i=a==null?void 0:a.length;W.toast.success(`${i===1?"Asset":i+" Assets"} uploaded successfully`)}},onError:()=>{W.toast.error("Failed to upload asset")}})},Iu=()=>{const e=cs(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[R.GET_ASSETS]}),W.toast.success("Asset deleted successfully")},onError:()=>{W.toast.error("Failed to delete asset")}})},_u=()=>{const e=cs(),s=U.useQueryClient(),n=Z();return U.useMutation({mutationFn:async a=>n(e,{action:R.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[R.GET_ASSETS]}),W.toast.success("Asset updated successfully")},onError:()=>{W.toast.error("Failed to update asset")}})},Du=(e={})=>{const s=cs(),n=Z(),{search:a,page:r=1,limit:i=30}=e;return U.useQuery({queryKey:[R.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:R.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},Lu=e=>{const s=cs(),n=Z();return U.useQuery({queryKey:[R.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:R.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Bu(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function ra(e){if(!e)return"N/A";const s=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(s)}function ia(e,s){let n=e,a=s==null?void 0:s.description;return(!a||typeof a!="string")&&(a=""),(!n||typeof n!="string")&&(n=""),n!==a}const Mu=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,j,y;const{data:i,isLoading:l,isError:o}=Lu(e||""),[u,h]=x.useState(""),d=async(p,g)=>{try{await navigator.clipboard.writeText(p),W.toast.success(`${g} copied to clipboard`)}catch(v){W.toast.error(`Failed to copy ${g}`,{description:v==null?void 0:v.message})}};return x.useEffect(()=>{i!=null&&i.description&&h(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(S.Loader,{className:"h-8 w-8 animate-spin"})}):o||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(S.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(S.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>d(i.url,"Asset URL"),disabled:r,children:[t.jsx(S.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(S.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((m=i.metadata)==null?void 0:m.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((j=i.metadata)==null?void 0:j.format)||i.type,capitalize:!0},{label:"Size",value:Bu(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:ra(i.createdAt)},{label:"Updated",value:ra(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(p.value,p.label),children:t.jsx(S.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,g)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},g))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>h(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!ia(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!ia(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(S.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})};function Ou({currentPage:e,totalPages:s,onPageChange:n,pageRangeDisplayed:a=3,showPageInput:r=!0,className:i=""}){const[l,o]=x.useState(String(e)),u=x.useMemo(()=>{const p=Math.floor(a/2);let g=Math.max(1,e-p),v=Math.min(s,e+p);v-g+1<a&&(g===1?v=Math.min(s,g+a-1):v===s&&(g=Math.max(1,v-a+1)));const w=[];g>1&&(w.push(1),g>2&&w.push("..."));for(let E=g;E<=v;E++)w.push(E);return v<s&&(v<s-1&&w.push("..."),w.push(s)),w},[e,s,a]),h=p=>{p!==e&&p>=1&&p<=s&&(n(p),o(String(p)))},d=()=>{e>1&&h(e-1)},m=()=>{e<s&&h(e+1)},j=()=>{const p=Number(l);!isNaN(p)&&p>=1&&p<=s&&h(p)},y=p=>{p.key==="Enter"&&j()};return s<=1?null:t.jsxs("div",{className:`flex flex-wrap items-center justify-center gap-3 ${i}`,children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:d,disabled:e===1,className:"px-2 py-1 text-sm hover:bg-gray-50",children:[t.jsx(S.ChevronLeft,{className:" h-4 w-4"}),"Previous"]}),t.jsx("div",{className:"flex items-center gap-2",children:u.map((p,g)=>{if(p==="...")return t.jsx("span",{className:"px-2 text-muted-foreground",children:"..."},`ellipsis-${g}`);const v=p,w=v===e;return t.jsx(c.Button,{variant:w?"default":"outline",size:"sm",onClick:()=>h(v),className:w?"border-blue-600 bg-blue-600 px-3 py-1 text-sm text-white":"border px-3 py-1 text-sm hover:bg-gray-50 hover:text-black",children:v},v)})}),t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:m,disabled:e===s,className:"px-2 py-1 text-sm hover:bg-gray-50",children:["Next",t.jsx(S.ChevronRight,{className:" h-4 w-4"})]})]}),r&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Go to"}),t.jsx(c.Input,{type:"number",min:1,max:s,value:l,onChange:p=>{const g=p.target.value.replace(/[^\d]/g,"");o(g)},onKeyDown:y,className:"h-8 w-16 px-2 py-1"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:j,disabled:l===""||Number(l)<1||Number(l)>s,children:"Go"})]})]})}const Ru=x.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs"))),Gu=10*1024*1024,Fu=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAssets:a,isUploadingAsset:r,onUploaded:i})=>{const[l,o]=x.useState(()=>{const p=localStorage.getItem("chai_optimize_images");return p!==null?p==="true":!0});x.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,h=x.useCallback(async p=>{try{const v=p.map(async P=>{let D=P;return P.type.startsWith("image/")&&(D=await Ca(P)),new Promise((A,I)=>{const O=new FileReader;O.readAsDataURL(D),O.onload=async()=>{A({file:O.result,folderId:void 0,name:P.name,optimize:l})},O.onerror=()=>I(null)})}),w=await Promise.all(v),E=await a(w);return(E==null?void 0:E.length)===1&&i(E[0]),E}catch(g){return Promise.reject(g)}},[a,l,i]),d=p=>{const g=[];let v=0;return p.forEach(w=>{w.size>Gu?v++:g.push(w)}),v>0&&W.toast.error(`${v===1&&p.length===1?"File":v+(v===1?" file":" files")} exceed the maximum size limit of 10MB.`),f.isEmpty(g)?[]:h(g)},{getRootProps:m,getInputProps:j,isDragActive:y}=Or.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},disabled:e||r,multiple:!0});return t.jsx("div",{className:`flex h-[60px] w-full flex-col items-center justify-center rounded-lg border-2 border-dashed border-slate-300 p-0 py-2 hover:border-black/50 ${u?"pointer-events-none bg-gray-100 opacity-90":"bg-gray-100 hover:border-black/50 hover:bg-gray-100"}`,children:t.jsxs("div",{...m(),className:$.mergeClasses("flex h-max w-full cursor-pointer flex-col justify-center rounded-lg text-center",u?"items-start":"items-center",y?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...j()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 leading-tight",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(S.Loader,{className:"h-4 w-4 animate-spin text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs font-light text-muted-foreground",children:["Please wait while we ",e?"update":"upload"," your file..."]})]})]})}):t.jsxs("div",{className:"flex w-full items-center justify-between px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex items-center justify-between gap-2 leading-tight",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full border border-indigo-500 bg-indigo-100 p-2",children:t.jsx(S.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"cursor-pointer text-indigo-500 hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs font-light text-muted-foreground",children:[t.jsxs("span",{className:"",children:["Accepted file types: ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size: ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange:p=>{o(p)},onClick:p=>{p.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`flex cursor-help items-center text-amber-500 ${l?"invisible":""}`,children:t.jsx(S.AlertTriangle,{className:"mr-1 h-4 w-4"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-xs text-white",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Ir({close:e,onSelect:s,mode:n="image",assetId:a}){const l=x.useMemo(()=>[n],[n]),[o,u]=x.useState(null),[h,d]=x.useState(null),[m,j]=x.useState(null),[y,p]=x.useState({show:!1,file:""}),[g,v]=x.useState(!1),[w,E]=x.useState(a?"details":"grid"),[P,D]=x.useState(""),[A,I]=x.useState(""),[O,Y]=x.useState(1),[ee]=x.useState(30),[L,q]=x.useState([]);x.useEffect(()=>{a&&(u(a),E("details"))},[a]),x.useEffect(()=>{const _=setTimeout(()=>{D(A),Y(1)},300);return()=>clearTimeout(_)},[A]);const{data:F,isLoading:z}=Du({search:P.toLowerCase().trim(),page:O,limit:ee}),G=(F==null?void 0:F.assets)||[],Q=(F==null?void 0:F.total)||0,ae=Math.ceil(Q/ee);x.useEffect(()=>{z||ae<=0||Y(_=>_>ae?ae:_<1?1:_)},[z,ae]);const je=(G==null?void 0:G.length)>0,{mutate:Ne}=Iu(),{mutateAsync:ce,isPending:N}=Pu(),{mutate:b,isPending:C}=_u(),M=x.useCallback(_=>{const se=Math.min(Math.max(1,_),Math.max(1,ae));se!==O&&Y(se)},[ae,O]),T=_=>{I(_.target.value)},B=x.useCallback(_=>{q(se=>f.find(se,{id:_.id})?[]:[_])},[!1]),H=x.useCallback(()=>{q([])},[]),V=_=>{(_==null?void 0:_.length)!==0&&(s(f.pick(f.first(_||L),["id","url","width","height","description"])),e())},J=async _=>{d(_)},re=async()=>{h&&(j(h==null?void 0:h.id),await Ne(h.id,{onSuccess:()=>{j(null),d(null)},onError:()=>{j(null)}}),d(null))},K=_=>{u(_.id),E("details")},ie=async(_,se)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";se?(await ce([{file:_,folderId:void 0,name:y.name||"",optimize:Ee}]),p({show:!1,file:""})):(await b({id:y.id||"",file:_}),p({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},me=x.useCallback(_=>{q([_])},[]),xe=x.useCallback(_=>{M(_)},[M]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-[80vh] max-h-[1232px] w-[80vw] max-w-[1232px] flex-col space-y-4",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),w==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Fu,{maxFileSize:10,allowedTypes:l,uploadAssets:ce,isUpdatingAsset:C,isUploadingAsset:N,onUploaded:me}),t.jsxs("div",{className:"relative flex flex-1 flex-col gap-y-3 overflow-hidden rounded-lg border p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2",children:[t.jsx(S.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${A.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:T,value:A,className:"pl-8"})]}),L.length>0?t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("div",{className:"flex items-center gap-2",children:[L.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>H(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>V(L),disabled:L.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:z?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"})]}):!z&&!je?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center rounded-lg border",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(S.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-lg text-muted-foreground",children:"No assets found"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:P.length>0?"No assets found for your search: "+P:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:G==null?void 0:G.map(_=>t.jsxs("div",{className:$.mergeClasses("group relative flex max-h-[180px] max-w-[180px] cursor-pointer flex-col justify-between overflow-hidden rounded-lg border-2 transition-all",L.some(se=>se.id===_.id)?"border-blue-500":"hover:border-black/90",m&&(h==null?void 0:h.id)===_.id?"pointer-events-none opacity-50":"",m===_.id?"pointer-events-none opacity-50":""),onClick:()=>B(_),onDoubleClick:()=>V([_]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===_.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(S.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,_.type==="image"?t.jsx("img",{src:`${_.thumbnailUrl||"/placeholder.svg"}?v=${(_==null?void 0:_.updatedAt)||_.createdAt}`,alt:_.name,className:`h-full min-h-[80px] w-full object-contain ${L.some(se=>se.id===_.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex h-full items-center justify-center",children:[t.jsx(S.Film,{className:"h-12 w-12 text-muted-foreground"}),_.thumbnailUrl&&t.jsx("img",{src:`${_.thumbnailUrl||"/placeholder.svg"}?v=${(_==null?void 0:_.updatedAt)||_.createdAt}`,alt:_.name,className:"absolute inset-0 h-full w-full object-cover"})]})]}),t.jsxs("div",{className:"flex items-end justify-between border-t-[1px] border-black/10 bg-white px-2 py-1",children:[t.jsx("div",{className:"truncate text-xs leading-tight",title:_.name,children:_.name}),t.jsx("div",{className:"flex items-center justify-between whitespace-nowrap text-[9px] font-light text-muted-foreground",children:t.jsx("span",{children:nn((_==null?void 0:_.size)||0)})})]}),!L.some(se=>se.id===_.id)&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),K(_)},children:t.jsx(S.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),navigator.clipboard.writeText(_.url),W.toast.success("Asset URL copied to clipboard")},children:t.jsx(S.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),p({id:_.id,show:!0,file:_.url,name:_.name})},children:t.jsx(S.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:se=>{se.stopPropagation(),J(_)},children:t.jsx(S.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),L.some(se=>se.id===_.id)&&t.jsx("div",{className:"absolute right-1 top-1 h-max rounded-full border border-white bg-blue-500 p-1",children:t.jsx(S.Check,{className:"h-3 w-3 text-white",strokeWidth:5})})]},_.id))})}),ae>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 border-t bg-white p-4",children:t.jsx(Au,{fallback:t.jsx("div",{className:"text-red-500",children:"Error loading pagination"}),children:t.jsx(Ou,{currentPage:O,totalPages:ae,onPageChange:xe,pageRangeDisplayed:3,showPageInput:!0})})})]})]}):t.jsx(Mu,{assetId:o||a||"",onBack:()=>{E("grid"),u(null)},onEdit:_=>{p({id:_.id,show:!0,file:_.url,name:_.name})},onSave:async _=>{if(o){v(!0);try{const se=G.find(Ee=>Ee.id===o);se&&await b(f.merge(se,{description:_}))}finally{v(!1)}}},isSaving:g})]}),y.show&&t.jsx(x.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(S.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Ru,{imageUrl:y.file,onSave:ie,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),h&&t.jsx(c.Dialog,{open:!!h,onOpenChange:()=>d(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',h.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>d(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:re,children:"Delete"})]})]})})]})}const Uu=Object.freeze(Object.defineProperty({__proto__:null,default:Ir},Symbol.toStringTag,{value:"Module"})),Bs=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,o]=x.useState(!1),u=()=>{i||o(!0)},h=()=>{o(!1)},d=y=>{const p=Array.isArray(y)?y[0]:y;p!=null&&p.url&&n(f.pick(p,["url","id"])),o(!1)},m=()=>{n({url:"",id:""})},j=(s==null?void 0:s.startsWith("{{"))&&(s==null?void 0:s.endsWith("}}"));return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative overflow-hidden rounded-md border",children:[j?t.jsx("div",{className:"flex h-12 items-center bg-gray-100 px-4",children:t.jsx("p",{className:"text-xs text-gray-500",children:s})}):t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"h-auto max-h-[100px] w-full bg-gray-100 object-contain"}),t.jsxs("div",{className:"absolute right-2 top-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8 rounded-full bg-white text-red-500",onClick:m,disabled:i,children:j?t.jsx(S.X,{className:"h-4 w-4"}):t.jsx(S.Trash2,{className:"h-4 w-4"})}),!j&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(S.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex cursor-pointer items-center justify-center rounded-md border border-dashed p-6 ${i?"cursor-not-allowed opacity-50":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(S.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(c.Dialog,{open:l,onOpenChange:o,children:t.jsxs(c.DialogContent,{className:"h-fit w-full max-w-7xl overflow-hidden p-0",children:[t.jsxs(c.DialogHeader,{className:"hidden border-b px-4 py-2",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:h,children:t.jsx(S.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"h-full flex-1 p-4",children:t.jsx(Ir,{close:h,onSelect:d,mode:"image",assetId:e})})]})})]})},qu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),$u=()=>{const[e,s]=x.useState({logoUrl:"",logoId:"",faviconUrl:"",faviconId:""}),[n,a]=x.useState(!1),r=()=>{a(!0),setTimeout(()=>{a(!1),console.log("Branding settings saved:",e)},1e3)};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Branding Settings"}),t.jsxs("div",{className:"rounded space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Logo"}),t.jsx(Bs,{assetId:e.logoId,assetUrl:e.logoUrl,onChange:i=>{s({...e,logoUrl:i.url,logoId:i.id})},placeholder:"Select logo image",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 200x50px"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Favicon"}),t.jsx(Bs,{assetId:e.faviconId,assetUrl:e.faviconUrl,onChange:i=>{s({...e,faviconUrl:i.url,faviconId:i.id})},placeholder:"Select favicon",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 32x32px"})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:r,disabled:n,className:"w-full",children:n?"Saving...":"Save Branding Settings"})})]})]})},zu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),Vu=()=>{const[e,s]=x.useState({contactEmail:"",contactPhone:"",contactAddress:""}),[n,a]=x.useState([]),[r,i]=x.useState({isOpen:!1,platform:"",url:"",customName:""}),[l,o]=x.useState(!1),u=[{value:"facebook",label:"Facebook"},{value:"twitter",label:"Twitter"},{value:"linkedin",label:"LinkedIn"},{value:"instagram",label:"Instagram"},{value:"youtube",label:"YouTube"},{value:"other",label:"Other"}],h=g=>s(v=>({...v,[g.target.name]:g.target.value})),d=()=>{const{platform:g,url:v,customName:w}=r;if(!v.trim()||!g)return;const E=g==="other"?w:g;E.trim()&&(a(P=>[...P,{platform:E,url:v,isCustom:g==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=g=>a(v=>v.filter((w,E)=>E!==g)),j=()=>i({isOpen:!1,platform:"",url:"",customName:""}),y=()=>{o(!0);const g={};n.forEach(w=>{g[w.platform.toLowerCase().replace(/\s+/g,"_")]=w.url});const v={...e,socialLinks:g};setTimeout(()=>{o(!1),console.log("Contact & Social settings saved:",v),s({contactEmail:"",contactPhone:"",contactAddress:""}),a([]),i({isOpen:!1,platform:"",url:"",customName:""})},1e3)},p=e.contactEmail.trim()||e.contactPhone.trim()||e.contactAddress.trim();return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Contact & Social Settings"}),t.jsxs("div",{className:"space-y-4 rounded",children:[t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Email"}),t.jsx("input",{type:"email",name:"contactEmail",value:e.contactEmail,onChange:h,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"contact@example.com"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Phone"}),t.jsx("input",{type:"tel",name:"contactPhone",value:e.contactPhone,onChange:h,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"+1 (555) 123-4567"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Address"}),t.jsx("textarea",{name:"contactAddress",value:e.contactAddress,onChange:h,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"Enter your business address",rows:3})]})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("h3",{className:"text-md font-medium text-gray-900",children:"Links"}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>i(g=>({...g,isOpen:!0})),className:"text-sm",children:"Add Link"})]}),r.isOpen&&t.jsxs("div",{className:"space-y-3 rounded border bg-gray-50 p-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Platform"}),t.jsxs("select",{value:r.platform,onChange:g=>i(v=>({...v,platform:g.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",children:[t.jsx("option",{value:"",children:"Select platform"}),u.map(g=>t.jsx("option",{value:g.value,children:g.label},g.value))]})]}),r.platform==="other"&&t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Platform Name"}),t.jsx("input",{type:"text",value:r.customName,onChange:g=>i(v=>({...v,customName:g.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"e.g., TikTok, Discord, Snapchat"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"URL"}),t.jsx("input",{type:"url",value:r.url,onChange:g=>i(v=>({...v,url:g.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"https://platform.com/yourprofile"})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{type:"button",onClick:d,disabled:!r.platform||!r.url.trim()||r.platform==="other"&&!r.customName.trim(),className:"flex-1",children:"Save Link"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:j,className:"flex-1",children:"Cancel"})]})]}),n.length>0&&t.jsx("div",{className:"space-y-2",children:n.map((g,v)=>t.jsxs("div",{className:"flex items-center justify-between rounded border p-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-sm font-medium capitalize",children:g.platform}),t.jsx("p",{className:"max-w-xs truncate text-xs text-gray-500",children:g.url})]}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m(v),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},v))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:y,disabled:!p||l,className:"w-full",children:l?"Saving...":"Save Contact & Social Settings"})})]})]})},Ku=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),Hu=()=>{const[e,s]=x.useState({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),[n,a]=x.useState([]),[r,i]=x.useState(""),[l,o]=x.useState(!1),u=y=>{const{name:p,value:g}=y.target;s(v=>({...v,[p]:g}))},h=()=>{r.trim()&&(a(y=>[...y,{id:Date.now().toString(),content:r}]),i(""))},d=y=>{a(p=>p.filter(g=>g.id!==y))},m=()=>{o(!0);const y={...e,customTrackingScripts:n.map(p=>p.content)};setTimeout(()=>{o(!1),console.log("Analytics & Tracking settings saved:",y),s({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),a([])},1e3)},j=Object.values(e).some(y=>y.trim())||n.length>0;return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Analytics & Tracking Settings"}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Google Analytics ID"}),t.jsx("input",{type:"text",name:"googleAnalyticsId",value:e.googleAnalyticsId,onChange:u,placeholder:"UA-XXXXXXXXX-X",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Google Tag Manager ID"}),t.jsx("input",{type:"text",name:"googleTagManagerId",value:e.googleTagManagerId,onChange:u,placeholder:"GTM-XXXXXX",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Meta Pixel ID"}),t.jsx("input",{type:"text",name:"metaPixelId",value:e.metaPixelId,onChange:u,placeholder:"XXXXXXXXXX",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("div",{className:"mb-2 flex items-center justify-between",children:t.jsx("label",{className:"text-sm font-medium",children:"Custom Tracking Scripts"})}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("textarea",{value:r,onChange:y=>i(y.target.value),placeholder:"Paste your tracking script code",className:"input-border min-h-[80px] w-full rounded px-3 py-2 font-mono text-sm",rows:4}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Add custom tracking scripts (e.g., Hotjar, Mixpanel, etc.)"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:h,disabled:!r.trim(),children:"Add Script"})]})]})]}),n.length>0&&t.jsx("div",{className:"mb-3 space-y-2",children:n.map(y=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"flex-1 overflow-hidden rounded border bg-gray-50 p-2",children:t.jsx("code",{className:"block max-h-20 overflow-auto text-xs",children:y.content.length>100?`${y.content.substring(0,100)}...`:y.content})}),t.jsx(c.Button,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>d(y.id),children:"Remove"})]},y.id))}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:m,disabled:!j||l,className:"w-full",children:l?"Saving...":"Save Settings"})})]})]})},Qu=()=>{Ss("branding",{label:"Branding",button:qu,panel:$u}),Ss("contact-social",{label:"Contact & Social",button:zu,panel:Vu}),Ss("analytics-tracking",{label:"Analytics & Tracking",button:Ku,panel:Hu})},Wu=x.lazy(()=>Promise.resolve().then(()=>Uu));Nu();Rr.loadWebBlocks();$.registerChaiTopBar(Zl);_o();Qu();$.registerChaiMediaManager(Wu);$.registerChaiSaveToLibrary(Ei);const Ju=e=>{const s=x.useRef([]),[n]=Pe(),a=n.get("page"),{data:r}=ke(),{data:i={role:"",permissions:null}}=Ga();no(),ui();const{data:l,isFetching:o}=Na(),{blocks:u}=so(l),{data:h}=Ce(),{mutateAsync:d}=fa(),m=eo(),{onSave:j}=ao(),{getPartialBlocks:y,getPartialBlockBlocks:p}=ro(),{aiContext:g,setAiContext:v}=yn(),{mutateAsync:w}=Ti(),[E,P]=x.useState(!1),{data:D}=Ve(),A=We(),{data:I}=bn(),{data:O}=Eu(),{mutateAsync:Y}=Cu(),ee=Pr();Xr(),x.useEffect(()=>{const z=()=>{document.hidden?P(!0):P(!1)};return window.addEventListener("visibilitychange",z),()=>window.removeEventListener("visibilitychange",z)},[]),s.current=u;const L=x.useMemo(()=>{const z={};return i&&(z.permissions=f.get(i,"permissions",null),z.role=f.get(i,"role","user")),z},[i]),q=x.useCallback(async(z,G)=>await w({pageType:z,query:G}),[w]),F=x.useMemo(()=>f.get(D,"theme",{})||{},[D]);return t.jsxs(t.Fragment,{children:[t.jsx($.ChaiBuilderEditor,{gotoPage:ee,collections:O??[],getBlockAsyncProps:Y,pageExternalData:I,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:A,languages:(D==null?void 0:D.languages)||[],brandingOptions:(D==null?void 0:D.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!E&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:y,blocks:o?[]:u,theme:f.cloneDeep(F),pageTypes:h,searchPageTypeItems:q,saveAiContextCallback:async z=>{if(!a)return!0;const G=s.current,Q={_type:"@chai/ai-context",_value:f.isString(z)?z:""},ae=[...G,Q];return await j({page:a,blocks:ae}),v(z),!0},aiContext:g,askAiCallBack:m,onSave:async({blocks:z,theme:G,needTranslations:Q})=>{if(!a)return!0;s.current=z;const ae={_type:"@chai/ai-context",_value:f.isString(g)?g:""},je=[...z,ae];return await j({page:a,blocks:je,needTranslations:Q}),s.current=je,f.isEqual(G,F)||await d({settings:{theme:G}}),!0},themePanelComponent:Mi,...L}),t.jsxs("div",{children:[t.jsx(fi,{}),t.jsx(xi,{})]})]})},Yu=new U.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Xu=e=>{const{isLoggedIn:s}=Oe(),[,n]=xa(),[a,r]=x.useState(!1);return x.useEffect(()=>(n(f.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","getAccessToken","supabaseInstance"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?t.jsxs(U.QueryClientProvider,{client:Yu,children:[s?t.jsx(Ju,{...e}):t.jsx(co,{}),t.jsx(Su,{})]}):t.jsx("div",{})},Zu=()=>{const e=oe(),s=Z(),{data:n}=Je(),a=U.useQueryClient();return U.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:R.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[R.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[R.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},ed=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ha();return x.useCallback(async({url:n,method:a="GET",body:r={},headers:i={}})=>{const l=await s();if(!l)throw new Error("No auth token");if(!n)throw new Error("URL is required");try{const o=await fetch(n,{method:a,headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`,...i},body:JSON.stringify(r)});if(o.status===401)return console.log("Session expired",o),await e(),window.location.reload(),null;if(o.status===400)throw new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",o),o}},[e,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Dn;exports.ChaiBuilderPages=Xu;exports.ChaiBuilderPagesRealtime=ba;exports.Dynamic=kc;exports.For=ec;exports.ImagePicker=Bs;exports.Index=tc;exports.LanguageSwitcher=_n;exports.Match=ac;exports.NestedPathSelector=He;exports.PermissionChecker=Me;exports.Portal=Tc;exports.Show=sc;exports.SmartJsonInput=ln;exports.Switch=nc;exports.addEventListener=lr;exports.batch=Oo;exports.className=ir;exports.clearDelegatedEvents=pc;exports.convertRemToPixels=pu;exports.createComponent=Mn;exports.createComputed=Ha;exports.createContext=qo;exports.createEffect=Ln;exports.createMemo=Te;exports.createRenderEffect=st;exports.createRoot=tt;exports.createSignal=we;exports.createUniqueId=Zo;exports.delegateEvents=rr;exports.deleteNestedDataByPath=Ft;exports.displayValue=du;exports.getMutationStatusColor=cu;exports.getPreferredColorScheme=yu;exports.getQueryStatusColor=ou;exports.getQueryStatusColorByLabel=uu;exports.getQueryStatusLabel=iu;exports.getSidedProp=lu;exports.insert=Ls;exports.memo=fc;exports.mergeProps=On;exports.mutationSortFns=gu;exports.on=Ro;exports.onCleanup=Dt;exports.onMount=Qa;exports.registerChaiSiteSetting=Ss;exports.registerLoginComponent=oo;exports.serialize=Cr;exports.setAttribute=Ds;exports.sortFns=fu;exports.splitProps=tr;exports.spread=or;exports.stringify=ru;exports.template=gc;exports.untrack=Ae;exports.updateNestedDataByPath=Gt;exports.use=cr;exports.useActivePage=Je;exports.useBuilderPageData=bn;exports.useChaiAuth=Oe;exports.useChaiFetch=ed;exports.useChaiUserInfo=Ke;exports.useContext=$o;exports.useCurrentPage=ke;exports.useFallbackLang=We;exports.useFetch=Z;exports.useGotoPage=Pr;exports.useLanguagePages=Ue;exports.usePageTypes=Ce;exports.useTransition=Uo;exports.useUpdateActivePageMetadata=Zu;exports.useUserRoleAndPermissions=Ga;exports.useWebsitePages=dt;exports.useWebsiteSetting=Ve;