@chaibuilder/pages 0.12.0 → 0.12.2

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.
@@ -0,0 +1,13 @@
1
+ "use strict";var Lr=Object.defineProperty;var _n=e=>{throw TypeError(e)};var Br=(e,s,n)=>s in e?Lr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var et=(e,s,n)=>Br(e,typeof s!="symbol"?s+"":s,n),Dn=(e,s,n)=>s.has(e)||_n("Cannot "+n);var Z=(e,s,n)=>(Dn(e,s,"read from private field"),n?n.call(e):s.get(e)),fe=(e,s,n)=>s.has(e)?_n("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),de=(e,s,n,a)=>(Dn(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),x=require("lodash-es"),f=require("react"),pe=require("jotai"),G=require("@tanstack/react-query"),Q=require("sonner"),q=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),ut=require("date-fns"),S=require("lucide-react"),Mr=require("compressorjs"),Qs=require("react-diff-view"),ra=require("@chaibuilder/runtime"),bs=require("zod"),Or=require("react-dropzone"),Rr=require("@chaibuilder/sdk/web-blocks");function Gr(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const ve=Gr(f),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"},B={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 Ur=0;function Ln(e,s){const n=`atom${++Ur}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Fr,a.write=qr),s&&(a.write=s),a}function Fr(e){return e(this)}function qr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const zr=Symbol(""),$r=e=>typeof(e==null?void 0:e.then)=="function";function Vr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,h)=>{var d,m;const 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 $r(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)}},o=u=>(h,d,m)=>u(h,v=>{let y;try{y=JSON.parse(v||"")}catch{y=m}d(y)});let l;try{l=(n=e())==null?void 0:n.subscribe}catch{}return!l&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(l=(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)}}),l&&(i.subscribe=o(l)),i}const Kr=Vr();function ia(e,s,n=Kr,a){const r=Ln(s);return r.onMount=o=>{o(n.getItem(e,s));let l;return n.subscribe&&(l=n.subscribe(e,o,s)),l},Ln(o=>o(r),(o,l,u)=>{const h=typeof u=="function"?u(o(r)):u;return h===zr?(l(r,s),n.removeItem(e)):h instanceof Promise?h.then(d=>(l(r,d),n.setItem(e,d))):(l(r,h),n.setItem(e,h))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const la="__logged_in_user",Hr=ia(la,null),Ge=()=>{const[e,s]=pe.useAtom(Hr),n=f.useCallback(()=>{s(null),localStorage.removeItem(la)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},fn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)});let xt=null;function Qr(){const{user:e,setUser:s,logout:n}=Ge(),a=Bs(),r=Ue("getAccessToken",!1),i=async()=>{if(r===!1&&e&&!(!x.has(e,"expiresAt")||!x.has(e,"accessToken")||!x.has(e,"refreshToken")))try{const o=await fn(a,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!o.ok){n(),window.location.reload();return}const l=await o.json();if(x.has(l,"id")&&x.has(l,"email")&&x.has(l,"accessToken")&&x.has(l,"refreshToken"))return s(l),l;n(),window.location.reload()}catch{n(),window.location.reload()}};return G.useMutation({mutationFn:async()=>{if(xt)return await xt;xt=i();try{return await xt}finally{xt=null}},onSuccess:()=>{}})}function Wr(){return xt}const oa=()=>{const{user:e,setUser:s}=Ge(),{mutateAsync:n}=Qr(),a=60,r=f.useCallback(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const l=Math.floor(Date.now()/1e3);return e.expiresAt-l<=a},[e]),o=Ue("getAccessToken",async()=>{if(!(!x.has(e,"expiresAt")||!x.has(e,"accessToken")||!x.has(e,"refreshToken"))){if(r()){const l=Wr();if(l){const h=await l;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:f.useCallback(async()=>{try{return await o()}catch{return""}},[o])}},X=()=>{const{logout:e}=Ge(),{getAccessToken:s}=oa();return f.useCallback(async(n,a,r={})=>{const i=await s();if(!i)return null;try{const o=x.get(a,"action","").toLowerCase(),l=await fn(n+(o?`?action=${o}`:""),a,{...r,Authorization:`Bearer ${i}`});if(l.status===401)return console.log("401 Response",l),e(),window.location.reload(),null;if(!l.ok){const u=await l.json();throw console.error(`API Error (${l.status}):`,u),{status:l.status,statusText:l.statusText,...u,message:u.error||u.message||`Server error: ${l.status}`}}return await l.json()}catch(o){throw console.error("API request failed:",a,o),o}},[e,s])},ca=()=>{const e=ie(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:B.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[B.GET_DRAFT_PAGE]})}})},ua=()=>{const e=ie(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:B.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[B.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||Q.toast.success("Website settings updated successfully.")},onError:a=>{Q.toast.error("Failed to update website settings",{description:a.message})}})},Jr=()=>{const e=ie(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:B.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[B.GET_WEBSITE_DATA]}),Q.toast.success("Website data updated successfully.")},onError:a=>{Q.toast.error("Failed to update website data",{description:a.message})}})};function Ie(){const[e,s]=f.useState(new URLSearchParams(window.location.search));return f.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Yr=pe.atom({}),da=()=>pe.useAtom(Yr),Xr=()=>{const[e]=Ie(),s=e.get("page"),n=f.useRef(""),{mutate:a}=ca();f.useEffect(()=>{!x.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Ue=(e,s)=>{const[n]=da();return f.useMemo(()=>x.get(n,e,s),[n,e,s])},ie=()=>Ue("apiUrl","/chai/api"),Bs=()=>Ue("usersApiUrl","/chai/users"),cs=()=>Ue("assetsApiUrl","/chai/assets"),Zr=()=>Ue("supabaseInstance",null),Re=e=>{const s=ie(),[n]=Ie(),a=e??n.get("page"),r=X();return G.useQuery({queryKey:[B.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:B.GET_LANGUAGE_PAGES,data:{id:a}});return x.reverse(x.sortBy(i,"primaryPage"))},enabled:!!a})},Ve=()=>{const e=ie(),s=X();return G.useQuery({queryKey:[B.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:B.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},ha=e=>{const{fallbackLang:s}=q.useLanguages(),{data:n}=Ve(),{data:a,isFetching:r}=Re(),i=f.useMemo(()=>{const o={[s]:!0};return x.each(x.get(n,"languages"),l=>{const u=x.find(a,{lang:l});o[l]=!!u}),o},[s,a,n]);return r||x.isEmpty(e)||e&&i[e]},xn=()=>{const e=G.useQueryClient(),{data:s}=G.useQuery({queryKey:[B.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:f.useCallback(a=>{e.setQueryData([B.AI_CONTEXT],a)},[e]),aiContext:s}},ei=pe.atom(null),ma=()=>pe.useAtom(ei),gn=()=>{const[e]=ma();return(e==null?void 0:e.slug)||""};function ti(e,s){const[n,a]=f.useState(e);return f.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const si=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=q.useLanguages(),{data:r}=Ae(),i=r==null?void 0:r.pageType,o=ie(),l=X(),{data:u,isFetching:h}=G.useQuery({queryKey:[B.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await l(o,{action:B.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),d=f.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}},fa=()=>{const{selectedLang:e,fallbackLang:s}=q.useLanguages(),[n,a]=ma(),[r,i]=f.useState(""),o=ti(r,500),{allLangPages:l,data:u,isFetching:h}=si({query:o}),d=f.useCallback(y=>a(y),[a]),m=f.useCallback(y=>i(y),[i]),v=f.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,b=l.filter(E=>(E==null?void 0:E.primaryPage)===p||E.id===p).find(E=>j?E.lang===e||E.lang===s:E.lang===e);a(b||n)},[n,e,l,a,s]);return{isPending:h,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:l,updateDynamicPage:d,updateSearchQuery:m,onChangeLanguage:v}},ni=pe.atom({lastSaved:void 0}),Ms=()=>pe.useAtom(ni),Ae=()=>{const[e]=Ie(),s=e.get("page"),{data:n,isFetching:a}=Re();return{data:f.useMemo(()=>({...x.find(n,{id:s})||{}}),[n,s]),isFetching:a}},Qe=()=>{const[e]=Ie(),s=e.get("lang")??"",{data:n,isFetching:a}=Re();return{data:f.useMemo(()=>x.find(n,{lang:s})||{},[n,s]),isFetching:a}},ai=pe.atom({}),ri=()=>pe.useAtom(ai),xa=()=>{const{data:e}=Qe(),s=gn(),n=Ue("getLiveUrl",x.noop),a=e==null?void 0:e.slug,r=n(a||"/");return s?r+s:r};class ga{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,o,l,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=(l=(o=(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:o.on("presence",{event:"leave"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:l.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(o=>o[0]).filter(Boolean);return s?r=r.filter(o=>o.pageId===s):n&&(r=r.filter(o=>o.userId===n)),r.sort((o,l)=>o.onlineAt-l.onlineAt)}getPageOwner(){const s=this.getOnlineUsers({pageId:this.pageId});return s.length>0?s[0]:null}getPageUserMapping(){const s=this.getOnlineUsers({}),n=x.groupBy(s,"pageId"),a={};return Object.keys(n).forEach(r=>{var o;const i=(o=x.minBy(n[r],"onlineAt"))==null?void 0:o.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 We=e=>{const s=Bs(),n=X();return G.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:B.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!x.isEmpty(e)})},ii=pe.atom(void 0),li=pe.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),oi=pe.atom(""),ci=pe.atom(null),pn=pe.atom({}),pa=()=>pe.useAtom(pn),Je=()=>{const[e]=Ie(),s=e.get("page"),{user:n}=Ge(),[a,r]=pe.useAtom(ii),[i,o]=pe.useAtom(li),[l,u]=pe.useAtom(ci),[h,d]=pe.useAtom(oi),[m]=pe.useAtom(pn);return f.useMemo(()=>({pageLock:i,pageToUser:m,lockingStatus:h,realtimeInstance:l,setPageLock:o,setCurrentEditor:r,setLockingStatus:d,setRealtimeInstance:u,realtimePageLockEnabled:!!l,currentEditor:l?m[s||""]:a,isLocked:l?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a}),[s,n==null?void 0:n.id,i,h,a,l,o,r,d,u,m])},ui=()=>{const e=Zr(),{data:s}=Ae(),{user:n}=Ge(),a=s==null?void 0:s.id,{data:r}=Ve(),{pageLock:i,setPageLock:o,setLockingStatus:l,realtimeInstance:u,setRealtimeInstance:h}=Je(),[,d]=pe.useAtom(pn),m=f.useRef(!1),v=f.useRef(i),y=f.useRef(!1);return f.useEffect(()=>{if(n!=null&&n.id&&e&&!u&&(r!=null&&r.appKey)&&!y.current){y.current=!0;const j=async(w,b)=>{var E,P;switch(w){case"UPDATE_ONLINE_USERS":d((b==null?void 0:b.pageToUser)||{});break;case"PAGE_LOCKED":o({...v==null?void 0:v.current,requestedBy:"",status:"locked",isActiveInOtherTab:b==null?void 0:b.isActiveInOtherTab});break;case"USER_JOINED":if(((E=v==null?void 0:v.current)==null?void 0:E.status)==="editing")return;((P=v==null?void 0:v.current)==null?void 0:P.status)==="locked"&&l("can_edit_now"),o({...v==null?void 0:v.current,requestedBy:"",status:"editing",isActiveInOtherTab:b==null?void 0:b.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":o({...v==null?void 0:v.current,requestingClientId:b==null?void 0:b.requestingClientId,requestedBy:b!=null&&b.isRequestedFromAnotherTab?"ANOTHER_TAB":b==null?void 0:b.requestedBy});break;case"TAKE_OVER_REQUEST_ACCEPTED":b!=null&&b.isTakingOverFromAnotherTab||(l("take_over_request_accepted"),Q.toast.success("Your Page Take Over Request Accepted",{position:"top-center"})),o({...v==null?void 0:v.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":l("take_over_request_rejected"),o({...v==null?void 0:v.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},p=new ga(e,r==null?void 0:r.appKey,n==null?void 0:n.id,j);h(p)}},[h,e,r==null?void 0:r.appKey]),f.useEffect(()=>{v.current=i},[i]),f.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},l(""),o(v.current),u==null||u.leavePage())}},[a,u]),i==null?void 0:i.status},ya=()=>{const{data:e}=Ae(),{user:s}=Ge(),n=e==null?void 0:e.id,{pageLock:a,setPageLock:r,realtimeInstance:i}=Je(),{savePageAsync:o}=q.useSavePage(),l=f.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=f.useCallback(async()=>{!i||!n||!(s!=null&&s.id)||(await o(),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,o,a]),h=f.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:l}},Ye=()=>{const{data:e}=Ve();return f.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},ja=()=>{const[e]=Ie(),s=e.get("page"),n=ie(),{setAiContext:a}=xn(),{setCurrentEditor:r}=Je(),[,i]=Ms(),[,o]=ri(),[,l]=q.useIsPageLoaded(),u=X();return G.useQuery({queryKey:[B.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r(""),l(!1);const h=await u(n,{action:B.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(h.currentEditor);const d=h.blocks??[],m=x.find(d,{_type:"@chai/ai-context"});return a(x.get(m,"_value","")||""),i(v=>({...v,lastSaved:h.lastSaved})),o(x.get(h,"metadata",{})),setTimeout(()=>l(!0),500),d},enabled:!!s})},yn=()=>{const{data:e}=Ae(),{data:s}=Qe(),n=ie(),a=X(),r=Ye(),i=gn();return G.useQuery({queryKey:[B.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:B.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})},us=({children:e})=>t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen flex-col items-center justify-center bg-black/20",children:e}),va=({fullScreen:e=!0})=>{const s=t.jsxs("div",{className:"flex flex-row gap-2",children:[t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-purple-500"}),t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-cyan-500 [animation-delay:-.3s]"}),t.jsx("div",{className:"h-4 w-4 animate-bounce rounded-full bg-pink-500 [animation-delay:-.5s]"})]});return e?t.jsx(us,{children:s}):t.jsx("div",{className:"flex h-full w-full items-center justify-center",children:s})},di=({userId:e})=>{const{data:s}=We(e);return(s==null?void 0:s.name)||"Unknown"};function hi({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,realtimePageLockEnabled:i,isRequestRejected:o,isFetchingUserInfo:l}){const[u,h]=f.useState(!1),[d,m]=f.useState(!1),v=()=>{h(!0),setTimeout(()=>{h(!1)},15e3),m(!1),r()};return t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl",children:[t.jsx(S.LockKeyhole,{className:"h-8 w-8 rounded-md bg-sky-500/20 p-1.5 text-sky-500"}),"Page is locked for editing"]})}),t.jsx(c.CardContent,{className:"w-md grid w-full pt-2",children:t.jsxs("div",{children:[t.jsxs("div",{className:"relative mx-auto flex w-96 items-center space-x-4 rounded-md border border-green-500 px-2 pb-2 pt-4",children:[t.jsx("div",{className:"absolute -top-2.5 left-3 w-max rounded-full bg-green-500 px-3 py-1 text-xs font-medium leading-3 text-white",children:"Locked By"}),e&&!l?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:l?"space-y-1.5":"space-y-0",children:[l?t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"}):t.jsx("span",{className:"truncate font-medium text-black",children:s}),n&&!l?t.jsx("p",{className:"truncate text-sm text-muted-foreground",children:n}):t.jsx(c.Skeleton,{className:"h-4 w-60 rounded"}),a&&!l?t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",ut.formatDistanceToNow(new Date(a),{addSuffix:!0})]}):t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{className:"py-4 text-center text-gray-600",children:["This page is currently being edited by ",t.jsx("span",{className:"font-bold",children:s}),".",t.jsx("br",{}),i&&t.jsxs(t.Fragment,{children:[" ",t.jsx("br",{})," You can either wait until they finish editing or"," ",i?"request to":""," take over the page."]})]})}),o&&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.":o?"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 ps=({isChecking:e,lockingStatus:s,onContinue:n})=>{const[a,r]=f.useState(!1),i=s==="page_is_active_in_other_tab",o=(s==null?void 0:s.length)>0,{pageLock:l,acceptTakeOver:u,rejectTakeOver:h}=ya(),d=()=>{r(!0),o||i?n():u(),setTimeout(()=>{r(!1)},3e3)};return f.useEffect(()=>{(l==null?void 0:l.requestedBy)==="ANOTHER_TAB"&&u()},[l,u]),(l==null?void 0:l.requestedBy)==="ANOTHER_TAB"?null:e?t.jsx(va,{}):t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl font-medium",children:[a?t.jsx(S.Loader,{className:"h-6 w-6 animate-spin text-gray-500"}):i?t.jsx(S.TableIcon,{className:"h-6 w-6 text-green-500"}):o?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":o?"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".'}):o?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(di,{userId:l==null?void 0:l.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:o?"":"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"]}):o?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"]})}),!o&&t.jsxs(c.Button,{variant:"outline",onClick:h,children:[t.jsx(S.X,{className:"h-5 w-5"})," Reject"]})]})]})})},mi=()=>{const{pageLock:e,requestTakeOver:s}=ya(),{isLocked:n,currentEditor:a,lockingStatus:r,setLockingStatus:i,realtimePageLockEnabled:o}=Je(),{data:l,isFetching:u}=We(a),[h]=Ie(),d=h.get("page"),{mutate:m}=ca(),{isFetching:v}=ja(),[y]=Ms(),j=G.useQueryClient(),p=f.useCallback(()=>{o?s():m({id:d})},[d,m,s,o]);return d?o&&(e==null?void 0:e.status)==="checking"?t.jsx(ps,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):o&&(e!=null&&e.requestedBy)?t.jsx(ps,{lockingStatus:"",onContinue:()=>{}}):(o?e.status!=="locked":!n||v)?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(ps,{lockingStatus:r,onContinue:()=>{j.invalidateQueries({queryKey:[B.GET_DRAFT_PAGE]}),i("")}}):null:o&&(e!=null&&e.isActiveInOtherTab)?t.jsx(ps,{lockingStatus:"page_is_active_in_other_tab",onContinue:s}):t.jsx(hi,{...l,isFetchingUserInfo:u,name:(l==null?void 0:l.name)||"Unknown User",email:(l==null?void 0:l.email)||"",lastSaved:(y==null?void 0:y.lastSaved)||"",onTakeOver:p,realtimePageLockEnabled:o,isRequestRejected:r==="take_over_request_rejected"}):null},fi=()=>{const[e,s]=Ie(),n=e.get("lang"),a=ha(n),{setSelectedLang:r}=q.useLanguages(),i=()=>{const l=new URLSearchParams(window.location.search);l.delete("lang");const u=l.toString(),h=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",h),s(l),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const o=x.get(Ne,n);return t.jsx(us,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(S.LockIcon,{className:"h-6 w-6 text-yellow-500"}),'Page missing for "',o,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',o,'" language. Either create the page in the "',o,'" 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"})})]})})},xi=e=>{const s=ie(),n=X();return G.useMutation({mutationFn:async a=>n(s,{action:B.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),Q.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},gi=e=>{const s=ie(),n=X();return G.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:B.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})},pi=e=>{const s=ie(),n=X();return G.useMutation({mutationFn:async a=>n(s,{action:B.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),Q.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},yi=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[o,l]=f.useState(!1),u=q.useUpdateBlocksPropsRealtime(),h=pi(()=>{u([e],{_libBlockId:void 0}),Q.toast.success("Block deleted successfully"),l(!1),a()}),d=()=>{l(!0),h.mutate(s)},m=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:v=>v.preventDefault(),disabled:o,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:o,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:d,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})},ji=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[o,l]=f.useState(!1);return t.jsx(yi,{blockId:e,libBlockId:s,isOpen:o,onClose:()=>{l(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>l(!0),children:[t.jsx(S.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},vi=()=>{const e=ie(),s=X(),n=G.useQueryClient(),{data:a=[],isLoading:r,error:i}=G.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:o,isPending:l}=G.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"]}),Q.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),Q.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:o,isCreating:l}},bi=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),o=f.useRef(null),{groups:l}=vi(),[u,h]=f.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=f.useMemo(()=>[...l,...u.filter(y=>!l.some(j=>j.id===y.id))],[l,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)};f.useEffect(()=>{n&&o.current&&o.current.focus()},[n]);const v=y=>{y.key==="Enter"&&(y.preventDefault(),m())};return f.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:o,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"}),l.length>0&&t.jsx("optgroup",{label:"Library Groups",children:l.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=>!l.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"})})]})},Bn=3*1024*1024,wi=10*1024*1024;function tn(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 ba(e){return new Promise((s,n)=>{if(e.size<=Bn){s(e);return}new Mr(e,{quality:.8,maxWidth:2048,maxHeight:2048,convertSize:Bn,success(a){s(a)},error(a){Q.toast.error(`Failed to compress image. Image size is ${tn(e.size)}, which exceeds the maximum allowed size of ${tn(wi)}.`),n(a)}})})}const Si=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),r=f.useRef(null),i=f.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 ba(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),Q.toast.error("Failed to process image",{description:m instanceof Error?m.message:"Unknown error"})}},[s]),o=()=>{s(""),r.current&&(r.current.value="")},l=()=>{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:l,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:o,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={...q.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"},Ni=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=q.usePartailBlocksStore(),i=s.find(A=>A._id===a),o=i==null?void 0:i._libBlockId,l=!!o,u=f.useMemo(()=>s.some(A=>A._type==="PartialBlock"||A._type==="GlobalBlock"),[s]),h=f.useMemo(()=>{let A=[];for(const R of s)if(R._type==="PartialBlock"||R._type==="GlobalBlock"){let z=r(R.partialBlockId);R._parent&&(z==null?void 0:z.length)>0&&(z=z.map(O=>(x.isEmpty(O._parent)&&x.set(O,"_parent",R._parent),O))),A=[...A,...z]}else A.push(R);return A},[s,r]),[d,m]=f.useState(""),[v,y]=f.useState(""),[j,p]=f.useState(""),[w,b]=f.useState(""),[E,P]=f.useState({}),[D,_]=f.useState(!1),[C,K]=f.useState(l),[ee,V]=f.useState(!1),{hasPermission:I}=q.usePermissions(),M=I(be.DELETE_LIBRARY_BLOCK),$=q.useUpdateBlocksPropsRealtime(),L=()=>{$([a],{_libBlockId:void 0}),Q.toast.success("Block delinked from library"),n()},{data:se,isLoading:W,isError:he}=gi(o);f.useEffect(()=>{he&&l&&(V(!0),K(!1))},[he,l]),f.useEffect(()=>{se&&!W&&(m(se.name||""),y(se.group||""),p(se.description||""),b(se.preview||""),K(!1))},[se,W]),f.useEffect(()=>{const A=d.trim().length>=2,R=v.trim()!=="";_(A&&R)},[d,v]);const je=()=>{const A={};return d.trim()?d.length<2&&(A.name="Name must be at least 2 characters"):A.name="Name is required",v||(A.group="Group is required"),P(A),Object.keys(A).length===0},{resetLibrary:we}=q.useLibraryBlocks({id:""}),oe=xi(A=>{l||$([a],{_libBlockId:A.id}),Q.toast.success(`Block ${l?"updated":"saved"} successfully`),we(A.library),n()}),N=async A=>{if(A.preventDefault(),!je())return;const R=h.map(z=>(x.has(z,"_libBlockId")&&delete z._libBlockId,z));oe.mutate({name:d.trim(),group:v,blocks:R,description:j.trim(),...w&&w.startsWith("data:")?{previewImage:w}:{},...l?{id:o}:{}})},g=oe.isPending;return C||W?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"})}):ee?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:L,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(S.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:N,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:E.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:d,onChange:A=>m(A.target.value),className:E.name?"border-destructive":""}),E.name&&t.jsx("p",{className:"text-xs text-destructive",children:E.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:E.group?"text-destructive":"",children:"Group"}),t.jsx(bi,{value:v,onChange:y}),E.group&&t.jsx("p",{className:"text-xs text-destructive",children:E.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:j,onChange:A=>p(A.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Si,{value:w,onChange:b})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[l&&M&&t.jsx(ji,{blockId:a,libBlockId:o,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||!D,children:g?"Saving...":l?"Update Block":"Save Block"})]})]})]})},re={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."},Ei={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},ke=()=>{const e=ie(),s=X();return G.useQuery({queryKey:[B.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:B.GET_PAGE_TYPES})})},wa=e=>{const{data:s}=ke();return f.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Ci=()=>{const e=ie(),s=X();return G.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:B.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Sa=()=>{const e=ie(),s=G.useQueryClient(),n=X(),{data:a}=ke();return G.useMutation({mutationFn:async r=>await n(e,{action:B.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var l;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]});const o=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((l=x.find(a,{key:i.pageType}))==null?void 0:l.name)+" added successfully":"New page added successfully";Q.toast.success(o)},onError:(r,i)=>{const o=x.find(a,{key:i.pageType});Q.toast.error(`Failed to add new ${o!=null&&o.hasSlug?"page":o.name}.`,{description:x.get(Ei,r.message,r.message)})}})},jn=()=>{const e=ie(),s=G.useQueryClient(),n=X(),{data:a}=Qe(),{data:r}=ke();return G.useMutation({mutationFn:async i=>await n(e,{action:B.UPDATE_PAGE,data:i}),onSuccess:(i,o)=>{(a==null?void 0:a.id)===(o==null?void 0:o.id)&&s.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES]}),o&&(o!=null&&o.primaryPage||o!=null&&o.seo)?(s.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES,o==null?void 0:o.primaryPage]}),s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]})},onError:(i,o)=>{const l=x.find(r,{key:o.pageType});Q.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:i.message})}})},Ti=()=>{const e=ie(),s=G.useQueryClient(),n=X(),{data:a}=ke();return G.useMutation({mutationFn:async r=>n(e,{action:B.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){Q.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const o=x.find(a,{key:i.pageType});Q.toast.error(`Failed to delete ${o!=null&&o.hasSlug?"page":o.name}.`,{description:r.message})}})},Ai=()=>{const e=ie(),s=G.useQueryClient(),n=X(),{data:a}=ke();return G.useMutation({mutationFn:async r=>n(e,{action:B.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]});const o=x.find(a,{key:i.pageType});Q.toast.success(o!=null&&o.hasSlug?re.PAGE_UNPUBLISH_SUCCESS:"New "+o.name+" added successfully.")},onError:(r,i)=>{const o=x.find(a,{key:i.pageType});Q.toast.error(`Failed to take offline ${o!=null&&o.hasSlug?"page":o.name}.`,{description:r.message})}})},vn=()=>{const e=ie(),s=X(),n=G.useQueryClient(),{data:a}=Ae(),{savePageAsync:r}=q.useSavePage();return G.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:B.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[B.GET_CHANGES]}),n.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),Q.toast.error("Failed to publish pages.")}})},ki=()=>{const e=ie(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async a=>{var r;return s(e,{action:B.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:[B.GET_WEBSITE_PAGES]}),Q.toast.success("Page marked as template successfully.")},onError:()=>{Q.toast.error("Failed to mark page as template.")}})},Pi=()=>{const e=ie(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async a=>s(e,{action:B.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]}),Q.toast.success("Page unmarked as template successfully.")},onError:()=>{Q.toast.error("Failed to unmark page as template.")}})},Ii=()=>{const e=ie(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:B.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{Q.toast.success(re.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]})},onError:()=>{Q.toast.error("Failed to change slug")}})};var bn={};(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),o=typeof Path2D=="function"&&typeof DOMMatrix=="function",l=function(){if(!s.OffscreenCanvas)return!1;var N=new OffscreenCanvas(1,1),g=N.getContext("2d");g.fillRect(0,0,1,1);var A=N.transferToImageBitmap();try{g.createPattern(A,"no-repeat")}catch{return!1}return!0}();function u(){}function h(N){var g=n.exports.Promise,A=g!==void 0?g:s.Promise;return typeof A=="function"?new A(N):(N(u,u),null)}var d=function(N,g){return{transform:function(A){if(N)return A;if(g.has(A))return g.get(A);var R=new OffscreenCanvas(A.width,A.height),z=R.getContext("2d");return z.drawImage(A,0,0),g.set(A,R),R},clear:function(){g.clear()}}}(l,new Map),m=function(){var N=Math.floor(16.666666666666668),g,A,R={},z=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(g=function(O){var U=Math.random();return R[U]=requestAnimationFrame(function F(J){z===J||z+N-1<J?(z=J,delete R[U],O()):R[U]=requestAnimationFrame(F)}),U},A=function(O){R[O]&&cancelAnimationFrame(R[O])}):(g=function(O){return setTimeout(O,N)},A=function(O){return clearTimeout(O)}),{frame:g,cancel:A}}(),v=function(){var N,g,A={};function R(z){function O(U,F){z.postMessage({options:U||{},callback:F})}z.init=function(F){var J=F.transferControlToOffscreen();z.postMessage({canvas:J},[J])},z.fire=function(F,J,le){if(g)return O(F,null),g;var H=Math.random().toString(36).slice(2);return g=h(function(ae){function me(xe){xe.data.callback===H&&(delete A[H],z.removeEventListener("message",me),g=null,d.clear(),le(),ae())}z.addEventListener("message",me),O(F,H),A[H]=me.bind(null,{data:{callback:H}})}),g},z.reset=function(){z.postMessage({reset:!0});for(var F in A)A[F](),delete A[F]}}return function(){if(N)return N;if(!a&&i){var z=["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{N=new Worker(URL.createObjectURL(new Blob([z])))}catch(O){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",O),null}R(N)}return N}}(),y={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function j(N,g){return g?g(N):N}function p(N){return N!=null}function w(N,g,A){return j(N&&p(N[g])?N[g]:y[g],A)}function b(N){return N<0?0:Math.floor(N)}function E(N,g){return Math.floor(Math.random()*(g-N))+N}function P(N){return parseInt(N,16)}function D(N){return N.map(_)}function _(N){var g=String(N).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 C(N){var g=w(N,"origin",Object);return g.x=w(g,"x",Number),g.y=w(g,"y",Number),g}function K(N){N.width=document.documentElement.clientWidth,N.height=document.documentElement.clientHeight}function ee(N){var g=N.getBoundingClientRect();N.width=g.width,N.height=g.height}function V(N){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=N,g}function I(N,g,A,R,z,O,U,F,J){N.save(),N.translate(g,A),N.rotate(O),N.scale(R,z),N.arc(0,0,1,U,F,J),N.restore()}function M(N){var g=N.angle*(Math.PI/180),A=N.spread*(Math.PI/180);return{x:N.x,y:N.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:N.startVelocity*.5+Math.random()*N.startVelocity,angle2D:-g+(.5*A-Math.random()*A),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:N.color,shape:N.shape,tick:0,totalTicks:N.ticks,decay:N.decay,drift:N.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:N.gravity*3,ovalScalar:.6,scalar:N.scalar,flat:N.flat}}function $(N,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 A=g.tick++/g.totalTicks,R=g.x+g.random*g.tiltCos,z=g.y+g.random*g.tiltSin,O=g.wobbleX+g.random*g.tiltCos,U=g.wobbleY+g.random*g.tiltSin;if(N.fillStyle="rgba("+g.color.r+", "+g.color.g+", "+g.color.b+", "+(1-A)+")",N.beginPath(),o&&g.shape.type==="path"&&typeof g.shape.path=="string"&&Array.isArray(g.shape.matrix))N.fill(je(g.shape.path,g.shape.matrix,g.x,g.y,Math.abs(O-R)*.1,Math.abs(U-z)*.1,Math.PI/10*g.wobble));else if(g.shape.type==="bitmap"){var F=Math.PI/10*g.wobble,J=Math.abs(O-R)*.1,le=Math.abs(U-z)*.1,H=g.shape.bitmap.width*g.scalar,ae=g.shape.bitmap.height*g.scalar,me=new DOMMatrix([Math.cos(F)*J,Math.sin(F)*J,-Math.sin(F)*le,Math.cos(F)*le,g.x,g.y]);me.multiplySelf(new DOMMatrix(g.shape.matrix));var xe=N.createPattern(d.transform(g.shape.bitmap),"no-repeat");xe.setTransform(me),N.globalAlpha=1-A,N.fillStyle=xe,N.fillRect(g.x-H/2,g.y-ae/2,H,ae),N.globalAlpha=1}else if(g.shape==="circle")N.ellipse?N.ellipse(g.x,g.y,Math.abs(O-R)*g.ovalScalar,Math.abs(U-z)*g.ovalScalar,Math.PI/10*g.wobble,0,2*Math.PI):I(N,g.x,g.y,Math.abs(O-R)*g.ovalScalar,Math.abs(U-z)*g.ovalScalar,Math.PI/10*g.wobble,0,2*Math.PI);else if(g.shape==="star")for(var k=Math.PI/2*3,te=4*g.scalar,Ee=8*g.scalar,Le=g.x,Y=g.y,_e=5,Be=Math.PI/_e;_e--;)Le=g.x+Math.cos(k)*Ee,Y=g.y+Math.sin(k)*Ee,N.lineTo(Le,Y),k+=Be,Le=g.x+Math.cos(k)*te,Y=g.y+Math.sin(k)*te,N.lineTo(Le,Y),k+=Be;else N.moveTo(Math.floor(g.x),Math.floor(g.y)),N.lineTo(Math.floor(g.wobbleX),Math.floor(z)),N.lineTo(Math.floor(O),Math.floor(U)),N.lineTo(Math.floor(R),Math.floor(g.wobbleY));return N.closePath(),N.fill(),g.tick<g.totalTicks}function L(N,g,A,R,z){var O=g.slice(),U=N.getContext("2d"),F,J,le=h(function(H){function ae(){F=J=null,U.clearRect(0,0,R.width,R.height),d.clear(),z(),H()}function me(){a&&!(R.width===r.width&&R.height===r.height)&&(R.width=N.width=r.width,R.height=N.height=r.height),!R.width&&!R.height&&(A(N),R.width=N.width,R.height=N.height),U.clearRect(0,0,R.width,R.height),O=O.filter(function(xe){return $(U,xe)}),O.length?F=m.frame(me):ae()}F=m.frame(me),J=ae});return{addFettis:function(H){return O=O.concat(H),le},canvas:N,promise:le,reset:function(){F&&m.cancel(F),J&&J()}}}function se(N,g){var A=!N,R=!!w(g||{},"resize"),z=!1,O=w(g,"disableForReducedMotion",Boolean),U=i&&!!w(g||{},"useWorker"),F=U?v():null,J=A?K:ee,le=N&&F?!!N.__confetti_initialized:!1,H=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,ae;function me(k,te,Ee){for(var Le=w(k,"particleCount",b),Y=w(k,"angle",Number),_e=w(k,"spread",Number),Be=w(k,"startVelocity",Number),qs=w(k,"decay",Number),zs=w(k,"gravity",Number),$s=w(k,"drift",Number),hs=w(k,"colors",D),Vs=w(k,"ticks",Number),ms=w(k,"shapes"),Ks=w(k,"scalar"),Hs=!!w(k,"flat"),Mt=C(k),ht=Le,Ze=[],fs=N.width*Mt.x,xs=N.height*Mt.y;ht--;)Ze.push(M({x:fs,y:xs,angle:Y,spread:_e,startVelocity:Be,color:hs[ht%hs.length],shape:ms[E(0,ms.length)],ticks:Vs,decay:qs,gravity:zs,drift:$s,scalar:Ks,flat:Hs}));return ae?ae.addFettis(Ze):(ae=L(N,Ze,J,te,Ee),ae.promise)}function xe(k){var te=O||w(k,"disableForReducedMotion",Boolean),Ee=w(k,"zIndex",Number);if(te&&H)return h(function(Be){Be()});A&&ae?N=ae.canvas:A&&!N&&(N=V(Ee),document.body.appendChild(N)),R&&!le&&J(N);var Le={width:N.width,height:N.height};F&&!le&&F.init(N),le=!0,F&&(N.__confetti_initialized=!0);function Y(){if(F){var Be={getBoundingClientRect:function(){if(!A)return N.getBoundingClientRect()}};J(Be),F.postMessage({resize:{width:Be.width,height:Be.height}});return}Le.width=Le.height=null}function _e(){ae=null,R&&(z=!1,s.removeEventListener("resize",Y)),A&&N&&(document.body.contains(N)&&document.body.removeChild(N),N=null,le=!1)}return R&&!z&&(z=!0,s.addEventListener("resize",Y,!1)),F?F.fire(k,Le,_e):me(k,Le,_e)}return xe.reset=function(){F&&F.reset(),ae&&ae.reset()},xe}var W;function he(){return W||(W=se(null,{useWorker:!0,resize:!0})),W}function je(N,g,A,R,z,O,U){var F=new Path2D(N),J=new Path2D;J.addPath(F,new DOMMatrix(g));var le=new Path2D;return le.addPath(J,new DOMMatrix([Math.cos(U)*z,Math.sin(U)*z,-Math.sin(U)*O,Math.cos(U)*O,A,R])),le}function we(N){if(!o)throw new Error("path confetti are not supported in this browser");var g,A;typeof N=="string"?g=N:(g=N.path,A=N.matrix);var R=new Path2D(g),z=document.createElement("canvas"),O=z.getContext("2d");if(!A){for(var U=1e3,F=U,J=U,le=0,H=0,ae,me,xe=0;xe<U;xe+=2)for(var k=0;k<U;k+=2)O.isPointInPath(R,xe,k,"nonzero")&&(F=Math.min(F,xe),J=Math.min(J,k),le=Math.max(le,xe),H=Math.max(H,k));ae=le-F,me=H-J;var te=10,Ee=Math.min(te/ae,te/me);A=[Ee,0,0,Ee,-Math.round(ae/2+F)*Ee,-Math.round(me/2+J)*Ee]}return{type:"path",path:g,matrix:A}}function oe(N){var g,A=1,R="#000000",z='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof N=="string"?g=N:(g=N.text,A="scalar"in N?N.scalar:A,z="fontFamily"in N?N.fontFamily:z,R="color"in N?N.color:R);var O=10*A,U=""+O+"px "+z,F=new OffscreenCanvas(O,O),J=F.getContext("2d");J.font=U;var le=J.measureText(g),H=Math.ceil(le.actualBoundingBoxRight+le.actualBoundingBoxLeft),ae=Math.ceil(le.actualBoundingBoxAscent+le.actualBoundingBoxDescent),me=2,xe=le.actualBoundingBoxLeft+me,k=le.actualBoundingBoxAscent+me;H+=me+me,ae+=me+me,F=new OffscreenCanvas(H,ae),J=F.getContext("2d"),J.font=U,J.fillStyle=R,J.fillText(g,xe,k);var te=1/A;return{type:"bitmap",bitmap:F.transferToImageBitmap(),matrix:[te,0,0,te,-H*te/2,-ae*te/2]}}n.exports=function(){return he().apply(this,arguments)},n.exports.reset=function(){he().reset()},n.exports.create=se,n.exports.shapeFromPath=we,n.exports.shapeFromText=oe})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),bn,!1);const _i=bn.exports;bn.exports.create;const Di={particleCount:350,spread:120,origin:{y:.6},angle:90},Li={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Ut=e=>{let s=Li[e];s||(s={});const n={...Di,...s};_i(n)},Bi=()=>{const[e]=q.useTheme(),{mutate:s,isPending:n}=vn(),{mutateAsync:a,isPending:r}=ua(),i=()=>{a({settings:{theme:e}})},o=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{Ut("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"flex items-center justify-center gap-x-3 border-t bg-white py-3",children:[t.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(c.Button,{size:"sm",disabled:n||r,onClick:o,children:"Publish"})]})},Lt=()=>{const e=X(),s=ie();return G.useQuery({queryKey:[B.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:B.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Mi=e=>{const s=X(),n=ie(),a=Ye();return G.useQuery({queryKey:[B.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:B.GET_WEBSITE_PAGES,data:{lang:e}})||[];return x.keyBy(x.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})};function Ft(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 ds=pe.atom(null),Oi=e=>{if(!e)return{base:e,extension:null};const s=e.lastIndexOf(".");if(s<=0)return{base:e,extension:null};const n=e.substring(s);return{base:e.substring(0,s),extension:n}},ct=e=>{if(!e)return e;const{base:s}=Oi(e);return s};function Ri(e,s){const n=(e||"").split("/").filter(Boolean);let a="",r=!0;if(s.slug==="/"){const i=n.pop()||"";if(Ne[i])r=!0;else{a=i;const o=n.pop()||"";r=!!Ne[o]}}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 Gi=e=>e&&ct(e),Mn=(e,s)=>{const n=ct(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function wn({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:o}){const[l,u]=f.useState(e),[h,d]=f.useState(null);f.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,w=p<=1;p>1?d("Invalid slug. Only one dot (.) is allowed in the slug"):d(null),r&&r(w),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:Gi(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:l,onChange:m,placeholder:n,className:h?"border-red-500":""}),h&&t.jsx("div",{className:"mt-1 text-xs text-red-500",children:h})]}),o&&o!=="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:o})]})})]})}const Na=({edit:e,lang:s,languages:n,name:a,setLang:r,setName:i,primaryPageObject:o})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",children:re.LANGUAGE}),t.jsxs("select",{value:e?"":s,disabled:e||!n.length,onChange:l=>{const u=l.target.value;r(u),!e&&(x.startsWith(a,o==null?void 0:o.name)||a.length===0)&&i(`${o==null?void 0:o.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?re.CHOOSE_LANGUAGE:re.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(l=>t.jsx("option",{value:l,children:Ne[l]||l},l))]})]}),Ea=({lang:e,name:s,setName:n,parentHasSelectedLanguagePage:a})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"name",children:re.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?re.ENTER_PAGE_NAME:re.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),Ui=({dynamic:e,isNonSlugPageType:s,isRootPage:n,lang:a,useLanguagePrefix:r,setUseLanguagePrefix:i,isHomePage:o,parentSlug:l,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:re.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(wn,{disabled:!a||!u,value:h,onChange:d,placeholder:a?o&&r?"Leave empty for home page":re.ENTER_PAGE_SLUG:re.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:l,onValidationChange:m,fullSlug:v()})]}),Ca=({parentHasSelectedLanguagePage:e,name:s,lang:n,slug:a,edit:r,id:i,primaryPageObject:o,pages:l,isNonSlugPageType:u,isHomePage:h,useLanguagePrefix:d,isSlugValid:m,isPending:v})=>{const y=v||!s||!n||l.some(j=>(r?j.id!==i:!0)&&j.parent===(o==null?void 0:o.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&&!o.dynamic,children:v?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?re.UPDATING:re.ADDING]}):r?re.UPDATE:re.ADD_NEW_LANGUAGE}),l.some(j=>(r?j.id!==i:!0)&&j.parent===(o==null?void 0:o.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."]})})})},Fi=({onSubmit:e,edit:s,lang:n,languages:a,name:r,setLang:i,setName:o,primaryPageObject:l,parentHasSelectedLanguagePage:u,id:h,pages:d,isNonSlugPageType:m,isHomePage:v,useLanguagePrefix:y,slug:j,isSlugValid:p,isPending:w})=>t.jsxs("form",{onSubmit:e,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(Na,{edit:s,lang:n,languages:a,name:r,setLang:i,setName:o,primaryPageObject:l}),t.jsx(Ea,{lang:n,name:r,setName:o,parentHasSelectedLanguagePage:u})]}),t.jsx(Ca,{parentHasSelectedLanguagePage:u,name:r,lang:n,slug:j,edit:s,id:h,primaryPageObject:l,pages:d,isNonSlugPageType:m,isHomePage:v,useLanguagePrefix:y,isSlugValid:p,isPending:w})]}),qi=({loading:e,onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u,parentHasSelectedLanguagePage:h,isNonSlugPageType:d,isRootPage:m,useLanguagePrefix:v,setUseLanguagePrefix:y,isHomePage:j,parentSlug:p,slug:w,setSlug:b,isSlugValid:E,setIsSlugValid:P,getSlug:D,isPending:_,id:C,pages:K})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(S.Loader,{className:"animate-spin"})}):d?t.jsx(Fi,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u,parentHasSelectedLanguagePage:h,id:C,pages:K,isNonSlugPageType:d,isHomePage:j,useLanguagePrefix:v,slug:w,isSlugValid:E,isPending:_}):t.jsxs("form",{onSubmit:s,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(Na,{edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u}),t.jsx(Ea,{lang:a,name:i,setName:l,parentHasSelectedLanguagePage:h}),t.jsx(Ui,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:d,isRootPage:m,lang:a,useLanguagePrefix:v,setUseLanguagePrefix:y,isHomePage:j,parentSlug:p,parentHasSelectedLanguagePage:h,slug:w,setSlug:b,isSlugValid:E,setIsSlugValid:P,getSlug:D})]}),t.jsx(Ca,{parentHasSelectedLanguagePage:h,name:i,lang:a,slug:w,edit:n,id:C,primaryPageObject:u,pages:K,isNonSlugPageType:d,isHomePage:j,useLanguagePrefix:v,isSlugValid:E,isPending:_})]}),zi=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:o=[]}=Lt(),l=f.useMemo(()=>o.find(H=>H.id===a),[o,a]),[u,h]=f.useState(""),[d,m]=f.useState(""),[v,y]=f.useState(""),[j,p]=f.useState(!0),[w,b]=f.useState(!0),{mutate:E,isPending:P}=Sa(),{mutate:D,isPending:_}=jn(),C=P||_,{data:K,isFetching:ee}=Ve(),V=Ye(),{data:I,isFetching:M}=Re(a),{data:$=[],isFetching:L}=Re(l==null?void 0:l.parent),{data:se=[],isFetching:W}=ke(),{setSelectedLang:he}=q.useLanguages(),[,je]=Ie(),[,we]=q.useSidebarActivePanel(),oe=ee||M||L||W,N=f.useMemo(()=>x.filter(K==null?void 0:K.languages,H=>!x.find(I,{lang:H})),[K,I]),g=f.useMemo(()=>se.find(H=>H.key===(l==null?void 0:l.pageType)),[se,l==null?void 0:l.pageType]),A=!(g!=null&&g.hasSlug),R=(l==null?void 0:l.slug)==="/";f.useEffect(()=>{if(!r&&l&&i&&(m(i),h(`${l.name} - ${Ne[i]}`)),!r||!l)return;const H=I==null?void 0:I.find(k=>k.id===e);if(!H)return;h(H.name),m(H.lang);const ae=H.slug||"",{initSlug:me,prefix:xe}=Ri(ae,l);y(me),b(xe)},[r,e,I,l,i]),f.useEffect(()=>{if(i)m(i);else if((N==null?void 0:N.length)===1&&!r){const H=N[0];if(!H||!Ne[H])return;m(H),(!u||u===(l==null?void 0:l.name))&&h(`${l==null?void 0:l.name} - ${Ne[H]}`)}},[i,N,r,u,l]);const{parentSlug:z,isRootPage:O}=f.useMemo(()=>{if(R||!d)return{parentSlug:void 0,isRootPage:!(l!=null&&l.parent)};if(!(l!=null&&l.parent))return{parentSlug:w?`/${d}`:void 0,isRootPage:!0};const H=$==null?void 0:$.find(ae=>ae.lang===d);return{parentSlug:H==null?void 0:H.slug,isRootPage:!1}},[l==null?void 0:l.parent,$,w,d,R]),U=f.useMemo(()=>O?!0:!!($!=null&&$.some(H=>(H==null?void 0:H.lang)===d)),[d,$,O]),F=()=>{let H="";return O?H=`/${w?[d,v].filter(Boolean).join("/"):v}`:H=`${ct(z)}/${v}`,H.replace(/\/{2,}/g,"/").replace(/\/$/,"")},J=H=>{const ae=new URLSearchParams(window.location.search);V&&H===V?ae.delete("lang"):ae.set("lang",H),je(ae),window.dispatchEvent(new PopStateEvent("popstate"))},le=H=>{H.preventDefault();const ae={name:u,lang:d,primaryPage:l==null?void 0:l.id,slug:A?"":F(),pageType:l==null?void 0:l.pageType,...r&&{id:e}},me=()=>{!r&&d&&(he(d),J(d)),we("outline"),n()};r?D(ae,{onSuccess:me}):E(ae,{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?re.EDIT_LANGUAGE:re.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:re.ENTER_LANGUAGE_DETAILS})]}),t.jsx(qi,{id:e,pages:o,loading:oe,onSubmit:le,edit:r,lang:d,languages:N,name:u,setLang:m,setName:h,primaryPageObject:l,parentHasSelectedLanguagePage:U,isNonSlugPageType:A,isRootPage:O,useLanguagePrefix:w,setUseLanguagePrefix:b,isHomePage:R,parentSlug:z,slug:v,setSlug:y,isSlugValid:j,setIsSlugValid:p,getSlug:F,isPending:C})]})})},$i=ia("expandedPagesState",[]),Sn=e=>x.flatMap(e,s=>[s,...s.children?Sn(s.children):[]]),Vi=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const o=[...r,i.id];if(i.id===s)return o;if(i.children&&i.children.length>0){const l=n(i.children,o);if(l)return l}}return null};return n(e)||[]},Ta=(e,s)=>{if(!s)return[];const n=Sn(e),a=x.find(n,r=>r.id===s);if(a){if(a.parent)return[...Ta(e,a.parent),s];const r=Vi(e,s);if(!x.isEmpty(r))return r}return[s]},Ki=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const o=[...r,i.id];i.shouldExpandOnSearch&&o.forEach(l=>s.add(l)),i.children&&!x.isEmpty(i.children)&&n(i.children,o)})};return n(e),Array.from(s)},Os=e=>{const[s,n]=pe.useAtom($i),a=e?x.includes(s,e):!1,r=f.useCallback(()=>{n(h=>a?x.filter(h,d=>d!==e):[...h,e])},[n,a,e]),i=f.useCallback((h,d)=>{if(!d||x.isEmpty(h))return;const m=Sn(h),v=Ta(m,d);if(!Array.isArray(v)||x.isEmpty(v))return;const y=v.slice(0,-1);x.isEmpty(y)||n(j=>x.uniq([...j,...y]))},[n]),o=f.useCallback(h=>{if(x.isEmpty(h))return;const d=Ki(h);x.isEmpty(d)||n(m=>x.union(m,d))},[n]),l=f.useCallback(h=>{if(x.isEmpty(h))return;const d=x.flatMap(h,m=>{const v=y=>[y.id,...y.children?x.flatMap(y.children,v):[]];return v(m)});n(d)},[n]),u=f.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:o,setExpandedPages:n,expandAll:l,collapseAll:u}},On=(e,s)=>!e||!Array.isArray(e)?[]:x.isEmpty(s)?e:x.compact(x.filter(e,n=>{const a=x.toLower(s);return x.includes(x.toLower((n==null?void 0:n.name)||""),a)||x.includes(x.toLower((n==null?void 0:n.slug)||""),a)})),Hi=(e,s)=>{const n=new Set,a=x.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])},sn=(e,s,n)=>x.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?sn(a.children,s,n):[]};const r=a.children&&a.children.some(i=>x.includes(x.toLower(i.name||""),x.toLower(s))||x.includes(x.toLower(i.slug||""),x.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?sn(a.children,s,n):[]}}),Qi=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},Aa=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Aa(n.children):[]})),Wi=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=x.compact(x.filter(e,{pageType:n}))),x.isEmpty(s))r=On(r,s);else{const d=On(r,s),m=Hi(e,d);r=x.uniqBy([...d,...m],"id")}const i=Aa(Qi(r)),o=sn(i,s,a),l=x.filter(o,d=>a(d.pageType)).sort((d,m)=>(d.name||"").localeCompare(m.name||"")),u=x.filter(o,d=>!a(d.pageType));let h=[];if(n==="all"){const d=x.keyBy(u,"pageType");h=Object.values(x.mapValues(d,(m,v)=>({...m,id:v,name:x.startCase(v),isPartialGroup:!0,children:o.filter(y=>y.pageType===v)})))}else h=u.sort((d,m)=>(d.name||"").localeCompare(m.name||""));return[...l,...h]},Ji=({selectedPageType:e,setSelectedPageType:s})=>{const[n,a]=f.useState(""),{data:r}=ke(),i=l=>{if(!n)return!0;const u=n.toLowerCase(),h=d=>String(x.get(l,d,"")).toLowerCase().includes(u);return h("name")||h("key")},o=r.find(l=>l.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:(o==null?void 0:o.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:l=>a(l.target.value),onKeyDown:l=>l.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"}),!x.isEmpty(x.filter(r,l=>l.hasSlug&&i(l)))&&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"}),x.map([...x.filter(r,l=>l.hasSlug&&i(l))].sort((l,u)=>x.get(l,"name","").localeCompare(x.get(u,"name",""))),l=>t.jsx(c.SelectItem,{value:x.get(l,"key"),children:x.get(l,"name")},x.get(l,"key")))]}),!x.isEmpty(x.filter(r,l=>!l.hasSlug&&i(l)))&&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"}),x.map([...x.filter(r,l=>!l.hasSlug&&i(l))].sort((l,u)=>x.get(l,"name","").localeCompare(x.get(u,"name",""))),l=>t.jsx(c.SelectItem,{value:x.get(l,"key"),children:x.get(l,"name")},x.get(l,"key")))]}),x.isEmpty(x.filter(r,i))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})},Yi=({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"})]}),Xi=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Os(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"})]})]})},ka=({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))})},Rn=()=>{const e=G.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:[B.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"})]})},Zi=({pages:e,search:s,setSearch:n,languages:a,onAddPage:r,selectedLanguage:i,setSelectedLanguage:o,selectedPageType:l,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(Ji,{selectedPageType:l,setSelectedPageType:u}),t.jsx(Yi,{search:s,setSearch:n}),t.jsx(Xi,{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(Rn,{})]}),m?t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(ka,{languages:a,selectedLanguage:i,setSelectedLanguage:v=>{o(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(Rn,{})]})]}):t.jsx("div",{className:"flex items-center justify-between gap-2"})]})};function ot({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 Pa=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:o,children:l,isLanguagePage:u})=>{const{hasPermission:h}=q.usePermissions(),{data:d}=ke(),m=f.useMemo(()=>x.find(d,{key:e.pageType}),[d,e.pageType]),v=f.useMemo(()=>!!e.isTemplate,[e.isTemplate]),y=f.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:l}),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"}),re.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"}),re.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(),o(e)},children:[t.jsx(S.SquareLibrary,{className:"size-3"}),re.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"}),re.MARK_AS_TEMPLATE]})})]})]})},el=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Os(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":""}`})})},tl=({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"})}),sl=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),nl=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i,showUntranslatedPages:o})=>{const[l]=pa(),u=Ye(),h=n===e.id,d=!!e.isTemplate,m=f.useMemo(()=>x.find(s,{key:e.pageType}),[s,e.pageType]),v=l==null?void 0:l[e.id],{data:y}=We(v),j=y?y==null?void 0:y.name:null;let p=x.get(r,e==null?void 0:e.id);p=x.get(p,"lang")===i?p:null;const w=i===u||!!p,b=(p==null?void 0:p.name)||(e==null?void 0:e.name)||"No name";let E=(p==null?void 0:p.slug)||(e==null?void 0:e.slug)||"";const P=E+(e!=null&&e.dynamic?`/${m==null?void 0:m.dynamicSlug}`:"")+(e!=null&&e.dynamicSlugCustom?`${e.dynamicSlugCustom}`:"");if(E.startsWith("/")&&!o){const _=E.split("/").pop();E=E.endsWith(_)&&e.dynamic?"":`/${_}`}const D=f.useMemo(()=>{const _="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]",C=`${h?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return w?`${_} ${C} ${j?"opacity-60":""}`:`${_} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[w,h,j]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&w&&a("select",e==null?void 0:e.id),className:D,children:[t.jsx(el,{page:e}),!e.isPartialGroup&&t.jsx(sl,{isOnline:p?p.online:e.online}),t.jsx(tl,{page:e,pageType:m}),t.jsx(ot,{content:b,side:"top",showTooltip:b.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:b})}),(E||e.dynamic)&&t.jsx(ot,{content:P,side:"top",showTooltip:!0,children:t.jsxs("span",{className:"max-w-[40%] truncate font-mono text-xs text-muted-foreground",children:[E,e.dynamic&&(m==null?void 0:m.dynamicSlug)&&t.jsxs("span",{className:"text-xs text-gray-500",children:["/",m==null?void 0:m.dynamicSlug,e.dynamicSlugCustom]})]})}),d&&t.jsx(ot,{content:"Template",side:"top",children:t.jsx("span",{className:"text-blue-500",children:t.jsx(S.NotepadText,{size:16})})}),!e.isPartialGroup&&w&&!j?t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(Pa,{isLanguagePage:!!p,page:p||e,setDuplicatePage:_=>a("duplicate",_),setAddEditPage:_=>a("edit",p||_),setUnpublishPage:_=>a("unpublish",_),setDeletePage:_=>a("delete",p||_),setMarkAsTemplate:_=>a("markAsTemplate",_),setUnmarkAsTemplate:_=>a("unmarkAsTemplate",_),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:_=>_.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:!w&&!e.isPartialGroup&&!j&&t.jsxs("button",{onClick:_=>{_.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 ",x.get(Ne,i)," Page"]})]})})]})},Ia=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l})=>{const{expandedPages:u}=Os();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(nl,{page:h,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l}),h.children&&h.children.length>0&&(u==null?void 0:u.includes(h.id))&&t.jsx(Ia,{pages:h.children,tier:s+1,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l})]},h.id))})};function al({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,o]=f.useState(null),l=f.useRef(null),[u,h]=f.useState(a+e);f.useEffect(()=>{h(a+e)},[e,a]);const d=y=>{const j=y.target.value;if(!j.startsWith(a)){const D=j.replace(a,""),_=a+D;h(_),s(D);return}const w=j.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),b=(w.match(/\./g)||[]).length,E=b<=1;b>1?o("Invalid slug. Only one dot (.) is allowed in the slug"):o(null),r&&r(E);const P=a+w;h(P),s(w)},m=()=>{if(l.current){const y=l.current;setTimeout(()=>{const j=a.length;y.setSelectionRange(j,j)},0)}},v=y=>{const j=y.currentTarget;(j.selectionStart||0)<=a.length&&setTimeout(()=>{const w=a.length;j.setSelectionRange(w,w)},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:l,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 Es=({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})},Ws=(...e)=>e.filter(Boolean).join(" ");function rl({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage",currentPage:i}){const[o,l]=f.useState(!1),[u,h]=f.useState(""),d=q.useChaiFeatureFlag("enable-add-page-dropdown");d||(a="w-full rounded-md border border-gray-300 px-3 py-2");const m=f.useMemo(()=>!e||e.length===0?[]:e.filter(E=>!x.isEmpty(E.slug)).filter(E=>E.slug!=="/").sort((E,P)=>E.slug.localeCompare(P.slug)),[e]),v=f.useMemo(()=>{if(!u.trim())return m;const b=u.toLowerCase();return m.filter(E=>E.name.toLowerCase().includes(b)||E.slug.toLowerCase().includes(b))},[m,u]),y=b=>Math.max(0,(b.match(/\//g)||[]).length-1),j=b=>"    ".repeat(b),p=b=>{if(b==="/")return"/";const E=b.split("/").filter(Boolean);if(E.length<=1){const P=E[0]||"";return`/${ct(P)}`}return`/${ct(E[E.length-1])}`},w=()=>{if(!s||s==="none")return"None";const b=m.find(E=>E.id===s);return b?`${b.name} (${p(b.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:o,onOpenChange:l,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{id:r,variant:"outline",role:"combobox",className:Ws("w-full justify-between",a),"data-testid":"parent-page-selector",children:[w(),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:b=>h(b.target.value)})]})})}),t.jsxs(Es,{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(""),l(!1),h("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(S.Check,{className:Ws("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),v.map(b=>{const E=j(y(b.slug)),P=p(b.slug),D=t.jsxs("span",{className:"flex items-center text-sm",children:[E,b.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",P,")"]})]});return t.jsxs(c.CommandItem,{value:b.id,onSelect:()=>{n(b.id),l(!1),h("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:D}),t.jsx(S.Check,{className:Ws("mr-2 h-4 w-4 shrink-0",s===b.id?"opacity-100":"opacity-0")})]},b.id)})]})]})]})})]}):t.jsxs("select",{id:r,value:s||"none",onChange:b=>n(b.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),m.map(b=>{const E=y(b.slug),P=E>0?j(E):"",D=p(b.slug);return(i==null?void 0:i.id)===b.id||b.slug.startsWith(i==null?void 0:i.slug)?null:t.jsxs("option",{value:b.id,children:[P,b.name," (",D,")"]},b.id)})]})]})}const il=(...e)=>e.filter(Boolean).join(" "),ll=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=f.useState(""),[o,l]=f.useState(!1),[u,h]=f.useState(""),d=q.useChaiFeatureFlag("enable-add-page-dropdown");if(f.useEffect(()=>{if(s){const p=e.find(w=>w.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 w=p.libraryName;m[w]||(m[w]=[]),m[w].push(p)});const v=Object.entries(m).reduce((p,[w,b])=>{const E=b.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())||w.toLowerCase().includes(u.toLowerCase()));return E.length>0&&(p[w]=E),p},{}),y=e.find(p=>p.id===s),j=y?x.startCase(y.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[d?t.jsxs(c.Popover,{open:o,onOpenChange:l,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(Es,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(v).map(([p,w])=>t.jsx(c.CommandGroup,{heading:p,children:w.map(b=>t.jsxs(c.CommandItem,{value:b.id,onSelect:()=>{n(b.id),l(!1),h("")},className:"flex cursor-pointer items-center justify-between",children:[x.startCase(b.name),t.jsx(S.Check,{className:il("mr-2 h-4 w-4",s===b.id?"opacity-100":"opacity-0")})]},b.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,w])=>t.jsx("optgroup",{label:p,children:w.map(b=>t.jsx("option",{value:b.id,children:x.startCase(b.name)},b.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"})]})]})},ol=()=>{const e=ie(),s=X();return G.useQuery({queryKey:[B.GET_LIBRARIES],queryFn:async()=>await s(e,{action:B.GET_LIBRARIES})||[]})},cl=e=>{const s=ie(),n=X();return G.useQuery({queryKey:[B.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:B.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?x.filter(a,{pageType:e}):a)||[]}})},ul=e=>{const{data:s=[],isLoading:n}=cl(e),{data:a=[],isLoading:r}=ol(),i=f.useMemo(()=>n||r?[]:s.map(l=>{const u=x.find(a,{id:l.library});return{...l,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]),o=f.useMemo(()=>x.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:o,isLoading:n||r}},Nn=()=>{const[,e]=Ie();return f.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},qt=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:"",metaOther:""},jsonLD:{},metaOther:{}};e!=null&&e.defaultSeo&&(x.has(e.defaultSeo,s)&&x.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};e!=null&&e.defaultJSONLD&&(x.has(e.defaultJSONLD,s)&&x.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],x.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,x.set(n,"seo.jsonLD",JSON.stringify(a))));let r={};return e!=null&&e.defaultMetaTags&&(x.has(e.defaultMetaTags,s)&&x.isObject(e.defaultMetaTags[s])?(r=e.defaultMetaTags[s],x.set(n,"seo.metaOther",JSON.stringify(r))):(r=e.defaultMetaTags,x.set(n,"seo.metaOther",JSON.stringify(r)))),{seo:n.seo,jsonLD:n.jsonLD,metaOther:r}},at=(...e)=>e.filter(Boolean).join(" ");function dl({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var fs,xs;const r=Nn(),i=!!(e!=null&&e.id),{data:o}=Lt(),{mutate:l,isPending:u}=Sa(),{mutate:h,isPending:d}=jn(),[m,v]=f.useState(null),[y,j]=f.useState(!0),[p,w]=f.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:b}=q.usePermissions(),E=b(be.CHANGE_PAGE_TYPE),[P,D]=f.useState(!1),[_,C]=f.useState(""),{selectedLang:K,fallbackLang:ee}=q.useLanguages(),V=K||ee,[I,M]=f.useState(""),[$,L]=f.useState(!1),se=f.useMemo(()=>{const T=s.find(ce=>ce.key===p);return(T==null?void 0:T.hasSlug)===!1},[p,s]),[W,he]=f.useState((e==null?void 0:e.parent)??""),[je,we]=f.useState((e==null?void 0:e.name)??""),[oe,N]=f.useState((e==null?void 0:e.dynamic)??!1),[g,A]=f.useState(oe?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[R,z]=f.useState((e==null?void 0:e.dynamicSlugCustom)??""),[O,U]=f.useState(!0),[F,J]=f.useState(!1),[le,H]=f.useState(""),{data:ae,isLoading:me}=ul(p),xe=u||d,k=q.useChaiFeatureFlag("enable-add-page-dropdown"),te=f.useMemo(()=>!i||!(e!=null&&e.id)||!o?null:o.find(T=>T.id===e.id),[i,e==null?void 0:e.id,o]),Ee=(te==null?void 0:te.online)||!1,Le=f.useMemo(()=>!i||!(e!=null&&e.id)||!o?!1:o.some(T=>T.parent===e.id),[i,e==null?void 0:e.id,o]),Y=s.find(T=>T.key===p),_e=T=>{if(i&&p!==T){C(T),D(!0),M(""),L(!1);return}w(T),M(""),L(!1)},Be=()=>{w(_),D(!1),N(!1)},qs=T=>{N(T),T?A(""):z("")},zs=T=>{if(he(T),T&&T!=="none"){const ce=o==null?void 0:o.find(De=>De.id===T),Fe=(ce==null?void 0:ce.slug)||"";if(g.startsWith(Fe)){const De=g.slice(Fe.length).replace(/^\/+/,"");A(De)}else A(g.replace(/^\/+/,""))}else A(g?`${g}`:"")},$s=T=>{H(T)},hs=()=>je.trim()?oe&&!x.isEmpty(g)?(v("Slug must be empty when using dynamic slug"),!1):oe&&!O?(v("Dynamic slug is invalid"),!1):!0:(Q.toast.error("Name is required"),!1),Vs=()=>{const T={pageType:Y==null?void 0:Y.key,name:je,slug:"",hasSlug:!1};i?h({id:e==null?void 0:e.id,name:je},{onSuccess:()=>{Q.toast.success((Y==null?void 0:Y.name)+" updated successfully"),n()}}):l(T,{onSuccess:ce=>{n(),r(ce.page.id,a)}})},ms=(T,ce)=>{if(!T.trim()&&!oe)return v("Child page slug is required"),!1;const Fe=ct(ce),De=Mn(Fe,T);return Object.keys(Ne).some(gs=>De===`/${gs}`||(De==null?void 0:De.startsWith(`/${gs}/`)))?(v("Slugs cannot start with a language code for primary page"),!1):!0},Ks=(T,ce)=>{const Fe=ct(ce),De=Mn(Fe,T),Oe={pageType:p,name:je,slug:De.replace(/\/$/,""),parent:W,dynamic:oe,hasSlug:!0,template:le||void 0,tracking:{},seo:{},jsonLD:{}};if(oe&&(Oe.dynamicSlugCustom=R),i){const qe=x.pick(Oe,["pageType","parent","name","slug","dynamic","dynamicSlugCustom"]);h({id:e==null?void 0:e.id,...qe},{onSuccess:()=>{Q.toast.success("Page updated successfully"),n()}})}else{const qe=x.find(s,{key:p});qe!=null&&qe.trackingDefault&&(Oe.tracking=qe.trackingDefault);const{seo:gs,jsonLD:_r}=qt(qe,V);x.set(Oe,"seo",gs),x.set(Oe,"jsonLD",_r),l(Oe,{onSuccess:Dr=>{n(),r(Dr.page.id,a)}})}},Hs=()=>{const T={pageType:p,name:je,slug:g===""?"/":`/${g.replace(/\/$/,"")}`,template:le||void 0,parent:null,tracking:{}};if(i)h({id:e==null?void 0:e.id,...T},{onSuccess:()=>{Q.toast.success("Page updated successfully"),n()}});else{const ce=x.find(s,{key:p});ce!=null&&ce.trackingDefault&&(T.tracking=ce.trackingDefault);const{seo:Fe,jsonLD:De}=qt(ce,V);x.set(T,"seo",Fe),x.set(T,"jsonLD",De),l(T,{onSuccess:Oe=>{var qe;(qe=Oe==null?void 0:Oe.page)!=null&&qe.id&&r(Oe.page.id,a),n()}})}},Mt=T=>{if(T.preventDefault(),v(null),!!hs()){if(!(Y!=null&&Y.hasSlug)){Vs();return}if(W&&W!=="none"){const ce=o==null?void 0:o.find(De=>De.id===W),Fe=(ce==null?void 0:ce.slug)||"";if(!ms(g,Fe))return;Ks(g,Fe)}else Hs()}},{pagesType:ht,partialsType:Ze}=f.useMemo(()=>{const T=ce=>I?ce.name.toLowerCase().includes(I.toLowerCase())||ce.key.toLowerCase().includes(I.toLowerCase()):!0;return{pagesType:s.filter(ce=>ce.hasSlug!==!1&&T(ce)),partialsType:s.filter(ce=>ce.hasSlug===!1&&T(ce))}},[s,I]);return Y!=null&&Y.hasSlug?t.jsxs("form",{onSubmit:Mt,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"}),k?t.jsxs(c.Popover,{open:$,onOpenChange:L,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:at("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(Y==null?void 0:Y.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:I,onChange:T=>M(T.target.value)})]})}),t.jsxs(Es,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),i?se?t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>_e(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(S.Check,{className:at("mr-2 h-4 w-4",p===T.key?"opacity-100":"opacity-0")})]},T.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:ht.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>_e(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(S.Check,{className:at("mr-2 h-4 w-4",p===T.key?"opacity-100":"opacity-0")})]},T.key))}):t.jsxs(t.Fragment,{children:[ht.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:ht.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>_e(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(S.Check,{className:at("mr-2 h-4 w-4",p===T.key?"opacity-100":"opacity-0")})]},T.key))}),Ze.length>0&&t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>_e(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(S.Check,{className:at("mr-2 h-4 w-4",p===T.key?"opacity-100":"opacity-0")})]},T.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!E,onChange:T=>_e(T.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!E?"cursor-not-allowed text-gray-500":""}`,children:i?se?t.jsx("optgroup",{label:"Partials",children:s.filter(T=>T.hasSlug===!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(T=>T.hasSlug!==!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(T=>T.hasSlug!==!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(T=>T.hasSlug===!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))})]})}),P&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>D(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]})]}),!i&&(Y==null?void 0:Y.hasSlug)&&ae.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(ll,{templates:ae,selectedTemplateId:le,onSelectTemplate:$s,isLoading:me})]}),t.jsx(rl,{pages:o,selectedParentId:W,onChange:zs,currentPage:e}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:je,onChange:T=>we(T.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(Y==null?void 0:Y.dynamicSegments)&&W&&W!=="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:oe,onChange:T=>qs(T.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),oe&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(al,{value:R,onChange:z,dynamicPattern:(Y==null?void 0:Y.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:U})})})]}),(!(Y!=null&&Y.dynamicSegments)||!oe)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(wn,{value:g,onChange:T=>{var ce;A(T),i&&T!==(((ce=e==null?void 0:e.slug)==null?void 0:ce.split("/").pop())||"")?J(!!(Ee||Le)):J(!1)},placeholder:W&&W!=="none"?"Enter page slug":p==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:W&&W!=="none"?(xs=o==null?void 0:o.find(T=>T.id===W))==null?void 0:xs.slug:void 0,onValidationChange:j}),m&&t.jsx("p",{className:"text-xs text-red-500",children:m}),F&&t.jsx("div",{className:"mt-4 rounded-md border border-amber-200 bg-amber-50 p-3",children:t.jsxs("div",{className:"flex items-start space-x-2",children:[t.jsx("div",{className:"flex-shrink-0",children:t.jsx("svg",{className:"h-5 w-5 text-amber-400",viewBox:"0 0 20 20",fill:"currentColor",children:t.jsx("path",{fillRule:"evenodd",d:"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})})}),t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"text-sm font-medium text-amber-800",children:"Slug Change Warning"}),t.jsx("div",{className:"mt-1 text-sm text-amber-700",children:t.jsx("p",{children:"The previous URL and any child pages will become inaccessible. You may want to set up a redirect to avoid broken links."})})]})]})})]}),t.jsx(c.Button,{disabled:xe||!y&&(!(Y!=null&&Y.dynamicSegments)||!oe)||oe&&!O,type:"submit",className:"w-full",children:i?xe?"Updating...":"Update page":xe?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Mt,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"}),k?t.jsxs(c.Popover,{open:$,onOpenChange:L,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:at("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(Y==null?void 0:Y.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:I,onChange:T=>M(T.target.value)})]})}),t.jsxs(Es,{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(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>{_e(T.key),L(!1)},className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(S.Check,{className:at("mr-2 h-4 w-4",p===T.key?"opacity-100":"opacity-0")})]},T.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!E,onChange:T=>_e(T.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!E?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(T=>T.hasSlug===!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))})}),P&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>D(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(fs=s.find(T=>T.key===p))==null?void 0:fs.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:je,onChange:T=>we(T.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:xe,type:"submit",className:"w-full",children:i?xe?"Updating...":"Update "+(Y==null?void 0:Y.name):xe?"Creating...":"Create "+(Y==null?void 0:Y.name)})]})}const _a=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=ke(),r=!!(e!=null&&e.id);return 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(dl,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function En({page:e,onClose:s}){const[,n]=Ie(),{mutate:a,isPending:r}=Ti(),{data:i}=ke(),{setSelectedLang:o,fallbackLang:l}=q.useLanguages(),[,u]=q.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")),o(l),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:x.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 hl=()=>{const e=ie(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const o={pageId:a,name:r};return i&&(o.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:o})},onSuccess:()=>{s.invalidateQueries({queryKey:[B.GET_WEBSITE_PAGES]}),Q.toast.success("Page duplicated successfully")},onError:a=>{Q.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Da=({page:e,onClose:s,closePanel:n=()=>{}})=>{const{mutate:a,isPending:r}=hl(),[i,o]=f.useState(null),[l,u]=f.useState(`${e.name} (Copy)`),h=Nn(),d=x.isEmpty(e.slug),[m,v]=f.useState(d?"":`${e.slug.split("/").pop()}-copy`),y=d?"":x.initial(e.slug.split("/")).join("/"),[j,p]=f.useState(!1),w=b=>{if(b.preventDefault(),!l.trim()){o("Name is required");return}if(!d&&!m.trim()){o("Slug is required");return}o(null),p(!0);const E={pageId:e.id,name:l};d||(E.slug=`${y}/${m}`),a(E,{onSuccess:P=>{p(!1),s(),h(P.id,n)},onError:P=>{p(!1),P.code==="SLUG_EXISTS"?o("A page with this slug already exists. Please choose a different slug."):P.code==="INVALID_SLUG"?o("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):P.code==="PERMISSION_DENIED"?o("You don't have permission to duplicate this page."):o(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:w,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:l,onChange:b=>u(b.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(wn,{value:m,onChange:b=>v(b),parentSlug:y,onValidationChange:b=>{o(b?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:!l.trim()||!d&&!m.trim()||r||j,children:r||j?"Duplicating...":"Duplicate"})]})]})]})})},ml=1*1024*1024,La=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),[o,l]=f.useState(""),[u,h]=f.useState(!1),d=f.useRef(null),m=ki(),{data:v}=ke(),y=v==null?void 0:v.find(P=>P.key===e.pageType),j=(y==null?void 0:y.name)||x.startCase(e.pageType),p=f.useCallback(P=>{var _;const D=(_=P.target.files)==null?void 0:_[0];if(D){if(D.size>ml){Q.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(D.size/1024).toFixed(2)}KB.`}),d.current&&(d.current.value="");return}try{h(!0);const C=new FileReader;C.onloadend=()=>{l(C.result),h(!1)},C.readAsDataURL(D)}catch(C){console.error("Error reading file:",C),h(!1),Q.toast.error("Failed to process image",{description:C instanceof Error?C.message:"Unknown error"})}}},[]),w=()=>{l(""),d.current&&(d.current.value="")},b=()=>{var P;(P=d.current)==null||P.click()},E=()=>{a(!0),m.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...o?{previewImage:o}:{}},{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:x.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:b,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"]})}),o&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:w,children:t.jsx(S.X,{className:"h-4 w-4"})})]}),o&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:o,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:P=>{P.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:E,children:"Mark as template"})]})]})})},Ba=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),r=Pi(),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:o=>{o.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},Rs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Ai(),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:[re.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?re.UPDATING:re.UNPUBLISH})]})]})})},Ma=({close:e})=>{const{languages:s,setSelectedLang:n}=q.useLanguages(),{data:a}=ke(),{data:r,isFetching:i}=Lt(),[o,l]=Ie(),{updateForSelectedPage:u,expandPagesOnSearch:h}=Os(null),d=Ye(),m=o.get("page"),[v,y]=f.useState(""),[j,p]=f.useState(null),[w,b]=f.useState(null),[E,P]=f.useState(null),[D,_]=f.useState(null),[C,K]=f.useState(""),[ee,V]=f.useState(null),[I,M]=f.useState(null),[$,L]=f.useState(d),[se,W]=f.useState(!1),[,he]=pe.useAtom(ds),je=se&&$!==d,{data:we,isFetching:oe}=Mi($),N=f.useCallback(O=>{var U;return(U=x.find(a,{key:O}))==null?void 0:U.hasSlug},[a]),g=f.useMemo(()=>r?je?x.filter(r,O=>!(we!=null&&we[O.id])):Wi(r,v,C,N):[],[r,N,v,C,we,je]);f.useEffect(()=>{n(d)},[d,n]),f.useEffect(()=>{if(!x.isEmpty(C))return;const O=sessionStorage.getItem("pageTypeFilter")||"all";!x.isEmpty(a)&&O&&(x.find(a,{key:O})?K(O):K("all"))},[a,C]),f.useEffect(()=>{if(m&&!i&&!x.find(r,{id:m})){const U=x.find(r,{slug:"/"});if(U){const F=new URLSearchParams({page:U.id});Ft(F,l)}else Ft(new URLSearchParams({}),l,!0)}},[r,m,i,l]),f.useEffect(()=>{m&&!i&&!x.isEmpty(g)&&u(g,m)},[m,i,g,u]),f.useEffect(()=>{!x.isEmpty(v)&&!x.isEmpty(g)&&h(g)},[v,g,h]);const{setSelectedLang:A}=q.useLanguages(),R=f.useCallback(O=>{const U=new URLSearchParams({page:O});$!==d?(U.set("lang",$),A($)):A(""),Ft(U,l),e()},[e,l,A,$,d]),z=(O,U)=>{var F;if(U)switch(O){case"add":b(U);break;case"select":R(U);break;case"edit":$!==d?he({edit:!0,id:U==null?void 0:U.id,primaryPage:U==null?void 0:U.primaryPage}):b(U);break;case"delete":p(U);break;case"unpublish":P(U);break;case"markAsTemplate":_(U);break;case"unmarkAsTemplate":M(U);break;case"duplicate":V(U);break;case"addLanguagePage":he({edit:!1,primaryPage:((F=U==null?void 0:U.page)==null?void 0:F.id)||"",preselectedLang:(U==null?void 0:U.language)||$});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(Zi,{pages:g,search:v,setSearch:y,languages:[d,...s],selectedLanguage:$,setSelectedLanguage:L,selectedPageType:C,setSelectedPageType:K,onAddPage:O=>z("add",O),showUntranslatedPages:je,setShowUntranslatedPages:W}),t.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-6 pt-2",children:i||oe?t.jsx("div",{className:"space-y-2",children:x.map([...Array(15).keys()],O=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},O))}):x.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(Ia,{tier:0,pages:g,pageTypes:a,currentPage:m||"",onClickAction:z,languagePages:we,selectedLanguage:$,showUntranslatedPages:je})})]}),w&&t.jsx(_a,{closePanel:e,editPage:R,addEditPage:w,setAddEditPage:b}),j&&t.jsx(En,{page:j,onClose:()=>p(null)}),E&&t.jsx(Rs,{page:E,onClose:()=>P(null)}),D&&t.jsx(La,{page:D,onClose:()=>_(null)}),I&&t.jsx(Ba,{page:I,onClose:()=>M(null)}),ee&&t.jsx(Da,{page:ee,onClose:()=>V(null),closePanel:e})]})},fl=()=>{const e=Ue("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:f.createElement(e,{})}):null},xl=()=>{const[e,s]=Ie(),n=e.get("page"),{data:a,isFetching:r}=Ae(),{data:i,isFetching:o}=Lt(),[l,u]=f.useState(!1),[h,d]=f.useState(!0),{savePage:m}=q.useSavePage(),v=!!n&&!x.isEmpty(a),y=f.useMemo(()=>!i||o?!1:i.some(b=>b.slug==="/"),[i,o]);f.useEffect(()=>{if(!n&&!o&&i&&y){const b=i.find(E=>E.slug==="/");if(b){const E=new URLSearchParams({page:b.id});Ft(E,s)}}!o&&i&&d(!1)},[n,o,i,y,s]);const j=!h&&!n&&!y,p=!h&&!r&&x.isEmpty(a)&&!y,w=l||j||p;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:w,onOpenChange:b=>!b&&v&&u(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`z-50 !min-w-[50vh] !max-w-[800px] border-border p-0 ${v?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:"mb-3 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:`${w?"h-[calc(100vh-80px)] overflow-y-auto":"h-[calc(100vh-70px)] overflow-y-auto"}`,children:t.jsx(Ma,{close:()=>u(!1)})})]})})]})},Cn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=q.useLanguages(),o=x.isEmpty(r)?n:r,[,l]=Ie(),{isLocked:u}=Je();f.useEffect(()=>{const w=new URLSearchParams(window.location.search),b=w.get("lang");b&&(a.includes(b)?i(b):(w.delete("lang"),l(w),i("")))},[a,l,i]);const[,h]=pe.useAtom(ds),{data:d}=Ae(),{data:m}=Ve(),{data:v}=Re(),y=f.useMemo(()=>{const w=x.compact(x.map(x.get(m,"languages"),b=>{const E=x.find(v,{lang:b});return{key:b,value:x.get(Ne,b,b),isLangPageAdded:!!E}})).filter(Boolean);return[{key:n,value:x.get(Ne,n),isLangPageAdded:!0},...w]},[n,v,m]),j=w=>{if(document.querySelector('[data-panel-id="seo"]')){const E=new CustomEvent("seo-language-switch-check",{detail:{fromLang:o,toLang:w,switchHandler:()=>p(w)}});window.dispatchEvent(E);return}p(w)},p=w=>{i(w);const b=new URLSearchParams(window.location.search);w===n?b.delete("lang"):b.set("lang",w),Ft(b,l)};return x.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"}),x.get(Ne,o,o),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"}),x.get(Ne,o,o),t.jsx(S.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[x.map(y.filter(w=>w.isLangPageAdded),w=>t.jsxs(c.DropdownMenuItem,{className:q.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",w.key===o&&"!bg-gray-200 text-gray-700"),onClick:()=>j(w.key),children:[t.jsx("div",{className:"text-slate-600",children:w.value}),w.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"]})]},w.value)),e&&!x.isEmpty(y.filter(w=>!w.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 gl(){const[e,s]=pe.useAtom(ds);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(fl,{}),t.jsx(xl,{}),e&&t.jsx(zi,{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 pl(e,s){const n=ie(),a=X();return G.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=l=>l==="draft"||l==="live"?l:"revision",i=l=>x.replace(l.uid,`${l.label}:`,"");return await a(n,{action:B.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 yl=({version:e})=>{const s=e==null?void 0:e.item,{data:n}=We(s==null?void 0:s.currentEditor),a=e.label==="live",r=e.label==="draft";return t.jsxs("span",{className:`flex items-center gap-x-2 rounded border bg-white px-2 text-xs shadow-lg ${a?"border-green-500/30":r?"border-amber-500/30":"border-purple-500/30"}`,children:[t.jsx("div",{className:"h-full items-center rounded px-1.5 py-0.5 font-medium capitalize"+(a?" bg-green-500 text-green-50":r?" bg-amber-500 text-amber-50":" bg-purple-500 text-purple-50"),children:e.label}),t.jsxs("div",{className:"py-1 text-xs font-light leading-none text-gray-800",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-light opacity-90",children:r?"Currently editing":"Published by"}),!r&&t.jsx("span",{className:"pl-1 font-medium",children:(n==null?void 0:n.name)||"Unknown"})]}),t.jsx("div",{className:"text-[10px] leading-tight",children:ut.formatDate(s.createdAt,"dd MMM yyyy, h:mm a")})]})]})},Gn=({version:e})=>t.jsx(yl,{version:e});function jl(e,s,n="data.json"){const a=JSON.stringify(e,null,2),r=JSON.stringify(s,null,2),i=a.split(`
3
+ `),o=r.split(`
4
+ `);let l=`--- a/${n}
5
+ `;l+=`+++ b/${n}
6
+ `;const u=[];let h=0,d=0;for(;h<i.length||d<o.length;){const y=i[h]||"",j=o[d]||"";if(y===j)u.push(` ${y}`),h++,d++;else{let p=-1,w=-1;for(let b=h+1;b<i.length;b++)if(o[d]===i[b]){p=b;break}for(let b=d+1;b<o.length;b++)if(i[h]===o[b]){w=b;break}if(p!==-1&&(w===-1||p-h<=w-d)){for(let b=h;b<p;b++)u.push(`-${i[b]}`);h=p}else if(w!==-1){for(let b=d;b<w;b++)u.push(`+${o[b]}`);d=w}else y&&u.push(`-${y}`),j&&u.push(`+${j}`),h++,d++}}const m=i.length,v=o.length;return l+=`@@ -1,${m} +1,${v} @@
7
+ `,l+=u.join(`
8
+ `)+`
9
+ `,l}function zt(e,s=!0,n=!1){if(x.isString(e)){const a=x.trim(e);if(x.startsWith(a,"{")||x.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 x.isArray(e)?x.map(e,a=>zt(a,s,n)):x.isPlainObject(e)?x.mapValues(e,a=>zt(a,s,n)):e}const vl=e=>{switch(e){case"blocks":return"Blocks";case"seo":return"SEO";case"tracking":return"Tracking";default:return e}},bl=(e,s)=>{if(!e||!s)return[{key:"blocks",label:"Blocks"}];const n=Object.keys(e),a=Object.keys(s);return n.filter(o=>a.includes(o)).map(o=>({key:o,label:vl(o)})).filter(o=>o.key.length>0)};function wl({open:e,compare:s,onOpenChange:n}){const a=s[0],r=s[1],[i,o]=f.useState(null),[l,u]=f.useState("split"),[h,d]=f.useState(!1),[m,v]=f.useState("blocks"),{data:y,isLoading:j}=pl(a,r),{leftData:p,rightData:w,options:b}=f.useMemo(()=>{var M,$;const C=(M=y==null?void 0:y.version1)==null?void 0:M[m],K=($=y==null?void 0:y.version2)==null?void 0:$[m],ee=zt(C),V=zt(K),I=bl(y==null?void 0:y.version1,y==null?void 0:y.version2);return{leftData:ee,rightData:V,options:I}},[y,m]),E=f.useMemo(()=>!p||!w?"":jl(p,w),[p,w]),P=f.useMemo(()=>{if(!E)return[];try{return Qs.parseDiff(E)}catch(C){return console.error("Failed to parse diff:",C),[]}},[E]),D=async(C,K)=>{try{await navigator.clipboard.writeText(JSON.stringify(C,null,2)),o(K),setTimeout(()=>o(null),2e3)}catch(ee){console.error("Failed to copy:",ee)}},_=C=>JSON.stringify(C,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","",b.map(C=>t.jsx("div",{className:`cursor-pointer rounded-full border px-2.5 py-1 text-xs leading-none ${m===C.key?"border-blue-500 bg-blue-500 text-white":"border-gray-600 text-gray-600 hover:bg-gray-200"}`,onClick:()=>v(C.key),children:C.label},C.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:l==="split",onCheckedChange:C=>u(C?"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:C=>d(C)}),t.jsx("label",{className:"text-sm",children:"Show Raw Data"})]})]})})]})}),j?t.jsx(va,{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(Gn,{version:a})}),t.jsx("div",{className:"flex w-1/2 items-center justify-center gap-2",children:t.jsx(Gn,{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:()=>D(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:_(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:()=>D(w,"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:_(w)})})]})]}):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((C,K)=>t.jsx("div",{className:"mb-4",children:t.jsx(Qs.Diff,{viewType:l,diffType:C.type,hunks:C.hunks,className:"rounded-lg text-xs",children:ee=>ee.map((V,I)=>t.jsx(Qs.Hunk,{hunk:V},I))})},K))})})]})})]})})}const Me=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=q.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n};function Sl(e){const s=ie(),n=X();return G.useQuery({queryKey:["revisions",e],queryFn:async()=>await n(s,{action:B.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Nl=()=>{const e=ie(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async a=>await s(e,{action:B.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},El=()=>{const e=ie(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:B.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},rt=({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 Cl({compare:e,setCompare:s,isComparisonEnabled:n}){const{data:a}=Ae(),{saveState:r}=q.useSavePage(),[i]=Ms();if(!a)return null;const o=!!e.find(h=>{var d;return(d=h==null?void 0:h.uid)==null?void 0:d.startsWith("draft:")}),l=e.length>=2&&!o,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(rt,{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:!x.isEmpty(i.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",ut.formatDistanceToNow(new Date(i.lastSaved),{addSuffix:!0})]})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:u?t.jsx(rt,{tag:"unsaved"}):null})]}),n&&t.jsx(Oa,{checked:o,disabled:l,onChange:()=>{s(o?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 Tl(){var L,se;const[e,s]=ve.useState([]),[n,a]=ve.useState(!1),[r,i]=ve.useState(null),[o,l]=ve.useState(!1),[u,h]=ve.useState(!1),{data:d}=Ae(),{data:m,isFetching:v,error:y,refetch:j}=Sl(d==null?void 0:d.id),{mutate:p,isPending:w}=Nl(),{mutate:b,isPending:E}=El(),P=G.useQueryClient(),D=xa(),_=q.useChaiFeatureFlag("enable-page-revisions-compare"),{selectedLang:C,fallbackLang:K}=q.useLanguages(),ee=C||K;f.useEffect(()=>s([]),[d==null?void 0:d.id]);const V=W=>{r&&b({revisionId:r.uid,discardCurrent:W},{onSuccess:()=>{l(!1),i(null),P.invalidateQueries({queryKey:[B.GET_DRAFT_PAGE]})}})},I=W=>{i(W),l(!0)},M=W=>{i(W),h(!0)},$=()=>{r&&p(r.uid,{onSuccess:()=>{h(!1),i(null)}})};return f.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 ",ut.format(new Date(d.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),v?t.jsx(Al,{}):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.jsx(kl,{lang:ee,compare:e,setCompare:s,pageId:d==null?void 0:d.id}),t.jsx(Cl,{compare:e,setCompare:s,isComparisonEnabled:_}),(L=m==null?void 0:m.filter(W=>W.uid==="current"))==null?void 0:L.map((W,he)=>t.jsx(Un,{lang:ee,pageId:d==null?void 0:d.id,revision:W,isLatest:!0,onRestore:()=>I(W),onDelete:()=>M(W),revisionNumber:he,compare:e,setCompare:s,pageLiveFullSlug:D,isComparisonEnabled:_},W.uid)),t.jsx(c.ScrollArea,{className:"min-h-0 flex-1",children:t.jsx("div",{className:"space-y-2",children:(se=m==null?void 0:m.filter(W=>W.uid!=="current"))==null?void 0:se.map((W,he)=>t.jsx(Un,{lang:ee,pageId:d==null?void 0:d.id,revision:W,isLatest:W.uid==="current",onRestore:()=>I(W),onDelete:()=>M(W),revisionNumber:he+1,compare:e,setCompare:s,pageLiveFullSlug:D,isComparisonEnabled:_},W.uid))})})]})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Il,{open:o,onOpenChange:l,revision:r,onRestore:V,isRestoring:E}),t.jsx(_l,{open:u,onOpenChange:h,revision:r,onDelete:$,isDeleting:w})]})}function Al(){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 Un({revision:e,isLatest:s,onRestore:n,onDelete:a,revisionNumber:r,compare:i,setCompare:o,pageId:l,pageLiveFullSlug:u,isComparisonEnabled:h,lang:d}){const{data:m}=We(e.currentEditor),v=(m==null?void 0:m.name)||"Unknown",y=!!i.find(p=>{var w;return s?(w=p==null?void 0:p.uid)==null?void 0:w.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(rt,{tag:s?"live":`#${r}`}),e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"text-xs font-bold",children:v}),!h&&s&&t.jsx(rt,{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(rt,{tag:"published"}):t.jsx(rt,{tag:"draft"})}),t.jsx("div",{className:"flex items-center text-[10px] text-muted-foreground",children:t.jsx("span",{className:"leading-tight",children:ut.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(Pl,{revision:e,onRestore:n,onDelete:a})})]}),h&&t.jsx(Oa,{checked:y,disabled:j,onChange:()=>{o(y?i.filter(p=>s?p.uid!==`live:${l}`:p.uid!==e.uid):[...i,{uid:s?`live:${l}`:e.uid,label:s?"live":`#${r}`,item:e}].sort((p,w)=>new Date(p.item.createdAt).getTime()-new Date(w.item.createdAt).getTime()))}})]})}function kl({compare:e,setCompare:s,pageId:n}){const[a,r]=f.useState(!1),[i,o]=e;if(e.length===0)return null;const l=({tab:u})=>t.jsxs("span",{className:"flex items-center justify-between rounded border border-blue-100 p-1 font-medium",children:[t.jsx(rt,{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(l,{tab:i}),t.jsx("span",{className:"font-medium leading-tight text-gray-600",children:"with"}),o?t.jsx(l,{tab:o}):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(wl,{open:a,onOpenChange:r,compare:e})]})}function Oa({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 Pl({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 Il({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=We((n==null?void 0:n.currentEditor)||""),o=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:l=>{r||s(l)},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"," ",ut.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",o]})]}),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 _l({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=We((n==null?void 0:n.currentEditor)||""),o=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:l=>{r||s(l)},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"," ",ut.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",o]})]}),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 Dl=()=>{const e=ie(),s=X();return G.useQuery({queryKey:[B.GET_CHANGES],queryFn:async()=>s(e,{action:B.GET_CHANGES})})},Ll=({page:e,selectedPages:s,handleCheckboxChange:n,getPageType:a,hasSlug:r,currentOwnerId:i})=>{const{data:o}=We(i),l=o==null?void 0:o.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 ${l?"opacity-50":""}`,children:[l?t.jsx(S.Lock,{className:"h-4 w-4 fill-red-200 text-red-500"}):t.jsx("input",{checked:x.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(ot,{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(ot,{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:x.first(e.changes)||""}),t.jsx(t.Fragment,{children:l&&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:l})," is editing this page"]})})]},e==null?void 0:e.id)};function Bl({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n]=pa(),[a,r]=f.useState([]),i=Ye(),[o,l]=f.useState(i),{data:u,isFetching:h}=Dl(),{data:d}=ke(),m=f.useCallback(I=>{var M;return(M=x.find(d,{key:I}))==null?void 0:M.hasSlug},[d]),v=f.useMemo(()=>x.filter(d,I=>!m(I.key)).map(I=>I.key),[m,d]),j=x.uniq(x.map(u,"lang")).filter(Boolean),p=f.useMemo(()=>x.filter(u,I=>I.pageType==="theme"?!1:o===i?I.lang===o||I.lang==="":I.lang===o),[u,o,i]),w=f.useMemo(()=>x.filter(p,I=>!v.includes(I.pageType)),[p,v]),b=f.useMemo(()=>x.filter(p,I=>v.includes(I.pageType)),[p,v]),{mutate:E,isPending:P}=vn();f.useEffect(()=>{const I=x.map(x.filter(p,{online:!0}),"id");r(I)},[p]),f.useEffect(()=>{const I=Object.keys(n);r(M=>x.filter(M,$=>!x.includes(I,$)))},[n]);const D=a.length===(p==null?void 0:p.length),_=I=>{r(M=>x.includes(M,I)?x.filter(M,$=>$!==I):x.concat(M,I))},C=()=>{r(D?[]:x.map(p,"id"))},K=()=>{E({ids:x.uniq(a)},{onSuccess:()=>{s(),Ut("CENTER_CENTER"),l(i)}})},ee=I=>{if(I==="theme")return"Theme";const M=x.find(d,{key:I});return M?M==null?void 0:M.name:I},V=f.useMemo(()=>{const I=[{label:"Updated",top:"pt-2"},...x.orderBy(x.filter(w,{online:!0}),"pageType"),...x.orderBy(x.filter(b,{online:!0}),"pageType")].filter($=>$.pageType!=="theme"),M=[{label:"Offline",top:"pt-6"},...x.orderBy(x.filter(w,{online:!1}),"pageType"),...x.orderBy(x.filter(b,{online:!1}),"pageType")];return[...I,...M]},[w,b]);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(ka,{languages:[i,...j],selectedLanguage:o,setSelectedLanguage:l})}),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:D,onClick:I=>{I.stopPropagation(),C()},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:x.map(V,I=>I.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:`relative px-6 py-2 text-xs font-medium text-gray-800 ${I.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:I.label})})]})},"separator"):t.jsx(Ll,{page:I,selectedPages:a,handleCheckboxChange:_,getPageType:ee,hasSlug:m,currentOwnerId:n[(I==null?void 0:I.primaryPage)||(I==null?void 0:I.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||x.isEmpty(a),onClick:K,children:P?"Publishing...":"Publish Selected"})]})]})})}const Ml=({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 o=()=>{s()},l=()=>{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:o,disabled:a,children:"Cancel"}),t.jsx(c.Button,{onClick:l,disabled:a,children:a?"Publishing...":"Continue Anyway"})]})]})})},Ol=()=>{const e=X(),s=ie();return G.useQuery({queryKey:[B.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:B.GET_WEBSITE_DATA,data:{draft:!0}})})};function Rl({onClose:e}){const{data:s,isFetching:n}=Ol(),{mutateAsync:a,isPending:r}=Jr(),i=Ue("settingComponent",null),o=x.debounce(async l=>(await a({data:l}),!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:f.createElement(i,{data:s||{},onSave:r?()=>{}:o,cancel:r?()=>{}:e})})]})}):null}const Gl=()=>{const{selectedLang:e,fallbackLang:s}=q.useLanguages(),n=Ue("getPreviewUrl",async m=>m),[a,r]=f.useState(""),{data:i}=Ae(),{data:o}=Re(),{data:l}=ke(),u=f.useMemo(()=>{var m;return(m=o==null?void 0:o.find(v=>(v==null?void 0:v.lang)===e))==null?void 0:m.slug},[e,o]),h=f.useCallback(m=>{var v;return(v=x.find(l,{key:m}))==null?void 0:v.hasSlug},[l]),d=e===s?"":e;return f.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"})," ",re.PREVIEW]})})})},Ul=()=>{const[e,s]=q.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(ot,{content:re.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"})]})},Fl=()=>{const[e,s]=f.useState(!1),{isLocked:n}=Je(),{savePageAsync:a,saveState:r}=q.useSavePage();f.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=f.useCallback(async()=>{e||(s(!0),await a(),s(!1))},[a,e]),{buttonIcon:o,buttonClass:l,tooltipContent:u}=f.useMemo(()=>{switch(r){case"UNSAVED":return{tooltipContent:re.SAVEDRAFT,buttonIcon:t.jsx(S.Save,{className:"h-4 w-4"}),buttonClass:"gap-x-1"};case"SAVING":return{tooltipContent:re.SAVING,buttonIcon:t.jsx(S.Loader,{className:"h-4 w-4 animate-spin text-sky-700"}),buttonClass:"gap-x-1"};case"SAVED":return{tooltipContent:re.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:l,children:[o," ",u]})},ql=()=>{const{selectedLang:e}=q.useLanguages(),{data:s}=Qe(),{data:n}=Re(),[a,r]=f.useState(!1),[i,o]=f.useState(!1),[l,u]=f.useState(null),{savePageAsync:h}=q.useSavePage(),[d,m]=f.useState(!1),{data:v}=Ae(),{mutate:y,isPending:j}=vn(),{needTranslations:p}=q.useSavePage(),w=p(),{buttonText:b,buttonClassName:E,isPublished:P}=f.useMemo(()=>{const V=v&&(v==null?void 0:v.online);return{buttonClassName:V?"hover:bg-green-600 bg-green-500":"",isPublished:V,buttonText:V?re.PUBLISHED:re.PUBLISH}},[v]),D=async()=>{if(w){m(!0);return}_()},_=()=>{const V=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];y({ids:x.compact(V)},{onSuccess:()=>Ut("TOP_RIGHT")})},C=()=>{m(!1),_()},K=async()=>{m(!1),await h()},ee=f.useMemo(()=>x.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:D,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 ${E}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!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:b}),e?`(${x.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 ${E}`,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:ee},{onSuccess:()=>Ut("TOP_RIGHT")}),children:[re.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:()=>Ut("TOP_RIGHT")}),children:[re.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[re.OPEN," publish menu"]}),P&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[re.UNPUBLISH," page ",e?`(${x.upperCase(e)})`:""]})]})]})]}),t.jsx(Bl,{showModal:a,onClose:()=>r(!1)}),l&&t.jsx(Rs,{page:l,onClose:()=>u(null)}),t.jsx(Ml,{isOpen:d,onClose:K,onContinue:C,isPending:j})]})},zl=()=>{const e=Ue("settingComponent",null),[s,n]=f.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(ot,{content:re.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(Rl,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function $l(){const{isLocked:e}=Je(),[s]=Ie(),n=s.get("lang"),a=ha(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Tl,{}),t.jsx(Me,{permission:be.EDIT_THEME,children:t.jsx(Ul,{})}),t.jsx(Me,{permission:be.EDIT_SETTINGS,children:t.jsx(zl,{})}),t.jsx(Gl,{}),t.jsx(Me,{permission:be.SAVE_PAGE,children:t.jsx(Fl,{})}),t.jsx(Me,{permission:be.PUBLISH_PAGE,children:t.jsx(ql,{})})]})}const Vl=({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()}),Kl=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:o}=q.useLanguages(),l=(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?x.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(Vl,{isDefaultLang:l,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:l?o!==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))]})]})},Hl=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:o,onChangeLanguage:l}=fa(),u=f.useRef(void 0);return f.useEffect(()=>{u.current!==a&&e&&(l(),u.current=a)},[a,s]),t.jsx("div",{className:"relative",children:t.jsx(Kl,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:o,dynamicPages:n})})},Ql=()=>{const[e,s]=f.useState(null),[n,a]=f.useState(null),[r,i]=f.useState(null),[o,l]=f.useState(null),[u,h]=f.useState(null),[d,m]=f.useState(null),[v,y]=f.useState(!1),{data:j,isFetching:p}=Qe(),{selectedLang:w,fallbackLang:b}=q.useLanguages(),{data:E}=Re(),P=E==null?void 0:E.find(V=>V.lang===w),{isLocked:D}=Je(),_=!(j!=null&&j.slug),[,C]=pe.useAtom(ds),{savePage:K}=q.useSavePage();if(!j)return null;const ee=V=>{w.length>0&&w!==b?C({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:()=>{K(),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.jsx(S.Globe,{className:"mr-1 h-4 w-4"}):t.jsx(S.File,{className:"mr-1 h-4 w-4"}),x.get(P||j,"name")??""]})}),D?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(Pa,{page:j,setDuplicatePage:V=>h(V),setAddEditPage:V=>ee(V),setUnpublishPage:V=>a(V),setDeletePage:V=>s(V),setMarkAsTemplate:V=>i(V),setUnmarkAsTemplate:V=>l(V),isLanguagePage:w.length>0&&w!==b,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(_a,{closePanel:()=>m(null),editPage:()=>{},addEditPage:d,setAddEditPage:m}),e&&t.jsx(En,{page:e,onClose:()=>s(null)}),n&&t.jsx(Rs,{page:n,onClose:()=>a(null)}),r&&t.jsx(La,{page:r,onClose:()=>i(null)}),o&&t.jsx(Ba,{page:o,onClose:()=>l(null)}),u&&t.jsx(Da,{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(Ma,{close:()=>y(!1)})})]})})]})},Wl=({hasDynamicPage:e})=>t.jsx(us,{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"})]})}),Jl=()=>{const{data:e}=Qe(),s=gn(),{data:n,isFetching:a}=Ae(),r=x.get(n,"dynamic",!1),i=q.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:o,allLangPages:l}=fa(),u=l.length>0,h=e==null?void 0:e.slug,d=!h,m=xa(),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:q.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(Ql,{})}),t.jsxs("div",{className:q.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(Cn,{}),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:[!o&&t.jsx(Wl,{hasDynamicPage:u}),t.jsx(Hl,{})]})]})},Yl=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(gl,{}),t.jsx(Jl,{}),t.jsx($l,{})]}),Xl=()=>{const e=ie(),{aiContext:s}=xn(),n=X();return f.useCallback(async(a,r,i,o)=>n(e,{action:B.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:o}}),[e,s,n])},Zl=(e,s)=>s.map(n=>{if(x.has(e,n._type)){const a=ra.getDefaultBlockProps(n._type);return{...a,...x.pick(n,[...x.keys(a),"_type","_id","_name","_parent","_bindings"]),...x.pickBy(n,(r,i)=>x.endsWith(i,"_attrs")),...n}}return n}),eo=e=>{const s=ra.useRegisteredChaiBlocks();return f.useMemo(()=>{if(!e||x.isEmpty(e))return{blocks:[]};const n=x.filter(e,a=>!x.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Zl(s,n)}},[e,s])},Fn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=x.get(a,"html",""),i=x.get(a,"blocks",[]);return x.isArray(i)?i:q.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),[]}}},to=()=>{const e=ie(),s=X();return G.useQuery({queryKey:["uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{q.registerChaiLibrary(r.id,{name:r.isSiteLibrary?r.name+" (Current Site) ":r.name,description:r.description,getBlocksList:i=>Fn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>Fn.getUILibraryBlock(i,s,e)})}),a}})},Ra=()=>{const e=Bs(),s=X(),{user:n}=Ge(),a=n==null?void 0:n.id;return G.useQuery({queryKey:["permissions",a],queryFn:()=>s(e,{action:B.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},so=()=>{const e=ie(),s=X(),{setCurrentEditor:n}=Je(),[,a]=Ms();return{onSave:async({page:i,blocks:o,needTranslations:l})=>{try{const u=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:o,needTranslations:l}});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")}}}},no=()=>{const{data:e}=Lt(),s=ie(),n=X();return{getPartialBlocks:f.useCallback(async()=>{const a={};for(const r of e??[])x.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:x.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:f.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return x.filter(r.blocks,i=>x.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},qn=bs.z.object({email:bs.z.string().email({message:"Please enter a valid email address"}),password:bs.z.string().min(6,{message:"Password must be at least 6 characters"})}),ao=()=>{const{setUser:e,logout:s}=Ge(),n=Bs(),[a,r]=f.useState(""),[i,o]=f.useState(""),[l,u]=f.useState({}),[h,d]=f.useState(!1),[m,v]=f.useState(""),y=G.useMutation({mutationFn:async w=>{v("");const b=await fn(n,{action:"LOGIN",data:w});if(!b.ok){const P=await b.json();throw new Error(P.error||"Login failed")}const E=await b.json();if(x.has(E,"id")&&x.has(E,"email")&&x.has(E,"accessToken")&&x.has(E,"refreshToken"))e(E);else throw s(),new Error("Something went wrong. Please try again.");return E},onSuccess:()=>{u({}),v("")},onError:w=>{u({email:" ",password:" "}),v(w.message?"Invalid email or password":"Something went wrong")}}),j=async w=>{w.preventDefault(),u({});const b={email:a,password:i};try{const E=qn.parse(b);y.mutate(E)}catch(E){if(E instanceof bs.z.ZodError){const P=E.issues.reduce((D,_)=>{const C=_.path[0];return D[C]=_.message,D},{});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:w=>r(w.target.value),className:l.email?"border-destructive":""}),l.email&&t.jsx("p",{className:"text-sm text-destructive",children:l.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:w=>o(w.target.value),className:l.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"})})]}),l.password&&t.jsx("p",{className:"text-sm text-destructive",children:l.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 nn=ao;const ro=()=>f.useMemo(()=>nn,[nn]),io=e=>{nn=e},lo=()=>{const e=ro();return t.jsx(f.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},oo=({page:e,onClose:s})=>{const[n,a]=f.useState(e.slug||""),{mutate:r,isPending:i}=Ii(),{data:o}=ke(),l=x.find(o,{key:e==null?void 0:e.pageType}),u=d=>{if(d.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Ne).some(y=>n===`/${y}`||x.startsWith(n,`/${y}/`))){Q.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:[" ",(l==null?void 0:l.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;x.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||!x.startsWith(n,`/${h}`)||x.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},co=()=>{const[,e]=pe.useAtom(ds),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=q.useLanguages(),{data:r,isFetching:i}=Re(),{data:o}=Ae(),{data:l}=ke(),u=f.useMemo(()=>{const b=l==null?void 0:l.find(E=>E.key===(o==null?void 0:o.pageType));return o!=null&&o.dynamic?b==null?void 0:b.dynamicSlug:""},[l,o==null?void 0:o.pageType,o==null?void 0:o.dynamic]),[h,d]=f.useState(null),[m,v]=f.useState(null),[y,j]=f.useState(null),{data:p}=Ve(),w=x.filter(x.get(p,"languages")||["en"],b=>!x.find(r,{lang:b})&&b!==x.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"})]}):x.map(r,b=>{const E=b.lang,P=b.slug,D=!b.primaryPage,_=E===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 ${_?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(E),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 ${b.online?"bg-green-300":"bg-gray-300"}`}),x.get(Ne,D?n:E,E)]}),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:[" ",b.name," "]})]})]})]}),D?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:C=>C.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:C=>{C.stopPropagation(),e({edit:!0,id:b.id,primaryPage:b.primaryPage})},children:[t.jsx(S.PencilIcon,{className:"size-3"}),re.EDIT]})}),t.jsx(Me,{permissions:[be.UNPUBLISH_PAGE],children:(b==null?void 0:b.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:C=>{C.stopPropagation(),v(b)},children:[t.jsx(S.Power,{className:"size-3"}),re.UNPUBLISH]})}),t.jsx(Me,{permissions:[be.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:C=>{C.stopPropagation(),d(b)},children:[t.jsx(S.TrashIcon,{className:"size-3"}),re.DELETE]})})]})]})})})]},b.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:x.isEmpty(w),onClick:()=>{e({primaryPage:o==null?void 0:o.id,edit:!1})},children:re.ADD_NEW_LANGUAGE})})}),h&&t.jsx(En,{page:h,onClose:()=>d(null)}),m&&t.jsx(Rs,{page:m,onClose:()=>v(null)}),y&&t.jsx(oo,{page:y,onClose:()=>j(null)})]})},uo=({isActive:e,show:s})=>{const{data:n}=Ve();return!x.has(n,"languages")||!x.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"})})},Ga="lang",ho={id:Ga,label:"Languages",position:"top",panel:co,button:uo,view:"modal",width:400};function Ke({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=ve.useState(!1),[o,l]=ve.useState([]),[u,h]=ve.useState(e);ve.useEffect(()=>{r||l([]),h(e)},[e,r]);const d=j=>Array.isArray(j)?"array":typeof j=="object"&&j!==null?"object":"value",m=ve.useCallback(j=>{const p=w=>n==="value"?w==="value"||w==="object":n==="array"?w==="array":w===n;j.type==="object"?(l(w=>[...w,j.key]),h(j.value)):p(j.type)&&(s([...o,j.key].join(".")),i(!1))},[o,s,n]),v=ve.useCallback(()=>{if(o.length>0){const j=o.slice(0,-1);l(j),h(j.reduce((p,w)=>p[w],e))}},[o,e]),y=ve.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:[o.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([...o,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 mo=()=>{const{selectedLang:e}=q.useLanguages(),{data:s,isFetching:n}=Re();return{data:f.useMemo(()=>x.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},fo=()=>{var o;const s=(o=document.getElementById("canvas-iframe").contentDocument)==null?void 0:o.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(l=>l.remove()),a.querySelectorAll("*").forEach(l=>{Array.from(l.attributes).forEach(u=>l.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(l=>`<${l.tagName.toLowerCase()}>${l.innerHTML}</${l.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},mt=({keyword:e,onComplete:s,field:n})=>{const a=X(),r=ie(),{selectedLang:i,fallbackLang:o}=q.useLanguages(),l=q.useBuilderProp("aiContext",""),{mutate:u,isPending:h}=G.useMutation({mutationFn:async()=>{const d=fo();return await a(r,{action:B.GENERATE_SEO_FIELD,data:{pageContext:l,dynamic:!1,field:n,lang:i||o,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"})})},xo=({isOpen:e,onClose:s,onSave:n,onDiscard:a,isSaving:r=!1,fromLanguage:i,toLanguage:o})=>{const l=Ne[i]||i,u=Ne[o]||o;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 "',l,'" 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"})]})]})})},go=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),zn=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],o=r.index,l=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:l,position:o}),a=a.replace(i,l)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const o=i,l=o.message.match(/position (\d+)/),u=l?parseInt(l[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:o.message,line:h,column:d,position:u}}}},po=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const o=`"__placeholder_${i}__"`,l=new RegExp(go(o),"g");a=a.replace(l,r)}),a},yo=(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],o=x.get(s,i,null);n=n.replace(r[0],o)}return n},an=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:o="json-input",pageData:l={},handleFieldInsert:u})=>{const[h,d]=f.useState("edit"),[m,v]=f.useState(null),[y,j]=f.useState(""),p=f.useRef(null);f.useEffect(()=>{e.trim()===""&&s("{}")},[e,s]);const w=D=>{if(a)return;const _=D.target.value;s(_)},b=D=>{if(D.key==="Tab"){D.preventDefault();const _=D.currentTarget,C=_.selectionStart,K=_.selectionEnd;if(C!==K){const V=e.substring(C,K).split(`
11
+ `);if(D.shiftKey){const M=V.map(L=>L.startsWith(" ")?L.substring(2):L).join(`
12
+ `),$=e.substring(0,C)+M+e.substring(K);s($),setTimeout(()=>{_.selectionStart=C,_.selectionEnd=C+M.length},0)}else{const M=V.map(L=>` ${L}`).join(`
13
+ `),$=e.substring(0,C)+M+e.substring(K);s($),setTimeout(()=>{_.selectionStart=C,_.selectionEnd=C+M.length},0)}}else{const ee=e.substring(0,C)+" "+e.substring(K);s(ee),setTimeout(()=>{_.selectionStart=_.selectionEnd=C+2},0)}}};f.useEffect(()=>{const D=zn(e);if(D.isValid)if(v(null),D.parsed){const _=yo(D.parsed,l);j(_)}else j("");else v(D.error),j("")},[e,l]);const E=()=>{const D=zn(e);if(D.isValid&&D.parsed){const _=po(D.parsed,D.placeholders);s(_)}},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(Ke,{dataType:"value",data:l??{},onSelect:D=>u&&u(D,o)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:E,disabled:!e.trim()||n||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:p,id:o,name:o,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:w,onKeyDown:b,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."})]})]})})},$n=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},jo=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),o=r.substring(a),l=`{{${s}}}`,u=i+""+l+o,h=n+0+l.length;return{value:u,newCursorPos:h}},Ua=()=>{const{t:e}=q.useTranslation(),[,s]=q.useSidebarActivePanel(),{data:n}=Ae(),{data:a}=yn(),{data:r,isFetching:i}=mo(),o=r==null?void 0:r.seo,l=f.useRef(null),u=n==null?void 0:n.id,h=n==null?void 0:n.pageType,d=wa(h),{selectedLang:m,fallbackLang:v}=q.useLanguages(),y=m||v,[j,p]=f.useState(!1),[w,b]=f.useState(!1),[E,P]=f.useState(!1),[D,_]=f.useState(null),[C,K]=f.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",metaOther:"{}",...o}),ee=f.useRef({}),{mutate:V,isPending:I}=jn(),M=I||j||w,{hasPermission:$}=q.usePermissions(),L=$(be.EDIT_SEO);f.useEffect(()=>{if(!i&&o&&u){const g={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",metaOther:"",...o};K(g),ee.current[y]=g}},[i,o,y,u]),f.useEffect(()=>{const g=A=>{const{fromLang:R,toLang:z,switchHandler:O}=A.detail,U=ee.current[y];(U?!x.isEqual(U,C):!1)?(_({fromLang:R,toLang:z,switchHandler:O}),P(!0)):O()};return window.addEventListener("seo-language-switch-check",g),()=>{window.removeEventListener("seo-language-switch-check",g)}},[u,C,y]);const se=async()=>{if(!(!d||!y))try{p(!0);const g=qt(d,y),A={...C,keyword:x.get(g,"seo.keyword",""),title:x.get(g,"seo.title",""),description:x.get(g,"seo.description",""),cononicalUrl:x.get(g,"seo.canonicalUrl",""),noIndex:x.get(g,"seo.noIndex",!1),noFollow:x.get(g,"seo.noFollow",!1),ogTitle:x.get(g,"seo.ogTitle",""),ogDescription:x.get(g,"seo.ogDescription","")};K(A),Q.toast.success(e("SEO fields reset to defaults"))}catch(g){Q.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",g)}finally{p(!1)}},W=async()=>{if(!(!d||!y))try{b(!0);const g=qt(d,y),A={...C,jsonLD:x.get(g,"seo.jsonLD","")};K(A),Q.toast.success(e("JSON-LD reset to default"))}catch(g){Q.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",g)}finally{b(!1)}},he=async()=>{if(!(!d||!y))try{p(!0);const g=qt(d,y),A={...C,ogTitle:x.get(g,"seo.ogTitle",""),ogDescription:x.get(g,"seo.ogDescription",""),ogImage:x.get(g,"seo.ogImage",""),ogImageId:x.get(g,"seo.ogImageId",""),metaOther:x.get(g,"seo.metaOther","{}")};K(A),Q.toast.success(e("Meta Tag fields reset to defaults"))}catch(g){Q.toast.error(e("Failed to reset Meta Tag fields")),console.error("Reset Meta Tag error:",g)}finally{p(!1)}},je=async()=>{V({id:r==null?void 0:r.id,seo:C,primaryPage:u},{onSuccess:()=>{console.log("SEO & JSON-LD updated successfully",C),ee.current[y]=C,Q.toast.success("SEO & JSON-LD updated successfully")}})},we=(g,A)=>{const R=document.getElementById(A);if(R){const{value:z,newCursorPos:O}=jo(R,g);l.current={id:A,position:O},R.tagName.toLowerCase()==="input"?(R.value=z,K(J=>({...J,[R.name]:z})),R.focus(),R.setSelectionRange(O,O),[0,10,50,100,200].forEach(J=>{setTimeout(()=>{const le=document.getElementById(A);le&&(le.focus(),le.setSelectionRange(O,O))},J)})):(K(F=>({...F,[R.name]:z})),requestAnimationFrame(()=>{const F=document.getElementById(A);F&&(F.focus(),F.setSelectionRange(O,O),setTimeout(()=>{const J=document.getElementById(A);J&&(J.focus(),J.setSelectionRange(O,O))},50))}))}},oe=g=>{const A={...C,[g.target.name]:g.target.name==="noIndex"||g.target.name==="noFollow"?g.target.checked:g.target.value};K(A)},N=g=>A=>{x.isEmpty(A.fieldValue)||oe({target:{name:g,value:typeof A.fieldValue=="string"?A.fieldValue.replace(/^"(.*)"$/,"$1"):A.fieldValue}}),A.error&&Q.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:A.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!L&&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(Cn,{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:[L&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:se,disabled:M||!L||!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")}),L&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:g=>we(g,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:C.keyword,onChange:oe,disabled:M||!L,placeholder:e("Enter keyword"),readOnly:!L})]}),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(mt,{keyword:C.keyword,onComplete:N("title"),field:"title"}),L&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:g=>we(g,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:C.title,onChange:oe,disabled:M||!L,placeholder:e("Enter SEO title"),readOnly:!L})]}),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(mt,{keyword:C.keyword,onComplete:N("description"),field:"description"}),L&&t.jsx(Ke,{data:a??{},onSelect:g=>we(g,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:C.description,onChange:oe,disabled:M||!L,placeholder:e("Enter SEO description"),readOnly:!L})]}),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")}),L&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:g=>we(g,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:C.canonicalUrl,onChange:oe,disabled:M||!L,placeholder:e("Enter Canonical URL"),readOnly:!L})]}),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:C.noIndex,onChange:oe,disabled:M||!L,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:C.noFollow,onChange:oe,disabled:M||!L,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:[L&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:he,disabled:M||!L||!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(mt,{keyword:C.keyword,onComplete:N("ogTitle"),field:"ogTitle"}),L&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:g=>we(g,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:C.ogTitle,onChange:oe,disabled:M||!L,placeholder:e("Enter OG title"),readOnly:!L})]}),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(mt,{keyword:C.keyword,onComplete:N("ogDescription"),field:"ogDescription"}),L&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:g=>we(g,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:C.ogDescription,onChange:oe,disabled:M||!L,placeholder:e("Enter OG description"),readOnly:!L})]}),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")}),L&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:g=>{K({...C,ogImage:`{{${g}}}`,ogImageId:""})}})]}),t.jsx(Ls,{assetId:C.ogImageId,assetUrl:C.ogImage,onChange:g=>{K({...C,ogImage:g.url,ogImageId:g.id})},disabled:M||!L,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(mt,{keyword:C.keyword,onComplete:N("metaOther"),field:"metaOther"})})]}),t.jsx(an,{id:"metaOther",value:C.metaOther,onChange:g=>{oe({target:{name:"metaOther",value:g}})},placeholder:e("Enter Meta Tags JSON"),disabled:M||!L,readOnly:!L,pageData:a||{},rows:8,handleFieldInsert:we})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[L&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:W,disabled:M||!L||!d,children:e(w?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(mt,{keyword:C.keyword,onComplete:N("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(an,{id:"jsonLD",value:C.jsonLD,onChange:g=>{oe({target:{name:"jsonLD",value:g}})},placeholder:e("Enter JSON-LD"),disabled:M||!L,readOnly:!L,pageData:a||{},rows:12,handleFieldInsert:we})]})]})})]})})]}),L&&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:[$n(C.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:je,disabled:!$n(C==null?void 0:C.jsonLD)||(ee.current[y]?x.isEqual(ee.current[y],C):!1)||M||!L,children:e(I?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(xo,{isOpen:E,onClose:()=>{P(!1),_(null)},onSave:async()=>{D&&(await je(),D.switchHandler(),P(!1),_(null))},onDiscard:()=>{if(D){const g=ee.current[y];g&&K(g),D.switchHandler(),P(!1),_(null)}},isSaving:I,fromLanguage:(D==null?void 0:D.fromLang)||y,toLanguage:(D==null?void 0:D.toLang)||""})]})};Ua.displayName="SeoPanel";const Fa="seo",vo=({isActive:e,show:s})=>{const{data:n}=Ae(),a=wa(n==null?void 0:n.pageType);return!x.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",strokeWidth:"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"})]})})},bo={id:Fa,label:"SEO",panel:Ua,button:vo,position:"top",width:600,view:"modal"},qa="user-info",wo=()=>{const{user:e,logout:s}=Ge(),n=Ue("onLogout",x.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(),x.isFunction(n)&&n()},children:"Logout"})]})]})]})]})]}):null},So={id:qa,label:"User Info",button:wo,position:"bottom"},No=()=>{q.registerChaiSidebarPanel(Fa,bo),q.registerChaiSidebarPanel(Ga,ho),q.registerChaiSidebarPanel(qa,So)};var ne={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Vn(this.context.count)},getNextContextId(){return Vn(this.context.count++)}};function Vn(e){const s=String(e),n=s.length-1;return ne.context.id+(n?String.fromCharCode(96+n):"")+s}function Ot(e){ne.context=e}var za=!1,Eo=(e,s)=>e===s,Cs=Symbol("solid-proxy"),$a=typeof Proxy=="function",Tn=Symbol("solid-track"),Ts={equals:Eo},Va=Za,Xe=1,As=2,Ka={owned:null,cleanups:null,context:null,owner:null},Js={},ue=null,Ys=null,Co=null,ge=null,Pe=null,He=null,Gs=0;function tt(e,s){const n=ge,a=ue,r=e.length===0,i=s===void 0?a:s,o=r?Ka:{owned:null,cleanups:null,context:i?i.context:null,owner:i},l=r?e:()=>e(()=>Te(()=>Kt(o)));ue=o,ge=null;try{return $e(l,!0)}finally{ge=n,ue=a}}function Se(e,s){s=s?Object.assign({},Ts,s):Ts;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Xa(n,r));return[Ya.bind(n),a]}function Ha(e,s,n){const a=Us(e,s,!0,Xe);Bt(a)}function st(e,s,n){const a=Us(e,s,!1,Xe);Bt(a)}function An(e,s,n){Va=Go;const a=Us(e,s,!1,Xe);(!n||!n.render)&&(a.user=!0),He?He.push(a):Bt(a)}function Ce(e,s,n){n=n?Object.assign({},Ts,n):Ts;const a=Us(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Bt(a),Ya.bind(a)}function To(e){return e&&typeof e=="object"&&"then"in e}function Ao(e,s,n){let a,r,i;a=!0,r=e,i={};let o=null,l=Js,u=null,h=!1,d="initialValue"in i,m=typeof a=="function"&&Ce(a);const v=new Set,[y,j]=(i.storage||Se)(i.initialValue),[p,w]=Se(void 0),[b,E]=Se(void 0,{equals:!1}),[P,D]=Se(d?"ready":"unresolved");ne.context&&(u=ne.getNextContextId(),i.ssrLoadFrom==="initial"?l=i.initialValue:ne.load&&ne.has(u)&&(l=ne.load(u)));function _(I,M,$,L){return o===I&&(o=null,L!==void 0&&(d=!0),(I===l||M===l)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(L,{value:M})),l=Js,C(M,$)),M}function C(I,M){$e(()=>{M===void 0&&j(()=>I),D(M!==void 0?"errored":d?"ready":"unresolved"),w(M);for(const $ of v.keys())$.decrement();v.clear()},!1)}function K(){const I=Mo,M=y(),$=p();if($!==void 0&&!o)throw $;return ge&&ge.user,M}function ee(I=!0){if(I!==!1&&h)return;h=!1;const M=m?m():a;if(M==null||M===!1){_(o,Te(y));return}let $;const L=l!==Js?l:Te(()=>{try{return r(M,{value:y(),refetching:I})}catch(se){$=se}});if($!==void 0){_(o,void 0,ws($),M);return}else if(!To(L))return _(o,L,void 0,M),L;return o=L,"v"in L?(L.s===1?_(o,L.v,void 0,M):_(o,void 0,ws(L.v),M),L):(h=!0,queueMicrotask(()=>h=!1),$e(()=>{D(d?"refreshing":"pending"),E()},!1),L.then(se=>_(L,se,void 0,M),se=>_(L,void 0,ws(se),M)))}Object.defineProperties(K,{state:{get:()=>P()},error:{get:()=>p()},loading:{get(){const I=P();return I==="pending"||I==="refreshing"}},latest:{get(){if(!d)return K();const I=p();if(I&&!o)throw I;return y()}}});let V=ue;return m?Ha(()=>(V=ue,ee(!1))):ee(!1),[K,{refetch:I=>Wa(V,()=>ee(I)),mutate:j}]}function ko(e){return $e(e,!1)}function Te(e){if(ge===null)return e();const s=ge;ge=null;try{return e()}finally{ge=s}}function Po(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return o=>{let l;if(a){l=Array(e.length);for(let h=0;h<e.length;h++)l[h]=e[h]()}else l=e();if(i)return i=!1,o;const u=Te(()=>s(l,r,o));return r=l,u}}function Qa(e){An(()=>Te(e))}function _t(e){return ue===null||(ue.cleanups===null?ue.cleanups=[e]:ue.cleanups.push(e)),e}function Kn(){return ue}function Wa(e,s){const n=ue,a=ge;ue=e,ge=null;try{return $e(s,!0)}catch(r){kn(r)}finally{ue=n,ge=a}}function Io(e){const s=ge,n=ue;return Promise.resolve().then(()=>{ge=s,ue=n;let a;return $e(e,!1),ge=ue=null,a?a.done:void 0})}var[_o,Wu]=Se(!1);function Do(){return[_o,Io]}function Lo(e,s){const n=Symbol("context");return{id:n,Provider:Uo(n),defaultValue:e}}function Bo(e){let s;return ue&&ue.context&&(s=ue.context[e.id])!==void 0?s:e.defaultValue}function Ja(e){const s=Ce(e),n=Ce(()=>rn(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Mo;function Ya(){if(this.sources&&this.state)if(this.state===Xe)Bt(this);else{const e=Pe;Pe=null,$e(()=>Ps(this),!1),Pe=e}if(ge){const e=this.observers?this.observers.length:0;ge.sources?(ge.sources.push(this),ge.sourceSlots.push(e)):(ge.sources=[this],ge.sourceSlots=[e]),this.observers?(this.observers.push(ge),this.observerSlots.push(ge.sources.length-1)):(this.observers=[ge],this.observerSlots=[ge.sources.length-1])}return this.value}function Xa(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&$e(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],o=Ys&&Ys.running;o&&Ys.disposed.has(i),(o?!i.tState:!i.state)&&(i.pure?Pe.push(i):He.push(i),i.observers&&er(i)),o||(i.state=Xe)}if(Pe.length>1e6)throw Pe=[],new Error},!1)),s}function Bt(e){if(!e.fn)return;Kt(e);const s=Gs;Oo(e,e.value,s)}function Oo(e,s,n){let a;const r=ue,i=ge;ge=ue=e;try{a=e.fn(s)}catch(o){return e.pure&&(e.state=Xe,e.owned&&e.owned.forEach(Kt),e.owned=null),e.updatedAt=n+1,kn(o)}finally{ge=i,ue=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Xa(e,a):e.value=a,e.updatedAt=n)}function Us(e,s,n,a=Xe,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:ue,context:ue?ue.context:null,pure:n};return ue===null||ue!==Ka&&(ue.owned?ue.owned.push(i):ue.owned=[i]),i}function ks(e){if(e.state===0)return;if(e.state===As)return Ps(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<Gs);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Xe)Bt(e);else if(e.state===As){const a=Pe;Pe=null,$e(()=>Ps(e,s[0]),!1),Pe=a}}function $e(e,s){if(Pe)return e();let n=!1;s||(Pe=[]),He?n=!0:He=[],Gs++;try{const a=e();return Ro(n),a}catch(a){n||(He=null),Pe=null,kn(a)}}function Ro(e){if(Pe&&(Za(Pe),Pe=null),e)return;const s=He;He=null,s.length&&$e(()=>Va(s),!1)}function Za(e){for(let s=0;s<e.length;s++)ks(e[s])}function Go(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:ks(a)}if(ne.context){if(ne.count){ne.effects||(ne.effects=[]),ne.effects.push(...e.slice(0,n));return}Ot()}for(ne.effects&&(ne.done||!ne.count)&&(e=[...ne.effects,...e],n+=ne.effects.length,delete ne.effects),s=0;s<n;s++)ks(e[s])}function Ps(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<Gs)&&ks(a):r===As&&Ps(a,s)}}}function er(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=As,n.pure?Pe.push(n):He.push(n),n.observers&&er(n))}}function Kt(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),o=n.observerSlots.pop();a<r.length&&(i.sourceSlots[o]=a,r[a]=i,n.observerSlots[a]=o)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Kt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Kt(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function ws(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function kn(e,s=ue){throw ws(e)}function rn(e){if(typeof e=="function"&&!e.length)return rn(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=rn(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Uo(e,s){return function(a){let r;return st(()=>r=Te(()=>(ue.context={...ue.context,[e]:a.value},Ja(()=>a.children))),void 0),r}}var ln=Symbol("fallback");function Is(e){for(let s=0;s<e.length;s++)e[s]()}function Fo(e,s,n={}){let a=[],r=[],i=[],o=0,l=s.length>1?[]:null;return _t(()=>Is(i)),()=>{let u=e()||[],h=u.length,d,m;return u[Tn],Te(()=>{let y,j,p,w,b,E,P,D,_;if(h===0)o!==0&&(Is(i),i=[],a=[],r=[],o=0,l&&(l=[])),n.fallback&&(a=[ln],r[0]=tt(C=>(i[0]=C,n.fallback())),o=1);else if(o===0){for(r=new Array(h),m=0;m<h;m++)a[m]=u[m],r[m]=tt(v);o=h}else{for(p=new Array(h),w=new Array(h),l&&(b=new Array(h)),E=0,P=Math.min(o,h);E<P&&a[E]===u[E];E++);for(P=o-1,D=h-1;P>=E&&D>=E&&a[P]===u[D];P--,D--)p[D]=r[P],w[D]=i[P],l&&(b[D]=l[P]);for(y=new Map,j=new Array(D+1),m=D;m>=E;m--)_=u[m],d=y.get(_),j[m]=d===void 0?-1:d,y.set(_,m);for(d=E;d<=P;d++)_=a[d],m=y.get(_),m!==void 0&&m!==-1?(p[m]=r[d],w[m]=i[d],l&&(b[m]=l[d]),m=j[m],y.set(_,m)):i[d]();for(m=E;m<h;m++)m in p?(r[m]=p[m],i[m]=w[m],l&&(l[m]=b[m],l[m](m))):r[m]=tt(v);r=r.slice(0,o=h),a=u.slice(0)}return r});function v(y){if(i[m]=y,l){const[j,p]=Se(m);return l[m]=p,s(u[m],j)}return s(u[m])}}}function qo(e,s,n={}){let a=[],r=[],i=[],o=[],l=0,u;return _t(()=>Is(i)),()=>{const h=e()||[],d=h.length;return h[Tn],Te(()=>{if(d===0)return l!==0&&(Is(i),i=[],a=[],r=[],l=0,o=[]),n.fallback&&(a=[ln],r[0]=tt(v=>(i[0]=v,n.fallback())),l=1),r;for(a[0]===ln&&(i[0](),i=[],a=[],r=[],l=0),u=0;u<d;u++)u<a.length&&a[u]!==h[u]?o[u](()=>h[u]):u>=a.length&&(r[u]=tt(m));for(;u<a.length;u++)i[u]();return l=o.length=i.length=d,a=h.slice(0),r=r.slice(0,l)});function m(v){i[u]=v;const[y,j]=Se(h[u]);return o[u]=j,s(y,u)}}}function Pn(e,s){return Te(()=>e(s||{}))}function ys(){return!0}var on={get(e,s,n){return s===Cs?n:e.get(s)},has(e,s){return s===Cs?!0:e.has(s)},set:ys,deleteProperty:ys,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:ys,deleteProperty:ys}},ownKeys(e){return e.keys()}};function Xs(e){return(e=typeof e=="function"?e():e)?e:{}}function zo(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function In(...e){let s=!1;for(let o=0;o<e.length;o++){const l=e[o];s=s||!!l&&Cs in l,e[o]=typeof l=="function"?(s=!0,Ce(l)):l}if($a&&s)return new Proxy({get(o){for(let l=e.length-1;l>=0;l--){const u=Xs(e[l])[o];if(u!==void 0)return u}},has(o){for(let l=e.length-1;l>=0;l--)if(o in Xs(e[l]))return!0;return!1},keys(){const o=[];for(let l=0;l<e.length;l++)o.push(...Object.keys(Xs(e[l])));return[...new Set(o)]}},on);const n={},a=Object.create(null);for(let o=e.length-1;o>=0;o--){const l=e[o];if(!l)continue;const u=Object.getOwnPropertyNames(l);for(let h=u.length-1;h>=0;h--){const d=u[h];if(d==="__proto__"||d==="constructor")continue;const m=Object.getOwnPropertyDescriptor(l,d);if(!a[d])a[d]=m.get?{enumerable:!0,configurable:!0,get:zo.bind(n[d]=[m.get.bind(l)])}:m.value!==void 0?m:void 0;else{const v=n[d];v&&(m.get?v.push(m.get.bind(l)):m.value!==void 0&&v.push(()=>m.value))}}}const r={},i=Object.keys(a);for(let o=i.length-1;o>=0;o--){const l=i[o],u=a[l];u&&u.get?Object.defineProperty(r,l,u):r[l]=u?u.value:void 0}return r}function tr(e,...s){if($a&&Cs in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(o=>new Proxy({get(l){return o.includes(l)?e[l]:void 0},has(l){return o.includes(l)&&l in e},keys(){return o.filter(l=>l in e)}},on));return i.push(new Proxy({get(o){return r.has(o)?void 0:e[o]},has(o){return r.has(o)?!1:o in e},keys(){return Object.keys(e).filter(o=>!r.has(o))}},on)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),o=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let l=!1,u=0;for(const h of s)h.includes(r)&&(l=!0,o?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;l||(o?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function sr(e){let s,n;const a=r=>{const i=ne.context;if(i){const[l,u]=Se();ne.count||(ne.count=0),ne.count++,(n||(n=e())).then(h=>{!ne.done&&Ot(i),ne.count--,u(()=>h.default),Ot()}),s=l}else if(!s){const[l]=Ao(()=>(n||(n=e())).then(u=>u.default));s=l}let o;return Ce(()=>(o=s())?Te(()=>{if(!i||ne.done)return o(r);const l=ne.context;Ot(i);const u=o(r);return Ot(l),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var $o=0;function Vo(){return ne.context?ne.getNextContextId():`cl-${$o++}`}var nr=e=>`Stale read from <${e}>.`;function Ko(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ce(Fo(()=>e.each,e.children,s||void 0))}function Ho(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ce(qo(()=>e.each,e.children,s||void 0))}function Qo(e){const s=e.keyed,n=Ce(()=>e.when,void 0,void 0),a=s?n:Ce(n,void 0,{equals:(r,i)=>!r==!i});return Ce(()=>{const r=a();if(r){const i=e.children;return typeof i=="function"&&i.length>0?Te(()=>i(s?r:()=>{if(!Te(a))throw nr("Show");return n()})):i}return e.fallback},void 0,void 0)}function Wo(e){const s=Ja(()=>e.children),n=Ce(()=>{const a=s(),r=Array.isArray(a)?a:[a];let i=()=>{};for(let o=0;o<r.length;o++){const l=o,u=r[o],h=i,d=Ce(()=>h()?void 0:u.when,void 0,void 0),m=u.keyed?d:Ce(d,void 0,{equals:(v,y)=>!v==!y});i=()=>h()||(m()?[l,d,u]:void 0)}return i});return Ce(()=>{const a=n()();if(!a)return e.fallback;const[r,i,o]=a,l=o.children;return typeof l=="function"&&l.length>0?Te(()=>l(o.keyed?i():()=>{var h;if(((h=Te(n)())==null?void 0:h[0])!==r)throw nr("Match");return i()})):l},void 0,void 0)}function Jo(e){return e}var Yo=["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"],Xo=new Set(["className","value","readOnly","noValidate","formNoValidate","isMap","noModule","playsInline",...Yo]),Zo=new Set(["innerHTML","textContent","innerText","children"]),ec=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),tc=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 sc(e,s){const n=tc[e];return typeof n=="object"?n[s]?n.$:void 0:n}var nc=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),ac=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"]),rc={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},ic=e=>Ce(()=>e());function lc(e,s,n){let a=n.length,r=s.length,i=a,o=0,l=0,u=s[r-1].nextSibling,h=null;for(;o<r||l<i;){if(s[o]===n[l]){o++,l++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===o){const d=i<a?l?n[l-1].nextSibling:n[i-l]:u;for(;l<i;)e.insertBefore(n[l++],d)}else if(i===l)for(;o<r;)(!h||!h.has(s[o]))&&s[o].remove(),o++;else if(s[o]===n[i-1]&&n[l]===s[r-1]){const d=s[--r].nextSibling;e.insertBefore(n[l++],s[o++].nextSibling),e.insertBefore(n[--i],d),s[r]=n[i]}else{if(!h){h=new Map;let m=l;for(;m<i;)h.set(n[m],m++)}const d=h.get(s[o]);if(d!=null)if(l<d&&d<i){let m=o,v=1,y;for(;++m<r&&m<i&&!((y=h.get(s[m]))==null||y!==d+v);)v++;if(v>d-l){const j=s[o];for(;l<d;)e.insertBefore(n[l++],j)}else e.replaceChild(n[l++],s[o++])}else o++;else s[o++].remove()}}}var $t="_$DX_DELEGATE";function ar(e,s,n,a={}){let r;return tt(i=>{r=i,s===document?e():Ds(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function oc(e,s,n,a){let r;const i=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},o=()=>(r||(r=i())).cloneNode(!0);return o.cloneNode=o,o}function rr(e,s=window.document){const n=s[$t]||(s[$t]=new Set);for(let a=0,r=e.length;a<r;a++){const i=e[a];n.has(i)||(n.add(i),s.addEventListener(i,ur))}}function cc(e=window.document){if(e[$t]){for(let s of e[$t].keys())e.removeEventListener(s,ur);delete e[$t]}}function _s(e,s,n){dt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function uc(e,s,n,a){dt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function dc(e,s,n){dt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function ir(e,s){dt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function lr(e,s,n,a){if(a)Array.isArray(n)?(e[`$$${s}`]=n[0],e[`$$${s}Data`]=n[1]):e[`$$${s}`]=n;else if(Array.isArray(n)){const r=n[0];e.addEventListener(s,n[0]=i=>r.call(e,n[1],i))}else e.addEventListener(s,n,typeof n!="function"&&n)}function hc(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,o;for(i=0,o=r.length;i<o;i++){const l=r[i];!l||l==="undefined"||s[l]||(Hn(e,l,!1),delete n[l])}for(i=0,o=a.length;i<o;i++){const l=a[i],u=!!s[l];!l||l==="undefined"||n[l]===u||!u||(Hn(e,l,!0),n[l]=u)}return n}function mc(e,s,n){if(!s)return n?_s(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function or(e,s={},n,a){const r={};return a||st(()=>r.children=Ht(e,s.children,r.children)),st(()=>typeof s.ref=="function"&&cr(s.ref,e)),st(()=>fc(e,s,n,!0,r,!0)),r}function cr(e,s,n){return Te(()=>e(s,n))}function Ds(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Ht(e,s,a,n);st(r=>Ht(e,s(),r,n),a)}function fc(e,s,n,a,r={},i=!1){s||(s={});for(const o in r)if(!(o in s)){if(o==="children")continue;r[o]=Qn(e,o,null,r[o],n,i,s)}for(const o in s){if(o==="children")continue;const l=s[o];r[o]=Qn(e,o,l,r[o],n,i,s)}}function xc(e){let s,n;return!dt()||!(s=ne.registry.get(n=pc()))?e():(ne.completed&&ne.completed.add(s),ne.registry.delete(n),s)}function dt(e){return!!ne.context&&!ne.done&&(!e||e.isConnected)}function gc(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Hn(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 Qn(e,s,n,a,r,i,o){let l,u,h,d,m;if(s==="style")return mc(e,n,a);if(s==="classList")return hc(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=nc.has(v);if(!y&&a){const j=Array.isArray(a)?a[0]:a;e.removeEventListener(v,j)}(y||n)&&(lr(e,v,n,y),y&&rr([v]))}else if(s.slice(0,5)==="attr:")_s(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")dc(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(h=Zo.has(s))||!r&&((d=sc(s,e.tagName))||(u=Xo.has(s)))||(l=e.nodeName.includes("-")||"is"in o)){if(m)s=s.slice(5),u=!0;else if(dt(e))return n;s==="class"||s==="className"?ir(e,n):l&&!u&&!h?e[gc(s)]=n:e[d||s]=n}else{const v=r&&s.indexOf(":")>-1&&rc[s.split(":")[0]];v?uc(e,v,s,n):_s(e,ec[s]||s,n)}return n}function ur(e){if(ne.registry&&ne.events&&ne.events.find(([u,h])=>h===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),o=()=>{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},l=()=>{for(;o()&&(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],!!o());h++){if(s._$host){s=s._$host,l();break}if(s.parentNode===r)break}}else l();i(a)}function Ht(e,s,n,a,r){const i=dt(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 o=typeof s,l=a!==void 0;if(e=l&&n[0]&&n[0].parentNode||e,o==="string"||o==="number"){if(i||o==="number"&&(s=s.toString(),s===n))return n;if(l){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=ft(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||o==="boolean"){if(i)return n;n=ft(e,n,a)}else{if(o==="function")return st(()=>{let u=s();for(;typeof u=="function";)u=u();n=Ht(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],h=n&&Array.isArray(n);if(cn(u,s,n,r))return st(()=>n=Ht(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let d=u[0];if(d.parentNode!==e)return n;const m=[d];for(;(d=d.nextSibling)!==a;)m.push(d);return n=m}if(u.length===0){if(n=ft(e,n,a),l)return n}else h?n.length===0?Wn(e,u,a):lc(e,n,u):(n&&ft(e),Wn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=l?[s]:s;if(Array.isArray(n)){if(l)return n=ft(e,n,a,s);ft(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function cn(e,s,n,a){let r=!1;for(let i=0,o=s.length;i<o;i++){let l=s[i],u=n&&n[e.length],h;if(!(l==null||l===!0||l===!1))if((h=typeof l)=="object"&&l.nodeType)e.push(l);else if(Array.isArray(l))r=cn(e,l,u)||r;else if(h==="function")if(a){for(;typeof l=="function";)l=l();r=cn(e,Array.isArray(l)?l:[l],Array.isArray(u)?u:[u])||r}else e.push(l),r=!0;else{const d=String(l);u&&u.nodeType===3&&u.data===d?e.push(u):e.push(document.createTextNode(d))}}return r}function Wn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function ft(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let o=s.length-1;o>=0;o--){const l=s[o];if(r!==l){const u=l.parentNode===e;!i&&!o?u?e.replaceChild(r,l):e.insertBefore(r,n):u&&l.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function pc(){return ne.getNextContextId()}var yc="http://www.w3.org/2000/svg";function dr(e,s=!1){return s?document.createElementNS(yc,e):document.createElement(e)}function jc(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Kn();let i,o=!!ne.context;return An(()=>{o&&(Kn().user=o=!1),i||(i=Wa(r,()=>Ce(()=>e.children)));const l=a();if(l instanceof HTMLHeadElement){const[u,h]=Se(!1),d=()=>h(!0);tt(m=>Ds(l,()=>u()?m():i(),null)),_t(d)}else{const u=dr(e.isSVG?"g":"div",e.isSVG),h=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),Ds(h,i),l.appendChild(u),e.ref&&e.ref(u),_t(()=>l.removeChild(u))}},void 0,{render:!o}),n}function vc(e,s){const n=Ce(e);return Ce(()=>{const a=n();switch(typeof a){case"function":return Te(()=>a(s));case"string":const r=ac.has(a),i=ne.context?xc():dr(a,r);return or(i,s,r),i}})}function bc(e){const[,s]=tr(e,["component"]);return vc(()=>e.component,s)}var wc=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,s){this.keyToValue.set(e,s),this.valueToKey.set(s,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},hr=class{constructor(e){this.generateIdentifier=e,this.kv=new wc}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)}},Sc=class extends hr{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,s){typeof s=="object"?(s.allowProps&&this.classToAllowedProps.set(e,s.allowProps),super.register(e,s.identifier)):super.register(e,s)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function Nc(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 Ec(e,s){const n=Nc(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 Dt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Ss(e,s){return e.indexOf(s)!==-1}function Jn(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Cc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Ec(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Tc=e=>Object.prototype.toString.call(e).slice(8,-1),mr=e=>typeof e>"u",Ac=e=>e===null,Qt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,un=e=>Qt(e)&&Object.keys(e).length===0,nt=e=>Array.isArray(e),kc=e=>typeof e=="string",Pc=e=>typeof e=="number"&&!isNaN(e),Ic=e=>typeof e=="boolean",_c=e=>e instanceof RegExp,Wt=e=>e instanceof Map,Jt=e=>e instanceof Set,fr=e=>Tc(e)==="Symbol",Dc=e=>e instanceof Date&&!isNaN(e.valueOf()),Lc=e=>e instanceof Error,Yn=e=>typeof e=="number"&&isNaN(e),Bc=e=>Ic(e)||Ac(e)||mr(e)||Pc(e)||kc(e)||fr(e),Mc=e=>typeof e=="bigint",Oc=e=>e===1/0||e===-1/0,Rc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Gc=e=>e instanceof URL,xr=e=>e.replace(/\./g,"\\."),Zs=e=>e.map(String).map(xr).join("."),Vt=e=>{const s=[];let n="";for(let r=0;r<e.length;r++){let i=e.charAt(r);if(i==="\\"&&e.charAt(r+1)==="."){n+=".",r++;continue}if(i==="."){s.push(n),n="";continue}n+=i}const a=n;return s.push(a),s};function ze(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var gr=[ze(mr,"undefined",()=>null,()=>{}),ze(Mc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),ze(Dc,"Date",e=>e.toISOString(),e=>new Date(e)),ze(Lc,"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}),ze(_c,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),ze(Jt,"set",e=>[...e.values()],e=>new Set(e)),ze(Wt,"map",e=>[...e.entries()],e=>new Map(e)),ze(e=>Yn(e)||Oc(e),"number",e=>Yn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),ze(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),ze(Gc,"URL",e=>e.toString(),e=>new URL(e))];function Fs(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var pr=Fs((e,s)=>fr(e)?!!s.symbolRegistry.getIdentifier(e):!1,(e,s)=>["symbol",s.symbolRegistry.getIdentifier(e)],e=>e.description,(e,s,n)=>{const a=n.symbolRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown symbol");return a}),Uc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),yr=Fs(Rc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Uc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function jr(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var vr=Fs(jr,(e,s)=>["class",s.classRegistry.getIdentifier(e.constructor)],(e,s)=>{const n=s.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};const a={};return n.forEach(r=>{a[r]=e[r]}),a},(e,s,n)=>{const a=n.classRegistry.getValue(s[1]);if(!a)throw new Error(`Trying to deserialize unknown class '${s[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(a.prototype),e)}),br=Fs((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)}),Fc=[vr,pr,br,yr],Xn=(e,s)=>{const n=Jn(Fc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=Jn(gr,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},wr={};gr.forEach(e=>{wr[e.annotation]=e});var qc=(e,s,n)=>{if(nt(s))switch(s[0]){case"symbol":return pr.untransform(e,s,n);case"class":return vr.untransform(e,s,n);case"custom":return br.untransform(e,s,n);case"typed-array":return yr.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=wr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},gt=(e,s)=>{if(s>e.size)throw new Error("index out of bounds");const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function Sr(e){if(Ss(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Ss(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Ss(e,"constructor"))throw new Error("constructor is not allowed as a property")}var zc=(e,s)=>{Sr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Jt(e))e=gt(e,+a);else if(Wt(e)){const r=+a,i=+s[++n]==0?"key":"value",o=gt(e,r);switch(i){case"key":e=o;break;case"value":e=e.get(o);break}}else e=e[a]}return e},dn=(e,s,n)=>{if(Sr(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const o=s[i];if(nt(a)){const l=+o;a=a[l]}else if(Qt(a))a=a[o];else if(Jt(a)){const l=+o;a=gt(a,l)}else if(Wt(a)){if(i===s.length-2)break;const u=+o,h=+s[++i]==0?"key":"value",d=gt(a,u);switch(h){case"key":a=d;break;case"value":a=a.get(d);break}}}const r=s[s.length-1];if(nt(a)?a[+r]=n(a[+r]):Qt(a)&&(a[r]=n(a[r])),Jt(a)){const i=gt(a,+r),o=n(i);i!==o&&(a.delete(i),a.add(o))}if(Wt(a)){const i=+s[s.length-2],o=gt(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(o);a.set(u,a.get(o)),u!==o&&a.delete(o);break}case"value":{a.set(o,n(a.get(o)));break}}}return e};function hn(e,s,n=[]){if(!e)return;if(!nt(e)){Dt(e,(i,o)=>hn(i,s,[...n,...Vt(o)]));return}const[a,r]=e;r&&Dt(r,(i,o)=>{hn(i,s,[...n,...Vt(o)])}),s(a,n)}function $c(e,s,n){return hn(s,(a,r)=>{e=dn(e,r,i=>qc(i,a,n))}),e}function Vc(e,s){function n(a,r){const i=zc(e,Vt(r));a.map(Vt).forEach(o=>{e=dn(e,o,()=>i)})}if(nt(s)){const[a,r]=s;a.forEach(i=>{e=dn(e,Vt(i),()=>e)}),r&&Dt(r,n)}else Dt(s,n);return e}var Kc=(e,s)=>Qt(e)||nt(e)||Wt(e)||Jt(e)||jr(e,s);function Hc(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function Qc(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(l=>l.map(String)).sort((l,u)=>l.length-u.length));const[i,...o]=r;i.length===0?a=o.map(Zs):n[Zs(i)]=o.map(Zs)}),a?un(n)?[a]:[a,n]:un(n)?void 0:n}var Nr=(e,s,n,a,r=[],i=[],o=new Map)=>{const l=Bc(e);if(!l){Hc(e,r,s);const y=o.get(e);if(y)return a?{transformedValue:null}:y}if(!Kc(e,n)){const y=Xn(e,n),j=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return l||o.set(e,j),j}if(Ss(i,e))return{transformedValue:null};const u=Xn(e,n),h=(u==null?void 0:u.value)??e,d=nt(h)?[]:{},m={};Dt(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=Nr(y,s,n,a,[...r,j],[...i,e],o);d[j]=p.transformedValue,nt(p.annotations)?m[j]=p.annotations:Qt(p.annotations)&&Dt(p.annotations,(w,b)=>{m[xr(j)+"."+b]=w})});const v=un(m)?{transformedValue:d,annotations:u?[u.type]:void 0}:{transformedValue:d,annotations:u?[u.type,m]:m};return l||o.set(e,v),v};function Er(e){return Object.prototype.toString.call(e).slice(8,-1)}function Zn(e){return Er(e)==="Array"}function Wc(e){if(Er(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Jc(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 mn(e,s={}){if(Zn(e))return e.map(r=>mn(r,s));if(!Wc(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(Zn(s.props)&&!s.props.includes(i))return r;const o=e[i],l=mn(o,s);return Jc(r,i,l,e,s.nonenumerable),r},{})}var ye=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Sc,this.symbolRegistry=new hr(s=>s.description??""),this.customTransformerRegistry=new Cc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Nr(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=Qc(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=mn(s);return n!=null&&n.values&&(a=$c(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Vc(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};ye.defaultInstance=new ye;ye.serialize=ye.defaultInstance.serialize.bind(ye.defaultInstance);ye.deserialize=ye.defaultInstance.deserialize.bind(ye.defaultInstance);ye.stringify=ye.defaultInstance.stringify.bind(ye.defaultInstance);ye.parse=ye.defaultInstance.parse.bind(ye.defaultInstance);ye.registerClass=ye.defaultInstance.registerClass.bind(ye.defaultInstance);ye.registerSymbol=ye.defaultInstance.registerSymbol.bind(ye.defaultInstance);ye.registerCustom=ye.defaultInstance.registerCustom.bind(ye.defaultInstance);ye.allowErrorProps=ye.defaultInstance.allowErrorProps.bind(ye.defaultInstance);var Cr=ye.serialize,Yc=ye.stringify;function Xc(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function Zc(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function eu({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function tu({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function su(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var nu=(e,s=!1)=>{const{json:n}=Cr(e);return JSON.stringify(n,null,s?2:void 0)},js=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,au=(e,s)=>e.queryHash.localeCompare(s.queryHash),Tr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,ru=(e,s)=>js(e)===js(s)?Tr(e,s):js(e)>js(s)?1:-1,iu={status:ru,"query hash":au,"last updated":Tr},vs=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Ar=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,lu=(e,s)=>vs(e)===vs(s)?Ar(e,s):vs(e)>vs(s)?1:-1,ou={status:lu,"last updated":Ar},cu=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),uu=()=>{const[e,s]=Se("dark");return Qa(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=r=>{s(r.matches?"dark":"light")};n.addEventListener("change",a),_t(()=>n.removeEventListener("change",a))}),e},Rt=(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,Rt(a.get(r),i,n)),a}if(e instanceof Set){const a=Rt(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]=Rt(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]=Rt(a[r],i,n),a}return e},Gt=(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,Gt(n.get(a),r)),n}if(e instanceof Set){const n=Gt(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,o)=>o.toString()!==s[0]);const[a,...r]=s;return n[a]=Gt(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]=Gt(n[a],r),n}return e},kr=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},pt,Yt,Xt,Zt,it,es,yt,jt,vt,bt,wt,ts,St,ss,na,du=(na=class{constructor(e){fe(this,pt);fe(this,Yt);fe(this,Xt);fe(this,Zt);fe(this,it,!1);fe(this,es);fe(this,yt);fe(this,jt);fe(this,vt);fe(this,bt);fe(this,wt);fe(this,ts);fe(this,St);fe(this,ss);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:h,shadowDOMTarget:d,hideDisabledQueries:m}=e;de(this,pt,Se(s)),de(this,Xt,n),de(this,Zt,a),de(this,Yt,r),de(this,es,h),de(this,yt,d),de(this,jt,Se(i)),de(this,vt,Se(o)),de(this,bt,Se(l)),de(this,wt,Se(u)),de(this,ts,Se(m))}setButtonPosition(e){Z(this,jt)[1](e)}setPosition(e){Z(this,vt)[1](e)}setInitialIsOpen(e){Z(this,bt)[1](e)}setErrorTypes(e){Z(this,wt)[1](e)}setClient(e){Z(this,pt)[1](e)}mount(e){if(Z(this,it))throw new Error("Devtools is already mounted");const s=ar(()=>{const n=this,[a]=Z(this,jt),[r]=Z(this,vt),[i]=Z(this,bt),[o]=Z(this,wt),[l]=Z(this,ts),[u]=Z(this,pt);let h;return Z(this,St)?h=Z(this,St):(h=sr(()=>Promise.resolve().then(()=>require("./LNWAZHJI-rq3TRPRK.cjs"))),de(this,St,h)),kr(Z(this,es),Z(this,yt)),Pn(h,In({get queryFlavor(){return Z(n,Xt)},get version(){return Z(n,Zt)},get onlineManager(){return Z(n,Yt)},get shadowDOMTarget(){return Z(n,yt)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return o()},get hideDisabledQueries(){return l()}}))},e);de(this,it,!0),de(this,ss,s)}unmount(){var e;if(!Z(this,it))throw new Error("Devtools is not mounted");(e=Z(this,ss))==null||e.call(this),de(this,it,!1)}},pt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,it=new WeakMap,es=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,ts=new WeakMap,St=new WeakMap,ss=new WeakMap,na),Nt,ns,as,rs,lt,is,Et,Ct,Tt,At,kt,ls,Pt,It,os,aa,hu=(aa=class{constructor(e){fe(this,Nt);fe(this,ns);fe(this,as);fe(this,rs);fe(this,lt,!1);fe(this,is);fe(this,Et);fe(this,Ct);fe(this,Tt);fe(this,At);fe(this,kt);fe(this,ls);fe(this,Pt);fe(this,It);fe(this,os);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:h,shadowDOMTarget:d,onClose:m,hideDisabledQueries:v}=e;de(this,Nt,Se(s)),de(this,as,n),de(this,rs,a),de(this,ns,r),de(this,is,h),de(this,Et,d),de(this,Ct,Se(i)),de(this,Tt,Se(o)),de(this,At,Se(l)),de(this,kt,Se(u)),de(this,ls,Se(v)),de(this,Pt,Se(m))}setButtonPosition(e){Z(this,Ct)[1](e)}setPosition(e){Z(this,Tt)[1](e)}setInitialIsOpen(e){Z(this,At)[1](e)}setErrorTypes(e){Z(this,kt)[1](e)}setClient(e){Z(this,Nt)[1](e)}setOnClose(e){Z(this,Pt)[1](()=>e)}mount(e){if(Z(this,lt))throw new Error("Devtools is already mounted");const s=ar(()=>{const n=this,[a]=Z(this,Ct),[r]=Z(this,Tt),[i]=Z(this,At),[o]=Z(this,kt),[l]=Z(this,ls),[u]=Z(this,Nt),[h]=Z(this,Pt);let d;return Z(this,It)?d=Z(this,It):(d=sr(()=>Promise.resolve().then(()=>require("./MWZ6AO7Z-B3njDJ82.cjs"))),de(this,It,d)),kr(Z(this,is),Z(this,Et)),Pn(d,In({get queryFlavor(){return Z(n,as)},get version(){return Z(n,rs)},get onlineManager(){return Z(n,ns)},get shadowDOMTarget(){return Z(n,Et)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return o()},get hideDisabledQueries(){return l()},get onClose(){return h()}}))},e);de(this,lt,!0),de(this,os,s)}unmount(){var e;if(!Z(this,lt))throw new Error("Devtools is not mounted");(e=Z(this,os))==null||e.call(this),de(this,lt,!1)}},Nt=new WeakMap,ns=new WeakMap,as=new WeakMap,rs=new WeakMap,lt=new WeakMap,is=new WeakMap,Et=new WeakMap,Ct=new WeakMap,Tt=new WeakMap,At=new WeakMap,kt=new WeakMap,ls=new WeakMap,Pt=new WeakMap,It=new WeakMap,os=new WeakMap,aa);function mu(e){const s=G.useQueryClient(e.client),n=ve.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u,hideDisabledQueries:h}=e,[d]=ve.useState(new du({client:s,queryFlavor:"React Query",version:"5",onlineManager:G.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u,hideDisabledQueries:h}));return ve.useEffect(()=>{d.setClient(s)},[s,d]),ve.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),ve.useEffect(()=>{r&&d.setPosition(r)},[r,d]),ve.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),ve.useEffect(()=>{d.setErrorTypes(o||[])},[o,d]),ve.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{dir:"ltr",className:"tsqd-parent-container",ref:n})}function fu(e){const s=G.useQueryClient(e.client),n=ve.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i,hideDisabledQueries:o}=e,[l]=ve.useState(new hu({client:s,queryFlavor:"React Query",version:"5",onlineManager:G.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose,hideDisabledQueries:o}));return ve.useEffect(()=>{l.setClient(s)},[s,l]),ve.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),ve.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),ve.useEffect(()=>(n.current&&l.mount(n.current),()=>{l.unmount()}),[l]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var xu=process.env.NODE_ENV!=="development"?function(){return null}:mu;process.env.NODE_ENV;const gu=()=>{q.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),q.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),q.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"})},pu=()=>{const e=ie(),s=X();return G.useQuery({queryKey:[B.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:B.GET_COLLECTIONS})})},yu=()=>{const{data:e}=Ae(),{data:s}=Qe(),{data:n}=Ve(),a=ie(),r=X(),i=f.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return G.useMutation({mutationFn:async({block:o})=>r(a,{action:B.GET_BLOCK_ASYNC_PROPS,data:{block:o,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},Pr=()=>{const e=Nn();return f.useCallback(({pageId:s})=>{e(s)},[e])},ea={},Ns=(e,s)=>{x.has(ea,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),x.set(ea,e,{id:e,...s})},ju=f.createContext(null),en={didCatch:!1,error:null};class vu extends f.Component{constructor(s){super(s),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=en}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),o=0;o<r;o++)i[o]=arguments[o];(n=(a=this.props).onReset)===null||n===void 0||n.call(a,{args:i,reason:"imperative-api"}),this.setState(en)}}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&&bu(s.resetKeys,r)){var i,o;(i=(o=this.props).onReset)===null||i===void 0||i.call(o,{next:r,prev:s.resetKeys,reason:"keys"}),this.setState(en)}}render(){const{children:s,fallbackRender:n,FallbackComponent:a,fallback:r}=this.props,{didCatch:i,error:o}=this.state;let l=s;if(i){const u={error:o,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")l=n(u);else if(a)l=f.createElement(a,u);else if(r!==void 0)l=r;else throw o}return f.createElement(ju.Provider,{value:{didCatch:i,error:o,resetErrorBoundary:this.resetErrorBoundary}},l)}}function bu(){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 wu=()=>{const e=cs(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>{const r=a.map(async o=>n(e,{action:B.UPLOAD_ASSET,data:o}));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:[B.GET_ASSETS]});const i=a==null?void 0:a.length;Q.toast.success(`${i===1?"Asset":i+" Assets"} uploaded successfully`)}},onError:()=>{Q.toast.error("Failed to upload asset")}})},Su=()=>{const e=cs(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:B.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[B.GET_ASSETS]}),Q.toast.success("Asset deleted successfully")},onError:()=>{Q.toast.error("Failed to delete asset")}})},Nu=()=>{const e=cs(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:B.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[B.GET_ASSETS]}),Q.toast.success("Asset updated successfully")},onError:()=>{Q.toast.error("Failed to update asset")}})};function Eu({currentPage:e,totalPages:s,onPageChange:n,pageRangeDisplayed:a=3,showPageInput:r=!0,className:i=""}){const[o,l]=f.useState(String(e)),u=f.useMemo(()=>{const j=Math.floor(a/2);let p=Math.max(1,e-j),w=Math.min(s,e+j);w-p+1<a&&(p===1?w=Math.min(s,p+a-1):w===s&&(p=Math.max(1,w-a+1)));const b=[];p>1&&(b.push(1),p>2&&b.push("..."));for(let E=p;E<=w;E++)b.push(E);return w<s&&(w<s-1&&b.push("..."),b.push(s)),b},[e,s,a]),h=j=>{j!==e&&j>=1&&j<=s&&(n(j),l(String(j)))},d=()=>{e>1&&h(e-1)},m=()=>{e<s&&h(e+1)},v=()=>{const j=Number(o);!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 w=j,b=w===e;return t.jsx(c.Button,{variant:b?"default":"outline",size:"sm",onClick:()=>h(w),className:b?"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:w},w)})}),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:o,onChange:j=>{const p=j.target.value.replace(/[^\d]/g,"");l(p)},onKeyDown:y,className:"h-8 w-16 px-2 py-1"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:v,disabled:o===""||Number(o)<1||Number(o)>s,children:"Go"})]})]})}const Cu=(e={})=>{const s=cs(),n=X(),{search:a,page:r=1,limit:i=30}=e;return G.useQuery({queryKey:[B.GET_ASSETS,a,r,i],queryFn:async()=>{const o=await n(s,{action:B.GET_ASSETS,data:{search:a,page:r,limit:i}});return o.page=r,o.limit=i,o},staleTime:1e3*60*5,retry:1})},Tu=e=>{const s=cs(),n=X();return G.useQuery({queryKey:[B.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:B.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Au(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 ta(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 sa(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 ku=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,v,y;const{data:i,isLoading:o,isError:l}=Tu(e||""),[u,h]=f.useState(""),d=async(j,p)=>{try{await navigator.clipboard.writeText(j),Q.toast.success(`${p} copied to clipboard`)}catch(w){Q.toast.error(`Failed to copy ${p}`,{description:w==null?void 0:w.message})}};return f.useEffect(()=>{i!=null&&i.description&&h(i.description)},[i]),o?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(S.Loader,{className:"h-8 w-8 animate-spin"})}):l||!(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:l?"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"}),l&&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:Au(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:ta(i.createdAt)},{label:"Updated",value:ta(((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||!sa(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!sa(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"})})]})]})]})]})},Pu=f.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs"))),Iu=25*1024*1024,_u=({isUpdatingAsset:e,allowedTypes:s,uploadAssets:n,isUploadingAsset:a,onUploaded:r})=>{const[i,o]=f.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});f.useEffect(()=>{localStorage.setItem("chai_optimize_images",i.toString())},[i]);const l=e||a,u=f.useCallback(async y=>{try{const j=y;if(!j.every(E=>E.type.startsWith("image/")))return Q.toast.error("Invalid file type. Please upload a valid file."),Promise.reject(new Error("Invalid file type"));const p=j.map(async E=>{let P=E;return E.type.startsWith("image/")&&(P=await ba(E)),new Promise((D,_)=>{const C=new FileReader;C.readAsDataURL(P),C.onload=async()=>{D({file:C.result,folderId:void 0,name:E.name,optimize:i})},C.onerror=()=>_(null)})}),w=await Promise.all(p),b=await n(w);return(b==null?void 0:b.length)===1&&r(b[0]),b}catch(j){return Promise.reject(j)}},[n,i,r]),h=y=>{const j=[];let p=0;return y.forEach(w=>{w.size>Iu?p++:j.push(w)}),p>0&&Q.toast.error(`${p===1&&y.length===1?"File":p+(p===1?" file":" files")} exceed the maximum size limit of 10MB.`),x.isEmpty(j)?[]:u(j)},{getRootProps:d,getInputProps:m,isDragActive:v}=Or.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 ${l?"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:q.mergeClasses("flex h-max w-full cursor-pointer flex-col justify-center rounded-lg text-center",l?"items-start":"items-center",v?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...m()}),l?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=>{o(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 Ir({close:e,onSelect:s,mode:n="image",assetId:a}){const o=f.useMemo(()=>[n],[n]),[l,u]=f.useState(null),[h,d]=f.useState(null),[m,v]=f.useState(null),[y,j]=f.useState({show:!1,file:""}),[p,w]=f.useState(!1),[b,E]=f.useState(a?"details":"grid"),[P,D]=f.useState(""),[_,C]=f.useState(""),[K,ee]=f.useState(1),[V]=f.useState(30),[I,M]=f.useState([]);f.useEffect(()=>{a&&(u(a),E("details"))},[a]),f.useEffect(()=>{const k=setTimeout(()=>{D(_),ee(1)},300);return()=>clearTimeout(k)},[_]);const{data:$,isLoading:L}=Cu({search:P.toLowerCase().trim(),page:K,limit:V}),se=($==null?void 0:$.assets)||[],W=($==null?void 0:$.total)||0,he=Math.ceil(W/V);f.useEffect(()=>{L||he<=0||ee(k=>k>he?he:k<1?1:k)},[L,he]);const je=(se==null?void 0:se.length)>0,{mutate:we}=Su(),{mutateAsync:oe,isPending:N}=wu(),{mutate:g,isPending:A}=Nu(),R=f.useCallback(k=>{const te=Math.min(Math.max(1,k),Math.max(1,he));te!==K&&ee(te)},[he,K]),z=k=>{C(k.target.value)},O=f.useCallback(k=>{M(te=>x.find(te,{id:k.id})?[]:[k])},[!1]),U=f.useCallback(()=>{M([])},[]),F=k=>{(k==null?void 0:k.length)!==0&&(s(x.pick(x.first(k||I),["id","url","width","height","description"])),e())},J=async k=>{d(k)},le=async()=>{h&&(v(h==null?void 0:h.id),await we(h.id,{onSuccess:()=>{v(null),d(null)},onError:()=>{v(null)}}),d(null))},H=k=>{u(k.id),E("details")},ae=async(k,te)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";te?(await oe([{file:k,folderId:void 0,name:y.name||"",optimize:Ee}]),j({show:!1,file:""})):(await g({id:y.id||"",file:k}),j({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},me=f.useCallback(k=>{M([k])},[]),xe=f.useCallback(k=>{R(k)},[R]);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"}),b==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(_u,{maxFileSize:10,allowedTypes:o,uploadAssets:oe,isUpdatingAsset:A,isUploadingAsset:N,onUploaded:me}),t.jsxs("div",{className:"relative flex flex-1 flex-col gap-y-3 overflow-hidden rounded-lg border p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2",children:[t.jsx(S.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${_.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:z,value:_,className:"pl-8"})]}),I.length>0?t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("div",{className:"flex items-center gap-2",children:[I.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>U(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>F(I),disabled:I.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:L?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"})]}):!L&&!je?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center rounded-lg border",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(S.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-lg text-muted-foreground",children:"No assets found"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:P.length>0?"No assets found for your search: "+P:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:se==null?void 0:se.map(k=>t.jsxs("div",{className:q.mergeClasses("group relative flex max-h-[180px] max-w-[180px] cursor-pointer flex-col justify-between overflow-hidden rounded-lg border-2 transition-all",I.some(te=>te.id===k.id)?"border-blue-500":"hover:border-black/90",m&&(h==null?void 0:h.id)===k.id?"pointer-events-none opacity-50":"",m===k.id?"pointer-events-none opacity-50":""),onClick:()=>O(k),onDoubleClick:()=>F([k]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===k.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,k.type==="image"?t.jsx("img",{src:`${k.thumbnailUrl||"/placeholder.svg"}?v=${(k==null?void 0:k.updatedAt)||k.createdAt}`,alt:k.name,className:`h-full min-h-[80px] w-full object-contain ${I.some(te=>te.id===k.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"}),k.thumbnailUrl&&t.jsx("img",{src:`${k.thumbnailUrl||"/placeholder.svg"}?v=${(k==null?void 0:k.updatedAt)||k.createdAt}`,alt:k.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:k.name,children:k.name}),t.jsx("div",{className:"flex items-center justify-between whitespace-nowrap text-[9px] font-light text-muted-foreground",children:t.jsx("span",{children:tn((k==null?void 0:k.size)||0)})})]}),!I.some(te=>te.id===k.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:te=>{te.stopPropagation(),H(k)},children:t.jsx(S.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:te=>{te.stopPropagation(),navigator.clipboard.writeText(k.url),Q.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:te=>{te.stopPropagation(),j({id:k.id,show:!0,file:k.url,name:k.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:te=>{te.stopPropagation(),J(k)},children:t.jsx(S.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),I.some(te=>te.id===k.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})})]},k.id))})}),he>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 border-t bg-white p-4",children:t.jsx(vu,{fallback:t.jsx("div",{className:"text-red-500",children:"Error loading pagination"}),children:t.jsx(Eu,{currentPage:K,totalPages:he,onPageChange:xe,pageRangeDisplayed:3,showPageInput:!0})})})]})]}):t.jsx(ku,{assetId:l||a||"",onBack:()=>{E("grid"),u(null)},onEdit:k=>{j({id:k.id,show:!0,file:k.url,name:k.name})},onSave:async k=>{if(l){w(!0);try{const te=se.find(Ee=>Ee.id===l);te&&await g(x.merge(te,{description:k}))}finally{w(!1)}}},isSaving:p})]}),y.show&&t.jsx(f.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(Pu,{imageUrl:y.file,onSave:ae,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:le,children:"Delete"})]})]})})]})}const Du=Object.freeze(Object.defineProperty({__proto__:null,default:Ir},Symbol.toStringTag,{value:"Module"})),Ls=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[o,l]=f.useState(!1),u=()=>{i||l(!0)},h=()=>{l(!1)},d=y=>{const j=Array.isArray(y)?y[0]:y;j!=null&&j.url&&n(x.pick(j,["url","id"])),l(!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:o,onOpenChange:l,children:t.jsxs(c.DialogContent,{className:"h-fit w-full max-w-7xl overflow-hidden p-0",children:[t.jsxs(c.DialogHeader,{className:"hidden border-b px-4 py-2",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:h,children:t.jsx(S.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"h-full flex-1 p-4",children:t.jsx(Ir,{close:h,onSelect:d,mode:"image",assetId:e})})]})})]})},Lu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),Bu=()=>{const[e,s]=f.useState({logoUrl:"",logoId:"",faviconUrl:"",faviconId:""}),[n,a]=f.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(Ls,{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(Ls,{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"})})]})]})},Mu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),Ou=()=>{const[e,s]=f.useState({contactEmail:"",contactPhone:"",contactAddress:""}),[n,a]=f.useState([]),[r,i]=f.useState({isOpen:!1,platform:"",url:"",customName:""}),[o,l]=f.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(w=>({...w,[p.target.name]:p.target.value})),d=()=>{const{platform:p,url:w,customName:b}=r;if(!w.trim()||!p)return;const E=p==="other"?b:p;E.trim()&&(a(P=>[...P,{platform:E,url:w,isCustom:p==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=p=>a(w=>w.filter((b,E)=>E!==p)),v=()=>i({isOpen:!1,platform:"",url:"",customName:""}),y=()=>{l(!0);const p={};n.forEach(b=>{p[b.platform.toLowerCase().replace(/\s+/g,"_")]=b.url});const w={...e,socialLinks:p};setTimeout(()=>{l(!1),console.log("Contact & Social settings saved:",w),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(w=>({...w,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(w=>({...w,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(w=>({...w,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,w)=>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(w),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},w))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:y,disabled:!j||o,className:"w-full",children:o?"Saving...":"Save Contact & Social Settings"})})]})]})},Ru=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),Gu=()=>{const[e,s]=f.useState({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),[n,a]=f.useState([]),[r,i]=f.useState(""),[o,l]=f.useState(!1),u=y=>{const{name:j,value:p}=y.target;s(w=>({...w,[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=()=>{l(!0);const y={...e,customTrackingScripts:n.map(j=>j.content)};setTimeout(()=>{l(!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||o,className:"w-full",children:o?"Saving...":"Save Settings"})})]})]})},Uu=()=>{Ns("branding",{label:"Branding",button:Lu,panel:Bu}),Ns("contact-social",{label:"Contact & Social",button:Mu,panel:Ou}),Ns("analytics-tracking",{label:"Analytics & Tracking",button:Ru,panel:Gu})},Fu=f.lazy(()=>Promise.resolve().then(()=>Du));gu();Rr.loadWebBlocks();q.registerChaiTopBar(Yl);No();Uu();q.registerChaiMediaManager(Fu);q.registerChaiSaveToLibrary(Ni);const qu=e=>{const s=f.useRef([]),[n]=Ie(),a=n.get("page"),{data:r}=Ae(),{data:i={role:"",permissions:null}}=Ra();to(),ui();const{data:o,isFetching:l}=ja(),{blocks:u}=eo(o),{data:h}=ke(),{mutateAsync:d}=ua(),m=Xl(),{onSave:v}=so(),{getPartialBlocks:y,getPartialBlockBlocks:j}=no(),{aiContext:p,setAiContext:w}=xn(),{mutateAsync:b}=Ci(),[E,P]=f.useState(!1),{data:D}=Ve(),_=Ye(),{data:C}=yn(),{data:K}=pu(),{mutateAsync:ee}=yu(),V=Pr();Xr(),f.useEffect(()=>{const L=()=>{document.hidden?P(!0):P(!1)};return window.addEventListener("visibilitychange",L),()=>window.removeEventListener("visibilitychange",L)},[]),s.current=u;const I=f.useMemo(()=>{const L={};return i&&(L.permissions=x.get(i,"permissions",null),L.role=x.get(i,"role","user")),L},[i]),M=f.useCallback(async(L,se)=>await b({pageType:L,query:se}),[b]),$=f.useMemo(()=>x.get(D,"theme",{})||{},[D]);return t.jsxs(t.Fragment,{children:[t.jsx(q.ChaiBuilderEditor,{gotoPage:V,collections:K??[],getBlockAsyncProps:ee,pageExternalData:C,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:l,fallbackLang:_,languages:(D==null?void 0:D.languages)||[],brandingOptions:(D==null?void 0:D.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!E&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:j,getPartialBlocks:y,blocks:l?[]:u,theme:x.cloneDeep($),pageTypes:h,searchPageTypeItems:M,saveAiContextCallback:async L=>{if(!a)return!0;const se=s.current,W={_type:"@chai/ai-context",_value:x.isString(L)?L:""},he=[...se,W];return await v({page:a,blocks:he}),w(L),!0},aiContext:p,askAiCallBack:m,onSave:async({blocks:L,theme:se,needTranslations:W})=>{if(!a)return!0;s.current=L;const he={_type:"@chai/ai-context",_value:x.isString(p)?p:""},je=[...L,he];return await v({page:a,blocks:je,needTranslations:W}),s.current=je,x.isEqual(se,$)||await d({settings:{theme:se}}),!0},themePanelComponent:Bi,...I}),t.jsxs("div",{children:[t.jsx(mi,{}),t.jsx(fi,{})]})]})},zu=new G.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),$u=e=>{const{isLoggedIn:s}=Ge(),[,n]=da(),[a,r]=f.useState(!1);return f.useEffect(()=>(n(x.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","getAccessToken","supabaseInstance"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?t.jsxs(G.QueryClientProvider,{client:zu,children:[s?t.jsx(qu,{...e}):t.jsx(lo,{}),t.jsx(xu,{})]}):t.jsx("div",{})},Vu=()=>{const{savePageAsync:e}=q.useSavePage(),s=G.useQueryClient();return f.useCallback(async()=>{await e(),s.invalidateQueries({queryKey:[B.GET_DRAFT_PAGE]}),s.invalidateQueries({queryKey:[B.GET_BUILDER_PAGE_DATA]})},[e,s])},Ku=()=>{const e=ie(),s=X(),{data:n}=Qe(),a=G.useQueryClient();return G.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:B.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[B.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[B.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},Hu=()=>{const{logout:e}=Ge(),{getAccessToken:s}=oa();return f.useCallback(async({url:n,method:a="GET",body:r={},headers:i={}})=>{const o=await s();if(!o)throw new Error("No auth token");if(!n)throw new Error("URL is required");try{const l=await fetch(n,{method:a,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...i},body:JSON.stringify(r)});if(l.status===401)return console.log("Session expired",l),await e(),window.location.reload(),null;if(l.status===400)throw new Error((await l.json()).error);return await l.json()}catch(l){throw console.log("Something went wrong",l),l}},[e,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Tn;exports.ChaiBuilderPages=$u;exports.ChaiBuilderPagesRealtime=ga;exports.Dynamic=bc;exports.For=Ko;exports.ImagePicker=Ls;exports.Index=Ho;exports.LanguageSwitcher=Cn;exports.Match=Jo;exports.NestedPathSelector=Ke;exports.PermissionChecker=Me;exports.Portal=jc;exports.Show=Qo;exports.SmartJsonInput=an;exports.Switch=Wo;exports.addEventListener=lr;exports.batch=ko;exports.className=ir;exports.clearDelegatedEvents=cc;exports.convertRemToPixels=cu;exports.createComponent=Pn;exports.createComputed=Ha;exports.createContext=Lo;exports.createEffect=An;exports.createMemo=Ce;exports.createRenderEffect=st;exports.createRoot=tt;exports.createSignal=Se;exports.createUniqueId=Vo;exports.delegateEvents=rr;exports.deleteNestedDataByPath=Gt;exports.displayValue=nu;exports.getMutationStatusColor=tu;exports.getPreferredColorScheme=uu;exports.getQueryStatusColor=eu;exports.getQueryStatusColorByLabel=su;exports.getQueryStatusLabel=Xc;exports.getSidedProp=Zc;exports.insert=Ds;exports.memo=ic;exports.mergeProps=In;exports.mutationSortFns=ou;exports.on=Po;exports.onCleanup=_t;exports.onMount=Qa;exports.registerChaiSiteSetting=Ns;exports.registerLoginComponent=io;exports.serialize=Cr;exports.setAttribute=_s;exports.sortFns=iu;exports.splitProps=tr;exports.spread=or;exports.stringify=Yc;exports.template=oc;exports.untrack=Te;exports.updateNestedDataByPath=Rt;exports.use=cr;exports.useActivePage=Qe;exports.useBuilderPageData=yn;exports.useChaiAuth=Ge;exports.useChaiFetch=Hu;exports.useChaiUserInfo=We;exports.useContext=Bo;exports.useCurrentPage=Ae;exports.useFallbackLang=Ye;exports.useFetch=X;exports.useGotoPage=Pr;exports.useLanguagePages=Re;exports.usePageTypes=ke;exports.useReloadPage=Vu;exports.useTransition=Do;exports.useUpdateActivePageMetadata=Ku;exports.useUserRoleAndPermissions=Ra;exports.useWebsitePages=Lt;exports.useWebsiteSetting=Ve;