@chaibuilder/pages 0.11.10 → 0.12.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,13 +1,13 @@
1
- "use strict";var Br=Object.defineProperty;var Rn=e=>{throw TypeError(e)};var Mr=(e,s,n)=>s in e?Br(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var et=(e,s,n)=>Mr(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"),je=require("jotai"),U=require("@tanstack/react-query"),W=require("sonner"),F=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),dt=require("date-fns"),S=require("lucide-react"),Or=require("compressorjs"),Js=require("react-diff-view"),ua=require("@chaibuilder/runtime"),Ss=require("zod"),Rr=require("react-dropzone"),Gr=require("@chaibuilder/sdk/web-blocks");function Ur(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 we=Ur(x),Ne={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"},O={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 Un(e,s){const n=`atom${++Fr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=qr,a.write=$r),s&&(a.write=s),a}function qr(e){return e(this)}function $r(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const zr=Symbol(""),Vr=e=>typeof(e==null?void 0:e.then)=="function";function Kr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,h)=>{var d,m;const v=j=>{if(j=j||"",a!==j){try{r=JSON.parse(j,s==null?void 0:s.reviver)}catch{return h}a=j}return r},y=(m=(d=e())==null?void 0:d.getItem(u))!=null?m:null;return Vr(y)?y.then(v):v(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,v=>{let y;try{y=JSON.parse(v||"")}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 Hr=Kr();function da(e,s,n=Hr,a){const r=Un(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Un(l=>l(r),(l,o,u)=>{const h=typeof u=="function"?u(l(r)):u;return h===zr?(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 ha="__logged_in_user",Qr=da(ha,null),Oe=()=>{const[e,s]=je.useAtom(Qr),n=x.useCallback(()=>{s(null),localStorage.removeItem(ha)},[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 pt=null;function Wr(){const{user:e,setUser:s,logout:n}=Oe(),a=Os(),r=Ue("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(pt)return await pt;pt=i();try{return await pt}finally{pt=null}},onSuccess:()=>{}})}function Jr(){return pt}const ma=()=>{const{user:e,setUser:s}=Oe(),{mutateAsync:n}=Wr(),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=Ue("getAccessToken",async()=>{if(!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken"))){if(r()){const o=Jr();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])}},ee=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ma();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])},fa=()=>{const e=le(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]})}})},xa=()=>{const e=le(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[O.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})}})},Yr=()=>{const e=le(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[O.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 Xr=je.atom({}),ga=()=>je.useAtom(Xr),Zr=()=>{const[e]=Pe(),s=e.get("page"),n=x.useRef(""),{mutate:a}=fa();x.useEffect(()=>{!f.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Ue=(e,s)=>{const[n]=ga();return x.useMemo(()=>f.get(n,e,s),[n,e,s])},le=()=>Ue("apiUrl","/chai/api"),Os=()=>Ue("usersApiUrl","/chai/users"),us=()=>Ue("assetsApiUrl","/chai/assets"),ei=()=>Ue("supabaseInstance",null),Ge=e=>{const s=le(),[n]=Pe(),a=e??n.get("page"),r=ee();return U.useQuery({queryKey:[O.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:O.GET_LANGUAGE_PAGES,data:{id:a}});return f.reverse(f.sortBy(i,"primaryPage"))},enabled:!!a})},Ve=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:O.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},pa=e=>{const{fallbackLang:s}=F.useLanguages(),{data:n}=Ve(),{data:a,isFetching:r}=Ge(),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:[O.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:x.useCallback(a=>{e.setQueryData([O.AI_CONTEXT],a)},[e]),aiContext:s}},ti=je.atom(null),ya=()=>je.useAtom(ti),jn=()=>{const[e]=ya();return(e==null?void 0:e.slug)||""};function si(e,s){const[n,a]=x.useState(e);return x.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const ni=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=F.useLanguages(),{data:r}=ke(),i=r==null?void 0:r.pageType,l=le(),o=ee(),{data:u,isFetching:h}=U.useQuery({queryKey:[O.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await o(l,{action:O.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}},ja=()=>{const{selectedLang:e,fallbackLang:s}=F.useLanguages(),[n,a]=ya(),[r,i]=x.useState(""),l=si(r,500),{allLangPages:o,data:u,isFetching:h}=ni({query:l}),d=x.useCallback(y=>a(y),[a]),m=x.useCallback(y=>i(y),[i]),v=x.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),j=e.length===0,p=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,w=o.filter(N=>(N==null?void 0:N.primaryPage)===p||N.id===p).find(N=>j?N.lang===e||N.lang===s:N.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:v}},ai=je.atom({lastSaved:void 0}),Rs=()=>je.useAtom(ai),ke=()=>{const[e]=Pe(),s=e.get("page"),{data:n,isFetching:a}=Ge();return{data:x.useMemo(()=>({...f.find(n,{id:s})||{}}),[n,s]),isFetching:a}},We=()=>{const[e]=Pe(),s=e.get("lang")??"",{data:n,isFetching:a}=Ge();return{data:x.useMemo(()=>f.find(n,{lang:s})||{},[n,s]),isFetching:a}},ri=je.atom({}),ii=()=>je.useAtom(ri),va=()=>{const{data:e}=We(),s=jn(),n=Ue("getLiveUrl",f.noop),a=e==null?void 0:e.slug,r=n(a||"/");return s?r+s:r};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=Os(),n=ee();return U.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:O.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!f.isEmpty(e)})},li=je.atom(void 0),oi=je.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),ci=je.atom(""),ui=je.atom(null),vn=je.atom({}),wa=()=>je.useAtom(vn),Je=()=>{const[e]=Pe(),s=e.get("page"),{user:n}=Oe(),[a,r]=je.useAtom(li),[i,l]=je.useAtom(oi),[o,u]=je.useAtom(ui),[h,d]=je.useAtom(ci),[m]=je.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])},di=()=>{const e=ei(),{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}=Je(),[,d]=je.useAtom(vn),m=x.useRef(!1),v=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 j=async(b,w)=>{var N,P;switch(b){case"UPDATE_ONLINE_USERS":d((w==null?void 0:w.pageToUser)||{});break;case"PAGE_LOCKED":l({...v==null?void 0:v.current,requestedBy:"",status:"locked",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"USER_JOINED":if(((N=v==null?void 0:v.current)==null?void 0:N.status)==="editing")return;((P=v==null?void 0:v.current)==null?void 0:P.status)==="locked"&&o("can_edit_now"),l({...v==null?void 0:v.current,requestedBy:"",status:"editing",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":l({...v==null?void 0:v.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({...v==null?void 0:v.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":o("take_over_request_rejected"),l({...v==null?void 0:v.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},p=new ba(e,r==null?void 0:r.appKey,n==null?void 0:n.id,j);h(p)}},[h,e,r==null?void 0:r.appKey]),x.useEffect(()=>{v.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,v.current={requestedBy:"",status:"checking",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1},o(""),l(v.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}=Je(),{savePageAsync:l}=F.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}},Ye=()=>{const{data:e}=Ve();return x.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},Na=()=>{const[e]=Pe(),s=e.get("page"),n=le(),{setAiContext:a}=yn(),{setCurrentEditor:r}=Je(),[,i]=Rs(),[,l]=ii(),[,o]=F.useIsPageLoaded(),u=ee();return U.useQuery({queryKey:[O.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r(""),o(!1);const h=await u(n,{action:O.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(v=>({...v,lastSaved:h.lastSaved})),l(f.get(h,"metadata",{})),setTimeout(()=>o(!0),500),d},enabled:!!s})},bn=()=>{const{data:e}=ke(),{data:s}=We(),n=le(),a=ee(),r=Ye(),i=jn();return U.useQuery({queryKey:[O.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:O.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,metadata:e.metadata||{}}}}),enabled:!!(e!=null&&e.pageType)&&!!s.id})},ds=({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(ds,{children:s}):t.jsx("div",{className:"flex h-full w-full items-center justify-center",children:s})},hi=({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"]})})]})})},mi=({userId:e})=>{const{data:s}=Ke(e);return(s==null?void 0:s.name)||"Unknown"};function fi({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),v=()=>{h(!0),setTimeout(()=>{h(!1)},15e3),m(!1),r()};return t.jsx(ds,{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:"," ",dt.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:v,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:v,children:"Yes, Take Over"})]})]})]})})]})})}const js=({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(ds,{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(mi,{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"]})]})]})})},xi=()=>{const{pageLock:e,requestTakeOver:s}=Sa(),{isLocked:n,currentEditor:a,lockingStatus:r,setLockingStatus:i,realtimePageLockEnabled:l}=Je(),{data:o,isFetching:u}=Ke(a),[h]=Pe(),d=h.get("page"),{mutate:m}=fa(),{isFetching:v}=Na(),[y]=Rs(),j=U.useQueryClient(),p=x.useCallback(()=>{l?s():m({id:d})},[d,m,s,l]);return d?l&&(e==null?void 0:e.status)==="checking"?t.jsx(js,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):l&&(e!=null&&e.requestedBy)?t.jsx(js,{lockingStatus:"",onContinue:()=>{}}):(l?e.status!=="locked":!n||v)?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(js,{lockingStatus:r,onContinue:()=>{j.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]}),i("")}}):null:l&&(e!=null&&e.isActiveInOtherTab)?t.jsx(js,{lockingStatus:"page_is_active_in_other_tab",onContinue:s}):t.jsx(fi,{...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:p,realtimePageLockEnabled:l,isRequestRejected:r==="take_over_request_rejected"}):null},gi=()=>{const[e,s]=Pe(),n=e.get("lang"),a=pa(n),{setSelectedLang:r}=F.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(Ne,n);return t.jsx(ds,{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"})})]})})},pi=e=>{const s=le(),n=ee();return U.useMutation({mutationFn:async a=>n(s,{action:O.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"})}})},yi=e=>{const s=le(),n=ee();return U.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:O.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})},ji=e=>{const s=le(),n=ee();return U.useMutation({mutationFn:async a=>n(s,{action:O.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"})}})},vi=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=x.useState(!1),u=F.useUpdateBlocksPropsRealtime(),h=ji(()=>{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:v=>v.preventDefault(),disabled:l,children:[t.jsx(S.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:v=>!v&&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"})]})]})})]})},bi=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=x.useState(!1);return t.jsx(vi,{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"]})})},wi=()=>{const e=le(),s=ee(),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}},Si=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),[r,i]=x.useState(""),l=x.useRef(null),{groups:o}=wi(),[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(j=>j.id===y.id))],[o,u]),m=()=>{const y=r.trim();if(!y)return;const j={id:y,name:y};h(p=>[...p,j]),s(j.id),i(""),a(!1)};x.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const v=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:v}),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(j=>j.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"})})]})},Fn=3*1024*1024,Ni=10*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<=Fn){s(e);return}new Or(e,{quality:.8,maxWidth:2048,maxHeight:2048,convertSize:Fn,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(Ni)}.`),n(a)}})})}const Ei=({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)try{a(!0);let m=h;h.type.startsWith("image/")&&(m=await Ca(h));const v=new FileReader;v.onloadend=()=>{s(v.result),a(!1)},v.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"})})]})},be={...F.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"},Ci=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=F.usePartailBlocksStore(),i=s.find(I=>I._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=x.useMemo(()=>s.some(I=>I._type==="PartialBlock"||I._type==="GlobalBlock"),[s]),h=x.useMemo(()=>{let I=[];for(const G of s)if(G._type==="PartialBlock"||G._type==="GlobalBlock"){let C=r(G.partialBlockId);G._parent&&(C==null?void 0:C.length)>0&&(C=C.map(D=>(f.isEmpty(D._parent)&&f.set(D,"_parent",G._parent),D))),I=[...I,...C]}else I.push(G);return I},[s,r]),[d,m]=x.useState(""),[v,y]=x.useState(""),[j,p]=x.useState(""),[b,w]=x.useState(""),[N,P]=x.useState({}),[_,T]=x.useState(!1),[A,z]=x.useState(o),[X,V]=x.useState(!1),{hasPermission:L}=F.usePermissions(),R=L(be.DELETE_LIBRARY_BLOCK),q=F.useUpdateBlocksPropsRealtime(),M=()=>{q([a],{_libBlockId:void 0}),W.toast.success("Block delinked from library"),n()},{data:J,isLoading:H,isError:ae}=yi(l);x.useEffect(()=>{ae&&o&&(V(!0),z(!1))},[ae,o]),x.useEffect(()=>{J&&!H&&(m(J.name||""),y(J.group||""),p(J.description||""),w(J.preview||""),z(!1))},[J,H]),x.useEffect(()=>{const I=d.trim().length>=2,G=v.trim()!=="";T(I&&G)},[d,v]);const xe=()=>{const I={};return d.trim()?d.length<2&&(I.name="Name must be at least 2 characters"):I.name="Name is required",v||(I.group="Group is required"),P(I),Object.keys(I).length===0},{resetLibrary:ge}=F.useLibraryBlocks({id:""}),ce=pi(I=>{o||q([a],{_libBlockId:I.id}),W.toast.success(`Block ${o?"updated":"saved"} successfully`),ge(I.library),n()}),E=async I=>{if(I.preventDefault(),!xe())return;const G=h.map(C=>(f.has(C,"_libBlockId")&&delete C._libBlockId,C));ce.mutate({name:d.trim(),group:v,blocks:G,description:j.trim(),...b&&b.startsWith("data:")?{previewImage:b}:{},...o?{id:l}:{}})},g=ce.isPending;return A||H?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"})}):X?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:M,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:E,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:N.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:d,onChange:I=>m(I.target.value),className:N.name?"border-destructive":""}),N.name&&t.jsx("p",{className:"text-xs text-destructive",children:N.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:N.group?"text-destructive":"",children:"Group"}),t.jsx(Si,{value:v,onChange:y}),N.group&&t.jsx("p",{className:"text-xs text-destructive",children:N.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:j,onChange:I=>p(I.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Ei,{value:b,onChange:w})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&R&&t.jsx(bi,{blockId:a,libBlockId:l,blockName:d,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:g,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:g||!_,children:g?"Saving...":o?"Update Block":"Save Block"})]})]})]})},ie={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."},Ai={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ce=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:O.GET_PAGE_TYPES})})},Aa=e=>{const{data:s}=Ce();return x.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Ti=()=>{const e=le(),s=ee();return U.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:O.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Ta=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>await n(e,{action:O.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[O.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(Ai,r.message,r.message)})}})},wn=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=We(),{data:r}=Ce();return U.useMutation({mutationFn:async i=>await n(e,{action:O.UPDATE_PAGE,data:i}),onSuccess:(i,l)=>{(a==null?void 0:a.id)===(l==null?void 0:l.id)&&s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES]}),l&&(l!=null&&l.primaryPage||l!=null&&l.seo)?(s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,l==null?void 0:l.primaryPage]}),s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[O.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})}})},ki=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:O.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:[O.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[O.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})}})},Pi=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:O.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]});const l=f.find(a,{key:i.pageType});W.toast.success(l!=null&&l.hasSlug?ie.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=le(),s=ee(),n=U.useQueryClient(),{data:a}=ke(),{savePageAsync:r}=F.useSavePage();return U.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:O.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[O.GET_CHANGES]}),n.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),W.toast.error("Failed to publish pages.")}})},Ii=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>{var r;return s(e,{action:O.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:[O.GET_WEBSITE_PAGES]}),W.toast.success("Page marked as template successfully.")},onError:()=>{W.toast.error("Failed to mark page as template.")}})},_i=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>s(e,{action:O.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]}),W.toast.success("Page unmarked as template successfully.")},onError:()=>{W.toast.error("Failed to unmark page as template.")}})},Di=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:O.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{W.toast.success(ie.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[O.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 E=new OffscreenCanvas(1,1),g=E.getContext("2d");g.fillRect(0,0,1,1);var I=E.transferToImageBitmap();try{g.createPattern(I,"no-repeat")}catch{return!1}return!0}();function u(){}function h(E){var g=n.exports.Promise,I=g!==void 0?g:s.Promise;return typeof I=="function"?new I(E):(E(u,u),null)}var d=function(E,g){return{transform:function(I){if(E)return I;if(g.has(I))return g.get(I);var G=new OffscreenCanvas(I.width,I.height),C=G.getContext("2d");return C.drawImage(I,0,0),g.set(I,G),G},clear:function(){g.clear()}}}(o,new Map),m=function(){var E=Math.floor(16.666666666666668),g,I,G={},C=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(g=function(D){var Q=Math.random();return G[Q]=requestAnimationFrame(function $(Y){C===Y||C+E-1<Y?(C=Y,delete G[Q],D()):G[Q]=requestAnimationFrame($)}),Q},I=function(D){G[D]&&cancelAnimationFrame(G[D])}):(g=function(D){return setTimeout(D,E)},I=function(D){return clearTimeout(D)}),{frame:g,cancel:I}}(),v=function(){var E,g,I={};function G(C){function D(Q,$){C.postMessage({options:Q||{},callback:$})}C.init=function($){var Y=$.transferControlToOffscreen();C.postMessage({canvas:Y},[Y])},C.fire=function($,Y,oe){if(g)return D($,null),g;var K=Math.random().toString(36).slice(2);return g=h(function(re){function me(pe){pe.data.callback===K&&(delete I[K],C.removeEventListener("message",me),g=null,d.clear(),oe(),re())}C.addEventListener("message",me),D($,K),I[K]=me.bind(null,{data:{callback:K}})}),g},C.reset=function(){C.postMessage({reset:!0});for(var $ in I)I[$](),delete I[$]}}return function(){if(E)return E;if(!a&&i){var C=["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
- `);try{E=new Worker(URL.createObjectURL(new Blob([C])))}catch(D){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",D),null}G(E)}return E}}(),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 j(E,g){return g?g(E):E}function p(E){return E!=null}function b(E,g,I){return j(E&&p(E[g])?E[g]:y[g],I)}function w(E){return E<0?0:Math.floor(E)}function N(E,g){return Math.floor(Math.random()*(g-E))+E}function P(E){return parseInt(E,16)}function _(E){return E.map(T)}function T(E){var g=String(E).replace(/[^0-9a-f]/gi,"");return g.length<6&&(g=g[0]+g[0]+g[1]+g[1]+g[2]+g[2]),{r:P(g.substring(0,2)),g:P(g.substring(2,4)),b:P(g.substring(4,6))}}function A(E){var g=b(E,"origin",Object);return g.x=b(g,"x",Number),g.y=b(g,"y",Number),g}function z(E){E.width=document.documentElement.clientWidth,E.height=document.documentElement.clientHeight}function X(E){var g=E.getBoundingClientRect();E.width=g.width,E.height=g.height}function V(E){var g=document.createElement("canvas");return g.style.position="fixed",g.style.top="0px",g.style.left="0px",g.style.pointerEvents="none",g.style.zIndex=E,g}function L(E,g,I,G,C,D,Q,$,Y){E.save(),E.translate(g,I),E.rotate(D),E.scale(G,C),E.arc(0,0,1,Q,$,Y),E.restore()}function R(E){var g=E.angle*(Math.PI/180),I=E.spread*(Math.PI/180);return{x:E.x,y:E.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:E.startVelocity*.5+Math.random()*E.startVelocity,angle2D:-g+(.5*I-Math.random()*I),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:E.color,shape:E.shape,tick:0,totalTicks:E.ticks,decay:E.decay,drift:E.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:E.gravity*3,ovalScalar:.6,scalar:E.scalar,flat:E.flat}}function q(E,g){g.x+=Math.cos(g.angle2D)*g.velocity+g.drift,g.y+=Math.sin(g.angle2D)*g.velocity+g.gravity,g.velocity*=g.decay,g.flat?(g.wobble=0,g.wobbleX=g.x+10*g.scalar,g.wobbleY=g.y+10*g.scalar,g.tiltSin=0,g.tiltCos=0,g.random=1):(g.wobble+=g.wobbleSpeed,g.wobbleX=g.x+10*g.scalar*Math.cos(g.wobble),g.wobbleY=g.y+10*g.scalar*Math.sin(g.wobble),g.tiltAngle+=.1,g.tiltSin=Math.sin(g.tiltAngle),g.tiltCos=Math.cos(g.tiltAngle),g.random=Math.random()+2);var I=g.tick++/g.totalTicks,G=g.x+g.random*g.tiltCos,C=g.y+g.random*g.tiltSin,D=g.wobbleX+g.random*g.tiltCos,Q=g.wobbleY+g.random*g.tiltSin;if(E.fillStyle="rgba("+g.color.r+", "+g.color.g+", "+g.color.b+", "+(1-I)+")",E.beginPath(),l&&g.shape.type==="path"&&typeof g.shape.path=="string"&&Array.isArray(g.shape.matrix))E.fill(xe(g.shape.path,g.shape.matrix,g.x,g.y,Math.abs(D-G)*.1,Math.abs(Q-C)*.1,Math.PI/10*g.wobble));else if(g.shape.type==="bitmap"){var $=Math.PI/10*g.wobble,Y=Math.abs(D-G)*.1,oe=Math.abs(Q-C)*.1,K=g.shape.bitmap.width*g.scalar,re=g.shape.bitmap.height*g.scalar,me=new DOMMatrix([Math.cos($)*Y,Math.sin($)*Y,-Math.sin($)*oe,Math.cos($)*oe,g.x,g.y]);me.multiplySelf(new DOMMatrix(g.shape.matrix));var pe=E.createPattern(d.transform(g.shape.bitmap),"no-repeat");pe.setTransform(me),E.globalAlpha=1-I,E.fillStyle=pe,E.fillRect(g.x-K/2,g.y-re/2,K,re),E.globalAlpha=1}else if(g.shape==="circle")E.ellipse?E.ellipse(g.x,g.y,Math.abs(D-G)*g.ovalScalar,Math.abs(Q-C)*g.ovalScalar,Math.PI/10*g.wobble,0,2*Math.PI):L(E,g.x,g.y,Math.abs(D-G)*g.ovalScalar,Math.abs(Q-C)*g.ovalScalar,Math.PI/10*g.wobble,0,2*Math.PI);else if(g.shape==="star")for(var B=Math.PI/2*3,se=4*g.scalar,Ee=8*g.scalar,Le=g.x,Z=g.y,_e=5,Be=Math.PI/_e;_e--;)Le=g.x+Math.cos(B)*Ee,Z=g.y+Math.sin(B)*Ee,E.lineTo(Le,Z),B+=Be,Le=g.x+Math.cos(B)*se,Z=g.y+Math.sin(B)*se,E.lineTo(Le,Z),B+=Be;else E.moveTo(Math.floor(g.x),Math.floor(g.y)),E.lineTo(Math.floor(g.wobbleX),Math.floor(C)),E.lineTo(Math.floor(D),Math.floor(Q)),E.lineTo(Math.floor(G),Math.floor(g.wobbleY));return E.closePath(),E.fill(),g.tick<g.totalTicks}function M(E,g,I,G,C){var D=g.slice(),Q=E.getContext("2d"),$,Y,oe=h(function(K){function re(){$=Y=null,Q.clearRect(0,0,G.width,G.height),d.clear(),C(),K()}function me(){a&&!(G.width===r.width&&G.height===r.height)&&(G.width=E.width=r.width,G.height=E.height=r.height),!G.width&&!G.height&&(I(E),G.width=E.width,G.height=E.height),Q.clearRect(0,0,G.width,G.height),D=D.filter(function(pe){return q(Q,pe)}),D.length?$=m.frame(me):re()}$=m.frame(me),Y=re});return{addFettis:function(K){return D=D.concat(K),oe},canvas:E,promise:oe,reset:function(){$&&m.cancel($),Y&&Y()}}}function J(E,g){var I=!E,G=!!b(g||{},"resize"),C=!1,D=b(g,"disableForReducedMotion",Boolean),Q=i&&!!b(g||{},"useWorker"),$=Q?v():null,Y=I?z:X,oe=E&&$?!!E.__confetti_initialized:!1,K=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,re;function me(B,se,Ee){for(var Le=b(B,"particleCount",w),Z=b(B,"angle",Number),_e=b(B,"spread",Number),Be=b(B,"startVelocity",Number),zs=b(B,"decay",Number),Vs=b(B,"gravity",Number),Ks=b(B,"drift",Number),fs=b(B,"colors",_),Hs=b(B,"ticks",Number),xs=b(B,"shapes"),Qs=b(B,"scalar"),Ws=!!b(B,"flat"),Rt=A(B),ft=Le,Ze=[],gs=E.width*Rt.x,ps=E.height*Rt.y;ft--;)Ze.push(R({x:gs,y:ps,angle:Z,spread:_e,startVelocity:Be,color:fs[ft%fs.length],shape:xs[N(0,xs.length)],ticks:Hs,decay:zs,gravity:Vs,drift:Ks,scalar:Qs,flat:Ws}));return re?re.addFettis(Ze):(re=M(E,Ze,Y,se,Ee),re.promise)}function pe(B){var se=D||b(B,"disableForReducedMotion",Boolean),Ee=b(B,"zIndex",Number);if(se&&K)return h(function(Be){Be()});I&&re?E=re.canvas:I&&!E&&(E=V(Ee),document.body.appendChild(E)),G&&!oe&&Y(E);var Le={width:E.width,height:E.height};$&&!oe&&$.init(E),oe=!0,$&&(E.__confetti_initialized=!0);function Z(){if($){var Be={getBoundingClientRect:function(){if(!I)return E.getBoundingClientRect()}};Y(Be),$.postMessage({resize:{width:Be.width,height:Be.height}});return}Le.width=Le.height=null}function _e(){re=null,G&&(C=!1,s.removeEventListener("resize",Z)),I&&E&&(document.body.contains(E)&&document.body.removeChild(E),E=null,oe=!1)}return G&&!C&&(C=!0,s.addEventListener("resize",Z,!1)),$?$.fire(B,Le,_e):me(B,Le,_e)}return pe.reset=function(){$&&$.reset(),re&&re.reset()},pe}var H;function ae(){return H||(H=J(null,{useWorker:!0,resize:!0})),H}function xe(E,g,I,G,C,D,Q){var $=new Path2D(E),Y=new Path2D;Y.addPath($,new DOMMatrix(g));var oe=new Path2D;return oe.addPath(Y,new DOMMatrix([Math.cos(Q)*C,Math.sin(Q)*C,-Math.sin(Q)*D,Math.cos(Q)*D,I,G])),oe}function ge(E){if(!l)throw new Error("path confetti are not supported in this browser");var g,I;typeof E=="string"?g=E:(g=E.path,I=E.matrix);var G=new Path2D(g),C=document.createElement("canvas"),D=C.getContext("2d");if(!I){for(var Q=1e3,$=Q,Y=Q,oe=0,K=0,re,me,pe=0;pe<Q;pe+=2)for(var B=0;B<Q;B+=2)D.isPointInPath(G,pe,B,"nonzero")&&($=Math.min($,pe),Y=Math.min(Y,B),oe=Math.max(oe,pe),K=Math.max(K,B));re=oe-$,me=K-Y;var se=10,Ee=Math.min(se/re,se/me);I=[Ee,0,0,Ee,-Math.round(re/2+$)*Ee,-Math.round(me/2+Y)*Ee]}return{type:"path",path:g,matrix:I}}function ce(E){var g,I=1,G="#000000",C='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof E=="string"?g=E:(g=E.text,I="scalar"in E?E.scalar:I,C="fontFamily"in E?E.fontFamily:C,G="color"in E?E.color:G);var D=10*I,Q=""+D+"px "+C,$=new OffscreenCanvas(D,D),Y=$.getContext("2d");Y.font=Q;var oe=Y.measureText(g),K=Math.ceil(oe.actualBoundingBoxRight+oe.actualBoundingBoxLeft),re=Math.ceil(oe.actualBoundingBoxAscent+oe.actualBoundingBoxDescent),me=2,pe=oe.actualBoundingBoxLeft+me,B=oe.actualBoundingBoxAscent+me;K+=me+me,re+=me+me,$=new OffscreenCanvas(K,re),Y=$.getContext("2d"),Y.font=Q,Y.fillStyle=G,Y.fillText(g,pe,B);var se=1/I;return{type:"bitmap",bitmap:$.transferToImageBitmap(),matrix:[se,0,0,se,-K*se/2,-re*se/2]}}n.exports=function(){return ae().apply(this,arguments)},n.exports.reset=function(){ae().reset()},n.exports.create=J,n.exports.shapeFromPath=ge,n.exports.shapeFromText=ce})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Nn,!1);const Li=Nn.exports;Nn.exports.create;const Bi={particleCount:350,spread:120,origin:{y:.6},angle:90},Mi={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},qt=e=>{let s=Mi[e];s||(s={});const n={...Bi,...s};Li(n)},Oi=()=>{const[e]=F.useTheme(),{mutate:s,isPending:n}=Sn(),{mutateAsync:a,isPending:r}=xa(),i=()=>{a({settings:{theme:e}})},l=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{qt("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"})]})},ht=()=>{const e=ee(),s=le();return U.useQuery({queryKey:[O.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:O.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Ri=e=>{const s=ee(),n=le(),a=Ye();return U.useQuery({queryKey:[O.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:O.GET_WEBSITE_PAGES,data:{lang:e}})||[];return f.keyBy(f.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})};function tt(e,s,n=!1){const a=e.toString()?`?${e.toString()}`:"/";n?window.history.replaceState(null,"",a):window.history.pushState({},"",a),s(e),window.dispatchEvent(new PopStateEvent("popstate"))}const hs=je.atom(null),Gi=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}},at=e=>{if(!e)return e;const{base:s}=Gi(e);return s};function Ui(e,s){const n=(e||"").split("/").filter(Boolean);let a="",r=!0;if(s.slug==="/"){const i=n.pop()||"";if(Ne[i])r=!0;else{a=i;const l=n.pop()||"";r=!!Ne[l]}}else if(s.parent)n.length&&(a=n.pop()||"");else if(n.length){a=n.pop()||"";const i=n.pop()||"";r=!!Ne[i]}return{initSlug:a,prefix:r}}const Fi=e=>e&&at(e),qn=(e,s)=>{const n=at(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=v=>{const j=v.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),p=(j.match(/\./g)||[]).length,b=p<=1;p>1?d("Invalid slug. Only one dot (.) is allowed in the slug"):d(null),r&&r(b),u(j),s(j)};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:Fi(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:ie.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} - ${Ne[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?Ne[s]||s:n.length?ie.CHOOSE_LANGUAGE:ie.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(o=>t.jsx("option",{value:o,children:Ne[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:ie.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?ie.ENTER_PAGE_NAME:ie.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),qi=({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:v})=>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:ie.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":ie.ENTER_PAGE_SLUG:ie.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:o,onValidationChange:m,fullSlug:v()})]}),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:v})=>{const y=v||!s||!n||o.some(j=>(r?j.id!==i:!0)&&j.parent===(l==null?void 0:l.id)&&j.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:v?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?ie.UPDATING:ie.ADDING]}):r?ie.UPDATE:ie.ADD_NEW_LANGUAGE}),o.some(j=>(r?j.id!==i:!0)&&j.parent===(l==null?void 0:l.id)&&j.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:Ne[n]})," page in the parent to add here."]})})})},$i=({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:v,useLanguagePrefix:y,slug:j,isSlugValid:p,isPending:b})=>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:j,edit:s,id:h,primaryPageObject:o,pages:d,isNonSlugPageType:m,isHomePage:v,useLanguagePrefix:y,isSlugValid:p,isPending:b})]}),zi=({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:v,setUseLanguagePrefix:y,isHomePage:j,parentSlug:p,slug:b,setSlug:w,isSlugValid:N,setIsSlugValid:P,getSlug:_,isPending:T,id:A,pages:z})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(S.Loader,{className:"animate-spin"})}):d?t.jsx($i,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:h,id:A,pages:z,isNonSlugPageType:d,isHomePage:j,useLanguagePrefix:v,slug:b,isSlugValid:N,isPending:T}):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(qi,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:d,isRootPage:m,lang:a,useLanguagePrefix:v,setUseLanguagePrefix:y,isHomePage:j,parentSlug:p,parentHasSelectedLanguagePage:h,slug:b,setSlug:w,isSlugValid:N,setIsSlugValid:P,getSlug:_})]}),t.jsx(Ia,{parentHasSelectedLanguagePage:h,name:i,lang:a,slug:b,edit:n,id:A,primaryPageObject:u,pages:z,isNonSlugPageType:d,isHomePage:j,useLanguagePrefix:v,isSlugValid:N,isPending:T})]}),Vi=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:l=[]}=ht(),o=x.useMemo(()=>l.find(K=>K.id===a),[l,a]),[u,h]=x.useState(""),[d,m]=x.useState(""),[v,y]=x.useState(""),[j,p]=x.useState(!0),[b,w]=x.useState(!0),{mutate:N,isPending:P}=Ta(),{mutate:_,isPending:T}=wn(),A=P||T,{data:z,isFetching:X}=Ve(),V=Ye(),{data:L,isFetching:R}=Ge(a),{data:q=[],isFetching:M}=Ge(o==null?void 0:o.parent),{data:J=[],isFetching:H}=Ce(),{setSelectedLang:ae}=F.useLanguages(),[,xe]=Pe(),[,ge]=F.useSidebarActivePanel(),ce=X||R||M||H,E=x.useMemo(()=>f.filter(z==null?void 0:z.languages,K=>!f.find(L,{lang:K})),[z,L]),g=x.useMemo(()=>J.find(K=>K.key===(o==null?void 0:o.pageType)),[J,o==null?void 0:o.pageType]),I=!(g!=null&&g.hasSlug),G=(o==null?void 0:o.slug)==="/";x.useEffect(()=>{if(!r&&o&&i&&(m(i),h(`${o.name} - ${Ne[i]}`)),!r||!o)return;const K=L==null?void 0:L.find(B=>B.id===e);if(!K)return;h(K.name),m(K.lang);const re=K.slug||"",{initSlug:me,prefix:pe}=Ui(re,o);y(me),w(pe)},[r,e,L,o,i]),x.useEffect(()=>{if(i)m(i);else if((E==null?void 0:E.length)===1&&!r){const K=E[0];if(!K||!Ne[K])return;m(K),(!u||u===(o==null?void 0:o.name))&&h(`${o==null?void 0:o.name} - ${Ne[K]}`)}},[i,E,r,u,o]);const{parentSlug:C,isRootPage:D}=x.useMemo(()=>{if(G||!d)return{parentSlug:void 0,isRootPage:!(o!=null&&o.parent)};if(!(o!=null&&o.parent))return{parentSlug:b?`/${d}`:void 0,isRootPage:!0};const K=q==null?void 0:q.find(re=>re.lang===d);return{parentSlug:K==null?void 0:K.slug,isRootPage:!1}},[o==null?void 0:o.parent,q,b,d,G]),Q=x.useMemo(()=>D?!0:!!(q!=null&&q.some(K=>(K==null?void 0:K.lang)===d)),[d,q,D]),$=()=>{let K="";return D?K=`/${b?[d,v].filter(Boolean).join("/"):v}`:K=`${at(C)}/${v}`,K.replace(/\/{2,}/g,"/").replace(/\/$/,"")},Y=K=>{const re=new URLSearchParams(window.location.search);V&&K===V?re.delete("lang"):re.set("lang",K),xe(re),window.dispatchEvent(new PopStateEvent("popstate"))},oe=K=>{K.preventDefault();const re={name:u,lang:d,primaryPage:o==null?void 0:o.id,slug:I?"":$(),pageType:o==null?void 0:o.pageType,...r&&{id:e}},me=()=>{!r&&d&&(ae(d),Y(d)),ge("outline"),n()};r?_(re,{onSuccess:me}):N(re,{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?ie.EDIT_LANGUAGE:ie.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:ie.ENTER_LANGUAGE_DETAILS})]}),t.jsx(zi,{id:e,pages:l,loading:ce,onSubmit:oe,edit:r,lang:d,languages:E,name:u,setLang:m,setName:h,primaryPageObject:o,parentHasSelectedLanguagePage:Q,isNonSlugPageType:I,isRootPage:D,useLanguagePrefix:b,setUseLanguagePrefix:w,isHomePage:G,parentSlug:C,slug:v,setSlug:y,isSlugValid:j,setIsSlugValid:p,getSlug:$,isPending:A})]})})};function Ki({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 j=y.target.value;if(!j.startsWith(a)){const _=j.replace(a,""),T=a+_;h(T),s(_);return}const b=j.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),w=(b.match(/\./g)||[]).length,N=w<=1;w>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(N);const P=a+b;h(P),s(b)},m=()=>{if(o.current){const y=o.current;setTimeout(()=>{const j=a.length;y.setSelectionRange(j,j)},0)}},v=y=>{const j=y.currentTarget;(j.selectionStart||0)<=a.length&&setTimeout(()=>{const b=a.length;j.setSelectionRange(b,b)},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:v,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const As=({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 Hi({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage",currentPage:i}){const[l,o]=x.useState(!1),[u,h]=x.useState(""),d=F.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(N=>!f.isEmpty(N.slug)).filter(N=>N.slug!=="/").sort((N,P)=>N.slug.localeCompare(P.slug)),[e]),v=x.useMemo(()=>{if(!u.trim())return m;const w=u.toLowerCase();return m.filter(N=>N.name.toLowerCase().includes(w)||N.slug.toLowerCase().includes(w))},[m,u]),y=w=>Math.max(0,(w.match(/\//g)||[]).length-1),j=w=>"    ".repeat(w),p=w=>{if(w==="/")return"/";const N=w.split("/").filter(Boolean);if(N.length<=1){const P=N[0]||"";return`/${at(P)}`}return`/${at(N[N.length-1])}`},b=()=>{if(!s||s==="none")return"None";const w=m.find(N=>N.id===s);return w?`${w.name} (${p(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:[b(),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(As,{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")})]}),v.map(w=>{const N=j(y(w.slug)),P=p(w.slug),_=t.jsxs("span",{className:"flex items-center text-sm",children:[N,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:_}),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 N=y(w.slug),P=N>0?j(N):"",_=p(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," (",_,")"]},w.id)})]})]})}const Qi=(...e)=>e.filter(Boolean).join(" "),Wi=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=x.useState(""),[l,o]=x.useState(!1),[u,h]=x.useState(""),d=F.useChaiFeatureFlag("enable-add-page-dropdown");if(x.useEffect(()=>{if(s){const p=e.find(b=>b.id===s);i((p==null?void 0:p.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(p=>{const b=p.libraryName;m[b]||(m[b]=[]),m[b].push(p)});const v=Object.entries(m).reduce((p,[b,w])=>{const N=w.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())||b.toLowerCase().includes(u.toLowerCase()));return N.length>0&&(p[b]=N),p},{}),y=e.find(p=>p.id===s),j=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:[j,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:p=>h(p.target.value)})]})}),t.jsxs(As,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(v).map(([p,b])=>t.jsx(c.CommandGroup,{heading:p,children:b.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:Qi("mr-2 h-4 w-4",s===w.id?"opacity-100":"opacity-0")})]},w.id))},p))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:p=>n(p.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(m).map(([p,b])=>t.jsx("optgroup",{label:p,children:b.map(w=>t.jsx("option",{value:w.id,children:f.startCase(w.name)},w.id))},p))]}),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"})]})]})},Ji=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_LIBRARIES],queryFn:async()=>await s(e,{action:O.GET_LIBRARIES})||[]})},Yi=e=>{const s=le(),n=ee();return U.useQuery({queryKey:[O.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:O.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?f.filter(a,{pageType:e}):a)||[]}})},Xi=e=>{const{data:s=[],isLoading:n}=Yi(e),{data:a=[],isLoading:r}=Ji(),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}},Gs=()=>{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])},$t=(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}},it=(...e)=>e.filter(Boolean).join(" ");function Zi({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var gs,ps;const r=Gs(),i=!!(e!=null&&e.id),{data:l}=ht(),{mutate:o,isPending:u}=Ta(),{mutate:h,isPending:d}=wn(),[m,v]=x.useState(null),[y,j]=x.useState(!0),[p,b]=x.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:w}=F.usePermissions(),N=w(be.CHANGE_PAGE_TYPE),[P,_]=x.useState(!1),[T,A]=x.useState(""),{selectedLang:z,fallbackLang:X}=F.useLanguages(),V=z||X,[L,R]=x.useState(""),[q,M]=x.useState(!1),J=x.useMemo(()=>{const k=s.find(ue=>ue.key===p);return(k==null?void 0:k.hasSlug)===!1},[p,s]),[H,ae]=x.useState((e==null?void 0:e.parent)??""),[xe,ge]=x.useState((e==null?void 0:e.name)??""),[ce,E]=x.useState((e==null?void 0:e.dynamic)??!1),[g,I]=x.useState(ce?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[G,C]=x.useState((e==null?void 0:e.dynamicSlugCustom)??""),[D,Q]=x.useState(!0),[$,Y]=x.useState(!1),[oe,K]=x.useState(""),{data:re,isLoading:me}=Xi(p),pe=u||d,B=F.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]),Z=s.find(k=>k.key===p),_e=k=>{if(i&&p!==k){A(k),_(!0),R(""),M(!1);return}b(k),R(""),M(!1)},Be=()=>{b(T),_(!1),E(!1)},zs=k=>{E(k),k?I(""):C("")},Vs=k=>{if(ae(k),k&&k!=="none"){const ue=l==null?void 0:l.find(De=>De.id===k),Fe=(ue==null?void 0:ue.slug)||"";if(g.startsWith(Fe)){const De=g.slice(Fe.length).replace(/^\/+/,"");I(De)}else I(g.replace(/^\/+/,""))}else I(g?`${g}`:"")},Ks=k=>{K(k)},fs=()=>xe.trim()?ce&&!f.isEmpty(g)?(v("Slug must be empty when using dynamic slug"),!1):ce&&!D?(v("Dynamic slug is invalid"),!1):!0:(W.toast.error("Name is required"),!1),Hs=()=>{const k={pageType:Z==null?void 0:Z.key,name:xe,slug:"",hasSlug:!1};i?h({id:e==null?void 0:e.id,name:xe},{onSuccess:()=>{W.toast.success((Z==null?void 0:Z.name)+" updated successfully"),n()}}):o(k,{onSuccess:ue=>{n(),r(ue.page.id,a)}})},xs=(k,ue)=>{if(!k.trim()&&!ce)return v("Child page slug is required"),!1;const Fe=at(ue),De=qn(Fe,k);return Object.keys(Ne).some(ys=>De===`/${ys}`||(De==null?void 0:De.startsWith(`/${ys}/`)))?(v("Slugs cannot start with a language code for primary page"),!1):!0},Qs=(k,ue)=>{const Fe=at(ue),De=qn(Fe,k),Re={pageType:p,name:xe,slug:De.replace(/\/$/,""),parent:H,dynamic:ce,hasSlug:!0,template:oe||void 0,tracking:{},seo:{},jsonLD:{}};if(ce&&(Re.dynamicSlugCustom=G),i){const qe=f.pick(Re,["pageType","parent","name","slug","dynamic","dynamicSlugCustom"]);h({id:e==null?void 0:e.id,...qe},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}})}else{const qe=f.find(s,{key:p});qe!=null&&qe.trackingDefault&&(Re.tracking=qe.trackingDefault);const{seo:ys,jsonLD:Dr}=$t(qe,V);f.set(Re,"seo",ys),f.set(Re,"jsonLD",Dr),o(Re,{onSuccess:Lr=>{n(),r(Lr.page.id,a)}})}},Ws=()=>{const k={pageType:p,name:xe,slug:g===""?"/":`/${g.replace(/\/$/,"")}`,template:oe||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:p});ue!=null&&ue.trackingDefault&&(k.tracking=ue.trackingDefault);const{seo:Fe,jsonLD:De}=$t(ue,V);f.set(k,"seo",Fe),f.set(k,"jsonLD",De),o(k,{onSuccess:Re=>{var qe;(qe=Re==null?void 0:Re.page)!=null&&qe.id&&r(Re.page.id,a),n()}})}},Rt=k=>{if(k.preventDefault(),v(null),!!fs()){if(!(Z!=null&&Z.hasSlug)){Hs();return}if(H&&H!=="none"){const ue=l==null?void 0:l.find(De=>De.id===H),Fe=(ue==null?void 0:ue.slug)||"";if(!xs(g,Fe))return;Qs(g,Fe)}else Ws()}},{pagesType:ft,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 Z!=null&&Z.hasSlug?t.jsxs("form",{onSubmit:Rt,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"}),B?t.jsxs(c.Popover,{open:q,onOpenChange:M,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!N,className:it("w-full justify-between",i&&!N?"cursor-not-allowed text-gray-500":""),children:[(Z==null?void 0:Z.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=>R(k.target.value)})]})}),t.jsxs(As,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),i?J?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:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:ft.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:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsxs(t.Fragment,{children:[ft.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:ft.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:it("mr-2 h-4 w-4",p===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:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!N,onChange:k=>_e(k.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!N?"cursor-not-allowed text-gray-500":""}`,children:i?J?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:()=>_(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]})]}),!i&&(Z==null?void 0:Z.hasSlug)&&re.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(Wi,{templates:re,selectedTemplateId:oe,onSelectTemplate:Ks,isLoading:me})]}),t.jsx(Hi,{pages:l,selectedParentId:H,onChange:Vs,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:xe,onChange:k=>ge(k.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(Z==null?void 0:Z.dynamicSegments)&&H&&H!=="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=>zs(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(Ki,{value:G,onChange:C,dynamicPattern:(Z==null?void 0:Z.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:Q})})})]}),(!(Z!=null&&Z.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:g,onChange:k=>{var ue;I(k),i&&k!==(((ue=e==null?void 0:e.slug)==null?void 0:ue.split("/").pop())||"")?Y(!!(Ee||Le)):Y(!1)},placeholder:H&&H!=="none"?"Enter page slug":p==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:H&&H!=="none"?(ps=l==null?void 0:l.find(k=>k.id===H))==null?void 0:ps.slug:void 0,onValidationChange:j}),m&&t.jsx("p",{className:"text-xs text-red-500",children:m}),$&&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:pe||!y&&(!(Z!=null&&Z.dynamicSegments)||!ce)||ce&&!D,type:"submit",className:"w-full",children:i?pe?"Updating...":"Update page":pe?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Rt,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"}),B?t.jsxs(c.Popover,{open:q,onOpenChange:M,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!N,className:it("w-full justify-between",i&&!N?"cursor-not-allowed text-gray-500":""),children:[(Z==null?void 0:Z.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=>R(k.target.value)})]})}),t.jsxs(As,{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),M(!1)},className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(S.Check,{className:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!N,onChange:k=>_e(k.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!N?"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:()=>_(!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:(gs=s.find(k=>k.key===p))==null?void 0:gs.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:xe,onChange:k=>ge(k.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:pe,type:"submit",className:"w-full",children:i?pe?"Updating...":"Update "+(Z==null?void 0:Z.name):pe?"Creating...":"Create "+(Z==null?void 0:Z.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(Zi,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function Us({page:e,onClose:s}){const[,n]=Pe(),{mutate:a,isPending:r}=ki(),{data:i}=Ce(),{setSelectedLang:l,fallbackLang:o}=F.useLanguages(),[,u]=F.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(Ne,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 el=()=>{const e=le(),s=U.useQueryClient(),n=ee();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:[O.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"})}})},An=({page:e,onClose:s,closePanel:n=()=>{}})=>{const{mutate:a,isPending:r}=el(),[i,l]=x.useState(null),[o,u]=x.useState(`${e.name} (Copy)`),h=Gs(),d=f.isEmpty(e.slug),[m,v]=x.useState(d?"":`${e.slug.split("/").pop()}-copy`),y=d?"":f.initial(e.slug.split("/")).join("/"),[j,p]=x.useState(!1),b=w=>{if(w.preventDefault(),!o.trim()){l("Name is required");return}if(!d&&!m.trim()){l("Slug is required");return}l(null),p(!0);const N={pageId:e.id,name:o};d||(N.slug=`${y}/${m}`),a(N,{onSuccess:P=>{p(!1),s(),h(P.id,n)},onError:P=>{p(!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:b,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=>v(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||j,children:r||j?"Duplicating...":"Duplicate"})]})]})]})})},tl=1*1024*1024,Tn=({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=Ii(),{data:v}=Ce(),y=v==null?void 0:v.find(P=>P.key===e.pageType),j=(y==null?void 0:y.name)||f.startCase(e.pageType),p=x.useCallback(P=>{var T;const _=(T=P.target.files)==null?void 0:T[0];if(_){if(_.size>tl){W.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(_.size/1024).toFixed(2)}KB.`}),d.current&&(d.current.value="");return}try{h(!0);const A=new FileReader;A.onloadend=()=>{o(A.result),h(!1)},A.readAsDataURL(_)}catch(A){console.error("Error reading file:",A),h(!1),W.toast.error("Failed to process image",{description:A instanceof Error?A.message:"Unknown error"})}}},[]),b=()=>{o(""),d.current&&(d.current.value="")},w=()=>{var P;(P=d.current)==null||P.click()},N=()=>{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:j})]})]}),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:p,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:b,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:N,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}=F.usePermissions(),{data:d}=Ce(),m=x.useMemo(()=>f.find(d,{key:e.pageType}),[d,e.pageType]),v=x.useMemo(()=>!!e.isTemplate,[e.isTemplate]),y=x.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!h(be.EDIT_PAGE)&&!h(be.DELETE_PAGE)&&!h(be.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:o}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[h(be.ADD_PAGE)&&!u&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(S.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),h(be.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(S.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&h(be.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(S.Power,{className:"size-3"}),ie.UNPUBLISH]}),h(be.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(S.Trash,{className:"size-3"}),ie.DELETE]}),h(be.MARK_AS_TEMPLATE)&&y&&!u&&t.jsx(t.Fragment,{children:v?t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(S.SquareLibrary,{className:"size-3"}),ie.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(S.SquareLibrary,{className:"size-3"}),ie.MARK_AS_TEMPLATE]})})]})]})},Pn=({page:e,onClose:s})=>{const[n,a]=x.useState(!1),r=_i(),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"})]})]})})},ms=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Pi(),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:[ie.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?ie.UPDATING:ie.UNPUBLISH})]})]})})},sl=da("expandedPagesState",[]),In=e=>f.flatMap(e,s=>[s,...s.children?In(s.children):[]]),nl=(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=nl(e,s);if(!f.isEmpty(r))return r}return[s]},al=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)},Mt=e=>{const[s,n]=je.useAtom(sl),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),v=_a(m,d);if(!Array.isArray(v)||f.isEmpty(v))return;const y=v.slice(0,-1);f.isEmpty(y)||n(j=>f.uniq([...j,...y]))},[n]),l=x.useCallback(h=>{if(f.isEmpty(h))return;const d=al(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 v=y=>[y.id,...y.children?f.flatMap(y.children,v):[]];return v(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}},$n=(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)})),rl=(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):[]}}),il=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=$n(r,s);else{const d=$n(r,s),m=rl(e,d);r=f.uniqBy([...d,...m],"id")}const i=Da(il(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,v)=>({...m,id:v,name:f.startCase(v),isPartialGroup:!0,children:l.filter(y=>y.pageType===v)})))}else h=u.sort((d,m)=>(d.name||"").localeCompare(m.name||""));return[...o,...h]},ll=({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:v})=>{const y=Gs(),{data:j}=Ce(),[,p]=F.useSidebarActivePanel(),b=x.useMemo(()=>f.find(j,{key:s.pageType}),[j,s.pageType]),w=x.useMemo(()=>{const T=f.get(s,"slug",""),A=e?at(e):"",z=A?T.replace(A,""):T;return z||"/"},[s,e]),N=x.useMemo(()=>!!s.isTemplate,[s.isTemplate]),P=x.useCallback(()=>{p("outline"),y(f.get(s,"id"),a)},[y,a,s,p]),_=x.useCallback(T=>{T.stopPropagation(),v()},[v]);return t.jsxs("div",{onClick:s.isPartialGroup?_: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:_,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"})}):b!=null&&b.icon?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:b.icon}}):b!=null&&b.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}),b!=null&&b.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,"/")?`${b==null?void 0:b.dynamicSlug}`:`/${b==null?void 0:b.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:b==null?void 0:b.name}),N&&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(hi,{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:T=>T.stopPropagation()})})})]})]})},ol=({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=C=>l?String(f.get(C,"name","")).toLowerCase().includes(l.toLowerCase())||String(f.get(C,"key","")).toLowerCase().includes(l.toLowerCase()):!0,[m,v]=x.useState(null),[y,j]=x.useState(null),[p,b]=x.useState(null),[w,N]=x.useState(null),{data:P,isFetching:_}=ht(),[T,A]=x.useState(""),{hasPermission:z}=F.usePermissions(),{updateForSelectedPage:X,expandPagesOnSearch:V,expandAll:L,collapseAll:R}=Mt(null),[q,M]=Pe(),J=q.get("page"),H=x.useRef(null),{data:ae}=Ce(),xe=F.useChaiFeatureFlag("enable-add-page-dropdown"),ge=x.useCallback(C=>{var D;return(D=f.find(ae,{key:C}))==null?void 0:D.hasSlug},[ae]);x.useEffect(()=>{if(!f.isEmpty(T))return;const C=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(ae)&&C&&(f.find(ae,{key:C})?A(C):A("all"))},[ae,T]);const ce=C=>{A(C),sessionStorage.setItem("pageTypeFilter",C),o("")},E=x.useCallback(C=>{const Q=new URLSearchParams(window.location.search).get("lang"),$=new URLSearchParams({page:C});Q&&$.set("lang",Q),tt($,M),e()},[M,e]);x.useEffect(()=>{if(J&&!_){const C=f.find(P,{id:J});if(C&&(C!=null&&C.pageType))s(D=>[...D,C==null?void 0:C.pageType]);else{const D=f.find(P,{slug:"/"});if(D){const Q=new URLSearchParams({page:D.id});tt(Q,M)}else tt(new URLSearchParams({}),M,!0)}}},[P,J,_,M]);const g=x.useMemo(()=>P?La(P,r,T,ge):[],[P,r,T,ge]);x.useEffect(()=>{J&&!_&&!f.isEmpty(g)&&(X(g,J),H.current&&H.current.scrollIntoView({behavior:"smooth",block:"end"}))},[J,_,g,X]),x.useEffect(()=>{!f.isEmpty(r)&&!f.isEmpty(g)&&V(g)},[r,g,V]);const I=x.useCallback(()=>{L(g)},[L,g]),G=x.useCallback(()=>{R()},[R]);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:C=>i(C.target.value)}),!f.isEmpty(T)&&t.jsxs(c.Select,{value:T,onValueChange:ce,children:[t.jsx(c.SelectTrigger,{className:`${T==="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:[xe&&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:C=>o(C.target.value),onKeyDown:C=>C.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!f.isEmpty(f.filter(ae,C=>C.hasSlug&&d(C)))&&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,C=>C.hasSlug&&d(C))].sort((C,D)=>f.get(C,"name","").localeCompare(f.get(D,"name",""))),C=>t.jsx(c.SelectItem,{value:f.get(C,"key"),children:f.get(C,"name")},f.get(C,"key")))]}),!f.isEmpty(f.filter(ae,C=>!C.hasSlug&&d(C)))&&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,C=>!C.hasSlug&&d(C))].sort((C,D)=>f.get(C,"name","").localeCompare(f.get(D,"name",""))),C=>t.jsx(c.SelectItem,{value:f.get(C,"key"),children:f.get(C,"name")},f.get(C,"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:I,className:"p-1 text-gray-500",children:t.jsx(S.ChevronsUpDown,{})}),t.jsx(c.Button,{variant:"outline",size:"icon",onClick:G,className:"p-1 text-gray-500",children:t.jsx(S.ChevronsDownUp,{})})]})]}),_?t.jsx("div",{className:"space-y-2",children:f.map([...Array(5).keys()],C=>t.jsx("div",{className:"h-9 w-full animate-pulse rounded bg-gray-200"},C))}):f.isEmpty(g)?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(g,C=>{const D=C.id===J;return t.jsx("div",{ref:D?H:null,children:t.jsx(Ba,{item:C,currentPage:J,close:e,setUnpublishPage:v,setDeletePage:h,setAddEditPage:j,setMarkAsTemplate:b,setUnmarkAsTemplate:N,setDuplicatePage:a,level:0})},`page-item-${C.id}`)})})]}),z(be.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex gap-x-2 text-sm",onClick:()=>{j({slug:"",name:"",pageType:T==="all"?"page":T})},children:[t.jsx(S.Plus,{className:"h-4 w-4"})," Add New"]}),y&&t.jsx(Cn,{closePanel:e,editPage:E,addEditPage:y,setAddEditPage:j}),u&&t.jsx(Us,{page:u,onClose:()=>h(null)}),m&&t.jsx(ms,{page:m,onClose:()=>v(null)}),p&&t.jsx(Tn,{page:p,onClose:()=>b(null)}),w&&t.jsx(Pn,{page:w,onClose:()=>N(null)}),n&&t.jsx(An,{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:v,toggleExpanded:y}=Mt(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(ll,{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:v,onToggleExpand:y}),m&&v&&t.jsx("div",{className:"bg-white pl-6 pt-2",children:f.map(f.get(e,"children",[]),j=>t.jsx(Ba,{item:j,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:d+1},j.id||`child-${d}-${j.key}`))})]},e.id||`level-${d}-${e.key}`)},cl=({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"})]})]})},ul=({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"})]}),dl=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Mt(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=Ye();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"}`}),Ne[r]||""]},r))})},zn=()=>{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:[O.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"})]})},hl=({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(cl,{selectedPageType:o,setSelectedPageType:u}),t.jsx(ul,{search:s,setSearch:n}),t.jsx(dl,{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(zn,{})]}),m?t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(Ma,{languages:a,selectedLanguage:i,setSelectedLanguage:v=>{l(v),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(zn,{})]})]}):t.jsx("div",{className:"flex items-center justify-between gap-2"})]})};function ut({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 ml=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Mt(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":""}`})})},fl=({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"})}),xl=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),gl=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i,showUntranslatedPages:l})=>{const[o]=wa(),u=Ye(),h=n===e.id,d=!!e.isTemplate,m=x.useMemo(()=>f.find(s,{key:e.pageType}),[s,e.pageType]),v=o==null?void 0:o[e.id],{data:y}=Ke(v),j=y?y==null?void 0:y.name:null;let p=f.get(r,e==null?void 0:e.id);p=f.get(p,"lang")===i?p:null;const b=i===u||!!p,w=(p==null?void 0:p.name)||(e==null?void 0:e.name)||"No name";let N=(p==null?void 0:p.slug)||(e==null?void 0:e.slug)||"";const P=N+(e!=null&&e.dynamic?`/${m==null?void 0:m.dynamicSlug}`:"")+(e!=null&&e.dynamicSlugCustom?`${e.dynamicSlugCustom}`:"");if(N.startsWith("/")&&!l){const T=N.split("/").pop();N=N.endsWith(T)&&e.dynamic?"":`/${T}`}const _=x.useMemo(()=>{const T="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]",A=`${h?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return b?`${T} ${A} ${j?"opacity-60":""}`:`${T} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[b,h,j]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&b&&a("select",e==null?void 0:e.id),className:_,children:[t.jsx(ml,{page:e}),!e.isPartialGroup&&t.jsx(xl,{isOnline:p?p.online:e.online}),t.jsx(fl,{page:e,pageType:m}),t.jsx(ut,{content:w,side:"top",showTooltip:w.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:w})}),(N||e.dynamic)&&t.jsx(ut,{content:P,side:"top",showTooltip:!0,children:t.jsxs("span",{className:"max-w-[40%] truncate font-mono text-xs text-muted-foreground",children:[N,e.dynamic&&(m==null?void 0:m.dynamicSlug)&&t.jsxs("span",{className:"text-xs text-gray-500",children:["/",m==null?void 0:m.dynamicSlug,e.dynamicSlugCustom]})]})}),d&&t.jsx(ut,{content:"Template",side:"top",children:t.jsx("span",{className:"text-blue-500",children:t.jsx(S.NotepadText,{size:16})})}),!e.isPartialGroup&&b&&!j?t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(kn,{isLanguagePage:!!p,page:p||e,setDuplicatePage:T=>a("duplicate",T),setAddEditPage:T=>a("edit",p||T),setUnpublishPage:T=>a("unpublish",T),setDeletePage:T=>a("delete",p||T),setMarkAsTemplate:T=>a("markAsTemplate",T),setUnmarkAsTemplate:T=>a("unmarkAsTemplate",T),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:T=>T.stopPropagation()})})})}):j?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:j&&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:j})," is editing this page"]})}),t.jsx(t.Fragment,{children:!b&&!e.isPartialGroup&&!j&&t.jsxs("button",{onClick:T=>{T.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(Ne,i)," Page"]})]})})]})},Oa=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o})=>{const{expandedPages:u}=Mt();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(gl,{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))})},Ra=({close:e})=>{const{languages:s,setSelectedLang:n}=F.useLanguages(),{data:a}=Ce(),{data:r,isFetching:i}=ht(),[l,o]=Pe(),{updateForSelectedPage:u,expandPagesOnSearch:h}=Mt(null),d=Ye(),m=l.get("page"),[v,y]=x.useState(""),[j,p]=x.useState(null),[b,w]=x.useState(null),[N,P]=x.useState(null),[_,T]=x.useState(null),[A,z]=x.useState(""),[X,V]=x.useState(null),[L,R]=x.useState(null),[q,M]=x.useState(d),[J,H]=x.useState(!1),[,ae]=je.useAtom(hs),xe=J&&q!==d,{data:ge,isFetching:ce}=Ri(q),E=x.useCallback(C=>{var D;return(D=f.find(a,{key:C}))==null?void 0:D.hasSlug},[a]),g=x.useMemo(()=>r?xe?f.filter(r,C=>!(ge!=null&&ge[C.id])):La(r,v,A,E):[],[r,E,v,A,ge,xe]);x.useEffect(()=>{n(d)},[d,n]),x.useEffect(()=>{if(!f.isEmpty(A))return;const C=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(a)&&C&&(f.find(a,{key:C})?z(C):z("all"))},[a,A]),x.useEffect(()=>{if(m&&!i&&!f.find(r,{id:m})){const D=f.find(r,{slug:"/"});if(D){const Q=new URLSearchParams({page:D.id});tt(Q,o)}else tt(new URLSearchParams({}),o,!0)}},[r,m,i,o]),x.useEffect(()=>{m&&!i&&!f.isEmpty(g)&&u(g,m)},[m,i,g,u]),x.useEffect(()=>{!f.isEmpty(v)&&!f.isEmpty(g)&&h(g)},[v,g,h]);const I=x.useCallback(C=>{const D=new URLSearchParams({page:C});q!==d&&D.set("lang",q),tt(D,o),e()},[e,o,q,d]),G=(C,D)=>{var Q;if(D)switch(C){case"add":w(D);break;case"select":I(D);break;case"edit":q!==d?ae({edit:!0,id:D==null?void 0:D.id,primaryPage:D==null?void 0:D.primaryPage}):w(D);break;case"delete":p(D);break;case"unpublish":P(D);break;case"markAsTemplate":T(D);break;case"unmarkAsTemplate":R(D);break;case"duplicate":V(D);break;case"addLanguagePage":ae({edit:!1,primaryPage:((Q=D==null?void 0:D.page)==null?void 0:Q.id)||"",preselectedLang:(D==null?void 0:D.language)||q});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(hl,{pages:g,search:v,setSearch:y,languages:[d,...s],selectedLanguage:q,setSelectedLanguage:M,selectedPageType:A,setSelectedPageType:z,onAddPage:C=>G("add",C),showUntranslatedPages:xe,setShowUntranslatedPages:H}),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()],C=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},C))}):f.isEmpty(g)?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:g,pageTypes:a,currentPage:m||"",onClickAction:G,languagePages:ge,selectedLanguage:q,showUntranslatedPages:xe})})]}),b&&t.jsx(Cn,{closePanel:e,editPage:I,addEditPage:b,setAddEditPage:w}),j&&t.jsx(Us,{page:j,onClose:()=>p(null)}),N&&t.jsx(ms,{page:N,onClose:()=>P(null)}),_&&t.jsx(Tn,{page:_,onClose:()=>T(null)}),L&&t.jsx(Pn,{page:L,onClose:()=>R(null)}),X&&t.jsx(An,{page:X,onClose:()=>V(null),closePanel:e})]})},pl=()=>{const e=Ue("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:x.createElement(e,{})}):null},yl=()=>{const[e,s]=Pe(),n=e.get("page"),{data:a,isFetching:r}=ke(),{data:i,isFetching:l}=ht(),[o,u]=x.useState(!1),[h,d]=x.useState(!0),{savePage:m}=F.useSavePage(),v=!!n&&!f.isEmpty(a),y=x.useMemo(()=>!i||l?!1:i.some(N=>N.slug==="/"),[i,l]);x.useEffect(()=>{if(!n&&!l&&i&&y){const N=i.find(P=>P.slug==="/");if(N){const P=new URLSearchParams({page:N.id});tt(P,s)}}!l&&i&&d(!1)},[n,l,i,y,s]);const j=!h&&!n&&!y,p=!h&&!r&&f.isEmpty(a)&&!y,b=o||j||p,w=F.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:()=>{m(),u(!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:b,onOpenChange:N=>!N&&v&&u(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`${w?"w-full !max-w-screen-md":"!min-w-[50vh] !max-w-[800px] p-0"} z-50 border-border ${v?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:`mb-3 ${w?"":"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:`${b?"h-[calc(100vh-80px)] overflow-y-auto":"h-[calc(100vh-70px)] overflow-y-auto"}`,children:w?t.jsx(ol,{close:()=>u(!1)}):b&&t.jsx(Ra,{close:()=>u(!1)})})]})})]})},_n=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=F.useLanguages(),l=f.isEmpty(r)?n:r,[,o]=Pe(),{isLocked:u}=Je();x.useEffect(()=>{const b=new URLSearchParams(window.location.search),w=b.get("lang");w&&(a.includes(w)?i(w):(b.delete("lang"),o(b),i("")))},[a,o,i]);const[,h]=je.useAtom(hs),{data:d}=ke(),{data:m}=Ve(),{data:v}=Ge(),y=x.useMemo(()=>{const b=f.compact(f.map(f.get(m,"languages"),w=>{const N=f.find(v,{lang:w});return{key:w,value:f.get(Ne,w,w),isLangPageAdded:!!N}})).filter(Boolean);return[{key:n,value:f.get(Ne,n),isLangPageAdded:!0},...b]},[n,v,m]),j=b=>{if(document.querySelector('[data-panel-id="seo"]')){const N=new CustomEvent("seo-language-switch-check",{detail:{fromLang:l,toLang:b,switchHandler:()=>p(b)}});window.dispatchEvent(N);return}p(b)},p=b=>{i(b);const w=new URLSearchParams(window.location.search);b===n?w.delete("lang"):w.set("lang",b),tt(w,o)};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(Ne,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(Ne,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(b=>b.isLangPageAdded),b=>t.jsxs(c.DropdownMenuItem,{className:F.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",b.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>j(b.key),children:[t.jsx("div",{className:"text-slate-600",children:b.value}),b.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"]})]},b.value)),e&&!f.isEmpty(y.filter(b=>!b.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 jl(){const[e,s]=je.useAtom(hs);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(pl,{}),t.jsx(yl,{}),e&&t.jsx(Vi,{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 vl(e,s){const n=le(),a=ee();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:O.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 bl=({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:dt.formatDate(s.createdAt,"dd MMM yyyy, h:mm a")})]})]})},Vn=({version:e})=>t.jsx(bl,{version:e});function wl(e,s,n="data.json"){const a=JSON.stringify(e,null,2),r=JSON.stringify(s,null,2),i=a.split(`
1
+ "use strict";var Mr=Object.defineProperty;var On=e=>{throw TypeError(e)};var Or=(e,s,n)=>s in e?Mr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var et=(e,s,n)=>Or(e,typeof s!="symbol"?s+"":s,n),Rn=(e,s,n)=>s.has(e)||On("Cannot "+n);var te=(e,s,n)=>(Rn(e,s,"read from private field"),n?n.call(e):s.get(e)),fe=(e,s,n)=>s.has(e)?On("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),he=(e,s,n,a)=>(Rn(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"),je=require("jotai"),U=require("@tanstack/react-query"),W=require("sonner"),F=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),dt=require("date-fns"),S=require("lucide-react"),Rr=require("compressorjs"),Js=require("react-diff-view"),ua=require("@chaibuilder/runtime"),Ss=require("zod"),Gr=require("react-dropzone"),Ur=require("@chaibuilder/sdk/web-blocks");function Fr(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 we=Fr(x),Ne={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"},O={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 qr=0;function Gn(e,s){const n=`atom${++qr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=$r,a.write=zr),s&&(a.write=s),a}function $r(e){return e(this)}function zr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const Vr=Symbol(""),Kr=e=>typeof(e==null?void 0:e.then)=="function";function Hr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,h)=>{var d,m;const v=j=>{if(j=j||"",a!==j){try{r=JSON.parse(j,s==null?void 0:s.reviver)}catch{return h}a=j}return r},y=(m=(d=e())==null?void 0:d.getItem(u))!=null?m:null;return Kr(y)?y.then(v):v(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,v=>{let y;try{y=JSON.parse(v||"")}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 Qr=Hr();function da(e,s,n=Qr,a){const r=Gn(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Gn(l=>l(r),(l,o,u)=>{const h=typeof u=="function"?u(l(r)):u;return h===Vr?(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 ha="__logged_in_user",Wr=da(ha,null),Oe=()=>{const[e,s]=je.useAtom(Wr),n=x.useCallback(()=>{s(null),localStorage.removeItem(ha)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},gn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)});let pt=null;function Jr(){const{user:e,setUser:s,logout:n}=Oe(),a=Os(),r=Ue("getAccessToken",!1),i=async()=>{if(r===!1&&e&&!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken")))try{const l=await gn(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(pt)return await pt;pt=i();try{return await pt}finally{pt=null}},onSuccess:()=>{}})}function Yr(){return pt}const ma=()=>{const{user:e,setUser:s}=Oe(),{mutateAsync:n}=Jr(),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=Ue("getAccessToken",async()=>{if(!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken"))){if(r()){const o=Yr();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])}},ee=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ma();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 gn(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])},fa=()=>{const e=le(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]})}})},xa=()=>{const e=le(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[O.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})}})},Xr=()=>{const e=le(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[O.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 Zr=je.atom({}),ga=()=>je.useAtom(Zr),ei=()=>{const[e]=Pe(),s=e.get("page"),n=x.useRef(""),{mutate:a}=fa();x.useEffect(()=>{!f.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Ue=(e,s)=>{const[n]=ga();return x.useMemo(()=>f.get(n,e,s),[n,e,s])},le=()=>Ue("apiUrl","/chai/api"),Os=()=>Ue("usersApiUrl","/chai/users"),us=()=>Ue("assetsApiUrl","/chai/assets"),ti=()=>Ue("supabaseInstance",null),Ge=e=>{const s=le(),[n]=Pe(),a=e??n.get("page"),r=ee();return U.useQuery({queryKey:[O.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:O.GET_LANGUAGE_PAGES,data:{id:a}});return f.reverse(f.sortBy(i,"primaryPage"))},enabled:!!a})},Ve=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:O.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},pa=e=>{const{fallbackLang:s}=F.useLanguages(),{data:n}=Ve(),{data:a,isFetching:r}=Ge(),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]},pn=()=>{const e=U.useQueryClient(),{data:s}=U.useQuery({queryKey:[O.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:x.useCallback(a=>{e.setQueryData([O.AI_CONTEXT],a)},[e]),aiContext:s}},si=je.atom(null),ya=()=>je.useAtom(si),yn=()=>{const[e]=ya();return(e==null?void 0:e.slug)||""};function ni(e,s){const[n,a]=x.useState(e);return x.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const ai=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=F.useLanguages(),{data:r}=ke(),i=r==null?void 0:r.pageType,l=le(),o=ee(),{data:u,isFetching:h}=U.useQuery({queryKey:[O.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await o(l,{action:O.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}},ja=()=>{const{selectedLang:e,fallbackLang:s}=F.useLanguages(),[n,a]=ya(),[r,i]=x.useState(""),l=ni(r,500),{allLangPages:o,data:u,isFetching:h}=ai({query:l}),d=x.useCallback(y=>a(y),[a]),m=x.useCallback(y=>i(y),[i]),v=x.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),j=e.length===0,p=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,w=o.filter(N=>(N==null?void 0:N.primaryPage)===p||N.id===p).find(N=>j?N.lang===e||N.lang===s:N.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:v}},ri=je.atom({lastSaved:void 0}),Rs=()=>je.useAtom(ri),ke=()=>{const[e]=Pe(),s=e.get("page"),{data:n,isFetching:a}=Ge();return{data:x.useMemo(()=>({...f.find(n,{id:s})||{}}),[n,s]),isFetching:a}},We=()=>{const[e]=Pe(),s=e.get("lang")??"",{data:n,isFetching:a}=Ge();return{data:x.useMemo(()=>f.find(n,{lang:s})||{},[n,s]),isFetching:a}},ii=je.atom({}),li=()=>je.useAtom(ii),va=()=>{const{data:e}=We(),s=yn(),n=Ue("getLiveUrl",f.noop),a=e==null?void 0:e.slug,r=n(a||"/");return s?r+s:r};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=Os(),n=ee();return U.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:O.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!f.isEmpty(e)})},oi=je.atom(void 0),ci=je.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),ui=je.atom(""),di=je.atom(null),jn=je.atom({}),wa=()=>je.useAtom(jn),Je=()=>{const[e]=Pe(),s=e.get("page"),{user:n}=Oe(),[a,r]=je.useAtom(oi),[i,l]=je.useAtom(ci),[o,u]=je.useAtom(di),[h,d]=je.useAtom(ui),[m]=je.useAtom(jn);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])},hi=()=>{const e=ti(),{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}=Je(),[,d]=je.useAtom(jn),m=x.useRef(!1),v=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 j=async(b,w)=>{var N,P;switch(b){case"UPDATE_ONLINE_USERS":d((w==null?void 0:w.pageToUser)||{});break;case"PAGE_LOCKED":l({...v==null?void 0:v.current,requestedBy:"",status:"locked",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"USER_JOINED":if(((N=v==null?void 0:v.current)==null?void 0:N.status)==="editing")return;((P=v==null?void 0:v.current)==null?void 0:P.status)==="locked"&&o("can_edit_now"),l({...v==null?void 0:v.current,requestedBy:"",status:"editing",isActiveInOtherTab:w==null?void 0:w.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":l({...v==null?void 0:v.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({...v==null?void 0:v.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":o("take_over_request_rejected"),l({...v==null?void 0:v.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},p=new ba(e,r==null?void 0:r.appKey,n==null?void 0:n.id,j);h(p)}},[h,e,r==null?void 0:r.appKey]),x.useEffect(()=>{v.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,v.current={requestedBy:"",status:"checking",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1},o(""),l(v.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}=Je(),{savePageAsync:l}=F.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}},Ye=()=>{const{data:e}=Ve();return x.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},Na=()=>{const[e]=Pe(),s=e.get("page"),n=le(),{setAiContext:a}=pn(),{setCurrentEditor:r}=Je(),[,i]=Rs(),[,l]=li(),[,o]=F.useIsPageLoaded(),u=ee();return U.useQuery({queryKey:[O.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r(""),o(!1);const h=await u(n,{action:O.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(v=>({...v,lastSaved:h.lastSaved})),l(f.get(h,"metadata",{})),setTimeout(()=>o(!0),500),d},enabled:!!s})},vn=()=>{const{data:e}=ke(),{data:s}=We(),n=le(),a=ee(),r=Ye(),i=yn();return U.useQuery({queryKey:[O.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:O.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,metadata:e.metadata||{}}}}),enabled:!!(e!=null&&e.pageType)&&!!s.id})},ds=({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(ds,{children:s}):t.jsx("div",{className:"flex h-full w-full items-center justify-center",children:s})},mi=({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"]})})]})})},fi=({userId:e})=>{const{data:s}=Ke(e);return(s==null?void 0:s.name)||"Unknown"};function xi({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),v=()=>{h(!0),setTimeout(()=>{h(!1)},15e3),m(!1),r()};return t.jsx(ds,{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:"," ",dt.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:v,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:v,children:"Yes, Take Over"})]})]})]})})]})})}const js=({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(ds,{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(fi,{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"]})]})]})})},gi=()=>{const{pageLock:e,requestTakeOver:s}=Sa(),{isLocked:n,currentEditor:a,lockingStatus:r,setLockingStatus:i,realtimePageLockEnabled:l}=Je(),{data:o,isFetching:u}=Ke(a),[h]=Pe(),d=h.get("page"),{mutate:m}=fa(),{isFetching:v}=Na(),[y]=Rs(),j=U.useQueryClient(),p=x.useCallback(()=>{l?s():m({id:d})},[d,m,s,l]);return d?l&&(e==null?void 0:e.status)==="checking"?t.jsx(js,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):l&&(e!=null&&e.requestedBy)?t.jsx(js,{lockingStatus:"",onContinue:()=>{}}):(l?e.status!=="locked":!n||v)?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(js,{lockingStatus:r,onContinue:()=>{j.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]}),i("")}}):null:l&&(e!=null&&e.isActiveInOtherTab)?t.jsx(js,{lockingStatus:"page_is_active_in_other_tab",onContinue:s}):t.jsx(xi,{...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:p,realtimePageLockEnabled:l,isRequestRejected:r==="take_over_request_rejected"}):null},pi=()=>{const[e,s]=Pe(),n=e.get("lang"),a=pa(n),{setSelectedLang:r}=F.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(Ne,n);return t.jsx(ds,{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"})})]})})},yi=e=>{const s=le(),n=ee();return U.useMutation({mutationFn:async a=>n(s,{action:O.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"})}})},ji=e=>{const s=le(),n=ee();return U.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:O.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})},vi=e=>{const s=le(),n=ee();return U.useMutation({mutationFn:async a=>n(s,{action:O.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"})}})},bi=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=x.useState(!1),u=F.useUpdateBlocksPropsRealtime(),h=vi(()=>{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:v=>v.preventDefault(),disabled:l,children:[t.jsx(S.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:v=>!v&&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"})]})]})})]})},wi=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=x.useState(!1);return t.jsx(bi,{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"]})})},Si=()=>{const e=le(),s=ee(),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}},Ni=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),[r,i]=x.useState(""),l=x.useRef(null),{groups:o}=Si(),[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(j=>j.id===y.id))],[o,u]),m=()=>{const y=r.trim();if(!y)return;const j={id:y,name:y};h(p=>[...p,j]),s(j.id),i(""),a(!1)};x.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const v=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:v}),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(j=>j.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"})})]})},Un=3*1024*1024,Ei=10*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<=Un){s(e);return}new Rr(e,{quality:.8,maxWidth:2048,maxHeight:2048,convertSize:Un,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(Ei)}.`),n(a)}})})}const Ci=({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)try{a(!0);let m=h;h.type.startsWith("image/")&&(m=await Ca(h));const v=new FileReader;v.onloadend=()=>{s(v.result),a(!1)},v.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"})})]})},be={...F.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"},Ai=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=F.usePartailBlocksStore(),i=s.find(I=>I._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=x.useMemo(()=>s.some(I=>I._type==="PartialBlock"||I._type==="GlobalBlock"),[s]),h=x.useMemo(()=>{let I=[];for(const G of s)if(G._type==="PartialBlock"||G._type==="GlobalBlock"){let C=r(G.partialBlockId);G._parent&&(C==null?void 0:C.length)>0&&(C=C.map(D=>(f.isEmpty(D._parent)&&f.set(D,"_parent",G._parent),D))),I=[...I,...C]}else I.push(G);return I},[s,r]),[d,m]=x.useState(""),[v,y]=x.useState(""),[j,p]=x.useState(""),[b,w]=x.useState(""),[N,P]=x.useState({}),[_,T]=x.useState(!1),[A,z]=x.useState(o),[X,V]=x.useState(!1),{hasPermission:L}=F.usePermissions(),R=L(be.DELETE_LIBRARY_BLOCK),q=F.useUpdateBlocksPropsRealtime(),M=()=>{q([a],{_libBlockId:void 0}),W.toast.success("Block delinked from library"),n()},{data:J,isLoading:H,isError:ae}=ji(l);x.useEffect(()=>{ae&&o&&(V(!0),z(!1))},[ae,o]),x.useEffect(()=>{J&&!H&&(m(J.name||""),y(J.group||""),p(J.description||""),w(J.preview||""),z(!1))},[J,H]),x.useEffect(()=>{const I=d.trim().length>=2,G=v.trim()!=="";T(I&&G)},[d,v]);const xe=()=>{const I={};return d.trim()?d.length<2&&(I.name="Name must be at least 2 characters"):I.name="Name is required",v||(I.group="Group is required"),P(I),Object.keys(I).length===0},{resetLibrary:ge}=F.useLibraryBlocks({id:""}),ce=yi(I=>{o||q([a],{_libBlockId:I.id}),W.toast.success(`Block ${o?"updated":"saved"} successfully`),ge(I.library),n()}),E=async I=>{if(I.preventDefault(),!xe())return;const G=h.map(C=>(f.has(C,"_libBlockId")&&delete C._libBlockId,C));ce.mutate({name:d.trim(),group:v,blocks:G,description:j.trim(),...b&&b.startsWith("data:")?{previewImage:b}:{},...o?{id:l}:{}})},g=ce.isPending;return A||H?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"})}):X?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:M,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:E,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:N.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:d,onChange:I=>m(I.target.value),className:N.name?"border-destructive":""}),N.name&&t.jsx("p",{className:"text-xs text-destructive",children:N.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:N.group?"text-destructive":"",children:"Group"}),t.jsx(Ni,{value:v,onChange:y}),N.group&&t.jsx("p",{className:"text-xs text-destructive",children:N.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:j,onChange:I=>p(I.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Ci,{value:b,onChange:w})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&R&&t.jsx(wi,{blockId:a,libBlockId:l,blockName:d,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:g,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:g||!_,children:g?"Saving...":o?"Update Block":"Save Block"})]})]})]})},ie={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."},Ti={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ce=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:O.GET_PAGE_TYPES})})},Aa=e=>{const{data:s}=Ce();return x.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},ki=()=>{const e=le(),s=ee();return U.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:O.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Ta=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>await n(e,{action:O.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[O.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(Ti,r.message,r.message)})}})},bn=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=We(),{data:r}=Ce();return U.useMutation({mutationFn:async i=>await n(e,{action:O.UPDATE_PAGE,data:i}),onSuccess:(i,l)=>{(a==null?void 0:a.id)===(l==null?void 0:l.id)&&s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES]}),l&&(l!=null&&l.primaryPage||l!=null&&l.seo)?(s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,l==null?void 0:l.primaryPage]}),s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[O.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})}})},Pi=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:O.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:[O.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[O.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})}})},Ii=()=>{const e=le(),s=U.useQueryClient(),n=ee(),{data:a}=Ce();return U.useMutation({mutationFn:async r=>n(e,{action:O.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]});const l=f.find(a,{key:i.pageType});W.toast.success(l!=null&&l.hasSlug?ie.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})}})},wn=()=>{const e=le(),s=ee(),n=U.useQueryClient(),{data:a}=ke(),{savePageAsync:r}=F.useSavePage();return U.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:O.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[O.GET_CHANGES]}),n.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),W.toast.error("Failed to publish pages.")}})},_i=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>{var r;return s(e,{action:O.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:[O.GET_WEBSITE_PAGES]}),W.toast.success("Page marked as template successfully.")},onError:()=>{W.toast.error("Failed to mark page as template.")}})},Di=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>s(e,{action:O.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]}),W.toast.success("Page unmarked as template successfully.")},onError:()=>{W.toast.error("Failed to unmark page as template.")}})},Li=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:O.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{W.toast.success(ie.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[O.GET_WEBSITE_PAGES]})},onError:()=>{W.toast.error("Failed to change slug")}})};var Sn={};(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 E=new OffscreenCanvas(1,1),g=E.getContext("2d");g.fillRect(0,0,1,1);var I=E.transferToImageBitmap();try{g.createPattern(I,"no-repeat")}catch{return!1}return!0}();function u(){}function h(E){var g=n.exports.Promise,I=g!==void 0?g:s.Promise;return typeof I=="function"?new I(E):(E(u,u),null)}var d=function(E,g){return{transform:function(I){if(E)return I;if(g.has(I))return g.get(I);var G=new OffscreenCanvas(I.width,I.height),C=G.getContext("2d");return C.drawImage(I,0,0),g.set(I,G),G},clear:function(){g.clear()}}}(o,new Map),m=function(){var E=Math.floor(16.666666666666668),g,I,G={},C=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(g=function(D){var Q=Math.random();return G[Q]=requestAnimationFrame(function $(Y){C===Y||C+E-1<Y?(C=Y,delete G[Q],D()):G[Q]=requestAnimationFrame($)}),Q},I=function(D){G[D]&&cancelAnimationFrame(G[D])}):(g=function(D){return setTimeout(D,E)},I=function(D){return clearTimeout(D)}),{frame:g,cancel:I}}(),v=function(){var E,g,I={};function G(C){function D(Q,$){C.postMessage({options:Q||{},callback:$})}C.init=function($){var Y=$.transferControlToOffscreen();C.postMessage({canvas:Y},[Y])},C.fire=function($,Y,oe){if(g)return D($,null),g;var K=Math.random().toString(36).slice(2);return g=h(function(re){function me(pe){pe.data.callback===K&&(delete I[K],C.removeEventListener("message",me),g=null,d.clear(),oe(),re())}C.addEventListener("message",me),D($,K),I[K]=me.bind(null,{data:{callback:K}})}),g},C.reset=function(){C.postMessage({reset:!0});for(var $ in I)I[$](),delete I[$]}}return function(){if(E)return E;if(!a&&i){var C=["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
+ `);try{E=new Worker(URL.createObjectURL(new Blob([C])))}catch(D){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",D),null}G(E)}return E}}(),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 j(E,g){return g?g(E):E}function p(E){return E!=null}function b(E,g,I){return j(E&&p(E[g])?E[g]:y[g],I)}function w(E){return E<0?0:Math.floor(E)}function N(E,g){return Math.floor(Math.random()*(g-E))+E}function P(E){return parseInt(E,16)}function _(E){return E.map(T)}function T(E){var g=String(E).replace(/[^0-9a-f]/gi,"");return g.length<6&&(g=g[0]+g[0]+g[1]+g[1]+g[2]+g[2]),{r:P(g.substring(0,2)),g:P(g.substring(2,4)),b:P(g.substring(4,6))}}function A(E){var g=b(E,"origin",Object);return g.x=b(g,"x",Number),g.y=b(g,"y",Number),g}function z(E){E.width=document.documentElement.clientWidth,E.height=document.documentElement.clientHeight}function X(E){var g=E.getBoundingClientRect();E.width=g.width,E.height=g.height}function V(E){var g=document.createElement("canvas");return g.style.position="fixed",g.style.top="0px",g.style.left="0px",g.style.pointerEvents="none",g.style.zIndex=E,g}function L(E,g,I,G,C,D,Q,$,Y){E.save(),E.translate(g,I),E.rotate(D),E.scale(G,C),E.arc(0,0,1,Q,$,Y),E.restore()}function R(E){var g=E.angle*(Math.PI/180),I=E.spread*(Math.PI/180);return{x:E.x,y:E.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:E.startVelocity*.5+Math.random()*E.startVelocity,angle2D:-g+(.5*I-Math.random()*I),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:E.color,shape:E.shape,tick:0,totalTicks:E.ticks,decay:E.decay,drift:E.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:E.gravity*3,ovalScalar:.6,scalar:E.scalar,flat:E.flat}}function q(E,g){g.x+=Math.cos(g.angle2D)*g.velocity+g.drift,g.y+=Math.sin(g.angle2D)*g.velocity+g.gravity,g.velocity*=g.decay,g.flat?(g.wobble=0,g.wobbleX=g.x+10*g.scalar,g.wobbleY=g.y+10*g.scalar,g.tiltSin=0,g.tiltCos=0,g.random=1):(g.wobble+=g.wobbleSpeed,g.wobbleX=g.x+10*g.scalar*Math.cos(g.wobble),g.wobbleY=g.y+10*g.scalar*Math.sin(g.wobble),g.tiltAngle+=.1,g.tiltSin=Math.sin(g.tiltAngle),g.tiltCos=Math.cos(g.tiltAngle),g.random=Math.random()+2);var I=g.tick++/g.totalTicks,G=g.x+g.random*g.tiltCos,C=g.y+g.random*g.tiltSin,D=g.wobbleX+g.random*g.tiltCos,Q=g.wobbleY+g.random*g.tiltSin;if(E.fillStyle="rgba("+g.color.r+", "+g.color.g+", "+g.color.b+", "+(1-I)+")",E.beginPath(),l&&g.shape.type==="path"&&typeof g.shape.path=="string"&&Array.isArray(g.shape.matrix))E.fill(xe(g.shape.path,g.shape.matrix,g.x,g.y,Math.abs(D-G)*.1,Math.abs(Q-C)*.1,Math.PI/10*g.wobble));else if(g.shape.type==="bitmap"){var $=Math.PI/10*g.wobble,Y=Math.abs(D-G)*.1,oe=Math.abs(Q-C)*.1,K=g.shape.bitmap.width*g.scalar,re=g.shape.bitmap.height*g.scalar,me=new DOMMatrix([Math.cos($)*Y,Math.sin($)*Y,-Math.sin($)*oe,Math.cos($)*oe,g.x,g.y]);me.multiplySelf(new DOMMatrix(g.shape.matrix));var pe=E.createPattern(d.transform(g.shape.bitmap),"no-repeat");pe.setTransform(me),E.globalAlpha=1-I,E.fillStyle=pe,E.fillRect(g.x-K/2,g.y-re/2,K,re),E.globalAlpha=1}else if(g.shape==="circle")E.ellipse?E.ellipse(g.x,g.y,Math.abs(D-G)*g.ovalScalar,Math.abs(Q-C)*g.ovalScalar,Math.PI/10*g.wobble,0,2*Math.PI):L(E,g.x,g.y,Math.abs(D-G)*g.ovalScalar,Math.abs(Q-C)*g.ovalScalar,Math.PI/10*g.wobble,0,2*Math.PI);else if(g.shape==="star")for(var B=Math.PI/2*3,se=4*g.scalar,Ee=8*g.scalar,Le=g.x,Z=g.y,_e=5,Be=Math.PI/_e;_e--;)Le=g.x+Math.cos(B)*Ee,Z=g.y+Math.sin(B)*Ee,E.lineTo(Le,Z),B+=Be,Le=g.x+Math.cos(B)*se,Z=g.y+Math.sin(B)*se,E.lineTo(Le,Z),B+=Be;else E.moveTo(Math.floor(g.x),Math.floor(g.y)),E.lineTo(Math.floor(g.wobbleX),Math.floor(C)),E.lineTo(Math.floor(D),Math.floor(Q)),E.lineTo(Math.floor(G),Math.floor(g.wobbleY));return E.closePath(),E.fill(),g.tick<g.totalTicks}function M(E,g,I,G,C){var D=g.slice(),Q=E.getContext("2d"),$,Y,oe=h(function(K){function re(){$=Y=null,Q.clearRect(0,0,G.width,G.height),d.clear(),C(),K()}function me(){a&&!(G.width===r.width&&G.height===r.height)&&(G.width=E.width=r.width,G.height=E.height=r.height),!G.width&&!G.height&&(I(E),G.width=E.width,G.height=E.height),Q.clearRect(0,0,G.width,G.height),D=D.filter(function(pe){return q(Q,pe)}),D.length?$=m.frame(me):re()}$=m.frame(me),Y=re});return{addFettis:function(K){return D=D.concat(K),oe},canvas:E,promise:oe,reset:function(){$&&m.cancel($),Y&&Y()}}}function J(E,g){var I=!E,G=!!b(g||{},"resize"),C=!1,D=b(g,"disableForReducedMotion",Boolean),Q=i&&!!b(g||{},"useWorker"),$=Q?v():null,Y=I?z:X,oe=E&&$?!!E.__confetti_initialized:!1,K=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,re;function me(B,se,Ee){for(var Le=b(B,"particleCount",w),Z=b(B,"angle",Number),_e=b(B,"spread",Number),Be=b(B,"startVelocity",Number),zs=b(B,"decay",Number),Vs=b(B,"gravity",Number),Ks=b(B,"drift",Number),fs=b(B,"colors",_),Hs=b(B,"ticks",Number),xs=b(B,"shapes"),Qs=b(B,"scalar"),Ws=!!b(B,"flat"),Rt=A(B),ft=Le,Ze=[],gs=E.width*Rt.x,ps=E.height*Rt.y;ft--;)Ze.push(R({x:gs,y:ps,angle:Z,spread:_e,startVelocity:Be,color:fs[ft%fs.length],shape:xs[N(0,xs.length)],ticks:Hs,decay:zs,gravity:Vs,drift:Ks,scalar:Qs,flat:Ws}));return re?re.addFettis(Ze):(re=M(E,Ze,Y,se,Ee),re.promise)}function pe(B){var se=D||b(B,"disableForReducedMotion",Boolean),Ee=b(B,"zIndex",Number);if(se&&K)return h(function(Be){Be()});I&&re?E=re.canvas:I&&!E&&(E=V(Ee),document.body.appendChild(E)),G&&!oe&&Y(E);var Le={width:E.width,height:E.height};$&&!oe&&$.init(E),oe=!0,$&&(E.__confetti_initialized=!0);function Z(){if($){var Be={getBoundingClientRect:function(){if(!I)return E.getBoundingClientRect()}};Y(Be),$.postMessage({resize:{width:Be.width,height:Be.height}});return}Le.width=Le.height=null}function _e(){re=null,G&&(C=!1,s.removeEventListener("resize",Z)),I&&E&&(document.body.contains(E)&&document.body.removeChild(E),E=null,oe=!1)}return G&&!C&&(C=!0,s.addEventListener("resize",Z,!1)),$?$.fire(B,Le,_e):me(B,Le,_e)}return pe.reset=function(){$&&$.reset(),re&&re.reset()},pe}var H;function ae(){return H||(H=J(null,{useWorker:!0,resize:!0})),H}function xe(E,g,I,G,C,D,Q){var $=new Path2D(E),Y=new Path2D;Y.addPath($,new DOMMatrix(g));var oe=new Path2D;return oe.addPath(Y,new DOMMatrix([Math.cos(Q)*C,Math.sin(Q)*C,-Math.sin(Q)*D,Math.cos(Q)*D,I,G])),oe}function ge(E){if(!l)throw new Error("path confetti are not supported in this browser");var g,I;typeof E=="string"?g=E:(g=E.path,I=E.matrix);var G=new Path2D(g),C=document.createElement("canvas"),D=C.getContext("2d");if(!I){for(var Q=1e3,$=Q,Y=Q,oe=0,K=0,re,me,pe=0;pe<Q;pe+=2)for(var B=0;B<Q;B+=2)D.isPointInPath(G,pe,B,"nonzero")&&($=Math.min($,pe),Y=Math.min(Y,B),oe=Math.max(oe,pe),K=Math.max(K,B));re=oe-$,me=K-Y;var se=10,Ee=Math.min(se/re,se/me);I=[Ee,0,0,Ee,-Math.round(re/2+$)*Ee,-Math.round(me/2+Y)*Ee]}return{type:"path",path:g,matrix:I}}function ce(E){var g,I=1,G="#000000",C='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof E=="string"?g=E:(g=E.text,I="scalar"in E?E.scalar:I,C="fontFamily"in E?E.fontFamily:C,G="color"in E?E.color:G);var D=10*I,Q=""+D+"px "+C,$=new OffscreenCanvas(D,D),Y=$.getContext("2d");Y.font=Q;var oe=Y.measureText(g),K=Math.ceil(oe.actualBoundingBoxRight+oe.actualBoundingBoxLeft),re=Math.ceil(oe.actualBoundingBoxAscent+oe.actualBoundingBoxDescent),me=2,pe=oe.actualBoundingBoxLeft+me,B=oe.actualBoundingBoxAscent+me;K+=me+me,re+=me+me,$=new OffscreenCanvas(K,re),Y=$.getContext("2d"),Y.font=Q,Y.fillStyle=G,Y.fillText(g,pe,B);var se=1/I;return{type:"bitmap",bitmap:$.transferToImageBitmap(),matrix:[se,0,0,se,-K*se/2,-re*se/2]}}n.exports=function(){return ae().apply(this,arguments)},n.exports.reset=function(){ae().reset()},n.exports.create=J,n.exports.shapeFromPath=ge,n.exports.shapeFromText=ce})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Sn,!1);const Bi=Sn.exports;Sn.exports.create;const Mi={particleCount:350,spread:120,origin:{y:.6},angle:90},Oi={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},qt=e=>{let s=Oi[e];s||(s={});const n={...Mi,...s};Bi(n)},Ri=()=>{const[e]=F.useTheme(),{mutate:s,isPending:n}=wn(),{mutateAsync:a,isPending:r}=xa(),i=()=>{a({settings:{theme:e}})},l=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{qt("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"})]})},ht=()=>{const e=ee(),s=le();return U.useQuery({queryKey:[O.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:O.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Gi=e=>{const s=ee(),n=le(),a=Ye();return U.useQuery({queryKey:[O.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:O.GET_WEBSITE_PAGES,data:{lang:e}})||[];return f.keyBy(f.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})};function tt(e,s,n=!1){const a=e.toString()?`?${e.toString()}`:"/";n?window.history.replaceState(null,"",a):window.history.pushState({},"",a),s(e),window.dispatchEvent(new PopStateEvent("popstate"))}const hs=je.atom(null),Ui=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}},at=e=>{if(!e)return e;const{base:s}=Ui(e);return s};function Fi(e,s){const n=(e||"").split("/").filter(Boolean);let a="",r=!0;if(s.slug==="/"){const i=n.pop()||"";if(Ne[i])r=!0;else{a=i;const l=n.pop()||"";r=!!Ne[l]}}else if(s.parent)n.length&&(a=n.pop()||"");else if(n.length){a=n.pop()||"";const i=n.pop()||"";r=!!Ne[i]}return{initSlug:a,prefix:r}}const qi=e=>e&&at(e),Fn=(e,s)=>{const n=at(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function Nn({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=v=>{const j=v.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),p=(j.match(/\./g)||[]).length,b=p<=1;p>1?d("Invalid slug. Only one dot (.) is allowed in the slug"):d(null),r&&r(b),u(j),s(j)};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:qi(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:ie.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} - ${Ne[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?Ne[s]||s:n.length?ie.CHOOSE_LANGUAGE:ie.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(o=>t.jsx("option",{value:o,children:Ne[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:ie.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?ie.ENTER_PAGE_NAME:ie.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),$i=({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:v})=>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:ie.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(Nn,{disabled:!a||!u,value:h,onChange:d,placeholder:a?l&&r?"Leave empty for home page":ie.ENTER_PAGE_SLUG:ie.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:o,onValidationChange:m,fullSlug:v()})]}),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:v})=>{const y=v||!s||!n||o.some(j=>(r?j.id!==i:!0)&&j.parent===(l==null?void 0:l.id)&&j.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:v?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?ie.UPDATING:ie.ADDING]}):r?ie.UPDATE:ie.ADD_NEW_LANGUAGE}),o.some(j=>(r?j.id!==i:!0)&&j.parent===(l==null?void 0:l.id)&&j.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:Ne[n]})," page in the parent to add here."]})})})},zi=({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:v,useLanguagePrefix:y,slug:j,isSlugValid:p,isPending:b})=>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:j,edit:s,id:h,primaryPageObject:o,pages:d,isNonSlugPageType:m,isHomePage:v,useLanguagePrefix:y,isSlugValid:p,isPending:b})]}),Vi=({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:v,setUseLanguagePrefix:y,isHomePage:j,parentSlug:p,slug:b,setSlug:w,isSlugValid:N,setIsSlugValid:P,getSlug:_,isPending:T,id:A,pages:z})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(S.Loader,{className:"animate-spin"})}):d?t.jsx(zi,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:h,id:A,pages:z,isNonSlugPageType:d,isHomePage:j,useLanguagePrefix:v,slug:b,isSlugValid:N,isPending:T}):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($i,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:d,isRootPage:m,lang:a,useLanguagePrefix:v,setUseLanguagePrefix:y,isHomePage:j,parentSlug:p,parentHasSelectedLanguagePage:h,slug:b,setSlug:w,isSlugValid:N,setIsSlugValid:P,getSlug:_})]}),t.jsx(Ia,{parentHasSelectedLanguagePage:h,name:i,lang:a,slug:b,edit:n,id:A,primaryPageObject:u,pages:z,isNonSlugPageType:d,isHomePage:j,useLanguagePrefix:v,isSlugValid:N,isPending:T})]}),Ki=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:l=[]}=ht(),o=x.useMemo(()=>l.find(K=>K.id===a),[l,a]),[u,h]=x.useState(""),[d,m]=x.useState(""),[v,y]=x.useState(""),[j,p]=x.useState(!0),[b,w]=x.useState(!0),{mutate:N,isPending:P}=Ta(),{mutate:_,isPending:T}=bn(),A=P||T,{data:z,isFetching:X}=Ve(),V=Ye(),{data:L,isFetching:R}=Ge(a),{data:q=[],isFetching:M}=Ge(o==null?void 0:o.parent),{data:J=[],isFetching:H}=Ce(),{setSelectedLang:ae}=F.useLanguages(),[,xe]=Pe(),[,ge]=F.useSidebarActivePanel(),ce=X||R||M||H,E=x.useMemo(()=>f.filter(z==null?void 0:z.languages,K=>!f.find(L,{lang:K})),[z,L]),g=x.useMemo(()=>J.find(K=>K.key===(o==null?void 0:o.pageType)),[J,o==null?void 0:o.pageType]),I=!(g!=null&&g.hasSlug),G=(o==null?void 0:o.slug)==="/";x.useEffect(()=>{if(!r&&o&&i&&(m(i),h(`${o.name} - ${Ne[i]}`)),!r||!o)return;const K=L==null?void 0:L.find(B=>B.id===e);if(!K)return;h(K.name),m(K.lang);const re=K.slug||"",{initSlug:me,prefix:pe}=Fi(re,o);y(me),w(pe)},[r,e,L,o,i]),x.useEffect(()=>{if(i)m(i);else if((E==null?void 0:E.length)===1&&!r){const K=E[0];if(!K||!Ne[K])return;m(K),(!u||u===(o==null?void 0:o.name))&&h(`${o==null?void 0:o.name} - ${Ne[K]}`)}},[i,E,r,u,o]);const{parentSlug:C,isRootPage:D}=x.useMemo(()=>{if(G||!d)return{parentSlug:void 0,isRootPage:!(o!=null&&o.parent)};if(!(o!=null&&o.parent))return{parentSlug:b?`/${d}`:void 0,isRootPage:!0};const K=q==null?void 0:q.find(re=>re.lang===d);return{parentSlug:K==null?void 0:K.slug,isRootPage:!1}},[o==null?void 0:o.parent,q,b,d,G]),Q=x.useMemo(()=>D?!0:!!(q!=null&&q.some(K=>(K==null?void 0:K.lang)===d)),[d,q,D]),$=()=>{let K="";return D?K=`/${b?[d,v].filter(Boolean).join("/"):v}`:K=`${at(C)}/${v}`,K.replace(/\/{2,}/g,"/").replace(/\/$/,"")},Y=K=>{const re=new URLSearchParams(window.location.search);V&&K===V?re.delete("lang"):re.set("lang",K),xe(re),window.dispatchEvent(new PopStateEvent("popstate"))},oe=K=>{K.preventDefault();const re={name:u,lang:d,primaryPage:o==null?void 0:o.id,slug:I?"":$(),pageType:o==null?void 0:o.pageType,...r&&{id:e}},me=()=>{!r&&d&&(ae(d),Y(d)),ge("outline"),n()};r?_(re,{onSuccess:me}):N(re,{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?ie.EDIT_LANGUAGE:ie.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:ie.ENTER_LANGUAGE_DETAILS})]}),t.jsx(Vi,{id:e,pages:l,loading:ce,onSubmit:oe,edit:r,lang:d,languages:E,name:u,setLang:m,setName:h,primaryPageObject:o,parentHasSelectedLanguagePage:Q,isNonSlugPageType:I,isRootPage:D,useLanguagePrefix:b,setUseLanguagePrefix:w,isHomePage:G,parentSlug:C,slug:v,setSlug:y,isSlugValid:j,setIsSlugValid:p,getSlug:$,isPending:A})]})})};function Hi({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 j=y.target.value;if(!j.startsWith(a)){const _=j.replace(a,""),T=a+_;h(T),s(_);return}const b=j.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),w=(b.match(/\./g)||[]).length,N=w<=1;w>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(N);const P=a+b;h(P),s(b)},m=()=>{if(o.current){const y=o.current;setTimeout(()=>{const j=a.length;y.setSelectionRange(j,j)},0)}},v=y=>{const j=y.currentTarget;(j.selectionStart||0)<=a.length&&setTimeout(()=>{const b=a.length;j.setSelectionRange(b,b)},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:v,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const As=({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 Qi({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage",currentPage:i}){const[l,o]=x.useState(!1),[u,h]=x.useState(""),d=F.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(N=>!f.isEmpty(N.slug)).filter(N=>N.slug!=="/").sort((N,P)=>N.slug.localeCompare(P.slug)),[e]),v=x.useMemo(()=>{if(!u.trim())return m;const w=u.toLowerCase();return m.filter(N=>N.name.toLowerCase().includes(w)||N.slug.toLowerCase().includes(w))},[m,u]),y=w=>Math.max(0,(w.match(/\//g)||[]).length-1),j=w=>"    ".repeat(w),p=w=>{if(w==="/")return"/";const N=w.split("/").filter(Boolean);if(N.length<=1){const P=N[0]||"";return`/${at(P)}`}return`/${at(N[N.length-1])}`},b=()=>{if(!s||s==="none")return"None";const w=m.find(N=>N.id===s);return w?`${w.name} (${p(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:[b(),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(As,{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")})]}),v.map(w=>{const N=j(y(w.slug)),P=p(w.slug),_=t.jsxs("span",{className:"flex items-center text-sm",children:[N,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:_}),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 N=y(w.slug),P=N>0?j(N):"",_=p(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," (",_,")"]},w.id)})]})]})}const Wi=(...e)=>e.filter(Boolean).join(" "),Ji=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=x.useState(""),[l,o]=x.useState(!1),[u,h]=x.useState(""),d=F.useChaiFeatureFlag("enable-add-page-dropdown");if(x.useEffect(()=>{if(s){const p=e.find(b=>b.id===s);i((p==null?void 0:p.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(p=>{const b=p.libraryName;m[b]||(m[b]=[]),m[b].push(p)});const v=Object.entries(m).reduce((p,[b,w])=>{const N=w.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())||b.toLowerCase().includes(u.toLowerCase()));return N.length>0&&(p[b]=N),p},{}),y=e.find(p=>p.id===s),j=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:[j,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:p=>h(p.target.value)})]})}),t.jsxs(As,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(v).map(([p,b])=>t.jsx(c.CommandGroup,{heading:p,children:b.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:Wi("mr-2 h-4 w-4",s===w.id?"opacity-100":"opacity-0")})]},w.id))},p))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:p=>n(p.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(m).map(([p,b])=>t.jsx("optgroup",{label:p,children:b.map(w=>t.jsx("option",{value:w.id,children:f.startCase(w.name)},w.id))},p))]}),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"})]})]})},Yi=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_LIBRARIES],queryFn:async()=>await s(e,{action:O.GET_LIBRARIES})||[]})},Xi=e=>{const s=le(),n=ee();return U.useQuery({queryKey:[O.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:O.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?f.filter(a,{pageType:e}):a)||[]}})},Zi=e=>{const{data:s=[],isLoading:n}=Xi(e),{data:a=[],isLoading:r}=Yi(),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}},Gs=()=>{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])},$t=(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}},it=(...e)=>e.filter(Boolean).join(" ");function el({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var gs,ps;const r=Gs(),i=!!(e!=null&&e.id),{data:l}=ht(),{mutate:o,isPending:u}=Ta(),{mutate:h,isPending:d}=bn(),[m,v]=x.useState(null),[y,j]=x.useState(!0),[p,b]=x.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:w}=F.usePermissions(),N=w(be.CHANGE_PAGE_TYPE),[P,_]=x.useState(!1),[T,A]=x.useState(""),{selectedLang:z,fallbackLang:X}=F.useLanguages(),V=z||X,[L,R]=x.useState(""),[q,M]=x.useState(!1),J=x.useMemo(()=>{const k=s.find(ue=>ue.key===p);return(k==null?void 0:k.hasSlug)===!1},[p,s]),[H,ae]=x.useState((e==null?void 0:e.parent)??""),[xe,ge]=x.useState((e==null?void 0:e.name)??""),[ce,E]=x.useState((e==null?void 0:e.dynamic)??!1),[g,I]=x.useState(ce?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[G,C]=x.useState((e==null?void 0:e.dynamicSlugCustom)??""),[D,Q]=x.useState(!0),[$,Y]=x.useState(!1),[oe,K]=x.useState(""),{data:re,isLoading:me}=Zi(p),pe=u||d,B=F.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]),Z=s.find(k=>k.key===p),_e=k=>{if(i&&p!==k){A(k),_(!0),R(""),M(!1);return}b(k),R(""),M(!1)},Be=()=>{b(T),_(!1),E(!1)},zs=k=>{E(k),k?I(""):C("")},Vs=k=>{if(ae(k),k&&k!=="none"){const ue=l==null?void 0:l.find(De=>De.id===k),Fe=(ue==null?void 0:ue.slug)||"";if(g.startsWith(Fe)){const De=g.slice(Fe.length).replace(/^\/+/,"");I(De)}else I(g.replace(/^\/+/,""))}else I(g?`${g}`:"")},Ks=k=>{K(k)},fs=()=>xe.trim()?ce&&!f.isEmpty(g)?(v("Slug must be empty when using dynamic slug"),!1):ce&&!D?(v("Dynamic slug is invalid"),!1):!0:(W.toast.error("Name is required"),!1),Hs=()=>{const k={pageType:Z==null?void 0:Z.key,name:xe,slug:"",hasSlug:!1};i?h({id:e==null?void 0:e.id,name:xe},{onSuccess:()=>{W.toast.success((Z==null?void 0:Z.name)+" updated successfully"),n()}}):o(k,{onSuccess:ue=>{n(),r(ue.page.id,a)}})},xs=(k,ue)=>{if(!k.trim()&&!ce)return v("Child page slug is required"),!1;const Fe=at(ue),De=Fn(Fe,k);return Object.keys(Ne).some(ys=>De===`/${ys}`||(De==null?void 0:De.startsWith(`/${ys}/`)))?(v("Slugs cannot start with a language code for primary page"),!1):!0},Qs=(k,ue)=>{const Fe=at(ue),De=Fn(Fe,k),Re={pageType:p,name:xe,slug:De.replace(/\/$/,""),parent:H,dynamic:ce,hasSlug:!0,template:oe||void 0,tracking:{},seo:{},jsonLD:{}};if(ce&&(Re.dynamicSlugCustom=G),i){const qe=f.pick(Re,["pageType","parent","name","slug","dynamic","dynamicSlugCustom"]);h({id:e==null?void 0:e.id,...qe},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}})}else{const qe=f.find(s,{key:p});qe!=null&&qe.trackingDefault&&(Re.tracking=qe.trackingDefault);const{seo:ys,jsonLD:Lr}=$t(qe,V);f.set(Re,"seo",ys),f.set(Re,"jsonLD",Lr),o(Re,{onSuccess:Br=>{n(),r(Br.page.id,a)}})}},Ws=()=>{const k={pageType:p,name:xe,slug:g===""?"/":`/${g.replace(/\/$/,"")}`,template:oe||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:p});ue!=null&&ue.trackingDefault&&(k.tracking=ue.trackingDefault);const{seo:Fe,jsonLD:De}=$t(ue,V);f.set(k,"seo",Fe),f.set(k,"jsonLD",De),o(k,{onSuccess:Re=>{var qe;(qe=Re==null?void 0:Re.page)!=null&&qe.id&&r(Re.page.id,a),n()}})}},Rt=k=>{if(k.preventDefault(),v(null),!!fs()){if(!(Z!=null&&Z.hasSlug)){Hs();return}if(H&&H!=="none"){const ue=l==null?void 0:l.find(De=>De.id===H),Fe=(ue==null?void 0:ue.slug)||"";if(!xs(g,Fe))return;Qs(g,Fe)}else Ws()}},{pagesType:ft,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 Z!=null&&Z.hasSlug?t.jsxs("form",{onSubmit:Rt,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"}),B?t.jsxs(c.Popover,{open:q,onOpenChange:M,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!N,className:it("w-full justify-between",i&&!N?"cursor-not-allowed text-gray-500":""),children:[(Z==null?void 0:Z.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=>R(k.target.value)})]})}),t.jsxs(As,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),i?J?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:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:ft.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:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsxs(t.Fragment,{children:[ft.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:ft.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:it("mr-2 h-4 w-4",p===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:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!N,onChange:k=>_e(k.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!N?"cursor-not-allowed text-gray-500":""}`,children:i?J?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:()=>_(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]})]}),!i&&(Z==null?void 0:Z.hasSlug)&&re.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(Ji,{templates:re,selectedTemplateId:oe,onSelectTemplate:Ks,isLoading:me})]}),t.jsx(Qi,{pages:l,selectedParentId:H,onChange:Vs,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:xe,onChange:k=>ge(k.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(Z==null?void 0:Z.dynamicSegments)&&H&&H!=="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=>zs(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(Hi,{value:G,onChange:C,dynamicPattern:(Z==null?void 0:Z.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:Q})})})]}),(!(Z!=null&&Z.dynamicSegments)||!ce)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Nn,{value:g,onChange:k=>{var ue;I(k),i&&k!==(((ue=e==null?void 0:e.slug)==null?void 0:ue.split("/").pop())||"")?Y(!!(Ee||Le)):Y(!1)},placeholder:H&&H!=="none"?"Enter page slug":p==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:H&&H!=="none"?(ps=l==null?void 0:l.find(k=>k.id===H))==null?void 0:ps.slug:void 0,onValidationChange:j}),m&&t.jsx("p",{className:"text-xs text-red-500",children:m}),$&&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:pe||!y&&(!(Z!=null&&Z.dynamicSegments)||!ce)||ce&&!D,type:"submit",className:"w-full",children:i?pe?"Updating...":"Update page":pe?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Rt,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"}),B?t.jsxs(c.Popover,{open:q,onOpenChange:M,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!N,className:it("w-full justify-between",i&&!N?"cursor-not-allowed text-gray-500":""),children:[(Z==null?void 0:Z.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=>R(k.target.value)})]})}),t.jsxs(As,{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),M(!1)},className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(S.Check,{className:it("mr-2 h-4 w-4",p===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!N,onChange:k=>_e(k.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!N?"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:()=>_(!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:(gs=s.find(k=>k.key===p))==null?void 0:gs.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:xe,onChange:k=>ge(k.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:pe,type:"submit",className:"w-full",children:i?pe?"Updating...":"Update "+(Z==null?void 0:Z.name):pe?"Creating...":"Create "+(Z==null?void 0:Z.name)})]})}const En=({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(el,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function Us({page:e,onClose:s}){const[,n]=Pe(),{mutate:a,isPending:r}=Pi(),{data:i}=Ce(),{setSelectedLang:l,fallbackLang:o}=F.useLanguages(),[,u]=F.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(Ne,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 tl=()=>{const e=le(),s=U.useQueryClient(),n=ee();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:[O.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"})}})},Cn=({page:e,onClose:s,closePanel:n=()=>{}})=>{const{mutate:a,isPending:r}=tl(),[i,l]=x.useState(null),[o,u]=x.useState(`${e.name} (Copy)`),h=Gs(),d=f.isEmpty(e.slug),[m,v]=x.useState(d?"":`${e.slug.split("/").pop()}-copy`),y=d?"":f.initial(e.slug.split("/")).join("/"),[j,p]=x.useState(!1),b=w=>{if(w.preventDefault(),!o.trim()){l("Name is required");return}if(!d&&!m.trim()){l("Slug is required");return}l(null),p(!0);const N={pageId:e.id,name:o};d||(N.slug=`${y}/${m}`),a(N,{onSuccess:P=>{p(!1),s(),h(P.id,n)},onError:P=>{p(!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:b,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(Nn,{value:m,onChange:w=>v(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||j,children:r||j?"Duplicating...":"Duplicate"})]})]})]})})},sl=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=_i(),{data:v}=Ce(),y=v==null?void 0:v.find(P=>P.key===e.pageType),j=(y==null?void 0:y.name)||f.startCase(e.pageType),p=x.useCallback(P=>{var T;const _=(T=P.target.files)==null?void 0:T[0];if(_){if(_.size>sl){W.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(_.size/1024).toFixed(2)}KB.`}),d.current&&(d.current.value="");return}try{h(!0);const A=new FileReader;A.onloadend=()=>{o(A.result),h(!1)},A.readAsDataURL(_)}catch(A){console.error("Error reading file:",A),h(!1),W.toast.error("Failed to process image",{description:A instanceof Error?A.message:"Unknown error"})}}},[]),b=()=>{o(""),d.current&&(d.current.value="")},w=()=>{var P;(P=d.current)==null||P.click()},N=()=>{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:j})]})]}),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:p,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:b,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:N,children:"Mark as template"})]})]})})},Tn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:o,isLanguagePage:u})=>{const{hasPermission:h}=F.usePermissions(),{data:d}=Ce(),m=x.useMemo(()=>f.find(d,{key:e.pageType}),[d,e.pageType]),v=x.useMemo(()=>!!e.isTemplate,[e.isTemplate]),y=x.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!h(be.EDIT_PAGE)&&!h(be.DELETE_PAGE)&&!h(be.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:o}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[h(be.ADD_PAGE)&&!u&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(S.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),h(be.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(S.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&h(be.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(S.Power,{className:"size-3"}),ie.UNPUBLISH]}),h(be.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(S.Trash,{className:"size-3"}),ie.DELETE]}),h(be.MARK_AS_TEMPLATE)&&y&&!u&&t.jsx(t.Fragment,{children:v?t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(S.SquareLibrary,{className:"size-3"}),ie.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(S.SquareLibrary,{className:"size-3"}),ie.MARK_AS_TEMPLATE]})})]})]})},kn=({page:e,onClose:s})=>{const[n,a]=x.useState(!1),r=Di(),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"})]})]})})},ms=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Ii(),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:[ie.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?ie.UPDATING:ie.UNPUBLISH})]})]})})},nl=da("expandedPagesState",[]),Pn=e=>f.flatMap(e,s=>[s,...s.children?Pn(s.children):[]]),al=(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=Pn(e),a=f.find(n,r=>r.id===s);if(a){if(a.parent)return[..._a(e,a.parent),s];const r=al(e,s);if(!f.isEmpty(r))return r}return[s]},rl=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)},Mt=e=>{const[s,n]=je.useAtom(nl),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=Pn(h),v=_a(m,d);if(!Array.isArray(v)||f.isEmpty(v))return;const y=v.slice(0,-1);f.isEmpty(y)||n(j=>f.uniq([...j,...y]))},[n]),l=x.useCallback(h=>{if(f.isEmpty(h))return;const d=rl(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 v=y=>[y.id,...y.children?f.flatMap(y.children,v):[]];return v(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)})),il=(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):[]}}),ll=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=il(e,d);r=f.uniqBy([...d,...m],"id")}const i=Da(ll(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,v)=>({...m,id:v,name:f.startCase(v),isPartialGroup:!0,children:l.filter(y=>y.pageType===v)})))}else h=u.sort((d,m)=>(d.name||"").localeCompare(m.name||""));return[...o,...h]},ol=({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:v})=>{const y=Gs(),{data:j}=Ce(),[,p]=F.useSidebarActivePanel(),b=x.useMemo(()=>f.find(j,{key:s.pageType}),[j,s.pageType]),w=x.useMemo(()=>{const T=f.get(s,"slug",""),A=e?at(e):"",z=A?T.replace(A,""):T;return z||"/"},[s,e]),N=x.useMemo(()=>!!s.isTemplate,[s.isTemplate]),P=x.useCallback(()=>{p("outline"),y(f.get(s,"id"),a)},[y,a,s,p]),_=x.useCallback(T=>{T.stopPropagation(),v()},[v]);return t.jsxs("div",{onClick:s.isPartialGroup?_: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:_,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"})}):b!=null&&b.icon?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:b.icon}}):b!=null&&b.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}),b!=null&&b.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,"/")?`${b==null?void 0:b.dynamicSlug}`:`/${b==null?void 0:b.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:b==null?void 0:b.name}),N&&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(mi,{currentEditor:s.currentEditor}),t.jsx(Tn,{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:T=>T.stopPropagation()})})})]})]})},cl=({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=C=>l?String(f.get(C,"name","")).toLowerCase().includes(l.toLowerCase())||String(f.get(C,"key","")).toLowerCase().includes(l.toLowerCase()):!0,[m,v]=x.useState(null),[y,j]=x.useState(null),[p,b]=x.useState(null),[w,N]=x.useState(null),{data:P,isFetching:_}=ht(),[T,A]=x.useState(""),{hasPermission:z}=F.usePermissions(),{updateForSelectedPage:X,expandPagesOnSearch:V,expandAll:L,collapseAll:R}=Mt(null),[q,M]=Pe(),J=q.get("page"),H=x.useRef(null),{data:ae}=Ce(),xe=F.useChaiFeatureFlag("enable-add-page-dropdown"),ge=x.useCallback(C=>{var D;return(D=f.find(ae,{key:C}))==null?void 0:D.hasSlug},[ae]);x.useEffect(()=>{if(!f.isEmpty(T))return;const C=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(ae)&&C&&(f.find(ae,{key:C})?A(C):A("all"))},[ae,T]);const ce=C=>{A(C),sessionStorage.setItem("pageTypeFilter",C),o("")},E=x.useCallback(C=>{const Q=new URLSearchParams(window.location.search).get("lang"),$=new URLSearchParams({page:C});Q&&$.set("lang",Q),tt($,M),e()},[M,e]);x.useEffect(()=>{if(J&&!_){const C=f.find(P,{id:J});if(C&&(C!=null&&C.pageType))s(D=>[...D,C==null?void 0:C.pageType]);else{const D=f.find(P,{slug:"/"});if(D){const Q=new URLSearchParams({page:D.id});tt(Q,M)}else tt(new URLSearchParams({}),M,!0)}}},[P,J,_,M]);const g=x.useMemo(()=>P?La(P,r,T,ge):[],[P,r,T,ge]);x.useEffect(()=>{J&&!_&&!f.isEmpty(g)&&(X(g,J),H.current&&H.current.scrollIntoView({behavior:"smooth",block:"end"}))},[J,_,g,X]),x.useEffect(()=>{!f.isEmpty(r)&&!f.isEmpty(g)&&V(g)},[r,g,V]);const I=x.useCallback(()=>{L(g)},[L,g]),G=x.useCallback(()=>{R()},[R]);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:C=>i(C.target.value)}),!f.isEmpty(T)&&t.jsxs(c.Select,{value:T,onValueChange:ce,children:[t.jsx(c.SelectTrigger,{className:`${T==="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:[xe&&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:C=>o(C.target.value),onKeyDown:C=>C.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!f.isEmpty(f.filter(ae,C=>C.hasSlug&&d(C)))&&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,C=>C.hasSlug&&d(C))].sort((C,D)=>f.get(C,"name","").localeCompare(f.get(D,"name",""))),C=>t.jsx(c.SelectItem,{value:f.get(C,"key"),children:f.get(C,"name")},f.get(C,"key")))]}),!f.isEmpty(f.filter(ae,C=>!C.hasSlug&&d(C)))&&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,C=>!C.hasSlug&&d(C))].sort((C,D)=>f.get(C,"name","").localeCompare(f.get(D,"name",""))),C=>t.jsx(c.SelectItem,{value:f.get(C,"key"),children:f.get(C,"name")},f.get(C,"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:I,className:"p-1 text-gray-500",children:t.jsx(S.ChevronsUpDown,{})}),t.jsx(c.Button,{variant:"outline",size:"icon",onClick:G,className:"p-1 text-gray-500",children:t.jsx(S.ChevronsDownUp,{})})]})]}),_?t.jsx("div",{className:"space-y-2",children:f.map([...Array(5).keys()],C=>t.jsx("div",{className:"h-9 w-full animate-pulse rounded bg-gray-200"},C))}):f.isEmpty(g)?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(g,C=>{const D=C.id===J;return t.jsx("div",{ref:D?H:null,children:t.jsx(Ba,{item:C,currentPage:J,close:e,setUnpublishPage:v,setDeletePage:h,setAddEditPage:j,setMarkAsTemplate:b,setUnmarkAsTemplate:N,setDuplicatePage:a,level:0})},`page-item-${C.id}`)})})]}),z(be.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex gap-x-2 text-sm",onClick:()=>{j({slug:"",name:"",pageType:T==="all"?"page":T})},children:[t.jsx(S.Plus,{className:"h-4 w-4"})," Add New"]}),y&&t.jsx(En,{closePanel:e,editPage:E,addEditPage:y,setAddEditPage:j}),u&&t.jsx(Us,{page:u,onClose:()=>h(null)}),m&&t.jsx(ms,{page:m,onClose:()=>v(null)}),p&&t.jsx(An,{page:p,onClose:()=>b(null)}),w&&t.jsx(kn,{page:w,onClose:()=>N(null)}),n&&t.jsx(Cn,{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:v,toggleExpanded:y}=Mt(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(ol,{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:v,onToggleExpand:y}),m&&v&&t.jsx("div",{className:"bg-white pl-6 pt-2",children:f.map(f.get(e,"children",[]),j=>t.jsx(Ba,{item:j,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:d+1},j.id||`child-${d}-${j.key}`))})]},e.id||`level-${d}-${e.key}`)},ul=({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"})]})]})},dl=({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"})]}),hl=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Mt(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=Ye();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"}`}),Ne[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:[O.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"})]})},ml=({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(ul,{selectedPageType:o,setSelectedPageType:u}),t.jsx(dl,{search:s,setSearch:n}),t.jsx(hl,{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:v=>{l(v),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 ut({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 fl=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Mt(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":""}`})})},xl=({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"})}),gl=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),pl=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i,showUntranslatedPages:l})=>{const[o]=wa(),u=Ye(),h=n===e.id,d=!!e.isTemplate,m=x.useMemo(()=>f.find(s,{key:e.pageType}),[s,e.pageType]),v=o==null?void 0:o[e.id],{data:y}=Ke(v),j=y?y==null?void 0:y.name:null;let p=f.get(r,e==null?void 0:e.id);p=f.get(p,"lang")===i?p:null;const b=i===u||!!p,w=(p==null?void 0:p.name)||(e==null?void 0:e.name)||"No name";let N=(p==null?void 0:p.slug)||(e==null?void 0:e.slug)||"";const P=N+(e!=null&&e.dynamic?`/${m==null?void 0:m.dynamicSlug}`:"")+(e!=null&&e.dynamicSlugCustom?`${e.dynamicSlugCustom}`:"");if(N.startsWith("/")&&!l){const T=N.split("/").pop();N=N.endsWith(T)&&e.dynamic?"":`/${T}`}const _=x.useMemo(()=>{const T="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]",A=`${h?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return b?`${T} ${A} ${j?"opacity-60":""}`:`${T} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[b,h,j]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&b&&a("select",e==null?void 0:e.id),className:_,children:[t.jsx(fl,{page:e}),!e.isPartialGroup&&t.jsx(gl,{isOnline:p?p.online:e.online}),t.jsx(xl,{page:e,pageType:m}),t.jsx(ut,{content:w,side:"top",showTooltip:w.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:w})}),(N||e.dynamic)&&t.jsx(ut,{content:P,side:"top",showTooltip:!0,children:t.jsxs("span",{className:"max-w-[40%] truncate font-mono text-xs text-muted-foreground",children:[N,e.dynamic&&(m==null?void 0:m.dynamicSlug)&&t.jsxs("span",{className:"text-xs text-gray-500",children:["/",m==null?void 0:m.dynamicSlug,e.dynamicSlugCustom]})]})}),d&&t.jsx(ut,{content:"Template",side:"top",children:t.jsx("span",{className:"text-blue-500",children:t.jsx(S.NotepadText,{size:16})})}),!e.isPartialGroup&&b&&!j?t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(Tn,{isLanguagePage:!!p,page:p||e,setDuplicatePage:T=>a("duplicate",T),setAddEditPage:T=>a("edit",p||T),setUnpublishPage:T=>a("unpublish",T),setDeletePage:T=>a("delete",p||T),setMarkAsTemplate:T=>a("markAsTemplate",T),setUnmarkAsTemplate:T=>a("unmarkAsTemplate",T),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:T=>T.stopPropagation()})})})}):j?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:j&&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:j})," is editing this page"]})}),t.jsx(t.Fragment,{children:!b&&!e.isPartialGroup&&!j&&t.jsxs("button",{onClick:T=>{T.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(Ne,i)," Page"]})]})})]})},Oa=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o})=>{const{expandedPages:u}=Mt();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(pl,{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))})},Ra=({close:e})=>{const{languages:s,setSelectedLang:n}=F.useLanguages(),{data:a}=Ce(),{data:r,isFetching:i}=ht(),[l,o]=Pe(),{updateForSelectedPage:u,expandPagesOnSearch:h}=Mt(null),d=Ye(),m=l.get("page"),[v,y]=x.useState(""),[j,p]=x.useState(null),[b,w]=x.useState(null),[N,P]=x.useState(null),[_,T]=x.useState(null),[A,z]=x.useState(""),[X,V]=x.useState(null),[L,R]=x.useState(null),[q,M]=x.useState(d),[J,H]=x.useState(!1),[,ae]=je.useAtom(hs),xe=J&&q!==d,{data:ge,isFetching:ce}=Gi(q),E=x.useCallback(C=>{var D;return(D=f.find(a,{key:C}))==null?void 0:D.hasSlug},[a]),g=x.useMemo(()=>r?xe?f.filter(r,C=>!(ge!=null&&ge[C.id])):La(r,v,A,E):[],[r,E,v,A,ge,xe]);x.useEffect(()=>{n(d)},[d,n]),x.useEffect(()=>{if(!f.isEmpty(A))return;const C=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(a)&&C&&(f.find(a,{key:C})?z(C):z("all"))},[a,A]),x.useEffect(()=>{if(m&&!i&&!f.find(r,{id:m})){const D=f.find(r,{slug:"/"});if(D){const Q=new URLSearchParams({page:D.id});tt(Q,o)}else tt(new URLSearchParams({}),o,!0)}},[r,m,i,o]),x.useEffect(()=>{m&&!i&&!f.isEmpty(g)&&u(g,m)},[m,i,g,u]),x.useEffect(()=>{!f.isEmpty(v)&&!f.isEmpty(g)&&h(g)},[v,g,h]);const I=x.useCallback(C=>{const D=new URLSearchParams({page:C});q!==d&&D.set("lang",q),tt(D,o),e()},[e,o,q,d]),G=(C,D)=>{var Q;if(D)switch(C){case"add":w(D);break;case"select":I(D);break;case"edit":q!==d?ae({edit:!0,id:D==null?void 0:D.id,primaryPage:D==null?void 0:D.primaryPage}):w(D);break;case"delete":p(D);break;case"unpublish":P(D);break;case"markAsTemplate":T(D);break;case"unmarkAsTemplate":R(D);break;case"duplicate":V(D);break;case"addLanguagePage":ae({edit:!1,primaryPage:((Q=D==null?void 0:D.page)==null?void 0:Q.id)||"",preselectedLang:(D==null?void 0:D.language)||q});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(ml,{pages:g,search:v,setSearch:y,languages:[d,...s],selectedLanguage:q,setSelectedLanguage:M,selectedPageType:A,setSelectedPageType:z,onAddPage:C=>G("add",C),showUntranslatedPages:xe,setShowUntranslatedPages:H}),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()],C=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},C))}):f.isEmpty(g)?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:g,pageTypes:a,currentPage:m||"",onClickAction:G,languagePages:ge,selectedLanguage:q,showUntranslatedPages:xe})})]}),b&&t.jsx(En,{closePanel:e,editPage:I,addEditPage:b,setAddEditPage:w}),j&&t.jsx(Us,{page:j,onClose:()=>p(null)}),N&&t.jsx(ms,{page:N,onClose:()=>P(null)}),_&&t.jsx(An,{page:_,onClose:()=>T(null)}),L&&t.jsx(kn,{page:L,onClose:()=>R(null)}),X&&t.jsx(Cn,{page:X,onClose:()=>V(null),closePanel:e})]})},yl=()=>{const e=Ue("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:x.createElement(e,{})}):null},jl=()=>{const[e,s]=Pe(),n=e.get("page"),{data:a,isFetching:r}=ke(),{data:i,isFetching:l}=ht(),[o,u]=x.useState(!1),[h,d]=x.useState(!0),{savePage:m}=F.useSavePage(),v=!!n&&!f.isEmpty(a),y=x.useMemo(()=>!i||l?!1:i.some(N=>N.slug==="/"),[i,l]);x.useEffect(()=>{if(!n&&!l&&i&&y){const N=i.find(P=>P.slug==="/");if(N){const P=new URLSearchParams({page:N.id});tt(P,s)}}!l&&i&&d(!1)},[n,l,i,y,s]);const j=!h&&!n&&!y,p=!h&&!r&&f.isEmpty(a)&&!y,b=o||j||p,w=F.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:()=>{m(),u(!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:b,onOpenChange:N=>!N&&v&&u(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`${w?"w-full !max-w-screen-md":"!min-w-[50vh] !max-w-[800px] p-0"} z-50 border-border ${v?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:`mb-3 ${w?"":"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:`${b?"h-[calc(100vh-80px)] overflow-y-auto":"h-[calc(100vh-70px)] overflow-y-auto"}`,children:w?t.jsx(cl,{close:()=>u(!1)}):b&&t.jsx(Ra,{close:()=>u(!1)})})]})})]})},In=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=F.useLanguages(),l=f.isEmpty(r)?n:r,[,o]=Pe(),{isLocked:u}=Je();x.useEffect(()=>{const b=new URLSearchParams(window.location.search),w=b.get("lang");w&&(a.includes(w)?i(w):(b.delete("lang"),o(b),i("")))},[a,o,i]);const[,h]=je.useAtom(hs),{data:d}=ke(),{data:m}=Ve(),{data:v}=Ge(),y=x.useMemo(()=>{const b=f.compact(f.map(f.get(m,"languages"),w=>{const N=f.find(v,{lang:w});return{key:w,value:f.get(Ne,w,w),isLangPageAdded:!!N}})).filter(Boolean);return[{key:n,value:f.get(Ne,n),isLangPageAdded:!0},...b]},[n,v,m]),j=b=>{if(document.querySelector('[data-panel-id="seo"]')){const N=new CustomEvent("seo-language-switch-check",{detail:{fromLang:l,toLang:b,switchHandler:()=>p(b)}});window.dispatchEvent(N);return}p(b)},p=b=>{i(b);const w=new URLSearchParams(window.location.search);b===n?w.delete("lang"):w.set("lang",b),tt(w,o)};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(Ne,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(Ne,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(b=>b.isLangPageAdded),b=>t.jsxs(c.DropdownMenuItem,{className:F.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",b.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>j(b.key),children:[t.jsx("div",{className:"text-slate-600",children:b.value}),b.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"]})]},b.value)),e&&!f.isEmpty(y.filter(b=>!b.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 vl(){const[e,s]=je.useAtom(hs);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(yl,{}),t.jsx(jl,{}),e&&t.jsx(Ki,{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 bl(e,s){const n=le(),a=ee();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:O.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 wl=({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:dt.formatDate(s.createdAt,"dd MMM yyyy, h:mm a")})]})]})},zn=({version:e})=>t.jsx(wl,{version:e});function Sl(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}
5
5
  `;o+=`+++ b/${n}
6
6
  `;const u=[];let h=0,d=0;for(;h<i.length||d<l.length;){const y=i[h]||"",j=l[d]||"";if(y===j)u.push(` ${y}`),h++,d++;else{let p=-1,b=-1;for(let w=h+1;w<i.length;w++)if(l[d]===i[w]){p=w;break}for(let w=d+1;w<l.length;w++)if(i[h]===l[w]){b=w;break}if(p!==-1&&(b===-1||p-h<=b-d)){for(let w=h;w<p;w++)u.push(`-${i[w]}`);h=p}else if(b!==-1){for(let w=d;w<b;w++)u.push(`+${l[w]}`);d=b}else y&&u.push(`-${y}`),j&&u.push(`+${j}`),h++,d++}}const m=i.length,v=l.length;return o+=`@@ -1,${m} +1,${v} @@
7
7
  `,o+=u.join(`
8
8
  `)+`
9
- `,o}function zt(e,s=!0,n=!1){if(f.isString(e)){const a=f.trim(e);if(f.startsWith(a,"{")||f.startsWith(a,"[")||s&&(a==="true"||a==="false"||a==="null"||/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(a)))try{const i=JSON.parse(a);return zt(i,s,n)}catch{if(n)throw new Error(`Invalid JSON string: ${a}`);return{}}return e}return f.isArray(e)?f.map(e,a=>zt(a,s,n)):f.isPlainObject(e)?f.mapValues(e,a=>zt(a,s,n)):e}const Sl=e=>{switch(e){case"blocks":return"Blocks";case"seo":return"SEO";case"tracking":return"Tracking";default:return e}},Nl=(e,s)=>{if(!e||!s)return[{key:"blocks",label:"Blocks"}];const n=Object.keys(e),a=Object.keys(s);return n.filter(l=>a.includes(l)).map(l=>({key:l,label:Sl(l)})).filter(l=>l.key.length>0)};function El({open:e,compare:s,onOpenChange:n}){const a=s[0],r=s[1],[i,l]=x.useState(null),[o,u]=x.useState("split"),[h,d]=x.useState(!1),[m,v]=x.useState("blocks"),{data:y,isLoading:j}=vl(a,r),{leftData:p,rightData:b,options:w}=x.useMemo(()=>{var R,q;const A=(R=y==null?void 0:y.version1)==null?void 0:R[m],z=(q=y==null?void 0:y.version2)==null?void 0:q[m],X=zt(A),V=zt(z),L=Nl(y==null?void 0:y.version1,y==null?void 0:y.version2);return{leftData:X,rightData:V,options:L}},[y,m]),N=x.useMemo(()=>!p||!b?"":wl(p,b),[p,b]),P=x.useMemo(()=>{if(!N)return[];try{return Js.parseDiff(N)}catch(A){return console.error("Failed to parse diff:",A),[]}},[N]),_=async(A,z)=>{try{await navigator.clipboard.writeText(JSON.stringify(A,null,2)),l(z),setTimeout(()=>l(null),2e3)}catch(X){console.error("Failed to copy:",X)}},T=A=>JSON.stringify(A,null,2);return t.jsx(c.Dialog,{open:e,onOpenChange:n,children:t.jsxs(c.DialogContent,{className:"flex h-[90vh] w-[95vw] max-w-[1900px] flex-col p-6",children:[t.jsx(c.DialogHeader,{className:"pb-4 pt-0",children:t.jsxs(c.DialogTitle,{className:"flex items-center justify-between gap-2 leading-none",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(S.FileJson,{className:"h-5 w-5"}),"Compare","",w.map(A=>t.jsx("div",{className:`cursor-pointer rounded-full border px-2.5 py-1 text-xs leading-none ${m===A.key?"border-blue-500 bg-blue-500 text-white":"border-gray-600 text-gray-600 hover:bg-gray-200"}`,onClick:()=>v(A.key),children:A.label},A.key))]}),t.jsx("div",{className:"flex w-1/3 items-center justify-end pr-8",children:t.jsxs("div",{className:"flex w-max items-center justify-end gap-2 rounded-md border px-1.5 py-1",children:[t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[t.jsx(c.Switch,{disabled:h,checked:h?!0:o==="split",onCheckedChange:A=>u(A?"split":"unified")}),t.jsx("label",{className:"text-sm",children:"Split View"})]}),t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[t.jsx(c.Switch,{checked:h,onCheckedChange:A=>d(A)}),t.jsx("label",{className:"text-sm",children:"Show Raw Data"})]})]})})]})}),j?t.jsx(Ea,{fullScreen:!1}):t.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:t.jsxs("div",{className:"relative min-h-0 flex-1",children:[t.jsxs("div",{className:"absolute -top-5 z-50 mt-0.5 flex w-full items-center justify-between gap-2",children:[t.jsx("div",{className:"flex w-1/2 items-center justify-center gap-2",children:t.jsx(Vn,{version:a})}),t.jsx("div",{className:"flex w-1/2 items-center justify-center gap-2",children:t.jsx(Vn,{version:r})})]}),h?t.jsxs("div",{className:"grid h-full grid-cols-2 gap-3 rounded-lg border",children:[t.jsxs("div",{className:"relative flex min-h-0 flex-col border-r",children:[t.jsx("div",{className:"absolute -top-4 right-4 z-50",children:t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:()=>_(p,"left"),children:[i==="left"?t.jsx(S.Check,{className:"text-green-500"}):t.jsx(S.Copy,{}),"Copy"]})}),t.jsx(c.ScrollArea,{className:"flex-1 rounded-lg bg-slate-50 p-3 dark:bg-slate-900",children:t.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs",children:T(p)})})]}),t.jsxs("div",{className:"relative flex min-h-0 flex-col",children:[t.jsx("div",{className:"absolute -top-4 right-4 z-50",children:t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:()=>_(b,"right"),children:[i==="right"?t.jsx(S.Check,{className:"text-green-500"}):t.jsx(S.Copy,{}),"Copy"]})}),t.jsx(c.ScrollArea,{className:"flex-1 rounded-lg bg-slate-50 p-3 dark:bg-slate-900",children:t.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs",children:T(b)})})]})]}):t.jsx(c.ScrollArea,{className:"h-full overflow-y-auto rounded-lg border bg-slate-50 text-xs dark:bg-slate-900",children:P.length===0?t.jsx("div",{className:"flex h-full items-center justify-center p-6",children:t.jsxs("div",{className:"text-center text-muted-foreground",children:[t.jsx(S.FileJson,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),t.jsx("p",{children:"No differences found or unable to parse diff"})]})}):t.jsx("div",{children:P.map((A,z)=>t.jsx("div",{className:"mb-4",children:t.jsx(Js.Diff,{viewType:o,diffType:A.type,hunks:A.hunks,className:"rounded-lg text-xs",children:X=>X.map((V,L)=>t.jsx(Js.Hunk,{hunk:V},L))})},z))})})]})})]})})}const Me=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=F.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n};function Cl(e){const s=le(),n=ee();return U.useQuery({queryKey:["revisions",e],queryFn:async()=>await n(s,{action:O.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Al=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>await s(e,{action:O.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},Tl=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:O.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},lt=({tag:e})=>e==="draft"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsxs("span",{className:"relative flex h-2 w-2",children:[t.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-amber-500"})]}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Draft"})]}):e==="live"?t.jsxs("span",{className:"flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:[t.jsxs("span",{className:"relative flex h-2 w-2",children:[t.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-green-500"})]}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Live"})]}):e==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(S.Rocket,{className:"h-3 w-3"}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Published"})]}):e==="unsaved"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(S.Save,{className:"h-3 w-3"}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Unsaved changes"})]}):t.jsx("span",{className:"rounded bg-purple-500/10 px-1.5 py-0.5 font-mono text-xs font-bold text-purple-600",children:e});function kl({compare:e,setCompare:s,isComparisonEnabled:n}){const{data:a}=ke(),{saveState:r}=F.useSavePage(),[i]=Rs();if(!a)return null;const l=!!e.find(h=>{var d;return(d=h==null?void 0:h.uid)==null?void 0:d.startsWith("draft:")}),o=e.length>=2&&!l,u=r==="UNSAVED";return t.jsxs("div",{className:"relative flex items-start gap-3 rounded-md border bg-primary/5 p-2 hover:bg-accent/50",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium leading-none",children:[t.jsx(lt,{tag:"draft"}),t.jsx("span",{className:"text-xs font-bold",children:"Currently editing"})]})}),t.jsx("div",{className:"flex items-center pl-2 text-[11px] text-muted-foreground",children:!f.isEmpty(i.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",dt.formatDistanceToNow(new Date(i.lastSaved),{addSuffix:!0})]})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:u?t.jsx(lt,{tag:"unsaved"}):null})]}),n&&t.jsx(Ga,{checked:l,disabled:o,onChange:()=>{s(l?e.filter(h=>h.uid!==`draft:${a==null?void 0:a.id}`):[...e,{uid:`draft:${a==null?void 0:a.id}`,label:"draft",item:{createdAt:Date.now()}}])}})]})}function Pl(){var M,J;const[e,s]=we.useState([]),[n,a]=we.useState(!1),[r,i]=we.useState(null),[l,o]=we.useState(!1),[u,h]=we.useState(!1),{data:d}=ke(),{data:m,isFetching:v,error:y,refetch:j}=Cl(d==null?void 0:d.id),{mutate:p,isPending:b}=Al(),{mutate:w,isPending:N}=Tl(),P=U.useQueryClient(),_=va(),T=F.useChaiFeatureFlag("enable-page-revisions-compare"),{selectedLang:A,fallbackLang:z}=F.useLanguages(),X=A||z;x.useEffect(()=>s([]),[d==null?void 0:d.id]);const V=H=>{r&&w({revisionId:r.uid,discardCurrent:H},{onSuccess:()=>{o(!1),i(null),P.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]})}})},L=H=>{i(H),o(!0)},R=H=>{i(H),h(!0)},q=()=>{r&&p(r.uid,{onSuccess:()=>{h(!1),i(null)}})};return x.useEffect(()=>{n&&j()},[n,j]),t.jsxs(t.Fragment,{children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:n,onOpenChange:a,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(S.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(c.SheetContent,{className:"flex h-[100vh] flex-col",children:[t.jsxs(c.SheetHeader,{children:[t.jsx(c.SheetTitle,{children:"Revision History"}),(d==null?void 0:d.createdAt)&&t.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Page created on ",dt.format(new Date(d.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),v?t.jsx(Il,{}):y?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 flex h-full min-h-0 flex-1 flex-col space-y-2",children:[T&&t.jsx(_l,{lang:X,compare:e,setCompare:s,pageId:d==null?void 0:d.id}),t.jsx(kl,{compare:e,setCompare:s,isComparisonEnabled:T}),(M=m==null?void 0:m.filter(H=>H.uid==="current"))==null?void 0:M.map((H,ae)=>t.jsx(Kn,{lang:X,pageId:d==null?void 0:d.id,revision:H,isLatest:!0,onRestore:()=>L(H),onDelete:()=>R(H),revisionNumber:ae,compare:e,setCompare:s,pageLiveFullSlug:_,isComparisonEnabled:T},H.uid)),t.jsx(c.ScrollArea,{className:"min-h-0 flex-1",children:t.jsx("div",{className:"space-y-2",children:(J=m==null?void 0:m.filter(H=>H.uid!=="current"))==null?void 0:J.map((H,ae)=>t.jsx(Kn,{lang:X,pageId:d==null?void 0:d.id,revision:H,isLatest:H.uid==="current",onRestore:()=>L(H),onDelete:()=>R(H),revisionNumber:ae+1,compare:e,setCompare:s,pageLiveFullSlug:_,isComparisonEnabled:T},H.uid))})})]})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Ll,{open:l,onOpenChange:o,revision:r,onRestore:V,isRestoring:N}),t.jsx(Bl,{open:u,onOpenChange:h,revision:r,onDelete:q,isDeleting:b})]})}function Il(){return t.jsx("div",{className:"mt-2 space-y-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(c.Skeleton,{className:"h-4 w-3/4"}),t.jsx(c.Skeleton,{className:"h-3 w-1/2"}),t.jsx(c.Skeleton,{className:"mt-1 h-5 w-20"})]}),t.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Kn({revision:e,isLatest:s,onRestore:n,onDelete:a,revisionNumber:r,compare:i,setCompare:l,pageId:o,pageLiveFullSlug:u,isComparisonEnabled:h,lang:d}){const{data:m}=Ke(e.currentEditor),v=(m==null?void 0:m.name)||"Unknown",y=!!i.find(p=>{var b;return s?(b=p==null?void 0:p.uid)==null?void 0:b.startsWith("live"):(p==null?void 0:p.uid)===e.uid}),j=i.length>=2&&!y;return t.jsxs("div",{className:"relative flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50",children:[t.jsxs("div",{className:"flex-1 space-y-3",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("p",{className:"flex items-center gap-1 text-xs leading-none",children:[h&&t.jsx(lt,{tag:s?"live":`#${r}`}),e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"text-xs font-bold",children:v}),!h&&s&&t.jsx(lt,{tag:"live"})]})}),t.jsxs("div",{className:"flex items-center gap-x-3",children:[t.jsx("div",{className:"flex items-center gap-2",children:e.type==="published"?t.jsx(lt,{tag:"published"}):t.jsx(lt,{tag:"draft"})}),t.jsx("div",{className:"flex items-center text-[10px] text-muted-foreground",children:t.jsx("span",{className:"leading-tight",children:dt.format(e.createdAt,"MMM d, h:mm a")})})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[e.type!=="draft"&&h&&t.jsx("a",{target:"_blank",href:s?u:`/revision/revision:${e.uid}:${r}?lang=${d}`,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-4 w-4 hover:text-blue-500",children:[t.jsx(S.Eye,{className:"h-3 w-3"}),t.jsx("span",{className:"sr-only",children:"View this version"})]})}),t.jsx(Me,{permissions:[be.RESTORE_REVISION,be.DELETE_REVISION],children:t.jsx(Dl,{revision:e,onRestore:n,onDelete:a})})]}),h&&t.jsx(Ga,{checked:y,disabled:j,onChange:()=>{l(y?i.filter(p=>s?p.uid!==`live:${o}`:p.uid!==e.uid):[...i,{uid:s?`live:${o}`:e.uid,label:s?"live":`#${r}`,item:e}].sort((p,b)=>new Date(p.item.createdAt).getTime()-new Date(b.item.createdAt).getTime()))}})]})}function _l({compare:e,setCompare:s,pageId:n}){const[a,r]=x.useState(!1),[i,l]=e;if(e.length===0)return null;const o=({tab:u})=>t.jsxs("span",{className:"flex items-center justify-between rounded border border-blue-100 p-1 font-medium",children:[t.jsx(lt,{tag:u.label}),t.jsx("button",{className:"z-0 flex h-4 w-4 items-center justify-center rounded-full text-gray-400 hover:text-red-500",style:{lineHeight:1},onClick:()=>s(e.filter(h=>h.uid!==u.uid)),"aria-label":"Remove selection 1",children:t.jsx(S.X,{className:"h-3 w-3"})})]});return t.jsxs("div",{className:"mb-2 flex w-full max-w-md flex-col gap-1 rounded border bg-accent/60 p-2 shadow-sm",children:[t.jsxs("div",{className:"flex items-center gap-x-2 text-xs",children:[t.jsx("span",{className:"font-medium leading-tight text-gray-600",children:"Compare"}),i&&t.jsx(o,{tab:i}),t.jsx("span",{className:"font-medium leading-tight text-gray-600",children:"with"}),l?t.jsx(o,{tab:l}):t.jsx("span",{className:"rounded border px-1 text-xs text-muted-foreground",children:"Choose another"})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 pb-0.5 pt-2",children:[t.jsx(c.Button,{size:"sm",className:"h-6 gap-1 rounded px-2 text-xs leading-none text-gray-500",variant:"outline",onClick:()=>s([]),children:t.jsx("span",{children:" Clear"})}),t.jsxs(c.Button,{size:"sm",className:"h-6 gap-1 rounded px-2 text-xs leading-none",variant:"default",onClick:()=>r(!0),disabled:e.length<2,children:[t.jsx(S.FileJson,{className:"h-2.5 w-2.5"}),t.jsx("span",{className:"pt-0.5",children:"Show JSON Diff"})]})]}),a&&(e==null?void 0:e.length)>1&&n&&t.jsx(El,{open:a,onOpenChange:r,compare:e})]})}function Ga({checked:e,disabled:s,onChange:n,label:a="Compare"}){return t.jsx("div",{className:"absolute bottom-2 right-2",children:t.jsxs("label",{className:`flex cursor-pointer items-center gap-x-1 text-[11px] ${s?"opacity-50":""}`,children:[t.jsx("input",{type:"checkbox",className:"h-3 w-3 cursor-pointer rounded focus:ring-0 focus:ring-offset-0",checked:e,disabled:s,onChange:n}),t.jsx("span",{className:"select-none leading-tight",children:a})]})})}function Dl({revision:e,onRestore:s,onDelete:n}){return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-5 w-5",children:[t.jsx(S.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Me,{permission:be.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer text-sm",children:[t.jsx(S.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Me,{permission:be.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(c.DropdownMenuSeparator,{}),t.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(S.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function Ll({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=Ke((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Restore Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," from"," ",dt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(S.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(S.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function Bl({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=Ke((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",dt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(S.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Ml=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_CHANGES],queryFn:async()=>s(e,{action:O.GET_CHANGES})})},Ol=({page:e,selectedPages:s,handleCheckboxChange:n,getPageType:a,hasSlug:r,currentOwnerId:i})=>{const{data:l}=Ke(i),o=l==null?void 0:l.name;return t.jsxs("tr",{className:"group relative border-b last:border-b-0 hover:bg-gray-50",children:[t.jsxs("td",{scope:"row",className:`flex items-center gap-x-1 whitespace-nowrap px-6 py-2 text-gray-900 dark:text-white ${o?"opacity-50":""}`,children:[o?t.jsx(S.Lock,{className:"h-4 w-4 fill-red-200 text-red-500"}):t.jsx("input",{checked:f.includes(s,e==null?void 0:e.id),onClick:u=>{u.stopPropagation(),n(e==null?void 0:e.id)},type:"checkbox",className:"cursor-pointer rounded focus:outline-none focus:ring-0"})," ",r(e.pageType)?t.jsx(S.File,{className:"h-4 w-4"}):t.jsx(S.GlobeIcon,{className:"h-4 w-4"}),t.jsx(ut,{content:e.name,side:"top",showTooltip:e.name.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-medium text-black",children:e.name})}),e.slug&&t.jsx(ut,{content:e.slug,side:"top",showTooltip:e.slug.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-mono text-xs text-muted-foreground",children:e.slug})})]}),t.jsx("td",{className:"px-2",children:a(e==null?void 0:e.pageType)}),t.jsx("td",{className:"px-4 text-right",children:f.first(e.changes)||""}),t.jsx(t.Fragment,{children:o&&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:o})," is editing this page"]})})]},e==null?void 0:e.id)};function Rl({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n]=wa(),[a,r]=x.useState([]),i=Ye(),[l,o]=x.useState(i),{data:u,isFetching:h}=Ml(),{data:d}=Ce(),m=x.useCallback(L=>{var R;return(R=f.find(d,{key:L}))==null?void 0:R.hasSlug},[d]),v=x.useMemo(()=>f.filter(d,L=>!m(L.key)).map(L=>L.key),[m,d]),j=f.uniq(f.map(u,"lang")).filter(Boolean),p=x.useMemo(()=>f.filter(u,L=>L.pageType==="theme"?!1:l===i?L.lang===l||L.lang==="":L.lang===l),[u,l,i]),b=x.useMemo(()=>f.filter(p,L=>!v.includes(L.pageType)),[p,v]),w=x.useMemo(()=>f.filter(p,L=>v.includes(L.pageType)),[p,v]),{mutate:N,isPending:P}=Sn();x.useEffect(()=>{const L=f.map(f.filter(p,{online:!0}),"id");r(L)},[p]),x.useEffect(()=>{const L=Object.keys(n);r(R=>f.filter(R,q=>!f.includes(L,q)))},[n]);const _=a.length===(p==null?void 0:p.length),T=L=>{r(R=>f.includes(R,L)?f.filter(R,q=>q!==L):f.concat(R,L))},A=()=>{r(_?[]:f.map(p,"id"))},z=()=>{N({ids:f.uniq(a)},{onSuccess:()=>{s(),qt("CENTER_CENTER"),o(i)}})},X=L=>{if(L==="theme")return"Theme";const R=f.find(d,{key:L});return R?R==null?void 0:R.name:L},V=x.useMemo(()=>{const L=[{label:"Updated",top:"pt-2"},...f.orderBy(f.filter(b,{online:!0}),"pageType"),...f.orderBy(f.filter(w,{online:!0}),"pageType")].filter(q=>q.pageType!=="theme"),R=[{label:"Offline",top:"pt-6"},...f.orderBy(f.filter(b,{online:!1}),"pageType"),...f.orderBy(f.filter(w,{online:!1}),"pageType")];return[...L,...R]},[b,w]);return t.jsx(c.Dialog,{open:e,onOpenChange:P?()=>{}:s,children:t.jsxs(c.DialogContent,{className:"flex max-h-[80%] max-w-4xl flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),j.length>0&&t.jsx("div",{className:"my-[2px] mt-0",children:t.jsx(Ma,{languages:[i,...j],selectedLanguage:l,setSelectedLanguage:o})}),t.jsx("div",{className:"no-scrollbar relative -mx-4 -mt-4 h-full max-h-full overflow-y-auto",children:h?t.jsxs("div",{className:"space-y-2 px-1",children:[t.jsx("div",{className:"mt-2 h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"})]}):t.jsxs("table",{className:"w-full text-left text-xs text-gray-500 dark:text-gray-400 rtl:text-right",children:[t.jsx("thead",{className:"sticky top-0 z-10 border-b bg-gray-50 text-gray-700 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"w-[1 50px] flex items-center gap-x-2 px-6 py-3",children:[t.jsx("input",{checked:_,onClick:L=>{L.stopPropagation(),A()},type:"checkbox",className:"mt-1 cursor-pointer rounded focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"w-[150px] px-2 py-3",children:"Type"}),t.jsx("th",{scope:"col",className:"w-[150px] px-4 py-3 text-right",children:"Status"})]})}),t.jsx("tbody",{children:f.map(V,L=>L.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:`relative px-6 py-2 text-xs font-medium text-gray-800 ${L.top}`,children:[t.jsx("div",{className:"absolute inset-0 left-6 flex items-center",children:t.jsx("div",{className:"order-gray-300 w-full"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"bg-gray-50 pr-2",children:L.label})})]})},"separator"):t.jsx(Ol,{page:L,selectedPages:a,handleCheckboxChange:T,getPageType:X,hasSlug:m,currentOwnerId:n[(L==null?void 0:L.primaryPage)||(L==null?void 0:L.id)]}))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10 flex items-center justify-center",children:[a.length>0&&t.jsxs("span",{className:"text-center text-sm text-muted-foreground",children:[a.length," Page",a.length!==1?"s":""," Selected"]}),t.jsx(c.Button,{disabled:P,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:P||h||f.isEmpty(a),onClick:z,children:P?"Publishing...":"Publish Selected"})]})]})})}const Gl=({isOpen:e,onClose:s,onContinue:n,isPending:a=!1,title:r="Translation Warning",description:i="Some blocks need translations before publishing. Do you want to continue anyway?"})=>{const l=()=>{s()},o=()=>{n()};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:r}),t.jsx(c.DialogDescription,{children:i})]}),t.jsxs(c.DialogFooter,{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:l,disabled:a,children:"Cancel"}),t.jsx(c.Button,{onClick:o,disabled:a,children:a?"Publishing...":"Continue Anyway"})]})]})})},Ul=()=>{const e=ee(),s=le();return U.useQuery({queryKey:[O.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:O.GET_WEBSITE_DATA,data:{draft:!0}})})};function Fl({onClose:e}){const{data:s,isFetching:n}=Ul(),{mutateAsync:a,isPending:r}=Yr(),i=Ue("settingComponent",null),l=f.debounce(async o=>(await a({data:o}),!0),300);return i?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:x.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}const ql=()=>{const{selectedLang:e,fallbackLang:s}=F.useLanguages(),n=Ue("getPreviewUrl",async m=>m),[a,r]=x.useState(""),{data:i}=ke(),{data:l}=Ge(),{data:o}=Ce(),u=x.useMemo(()=>{var m;return(m=l==null?void 0:l.find(v=>(v==null?void 0:v.lang)===e))==null?void 0:m.slug},[e,l]),h=x.useCallback(m=>{var v;return(v=f.find(o,{key:m}))==null?void 0:v.hasSlug},[o]),d=e===s?"":e;return x.useEffect(()=>{(async()=>{if(typeof n=="function"){const m=!h(i==null?void 0:i.pageType),v=await n(m?`${d!==""?d+"/":""}${i==null?void 0:i.id}`:u||"");r(v)}else r("")})()},[n,u,i==null?void 0:i.pageType,h,i==null?void 0:i.id,d]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(S.Eye,{className:"h-4 w-4"})," ",ie.PREVIEW]})})})},$l=()=>{const[e,s]=F.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(ut,{content:ie.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(S.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},zl=()=>{const[e,s]=x.useState(!1),{isLocked:n}=Je(),{savePageAsync:a,saveState:r}=F.useSavePage();x.useEffect(()=>{const h=d=>{r==="UNSAVED"&&(d.preventDefault(),d.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=x.useCallback(async()=>{e||(s(!0),await a(),s(!1))},[a,e]),{buttonIcon:l,buttonClass:o,tooltipContent:u}=x.useMemo(()=>{switch(r){case"UNSAVED":return{tooltipContent:ie.SAVEDRAFT,buttonIcon:t.jsx(S.Save,{className:"h-4 w-4"}),buttonClass:"gap-x-1"};case"SAVING":return{tooltipContent:ie.SAVING,buttonIcon:t.jsx(S.Loader,{className:"h-4 w-4 animate-spin text-sky-700"}),buttonClass:"gap-x-1"};case"SAVED":return{tooltipContent:ie.SAVED,buttonIcon:t.jsx(S.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 gap-x-1"}}},[r]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:o,children:[l," ",u]})},Vl=()=>{const{selectedLang:e}=F.useLanguages(),{data:s}=We(),{data:n}=Ge(),[a,r]=x.useState(!1),[i,l]=x.useState(!1),[o,u]=x.useState(null),{savePageAsync:h}=F.useSavePage(),[d,m]=x.useState(!1),{data:v}=ke(),{mutate:y,isPending:j}=Sn(),{needTranslations:p}=F.useSavePage(),b=p(),{buttonText:w,buttonClassName:N,isPublished:P}=x.useMemo(()=>{const V=v&&(v==null?void 0:v.online);return{buttonClassName:V?"hover:bg-green-600 bg-green-500":"",isPublished:V,buttonText:V?ie.PUBLISHED:ie.PUBLISH}},[v]),_=async()=>{if(b){m(!0);return}T()},T=()=>{const V=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];y({ids:f.compact(V)},{onSuccess:()=>qt("TOP_RIGHT")})},A=()=>{m(!1),T()},z=async()=>{m(!1),await h()},X=x.useMemo(()=>f.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:_,disabled:j||!(v!=null&&v.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${N}`,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${i?"-translate-y-10":""}`,children:P?t.jsx(S.Send,{className:"h-4 w-4"}):t.jsx(S.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:P?t.jsx(S.Rocket,{className:"h-4 w-4"}):t.jsx(S.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:w}),e?`(${f.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:j||!(v!=null&&v.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${N}`,children:t.jsx(S.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(c.DropdownMenuItem,{disabled:j,className:"cursor-pointer text-xs",onClick:()=>y({ids:X},{onSuccess:()=>qt("TOP_RIGHT")}),children:[ie.PUBLISH," with translation pages"]}),!P&&t.jsxs(c.DropdownMenuItem,{disabled:j,className:"cursor-pointer text-xs",onClick:()=>y({ids:[v==null?void 0:v.id]},{onSuccess:()=>qt("TOP_RIGHT")}),children:[ie.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[ie.OPEN," publish menu"]}),P&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[ie.UNPUBLISH," page ",e?`(${f.upperCase(e)})`:""]})]})]})]}),t.jsx(Rl,{showModal:a,onClose:()=>r(!1)}),o&&t.jsx(ms,{page:o,onClose:()=>u(null)}),t.jsx(Gl,{isOpen:d,onClose:z,onContinue:A,isPending:j})]})},Kl=()=>{const e=Ue("settingComponent",null),[s,n]=x.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(ut,{content:ie.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(S.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(Fl,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Hl(){const{isLocked:e}=Je(),[s]=Pe(),n=s.get("lang"),a=pa(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Pl,{}),t.jsx(Me,{permission:be.EDIT_THEME,children:t.jsx($l,{})}),t.jsx(Me,{permission:be.EDIT_SETTINGS,children:t.jsx(Kl,{})}),t.jsx(ql,{}),t.jsx(Me,{permission:be.SAVE_PAGE,children:t.jsx(zl,{})}),t.jsx(Me,{permission:be.PUBLISH_PAGE,children:t.jsx(Vl,{})})]})}const Ql=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(c.Input,{type:"text",autoFocus:!0,value:e?s:"",onChange:a=>n(a.target.value),placeholder:e?"Search pages...":"To search select default language",disabled:!e,onKeyDown:a=>a.stopPropagation()}),Wl=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=F.useLanguages(),o=(i==null?void 0:i.length)===0;return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",className:"w-max focus:outline-none focus:ring-0 border-[0px] rounded-md py-1 text-sm h-max border border-gray-200 hover:bg-gray-100 pl-4",children:[e?f.get(e,"name"):"Select Page",t.jsx(S.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"w-96 divide-y shadow-xl p-0 max-h-[75vh]",children:[t.jsx("div",{className:"p-1.5 bg-gray-50/30",children:t.jsx(Ql,{isDefaultLang:o,searchQuery:n,setSearchQuery:a})}),(r==null?void 0:r.length)===0?t.jsx("div",{className:"h-24 text-xs flex items-center justify-center",children:"No pages found"}):r==null?void 0:r.map(u=>t.jsx(c.DropdownMenuItem,{onClick:()=>s(u),disabled:o?l!==u.lang:i!==u.lang,className:`flex flex-col justify-start cursor-pointer overflow-x-auto whitespace-nowrap no-scrollbar ${u.id===(e==null?void 0:e.id)?"bg-blue-50":"hover:bg-gray-50"}`,children:t.jsx("div",{className:"w-full text-xs whitespace-nowrap px-2 py-[2px]",children:t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("span",{className:"font-medium",children:u.name}),t.jsx("span",{className:"font-mono font-medium text-gray-500 text-xs rounded-full px-2 py-[1px] border border-gray-300 truncate",children:u.slug})]})})},u.id))]})]})},Jl=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:l,onChangeLanguage:o}=ja(),u=x.useRef(void 0);return x.useEffect(()=>{u.current!==a&&e&&(o(),u.current=a)},[a,s]),t.jsx("div",{className:"relative",children:t.jsx(Wl,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:l,dynamicPages:n})})},Yl=()=>{const[e,s]=x.useState(null),[n,a]=x.useState(null),[r,i]=x.useState(null),[l,o]=x.useState(null),[u,h]=x.useState(null),[d,m]=x.useState(null),[v,y]=x.useState(!1),{data:j,isFetching:p}=We(),{selectedLang:b,fallbackLang:w}=F.useLanguages(),{data:N}=Ge(),P=N==null?void 0:N.find(V=>V.lang===b),{isLocked:_}=Je(),T=!(j!=null&&j.slug),[,A]=je.useAtom(hs),{savePage:z}=F.useSavePage();if(!j)return null;const X=V=>{b.length>0&&b!==w?A({edit:!0,id:V==null?void 0:V.id,primaryPage:V==null?void 0:V.primaryPage}):m(V)};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between px-[2px] rounded transition-colors duration-200",children:[t.jsx(c.Button,{className:"flex h-7 max-w-[200px] cursor-pointer items-center truncate rounded px-1 text-xs font-medium",variant:"ghost",onClick:()=>{z(),y(!0)},children:p?t.jsx(S.Loader,{className:"h-4 w-4 animate-spin text-slate-400"}):t.jsxs("span",{className:"flex w-full cursor-pointer items-end overflow-hidden text-ellipsis whitespace-nowrap rounded-sm text-xs font-medium",children:[T?t.jsx(S.Globe,{className:"mr-1 h-4 w-4"}):t.jsx(S.File,{className:"mr-1 h-4 w-4"}),f.get(P||j,"name")??""]})}),_?t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 cursor-not-allowed rounded opacity-50 hover:bg-transparent",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4"})}):t.jsx(kn,{page:j,setDuplicatePage:V=>h(V),setAddEditPage:V=>X(V),setUnpublishPage:V=>a(V),setDeletePage:V=>s(V),setMarkAsTemplate:V=>i(V),setUnmarkAsTemplate:V=>o(V),isLanguagePage:b.length>0&&b!==w,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 rounded",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4"})})})]}),d&&t.jsx(Cn,{closePanel:()=>m(null),editPage:()=>{},addEditPage:d,setAddEditPage:m}),e&&t.jsx(Us,{page:e,onClose:()=>s(null)}),n&&t.jsx(ms,{page:n,onClose:()=>a(null)}),r&&t.jsx(Tn,{page:r,onClose:()=>i(null)}),l&&t.jsx(Pn,{page:l,onClose:()=>o(null)}),u&&t.jsx(An,{page:u,onClose:()=>h(null),closePanel:()=>m(null)}),t.jsx(c.Sheet,{open:v,onOpenChange:y,children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:"z-50 w-full !max-w-screen-md border-border px-1",children:[t.jsxs(c.SheetHeader,{className:"mb-3",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2 px-4 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:"h-[calc(100vh-80px)] overflow-y-auto",children:t.jsx(Ra,{close:()=>y(!1)})})]})})]})},Xl=({hasDynamicPage:e})=>t.jsx(ds,{children:t.jsxs("div",{className:"flex min-w-[300px] max-w-[400px] flex-col items-center justify-center rounded-lg border bg-white p-4 shadow-lg",children:[t.jsx("h1",{className:"text-lg font-medium",children:e?"Select a page":"No pages found"}),t.jsx("p",{className:"pt-2 text-center text-sm font-light text-gray-600",children:e?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]})}),Zl=()=>{const{data:e}=We(),s=jn(),{data:n,isFetching:a}=ke(),r=f.get(n,"dynamic",!1),i=F.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:l,allLangPages:o}=ja(),u=o.length>0,h=e==null?void 0:e.slug,d=!h,m=va(),y=(d?`Partial: ${e==null?void 0:e.name} `:`${h}${s}`).replace(window.location.host,"");return t.jsxs("div",{className:"relative z-10 flex items-center gap-x-1",children:[t.jsx("div",{className:F.mergeClasses("flex h-8 w-auto max-w-[600px] items-center rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800",a&&"pointer-events-none cursor-not-allowed opacity-50"),children:t.jsx(Yl,{})}),t.jsxs("div",{className:F.mergeClasses("flex h-8 w-auto max-w-[600px] items-center rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800"+(d?" pr-2":""),a&&"pointer-events-none cursor-not-allowed opacity-50"),children:[t.jsx(_n,{}),t.jsxs("div",{className:"flex w-full items-center overflow-hidden",children:[t.jsx("div",{className:`w-full max-w-[200px] overflow-hidden overflow-ellipsis whitespace-nowrap pl-1 text-xs ${d?"italic text-gray-400":"font-mono text-gray-500"}`,children:y==="/"?t.jsxs("span",{className:"text-gray-900",children:["/",t.jsx("span",{className:"text-[11px] font-light italic text-gray-400",children:"(Homepage)"})]}):y}),!d&&t.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",children:t.jsx("div",{className:"ml-2 mr-px flex-shrink-0 rounded-sm p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(S.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})]}),r&&!a&&i&&t.jsxs("div",{className:"relative",children:[!l&&t.jsx(Xl,{hasDynamicPage:u}),t.jsx(Jl,{})]})]})},eo=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(jl,{}),t.jsx(Zl,{}),t.jsx(Hl,{})]}),to=()=>{const e=le(),{aiContext:s}=yn(),n=ee();return x.useCallback(async(a,r,i,l)=>n(e,{action:O.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},so=(e,s)=>s.map(n=>{if(f.has(e,n._type)){const a=ua.getDefaultBlockProps(n._type);return{...a,...f.pick(n,[...f.keys(a),"_type","_id","_name","_parent","_bindings"]),...f.pickBy(n,(r,i)=>f.endsWith(i,"_attrs")),...n}}return n}),no=e=>{const s=ua.useRegisteredChaiBlocks();return x.useMemo(()=>{if(!e||f.isEmpty(e))return{blocks:[]};const n=f.filter(e,a=>!f.includes(a==null?void 0:a._type,"@chai/"));return{blocks:so(s,n)}},[e,s])},Hn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=f.get(a,"html",""),i=f.get(a,"blocks",[]);return f.isArray(i)?i:F.getBlocksFromHTML(r)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(r=>({...r}))}catch(a){return console.error(a),[]}}},ao=()=>{const e=le(),s=ee();return U.useQuery({queryKey:["uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{F.registerChaiLibrary(r.id,{name:r.isSiteLibrary?r.name+" (Current Site) ":r.name,description:r.description,getBlocksList:i=>Hn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>Hn.getUILibraryBlock(i,s,e)})}),a}})},Ua=()=>{const e=Os(),s=ee(),{user:n}=Oe(),a=n==null?void 0:n.id;return U.useQuery({queryKey:["permissions",a],queryFn:()=>s(e,{action:O.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},ro=()=>{const e=le(),s=ee(),{setCurrentEditor:n}=Je(),[,a]=Rs();return{onSave:async({page:i,blocks:l,needTranslations:o})=>{try{const u=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l,needTranslations:o}});return u.code==="PAGE_LOCKED"?(n(u.editor),!0):(a(h=>({...h,lastSaved:new Date().toISOString()})),u)}catch(u){return console.error(u),new Error("Failed to save blocks")}}}},io=()=>{const{data:e}=ht(),s=le(),n=ee();return{getPartialBlocks:x.useCallback(async()=>{const a={};for(const r of e??[])f.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:f.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:x.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return f.filter(r.blocks,i=>f.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},Qn=Ss.z.object({email:Ss.z.string().email({message:"Please enter a valid email address"}),password:Ss.z.string().min(6,{message:"Password must be at least 6 characters"})}),lo=()=>{const{setUser:e,logout:s}=Oe(),n=Os(),[a,r]=x.useState(""),[i,l]=x.useState(""),[o,u]=x.useState({}),[h,d]=x.useState(!1),[m,v]=x.useState(""),y=U.useMutation({mutationFn:async b=>{v("");const w=await pn(n,{action:"LOGIN",data:b});if(!w.ok){const P=await w.json();throw new Error(P.error||"Login failed")}const N=await w.json();if(f.has(N,"id")&&f.has(N,"email")&&f.has(N,"accessToken")&&f.has(N,"refreshToken"))e(N);else throw s(),new Error("Something went wrong. Please try again.");return N},onSuccess:()=>{u({}),v("")},onError:b=>{u({email:" ",password:" "}),v(b.message?"Invalid email or password":"Something went wrong")}}),j=async b=>{b.preventDefault(),u({});const w={email:a,password:i};try{const N=Qn.parse(w);y.mutate(N)}catch(N){if(N instanceof Ss.z.ZodError){const P=N.issues.reduce((_,T)=>{const A=T.path[0];return _[A]=T.message,_},{});u(P)}}},p=Qn.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-50",children:t.jsxs(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:b=>r(b.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:h?"text":"password",value:i,onChange:b=>l(b.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>d(!h),children:h?t.jsx(S.EyeOff,{className:"h-4 w-4"}):t.jsx(S.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:m})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!p||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(S.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center gap-2 border-t px-10 pt-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"flex items-center gap-1 text-primary hover:underline",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"h-4 w-4 rounded font-bold uppercase"}),"Chai Builder"]})]})]})]})})};let rn=lo;const oo=()=>x.useMemo(()=>rn,[rn]),co=e=>{rn=e},uo=()=>{const e=oo();return t.jsx(x.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},ho=({page:e,onClose:s})=>{const[n,a]=x.useState(e.slug||""),{mutate:r,isPending:i}=Di(),{data:l}=Ce(),o=f.find(l,{key:e==null?void 0:e.pageType}),u=d=>{if(d.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Ne).some(y=>n===`/${y}`||f.startsWith(n,`/${y}/`))){W.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},h=(e==null?void 0:e.lang)||"";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:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(S.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",h]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:d=>{const m=d.target.value;f.startsWith(m,`/${h}`)&&a(m)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!f.startsWith(n,`/${h}`)||f.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},mo=()=>{const[,e]=je.useAtom(hs),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=F.useLanguages(),{data:r,isFetching:i}=Ge(),{data:l}=ke(),{data:o}=Ce(),u=x.useMemo(()=>{const w=o==null?void 0:o.find(N=>N.key===(l==null?void 0:l.pageType));return l!=null&&l.dynamic?w==null?void 0:w.dynamicSlug:""},[o,l==null?void 0:l.pageType,l==null?void 0:l.dynamic]),[h,d]=x.useState(null),[m,v]=x.useState(null),[y,j]=x.useState(null),{data:p}=Ve(),b=f.filter(f.get(p,"languages")||["en"],w=>!f.find(r,{lang:w})&&w!==f.get(p,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:i?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"})]}):f.map(r,w=>{const N=w.lang,P=w.slug,_=!w.primaryPage,T=N===s;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`flex w-full cursor-pointer items-center justify-between rounded p-2 text-slate-500 ${T?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(N),children:[t.jsxs("div",{className:"flex-1 gap-x-3",children:[t.jsxs("div",{className:"flex items-center gap-x-2 text-[13px] text-slate-800",children:[t.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${w.online?"bg-green-300":"bg-gray-300"}`}),f.get(Ne,_?n:N,N)]}),t.jsxs("div",{children:[P&&t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Slug: ",t.jsx("b",{className:"font-mono font-medium",children:u?`${P}/${u}`:P})]}),t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",w.name," "]})]})]})]}),_?t.jsxs("div",{className:"flex items-center gap-x-1 text-[11px] text-orange-500",children:[t.jsx(S.StarIcon,{fill:"orange",className:"h-3 w-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(Me,{permissions:[be.EDIT_PAGE,be.DELETE_PAGE,be.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:A=>A.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"z-[9999] text-sm",children:[t.jsx(Me,{permissions:[be.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:A=>{A.stopPropagation(),e({edit:!0,id:w.id,primaryPage:w.primaryPage})},children:[t.jsx(S.PencilIcon,{className:"size-3"}),ie.EDIT]})}),t.jsx(Me,{permissions:[be.UNPUBLISH_PAGE],children:(w==null?void 0:w.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:A=>{A.stopPropagation(),v(w)},children:[t.jsx(S.Power,{className:"size-3"}),ie.UNPUBLISH]})}),t.jsx(Me,{permissions:[be.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:A=>{A.stopPropagation(),d(w)},children:[t.jsx(S.TrashIcon,{className:"size-3"}),ie.DELETE]})})]})]})})})]},w.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Me,{permissions:[be.ADD_PAGE],children:t.jsx("div",{className:"flex w-full justify-center",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:f.isEmpty(b),onClick:()=>{e({primaryPage:l==null?void 0:l.id,edit:!1})},children:ie.ADD_NEW_LANGUAGE})})}),h&&t.jsx(Us,{page:h,onClose:()=>d(null)}),m&&t.jsx(ms,{page:m,onClose:()=>v(null)}),y&&t.jsx(ho,{page:y,onClose:()=>j(null)})]})},fo=({isActive:e,show:s})=>{const{data:n}=Ve();return!f.has(n,"languages")||!f.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(S.LanguagesIcon,{className:"w-4 h-4"})})},Fa="lang",xo={id:Fa,label:"Languages",position:"top",panel:mo,button:fo,view:"modal",width:400};function He({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=we.useState(!1),[l,o]=we.useState([]),[u,h]=we.useState(e);we.useEffect(()=>{r||o([]),h(e)},[e,r]);const d=j=>Array.isArray(j)?"array":typeof j=="object"&&j!==null?"object":"value",m=we.useCallback(j=>{const p=b=>n==="value"?b==="value"||b==="object":n==="array"?b==="array":b===n;j.type==="object"?(o(b=>[...b,j.key]),h(j.value)):p(j.type)&&(s([...l,j.key].join(".")),i(!1))},[l,s,n]),v=we.useCallback(()=>{if(l.length>0){const j=l.slice(0,-1);o(j),h(j.reduce((p,b)=>p[b],e))}},[l,e]),y=we.useMemo(()=>Object.entries(u).map(([j,p])=>({key:j,value:p,type:d(p)})).filter(j=>n==="value"?j.type==="value"||j.type==="object":n==="array"?j.type==="array"||j.type==="object":n==="object"?j.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(S.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:j=>{try{j.preventDefault();const p=j.currentTarget;p.scrollTop+=j.deltaY}catch{j.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:v,className:"flex items-center text-sm",children:[t.jsx(S.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(j=>t.jsxs(c.CommandItem,{onSelect:()=>m(j),className:"flex items-center justify-between",children:[t.jsx("span",{children:j.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&j.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:p=>{p.stopPropagation(),s([...l,j.key].join(".")),i(!1)},children:"Select"}),(j.type==="object"||j.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(S.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},j.key))]})]})]})})]})}const go=()=>{const{selectedLang:e}=F.useLanguages(),{data:s,isFetching:n}=Ge();return{data:x.useMemo(()=>f.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},po=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg, [data-block-type='PartialBlock']").forEach(o=>o.remove()),a.querySelectorAll("*").forEach(o=>{Array.from(o.attributes).forEach(u=>o.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(o=>`<${o.tagName.toLowerCase()}>${o.innerHTML}</${o.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},xt=({keyword:e,onComplete:s,field:n})=>{const a=ee(),r=le(),{selectedLang:i,fallbackLang:l}=F.useLanguages(),o=F.useBuilderProp("aiContext",""),{mutate:u,isPending:h}=U.useMutation({mutationFn:async()=>{const d=po();return await a(r,{action:O.GENERATE_SEO_FIELD,data:{pageContext:o,dynamic:!1,field:n,lang:i||l,pageContent:d,keyword:e}})},onSuccess:d=>{s({fieldValue:d.field})},onError:d=>{s({fieldValue:null,error:d.message})}});return t.jsx(c.Button,{disabled:h,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:h?t.jsx(S.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(S.Sparkles,{className:"text-yellow-500"})})},yo=({isOpen:e,onClose:s,onSave:n,onDiscard:a,isSaving:r=!1,fromLanguage:i,toLanguage:l})=>{const o=Ne[i]||i,u=Ne[l]||l;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:"Unsaved SEO Changes"}),t.jsxs(c.DialogDescription,{children:['You have unsaved changes in the SEO for "',o,'" version. Do you want to save these changes before switching to "',u,'" version?']})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx(c.Button,{variant:"outline",onClick:a,disabled:r,children:"Discard Changes"}),t.jsx(c.Button,{onClick:n,disabled:r,children:r?"Saving...":"Save & Switch"})]})]})})},jo=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wn=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,o=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:o,position:l}),a=a.replace(i,o)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,o=l.message.match(/position (\d+)/),u=o?parseInt(o[1]):void 0;let h,d;if(u!==void 0){const m=a.substring(0,u).split(`
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}}}},vo=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,o=new RegExp(jo(l),"g");a=a.replace(o,r)}),a},bo=(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,v]=x.useState(null),[y,j]=x.useState(""),p=x.useRef(null);x.useEffect(()=>{e.trim()===""&&s("{}")},[e,s]);const b=_=>{if(a)return;const T=_.target.value;s(T)},w=_=>{if(_.key==="Tab"){_.preventDefault();const T=_.currentTarget,A=T.selectionStart,z=T.selectionEnd;if(A!==z){const V=e.substring(A,z).split(`
9
+ `,o}function zt(e,s=!0,n=!1){if(f.isString(e)){const a=f.trim(e);if(f.startsWith(a,"{")||f.startsWith(a,"[")||s&&(a==="true"||a==="false"||a==="null"||/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(a)))try{const i=JSON.parse(a);return zt(i,s,n)}catch{if(n)throw new Error(`Invalid JSON string: ${a}`);return{}}return e}return f.isArray(e)?f.map(e,a=>zt(a,s,n)):f.isPlainObject(e)?f.mapValues(e,a=>zt(a,s,n)):e}const Nl=e=>{switch(e){case"blocks":return"Blocks";case"seo":return"SEO";case"tracking":return"Tracking";default:return e}},El=(e,s)=>{if(!e||!s)return[{key:"blocks",label:"Blocks"}];const n=Object.keys(e),a=Object.keys(s);return n.filter(l=>a.includes(l)).map(l=>({key:l,label:Nl(l)})).filter(l=>l.key.length>0)};function Cl({open:e,compare:s,onOpenChange:n}){const a=s[0],r=s[1],[i,l]=x.useState(null),[o,u]=x.useState("split"),[h,d]=x.useState(!1),[m,v]=x.useState("blocks"),{data:y,isLoading:j}=bl(a,r),{leftData:p,rightData:b,options:w}=x.useMemo(()=>{var R,q;const A=(R=y==null?void 0:y.version1)==null?void 0:R[m],z=(q=y==null?void 0:y.version2)==null?void 0:q[m],X=zt(A),V=zt(z),L=El(y==null?void 0:y.version1,y==null?void 0:y.version2);return{leftData:X,rightData:V,options:L}},[y,m]),N=x.useMemo(()=>!p||!b?"":Sl(p,b),[p,b]),P=x.useMemo(()=>{if(!N)return[];try{return Js.parseDiff(N)}catch(A){return console.error("Failed to parse diff:",A),[]}},[N]),_=async(A,z)=>{try{await navigator.clipboard.writeText(JSON.stringify(A,null,2)),l(z),setTimeout(()=>l(null),2e3)}catch(X){console.error("Failed to copy:",X)}},T=A=>JSON.stringify(A,null,2);return t.jsx(c.Dialog,{open:e,onOpenChange:n,children:t.jsxs(c.DialogContent,{className:"flex h-[90vh] w-[95vw] max-w-[1900px] flex-col p-6",children:[t.jsx(c.DialogHeader,{className:"pb-4 pt-0",children:t.jsxs(c.DialogTitle,{className:"flex items-center justify-between gap-2 leading-none",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(S.FileJson,{className:"h-5 w-5"}),"Compare","",w.map(A=>t.jsx("div",{className:`cursor-pointer rounded-full border px-2.5 py-1 text-xs leading-none ${m===A.key?"border-blue-500 bg-blue-500 text-white":"border-gray-600 text-gray-600 hover:bg-gray-200"}`,onClick:()=>v(A.key),children:A.label},A.key))]}),t.jsx("div",{className:"flex w-1/3 items-center justify-end pr-8",children:t.jsxs("div",{className:"flex w-max items-center justify-end gap-2 rounded-md border px-1.5 py-1",children:[t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[t.jsx(c.Switch,{disabled:h,checked:h?!0:o==="split",onCheckedChange:A=>u(A?"split":"unified")}),t.jsx("label",{className:"text-sm",children:"Split View"})]}),t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[t.jsx(c.Switch,{checked:h,onCheckedChange:A=>d(A)}),t.jsx("label",{className:"text-sm",children:"Show Raw Data"})]})]})})]})}),j?t.jsx(Ea,{fullScreen:!1}):t.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:t.jsxs("div",{className:"relative min-h-0 flex-1",children:[t.jsxs("div",{className:"absolute -top-5 z-50 mt-0.5 flex w-full items-center justify-between gap-2",children:[t.jsx("div",{className:"flex w-1/2 items-center justify-center gap-2",children:t.jsx(zn,{version:a})}),t.jsx("div",{className:"flex w-1/2 items-center justify-center gap-2",children:t.jsx(zn,{version:r})})]}),h?t.jsxs("div",{className:"grid h-full grid-cols-2 gap-3 rounded-lg border",children:[t.jsxs("div",{className:"relative flex min-h-0 flex-col border-r",children:[t.jsx("div",{className:"absolute -top-4 right-4 z-50",children:t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:()=>_(p,"left"),children:[i==="left"?t.jsx(S.Check,{className:"text-green-500"}):t.jsx(S.Copy,{}),"Copy"]})}),t.jsx(c.ScrollArea,{className:"flex-1 rounded-lg bg-slate-50 p-3 dark:bg-slate-900",children:t.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs",children:T(p)})})]}),t.jsxs("div",{className:"relative flex min-h-0 flex-col",children:[t.jsx("div",{className:"absolute -top-4 right-4 z-50",children:t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:()=>_(b,"right"),children:[i==="right"?t.jsx(S.Check,{className:"text-green-500"}):t.jsx(S.Copy,{}),"Copy"]})}),t.jsx(c.ScrollArea,{className:"flex-1 rounded-lg bg-slate-50 p-3 dark:bg-slate-900",children:t.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs",children:T(b)})})]})]}):t.jsx(c.ScrollArea,{className:"h-full overflow-y-auto rounded-lg border bg-slate-50 text-xs dark:bg-slate-900",children:P.length===0?t.jsx("div",{className:"flex h-full items-center justify-center p-6",children:t.jsxs("div",{className:"text-center text-muted-foreground",children:[t.jsx(S.FileJson,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),t.jsx("p",{children:"No differences found or unable to parse diff"})]})}):t.jsx("div",{children:P.map((A,z)=>t.jsx("div",{className:"mb-4",children:t.jsx(Js.Diff,{viewType:o,diffType:A.type,hunks:A.hunks,className:"rounded-lg text-xs",children:X=>X.map((V,L)=>t.jsx(Js.Hunk,{hunk:V},L))})},z))})})]})})]})})}const Me=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=F.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n};function Al(e){const s=le(),n=ee();return U.useQuery({queryKey:["revisions",e],queryFn:async()=>await n(s,{action:O.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Tl=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async a=>await s(e,{action:O.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},kl=()=>{const e=le(),s=ee(),n=U.useQueryClient();return U.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:O.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},lt=({tag:e})=>e==="draft"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsxs("span",{className:"relative flex h-2 w-2",children:[t.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-amber-500"})]}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Draft"})]}):e==="live"?t.jsxs("span",{className:"flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:[t.jsxs("span",{className:"relative flex h-2 w-2",children:[t.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-green-500"})]}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Live"})]}):e==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(S.Rocket,{className:"h-3 w-3"}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Published"})]}):e==="unsaved"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(S.Save,{className:"h-3 w-3"}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Unsaved changes"})]}):t.jsx("span",{className:"rounded bg-purple-500/10 px-1.5 py-0.5 font-mono text-xs font-bold text-purple-600",children:e});function Pl({compare:e,setCompare:s,isComparisonEnabled:n}){const{data:a}=ke(),{saveState:r}=F.useSavePage(),[i]=Rs();if(!a)return null;const l=!!e.find(h=>{var d;return(d=h==null?void 0:h.uid)==null?void 0:d.startsWith("draft:")}),o=e.length>=2&&!l,u=r==="UNSAVED";return t.jsxs("div",{className:"relative flex items-start gap-3 rounded-md border bg-primary/5 p-2 hover:bg-accent/50",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium leading-none",children:[t.jsx(lt,{tag:"draft"}),t.jsx("span",{className:"text-xs font-bold",children:"Currently editing"})]})}),t.jsx("div",{className:"flex items-center pl-2 text-[11px] text-muted-foreground",children:!f.isEmpty(i.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",dt.formatDistanceToNow(new Date(i.lastSaved),{addSuffix:!0})]})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:u?t.jsx(lt,{tag:"unsaved"}):null})]}),n&&t.jsx(Ga,{checked:l,disabled:o,onChange:()=>{s(l?e.filter(h=>h.uid!==`draft:${a==null?void 0:a.id}`):[...e,{uid:`draft:${a==null?void 0:a.id}`,label:"draft",item:{createdAt:Date.now()}}])}})]})}function Il(){var M,J;const[e,s]=we.useState([]),[n,a]=we.useState(!1),[r,i]=we.useState(null),[l,o]=we.useState(!1),[u,h]=we.useState(!1),{data:d}=ke(),{data:m,isFetching:v,error:y,refetch:j}=Al(d==null?void 0:d.id),{mutate:p,isPending:b}=Tl(),{mutate:w,isPending:N}=kl(),P=U.useQueryClient(),_=va(),T=F.useChaiFeatureFlag("enable-page-revisions-compare"),{selectedLang:A,fallbackLang:z}=F.useLanguages(),X=A||z;x.useEffect(()=>s([]),[d==null?void 0:d.id]);const V=H=>{r&&w({revisionId:r.uid,discardCurrent:H},{onSuccess:()=>{o(!1),i(null),P.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]})}})},L=H=>{i(H),o(!0)},R=H=>{i(H),h(!0)},q=()=>{r&&p(r.uid,{onSuccess:()=>{h(!1),i(null)}})};return x.useEffect(()=>{n&&j()},[n,j]),t.jsxs(t.Fragment,{children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:n,onOpenChange:a,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(S.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(c.SheetContent,{className:"flex h-[100vh] flex-col",children:[t.jsxs(c.SheetHeader,{children:[t.jsx(c.SheetTitle,{children:"Revision History"}),(d==null?void 0:d.createdAt)&&t.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Page created on ",dt.format(new Date(d.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),v?t.jsx(_l,{}):y?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 flex h-full min-h-0 flex-1 flex-col space-y-2",children:[T&&t.jsx(Dl,{lang:X,compare:e,setCompare:s,pageId:d==null?void 0:d.id}),t.jsx(Pl,{compare:e,setCompare:s,isComparisonEnabled:T}),(M=m==null?void 0:m.filter(H=>H.uid==="current"))==null?void 0:M.map((H,ae)=>t.jsx(Vn,{lang:X,pageId:d==null?void 0:d.id,revision:H,isLatest:!0,onRestore:()=>L(H),onDelete:()=>R(H),revisionNumber:ae,compare:e,setCompare:s,pageLiveFullSlug:_,isComparisonEnabled:T},H.uid)),t.jsx(c.ScrollArea,{className:"min-h-0 flex-1",children:t.jsx("div",{className:"space-y-2",children:(J=m==null?void 0:m.filter(H=>H.uid!=="current"))==null?void 0:J.map((H,ae)=>t.jsx(Vn,{lang:X,pageId:d==null?void 0:d.id,revision:H,isLatest:H.uid==="current",onRestore:()=>L(H),onDelete:()=>R(H),revisionNumber:ae+1,compare:e,setCompare:s,pageLiveFullSlug:_,isComparisonEnabled:T},H.uid))})})]})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Bl,{open:l,onOpenChange:o,revision:r,onRestore:V,isRestoring:N}),t.jsx(Ml,{open:u,onOpenChange:h,revision:r,onDelete:q,isDeleting:b})]})}function _l(){return t.jsx("div",{className:"mt-2 space-y-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(c.Skeleton,{className:"h-4 w-3/4"}),t.jsx(c.Skeleton,{className:"h-3 w-1/2"}),t.jsx(c.Skeleton,{className:"mt-1 h-5 w-20"})]}),t.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Vn({revision:e,isLatest:s,onRestore:n,onDelete:a,revisionNumber:r,compare:i,setCompare:l,pageId:o,pageLiveFullSlug:u,isComparisonEnabled:h,lang:d}){const{data:m}=Ke(e.currentEditor),v=(m==null?void 0:m.name)||"Unknown",y=!!i.find(p=>{var b;return s?(b=p==null?void 0:p.uid)==null?void 0:b.startsWith("live"):(p==null?void 0:p.uid)===e.uid}),j=i.length>=2&&!y;return t.jsxs("div",{className:"relative flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50",children:[t.jsxs("div",{className:"flex-1 space-y-3",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("p",{className:"flex items-center gap-1 text-xs leading-none",children:[h&&t.jsx(lt,{tag:s?"live":`#${r}`}),e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"text-xs font-bold",children:v}),!h&&s&&t.jsx(lt,{tag:"live"})]})}),t.jsxs("div",{className:"flex items-center gap-x-3",children:[t.jsx("div",{className:"flex items-center gap-2",children:e.type==="published"?t.jsx(lt,{tag:"published"}):t.jsx(lt,{tag:"draft"})}),t.jsx("div",{className:"flex items-center text-[10px] text-muted-foreground",children:t.jsx("span",{className:"leading-tight",children:dt.format(e.createdAt,"MMM d, h:mm a")})})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[e.type!=="draft"&&h&&t.jsx("a",{target:"_blank",href:s?u:`/revision/revision:${e.uid}:${r}?lang=${d}`,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-4 w-4 hover:text-blue-500",children:[t.jsx(S.Eye,{className:"h-3 w-3"}),t.jsx("span",{className:"sr-only",children:"View this version"})]})}),t.jsx(Me,{permissions:[be.RESTORE_REVISION,be.DELETE_REVISION],children:t.jsx(Ll,{revision:e,onRestore:n,onDelete:a})})]}),h&&t.jsx(Ga,{checked:y,disabled:j,onChange:()=>{l(y?i.filter(p=>s?p.uid!==`live:${o}`:p.uid!==e.uid):[...i,{uid:s?`live:${o}`:e.uid,label:s?"live":`#${r}`,item:e}].sort((p,b)=>new Date(p.item.createdAt).getTime()-new Date(b.item.createdAt).getTime()))}})]})}function Dl({compare:e,setCompare:s,pageId:n}){const[a,r]=x.useState(!1),[i,l]=e;if(e.length===0)return null;const o=({tab:u})=>t.jsxs("span",{className:"flex items-center justify-between rounded border border-blue-100 p-1 font-medium",children:[t.jsx(lt,{tag:u.label}),t.jsx("button",{className:"z-0 flex h-4 w-4 items-center justify-center rounded-full text-gray-400 hover:text-red-500",style:{lineHeight:1},onClick:()=>s(e.filter(h=>h.uid!==u.uid)),"aria-label":"Remove selection 1",children:t.jsx(S.X,{className:"h-3 w-3"})})]});return t.jsxs("div",{className:"mb-2 flex w-full max-w-md flex-col gap-1 rounded border bg-accent/60 p-2 shadow-sm",children:[t.jsxs("div",{className:"flex items-center gap-x-2 text-xs",children:[t.jsx("span",{className:"font-medium leading-tight text-gray-600",children:"Compare"}),i&&t.jsx(o,{tab:i}),t.jsx("span",{className:"font-medium leading-tight text-gray-600",children:"with"}),l?t.jsx(o,{tab:l}):t.jsx("span",{className:"rounded border px-1 text-xs text-muted-foreground",children:"Choose another"})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 pb-0.5 pt-2",children:[t.jsx(c.Button,{size:"sm",className:"h-6 gap-1 rounded px-2 text-xs leading-none text-gray-500",variant:"outline",onClick:()=>s([]),children:t.jsx("span",{children:" Clear"})}),t.jsxs(c.Button,{size:"sm",className:"h-6 gap-1 rounded px-2 text-xs leading-none",variant:"default",onClick:()=>r(!0),disabled:e.length<2,children:[t.jsx(S.FileJson,{className:"h-2.5 w-2.5"}),t.jsx("span",{className:"pt-0.5",children:"Show JSON Diff"})]})]}),a&&(e==null?void 0:e.length)>1&&n&&t.jsx(Cl,{open:a,onOpenChange:r,compare:e})]})}function Ga({checked:e,disabled:s,onChange:n,label:a="Compare"}){return t.jsx("div",{className:"absolute bottom-2 right-2",children:t.jsxs("label",{className:`flex cursor-pointer items-center gap-x-1 text-[11px] ${s?"opacity-50":""}`,children:[t.jsx("input",{type:"checkbox",className:"h-3 w-3 cursor-pointer rounded focus:ring-0 focus:ring-offset-0",checked:e,disabled:s,onChange:n}),t.jsx("span",{className:"select-none leading-tight",children:a})]})})}function Ll({revision:e,onRestore:s,onDelete:n}){return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-5 w-5",children:[t.jsx(S.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Me,{permission:be.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer text-sm",children:[t.jsx(S.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Me,{permission:be.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(c.DropdownMenuSeparator,{}),t.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(S.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function Bl({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=Ke((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Restore Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," from"," ",dt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(S.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(S.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function Ml({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=Ke((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",dt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(S.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Ol=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_CHANGES],queryFn:async()=>s(e,{action:O.GET_CHANGES})})},Rl=({page:e,selectedPages:s,handleCheckboxChange:n,getPageType:a,hasSlug:r,currentOwnerId:i})=>{const{data:l}=Ke(i),o=l==null?void 0:l.name;return t.jsxs("tr",{className:"group relative border-b last:border-b-0 hover:bg-gray-50",children:[t.jsxs("td",{scope:"row",className:`flex items-center gap-x-1 whitespace-nowrap px-6 py-2 text-gray-900 dark:text-white ${o?"opacity-50":""}`,children:[o?t.jsx(S.Lock,{className:"h-4 w-4 fill-red-200 text-red-500"}):t.jsx("input",{checked:f.includes(s,e==null?void 0:e.id),onClick:u=>{u.stopPropagation(),n(e==null?void 0:e.id)},type:"checkbox",className:"cursor-pointer rounded focus:outline-none focus:ring-0"})," ",r(e.pageType)?t.jsx(S.File,{className:"h-4 w-4"}):t.jsx(S.GlobeIcon,{className:"h-4 w-4"}),t.jsx(ut,{content:e.name,side:"top",showTooltip:e.name.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-medium text-black",children:e.name})}),e.slug&&t.jsx(ut,{content:e.slug,side:"top",showTooltip:e.slug.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-mono text-xs text-muted-foreground",children:e.slug})})]}),t.jsx("td",{className:"px-2",children:a(e==null?void 0:e.pageType)}),t.jsx("td",{className:"px-4 text-right",children:f.first(e.changes)||""}),t.jsx(t.Fragment,{children:o&&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:o})," is editing this page"]})})]},e==null?void 0:e.id)};function Gl({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n]=wa(),[a,r]=x.useState([]),i=Ye(),[l,o]=x.useState(i),{data:u,isFetching:h}=Ol(),{data:d}=Ce(),m=x.useCallback(L=>{var R;return(R=f.find(d,{key:L}))==null?void 0:R.hasSlug},[d]),v=x.useMemo(()=>f.filter(d,L=>!m(L.key)).map(L=>L.key),[m,d]),j=f.uniq(f.map(u,"lang")).filter(Boolean),p=x.useMemo(()=>f.filter(u,L=>L.pageType==="theme"?!1:l===i?L.lang===l||L.lang==="":L.lang===l),[u,l,i]),b=x.useMemo(()=>f.filter(p,L=>!v.includes(L.pageType)),[p,v]),w=x.useMemo(()=>f.filter(p,L=>v.includes(L.pageType)),[p,v]),{mutate:N,isPending:P}=wn();x.useEffect(()=>{const L=f.map(f.filter(p,{online:!0}),"id");r(L)},[p]),x.useEffect(()=>{const L=Object.keys(n);r(R=>f.filter(R,q=>!f.includes(L,q)))},[n]);const _=a.length===(p==null?void 0:p.length),T=L=>{r(R=>f.includes(R,L)?f.filter(R,q=>q!==L):f.concat(R,L))},A=()=>{r(_?[]:f.map(p,"id"))},z=()=>{N({ids:f.uniq(a)},{onSuccess:()=>{s(),qt("CENTER_CENTER"),o(i)}})},X=L=>{if(L==="theme")return"Theme";const R=f.find(d,{key:L});return R?R==null?void 0:R.name:L},V=x.useMemo(()=>{const L=[{label:"Updated",top:"pt-2"},...f.orderBy(f.filter(b,{online:!0}),"pageType"),...f.orderBy(f.filter(w,{online:!0}),"pageType")].filter(q=>q.pageType!=="theme"),R=[{label:"Offline",top:"pt-6"},...f.orderBy(f.filter(b,{online:!1}),"pageType"),...f.orderBy(f.filter(w,{online:!1}),"pageType")];return[...L,...R]},[b,w]);return t.jsx(c.Dialog,{open:e,onOpenChange:P?()=>{}:s,children:t.jsxs(c.DialogContent,{className:"flex max-h-[80%] max-w-4xl flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),j.length>0&&t.jsx("div",{className:"my-[2px] mt-0",children:t.jsx(Ma,{languages:[i,...j],selectedLanguage:l,setSelectedLanguage:o})}),t.jsx("div",{className:"no-scrollbar relative -mx-4 -mt-4 h-full max-h-full overflow-y-auto",children:h?t.jsxs("div",{className:"space-y-2 px-1",children:[t.jsx("div",{className:"mt-2 h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"})]}):t.jsxs("table",{className:"w-full text-left text-xs text-gray-500 dark:text-gray-400 rtl:text-right",children:[t.jsx("thead",{className:"sticky top-0 z-10 border-b bg-gray-50 text-gray-700 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"w-[1 50px] flex items-center gap-x-2 px-6 py-3",children:[t.jsx("input",{checked:_,onClick:L=>{L.stopPropagation(),A()},type:"checkbox",className:"mt-1 cursor-pointer rounded focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"w-[150px] px-2 py-3",children:"Type"}),t.jsx("th",{scope:"col",className:"w-[150px] px-4 py-3 text-right",children:"Status"})]})}),t.jsx("tbody",{children:f.map(V,L=>L.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:`relative px-6 py-2 text-xs font-medium text-gray-800 ${L.top}`,children:[t.jsx("div",{className:"absolute inset-0 left-6 flex items-center",children:t.jsx("div",{className:"order-gray-300 w-full"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"bg-gray-50 pr-2",children:L.label})})]})},"separator"):t.jsx(Rl,{page:L,selectedPages:a,handleCheckboxChange:T,getPageType:X,hasSlug:m,currentOwnerId:n[(L==null?void 0:L.primaryPage)||(L==null?void 0:L.id)]}))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10 flex items-center justify-center",children:[a.length>0&&t.jsxs("span",{className:"text-center text-sm text-muted-foreground",children:[a.length," Page",a.length!==1?"s":""," Selected"]}),t.jsx(c.Button,{disabled:P,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:P||h||f.isEmpty(a),onClick:z,children:P?"Publishing...":"Publish Selected"})]})]})})}const Ul=({isOpen:e,onClose:s,onContinue:n,isPending:a=!1,title:r="Translation Warning",description:i="Some blocks need translations before publishing. Do you want to continue anyway?"})=>{const l=()=>{s()},o=()=>{n()};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:r}),t.jsx(c.DialogDescription,{children:i})]}),t.jsxs(c.DialogFooter,{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:l,disabled:a,children:"Cancel"}),t.jsx(c.Button,{onClick:o,disabled:a,children:a?"Publishing...":"Continue Anyway"})]})]})})},Fl=()=>{const e=ee(),s=le();return U.useQuery({queryKey:[O.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:O.GET_WEBSITE_DATA,data:{draft:!0}})})};function ql({onClose:e}){const{data:s,isFetching:n}=Fl(),{mutateAsync:a,isPending:r}=Xr(),i=Ue("settingComponent",null),l=f.debounce(async o=>(await a({data:o}),!0),300);return i?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:x.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}const $l=()=>{const{selectedLang:e,fallbackLang:s}=F.useLanguages(),n=Ue("getPreviewUrl",async m=>m),[a,r]=x.useState(""),{data:i}=ke(),{data:l}=Ge(),{data:o}=Ce(),u=x.useMemo(()=>{var m;return(m=l==null?void 0:l.find(v=>(v==null?void 0:v.lang)===e))==null?void 0:m.slug},[e,l]),h=x.useCallback(m=>{var v;return(v=f.find(o,{key:m}))==null?void 0:v.hasSlug},[o]),d=e===s?"":e;return x.useEffect(()=>{(async()=>{if(typeof n=="function"){const m=!h(i==null?void 0:i.pageType),v=await n(m?`${d!==""?d+"/":""}${i==null?void 0:i.id}`:u||"");r(v)}else r("")})()},[n,u,i==null?void 0:i.pageType,h,i==null?void 0:i.id,d]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(S.Eye,{className:"h-4 w-4"})," ",ie.PREVIEW]})})})},zl=()=>{const[e,s]=F.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(ut,{content:ie.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(S.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},Vl=()=>{const[e,s]=x.useState(!1),{isLocked:n}=Je(),{savePageAsync:a,saveState:r}=F.useSavePage();x.useEffect(()=>{const h=d=>{r==="UNSAVED"&&(d.preventDefault(),d.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=x.useCallback(async()=>{e||(s(!0),await a(),s(!1))},[a,e]),{buttonIcon:l,buttonClass:o,tooltipContent:u}=x.useMemo(()=>{switch(r){case"UNSAVED":return{tooltipContent:ie.SAVEDRAFT,buttonIcon:t.jsx(S.Save,{className:"h-4 w-4"}),buttonClass:"gap-x-1"};case"SAVING":return{tooltipContent:ie.SAVING,buttonIcon:t.jsx(S.Loader,{className:"h-4 w-4 animate-spin text-sky-700"}),buttonClass:"gap-x-1"};case"SAVED":return{tooltipContent:ie.SAVED,buttonIcon:t.jsx(S.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 gap-x-1"}}},[r]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:o,children:[l," ",u]})},Kl=()=>{const{selectedLang:e}=F.useLanguages(),{data:s}=We(),{data:n}=Ge(),[a,r]=x.useState(!1),[i,l]=x.useState(!1),[o,u]=x.useState(null),{savePageAsync:h}=F.useSavePage(),[d,m]=x.useState(!1),{data:v}=ke(),{mutate:y,isPending:j}=wn(),{needTranslations:p}=F.useSavePage(),b=p(),{buttonText:w,buttonClassName:N,isPublished:P}=x.useMemo(()=>{const V=v&&(v==null?void 0:v.online);return{buttonClassName:V?"hover:bg-green-600 bg-green-500":"",isPublished:V,buttonText:V?ie.PUBLISHED:ie.PUBLISH}},[v]),_=async()=>{if(b){m(!0);return}T()},T=()=>{const V=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];y({ids:f.compact(V)},{onSuccess:()=>qt("TOP_RIGHT")})},A=()=>{m(!1),T()},z=async()=>{m(!1),await h()},X=x.useMemo(()=>f.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:_,disabled:j||!(v!=null&&v.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${N}`,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${i?"-translate-y-10":""}`,children:P?t.jsx(S.Send,{className:"h-4 w-4"}):t.jsx(S.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:P?t.jsx(S.Rocket,{className:"h-4 w-4"}):t.jsx(S.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:w}),e?`(${f.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:j||!(v!=null&&v.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${N}`,children:t.jsx(S.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(c.DropdownMenuItem,{disabled:j,className:"cursor-pointer text-xs",onClick:()=>y({ids:X},{onSuccess:()=>qt("TOP_RIGHT")}),children:[ie.PUBLISH," with translation pages"]}),!P&&t.jsxs(c.DropdownMenuItem,{disabled:j,className:"cursor-pointer text-xs",onClick:()=>y({ids:[v==null?void 0:v.id]},{onSuccess:()=>qt("TOP_RIGHT")}),children:[ie.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[ie.OPEN," publish menu"]}),P&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[ie.UNPUBLISH," page ",e?`(${f.upperCase(e)})`:""]})]})]})]}),t.jsx(Gl,{showModal:a,onClose:()=>r(!1)}),o&&t.jsx(ms,{page:o,onClose:()=>u(null)}),t.jsx(Ul,{isOpen:d,onClose:z,onContinue:A,isPending:j})]})},Hl=()=>{const e=Ue("settingComponent",null),[s,n]=x.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(ut,{content:ie.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(S.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(ql,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Ql(){const{isLocked:e}=Je(),[s]=Pe(),n=s.get("lang"),a=pa(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Il,{}),t.jsx(Me,{permission:be.EDIT_THEME,children:t.jsx(zl,{})}),t.jsx(Me,{permission:be.EDIT_SETTINGS,children:t.jsx(Hl,{})}),t.jsx($l,{}),t.jsx(Me,{permission:be.SAVE_PAGE,children:t.jsx(Vl,{})}),t.jsx(Me,{permission:be.PUBLISH_PAGE,children:t.jsx(Kl,{})})]})}const Wl=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(c.Input,{type:"text",autoFocus:!0,value:e?s:"",onChange:a=>n(a.target.value),placeholder:e?"Search pages...":"To search select default language",disabled:!e,onKeyDown:a=>a.stopPropagation()}),Jl=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=F.useLanguages(),o=(i==null?void 0:i.length)===0;return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",className:"w-max focus:outline-none focus:ring-0 border-[0px] rounded-md py-1 text-sm h-max border border-gray-200 hover:bg-gray-100 pl-4",children:[e?f.get(e,"name"):"Select Page",t.jsx(S.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"w-96 divide-y shadow-xl p-0 max-h-[75vh]",children:[t.jsx("div",{className:"p-1.5 bg-gray-50/30",children:t.jsx(Wl,{isDefaultLang:o,searchQuery:n,setSearchQuery:a})}),(r==null?void 0:r.length)===0?t.jsx("div",{className:"h-24 text-xs flex items-center justify-center",children:"No pages found"}):r==null?void 0:r.map(u=>t.jsx(c.DropdownMenuItem,{onClick:()=>s(u),disabled:o?l!==u.lang:i!==u.lang,className:`flex flex-col justify-start cursor-pointer overflow-x-auto whitespace-nowrap no-scrollbar ${u.id===(e==null?void 0:e.id)?"bg-blue-50":"hover:bg-gray-50"}`,children:t.jsx("div",{className:"w-full text-xs whitespace-nowrap px-2 py-[2px]",children:t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("span",{className:"font-medium",children:u.name}),t.jsx("span",{className:"font-mono font-medium text-gray-500 text-xs rounded-full px-2 py-[1px] border border-gray-300 truncate",children:u.slug})]})})},u.id))]})]})},Yl=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:l,onChangeLanguage:o}=ja(),u=x.useRef(void 0);return x.useEffect(()=>{u.current!==a&&e&&(o(),u.current=a)},[a,s]),t.jsx("div",{className:"relative",children:t.jsx(Jl,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:l,dynamicPages:n})})},Xl=()=>{const[e,s]=x.useState(null),[n,a]=x.useState(null),[r,i]=x.useState(null),[l,o]=x.useState(null),[u,h]=x.useState(null),[d,m]=x.useState(null),[v,y]=x.useState(!1),{data:j,isFetching:p}=We(),{selectedLang:b,fallbackLang:w}=F.useLanguages(),{data:N}=Ge(),P=N==null?void 0:N.find(V=>V.lang===b),{isLocked:_}=Je(),T=!(j!=null&&j.slug),[,A]=je.useAtom(hs),{savePage:z}=F.useSavePage();if(!j)return null;const X=V=>{b.length>0&&b!==w?A({edit:!0,id:V==null?void 0:V.id,primaryPage:V==null?void 0:V.primaryPage}):m(V)};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between px-[2px] rounded transition-colors duration-200",children:[t.jsx(c.Button,{className:"flex h-7 max-w-[200px] cursor-pointer items-center truncate rounded px-1 text-xs font-medium",variant:"ghost",onClick:()=>{z(),y(!0)},children:p?t.jsx(S.Loader,{className:"h-4 w-4 animate-spin text-slate-400"}):t.jsxs("span",{className:"flex w-full cursor-pointer items-end overflow-hidden text-ellipsis whitespace-nowrap rounded-sm text-xs font-medium",children:[T?t.jsx(S.Globe,{className:"mr-1 h-4 w-4"}):t.jsx(S.File,{className:"mr-1 h-4 w-4"}),f.get(P||j,"name")??""]})}),_?t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 cursor-not-allowed rounded opacity-50 hover:bg-transparent",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4"})}):t.jsx(Tn,{page:j,setDuplicatePage:V=>h(V),setAddEditPage:V=>X(V),setUnpublishPage:V=>a(V),setDeletePage:V=>s(V),setMarkAsTemplate:V=>i(V),setUnmarkAsTemplate:V=>o(V),isLanguagePage:b.length>0&&b!==w,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 rounded",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4"})})})]}),d&&t.jsx(En,{closePanel:()=>m(null),editPage:()=>{},addEditPage:d,setAddEditPage:m}),e&&t.jsx(Us,{page:e,onClose:()=>s(null)}),n&&t.jsx(ms,{page:n,onClose:()=>a(null)}),r&&t.jsx(An,{page:r,onClose:()=>i(null)}),l&&t.jsx(kn,{page:l,onClose:()=>o(null)}),u&&t.jsx(Cn,{page:u,onClose:()=>h(null),closePanel:()=>m(null)}),t.jsx(c.Sheet,{open:v,onOpenChange:y,children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:"z-50 w-full !max-w-screen-md border-border px-1",children:[t.jsxs(c.SheetHeader,{className:"mb-3",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2 px-4 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:"h-[calc(100vh-80px)] overflow-y-auto",children:t.jsx(Ra,{close:()=>y(!1)})})]})})]})},Zl=({hasDynamicPage:e})=>t.jsx(ds,{children:t.jsxs("div",{className:"flex min-w-[300px] max-w-[400px] flex-col items-center justify-center rounded-lg border bg-white p-4 shadow-lg",children:[t.jsx("h1",{className:"text-lg font-medium",children:e?"Select a page":"No pages found"}),t.jsx("p",{className:"pt-2 text-center text-sm font-light text-gray-600",children:e?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]})}),eo=()=>{const{data:e}=We(),s=yn(),{data:n,isFetching:a}=ke(),r=f.get(n,"dynamic",!1),i=F.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:l,allLangPages:o}=ja(),u=o.length>0,h=e==null?void 0:e.slug,d=!h,m=va(),y=(d?`Partial: ${e==null?void 0:e.name} `:`${h}${s}`).replace(window.location.host,"");return t.jsxs("div",{className:"relative z-10 flex items-center gap-x-1",children:[t.jsx("div",{className:F.mergeClasses("flex h-8 w-auto max-w-[600px] items-center rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800",a&&"pointer-events-none cursor-not-allowed opacity-50"),children:t.jsx(Xl,{})}),t.jsxs("div",{className:F.mergeClasses("flex h-8 w-auto max-w-[600px] items-center rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800"+(d?" pr-2":""),a&&"pointer-events-none cursor-not-allowed opacity-50"),children:[t.jsx(In,{}),t.jsxs("div",{className:"flex w-full items-center overflow-hidden",children:[t.jsx("div",{className:`w-full max-w-[200px] overflow-hidden overflow-ellipsis whitespace-nowrap pl-1 text-xs ${d?"italic text-gray-400":"font-mono text-gray-500"}`,children:y==="/"?t.jsxs("span",{className:"text-gray-900",children:["/",t.jsx("span",{className:"text-[11px] font-light italic text-gray-400",children:"(Homepage)"})]}):y}),!d&&t.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",children:t.jsx("div",{className:"ml-2 mr-px flex-shrink-0 rounded-sm p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(S.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})]}),r&&!a&&i&&t.jsxs("div",{className:"relative",children:[!l&&t.jsx(Zl,{hasDynamicPage:u}),t.jsx(Yl,{})]})]})},to=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(vl,{}),t.jsx(eo,{}),t.jsx(Ql,{})]}),so=()=>{const e=le(),{aiContext:s}=pn(),n=ee();return x.useCallback(async(a,r,i,l)=>n(e,{action:O.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},no=(e,s)=>s.map(n=>{if(f.has(e,n._type)){const a=ua.getDefaultBlockProps(n._type);return{...a,...f.pick(n,[...f.keys(a),"_type","_id","_name","_parent","_bindings"]),...f.pickBy(n,(r,i)=>f.endsWith(i,"_attrs")),...n}}return n}),ao=e=>{const s=ua.useRegisteredChaiBlocks();return x.useMemo(()=>{if(!e||f.isEmpty(e))return{blocks:[]};const n=f.filter(e,a=>!f.includes(a==null?void 0:a._type,"@chai/"));return{blocks:no(s,n)}},[e,s])},Kn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=f.get(a,"html",""),i=f.get(a,"blocks",[]);return f.isArray(i)?i:F.getBlocksFromHTML(r)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(r=>({...r}))}catch(a){return console.error(a),[]}}},ro=()=>{const e=le(),s=ee();return U.useQuery({queryKey:["uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{F.registerChaiLibrary(r.id,{name:r.isSiteLibrary?r.name+" (Current Site) ":r.name,description:r.description,getBlocksList:i=>Kn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>Kn.getUILibraryBlock(i,s,e)})}),a}})},Ua=()=>{const e=Os(),s=ee(),{user:n}=Oe(),a=n==null?void 0:n.id;return U.useQuery({queryKey:["permissions",a],queryFn:()=>s(e,{action:O.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},io=()=>{const e=le(),s=ee(),{setCurrentEditor:n}=Je(),[,a]=Rs();return{onSave:async({page:i,blocks:l,needTranslations:o})=>{try{const u=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l,needTranslations:o}});return u.code==="PAGE_LOCKED"?(n(u.editor),!0):(a(h=>({...h,lastSaved:new Date().toISOString()})),u)}catch(u){return console.error(u),new Error("Failed to save blocks")}}}},lo=()=>{const{data:e}=ht(),s=le(),n=ee();return{getPartialBlocks:x.useCallback(async()=>{const a={};for(const r of e??[])f.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:f.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:x.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return f.filter(r.blocks,i=>f.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},Hn=Ss.z.object({email:Ss.z.string().email({message:"Please enter a valid email address"}),password:Ss.z.string().min(6,{message:"Password must be at least 6 characters"})}),oo=()=>{const{setUser:e,logout:s}=Oe(),n=Os(),[a,r]=x.useState(""),[i,l]=x.useState(""),[o,u]=x.useState({}),[h,d]=x.useState(!1),[m,v]=x.useState(""),y=U.useMutation({mutationFn:async b=>{v("");const w=await gn(n,{action:"LOGIN",data:b});if(!w.ok){const P=await w.json();throw new Error(P.error||"Login failed")}const N=await w.json();if(f.has(N,"id")&&f.has(N,"email")&&f.has(N,"accessToken")&&f.has(N,"refreshToken"))e(N);else throw s(),new Error("Something went wrong. Please try again.");return N},onSuccess:()=>{u({}),v("")},onError:b=>{u({email:" ",password:" "}),v(b.message?"Invalid email or password":"Something went wrong")}}),j=async b=>{b.preventDefault(),u({});const w={email:a,password:i};try{const N=Hn.parse(w);y.mutate(N)}catch(N){if(N instanceof Ss.z.ZodError){const P=N.issues.reduce((_,T)=>{const A=T.path[0];return _[A]=T.message,_},{});u(P)}}},p=Hn.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-50",children:t.jsxs(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:b=>r(b.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:h?"text":"password",value:i,onChange:b=>l(b.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>d(!h),children:h?t.jsx(S.EyeOff,{className:"h-4 w-4"}):t.jsx(S.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:m})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!p||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(S.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center gap-2 border-t px-10 pt-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"flex items-center gap-1 text-primary hover:underline",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"h-4 w-4 rounded font-bold uppercase"}),"Chai Builder"]})]})]})]})})};let rn=oo;const co=()=>x.useMemo(()=>rn,[rn]),uo=e=>{rn=e},ho=()=>{const e=co();return t.jsx(x.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},mo=({page:e,onClose:s})=>{const[n,a]=x.useState(e.slug||""),{mutate:r,isPending:i}=Li(),{data:l}=Ce(),o=f.find(l,{key:e==null?void 0:e.pageType}),u=d=>{if(d.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Ne).some(y=>n===`/${y}`||f.startsWith(n,`/${y}/`))){W.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},h=(e==null?void 0:e.lang)||"";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:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(S.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",h]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:d=>{const m=d.target.value;f.startsWith(m,`/${h}`)&&a(m)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!f.startsWith(n,`/${h}`)||f.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},fo=()=>{const[,e]=je.useAtom(hs),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=F.useLanguages(),{data:r,isFetching:i}=Ge(),{data:l}=ke(),{data:o}=Ce(),u=x.useMemo(()=>{const w=o==null?void 0:o.find(N=>N.key===(l==null?void 0:l.pageType));return l!=null&&l.dynamic?w==null?void 0:w.dynamicSlug:""},[o,l==null?void 0:l.pageType,l==null?void 0:l.dynamic]),[h,d]=x.useState(null),[m,v]=x.useState(null),[y,j]=x.useState(null),{data:p}=Ve(),b=f.filter(f.get(p,"languages")||["en"],w=>!f.find(r,{lang:w})&&w!==f.get(p,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:i?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"})]}):f.map(r,w=>{const N=w.lang,P=w.slug,_=!w.primaryPage,T=N===s;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`flex w-full cursor-pointer items-center justify-between rounded p-2 text-slate-500 ${T?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(N),children:[t.jsxs("div",{className:"flex-1 gap-x-3",children:[t.jsxs("div",{className:"flex items-center gap-x-2 text-[13px] text-slate-800",children:[t.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${w.online?"bg-green-300":"bg-gray-300"}`}),f.get(Ne,_?n:N,N)]}),t.jsxs("div",{children:[P&&t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Slug: ",t.jsx("b",{className:"font-mono font-medium",children:u?`${P}/${u}`:P})]}),t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",w.name," "]})]})]})]}),_?t.jsxs("div",{className:"flex items-center gap-x-1 text-[11px] text-orange-500",children:[t.jsx(S.StarIcon,{fill:"orange",className:"h-3 w-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(Me,{permissions:[be.EDIT_PAGE,be.DELETE_PAGE,be.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:A=>A.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(S.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"z-[9999] text-sm",children:[t.jsx(Me,{permissions:[be.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:A=>{A.stopPropagation(),e({edit:!0,id:w.id,primaryPage:w.primaryPage})},children:[t.jsx(S.PencilIcon,{className:"size-3"}),ie.EDIT]})}),t.jsx(Me,{permissions:[be.UNPUBLISH_PAGE],children:(w==null?void 0:w.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:A=>{A.stopPropagation(),v(w)},children:[t.jsx(S.Power,{className:"size-3"}),ie.UNPUBLISH]})}),t.jsx(Me,{permissions:[be.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:A=>{A.stopPropagation(),d(w)},children:[t.jsx(S.TrashIcon,{className:"size-3"}),ie.DELETE]})})]})]})})})]},w.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Me,{permissions:[be.ADD_PAGE],children:t.jsx("div",{className:"flex w-full justify-center",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:f.isEmpty(b),onClick:()=>{e({primaryPage:l==null?void 0:l.id,edit:!1})},children:ie.ADD_NEW_LANGUAGE})})}),h&&t.jsx(Us,{page:h,onClose:()=>d(null)}),m&&t.jsx(ms,{page:m,onClose:()=>v(null)}),y&&t.jsx(mo,{page:y,onClose:()=>j(null)})]})},xo=({isActive:e,show:s})=>{const{data:n}=Ve();return!f.has(n,"languages")||!f.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(S.LanguagesIcon,{className:"w-4 h-4"})})},Fa="lang",go={id:Fa,label:"Languages",position:"top",panel:fo,button:xo,view:"modal",width:400};function He({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=we.useState(!1),[l,o]=we.useState([]),[u,h]=we.useState(e);we.useEffect(()=>{r||o([]),h(e)},[e,r]);const d=j=>Array.isArray(j)?"array":typeof j=="object"&&j!==null?"object":"value",m=we.useCallback(j=>{const p=b=>n==="value"?b==="value"||b==="object":n==="array"?b==="array":b===n;j.type==="object"?(o(b=>[...b,j.key]),h(j.value)):p(j.type)&&(s([...l,j.key].join(".")),i(!1))},[l,s,n]),v=we.useCallback(()=>{if(l.length>0){const j=l.slice(0,-1);o(j),h(j.reduce((p,b)=>p[b],e))}},[l,e]),y=we.useMemo(()=>Object.entries(u).map(([j,p])=>({key:j,value:p,type:d(p)})).filter(j=>n==="value"?j.type==="value"||j.type==="object":n==="array"?j.type==="array"||j.type==="object":n==="object"?j.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(S.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:j=>{try{j.preventDefault();const p=j.currentTarget;p.scrollTop+=j.deltaY}catch{j.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:v,className:"flex items-center text-sm",children:[t.jsx(S.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(j=>t.jsxs(c.CommandItem,{onSelect:()=>m(j),className:"flex items-center justify-between",children:[t.jsx("span",{children:j.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&j.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:p=>{p.stopPropagation(),s([...l,j.key].join(".")),i(!1)},children:"Select"}),(j.type==="object"||j.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(S.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},j.key))]})]})]})})]})}const po=()=>{const{selectedLang:e}=F.useLanguages(),{data:s,isFetching:n}=Ge();return{data:x.useMemo(()=>f.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},yo=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg, [data-block-type='PartialBlock']").forEach(o=>o.remove()),a.querySelectorAll("*").forEach(o=>{Array.from(o.attributes).forEach(u=>o.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(o=>`<${o.tagName.toLowerCase()}>${o.innerHTML}</${o.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},xt=({keyword:e,onComplete:s,field:n})=>{const a=ee(),r=le(),{selectedLang:i,fallbackLang:l}=F.useLanguages(),o=F.useBuilderProp("aiContext",""),{mutate:u,isPending:h}=U.useMutation({mutationFn:async()=>{const d=yo();return await a(r,{action:O.GENERATE_SEO_FIELD,data:{pageContext:o,dynamic:!1,field:n,lang:i||l,pageContent:d,keyword:e}})},onSuccess:d=>{s({fieldValue:d.field})},onError:d=>{s({fieldValue:null,error:d.message})}});return t.jsx(c.Button,{disabled:h,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:h?t.jsx(S.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(S.Sparkles,{className:"text-yellow-500"})})},jo=({isOpen:e,onClose:s,onSave:n,onDiscard:a,isSaving:r=!1,fromLanguage:i,toLanguage:l})=>{const o=Ne[i]||i,u=Ne[l]||l;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:"Unsaved SEO Changes"}),t.jsxs(c.DialogDescription,{children:['You have unsaved changes in the SEO for "',o,'" version. Do you want to save these changes before switching to "',u,'" version?']})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx(c.Button,{variant:"outline",onClick:a,disabled:r,children:"Discard Changes"}),t.jsx(c.Button,{onClick:n,disabled:r,children:r?"Saving...":"Save & Switch"})]})]})})},vo=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Qn=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,o=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:o,position:l}),a=a.replace(i,o)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,o=l.message.match(/position (\d+)/),u=o?parseInt(o[1]):void 0;let h,d;if(u!==void 0){const m=a.substring(0,u).split(`
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}}}},bo=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,o=new RegExp(vo(l),"g");a=a.replace(o,r)}),a},wo=(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,v]=x.useState(null),[y,j]=x.useState(""),p=x.useRef(null);x.useEffect(()=>{e.trim()===""&&s("{}")},[e,s]);const b=_=>{if(a)return;const T=_.target.value;s(T)},w=_=>{if(_.key==="Tab"){_.preventDefault();const T=_.currentTarget,A=T.selectionStart,z=T.selectionEnd;if(A!==z){const V=e.substring(A,z).split(`
11
11
  `);if(_.shiftKey){const R=V.map(M=>M.startsWith(" ")?M.substring(2):M).join(`
12
12
  `),q=e.substring(0,A)+R+e.substring(z);s(q),setTimeout(()=>{T.selectionStart=A,T.selectionEnd=A+R.length},0)}else{const R=V.map(M=>` ${M}`).join(`
13
- `),q=e.substring(0,A)+R+e.substring(z);s(q),setTimeout(()=>{T.selectionStart=A,T.selectionEnd=A+R.length},0)}}else{const X=e.substring(0,A)+" "+e.substring(z);s(X),setTimeout(()=>{T.selectionStart=T.selectionEnd=A+2},0)}}};x.useEffect(()=>{const _=Wn(e);if(_.isValid)if(v(null),_.parsed){const T=bo(_.parsed,o);j(T)}else j("");else v(_.error),j("")},[e,o]);const N=()=>{const _=Wn(e);if(_.isValid&&_.parsed){const T=vo(_.parsed,_.placeholders);s(T)}},P=()=>{m!=null&&m.position&&p.current&&(p.current.focus(),p.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:_=>u&&u(_,l)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:N,disabled:!e.trim()||n||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:p,id:l,name:l,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:b,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."})]})]})})},Jn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},wo=(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}},qa=()=>{const{t:e}=F.useTranslation(),[,s]=F.useSidebarActivePanel(),{data:n}=ke(),{data:a}=bn(),{data:r,isFetching:i}=go(),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=Aa(h),{selectedLang:m,fallbackLang:v}=F.useLanguages(),y=m||v,[j,p]=x.useState(!1),[b,w]=x.useState(!1),[N,P]=x.useState(!1),[_,T]=x.useState(null),[A,z]=x.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",metaOther:"{}",...l}),X=x.useRef({}),{mutate:V,isPending:L}=wn(),R=L||j||b,{hasPermission:q}=F.usePermissions(),M=q(be.EDIT_SEO);x.useEffect(()=>{if(!i&&l&&u){const g={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",metaOther:"",...l};z(g),X.current[y]=g}},[i,l,y,u]),x.useEffect(()=>{const g=I=>{const{fromLang:G,toLang:C,switchHandler:D}=I.detail,Q=X.current[y];(Q?!f.isEqual(Q,A):!1)?(T({fromLang:G,toLang:C,switchHandler:D}),P(!0)):D()};return window.addEventListener("seo-language-switch-check",g),()=>{window.removeEventListener("seo-language-switch-check",g)}},[u,A,y]);const J=async()=>{if(!(!d||!y))try{p(!0);const g=$t(d,y),I={...A,keyword:f.get(g,"seo.keyword",""),title:f.get(g,"seo.title",""),description:f.get(g,"seo.description",""),cononicalUrl:f.get(g,"seo.canonicalUrl",""),noIndex:f.get(g,"seo.noIndex",!1),noFollow:f.get(g,"seo.noFollow",!1),ogTitle:f.get(g,"seo.ogTitle",""),ogDescription:f.get(g,"seo.ogDescription","")};z(I),W.toast.success(e("SEO fields reset to defaults"))}catch(g){W.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",g)}finally{p(!1)}},H=async()=>{if(!(!d||!y))try{w(!0);const g=$t(d,y),I={...A,jsonLD:f.get(g,"seo.jsonLD","")};z(I),W.toast.success(e("JSON-LD reset to default"))}catch(g){W.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",g)}finally{w(!1)}},ae=async()=>{if(!(!d||!y))try{p(!0);const g=$t(d,y),I={...A,ogTitle:f.get(g,"seo.ogTitle",""),ogDescription:f.get(g,"seo.ogDescription",""),ogImage:f.get(g,"seo.ogImage",""),ogImageId:f.get(g,"seo.ogImageId",""),metaOther:f.get(g,"seo.metaOther","{}")};z(I),W.toast.success(e("Meta Tag fields reset to defaults"))}catch(g){W.toast.error(e("Failed to reset Meta Tag fields")),console.error("Reset Meta Tag error:",g)}finally{p(!1)}},xe=async()=>{V({id:r==null?void 0:r.id,seo:A,primaryPage:u},{onSuccess:()=>{console.log("SEO & JSON-LD updated successfully",A),X.current[y]=A,W.toast.success("SEO & JSON-LD updated successfully")}})},ge=(g,I)=>{const G=document.getElementById(I);if(G){const{value:C,newCursorPos:D}=wo(G,g);o.current={id:I,position:D},G.tagName.toLowerCase()==="input"?(G.value=C,z(Y=>({...Y,[G.name]:C})),G.focus(),G.setSelectionRange(D,D),[0,10,50,100,200].forEach(Y=>{setTimeout(()=>{const oe=document.getElementById(I);oe&&(oe.focus(),oe.setSelectionRange(D,D))},Y)})):(z($=>({...$,[G.name]:C})),requestAnimationFrame(()=>{const $=document.getElementById(I);$&&($.focus(),$.setSelectionRange(D,D),setTimeout(()=>{const Y=document.getElementById(I);Y&&(Y.focus(),Y.setSelectionRange(D,D))},50))}))}},ce=g=>{const I={...A,[g.target.name]:g.target.name==="noIndex"||g.target.name==="noFollow"?g.target.checked:g.target.value};z(I)},E=g=>I=>{f.isEmpty(I.fieldValue)||ce({target:{name:g,value:typeof I.fieldValue=="string"?I.fieldValue.replace(/^"(.*)"$/,"$1"):I.fieldValue}}),I.error&&W.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:I.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!M&&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 grid-cols-3",children:[t.jsx(c.TabsTrigger,{value:"seo",children:e("SEO")}),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:[M&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:J,disabled:R||!M||!d,children:e(j?"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")}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:A.keyword,onChange:ce,disabled:R||!M,placeholder:e("Enter keyword"),readOnly:!M})]}),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(xt,{keyword:A.keyword,onComplete:E("title"),field:"title"}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:A.title,onChange:ce,disabled:R||!M,placeholder:e("Enter SEO title"),readOnly:!M})]}),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(xt,{keyword:A.keyword,onComplete:E("description"),field:"description"}),M&&t.jsx(He,{data:a??{},onSelect:g=>ge(g,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:A.description,onChange:ce,disabled:R||!M,placeholder:e("Enter SEO description"),readOnly:!M})]}),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")}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:A.canonicalUrl,onChange:ce,disabled:R||!M,placeholder:e("Enter Canonical URL"),readOnly:!M})]}),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:A.noIndex,onChange:ce,disabled:R||!M,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:A.noFollow,onChange:ce,disabled:R||!M,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:"opengraph",children:t.jsxs("div",{className:"space-y-4",children:[M&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:ae,disabled:R||!M||!d,children:e(j?"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(xt,{keyword:A.keyword,onComplete:E("ogTitle"),field:"ogTitle"}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:A.ogTitle,onChange:ce,disabled:R||!M,placeholder:e("Enter OG title"),readOnly:!M})]}),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(xt,{keyword:A.keyword,onComplete:E("ogDescription"),field:"ogDescription"}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:A.ogDescription,onChange:ce,disabled:R||!M,placeholder:e("Enter OG description"),readOnly:!M})]}),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")}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>{z({...A,ogImage:`{{${g}}}`,ogImageId:""})}})]}),t.jsx(Ms,{assetId:A.ogImageId,assetUrl:A.ogImage,onChange:g=>{z({...A,ogImage:g.url,ogImageId:g.id})},disabled:R||!M,placeholder:e("Select OG image"),className:"mb-2"})]}),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(xt,{keyword:A.keyword,onComplete:E("metaOther"),field:"metaOther"})})]}),t.jsx(ln,{id:"metaOther",value:A.metaOther,onChange:g=>{ce({target:{name:"metaOther",value:g}})},placeholder:e("Enter Meta Tags JSON"),disabled:R||!M,readOnly:!M,pageData:a||{},rows:8,handleFieldInsert:ge})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[M&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:H,disabled:R||!M||!d,children:e(b?"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(xt,{keyword:A.keyword,onComplete:E("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(ln,{id:"jsonLD",value:A.jsonLD,onChange:g=>{ce({target:{name:"jsonLD",value:g}})},placeholder:e("Enter JSON-LD"),disabled:R||!M,readOnly:!M,pageData:a||{},rows:12,handleFieldInsert:ge})]})]})})]})})]}),M&&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:[Jn(A.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:xe,disabled:!Jn(A==null?void 0:A.jsonLD)||(X.current[y]?f.isEqual(X.current[y],A):!1)||R||!M,children:e(L?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(yo,{isOpen:N,onClose:()=>{P(!1),T(null)},onSave:async()=>{_&&(await xe(),_.switchHandler(),P(!1),T(null))},onDiscard:()=>{if(_){const g=X.current[y];g&&z(g),_.switchHandler(),P(!1),T(null)}},isSaving:L,fromLanguage:(_==null?void 0:_.fromLang)||y,toLanguage:(_==null?void 0:_.toLang)||""})]})};qa.displayName="SeoPanel";const $a="seo",So=({isActive:e,show:s})=>{const{data:n}=ke(),a=Aa(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",{stroke:"currentColor",fill:"none","stroke-width":"2",viewBox:"0 0 24 24","stroke-linecap":"round","stroke-linejoin":"round",height:"200px",width:"200px",xmlns:"http://www.w3.org/2000/svg",children:[t.jsx("path",{d:"M7 8h-3a1 1 0 0 0 -1 1v2a1 1 0 0 0 1 1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-3"}),t.jsx("path",{d:"M14 16h-4v-8h4"}),t.jsx("path",{d:"M11 12h2"}),t.jsx("path",{d:"M17 8m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"})]})})},No={id:$a,label:"SEO",panel:qa,button:So,position:"top",width:600,view:"modal"},on={},Ns=(e,s)=>{f.has(on,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),f.set(on,e,{id:e,...s})},Eo=()=>f.values(on),Co=()=>{var i;const e=Eo(),[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"})})})})]})},Ao="site-settings",To=({isActive:e,show:s})=>F.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,ko={id:Ao,label:"Site Settings",panel:Co,button:To,position:"bottom",width:800,view:"modal"},Po="user-info",Io=()=>{const{user:e,logout:s}=Oe(),n=Ue("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},_o={id:Po,label:"User Info",button:Io,position:"bottom"},Do=()=>{F.registerChaiSidebarPanel($a,No),F.registerChaiSidebarPanel(Fa,xo),F.registerChaiSidebarPanel("site-settings",ko),F.registerChaiSidebarPanel("user-info",_o)};var ne={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Yn(this.context.count)},getNextContextId(){return Yn(this.context.count++)}};function Yn(e){const s=String(e),n=s.length-1;return ne.context.id+(n?String.fromCharCode(96+n):"")+s}function Gt(e){ne.context=e}var za=!1,Lo=(e,s)=>e===s,Ts=Symbol("solid-proxy"),Va=typeof Proxy=="function",Dn=Symbol("solid-track"),ks={equals:Lo},Ka=er,Xe=1,Ps=2,Ha={owned:null,cleanups:null,context:null,owner:null},Xs={},de=null,Zs=null,Bo=null,ye=null,Ie=null,Qe=null,Fs=0;function st(e,s){const n=ye,a=de,r=e.length===0,i=s===void 0?a:s,l=r?Ha:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Te(()=>Ht(l)));de=l,ye=null;try{return ze(o,!0)}finally{ye=n,de=a}}function Se(e,s){s=s?Object.assign({},ks,s):ks;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Za(n,r));return[Xa.bind(n),a]}function Qa(e,s,n){const a=qs(e,s,!0,Xe);Ot(a)}function nt(e,s,n){const a=qs(e,s,!1,Xe);Ot(a)}function Ln(e,s,n){Ka=Qo;const a=qs(e,s,!1,Xe);(!n||!n.render)&&(a.user=!0),Qe?Qe.push(a):Ot(a)}function Ae(e,s,n){n=n?Object.assign({},ks,n):ks;const a=qs(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Ot(a),Xa.bind(a)}function Mo(e){return e&&typeof e=="object"&&"then"in e}function Oo(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"&&Ae(a);const v=new Set,[y,j]=(i.storage||Se)(i.initialValue),[p,b]=Se(void 0),[w,N]=Se(void 0,{equals:!1}),[P,_]=Se(d?"ready":"unresolved");ne.context&&(u=ne.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:ne.load&&ne.has(u)&&(o=ne.load(u)));function T(L,R,q,M){return l===L&&(l=null,M!==void 0&&(d=!0),(L===o||R===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(M,{value:R})),o=Xs,A(R,q)),R}function A(L,R){ze(()=>{R===void 0&&j(()=>L),_(R!==void 0?"errored":d?"ready":"unresolved"),b(R);for(const q of v.keys())q.decrement();v.clear()},!1)}function z(){const L=Vo,R=y(),q=p();if(q!==void 0&&!l)throw q;return ye&&ye.user,R}function X(L=!0){if(L!==!1&&h)return;h=!1;const R=m?m():a;if(R==null||R===!1){T(l,Te(y));return}let q;const M=o!==Xs?o:Te(()=>{try{return r(R,{value:y(),refetching:L})}catch(J){q=J}});if(q!==void 0){T(l,void 0,Es(q),R);return}else if(!Mo(M))return T(l,M,void 0,R),M;return l=M,"v"in M?(M.s===1?T(l,M.v,void 0,R):T(l,void 0,Es(M.v),R),M):(h=!0,queueMicrotask(()=>h=!1),ze(()=>{_(d?"refreshing":"pending"),N()},!1),M.then(J=>T(M,J,void 0,R),J=>T(M,void 0,Es(J),R)))}Object.defineProperties(z,{state:{get:()=>P()},error:{get:()=>p()},loading:{get(){const L=P();return L==="pending"||L==="refreshing"}},latest:{get(){if(!d)return z();const L=p();if(L&&!l)throw L;return y()}}});let V=de;return m?Qa(()=>(V=de,X(!1))):X(!1),[z,{refetch:L=>Ja(V,()=>X(L)),mutate:j}]}function Ro(e){return ze(e,!1)}function Te(e){if(ye===null)return e();const s=ye;ye=null;try{return e()}finally{ye=s}}function Go(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=Te(()=>s(o,r,l));return r=o,u}}function Wa(e){Ln(()=>Te(e))}function Lt(e){return de===null||(de.cleanups===null?de.cleanups=[e]:de.cleanups.push(e)),e}function Xn(){return de}function Ja(e,s){const n=de,a=ye;de=e,ye=null;try{return ze(s,!0)}catch(r){Bn(r)}finally{de=n,ye=a}}function Uo(e){const s=ye,n=de;return Promise.resolve().then(()=>{ye=s,de=n;let a;return ze(e,!1),ye=de=null,a?a.done:void 0})}var[Fo,ad]=Se(!1);function qo(){return[Fo,Uo]}function $o(e,s){const n=Symbol("context");return{id:n,Provider:Wo(n),defaultValue:e}}function zo(e){let s;return de&&de.context&&(s=de.context[e.id])!==void 0?s:e.defaultValue}function Ya(e){const s=Ae(e),n=Ae(()=>cn(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Vo;function Xa(){if(this.sources&&this.state)if(this.state===Xe)Ot(this);else{const e=Ie;Ie=null,ze(()=>_s(this),!1),Ie=e}if(ye){const e=this.observers?this.observers.length:0;ye.sources?(ye.sources.push(this),ye.sourceSlots.push(e)):(ye.sources=[this],ye.sourceSlots=[e]),this.observers?(this.observers.push(ye),this.observerSlots.push(ye.sources.length-1)):(this.observers=[ye],this.observerSlots=[ye.sources.length-1])}return this.value}function Za(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&&tr(i)),l||(i.state=Xe)}if(Ie.length>1e6)throw Ie=[],new Error},!1)),s}function Ot(e){if(!e.fn)return;Ht(e);const s=Fs;Ko(e,e.value,s)}function Ko(e,s,n){let a;const r=de,i=ye;ye=de=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Xe,e.owned&&e.owned.forEach(Ht),e.owned=null),e.updatedAt=n+1,Bn(l)}finally{ye=i,de=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Za(e,a):e.value=a,e.updatedAt=n)}function qs(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!==Ha&&(de.owned?de.owned.push(i):de.owned=[i]),i}function Is(e){if(e.state===0)return;if(e.state===Ps)return _s(e);if(e.suspense&&Te(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)Ot(e);else if(e.state===Ps){const a=Ie;Ie=null,ze(()=>_s(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 Ho(n),a}catch(a){n||(Qe=null),Ie=null,Bn(a)}}function Ho(e){if(Ie&&(er(Ie),Ie=null),e)return;const s=Qe;Qe=null,s.length&&ze(()=>Ka(s),!1)}function er(e){for(let s=0;s<e.length;s++)Is(e[s])}function Qo(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:Is(a)}if(ne.context){if(ne.count){ne.effects||(ne.effects=[]),ne.effects.push(...e.slice(0,n));return}Gt()}for(ne.effects&&(ne.done||!ne.count)&&(e=[...ne.effects,...e],n+=ne.effects.length,delete ne.effects),s=0;s<n;s++)Is(e[s])}function _s(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)&&Is(a):r===Ps&&_s(a,s)}}}function tr(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=Ps,n.pure?Ie.push(n):Qe.push(n),n.observers&&tr(n))}}function Ht(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--)Ht(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Ht(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 Es(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Bn(e,s=de){throw Es(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 Wo(e,s){return function(a){let r;return nt(()=>r=Te(()=>(de.context={...de.context,[e]:a.value},Ya(()=>a.children))),void 0),r}}var un=Symbol("fallback");function Ds(e){for(let s=0;s<e.length;s++)e[s]()}function Jo(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return Lt(()=>Ds(i)),()=>{let u=e()||[],h=u.length,d,m;return u[Dn],Te(()=>{let y,j,p,b,w,N,P,_,T;if(h===0)l!==0&&(Ds(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[un],r[0]=st(A=>(i[0]=A,n.fallback())),l=1);else if(l===0){for(r=new Array(h),m=0;m<h;m++)a[m]=u[m],r[m]=st(v);l=h}else{for(p=new Array(h),b=new Array(h),o&&(w=new Array(h)),N=0,P=Math.min(l,h);N<P&&a[N]===u[N];N++);for(P=l-1,_=h-1;P>=N&&_>=N&&a[P]===u[_];P--,_--)p[_]=r[P],b[_]=i[P],o&&(w[_]=o[P]);for(y=new Map,j=new Array(_+1),m=_;m>=N;m--)T=u[m],d=y.get(T),j[m]=d===void 0?-1:d,y.set(T,m);for(d=N;d<=P;d++)T=a[d],m=y.get(T),m!==void 0&&m!==-1?(p[m]=r[d],b[m]=i[d],o&&(w[m]=o[d]),m=j[m],y.set(T,m)):i[d]();for(m=N;m<h;m++)m in p?(r[m]=p[m],i[m]=b[m],o&&(o[m]=w[m],o[m](m))):r[m]=st(v);r=r.slice(0,l=h),a=u.slice(0)}return r});function v(y){if(i[m]=y,o){const[j,p]=Se(m);return o[m]=p,s(u[m],j)}return s(u[m])}}}function Yo(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return Lt(()=>Ds(i)),()=>{const h=e()||[],d=h.length;return h[Dn],Te(()=>{if(d===0)return o!==0&&(Ds(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[un],r[0]=st(v=>(i[0]=v,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]=st(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(v){i[u]=v;const[y,j]=Se(h[u]);return l[u]=j,s(y,u)}}}function Mn(e,s){return Te(()=>e(s||{}))}function vs(){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:vs,deleteProperty:vs,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:vs,deleteProperty:vs}},ownKeys(e){return e.keys()}};function en(e){return(e=typeof e=="function"?e():e)?e:{}}function Xo(){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,Ae(o)):o}if(Va&&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:Xo.bind(n[d]=[m.get.bind(o)])}:m.value!==void 0?m:void 0;else{const v=n[d];v&&(m.get?v.push(m.get.bind(o)):m.value!==void 0&&v.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 sr(e,...s){if(Va&&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 nr(e){let s,n;const a=r=>{const i=ne.context;if(i){const[o,u]=Se();ne.count||(ne.count=0),ne.count++,(n||(n=e())).then(h=>{!ne.done&&Gt(i),ne.count--,u(()=>h.default),Gt()}),s=o}else if(!s){const[o]=Oo(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Ae(()=>(l=s())?Te(()=>{if(!i||ne.done)return l(r);const o=ne.context;Gt(i);const u=l(r);return Gt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Zo=0;function ec(){return ne.context?ne.getNextContextId():`cl-${Zo++}`}var ar=e=>`Stale read from <${e}>.`;function tc(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ae(Jo(()=>e.each,e.children,s||void 0))}function sc(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ae(Yo(()=>e.each,e.children,s||void 0))}function nc(e){const s=e.keyed,n=Ae(()=>e.when,void 0,void 0),a=s?n:Ae(n,void 0,{equals:(r,i)=>!r==!i});return Ae(()=>{const r=a();if(r){const i=e.children;return typeof i=="function"&&i.length>0?Te(()=>i(s?r:()=>{if(!Te(a))throw ar("Show");return n()})):i}return e.fallback},void 0,void 0)}function ac(e){const s=Ya(()=>e.children),n=Ae(()=>{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=Ae(()=>h()?void 0:u.when,void 0,void 0),m=u.keyed?d:Ae(d,void 0,{equals:(v,y)=>!v==!y});i=()=>h()||(m()?[o,d,u]:void 0)}return i});return Ae(()=>{const a=n()();if(!a)return e.fallback;const[r,i,l]=a,o=l.children;return typeof o=="function"&&o.length>0?Te(()=>o(l.keyed?i():()=>{var h;if(((h=Te(n)())==null?void 0:h[0])!==r)throw ar("Match");return i()})):o},void 0,void 0)}function rc(e){return e}var ic=["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"],lc=new Set(["className","value","readOnly","noValidate","formNoValidate","isMap","noModule","playsInline",...ic]),oc=new Set(["innerHTML","textContent","innerText","children"]),cc=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),uc=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 dc(e,s){const n=uc[e];return typeof n=="object"?n[s]?n.$:void 0:n}var hc=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),mc=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"]),fc={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},xc=e=>Ae(()=>e());function gc(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,v=1,y;for(;++m<r&&m<i&&!((y=h.get(s[m]))==null||y!==d+v);)v++;if(v>d-o){const j=s[l];for(;o<d;)e.insertBefore(n[o++],j)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var Vt="_$DX_DELEGATE";function rr(e,s,n,a={}){let r;return st(i=>{r=i,s===document?e():Bs(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function pc(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 ir(e,s=window.document){const n=s[Vt]||(s[Vt]=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,dr))}}function yc(e=window.document){if(e[Vt]){for(let s of e[Vt].keys())e.removeEventListener(s,dr);delete e[Vt]}}function Ls(e,s,n){mt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function jc(e,s,n,a){mt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function vc(e,s,n){mt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function lr(e,s){mt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function or(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 bc(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]||(Zn(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||(Zn(e,o,!0),n[o]=u)}return n}function wc(e,s,n){if(!s)return n?Ls(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 cr(e,s={},n,a){const r={};return a||nt(()=>r.children=Qt(e,s.children,r.children)),nt(()=>typeof s.ref=="function"&&ur(s.ref,e)),nt(()=>Sc(e,s,n,!0,r,!0)),r}function ur(e,s,n){return Te(()=>e(s,n))}function Bs(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Qt(e,s,a,n);nt(r=>Qt(e,s(),r,n),a)}function Sc(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=ea(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=ea(e,l,o,r[l],n,i,s)}}function Nc(e){let s,n;return!mt()||!(s=ne.registry.get(n=Cc()))?e():(ne.completed&&ne.completed.add(s),ne.registry.delete(n),s)}function mt(e){return!!ne.context&&!ne.done&&(!e||e.isConnected)}function Ec(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Zn(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 ea(e,s,n,a,r,i,l){let o,u,h,d,m;if(s==="style")return wc(e,n,a);if(s==="classList")return bc(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const v=s.slice(3);a&&e.removeEventListener(v,a,typeof a!="function"&&a),n&&e.addEventListener(v,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const v=s.slice(10);a&&e.removeEventListener(v,a,!0),n&&e.addEventListener(v,n,!0)}else if(s.slice(0,2)==="on"){const v=s.slice(2).toLowerCase(),y=hc.has(v);if(!y&&a){const j=Array.isArray(a)?a[0]:a;e.removeEventListener(v,j)}(y||n)&&(or(e,v,n,y),y&&ir([v]))}else if(s.slice(0,5)==="attr:")Ls(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")vc(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(h=oc.has(s))||!r&&((d=dc(s,e.tagName))||(u=lc.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(m)s=s.slice(5),u=!0;else if(mt(e))return n;s==="class"||s==="className"?lr(e,n):o&&!u&&!h?e[Ec(s)]=n:e[d||s]=n}else{const v=r&&s.indexOf(":")>-1&&fc[s.split(":")[0]];v?jc(e,v,s,n):Ls(e,cc[s]||s,n)}return n}function dr(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 Qt(e,s,n,a,r){const i=mt(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=gt(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=gt(e,n,a)}else{if(l==="function")return nt(()=>{let u=s();for(;typeof u=="function";)u=u();n=Qt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],h=n&&Array.isArray(n);if(hn(u,s,n,r))return nt(()=>n=Qt(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=gt(e,n,a),o)return n}else h?n.length===0?ta(e,u,a):gc(e,n,u):(n&&gt(e),ta(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=gt(e,n,a,s);gt(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 ta(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function gt(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 Cc(){return ne.getNextContextId()}var Ac="http://www.w3.org/2000/svg";function hr(e,s=!1){return s?document.createElementNS(Ac,e):document.createElement(e)}function Tc(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Xn();let i,l=!!ne.context;return Ln(()=>{l&&(Xn().user=l=!1),i||(i=Ja(r,()=>Ae(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,h]=Se(!1),d=()=>h(!0);st(m=>Bs(o,()=>u()?m():i(),null)),Lt(d)}else{const u=hr(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}),Bs(h,i),o.appendChild(u),e.ref&&e.ref(u),Lt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function kc(e,s){const n=Ae(e);return Ae(()=>{const a=n();switch(typeof a){case"function":return Te(()=>a(s));case"string":const r=mc.has(a),i=ne.context?Nc():hr(a,r);return cr(i,s,r),i}})}function Pc(e){const[,s]=sr(e,["component"]);return kc(()=>e.component,s)}var Ic=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()}},mr=class{constructor(e){this.generateIdentifier=e,this.kv=new Ic}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)}},_c=class extends mr{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 Dc(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 Lc(e,s){const n=Dc(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 Bt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Cs(e,s){return e.indexOf(s)!==-1}function sa(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Bc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Lc(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Mc=e=>Object.prototype.toString.call(e).slice(8,-1),fr=e=>typeof e>"u",Oc=e=>e===null,Wt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,mn=e=>Wt(e)&&Object.keys(e).length===0,rt=e=>Array.isArray(e),Rc=e=>typeof e=="string",Gc=e=>typeof e=="number"&&!isNaN(e),Uc=e=>typeof e=="boolean",Fc=e=>e instanceof RegExp,Jt=e=>e instanceof Map,Yt=e=>e instanceof Set,xr=e=>Mc(e)==="Symbol",qc=e=>e instanceof Date&&!isNaN(e.valueOf()),$c=e=>e instanceof Error,na=e=>typeof e=="number"&&isNaN(e),zc=e=>Uc(e)||Oc(e)||fr(e)||Gc(e)||Rc(e)||xr(e),Vc=e=>typeof e=="bigint",Kc=e=>e===1/0||e===-1/0,Hc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Qc=e=>e instanceof URL,gr=e=>e.replace(/\./g,"\\."),tn=e=>e.map(String).map(gr).join("."),Kt=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 pr=[$e(fr,"undefined",()=>null,()=>{}),$e(Vc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),$e(qc,"Date",e=>e.toISOString(),e=>new Date(e)),$e($c,"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(Yt,"set",e=>[...e.values()],e=>new Set(e)),$e(Jt,"map",e=>[...e.entries()],e=>new Map(e)),$e(e=>na(e)||Kc(e),"number",e=>na(e)?"NaN":e>0?"Infinity":"-Infinity",Number),$e(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),$e(Qc,"URL",e=>e.toString(),e=>new URL(e))];function $s(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var yr=$s((e,s)=>xr(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}),Wc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),jr=$s(Hc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Wc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function vr(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var br=$s(vr,(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)}),wr=$s((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)}),Jc=[br,yr,wr,jr],aa=(e,s)=>{const n=sa(Jc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=sa(pr,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},Sr={};pr.forEach(e=>{Sr[e.annotation]=e});var Yc=(e,s,n)=>{if(rt(s))switch(s[0]){case"symbol":return yr.untransform(e,s,n);case"class":return br.untransform(e,s,n);case"custom":return wr.untransform(e,s,n);case"typed-array":return jr.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=Sr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},yt=(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 Nr(e){if(Cs(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Cs(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Cs(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Xc=(e,s)=>{Nr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Yt(e))e=yt(e,+a);else if(Jt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=yt(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(Nr(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(rt(a)){const o=+l;a=a[o]}else if(Wt(a))a=a[l];else if(Yt(a)){const o=+l;a=yt(a,o)}else if(Jt(a)){if(i===s.length-2)break;const u=+l,h=+s[++i]==0?"key":"value",d=yt(a,u);switch(h){case"key":a=d;break;case"value":a=a.get(d);break}}}const r=s[s.length-1];if(rt(a)?a[+r]=n(a[+r]):Wt(a)&&(a[r]=n(a[r])),Yt(a)){const i=yt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Jt(a)){const i=+s[s.length-2],l=yt(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(!rt(e)){Bt(e,(i,l)=>xn(i,s,[...n,...Kt(l)]));return}const[a,r]=e;r&&Bt(r,(i,l)=>{xn(i,s,[...n,...Kt(l)])}),s(a,n)}function Zc(e,s,n){return xn(s,(a,r)=>{e=fn(e,r,i=>Yc(i,a,n))}),e}function eu(e,s){function n(a,r){const i=Xc(e,Kt(r));a.map(Kt).forEach(l=>{e=fn(e,l,()=>i)})}if(rt(s)){const[a,r]=s;a.forEach(i=>{e=fn(e,Kt(i),()=>e)}),r&&Bt(r,n)}else Bt(s,n);return e}var tu=(e,s)=>Wt(e)||rt(e)||Jt(e)||Yt(e)||vr(e,s);function su(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function nu(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 Er=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=zc(e);if(!o){su(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!tu(e,n)){const y=aa(e,n),j=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,j),j}if(Cs(i,e))return{transformedValue:null};const u=aa(e,n),h=(u==null?void 0:u.value)??e,d=rt(h)?[]:{},m={};Bt(h,(y,j)=>{if(j==="__proto__"||j==="constructor"||j==="prototype")throw new Error(`Detected property ${j}. This is a prototype pollution risk, please remove it from your object.`);const p=Er(y,s,n,a,[...r,j],[...i,e],l);d[j]=p.transformedValue,rt(p.annotations)?m[j]=p.annotations:Wt(p.annotations)&&Bt(p.annotations,(b,w)=>{m[gr(j)+"."+w]=b})});const v=mn(m)?{transformedValue:d,annotations:u?[u.type]:void 0}:{transformedValue:d,annotations:u?[u.type,m]:m};return o||l.set(e,v),v};function Cr(e){return Object.prototype.toString.call(e).slice(8,-1)}function ra(e){return Cr(e)==="Array"}function au(e){if(Cr(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function ru(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(ra(e))return e.map(r=>gn(r,s));if(!au(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(ra(s.props)&&!s.props.includes(i))return r;const l=e[i],o=gn(l,s);return ru(r,i,o,e,s.nonenumerable),r},{})}var ve=class{constructor({dedupe:e=!1}={}){this.classRegistry=new _c,this.symbolRegistry=new mr(s=>s.description??""),this.customTransformerRegistry=new Bc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Er(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=nu(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=Zc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=eu(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)}};ve.defaultInstance=new ve;ve.serialize=ve.defaultInstance.serialize.bind(ve.defaultInstance);ve.deserialize=ve.defaultInstance.deserialize.bind(ve.defaultInstance);ve.stringify=ve.defaultInstance.stringify.bind(ve.defaultInstance);ve.parse=ve.defaultInstance.parse.bind(ve.defaultInstance);ve.registerClass=ve.defaultInstance.registerClass.bind(ve.defaultInstance);ve.registerSymbol=ve.defaultInstance.registerSymbol.bind(ve.defaultInstance);ve.registerCustom=ve.defaultInstance.registerCustom.bind(ve.defaultInstance);ve.allowErrorProps=ve.defaultInstance.allowErrorProps.bind(ve.defaultInstance);var Ar=ve.serialize,iu=ve.stringify;function lu(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function ou(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function cu({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function uu({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function du(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var hu=(e,s=!1)=>{const{json:n}=Ar(e);return JSON.stringify(n,null,s?2:void 0)},bs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,mu=(e,s)=>e.queryHash.localeCompare(s.queryHash),Tr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,fu=(e,s)=>bs(e)===bs(s)?Tr(e,s):bs(e)>bs(s)?1:-1,xu={status:fu,"query hash":mu,"last updated":Tr},ws=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,kr=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,gu=(e,s)=>ws(e)===ws(s)?kr(e,s):ws(e)>ws(s)?1:-1,pu={status:gu,"last updated":kr},yu=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),ju=()=>{const[e,s]=Se("dark");return Wa(()=>{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),Lt(()=>n.removeEventListener("change",a))}),e},Ut=(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,Ut(a.get(r),i,n)),a}if(e instanceof Set){const a=Ut(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]=Ut(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]=Ut(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},Pr=(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)},jt,Xt,Zt,es,ot,ts,vt,bt,wt,St,Nt,ss,Et,ns,oa,vu=(oa=class{constructor(e){fe(this,jt);fe(this,Xt);fe(this,Zt);fe(this,es);fe(this,ot,!1);fe(this,ts);fe(this,vt);fe(this,bt);fe(this,wt);fe(this,St);fe(this,Nt);fe(this,ss);fe(this,Et);fe(this,ns);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,jt,Se(s)),he(this,Zt,n),he(this,es,a),he(this,Xt,r),he(this,ts,h),he(this,vt,d),he(this,bt,Se(i)),he(this,wt,Se(l)),he(this,St,Se(o)),he(this,Nt,Se(u)),he(this,ss,Se(m))}setButtonPosition(e){te(this,bt)[1](e)}setPosition(e){te(this,wt)[1](e)}setInitialIsOpen(e){te(this,St)[1](e)}setErrorTypes(e){te(this,Nt)[1](e)}setClient(e){te(this,jt)[1](e)}mount(e){if(te(this,ot))throw new Error("Devtools is already mounted");const s=rr(()=>{const n=this,[a]=te(this,bt),[r]=te(this,wt),[i]=te(this,St),[l]=te(this,Nt),[o]=te(this,ss),[u]=te(this,jt);let h;return te(this,Et)?h=te(this,Et):(h=nr(()=>Promise.resolve().then(()=>require("./LNWAZHJI-C5ZKFd7E.cjs"))),he(this,Et,h)),Pr(te(this,ts),te(this,vt)),Mn(h,On({get queryFlavor(){return te(n,Zt)},get version(){return te(n,es)},get onlineManager(){return te(n,Xt)},get shadowDOMTarget(){return te(n,vt)}},{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,ot,!0),he(this,ns,s)}unmount(){var e;if(!te(this,ot))throw new Error("Devtools is not mounted");(e=te(this,ns))==null||e.call(this),he(this,ot,!1)}},jt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,es=new WeakMap,ot=new WeakMap,ts=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,Nt=new WeakMap,ss=new WeakMap,Et=new WeakMap,ns=new WeakMap,oa),Ct,as,rs,is,ct,ls,At,Tt,kt,Pt,It,os,_t,Dt,cs,ca,bu=(ca=class{constructor(e){fe(this,Ct);fe(this,as);fe(this,rs);fe(this,is);fe(this,ct,!1);fe(this,ls);fe(this,At);fe(this,Tt);fe(this,kt);fe(this,Pt);fe(this,It);fe(this,os);fe(this,_t);fe(this,Dt);fe(this,cs);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:h,shadowDOMTarget:d,onClose:m,hideDisabledQueries:v}=e;he(this,Ct,Se(s)),he(this,rs,n),he(this,is,a),he(this,as,r),he(this,ls,h),he(this,At,d),he(this,Tt,Se(i)),he(this,kt,Se(l)),he(this,Pt,Se(o)),he(this,It,Se(u)),he(this,os,Se(v)),he(this,_t,Se(m))}setButtonPosition(e){te(this,Tt)[1](e)}setPosition(e){te(this,kt)[1](e)}setInitialIsOpen(e){te(this,Pt)[1](e)}setErrorTypes(e){te(this,It)[1](e)}setClient(e){te(this,Ct)[1](e)}setOnClose(e){te(this,_t)[1](()=>e)}mount(e){if(te(this,ct))throw new Error("Devtools is already mounted");const s=rr(()=>{const n=this,[a]=te(this,Tt),[r]=te(this,kt),[i]=te(this,Pt),[l]=te(this,It),[o]=te(this,os),[u]=te(this,Ct),[h]=te(this,_t);let d;return te(this,Dt)?d=te(this,Dt):(d=nr(()=>Promise.resolve().then(()=>require("./MWZ6AO7Z-CwnJeRzf.cjs"))),he(this,Dt,d)),Pr(te(this,ls),te(this,At)),Mn(d,On({get queryFlavor(){return te(n,rs)},get version(){return te(n,is)},get onlineManager(){return te(n,as)},get shadowDOMTarget(){return te(n,At)}},{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,ct,!0),he(this,cs,s)}unmount(){var e;if(!te(this,ct))throw new Error("Devtools is not mounted");(e=te(this,cs))==null||e.call(this),he(this,ct,!1)}},Ct=new WeakMap,as=new WeakMap,rs=new WeakMap,is=new WeakMap,ct=new WeakMap,ls=new WeakMap,At=new WeakMap,Tt=new WeakMap,kt=new WeakMap,Pt=new WeakMap,It=new WeakMap,os=new WeakMap,_t=new WeakMap,Dt=new WeakMap,cs=new WeakMap,ca);function wu(e){const s=U.useQueryClient(e.client),n=we.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u,hideDisabledQueries:h}=e,[d]=we.useState(new vu({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 we.useEffect(()=>{d.setClient(s)},[s,d]),we.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),we.useEffect(()=>{r&&d.setPosition(r)},[r,d]),we.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),we.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),we.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{dir:"ltr",className:"tsqd-parent-container",ref:n})}function Su(e){const s=U.useQueryClient(e.client),n=we.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i,hideDisabledQueries:l}=e,[o]=we.useState(new bu({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 we.useEffect(()=>{o.setClient(s)},[s,o]),we.useEffect(()=>{o.setOnClose(e.onClose??(()=>{}))},[e.onClose,o]),we.useEffect(()=>{o.setErrorTypes(a||[])},[a,o]),we.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 Nu=process.env.NODE_ENV!=="development"?function(){return null}:wu;process.env.NODE_ENV;const Eu=()=>{F.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),F.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),F.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"}),F.registerChaiFeatureFlag("enable-old-page-manager",{description:"Switch to older page manager"}),F.registerChaiFeatureFlag("enable-site-settings",{description:"Site settings"})},Cu=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:O.GET_COLLECTIONS})})},Au=()=>{const{data:e}=ke(),{data:s}=We(),{data:n}=Ve(),a=le(),r=ee(),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:O.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}}})})},Ir=()=>{const e=Gs();return x.useCallback(({pageId:s})=>{e(s)},[e])},Tu=x.createContext(null),sn={didCatch:!1,error:null};class ku 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&&Pu(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 Pu(){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 Iu=()=>{const e=us(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>{const r=a.map(async l=>n(e,{action:O.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:[O.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")}})},_u=()=>{const e=us(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[O.GET_ASSETS]}),W.toast.success("Asset deleted successfully")},onError:()=>{W.toast.error("Failed to delete asset")}})},Du=()=>{const e=us(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[O.GET_ASSETS]}),W.toast.success("Asset updated successfully")},onError:()=>{W.toast.error("Failed to update asset")}})};function Lu({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 j=Math.floor(a/2);let p=Math.max(1,e-j),b=Math.min(s,e+j);b-p+1<a&&(p===1?b=Math.min(s,p+a-1):b===s&&(p=Math.max(1,b-a+1)));const w=[];p>1&&(w.push(1),p>2&&w.push("..."));for(let N=p;N<=b;N++)w.push(N);return b<s&&(b<s-1&&w.push("..."),w.push(s)),w},[e,s,a]),h=j=>{j!==e&&j>=1&&j<=s&&(n(j),o(String(j)))},d=()=>{e>1&&h(e-1)},m=()=>{e<s&&h(e+1)},v=()=>{const j=Number(l);!isNaN(j)&&j>=1&&j<=s&&h(j)},y=j=>{j.key==="Enter"&&v()};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((j,p)=>{if(j==="...")return t.jsx("span",{className:"px-2 text-muted-foreground",children:"..."},`ellipsis-${p}`);const b=j,w=b===e;return t.jsx(c.Button,{variant:w?"default":"outline",size:"sm",onClick:()=>h(b),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:b},b)})}),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:j=>{const p=j.target.value.replace(/[^\d]/g,"");o(p)},onKeyDown:y,className:"h-8 w-16 px-2 py-1"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:v,disabled:l===""||Number(l)<1||Number(l)>s,children:"Go"})]})]})}const Bu=(e={})=>{const s=us(),n=ee(),{search:a,page:r=1,limit:i=30}=e;return U.useQuery({queryKey:[O.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:O.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},Mu=e=>{const s=us(),n=ee();return U.useQuery({queryKey:[O.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:O.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Ou(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 ia(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 la(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 Ru=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,v,y;const{data:i,isLoading:l,isError:o}=Mu(e||""),[u,h]=x.useState(""),d=async(j,p)=>{try{await navigator.clipboard.writeText(j),W.toast.success(`${p} copied to clipboard`)}catch(b){W.toast.error(`Failed to copy ${p}`,{description:b==null?void 0:b.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:((v=i.metadata)==null?void 0:v.format)||i.type,capitalize:!0},{label:"Size",value:Ou(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:ia(i.createdAt)},{label:"Updated",value:ia(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(j=>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:j.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(j.capitalize?" capitalize":""),children:j.value}),j.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(j.value,j.label),children:t.jsx(S.Link,{className:"h-3 w-3"})})]})]},j.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((j,p)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:j.name}),t.jsxs("div",{className:"text-gray-500",children:["(",j.slug,")"]})]},p))})]}),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:j=>h(j.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||!la(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!la(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"})})]})]})]})]})},Gu=x.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs"))),Uu=25*1024*1024,Fu=({isUpdatingAsset:e,allowedTypes:s,uploadAssets:n,isUploadingAsset:a,onUploaded:r})=>{const[i,l]=x.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});x.useEffect(()=>{localStorage.setItem("chai_optimize_images",i.toString())},[i]);const o=e||a,u=x.useCallback(async y=>{try{const j=y;if(!j.every(N=>N.type.startsWith("image/")))return W.toast.error("Invalid file type. Please upload a valid file."),Promise.reject(new Error("Invalid file type"));const p=j.map(async N=>{let P=N;return N.type.startsWith("image/")&&(P=await Ca(N)),new Promise((_,T)=>{const A=new FileReader;A.readAsDataURL(P),A.onload=async()=>{_({file:A.result,folderId:void 0,name:N.name,optimize:i})},A.onerror=()=>T(null)})}),b=await Promise.all(p),w=await n(b);return(w==null?void 0:w.length)===1&&r(w[0]),w}catch(j){return Promise.reject(j)}},[n,i,r]),h=y=>{const j=[];let p=0;return y.forEach(b=>{b.size>Uu?p++:j.push(b)}),p>0&&W.toast.error(`${p===1&&y.length===1?"File":p+(p===1?" file":" files")} exceed the maximum size limit of 10MB.`),f.isEmpty(j)?[]:u(j)},{getRootProps:d,getInputProps:m,isDragActive:v}=Rr.useDropzone({onDrop:h,accept:{"image/*":s.includes("image")?[]:[]},disabled:e||a,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 ${o?"pointer-events-none bg-gray-100 opacity-90":"bg-gray-100 hover:border-black/50 hover:bg-gray-100"}`,children:t.jsxs("div",{...d(),className:F.mergeClasses("flex h-max w-full cursor-pointer flex-col justify-center rounded-lg text-center",o?"items-start":"items-center",v?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...m()}),o?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.jsx("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("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:i?"text-indigo-600":"text-gray-400",children:i?"On":"Off"})]}),t.jsx(c.Switch,{checked:i,onCheckedChange:y=>{l(y)},onClick:y=>{y.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 ${i?"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 _r({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,v]=x.useState(null),[y,j]=x.useState({show:!1,file:""}),[p,b]=x.useState(!1),[w,N]=x.useState(a?"details":"grid"),[P,_]=x.useState(""),[T,A]=x.useState(""),[z,X]=x.useState(1),[V]=x.useState(30),[L,R]=x.useState([]);x.useEffect(()=>{a&&(u(a),N("details"))},[a]),x.useEffect(()=>{const B=setTimeout(()=>{_(T),X(1)},300);return()=>clearTimeout(B)},[T]);const{data:q,isLoading:M}=Bu({search:P.toLowerCase().trim(),page:z,limit:V}),J=(q==null?void 0:q.assets)||[],H=(q==null?void 0:q.total)||0,ae=Math.ceil(H/V);x.useEffect(()=>{M||ae<=0||X(B=>B>ae?ae:B<1?1:B)},[M,ae]);const xe=(J==null?void 0:J.length)>0,{mutate:ge}=_u(),{mutateAsync:ce,isPending:E}=Iu(),{mutate:g,isPending:I}=Du(),G=x.useCallback(B=>{const se=Math.min(Math.max(1,B),Math.max(1,ae));se!==z&&X(se)},[ae,z]),C=B=>{A(B.target.value)},D=x.useCallback(B=>{R(se=>f.find(se,{id:B.id})?[]:[B])},[!1]),Q=x.useCallback(()=>{R([])},[]),$=B=>{(B==null?void 0:B.length)!==0&&(s(f.pick(f.first(B||L),["id","url","width","height","description"])),e())},Y=async B=>{d(B)},oe=async()=>{h&&(v(h==null?void 0:h.id),await ge(h.id,{onSuccess:()=>{v(null),d(null)},onError:()=>{v(null)}}),d(null))},K=B=>{u(B.id),N("details")},re=async(B,se)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";se?(await ce([{file:B,folderId:void 0,name:y.name||"",optimize:Ee}]),j({show:!1,file:""})):(await g({id:y.id||"",file:B}),j({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},me=x.useCallback(B=>{R([B])},[]),pe=x.useCallback(B=>{G(B)},[G]);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:I,isUploadingAsset:E,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 ${T.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:C,value:T,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:()=>Q(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>$(L),disabled:L.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:M?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"})]}):!M&&!xe?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:J==null?void 0:J.map(B=>t.jsxs("div",{className:F.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===B.id)?"border-blue-500":"hover:border-black/90",m&&(h==null?void 0:h.id)===B.id?"pointer-events-none opacity-50":"",m===B.id?"pointer-events-none opacity-50":""),onClick:()=>D(B),onDoubleClick:()=>$([B]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===B.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,B.type==="image"?t.jsx("img",{src:`${B.thumbnailUrl||"/placeholder.svg"}?v=${(B==null?void 0:B.updatedAt)||B.createdAt}`,alt:B.name,className:`h-full min-h-[80px] w-full object-contain ${L.some(se=>se.id===B.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"}),B.thumbnailUrl&&t.jsx("img",{src:`${B.thumbnailUrl||"/placeholder.svg"}?v=${(B==null?void 0:B.updatedAt)||B.createdAt}`,alt:B.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:B.name,children:B.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((B==null?void 0:B.size)||0)})})]}),!L.some(se=>se.id===B.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(B)},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(B.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(),j({id:B.id,show:!0,file:B.url,name:B.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(),Y(B)},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===B.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})})]},B.id))})}),ae>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 border-t bg-white p-4",children:t.jsx(ku,{fallback:t.jsx("div",{className:"text-red-500",children:"Error loading pagination"}),children:t.jsx(Lu,{currentPage:z,totalPages:ae,onPageChange:pe,pageRangeDisplayed:3,showPageInput:!0})})})]})]}):t.jsx(Ru,{assetId:o||a||"",onBack:()=>{N("grid"),u(null)},onEdit:B=>{j({id:B.id,show:!0,file:B.url,name:B.name})},onSave:async B=>{if(o){b(!0);try{const se=J.find(Ee=>Ee.id===o);se&&await g(f.merge(se,{description:B}))}finally{b(!1)}}},isSaving:p})]}),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(Gu,{imageUrl:y.file,onSave:re,onClose:()=>j({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:oe,children:"Delete"})]})]})})]})}const qu=Object.freeze(Object.defineProperty({__proto__:null,default:_r},Symbol.toStringTag,{value:"Module"})),Ms=({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 j=Array.isArray(y)?y[0]:y;j!=null&&j.url&&n(f.pick(j,["url","id"])),o(!1)},m=()=>{n({url:"",id:""})},v=(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:[v?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:v?t.jsx(S.X,{className:"h-4 w-4"}):t.jsx(S.Trash2,{className:"h-4 w-4"})}),!v&&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(_r,{close:h,onSelect:d,mode:"image",assetId:e})})]})})]})},$u=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),zu=()=>{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(Ms,{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(Ms,{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"})})]})]})},Vu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),Ku=()=>{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=p=>s(b=>({...b,[p.target.name]:p.target.value})),d=()=>{const{platform:p,url:b,customName:w}=r;if(!b.trim()||!p)return;const N=p==="other"?w:p;N.trim()&&(a(P=>[...P,{platform:N,url:b,isCustom:p==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=p=>a(b=>b.filter((w,N)=>N!==p)),v=()=>i({isOpen:!1,platform:"",url:"",customName:""}),y=()=>{o(!0);const p={};n.forEach(w=>{p[w.platform.toLowerCase().replace(/\s+/g,"_")]=w.url});const b={...e,socialLinks:p};setTimeout(()=>{o(!1),console.log("Contact & Social settings saved:",b),s({contactEmail:"",contactPhone:"",contactAddress:""}),a([]),i({isOpen:!1,platform:"",url:"",customName:""})},1e3)},j=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(p=>({...p,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:p=>i(b=>({...b,platform:p.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",children:[t.jsx("option",{value:"",children:"Select platform"}),u.map(p=>t.jsx("option",{value:p.value,children:p.label},p.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:p=>i(b=>({...b,customName:p.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:p=>i(b=>({...b,url:p.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:v,className:"flex-1",children:"Cancel"})]})]}),n.length>0&&t.jsx("div",{className:"space-y-2",children:n.map((p,b)=>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:p.platform}),t.jsx("p",{className:"max-w-xs truncate text-xs text-gray-500",children:p.url})]}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m(b),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},b))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:y,disabled:!j||l,className:"w-full",children:l?"Saving...":"Save Contact & Social Settings"})})]})]})},Hu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),Qu=()=>{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:j,value:p}=y.target;s(b=>({...b,[j]:p}))},h=()=>{r.trim()&&(a(y=>[...y,{id:Date.now().toString(),content:r}]),i(""))},d=y=>{a(j=>j.filter(p=>p.id!==y))},m=()=>{o(!0);const y={...e,customTrackingScripts:n.map(j=>j.content)};setTimeout(()=>{o(!1),console.log("Analytics & Tracking settings saved:",y),s({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),a([])},1e3)},v=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:!v||l,className:"w-full",children:l?"Saving...":"Save Settings"})})]})]})},Wu=()=>{Ns("branding",{label:"Branding",button:$u,panel:zu}),Ns("contact-social",{label:"Contact & Social",button:Vu,panel:Ku}),Ns("analytics-tracking",{label:"Analytics & Tracking",button:Hu,panel:Qu})},Ju=x.lazy(()=>Promise.resolve().then(()=>qu));Eu();Gr.loadWebBlocks();F.registerChaiTopBar(eo);Do();Wu();F.registerChaiMediaManager(Ju);F.registerChaiSaveToLibrary(Ci);const Yu=e=>{const s=x.useRef([]),[n]=Pe(),a=n.get("page"),{data:r}=ke(),{data:i={role:"",permissions:null}}=Ua();ao(),di();const{data:l,isFetching:o}=Na(),{blocks:u}=no(l),{data:h}=Ce(),{mutateAsync:d}=xa(),m=to(),{onSave:v}=ro(),{getPartialBlocks:y,getPartialBlockBlocks:j}=io(),{aiContext:p,setAiContext:b}=yn(),{mutateAsync:w}=Ti(),[N,P]=x.useState(!1),{data:_}=Ve(),T=Ye(),{data:A}=bn(),{data:z}=Cu(),{mutateAsync:X}=Au(),V=Ir();Zr(),x.useEffect(()=>{const M=()=>{document.hidden?P(!0):P(!1)};return window.addEventListener("visibilitychange",M),()=>window.removeEventListener("visibilitychange",M)},[]),s.current=u;const L=x.useMemo(()=>{const M={};return i&&(M.permissions=f.get(i,"permissions",null),M.role=f.get(i,"role","user")),M},[i]),R=x.useCallback(async(M,J)=>await w({pageType:M,query:J}),[w]),q=x.useMemo(()=>f.get(_,"theme",{})||{},[_]);return t.jsxs(t.Fragment,{children:[t.jsx(F.ChaiBuilderEditor,{gotoPage:V,collections:z??[],getBlockAsyncProps:X,pageExternalData:A,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:T,languages:(_==null?void 0:_.languages)||[],brandingOptions:(_==null?void 0:_.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!N&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:j,getPartialBlocks:y,blocks:o?[]:u,theme:f.cloneDeep(q),pageTypes:h,searchPageTypeItems:R,saveAiContextCallback:async M=>{if(!a)return!0;const J=s.current,H={_type:"@chai/ai-context",_value:f.isString(M)?M:""},ae=[...J,H];return await v({page:a,blocks:ae}),b(M),!0},aiContext:p,askAiCallBack:m,onSave:async({blocks:M,theme:J,needTranslations:H})=>{if(!a)return!0;s.current=M;const ae={_type:"@chai/ai-context",_value:f.isString(p)?p:""},xe=[...M,ae];return await v({page:a,blocks:xe,needTranslations:H}),s.current=xe,f.isEqual(J,q)||await d({settings:{theme:J}}),!0},themePanelComponent:Oi,...L}),t.jsxs("div",{children:[t.jsx(xi,{}),t.jsx(gi,{})]})]})},Xu=new U.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Zu=e=>{const{isLoggedIn:s}=Oe(),[,n]=ga(),[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:Xu,children:[s?t.jsx(Yu,{...e}):t.jsx(uo,{}),t.jsx(Nu,{})]}):t.jsx("div",{})},ed=()=>{const{savePageAsync:e}=F.useSavePage(),s=U.useQueryClient();return x.useCallback(async()=>{await e(),s.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]})},[e])},td=()=>{const e=le(),s=ee(),{data:n}=We(),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:O.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[O.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},sd=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ma();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=Zu;exports.ChaiBuilderPagesRealtime=ba;exports.Dynamic=Pc;exports.For=tc;exports.ImagePicker=Ms;exports.Index=sc;exports.LanguageSwitcher=_n;exports.Match=rc;exports.NestedPathSelector=He;exports.PermissionChecker=Me;exports.Portal=Tc;exports.Show=nc;exports.SmartJsonInput=ln;exports.Switch=ac;exports.addEventListener=or;exports.batch=Ro;exports.className=lr;exports.clearDelegatedEvents=yc;exports.convertRemToPixels=yu;exports.createComponent=Mn;exports.createComputed=Qa;exports.createContext=$o;exports.createEffect=Ln;exports.createMemo=Ae;exports.createRenderEffect=nt;exports.createRoot=st;exports.createSignal=Se;exports.createUniqueId=ec;exports.delegateEvents=ir;exports.deleteNestedDataByPath=Ft;exports.displayValue=hu;exports.getMutationStatusColor=uu;exports.getPreferredColorScheme=ju;exports.getQueryStatusColor=cu;exports.getQueryStatusColorByLabel=du;exports.getQueryStatusLabel=lu;exports.getSidedProp=ou;exports.insert=Bs;exports.memo=xc;exports.mergeProps=On;exports.mutationSortFns=pu;exports.on=Go;exports.onCleanup=Lt;exports.onMount=Wa;exports.registerChaiSiteSetting=Ns;exports.registerLoginComponent=co;exports.serialize=Ar;exports.setAttribute=Ls;exports.sortFns=xu;exports.splitProps=sr;exports.spread=cr;exports.stringify=iu;exports.template=pc;exports.untrack=Te;exports.updateNestedDataByPath=Ut;exports.use=ur;exports.useActivePage=We;exports.useBuilderPageData=bn;exports.useChaiAuth=Oe;exports.useChaiFetch=sd;exports.useChaiUserInfo=Ke;exports.useContext=zo;exports.useCurrentPage=ke;exports.useFallbackLang=Ye;exports.useFetch=ee;exports.useGotoPage=Ir;exports.useLanguagePages=Ge;exports.usePageTypes=Ce;exports.useReloadPage=ed;exports.useTransition=qo;exports.useUpdateActivePageMetadata=td;exports.useUserRoleAndPermissions=Ua;exports.useWebsitePages=ht;exports.useWebsiteSetting=Ve;
13
+ `),q=e.substring(0,A)+R+e.substring(z);s(q),setTimeout(()=>{T.selectionStart=A,T.selectionEnd=A+R.length},0)}}else{const X=e.substring(0,A)+" "+e.substring(z);s(X),setTimeout(()=>{T.selectionStart=T.selectionEnd=A+2},0)}}};x.useEffect(()=>{const _=Qn(e);if(_.isValid)if(v(null),_.parsed){const T=wo(_.parsed,o);j(T)}else j("");else v(_.error),j("")},[e,o]);const N=()=>{const _=Qn(e);if(_.isValid&&_.parsed){const T=bo(_.parsed,_.placeholders);s(T)}},P=()=>{m!=null&&m.position&&p.current&&(p.current.focus(),p.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:_=>u&&u(_,l)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:N,disabled:!e.trim()||n||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:p,id:l,name:l,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:b,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}},So=(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}},qa=()=>{const{t:e}=F.useTranslation(),[,s]=F.useSidebarActivePanel(),{data:n}=ke(),{data:a}=vn(),{data:r,isFetching:i}=po(),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=Aa(h),{selectedLang:m,fallbackLang:v}=F.useLanguages(),y=m||v,[j,p]=x.useState(!1),[b,w]=x.useState(!1),[N,P]=x.useState(!1),[_,T]=x.useState(null),[A,z]=x.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",metaOther:"{}",...l}),X=x.useRef({}),{mutate:V,isPending:L}=bn(),R=L||j||b,{hasPermission:q}=F.usePermissions(),M=q(be.EDIT_SEO);x.useEffect(()=>{if(!i&&l&&u){const g={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",metaOther:"",...l};z(g),X.current[y]=g}},[i,l,y,u]),x.useEffect(()=>{const g=I=>{const{fromLang:G,toLang:C,switchHandler:D}=I.detail,Q=X.current[y];(Q?!f.isEqual(Q,A):!1)?(T({fromLang:G,toLang:C,switchHandler:D}),P(!0)):D()};return window.addEventListener("seo-language-switch-check",g),()=>{window.removeEventListener("seo-language-switch-check",g)}},[u,A,y]);const J=async()=>{if(!(!d||!y))try{p(!0);const g=$t(d,y),I={...A,keyword:f.get(g,"seo.keyword",""),title:f.get(g,"seo.title",""),description:f.get(g,"seo.description",""),cononicalUrl:f.get(g,"seo.canonicalUrl",""),noIndex:f.get(g,"seo.noIndex",!1),noFollow:f.get(g,"seo.noFollow",!1),ogTitle:f.get(g,"seo.ogTitle",""),ogDescription:f.get(g,"seo.ogDescription","")};z(I),W.toast.success(e("SEO fields reset to defaults"))}catch(g){W.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",g)}finally{p(!1)}},H=async()=>{if(!(!d||!y))try{w(!0);const g=$t(d,y),I={...A,jsonLD:f.get(g,"seo.jsonLD","")};z(I),W.toast.success(e("JSON-LD reset to default"))}catch(g){W.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",g)}finally{w(!1)}},ae=async()=>{if(!(!d||!y))try{p(!0);const g=$t(d,y),I={...A,ogTitle:f.get(g,"seo.ogTitle",""),ogDescription:f.get(g,"seo.ogDescription",""),ogImage:f.get(g,"seo.ogImage",""),ogImageId:f.get(g,"seo.ogImageId",""),metaOther:f.get(g,"seo.metaOther","{}")};z(I),W.toast.success(e("Meta Tag fields reset to defaults"))}catch(g){W.toast.error(e("Failed to reset Meta Tag fields")),console.error("Reset Meta Tag error:",g)}finally{p(!1)}},xe=async()=>{V({id:r==null?void 0:r.id,seo:A,primaryPage:u},{onSuccess:()=>{console.log("SEO & JSON-LD updated successfully",A),X.current[y]=A,W.toast.success("SEO & JSON-LD updated successfully")}})},ge=(g,I)=>{const G=document.getElementById(I);if(G){const{value:C,newCursorPos:D}=So(G,g);o.current={id:I,position:D},G.tagName.toLowerCase()==="input"?(G.value=C,z(Y=>({...Y,[G.name]:C})),G.focus(),G.setSelectionRange(D,D),[0,10,50,100,200].forEach(Y=>{setTimeout(()=>{const oe=document.getElementById(I);oe&&(oe.focus(),oe.setSelectionRange(D,D))},Y)})):(z($=>({...$,[G.name]:C})),requestAnimationFrame(()=>{const $=document.getElementById(I);$&&($.focus(),$.setSelectionRange(D,D),setTimeout(()=>{const Y=document.getElementById(I);Y&&(Y.focus(),Y.setSelectionRange(D,D))},50))}))}},ce=g=>{const I={...A,[g.target.name]:g.target.name==="noIndex"||g.target.name==="noFollow"?g.target.checked:g.target.value};z(I)},E=g=>I=>{f.isEmpty(I.fieldValue)||ce({target:{name:g,value:typeof I.fieldValue=="string"?I.fieldValue.replace(/^"(.*)"$/,"$1"):I.fieldValue}}),I.error&&W.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:I.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!M&&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(In,{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 grid-cols-3",children:[t.jsx(c.TabsTrigger,{value:"seo",children:e("SEO")}),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:[M&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:J,disabled:R||!M||!d,children:e(j?"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")}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:A.keyword,onChange:ce,disabled:R||!M,placeholder:e("Enter keyword"),readOnly:!M})]}),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(xt,{keyword:A.keyword,onComplete:E("title"),field:"title"}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:A.title,onChange:ce,disabled:R||!M,placeholder:e("Enter SEO title"),readOnly:!M})]}),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(xt,{keyword:A.keyword,onComplete:E("description"),field:"description"}),M&&t.jsx(He,{data:a??{},onSelect:g=>ge(g,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:A.description,onChange:ce,disabled:R||!M,placeholder:e("Enter SEO description"),readOnly:!M})]}),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")}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:A.canonicalUrl,onChange:ce,disabled:R||!M,placeholder:e("Enter Canonical URL"),readOnly:!M})]}),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:A.noIndex,onChange:ce,disabled:R||!M,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:A.noFollow,onChange:ce,disabled:R||!M,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:"opengraph",children:t.jsxs("div",{className:"space-y-4",children:[M&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:ae,disabled:R||!M||!d,children:e(j?"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(xt,{keyword:A.keyword,onComplete:E("ogTitle"),field:"ogTitle"}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:A.ogTitle,onChange:ce,disabled:R||!M,placeholder:e("Enter OG title"),readOnly:!M})]}),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(xt,{keyword:A.keyword,onComplete:E("ogDescription"),field:"ogDescription"}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>ge(g,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:A.ogDescription,onChange:ce,disabled:R||!M,placeholder:e("Enter OG description"),readOnly:!M})]}),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")}),M&&t.jsx(He,{dataType:"value",data:a??{},onSelect:g=>{z({...A,ogImage:`{{${g}}}`,ogImageId:""})}})]}),t.jsx(Ms,{assetId:A.ogImageId,assetUrl:A.ogImage,onChange:g=>{z({...A,ogImage:g.url,ogImageId:g.id})},disabled:R||!M,placeholder:e("Select OG image"),className:"mb-2"})]}),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(xt,{keyword:A.keyword,onComplete:E("metaOther"),field:"metaOther"})})]}),t.jsx(ln,{id:"metaOther",value:A.metaOther,onChange:g=>{ce({target:{name:"metaOther",value:g}})},placeholder:e("Enter Meta Tags JSON"),disabled:R||!M,readOnly:!M,pageData:a||{},rows:8,handleFieldInsert:ge})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[M&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:H,disabled:R||!M||!d,children:e(b?"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(xt,{keyword:A.keyword,onComplete:E("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(ln,{id:"jsonLD",value:A.jsonLD,onChange:g=>{ce({target:{name:"jsonLD",value:g}})},placeholder:e("Enter JSON-LD"),disabled:R||!M,readOnly:!M,pageData:a||{},rows:12,handleFieldInsert:ge})]})]})})]})})]}),M&&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(A.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:xe,disabled:!Wn(A==null?void 0:A.jsonLD)||(X.current[y]?f.isEqual(X.current[y],A):!1)||R||!M,children:e(L?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(jo,{isOpen:N,onClose:()=>{P(!1),T(null)},onSave:async()=>{_&&(await xe(),_.switchHandler(),P(!1),T(null))},onDiscard:()=>{if(_){const g=X.current[y];g&&z(g),_.switchHandler(),P(!1),T(null)}},isSaving:L,fromLanguage:(_==null?void 0:_.fromLang)||y,toLanguage:(_==null?void 0:_.toLang)||""})]})};qa.displayName="SeoPanel";const $a="seo",No=({isActive:e,show:s})=>{const{data:n}=ke(),a=Aa(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",{stroke:"currentColor",fill:"none","stroke-width":"2",viewBox:"0 0 24 24",strokeLinecap:"round",strokeLinejoin:"round",height:"200px",width:"200px",xmlns:"http://www.w3.org/2000/svg",children:[t.jsx("path",{d:"M7 8h-3a1 1 0 0 0 -1 1v2a1 1 0 0 0 1 1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-3"}),t.jsx("path",{d:"M14 16h-4v-8h4"}),t.jsx("path",{d:"M11 12h2"}),t.jsx("path",{d:"M17 8m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"})]})})},Eo={id:$a,label:"SEO",panel:qa,button:No,position:"top",width:600,view:"modal"},za="user-info",Co=()=>{const{user:e,logout:s}=Oe(),n=Ue("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},Ao={id:za,label:"User Info",button:Co,position:"bottom"},To=()=>{F.registerChaiSidebarPanel($a,Eo),F.registerChaiSidebarPanel(Fa,go),F.registerChaiSidebarPanel(za,Ao)};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 Gt(e){ne.context=e}var Va=!1,ko=(e,s)=>e===s,Ts=Symbol("solid-proxy"),Ka=typeof Proxy=="function",_n=Symbol("solid-track"),ks={equals:ko},Ha=tr,Xe=1,Ps=2,Qa={owned:null,cleanups:null,context:null,owner:null},Xs={},de=null,Zs=null,Po=null,ye=null,Ie=null,Qe=null,Fs=0;function st(e,s){const n=ye,a=de,r=e.length===0,i=s===void 0?a:s,l=r?Qa:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Te(()=>Ht(l)));de=l,ye=null;try{return ze(o,!0)}finally{ye=n,de=a}}function Se(e,s){s=s?Object.assign({},ks,s):ks;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),er(n,r));return[Za.bind(n),a]}function Wa(e,s,n){const a=qs(e,s,!0,Xe);Ot(a)}function nt(e,s,n){const a=qs(e,s,!1,Xe);Ot(a)}function Dn(e,s,n){Ha=$o;const a=qs(e,s,!1,Xe);(!n||!n.render)&&(a.user=!0),Qe?Qe.push(a):Ot(a)}function Ae(e,s,n){n=n?Object.assign({},ks,n):ks;const a=qs(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Ot(a),Za.bind(a)}function Io(e){return e&&typeof e=="object"&&"then"in e}function _o(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"&&Ae(a);const v=new Set,[y,j]=(i.storage||Se)(i.initialValue),[p,b]=Se(void 0),[w,N]=Se(void 0,{equals:!1}),[P,_]=Se(d?"ready":"unresolved");ne.context&&(u=ne.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:ne.load&&ne.has(u)&&(o=ne.load(u)));function T(L,R,q,M){return l===L&&(l=null,M!==void 0&&(d=!0),(L===o||R===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(M,{value:R})),o=Xs,A(R,q)),R}function A(L,R){ze(()=>{R===void 0&&j(()=>L),_(R!==void 0?"errored":d?"ready":"unresolved"),b(R);for(const q of v.keys())q.decrement();v.clear()},!1)}function z(){const L=Uo,R=y(),q=p();if(q!==void 0&&!l)throw q;return ye&&ye.user,R}function X(L=!0){if(L!==!1&&h)return;h=!1;const R=m?m():a;if(R==null||R===!1){T(l,Te(y));return}let q;const M=o!==Xs?o:Te(()=>{try{return r(R,{value:y(),refetching:L})}catch(J){q=J}});if(q!==void 0){T(l,void 0,Ns(q),R);return}else if(!Io(M))return T(l,M,void 0,R),M;return l=M,"v"in M?(M.s===1?T(l,M.v,void 0,R):T(l,void 0,Ns(M.v),R),M):(h=!0,queueMicrotask(()=>h=!1),ze(()=>{_(d?"refreshing":"pending"),N()},!1),M.then(J=>T(M,J,void 0,R),J=>T(M,void 0,Ns(J),R)))}Object.defineProperties(z,{state:{get:()=>P()},error:{get:()=>p()},loading:{get(){const L=P();return L==="pending"||L==="refreshing"}},latest:{get(){if(!d)return z();const L=p();if(L&&!l)throw L;return y()}}});let V=de;return m?Wa(()=>(V=de,X(!1))):X(!1),[z,{refetch:L=>Ya(V,()=>X(L)),mutate:j}]}function Do(e){return ze(e,!1)}function Te(e){if(ye===null)return e();const s=ye;ye=null;try{return e()}finally{ye=s}}function Lo(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=Te(()=>s(o,r,l));return r=o,u}}function Ja(e){Dn(()=>Te(e))}function Lt(e){return de===null||(de.cleanups===null?de.cleanups=[e]:de.cleanups.push(e)),e}function Yn(){return de}function Ya(e,s){const n=de,a=ye;de=e,ye=null;try{return ze(s,!0)}catch(r){Ln(r)}finally{de=n,ye=a}}function Bo(e){const s=ye,n=de;return Promise.resolve().then(()=>{ye=s,de=n;let a;return ze(e,!1),ye=de=null,a?a.done:void 0})}var[Mo,Zu]=Se(!1);function Oo(){return[Mo,Bo]}function Ro(e,s){const n=Symbol("context");return{id:n,Provider:zo(n),defaultValue:e}}function Go(e){let s;return de&&de.context&&(s=de.context[e.id])!==void 0?s:e.defaultValue}function Xa(e){const s=Ae(e),n=Ae(()=>on(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Uo;function Za(){if(this.sources&&this.state)if(this.state===Xe)Ot(this);else{const e=Ie;Ie=null,ze(()=>_s(this),!1),Ie=e}if(ye){const e=this.observers?this.observers.length:0;ye.sources?(ye.sources.push(this),ye.sourceSlots.push(e)):(ye.sources=[this],ye.sourceSlots=[e]),this.observers?(this.observers.push(ye),this.observerSlots.push(ye.sources.length-1)):(this.observers=[ye],this.observerSlots=[ye.sources.length-1])}return this.value}function er(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&&sr(i)),l||(i.state=Xe)}if(Ie.length>1e6)throw Ie=[],new Error},!1)),s}function Ot(e){if(!e.fn)return;Ht(e);const s=Fs;Fo(e,e.value,s)}function Fo(e,s,n){let a;const r=de,i=ye;ye=de=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Xe,e.owned&&e.owned.forEach(Ht),e.owned=null),e.updatedAt=n+1,Ln(l)}finally{ye=i,de=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?er(e,a):e.value=a,e.updatedAt=n)}function qs(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!==Qa&&(de.owned?de.owned.push(i):de.owned=[i]),i}function Is(e){if(e.state===0)return;if(e.state===Ps)return _s(e);if(e.suspense&&Te(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)Ot(e);else if(e.state===Ps){const a=Ie;Ie=null,ze(()=>_s(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 qo(n),a}catch(a){n||(Qe=null),Ie=null,Ln(a)}}function qo(e){if(Ie&&(tr(Ie),Ie=null),e)return;const s=Qe;Qe=null,s.length&&ze(()=>Ha(s),!1)}function tr(e){for(let s=0;s<e.length;s++)Is(e[s])}function $o(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:Is(a)}if(ne.context){if(ne.count){ne.effects||(ne.effects=[]),ne.effects.push(...e.slice(0,n));return}Gt()}for(ne.effects&&(ne.done||!ne.count)&&(e=[...ne.effects,...e],n+=ne.effects.length,delete ne.effects),s=0;s<n;s++)Is(e[s])}function _s(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)&&Is(a):r===Ps&&_s(a,s)}}}function sr(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=Ps,n.pure?Ie.push(n):Qe.push(n),n.observers&&sr(n))}}function Ht(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--)Ht(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Ht(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 Ln(e,s=de){throw Ns(e)}function on(e){if(typeof e=="function"&&!e.length)return on(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=on(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function zo(e,s){return function(a){let r;return nt(()=>r=Te(()=>(de.context={...de.context,[e]:a.value},Xa(()=>a.children))),void 0),r}}var cn=Symbol("fallback");function Ds(e){for(let s=0;s<e.length;s++)e[s]()}function Vo(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return Lt(()=>Ds(i)),()=>{let u=e()||[],h=u.length,d,m;return u[_n],Te(()=>{let y,j,p,b,w,N,P,_,T;if(h===0)l!==0&&(Ds(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[cn],r[0]=st(A=>(i[0]=A,n.fallback())),l=1);else if(l===0){for(r=new Array(h),m=0;m<h;m++)a[m]=u[m],r[m]=st(v);l=h}else{for(p=new Array(h),b=new Array(h),o&&(w=new Array(h)),N=0,P=Math.min(l,h);N<P&&a[N]===u[N];N++);for(P=l-1,_=h-1;P>=N&&_>=N&&a[P]===u[_];P--,_--)p[_]=r[P],b[_]=i[P],o&&(w[_]=o[P]);for(y=new Map,j=new Array(_+1),m=_;m>=N;m--)T=u[m],d=y.get(T),j[m]=d===void 0?-1:d,y.set(T,m);for(d=N;d<=P;d++)T=a[d],m=y.get(T),m!==void 0&&m!==-1?(p[m]=r[d],b[m]=i[d],o&&(w[m]=o[d]),m=j[m],y.set(T,m)):i[d]();for(m=N;m<h;m++)m in p?(r[m]=p[m],i[m]=b[m],o&&(o[m]=w[m],o[m](m))):r[m]=st(v);r=r.slice(0,l=h),a=u.slice(0)}return r});function v(y){if(i[m]=y,o){const[j,p]=Se(m);return o[m]=p,s(u[m],j)}return s(u[m])}}}function Ko(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return Lt(()=>Ds(i)),()=>{const h=e()||[],d=h.length;return h[_n],Te(()=>{if(d===0)return o!==0&&(Ds(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[cn],r[0]=st(v=>(i[0]=v,n.fallback())),o=1),r;for(a[0]===cn&&(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]=st(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(v){i[u]=v;const[y,j]=Se(h[u]);return l[u]=j,s(y,u)}}}function Bn(e,s){return Te(()=>e(s||{}))}function vs(){return!0}var un={get(e,s,n){return s===Ts?n:e.get(s)},has(e,s){return s===Ts?!0:e.has(s)},set:vs,deleteProperty:vs,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:vs,deleteProperty:vs}},ownKeys(e){return e.keys()}};function en(e){return(e=typeof e=="function"?e():e)?e:{}}function Ho(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function Mn(...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,Ae(o)):o}if(Ka&&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)]}},un);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:Ho.bind(n[d]=[m.get.bind(o)])}:m.value!==void 0?m:void 0;else{const v=n[d];v&&(m.get?v.push(m.get.bind(o)):m.value!==void 0&&v.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 nr(e,...s){if(Ka&&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)}},un));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))}},un)),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 ar(e){let s,n;const a=r=>{const i=ne.context;if(i){const[o,u]=Se();ne.count||(ne.count=0),ne.count++,(n||(n=e())).then(h=>{!ne.done&&Gt(i),ne.count--,u(()=>h.default),Gt()}),s=o}else if(!s){const[o]=_o(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Ae(()=>(l=s())?Te(()=>{if(!i||ne.done)return l(r);const o=ne.context;Gt(i);const u=l(r);return Gt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Qo=0;function Wo(){return ne.context?ne.getNextContextId():`cl-${Qo++}`}var rr=e=>`Stale read from <${e}>.`;function Jo(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ae(Vo(()=>e.each,e.children,s||void 0))}function Yo(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ae(Ko(()=>e.each,e.children,s||void 0))}function Xo(e){const s=e.keyed,n=Ae(()=>e.when,void 0,void 0),a=s?n:Ae(n,void 0,{equals:(r,i)=>!r==!i});return Ae(()=>{const r=a();if(r){const i=e.children;return typeof i=="function"&&i.length>0?Te(()=>i(s?r:()=>{if(!Te(a))throw rr("Show");return n()})):i}return e.fallback},void 0,void 0)}function Zo(e){const s=Xa(()=>e.children),n=Ae(()=>{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=Ae(()=>h()?void 0:u.when,void 0,void 0),m=u.keyed?d:Ae(d,void 0,{equals:(v,y)=>!v==!y});i=()=>h()||(m()?[o,d,u]:void 0)}return i});return Ae(()=>{const a=n()();if(!a)return e.fallback;const[r,i,l]=a,o=l.children;return typeof o=="function"&&o.length>0?Te(()=>o(l.keyed?i():()=>{var h;if(((h=Te(n)())==null?void 0:h[0])!==r)throw rr("Match");return i()})):o},void 0,void 0)}function ec(e){return e}var tc=["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"],sc=new Set(["className","value","readOnly","noValidate","formNoValidate","isMap","noModule","playsInline",...tc]),nc=new Set(["innerHTML","textContent","innerText","children"]),ac=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),rc=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 ic(e,s){const n=rc[e];return typeof n=="object"?n[s]?n.$:void 0:n}var lc=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),oc=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"]),cc={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},uc=e=>Ae(()=>e());function dc(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,v=1,y;for(;++m<r&&m<i&&!((y=h.get(s[m]))==null||y!==d+v);)v++;if(v>d-o){const j=s[l];for(;o<d;)e.insertBefore(n[o++],j)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var Vt="_$DX_DELEGATE";function ir(e,s,n,a={}){let r;return st(i=>{r=i,s===document?e():Bs(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function hc(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 lr(e,s=window.document){const n=s[Vt]||(s[Vt]=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,hr))}}function mc(e=window.document){if(e[Vt]){for(let s of e[Vt].keys())e.removeEventListener(s,hr);delete e[Vt]}}function Ls(e,s,n){mt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function fc(e,s,n,a){mt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function xc(e,s,n){mt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function or(e,s){mt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function cr(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 gc(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 pc(e,s,n){if(!s)return n?Ls(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 ur(e,s={},n,a){const r={};return a||nt(()=>r.children=Qt(e,s.children,r.children)),nt(()=>typeof s.ref=="function"&&dr(s.ref,e)),nt(()=>yc(e,s,n,!0,r,!0)),r}function dr(e,s,n){return Te(()=>e(s,n))}function Bs(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Qt(e,s,a,n);nt(r=>Qt(e,s(),r,n),a)}function yc(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 jc(e){let s,n;return!mt()||!(s=ne.registry.get(n=bc()))?e():(ne.completed&&ne.completed.add(s),ne.registry.delete(n),s)}function mt(e){return!!ne.context&&!ne.done&&(!e||e.isConnected)}function vc(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 pc(e,n,a);if(s==="classList")return gc(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const v=s.slice(3);a&&e.removeEventListener(v,a,typeof a!="function"&&a),n&&e.addEventListener(v,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const v=s.slice(10);a&&e.removeEventListener(v,a,!0),n&&e.addEventListener(v,n,!0)}else if(s.slice(0,2)==="on"){const v=s.slice(2).toLowerCase(),y=lc.has(v);if(!y&&a){const j=Array.isArray(a)?a[0]:a;e.removeEventListener(v,j)}(y||n)&&(cr(e,v,n,y),y&&lr([v]))}else if(s.slice(0,5)==="attr:")Ls(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")xc(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(h=nc.has(s))||!r&&((d=ic(s,e.tagName))||(u=sc.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(m)s=s.slice(5),u=!0;else if(mt(e))return n;s==="class"||s==="className"?or(e,n):o&&!u&&!h?e[vc(s)]=n:e[d||s]=n}else{const v=r&&s.indexOf(":")>-1&&cc[s.split(":")[0]];v?fc(e,v,s,n):Ls(e,ac[s]||s,n)}return n}function hr(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 Qt(e,s,n,a,r){const i=mt(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=gt(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=gt(e,n,a)}else{if(l==="function")return nt(()=>{let u=s();for(;typeof u=="function";)u=u();n=Qt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],h=n&&Array.isArray(n);if(dn(u,s,n,r))return nt(()=>n=Qt(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=gt(e,n,a),o)return n}else h?n.length===0?ea(e,u,a):dc(e,n,u):(n&&gt(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=gt(e,n,a,s);gt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function dn(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=dn(e,o,u)||r;else if(h==="function")if(a){for(;typeof o=="function";)o=o();r=dn(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 gt(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 bc(){return ne.getNextContextId()}var wc="http://www.w3.org/2000/svg";function mr(e,s=!1){return s?document.createElementNS(wc,e):document.createElement(e)}function Sc(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Yn();let i,l=!!ne.context;return Dn(()=>{l&&(Yn().user=l=!1),i||(i=Ya(r,()=>Ae(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,h]=Se(!1),d=()=>h(!0);st(m=>Bs(o,()=>u()?m():i(),null)),Lt(d)}else{const u=mr(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}),Bs(h,i),o.appendChild(u),e.ref&&e.ref(u),Lt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function Nc(e,s){const n=Ae(e);return Ae(()=>{const a=n();switch(typeof a){case"function":return Te(()=>a(s));case"string":const r=oc.has(a),i=ne.context?jc():mr(a,r);return ur(i,s,r),i}})}function Ec(e){const[,s]=nr(e,["component"]);return Nc(()=>e.component,s)}var Cc=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()}},fr=class{constructor(e){this.generateIdentifier=e,this.kv=new Cc}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)}},Ac=class extends fr{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 Tc(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 kc(e,s){const n=Tc(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 Bt(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 Pc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return kc(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Ic=e=>Object.prototype.toString.call(e).slice(8,-1),xr=e=>typeof e>"u",_c=e=>e===null,Wt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,hn=e=>Wt(e)&&Object.keys(e).length===0,rt=e=>Array.isArray(e),Dc=e=>typeof e=="string",Lc=e=>typeof e=="number"&&!isNaN(e),Bc=e=>typeof e=="boolean",Mc=e=>e instanceof RegExp,Jt=e=>e instanceof Map,Yt=e=>e instanceof Set,gr=e=>Ic(e)==="Symbol",Oc=e=>e instanceof Date&&!isNaN(e.valueOf()),Rc=e=>e instanceof Error,sa=e=>typeof e=="number"&&isNaN(e),Gc=e=>Bc(e)||_c(e)||xr(e)||Lc(e)||Dc(e)||gr(e),Uc=e=>typeof e=="bigint",Fc=e=>e===1/0||e===-1/0,qc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),$c=e=>e instanceof URL,pr=e=>e.replace(/\./g,"\\."),tn=e=>e.map(String).map(pr).join("."),Kt=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 yr=[$e(xr,"undefined",()=>null,()=>{}),$e(Uc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),$e(Oc,"Date",e=>e.toISOString(),e=>new Date(e)),$e(Rc,"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(Mc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),$e(Yt,"set",e=>[...e.values()],e=>new Set(e)),$e(Jt,"map",e=>[...e.entries()],e=>new Map(e)),$e(e=>sa(e)||Fc(e),"number",e=>sa(e)?"NaN":e>0?"Infinity":"-Infinity",Number),$e(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),$e($c,"URL",e=>e.toString(),e=>new URL(e))];function $s(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var jr=$s((e,s)=>gr(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}),zc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),vr=$s(qc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=zc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function br(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var wr=$s(br,(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)}),Sr=$s((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)}),Vc=[wr,jr,Sr,vr],na=(e,s)=>{const n=ta(Vc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=ta(yr,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},Nr={};yr.forEach(e=>{Nr[e.annotation]=e});var Kc=(e,s,n)=>{if(rt(s))switch(s[0]){case"symbol":return jr.untransform(e,s,n);case"class":return wr.untransform(e,s,n);case"custom":return Sr.untransform(e,s,n);case"typed-array":return vr.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=Nr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},yt=(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 Er(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 Hc=(e,s)=>{Er(s);for(let n=0;n<s.length;n++){const a=s[n];if(Yt(e))e=yt(e,+a);else if(Jt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=yt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},mn=(e,s,n)=>{if(Er(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(rt(a)){const o=+l;a=a[o]}else if(Wt(a))a=a[l];else if(Yt(a)){const o=+l;a=yt(a,o)}else if(Jt(a)){if(i===s.length-2)break;const u=+l,h=+s[++i]==0?"key":"value",d=yt(a,u);switch(h){case"key":a=d;break;case"value":a=a.get(d);break}}}const r=s[s.length-1];if(rt(a)?a[+r]=n(a[+r]):Wt(a)&&(a[r]=n(a[r])),Yt(a)){const i=yt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Jt(a)){const i=+s[s.length-2],l=yt(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 fn(e,s,n=[]){if(!e)return;if(!rt(e)){Bt(e,(i,l)=>fn(i,s,[...n,...Kt(l)]));return}const[a,r]=e;r&&Bt(r,(i,l)=>{fn(i,s,[...n,...Kt(l)])}),s(a,n)}function Qc(e,s,n){return fn(s,(a,r)=>{e=mn(e,r,i=>Kc(i,a,n))}),e}function Wc(e,s){function n(a,r){const i=Hc(e,Kt(r));a.map(Kt).forEach(l=>{e=mn(e,l,()=>i)})}if(rt(s)){const[a,r]=s;a.forEach(i=>{e=mn(e,Kt(i),()=>e)}),r&&Bt(r,n)}else Bt(s,n);return e}var Jc=(e,s)=>Wt(e)||rt(e)||Jt(e)||Yt(e)||br(e,s);function Yc(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function Xc(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?hn(n)?[a]:[a,n]:hn(n)?void 0:n}var Cr=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=Gc(e);if(!o){Yc(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!Jc(e,n)){const y=na(e,n),j=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,j),j}if(Es(i,e))return{transformedValue:null};const u=na(e,n),h=(u==null?void 0:u.value)??e,d=rt(h)?[]:{},m={};Bt(h,(y,j)=>{if(j==="__proto__"||j==="constructor"||j==="prototype")throw new Error(`Detected property ${j}. This is a prototype pollution risk, please remove it from your object.`);const p=Cr(y,s,n,a,[...r,j],[...i,e],l);d[j]=p.transformedValue,rt(p.annotations)?m[j]=p.annotations:Wt(p.annotations)&&Bt(p.annotations,(b,w)=>{m[pr(j)+"."+w]=b})});const v=hn(m)?{transformedValue:d,annotations:u?[u.type]:void 0}:{transformedValue:d,annotations:u?[u.type,m]:m};return o||l.set(e,v),v};function Ar(e){return Object.prototype.toString.call(e).slice(8,-1)}function aa(e){return Ar(e)==="Array"}function Zc(e){if(Ar(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function eu(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 xn(e,s={}){if(aa(e))return e.map(r=>xn(r,s));if(!Zc(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=xn(l,s);return eu(r,i,o,e,s.nonenumerable),r},{})}var ve=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Ac,this.symbolRegistry=new fr(s=>s.description??""),this.customTransformerRegistry=new Pc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Cr(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=Xc(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=xn(s);return n!=null&&n.values&&(a=Qc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Wc(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)}};ve.defaultInstance=new ve;ve.serialize=ve.defaultInstance.serialize.bind(ve.defaultInstance);ve.deserialize=ve.defaultInstance.deserialize.bind(ve.defaultInstance);ve.stringify=ve.defaultInstance.stringify.bind(ve.defaultInstance);ve.parse=ve.defaultInstance.parse.bind(ve.defaultInstance);ve.registerClass=ve.defaultInstance.registerClass.bind(ve.defaultInstance);ve.registerSymbol=ve.defaultInstance.registerSymbol.bind(ve.defaultInstance);ve.registerCustom=ve.defaultInstance.registerCustom.bind(ve.defaultInstance);ve.allowErrorProps=ve.defaultInstance.allowErrorProps.bind(ve.defaultInstance);var Tr=ve.serialize,tu=ve.stringify;function su(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function nu(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function au({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function ru({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function iu(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var lu=(e,s=!1)=>{const{json:n}=Tr(e);return JSON.stringify(n,null,s?2:void 0)},bs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,ou=(e,s)=>e.queryHash.localeCompare(s.queryHash),kr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,cu=(e,s)=>bs(e)===bs(s)?kr(e,s):bs(e)>bs(s)?1:-1,uu={status:cu,"query hash":ou,"last updated":kr},ws=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Pr=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,du=(e,s)=>ws(e)===ws(s)?Pr(e,s):ws(e)>ws(s)?1:-1,hu={status:du,"last updated":Pr},mu=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),fu=()=>{const[e,s]=Se("dark");return Ja(()=>{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),Lt(()=>n.removeEventListener("change",a))}),e},Ut=(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,Ut(a.get(r),i,n)),a}if(e instanceof Set){const a=Ut(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]=Ut(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]=Ut(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},Ir=(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)},jt,Xt,Zt,es,ot,ts,vt,bt,wt,St,Nt,ss,Et,ns,oa,xu=(oa=class{constructor(e){fe(this,jt);fe(this,Xt);fe(this,Zt);fe(this,es);fe(this,ot,!1);fe(this,ts);fe(this,vt);fe(this,bt);fe(this,wt);fe(this,St);fe(this,Nt);fe(this,ss);fe(this,Et);fe(this,ns);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,jt,Se(s)),he(this,Zt,n),he(this,es,a),he(this,Xt,r),he(this,ts,h),he(this,vt,d),he(this,bt,Se(i)),he(this,wt,Se(l)),he(this,St,Se(o)),he(this,Nt,Se(u)),he(this,ss,Se(m))}setButtonPosition(e){te(this,bt)[1](e)}setPosition(e){te(this,wt)[1](e)}setInitialIsOpen(e){te(this,St)[1](e)}setErrorTypes(e){te(this,Nt)[1](e)}setClient(e){te(this,jt)[1](e)}mount(e){if(te(this,ot))throw new Error("Devtools is already mounted");const s=ir(()=>{const n=this,[a]=te(this,bt),[r]=te(this,wt),[i]=te(this,St),[l]=te(this,Nt),[o]=te(this,ss),[u]=te(this,jt);let h;return te(this,Et)?h=te(this,Et):(h=ar(()=>Promise.resolve().then(()=>require("./LNWAZHJI-D8UfC3ls.cjs"))),he(this,Et,h)),Ir(te(this,ts),te(this,vt)),Bn(h,Mn({get queryFlavor(){return te(n,Zt)},get version(){return te(n,es)},get onlineManager(){return te(n,Xt)},get shadowDOMTarget(){return te(n,vt)}},{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,ot,!0),he(this,ns,s)}unmount(){var e;if(!te(this,ot))throw new Error("Devtools is not mounted");(e=te(this,ns))==null||e.call(this),he(this,ot,!1)}},jt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,es=new WeakMap,ot=new WeakMap,ts=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,Nt=new WeakMap,ss=new WeakMap,Et=new WeakMap,ns=new WeakMap,oa),Ct,as,rs,is,ct,ls,At,Tt,kt,Pt,It,os,_t,Dt,cs,ca,gu=(ca=class{constructor(e){fe(this,Ct);fe(this,as);fe(this,rs);fe(this,is);fe(this,ct,!1);fe(this,ls);fe(this,At);fe(this,Tt);fe(this,kt);fe(this,Pt);fe(this,It);fe(this,os);fe(this,_t);fe(this,Dt);fe(this,cs);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:h,shadowDOMTarget:d,onClose:m,hideDisabledQueries:v}=e;he(this,Ct,Se(s)),he(this,rs,n),he(this,is,a),he(this,as,r),he(this,ls,h),he(this,At,d),he(this,Tt,Se(i)),he(this,kt,Se(l)),he(this,Pt,Se(o)),he(this,It,Se(u)),he(this,os,Se(v)),he(this,_t,Se(m))}setButtonPosition(e){te(this,Tt)[1](e)}setPosition(e){te(this,kt)[1](e)}setInitialIsOpen(e){te(this,Pt)[1](e)}setErrorTypes(e){te(this,It)[1](e)}setClient(e){te(this,Ct)[1](e)}setOnClose(e){te(this,_t)[1](()=>e)}mount(e){if(te(this,ct))throw new Error("Devtools is already mounted");const s=ir(()=>{const n=this,[a]=te(this,Tt),[r]=te(this,kt),[i]=te(this,Pt),[l]=te(this,It),[o]=te(this,os),[u]=te(this,Ct),[h]=te(this,_t);let d;return te(this,Dt)?d=te(this,Dt):(d=ar(()=>Promise.resolve().then(()=>require("./MWZ6AO7Z-DtuyAHY3.cjs"))),he(this,Dt,d)),Ir(te(this,ls),te(this,At)),Bn(d,Mn({get queryFlavor(){return te(n,rs)},get version(){return te(n,is)},get onlineManager(){return te(n,as)},get shadowDOMTarget(){return te(n,At)}},{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,ct,!0),he(this,cs,s)}unmount(){var e;if(!te(this,ct))throw new Error("Devtools is not mounted");(e=te(this,cs))==null||e.call(this),he(this,ct,!1)}},Ct=new WeakMap,as=new WeakMap,rs=new WeakMap,is=new WeakMap,ct=new WeakMap,ls=new WeakMap,At=new WeakMap,Tt=new WeakMap,kt=new WeakMap,Pt=new WeakMap,It=new WeakMap,os=new WeakMap,_t=new WeakMap,Dt=new WeakMap,cs=new WeakMap,ca);function pu(e){const s=U.useQueryClient(e.client),n=we.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u,hideDisabledQueries:h}=e,[d]=we.useState(new xu({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 we.useEffect(()=>{d.setClient(s)},[s,d]),we.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),we.useEffect(()=>{r&&d.setPosition(r)},[r,d]),we.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),we.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),we.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{dir:"ltr",className:"tsqd-parent-container",ref:n})}function yu(e){const s=U.useQueryClient(e.client),n=we.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i,hideDisabledQueries:l}=e,[o]=we.useState(new gu({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 we.useEffect(()=>{o.setClient(s)},[s,o]),we.useEffect(()=>{o.setOnClose(e.onClose??(()=>{}))},[e.onClose,o]),we.useEffect(()=>{o.setErrorTypes(a||[])},[a,o]),we.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 ju=process.env.NODE_ENV!=="development"?function(){return null}:pu;process.env.NODE_ENV;const vu=()=>{F.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),F.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),F.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"}),F.registerChaiFeatureFlag("enable-old-page-manager",{description:"Switch to older page manager"}),F.registerChaiFeatureFlag("enable-site-settings",{description:"Site settings"})},bu=()=>{const e=le(),s=ee();return U.useQuery({queryKey:[O.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:O.GET_COLLECTIONS})})},wu=()=>{const{data:e}=ke(),{data:s}=We(),{data:n}=Ve(),a=le(),r=ee(),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:O.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}}})})},_r=()=>{const e=Gs();return x.useCallback(({pageId:s})=>{e(s)},[e])},ra={},Cs=(e,s)=>{f.has(ra,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),f.set(ra,e,{id:e,...s})},Su=x.createContext(null),sn={didCatch:!1,error:null};class Nu 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&&Eu(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(Su.Provider,{value:{didCatch:i,error:l,resetErrorBoundary:this.resetErrorBoundary}},o)}}function Eu(){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 Cu=()=>{const e=us(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>{const r=a.map(async l=>n(e,{action:O.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:[O.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")}})},Au=()=>{const e=us(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[O.GET_ASSETS]}),W.toast.success("Asset deleted successfully")},onError:()=>{W.toast.error("Failed to delete asset")}})},Tu=()=>{const e=us(),s=U.useQueryClient(),n=ee();return U.useMutation({mutationFn:async a=>n(e,{action:O.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[O.GET_ASSETS]}),W.toast.success("Asset updated successfully")},onError:()=>{W.toast.error("Failed to update asset")}})};function ku({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 j=Math.floor(a/2);let p=Math.max(1,e-j),b=Math.min(s,e+j);b-p+1<a&&(p===1?b=Math.min(s,p+a-1):b===s&&(p=Math.max(1,b-a+1)));const w=[];p>1&&(w.push(1),p>2&&w.push("..."));for(let N=p;N<=b;N++)w.push(N);return b<s&&(b<s-1&&w.push("..."),w.push(s)),w},[e,s,a]),h=j=>{j!==e&&j>=1&&j<=s&&(n(j),o(String(j)))},d=()=>{e>1&&h(e-1)},m=()=>{e<s&&h(e+1)},v=()=>{const j=Number(l);!isNaN(j)&&j>=1&&j<=s&&h(j)},y=j=>{j.key==="Enter"&&v()};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((j,p)=>{if(j==="...")return t.jsx("span",{className:"px-2 text-muted-foreground",children:"..."},`ellipsis-${p}`);const b=j,w=b===e;return t.jsx(c.Button,{variant:w?"default":"outline",size:"sm",onClick:()=>h(b),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:b},b)})}),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:j=>{const p=j.target.value.replace(/[^\d]/g,"");o(p)},onKeyDown:y,className:"h-8 w-16 px-2 py-1"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:v,disabled:l===""||Number(l)<1||Number(l)>s,children:"Go"})]})]})}const Pu=(e={})=>{const s=us(),n=ee(),{search:a,page:r=1,limit:i=30}=e;return U.useQuery({queryKey:[O.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:O.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},Iu=e=>{const s=us(),n=ee();return U.useQuery({queryKey:[O.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:O.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function _u(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 ia(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 la(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 Du=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,v,y;const{data:i,isLoading:l,isError:o}=Iu(e||""),[u,h]=x.useState(""),d=async(j,p)=>{try{await navigator.clipboard.writeText(j),W.toast.success(`${p} copied to clipboard`)}catch(b){W.toast.error(`Failed to copy ${p}`,{description:b==null?void 0:b.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:((v=i.metadata)==null?void 0:v.format)||i.type,capitalize:!0},{label:"Size",value:_u(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:ia(i.createdAt)},{label:"Updated",value:ia(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(j=>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:j.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(j.capitalize?" capitalize":""),children:j.value}),j.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(j.value,j.label),children:t.jsx(S.Link,{className:"h-3 w-3"})})]})]},j.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((j,p)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:j.name}),t.jsxs("div",{className:"text-gray-500",children:["(",j.slug,")"]})]},p))})]}),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:j=>h(j.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||!la(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!la(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"})})]})]})]})]})},Lu=x.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs"))),Bu=25*1024*1024,Mu=({isUpdatingAsset:e,allowedTypes:s,uploadAssets:n,isUploadingAsset:a,onUploaded:r})=>{const[i,l]=x.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});x.useEffect(()=>{localStorage.setItem("chai_optimize_images",i.toString())},[i]);const o=e||a,u=x.useCallback(async y=>{try{const j=y;if(!j.every(N=>N.type.startsWith("image/")))return W.toast.error("Invalid file type. Please upload a valid file."),Promise.reject(new Error("Invalid file type"));const p=j.map(async N=>{let P=N;return N.type.startsWith("image/")&&(P=await Ca(N)),new Promise((_,T)=>{const A=new FileReader;A.readAsDataURL(P),A.onload=async()=>{_({file:A.result,folderId:void 0,name:N.name,optimize:i})},A.onerror=()=>T(null)})}),b=await Promise.all(p),w=await n(b);return(w==null?void 0:w.length)===1&&r(w[0]),w}catch(j){return Promise.reject(j)}},[n,i,r]),h=y=>{const j=[];let p=0;return y.forEach(b=>{b.size>Bu?p++:j.push(b)}),p>0&&W.toast.error(`${p===1&&y.length===1?"File":p+(p===1?" file":" files")} exceed the maximum size limit of 10MB.`),f.isEmpty(j)?[]:u(j)},{getRootProps:d,getInputProps:m,isDragActive:v}=Gr.useDropzone({onDrop:h,accept:{"image/*":s.includes("image")?[]:[]},disabled:e||a,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 ${o?"pointer-events-none bg-gray-100 opacity-90":"bg-gray-100 hover:border-black/50 hover:bg-gray-100"}`,children:t.jsxs("div",{...d(),className:F.mergeClasses("flex h-max w-full cursor-pointer flex-col justify-center rounded-lg text-center",o?"items-start":"items-center",v?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...m()}),o?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.jsx("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("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:i?"text-indigo-600":"text-gray-400",children:i?"On":"Off"})]}),t.jsx(c.Switch,{checked:i,onCheckedChange:y=>{l(y)},onClick:y=>{y.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 ${i?"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 Dr({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,v]=x.useState(null),[y,j]=x.useState({show:!1,file:""}),[p,b]=x.useState(!1),[w,N]=x.useState(a?"details":"grid"),[P,_]=x.useState(""),[T,A]=x.useState(""),[z,X]=x.useState(1),[V]=x.useState(30),[L,R]=x.useState([]);x.useEffect(()=>{a&&(u(a),N("details"))},[a]),x.useEffect(()=>{const B=setTimeout(()=>{_(T),X(1)},300);return()=>clearTimeout(B)},[T]);const{data:q,isLoading:M}=Pu({search:P.toLowerCase().trim(),page:z,limit:V}),J=(q==null?void 0:q.assets)||[],H=(q==null?void 0:q.total)||0,ae=Math.ceil(H/V);x.useEffect(()=>{M||ae<=0||X(B=>B>ae?ae:B<1?1:B)},[M,ae]);const xe=(J==null?void 0:J.length)>0,{mutate:ge}=Au(),{mutateAsync:ce,isPending:E}=Cu(),{mutate:g,isPending:I}=Tu(),G=x.useCallback(B=>{const se=Math.min(Math.max(1,B),Math.max(1,ae));se!==z&&X(se)},[ae,z]),C=B=>{A(B.target.value)},D=x.useCallback(B=>{R(se=>f.find(se,{id:B.id})?[]:[B])},[!1]),Q=x.useCallback(()=>{R([])},[]),$=B=>{(B==null?void 0:B.length)!==0&&(s(f.pick(f.first(B||L),["id","url","width","height","description"])),e())},Y=async B=>{d(B)},oe=async()=>{h&&(v(h==null?void 0:h.id),await ge(h.id,{onSuccess:()=>{v(null),d(null)},onError:()=>{v(null)}}),d(null))},K=B=>{u(B.id),N("details")},re=async(B,se)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";se?(await ce([{file:B,folderId:void 0,name:y.name||"",optimize:Ee}]),j({show:!1,file:""})):(await g({id:y.id||"",file:B}),j({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},me=x.useCallback(B=>{R([B])},[]),pe=x.useCallback(B=>{G(B)},[G]);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(Mu,{maxFileSize:10,allowedTypes:l,uploadAssets:ce,isUpdatingAsset:I,isUploadingAsset:E,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 ${T.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:C,value:T,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:()=>Q(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>$(L),disabled:L.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:M?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"})]}):!M&&!xe?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:J==null?void 0:J.map(B=>t.jsxs("div",{className:F.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===B.id)?"border-blue-500":"hover:border-black/90",m&&(h==null?void 0:h.id)===B.id?"pointer-events-none opacity-50":"",m===B.id?"pointer-events-none opacity-50":""),onClick:()=>D(B),onDoubleClick:()=>$([B]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===B.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,B.type==="image"?t.jsx("img",{src:`${B.thumbnailUrl||"/placeholder.svg"}?v=${(B==null?void 0:B.updatedAt)||B.createdAt}`,alt:B.name,className:`h-full min-h-[80px] w-full object-contain ${L.some(se=>se.id===B.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"}),B.thumbnailUrl&&t.jsx("img",{src:`${B.thumbnailUrl||"/placeholder.svg"}?v=${(B==null?void 0:B.updatedAt)||B.createdAt}`,alt:B.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:B.name,children:B.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((B==null?void 0:B.size)||0)})})]}),!L.some(se=>se.id===B.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(B)},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(B.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(),j({id:B.id,show:!0,file:B.url,name:B.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(),Y(B)},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===B.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})})]},B.id))})}),ae>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 border-t bg-white p-4",children:t.jsx(Nu,{fallback:t.jsx("div",{className:"text-red-500",children:"Error loading pagination"}),children:t.jsx(ku,{currentPage:z,totalPages:ae,onPageChange:pe,pageRangeDisplayed:3,showPageInput:!0})})})]})]}):t.jsx(Du,{assetId:o||a||"",onBack:()=>{N("grid"),u(null)},onEdit:B=>{j({id:B.id,show:!0,file:B.url,name:B.name})},onSave:async B=>{if(o){b(!0);try{const se=J.find(Ee=>Ee.id===o);se&&await g(f.merge(se,{description:B}))}finally{b(!1)}}},isSaving:p})]}),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(Lu,{imageUrl:y.file,onSave:re,onClose:()=>j({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:oe,children:"Delete"})]})]})})]})}const Ou=Object.freeze(Object.defineProperty({__proto__:null,default:Dr},Symbol.toStringTag,{value:"Module"})),Ms=({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 j=Array.isArray(y)?y[0]:y;j!=null&&j.url&&n(f.pick(j,["url","id"])),o(!1)},m=()=>{n({url:"",id:""})},v=(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:[v?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:v?t.jsx(S.X,{className:"h-4 w-4"}):t.jsx(S.Trash2,{className:"h-4 w-4"})}),!v&&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(Dr,{close:h,onSelect:d,mode:"image",assetId:e})})]})})]})},Ru=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),Gu=()=>{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(Ms,{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(Ms,{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"})})]})]})},Uu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),Fu=()=>{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=p=>s(b=>({...b,[p.target.name]:p.target.value})),d=()=>{const{platform:p,url:b,customName:w}=r;if(!b.trim()||!p)return;const N=p==="other"?w:p;N.trim()&&(a(P=>[...P,{platform:N,url:b,isCustom:p==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=p=>a(b=>b.filter((w,N)=>N!==p)),v=()=>i({isOpen:!1,platform:"",url:"",customName:""}),y=()=>{o(!0);const p={};n.forEach(w=>{p[w.platform.toLowerCase().replace(/\s+/g,"_")]=w.url});const b={...e,socialLinks:p};setTimeout(()=>{o(!1),console.log("Contact & Social settings saved:",b),s({contactEmail:"",contactPhone:"",contactAddress:""}),a([]),i({isOpen:!1,platform:"",url:"",customName:""})},1e3)},j=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(p=>({...p,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:p=>i(b=>({...b,platform:p.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",children:[t.jsx("option",{value:"",children:"Select platform"}),u.map(p=>t.jsx("option",{value:p.value,children:p.label},p.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:p=>i(b=>({...b,customName:p.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:p=>i(b=>({...b,url:p.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:v,className:"flex-1",children:"Cancel"})]})]}),n.length>0&&t.jsx("div",{className:"space-y-2",children:n.map((p,b)=>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:p.platform}),t.jsx("p",{className:"max-w-xs truncate text-xs text-gray-500",children:p.url})]}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m(b),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},b))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:y,disabled:!j||l,className:"w-full",children:l?"Saving...":"Save Contact & Social Settings"})})]})]})},qu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),$u=()=>{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:j,value:p}=y.target;s(b=>({...b,[j]:p}))},h=()=>{r.trim()&&(a(y=>[...y,{id:Date.now().toString(),content:r}]),i(""))},d=y=>{a(j=>j.filter(p=>p.id!==y))},m=()=>{o(!0);const y={...e,customTrackingScripts:n.map(j=>j.content)};setTimeout(()=>{o(!1),console.log("Analytics & Tracking settings saved:",y),s({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),a([])},1e3)},v=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:!v||l,className:"w-full",children:l?"Saving...":"Save Settings"})})]})]})},zu=()=>{Cs("branding",{label:"Branding",button:Ru,panel:Gu}),Cs("contact-social",{label:"Contact & Social",button:Uu,panel:Fu}),Cs("analytics-tracking",{label:"Analytics & Tracking",button:qu,panel:$u})},Vu=x.lazy(()=>Promise.resolve().then(()=>Ou));vu();Ur.loadWebBlocks();F.registerChaiTopBar(to);To();zu();F.registerChaiMediaManager(Vu);F.registerChaiSaveToLibrary(Ai);const Ku=e=>{const s=x.useRef([]),[n]=Pe(),a=n.get("page"),{data:r}=ke(),{data:i={role:"",permissions:null}}=Ua();ro(),hi();const{data:l,isFetching:o}=Na(),{blocks:u}=ao(l),{data:h}=Ce(),{mutateAsync:d}=xa(),m=so(),{onSave:v}=io(),{getPartialBlocks:y,getPartialBlockBlocks:j}=lo(),{aiContext:p,setAiContext:b}=pn(),{mutateAsync:w}=ki(),[N,P]=x.useState(!1),{data:_}=Ve(),T=Ye(),{data:A}=vn(),{data:z}=bu(),{mutateAsync:X}=wu(),V=_r();ei(),x.useEffect(()=>{const M=()=>{document.hidden?P(!0):P(!1)};return window.addEventListener("visibilitychange",M),()=>window.removeEventListener("visibilitychange",M)},[]),s.current=u;const L=x.useMemo(()=>{const M={};return i&&(M.permissions=f.get(i,"permissions",null),M.role=f.get(i,"role","user")),M},[i]),R=x.useCallback(async(M,J)=>await w({pageType:M,query:J}),[w]),q=x.useMemo(()=>f.get(_,"theme",{})||{},[_]);return t.jsxs(t.Fragment,{children:[t.jsx(F.ChaiBuilderEditor,{gotoPage:V,collections:z??[],getBlockAsyncProps:X,pageExternalData:A,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:T,languages:(_==null?void 0:_.languages)||[],brandingOptions:(_==null?void 0:_.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!N&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:j,getPartialBlocks:y,blocks:o?[]:u,theme:f.cloneDeep(q),pageTypes:h,searchPageTypeItems:R,saveAiContextCallback:async M=>{if(!a)return!0;const J=s.current,H={_type:"@chai/ai-context",_value:f.isString(M)?M:""},ae=[...J,H];return await v({page:a,blocks:ae}),b(M),!0},aiContext:p,askAiCallBack:m,onSave:async({blocks:M,theme:J,needTranslations:H})=>{if(!a)return!0;s.current=M;const ae={_type:"@chai/ai-context",_value:f.isString(p)?p:""},xe=[...M,ae];return await v({page:a,blocks:xe,needTranslations:H}),s.current=xe,f.isEqual(J,q)||await d({settings:{theme:J}}),!0},themePanelComponent:Ri,...L}),t.jsxs("div",{children:[t.jsx(gi,{}),t.jsx(pi,{})]})]})},Hu=new U.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Qu=e=>{const{isLoggedIn:s}=Oe(),[,n]=ga(),[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:Hu,children:[s?t.jsx(Ku,{...e}):t.jsx(ho,{}),t.jsx(ju,{})]}):t.jsx("div",{})},Wu=()=>{const{savePageAsync:e}=F.useSavePage(),s=U.useQueryClient();return x.useCallback(async()=>{await e(),s.invalidateQueries({queryKey:[O.GET_DRAFT_PAGE]})},[e])},Ju=()=>{const e=le(),s=ee(),{data:n}=We(),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:O.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[O.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[O.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},Yu=()=>{const{logout:e}=Oe(),{getAccessToken:s}=ma();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=_n;exports.ChaiBuilderPages=Qu;exports.ChaiBuilderPagesRealtime=ba;exports.Dynamic=Ec;exports.For=Jo;exports.ImagePicker=Ms;exports.Index=Yo;exports.LanguageSwitcher=In;exports.Match=ec;exports.NestedPathSelector=He;exports.PermissionChecker=Me;exports.Portal=Sc;exports.Show=Xo;exports.SmartJsonInput=ln;exports.Switch=Zo;exports.addEventListener=cr;exports.batch=Do;exports.className=or;exports.clearDelegatedEvents=mc;exports.convertRemToPixels=mu;exports.createComponent=Bn;exports.createComputed=Wa;exports.createContext=Ro;exports.createEffect=Dn;exports.createMemo=Ae;exports.createRenderEffect=nt;exports.createRoot=st;exports.createSignal=Se;exports.createUniqueId=Wo;exports.delegateEvents=lr;exports.deleteNestedDataByPath=Ft;exports.displayValue=lu;exports.getMutationStatusColor=ru;exports.getPreferredColorScheme=fu;exports.getQueryStatusColor=au;exports.getQueryStatusColorByLabel=iu;exports.getQueryStatusLabel=su;exports.getSidedProp=nu;exports.insert=Bs;exports.memo=uc;exports.mergeProps=Mn;exports.mutationSortFns=hu;exports.on=Lo;exports.onCleanup=Lt;exports.onMount=Ja;exports.registerChaiSiteSetting=Cs;exports.registerLoginComponent=uo;exports.serialize=Tr;exports.setAttribute=Ls;exports.sortFns=uu;exports.splitProps=nr;exports.spread=ur;exports.stringify=tu;exports.template=hc;exports.untrack=Te;exports.updateNestedDataByPath=Ut;exports.use=dr;exports.useActivePage=We;exports.useBuilderPageData=vn;exports.useChaiAuth=Oe;exports.useChaiFetch=Yu;exports.useChaiUserInfo=Ke;exports.useContext=Go;exports.useCurrentPage=ke;exports.useFallbackLang=Ye;exports.useFetch=ee;exports.useGotoPage=_r;exports.useLanguagePages=Ge;exports.usePageTypes=Ce;exports.useReloadPage=Wu;exports.useTransition=Oo;exports.useUpdateActivePageMetadata=Ju;exports.useUserRoleAndPermissions=Ua;exports.useWebsitePages=ht;exports.useWebsiteSetting=Ve;