@chaibuilder/pages 0.13.2 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +0,0 @@
1
- "use strict";var Ur=Object.defineProperty;var _n=e=>{throw TypeError(e)};var Fr=(e,s,n)=>s in e?Ur(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var et=(e,s,n)=>Fr(e,typeof s!="symbol"?s+"":s,n),Ln=(e,s,n)=>s.has(e)||_n("Cannot "+n);var te=(e,s,n)=>(Ln(e,s,"read from private field"),n?n.call(e):s.get(e)),he=(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),ue=(e,s,n,a)=>(Ln(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),g=require("lodash-es"),x=require("react"),ge=require("jotai"),R=require("@tanstack/react-query"),J=require("sonner"),Q=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),ut=require("date-fns"),N=require("lucide-react"),qr=require("compressorjs"),Ws=require("react-diff-view"),oa=require("@chaibuilder/runtime"),bs=require("zod"),zr=require("react-dropzone"),$r=require("@chaibuilder/sdk/web-blocks");function Vr(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 je=Vr(x),Ne={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},_={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",GET_APP_SHARED_JSONLD:"GET_APP_SHARED_JSONLD",UPDATE_APP_SHARED_JSONLD:"UPDATE_APP_SHARED_JSONLD",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"};let Kr=0;function Bn(e,s){const n=`atom${++Kr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Hr,a.write=Qr),s&&(a.write=s),a}function Hr(e){return e(this)}function Qr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const Wr=Symbol(""),ca=e=>typeof(e==null?void 0:e.then)=="function";function Jr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,m;const y=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},j=(m=(h=e())==null?void 0:h.getItem(u))!=null?m:null;return ca(j)?j.then(y):y(j)},setItem:(u,d)=>{var h;return(h=e())==null?void 0:h.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},o=u=>(d,h,m)=>u(d,y=>{let j;try{j=JSON.parse(y||"")}catch{j=m}h(j)});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,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=m=>{m.storageArea===e()&&m.key===u&&d(m.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),l&&(i.subscribe=o(l)),i}const Yr=Jr();function ua(e,s,n=Yr,a){const r=Bn(s);return r.onMount=o=>{o(n.getItem(e,s));let l;return n.subscribe&&(l=n.subscribe(e,o,s)),l},Bn(o=>o(r),(o,l,u)=>{const d=typeof u=="function"?u(o(r)):u;return d===Wr?(l(r,s),n.removeItem(e)):ca(d)?d.then(h=>(l(r,h),n.setItem(e,h))):(l(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const da="__logged_in_user",Xr=ua(da,null),Ge=()=>{const[e,s]=ge.useAtom(Xr),n=x.useCallback(()=>{s(null),localStorage.removeItem(da)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},xn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)});let xt=null;function Zr(){const{user:e,setUser:s,logout:n}=Ge(),a=Os(),r=Ue("getAccessToken",!1),i=async()=>{if(r===!1&&e&&!(!g.has(e,"expiresAt")||!g.has(e,"accessToken")||!g.has(e,"refreshToken")))try{const o=await xn(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(g.has(l,"id")&&g.has(l,"email")&&g.has(l,"accessToken")&&g.has(l,"refreshToken"))return s(l),l;n(),window.location.reload()}catch{n(),window.location.reload()}};return R.useMutation({mutationFn:async()=>{if(xt)return await xt;xt=i();try{return await xt}finally{xt=null}},onSuccess:()=>{}})}function ei(){return xt}const ha=()=>{const{user:e,setUser:s}=Ge(),{mutateAsync:n}=Zr(),a=60,r=x.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(!g.has(e,"expiresAt")||!g.has(e,"accessToken")||!g.has(e,"refreshToken"))return(e==null?void 0:e.accessToken)||"";if(r()){const l=ei();if(l){const d=await l;return d&&s(d),(d==null?void 0:d.accessToken)||""}const u=await n();return u&&s(u),(u==null?void 0:u.accessToken)||""}return(e==null?void 0:e.accessToken)||""});return{getAccessToken:x.useCallback(async()=>{try{return await o()}catch{return""}},[o])}},X=()=>{const{logout:e}=Ge(),{getAccessToken:s}=ha();return x.useCallback(async(n,a,r={})=>{const i=await s();if(!i)return console.error("No auth token found"),null;try{const o=g.get(a,"action","").toLowerCase(),l=await xn(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])},ma=()=>{const e=re(),s=R.useQueryClient(),n=X();return R.useMutation({mutationFn:async a=>n(e,{action:_.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]})}})},fa=()=>{const e=re(),s=R.useQueryClient(),n=X();return R.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[_.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||J.toast.success("Website settings updated successfully.")},onError:a=>{J.toast.error("Failed to update website settings",{description:a.message})}})},ti=()=>{const e=re(),s=R.useQueryClient(),n=X();return R.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[_.GET_WEBSITE_DATA]}),J.toast.success("Website data updated successfully.")},onError:a=>{J.toast.error("Failed to update website data",{description:a.message})}})},xa=()=>{const e=re(),s=R.useQueryClient(),n=X();return R.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_APP_SHARED_JSONLD,data:JSON.stringify(a)}),onSuccess:()=>{s.invalidateQueries({queryKey:[_.GET_APP_SHARED_JSONLD]}),J.toast.success("Shared JSON-LD updated successfully.")},onError:a=>{J.toast.error("Failed to update shared JSON-LD",{description:a.message})}})};function Ie(){const[e,s]=x.useState(new URLSearchParams(window.location.search));return x.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const si=ge.atom({}),gn=()=>ge.useAtom(si),ni=()=>{const[e]=Ie(),s=e.get("page"),n=x.useRef(""),{mutate:a}=ma();x.useEffect(()=>{!g.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Ue=(e,s)=>{const[n]=gn();return x.useMemo(()=>g.get(n,e,s),[n,e,s])},re=()=>Ue("apiUrl","/chai/api"),Os=()=>Ue("usersApiUrl","/chai/users"),us=()=>Ue("assetsApiUrl","/chai/assets"),ai=()=>Ue("supabaseInstance",null),Re=e=>{const s=re(),[n]=Ie(),a=e??n.get("page"),r=X();return R.useQuery({queryKey:[_.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:_.GET_LANGUAGE_PAGES,data:{id:a}});return g.reverse(g.sortBy(i,"primaryPage"))},enabled:!!a})},Ve=()=>{const e=re(),s=X();return R.useQuery({queryKey:[_.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:_.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},ga=e=>{const{fallbackLang:s}=Q.useLanguages(),{data:n}=Ve(),{data:a,isFetching:r}=Re(),i=x.useMemo(()=>{const o={[s]:!0};return g.each(g.get(n,"languages"),l=>{const u=g.find(a,{lang:l});o[l]=!!u}),o},[s,a,n]);return r||g.isEmpty(e)||e&&i[e]},pa=()=>{const e=R.useQueryClient(),{data:s}=R.useQuery({queryKey:[_.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:x.useCallback(a=>{e.setQueryData([_.AI_CONTEXT],a)},[e]),aiContext:s}},ri=ge.atom(null),ya=()=>ge.useAtom(ri),pn=()=>{const[e]=ya();return(e==null?void 0:e.slug)||""};function ii(e,s){const[n,a]=x.useState(e);return x.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const li=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=Q.useLanguages(),{data:r}=Ce(),i=r==null?void 0:r.pageType,o=re(),l=X(),{data:u,isFetching:d}=R.useQuery({queryKey:[_.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await l(o,{action:_.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),h=x.useMemo(()=>n===""?u.filter(m=>m.lang===""||m.lang===a):u.filter(m=>m.lang===n),[n,a,u]);return{allLangPages:u,data:h,isFetching:d}},ja=()=>{const{selectedLang:e,fallbackLang:s}=Q.useLanguages(),[n,a]=ya(),[r,i]=x.useState(""),o=ii(r,500),{allLangPages:l,data:u,isFetching:d}=li({query:o}),h=x.useCallback(j=>a(j),[a]),m=x.useCallback(j=>i(j),[i]),y=x.useCallback(()=>{if(!n)return;const j=!(n!=null&&n.primaryPage),p=e.length===0,f=j?n==null?void 0:n.id:n==null?void 0:n.primaryPage,v=l.filter(S=>(S==null?void 0:S.primaryPage)===f||S.id===f).find(S=>p?S.lang===e||S.lang===s:S.lang===e);a(v||n)},[n,e,l,a,s]);return{isPending:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:l,updateDynamicPage:h,updateSearchQuery:m,onChangeLanguage:y}},oi=ge.atom({lastSaved:void 0}),Ms=()=>ge.useAtom(oi),Ce=()=>{const[e]=Ie(),s=e.get("page"),{data:n,isFetching:a}=Re();return{data:x.useMemo(()=>({...g.find(n,{id:s})||{}}),[n,s]),isFetching:a}},We=()=>{const[e]=Ie(),s=e.get("lang")??"",{data:n,isFetching:a}=Re();return{data:x.useMemo(()=>g.find(n,{lang:s})||{},[n,s]),isFetching:a}},ci=ge.atom({}),ui=()=>ge.useAtom(ci),va=()=>{const{data:e}=We(),s=pn(),n=Ue("getLiveUrl",g.noop),a=e==null?void 0:e.slug,r=n(a||"/");return s?r+s:r};class ba{constructor(s,n,a,r){et(this,"channelId");et(this,"supabase");et(this,"channel",null);et(this,"userId",null);et(this,"clientId",null);et(this,"pageId",null);et(this,"callback");var i,o,l,u,d,h;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}}}),(h=(d=(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:d.on("broadcast",{event:"TAKE_OVER_REQUEST_ACCEPTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUEST_ACCEPTED",m)))==null||h.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=g.groupBy(s,"pageId"),a={};return Object.keys(n).forEach(r=>{var o;const i=(o=g.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 Je=e=>{const s=Os(),n=X();return R.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:_.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!g.isEmpty(e)})},di=ge.atom(void 0),hi=ge.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),mi=ge.atom(""),fi=ge.atom(null),yn=ge.atom({}),wa=()=>ge.useAtom(yn),Ke=()=>{const[e]=Ie(),s=e.get("page"),{user:n}=Ge(),[a,r]=ge.useAtom(di),[i,o]=ge.useAtom(hi),[l,u]=ge.useAtom(fi),[d,h]=ge.useAtom(mi),[m]=ge.useAtom(yn);return{pageLock:i,pageToUser:m,lockingStatus:d,realtimeInstance:l,setPageLock:o,setCurrentEditor:r,setLockingStatus:h,setRealtimeInstance:u,realtimePageLockEnabled:!!l,currentEditor:l?m[s||""]:a,isLocked:l?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a}},xi=()=>{const e=ai(),{data:s}=Ce(),{user:n}=Ge(),a=s==null?void 0:s.id,{data:r}=Ve(),{pageLock:i,setPageLock:o,setLockingStatus:l,realtimeInstance:u,setRealtimeInstance:d}=Ke(),[,h]=ge.useAtom(yn),m=x.useRef(!1),y=x.useRef(i),j=x.useRef(!1);return x.useEffect(()=>{if(n!=null&&n.id&&e&&!u&&(r!=null&&r.appKey)&&!j.current){j.current=!0;const p=async(b,v)=>{var S,P;switch(b){case"UPDATE_ONLINE_USERS":h((v==null?void 0:v.pageToUser)||{});break;case"PAGE_LOCKED":o({...y==null?void 0:y.current,requestedBy:"",status:"locked",isActiveInOtherTab:v==null?void 0:v.isActiveInOtherTab});break;case"USER_JOINED":if(((S=y==null?void 0:y.current)==null?void 0:S.status)==="editing")return;((P=y==null?void 0:y.current)==null?void 0:P.status)==="locked"&&l("can_edit_now"),o({...y==null?void 0:y.current,requestedBy:"",status:"editing",isActiveInOtherTab:v==null?void 0:v.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":o({...y==null?void 0:y.current,requestingClientId:v==null?void 0:v.requestingClientId,requestedBy:v!=null&&v.isRequestedFromAnotherTab?"ANOTHER_TAB":v==null?void 0:v.requestedBy});break;case"TAKE_OVER_REQUEST_ACCEPTED":v!=null&&v.isTakingOverFromAnotherTab||(l("take_over_request_accepted"),J.toast.success("Your Page Take Over Request Accepted",{position:"top-center"})),o({...y==null?void 0:y.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":l("take_over_request_rejected"),o({...y==null?void 0:y.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},f=new ba(e,r==null?void 0:r.appKey,n==null?void 0:n.id,p);d(f)}},[d,e,r==null?void 0:r.appKey]),x.useEffect(()=>{y.current=i},[i]),x.useEffect(()=>{if(!(!u||!a||!(n!=null&&n.id)||m.current))return m.current=!0,u==null||u.joinPage(a),()=>{u&&m.current&&(m.current=!1,y.current={requestedBy:"",status:"checking",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1},l(""),o(y.current),u==null||u.leavePage())}},[a,u]),i==null?void 0:i.status},Na=()=>{const{data:e}=Ce(),{user:s}=Ge(),n=e==null?void 0:e.id,{pageLock:a,setPageLock:r,realtimeInstance:i}=Ke(),{savePageAsync:o}=Q.useSavePage(),l=x.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(r({...a,isTakeOverRequested:!0}),i==null||i.sendEvent("TAKE_OVER_REQUESTED"))},[i,n,s==null?void 0:s.id,r,a]),u=x.useCallback(async()=>{!i||!n||!(s!=null&&s.id)||(await 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]),d=x.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(i==null||i.sendEvent("TAKE_OVER_REQUEST_REJECTED",{requestingClientId:a==null?void 0:a.requestingClientId}),r({...a,requestedBy:"",status:"editing",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1}))},[n,i,s==null?void 0:s.id,r,a]);return{pageLock:a,acceptTakeOver:u,rejectTakeOver:d,requestTakeOver:l}},Ye=()=>{const{data:e}=Ve();return x.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},Sa=()=>{const[e]=Ie(),s=e.get("page"),n=re(),{setAiContext:a}=pa(),{setCurrentEditor:r}=Ke(),[,i]=Ms(),[,o]=ui(),[,l]=Q.useIsPageLoaded(),u=X();return R.useQuery({queryKey:[_.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r(""),l(!1);const d=await u(n,{action:_.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(d.currentEditor);const h=d.blocks??[],m=g.find(h,{_type:"@chai/ai-context"});return a(g.get(m,"_value","")||""),i(y=>({...y,lastSaved:d.lastSaved})),o(g.get(d,"metadata",{})),setTimeout(()=>l(!0),500),h},enabled:!!s})},jn=()=>{const{data:e}=Ce(),{data:s}=We(),n=re(),a=X(),r=Ye(),i=pn();return R.useQuery({queryKey:[_.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:_.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})},Dt=({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/40",children:e}),gi=({userId:e})=>{const{data:s}=Je(e);return(s==null?void 0:s.name)||"Unknown"};function pi({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,isRequestRejected:i,isFetchingUserInfo:o,realtimePageLockEnabled:l}){const[u,d]=x.useState(!1),[h,m]=x.useState(!1),y=()=>{d(!0),setTimeout(()=>{d(!1)},15e3),m(!1),r()};return t.jsx(Dt,{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(N.LockKeyhole,{className:"h-8 w-8 rounded-md bg-sky-500/20 p-1.5 text-sky-500"}),"Page is locked for editing"]})}),t.jsx(c.CardContent,{className:"w-md grid w-full pt-2",children:t.jsxs("div",{children:[t.jsxs("div",{className:"relative mx-auto flex w-96 items-center space-x-4 rounded-md border border-green-500 px-2 pb-2 pt-4",children:[t.jsx("div",{className:"absolute -top-2.5 left-3 w-max rounded-full bg-green-500 px-3 py-1 text-xs font-medium leading-3 text-white",children:"Locked By"}),e&&!o?t.jsx("img",{src:e,alt:s,className:"h-14 w-14 rounded-full border border-gray-300"}):t.jsx(N.UserIcon,{className:"h-14 w-14 flex-shrink-0 rounded-full bg-gradient-to-br from-purple-400 to-pink-500 p-2 text-white"}),t.jsxs("div",{className:o?"space-y-1.5":"space-y-0",children:[o?t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"}):t.jsx("span",{className:"truncate font-medium text-black",children:s}),n&&!o?t.jsx("p",{className:"truncate text-sm text-muted-foreground",children:n}):t.jsx(c.Skeleton,{className:"h-4 w-60 rounded"}),a&&!o?t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",ut.formatDistanceToNow(new Date(a),{addSuffix:!0})]}):t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{className:"py-4 text-center text-gray-600",children:["This page is currently being edited by ",t.jsx("span",{className:"font-bold",children:s}),".",t.jsx("br",{}),l&&t.jsxs(t.Fragment,{children:[" ",t.jsx("br",{})," You can either wait until they finish editing or"," ",l?"request to":""," take over the page."]})]})}),i&&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(N.Info,{className:"h-5 w-5"})," Page take over request is rejected"]})]})}),t.jsx(c.CardFooter,{children:l?t.jsxs(c.Button,{disabled:u,onClick:y,className:"w-full",variant:"destructive",children:[t.jsx(N.KeyIcon,{className:"h-5 w-5"}),u?"Page take is requested.":i?"Request take over again":"Request take over"]}):t.jsxs(c.AlertDialog,{open:h,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(N.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:y,children:"Yes, Take Over"})]})]})]})})]})})}const ps=({isChecking:e,lockingStatus:s,onContinue:n})=>{const[a,r]=x.useState(!1),i=s==="page_is_active_in_other_tab",o=(s==null?void 0:s.length)>0,{pageLock:l,acceptTakeOver:u,rejectTakeOver:d}=Na(),h=()=>{r(!0),o||i?n():u(),setTimeout(()=>{r(!1)},3e3)};return x.useEffect(()=>{(l==null?void 0:l.requestedBy)==="ANOTHER_TAB"&&u()},[l,u]),(l==null?void 0:l.requestedBy)==="ANOTHER_TAB"?null:e?t.jsx(Dt,{children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin text-primary"})}):t.jsx(Dt,{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(N.Loader,{className:"h-6 w-6 animate-spin text-gray-500"}):i?t.jsx(N.TableIcon,{className:"h-6 w-6 text-green-500"}):o?t.jsx(N.CheckCircle,{className:"h-6 w-6 text-green-500"}):t.jsx(N.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(gi,{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:h,className:o?"":"bg-green-500 hover:bg-green-600",children:i?t.jsxs(t.Fragment,{children:[t.jsx(N.Edit,{className:"h-5 w-5"})," Continue editing here"]}):o?t.jsxs(t.Fragment,{children:[t.jsx(N.Edit,{className:"h-5 w-5"})," Continue to edit"]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Check,{className:"h-5 w-5"})," Accept"]})}),!o&&t.jsxs(c.Button,{variant:"outline",onClick:d,children:[t.jsx(N.X,{className:"h-5 w-5"})," Reject"]})]})]})})},yi=({isFetchingPage:e})=>{const{pageLock:s,requestTakeOver:n}=Na(),{isLocked:a,currentEditor:r,lockingStatus:i,setLockingStatus:o,realtimePageLockEnabled:l}=Ke(),{data:u,isFetching:d}=Je(r),[h]=Ie(),m=h.get("page"),{mutate:y}=ma(),{isFetching:j}=Sa(),[p]=Ms(),f=R.useQueryClient(),b=x.useCallback(()=>{l?n():y({id:m})},[m,y,n,l]);return!m||e?null:l&&(s==null?void 0:s.status)==="checking"?t.jsx(ps,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):l&&(s!=null&&s.requestedBy)?t.jsx(ps,{lockingStatus:"",onContinue:()=>{}}):(l?s.status!=="locked":!a||j)?i==="take_over_request_accepted"||i==="can_edit_now"?t.jsx(ps,{lockingStatus:i,onContinue:()=>{f.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]}),o("")}}):null:l&&(s!=null&&s.isActiveInOtherTab)?t.jsx(ps,{lockingStatus:"page_is_active_in_other_tab",onContinue:n}):t.jsx(pi,{...u,isFetchingUserInfo:d,name:(u==null?void 0:u.name)||"Unknown User",email:(u==null?void 0:u.email)||"",lastSaved:(p==null?void 0:p.lastSaved)||"",onTakeOver:b,realtimePageLockEnabled:l,isRequestRejected:i==="take_over_request_rejected"})},ji=()=>{const[e,s]=Ie(),n=e.get("lang"),a=ga(n),{setSelectedLang:r}=Q.useLanguages(),i=()=>{const l=new URLSearchParams(window.location.search);l.delete("lang");const u=l.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(l),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const o=g.get(Ne,n);return t.jsx(Dt,{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(N.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"})})]})})},vi=e=>{const s=re(),n=X();return R.useMutation({mutationFn:async a=>n(s,{action:_.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),J.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},bi=e=>{const s=re(),n=X();return R.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:_.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})},wi=e=>{const s=re(),n=X();return R.useMutation({mutationFn:async a=>n(s,{action:_.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),J.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},Ni=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[o,l]=x.useState(!1),u=Q.useUpdateBlocksPropsRealtime(),d=wi(()=>{u([e],{_libBlockId:void 0}),J.toast.success("Block deleted successfully"),l(!1),a()}),h=()=>{l(!0),d.mutate(s)},m=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:y=>y.preventDefault(),disabled:o,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:y=>!y&&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:h,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})},Si=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[o,l]=x.useState(!1);return t.jsx(Ni,{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(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Ei=()=>{const e=re(),s=X(),n=R.useQueryClient(),{data:a=[],isLoading:r,error:i}=R.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}=R.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"]}),J.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),J.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}},Ci=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),[r,i]=x.useState(""),o=x.useRef(null),{groups:l}=Ei(),[u,d]=x.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=x.useMemo(()=>[...l,...u.filter(j=>!l.some(p=>p.id===j.id))],[l,u]),m=()=>{const j=r.trim();if(!j)return;const p={id:j,name:j};d(f=>[...f,p]),s(p.id),i(""),a(!1)};x.useEffect(()=>{n&&o.current&&o.current.focus()},[n]);const y=j=>{j.key==="Enter"&&(j.preventDefault(),m())};return x.useEffect(()=>{e&&!h.some(j=>j.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:o,placeholder:"Enter new group name",value:r,onChange:j=>i(j.target.value),onKeyDown:y}),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:j=>s(j.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),l.length>0&&t.jsx("optgroup",{label:"Library Groups",children:l.map(j=>t.jsx("option",{value:j.id,children:j.name},`lib-${j.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(j=>!l.some(p=>p.id===j.id)).map(j=>t.jsx("option",{value:j.id,children:j.name},`local-${j.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(N.Plus,{className:"h-4 w-4"})})]})},On=3*1024*1024,Ai=10*1024*1024;function sn(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 Ea(e){return new Promise((s,n)=>{if(e.size<=On){s(e);return}new qr(e,{quality:.8,maxWidth:2048,maxHeight:2048,convertSize:On,success(a){s(a)},error(a){J.toast.error(`Failed to compress image. Image size is ${sn(e.size)}, which exceeds the maximum allowed size of ${sn(Ai)}.`),n(a)}})})}const Ti=({value:e,onChange:s})=>{const[n,a]=x.useState(!1),r=x.useRef(null),i=x.useCallback(async u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d)try{a(!0);let m=d;d.type.startsWith("image/")&&(m=await Ea(d));const y=new FileReader;y.onloadend=()=>{s(y.result),a(!1)},y.readAsDataURL(m)}catch(m){console.error("Error reading file:",m),a(!1),J.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(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:o,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"aspect-video h-[200px] max-h-[200px] overflow-hidden rounded-md border",children:t.jsx("img",{src:e,alt:"Preview",className:"h-full w-full object-contain"})})]})},ve={...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"},ki=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=Q.usePartailBlocksStore(),i=s.find(I=>I._id===a),o=i==null?void 0:i._libBlockId,l=!!o,u=x.useMemo(()=>s.some(I=>I._type==="PartialBlock"||I._type==="GlobalBlock"),[s]),d=x.useMemo(()=>{let I=[];for(const C of s)if(C._type==="PartialBlock"||C._type==="GlobalBlock"){let M=r(C.partialBlockId);C._parent&&(M==null?void 0:M.length)>0&&(M=M.map(G=>(g.isEmpty(G._parent)&&g.set(G,"_parent",C._parent),G))),I=[...I,...M]}else I.push(C);return I},[s,r]),[h,m]=x.useState(""),[y,j]=x.useState(""),[p,f]=x.useState(""),[b,v]=x.useState(""),[S,P]=x.useState({}),[z,B]=x.useState(!1),[O,W]=x.useState(l),[D,F]=x.useState(!1),{hasPermission:T}=Q.usePermissions(),$=T(ve.DELETE_LIBRARY_BLOCK),K=Q.useUpdateBlocksPropsRealtime(),V=()=>{K([a],{_libBlockId:void 0}),J.toast.success("Block delinked from library"),n()},{data:Y,isLoading:L,isError:me}=bi(o);x.useEffect(()=>{me&&l&&(F(!0),W(!1))},[me,l]),x.useEffect(()=>{Y&&!L&&(m(Y.name||""),j(Y.group||""),f(Y.description||""),v(Y.preview||""),W(!1))},[Y,L]),x.useEffect(()=>{const I=h.trim().length>=2,C=y.trim()!=="";B(I&&C)},[h,y]);const be=()=>{const I={};return h.trim()?h.length<2&&(I.name="Name must be at least 2 characters"):I.name="Name is required",y||(I.group="Group is required"),P(I),Object.keys(I).length===0},{resetLibrary:Ae}=Q.useLibraryBlocks({id:""}),ye=vi(I=>{l||K([a],{_libBlockId:I.id}),J.toast.success(`Block ${l?"updated":"saved"} successfully`),Ae(I.library),n()}),E=async I=>{if(I.preventDefault(),!be())return;const C=d.map(M=>(g.has(M,"_libBlockId")&&delete M._libBlockId,M));ye.mutate({name:h.trim(),group:y,blocks:C,description:p.trim(),...b&&b.startsWith("data:")?{previewImage:b}:{},...l?{id:o}:{}})},w=ye.isPending;return O||L?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"})}):D?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:V,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(N.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:E,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:S.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:I=>m(I.target.value),className:S.name?"border-destructive":""}),S.name&&t.jsx("p",{className:"text-xs text-destructive",children:S.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:S.group?"text-destructive":"",children:"Group"}),t.jsx(Ci,{value:y,onChange:j}),S.group&&t.jsx("p",{className:"text-xs text-destructive",children:S.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:I=>f(I.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Ti,{value:b,onChange:v})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[l&&$&&t.jsx(Si,{blockId:a,libBlockId:o,blockName:h,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:w,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:w||!z,children:w?"Saving...":l?"Update Block":"Save Block"})]})]})]})},le={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},Pi={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},ke=()=>{const e=re(),s=X();return R.useQuery({queryKey:[_.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:_.GET_PAGE_TYPES})})},Ca=e=>{const{data:s}=ke();return x.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Ii=()=>{const e=re(),s=X();return R.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:_.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Aa=()=>{const e=re(),s=R.useQueryClient(),n=X(),{data:a}=ke();return R.useMutation({mutationFn:async r=>await n(e,{action:_.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var l;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]});const o=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((l=g.find(a,{key:i.pageType}))==null?void 0:l.name)+" added successfully":"New page added successfully";J.toast.success(o)},onError:(r,i)=>{const o=g.find(a,{key:i.pageType});J.toast.error(`Failed to add new ${o!=null&&o.hasSlug?"page":o.name}.`,{description:g.get(Pi,r.message,r.message)})}})},vn=()=>{const e=re(),s=R.useQueryClient(),n=X(),{data:a}=We(),{data:r}=ke();return R.useMutation({mutationFn:async i=>await n(e,{action:_.UPDATE_PAGE,data:i}),onSuccess:(i,o)=>{(a==null?void 0:a.id)===(o==null?void 0:o.id)&&s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES]}),o&&(o!=null&&o.primaryPage||o!=null&&o.seo)?(s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,o==null?void 0:o.primaryPage]}),s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:(i,o)=>{const l=g.find(r,{key:o.pageType});J.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:i.message})}})},Di=()=>{const e=re(),s=R.useQueryClient(),n=X(),{data:a}=ke();return R.useMutation({mutationFn:async r=>n(e,{action:_.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){J.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const o=g.find(a,{key:i.pageType});J.toast.error(`Failed to delete ${o!=null&&o.hasSlug?"page":o.name}.`,{description:r.message})}})},_i=()=>{const e=re(),s=R.useQueryClient(),n=X(),{data:a}=ke();return R.useMutation({mutationFn:async r=>n(e,{action:_.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]});const o=g.find(a,{key:i.pageType});J.toast.success(o!=null&&o.hasSlug?le.PAGE_UNPUBLISH_SUCCESS:"New "+o.name+" added successfully.")},onError:(r,i)=>{const o=g.find(a,{key:i.pageType});J.toast.error(`Failed to take offline ${o!=null&&o.hasSlug?"page":o.name}.`,{description:r.message})}})},bn=()=>{const e=re(),s=X(),n=R.useQueryClient(),{data:a}=Ce(),{savePageAsync:r}=Q.useSavePage();return R.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:_.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[_.GET_CHANGES]}),n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),J.toast.error("Failed to publish pages.")}})},Li=()=>{const e=re(),s=X(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>{var r;return s(e,{action:_.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:[_.GET_WEBSITE_PAGES]}),J.toast.success("Page marked as template successfully.")},onError:()=>{J.toast.error("Failed to mark page as template.")}})},Bi=()=>{const e=re(),s=X(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>s(e,{action:_.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),J.toast.success("Page unmarked as template successfully.")},onError:()=>{J.toast.error("Failed to unmark page as template.")}})},Oi=()=>{const e=re(),s=X(),n=R.useQueryClient();return R.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:_.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{J.toast.success(le.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:()=>{J.toast.error("Failed to change slug")}})};var wn={};(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 E=new OffscreenCanvas(1,1),w=E.getContext("2d");w.fillRect(0,0,1,1);var I=E.transferToImageBitmap();try{w.createPattern(I,"no-repeat")}catch{return!1}return!0}();function u(){}function d(E){var w=n.exports.Promise,I=w!==void 0?w:s.Promise;return typeof I=="function"?new I(E):(E(u,u),null)}var h=function(E,w){return{transform:function(I){if(E)return I;if(w.has(I))return w.get(I);var C=new OffscreenCanvas(I.width,I.height),M=C.getContext("2d");return M.drawImage(I,0,0),w.set(I,C),C},clear:function(){w.clear()}}}(l,new Map),m=function(){var E=Math.floor(16.666666666666668),w,I,C={},M=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(w=function(G){var U=Math.random();return C[U]=requestAnimationFrame(function q(ee){M===ee||M+E-1<ee?(M=ee,delete C[U],G()):C[U]=requestAnimationFrame(q)}),U},I=function(G){C[G]&&cancelAnimationFrame(C[G])}):(w=function(G){return setTimeout(G,E)},I=function(G){return clearTimeout(G)}),{frame:w,cancel:I}}(),y=function(){var E,w,I={};function C(M){function G(U,q){M.postMessage({options:U||{},callback:q})}M.init=function(q){var ee=q.transferControlToOffscreen();M.postMessage({canvas:ee},[ee])},M.fire=function(q,ee,ie){if(w)return G(q,null),w;var H=Math.random().toString(36).slice(2);return w=d(function(se){function de(fe){fe.data.callback===H&&(delete I[H],M.removeEventListener("message",de),w=null,h.clear(),ie(),se())}M.addEventListener("message",de),G(q,H),I[H]=de.bind(null,{data:{callback:H}})}),w},M.reset=function(){M.postMessage({reset:!0});for(var q in I)I[q](),delete I[q]}}return function(){if(E)return E;if(!a&&i){var M=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
2
- `);try{E=new Worker(URL.createObjectURL(new Blob([M])))}catch(G){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",G),null}C(E)}return E}}(),j={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function p(E,w){return w?w(E):E}function f(E){return E!=null}function b(E,w,I){return p(E&&f(E[w])?E[w]:j[w],I)}function v(E){return E<0?0:Math.floor(E)}function S(E,w){return Math.floor(Math.random()*(w-E))+E}function P(E){return parseInt(E,16)}function z(E){return E.map(B)}function B(E){var w=String(E).replace(/[^0-9a-f]/gi,"");return w.length<6&&(w=w[0]+w[0]+w[1]+w[1]+w[2]+w[2]),{r:P(w.substring(0,2)),g:P(w.substring(2,4)),b:P(w.substring(4,6))}}function O(E){var w=b(E,"origin",Object);return w.x=b(w,"x",Number),w.y=b(w,"y",Number),w}function W(E){E.width=document.documentElement.clientWidth,E.height=document.documentElement.clientHeight}function D(E){var w=E.getBoundingClientRect();E.width=w.width,E.height=w.height}function F(E){var w=document.createElement("canvas");return w.style.position="fixed",w.style.top="0px",w.style.left="0px",w.style.pointerEvents="none",w.style.zIndex=E,w}function T(E,w,I,C,M,G,U,q,ee){E.save(),E.translate(w,I),E.rotate(G),E.scale(C,M),E.arc(0,0,1,U,q,ee),E.restore()}function $(E){var w=E.angle*(Math.PI/180),I=E.spread*(Math.PI/180);return{x:E.x,y:E.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:E.startVelocity*.5+Math.random()*E.startVelocity,angle2D:-w+(.5*I-Math.random()*I),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:E.color,shape:E.shape,tick:0,totalTicks:E.ticks,decay:E.decay,drift:E.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:E.gravity*3,ovalScalar:.6,scalar:E.scalar,flat:E.flat}}function K(E,w){w.x+=Math.cos(w.angle2D)*w.velocity+w.drift,w.y+=Math.sin(w.angle2D)*w.velocity+w.gravity,w.velocity*=w.decay,w.flat?(w.wobble=0,w.wobbleX=w.x+10*w.scalar,w.wobbleY=w.y+10*w.scalar,w.tiltSin=0,w.tiltCos=0,w.random=1):(w.wobble+=w.wobbleSpeed,w.wobbleX=w.x+10*w.scalar*Math.cos(w.wobble),w.wobbleY=w.y+10*w.scalar*Math.sin(w.wobble),w.tiltAngle+=.1,w.tiltSin=Math.sin(w.tiltAngle),w.tiltCos=Math.cos(w.tiltAngle),w.random=Math.random()+2);var I=w.tick++/w.totalTicks,C=w.x+w.random*w.tiltCos,M=w.y+w.random*w.tiltSin,G=w.wobbleX+w.random*w.tiltCos,U=w.wobbleY+w.random*w.tiltSin;if(E.fillStyle="rgba("+w.color.r+", "+w.color.g+", "+w.color.b+", "+(1-I)+")",E.beginPath(),o&&w.shape.type==="path"&&typeof w.shape.path=="string"&&Array.isArray(w.shape.matrix))E.fill(be(w.shape.path,w.shape.matrix,w.x,w.y,Math.abs(G-C)*.1,Math.abs(U-M)*.1,Math.PI/10*w.wobble));else if(w.shape.type==="bitmap"){var q=Math.PI/10*w.wobble,ee=Math.abs(G-C)*.1,ie=Math.abs(U-M)*.1,H=w.shape.bitmap.width*w.scalar,se=w.shape.bitmap.height*w.scalar,de=new DOMMatrix([Math.cos(q)*ee,Math.sin(q)*ee,-Math.sin(q)*ie,Math.cos(q)*ie,w.x,w.y]);de.multiplySelf(new DOMMatrix(w.shape.matrix));var fe=E.createPattern(h.transform(w.shape.bitmap),"no-repeat");fe.setTransform(de),E.globalAlpha=1-I,E.fillStyle=fe,E.fillRect(w.x-H/2,w.y-se/2,H,se),E.globalAlpha=1}else if(w.shape==="circle")E.ellipse?E.ellipse(w.x,w.y,Math.abs(G-C)*w.ovalScalar,Math.abs(U-M)*w.ovalScalar,Math.PI/10*w.wobble,0,2*Math.PI):T(E,w.x,w.y,Math.abs(G-C)*w.ovalScalar,Math.abs(U-M)*w.ovalScalar,Math.PI/10*w.wobble,0,2*Math.PI);else if(w.shape==="star")for(var k=Math.PI/2*3,ne=4*w.scalar,Se=8*w.scalar,Le=w.x,Z=w.y,De=5,Be=Math.PI/De;De--;)Le=w.x+Math.cos(k)*Se,Z=w.y+Math.sin(k)*Se,E.lineTo(Le,Z),k+=Be,Le=w.x+Math.cos(k)*ne,Z=w.y+Math.sin(k)*ne,E.lineTo(Le,Z),k+=Be;else E.moveTo(Math.floor(w.x),Math.floor(w.y)),E.lineTo(Math.floor(w.wobbleX),Math.floor(M)),E.lineTo(Math.floor(G),Math.floor(U)),E.lineTo(Math.floor(C),Math.floor(w.wobbleY));return E.closePath(),E.fill(),w.tick<w.totalTicks}function V(E,w,I,C,M){var G=w.slice(),U=E.getContext("2d"),q,ee,ie=d(function(H){function se(){q=ee=null,U.clearRect(0,0,C.width,C.height),h.clear(),M(),H()}function de(){a&&!(C.width===r.width&&C.height===r.height)&&(C.width=E.width=r.width,C.height=E.height=r.height),!C.width&&!C.height&&(I(E),C.width=E.width,C.height=E.height),U.clearRect(0,0,C.width,C.height),G=G.filter(function(fe){return K(U,fe)}),G.length?q=m.frame(de):se()}q=m.frame(de),ee=se});return{addFettis:function(H){return G=G.concat(H),ie},canvas:E,promise:ie,reset:function(){q&&m.cancel(q),ee&&ee()}}}function Y(E,w){var I=!E,C=!!b(w||{},"resize"),M=!1,G=b(w,"disableForReducedMotion",Boolean),U=i&&!!b(w||{},"useWorker"),q=U?y():null,ee=I?W:D,ie=E&&q?!!E.__confetti_initialized:!1,H=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,se;function de(k,ne,Se){for(var Le=b(k,"particleCount",v),Z=b(k,"angle",Number),De=b(k,"spread",Number),Be=b(k,"startVelocity",Number),zs=b(k,"decay",Number),$s=b(k,"gravity",Number),Vs=b(k,"drift",Number),hs=b(k,"colors",z),Ks=b(k,"ticks",Number),ms=b(k,"shapes"),Hs=b(k,"scalar"),Qs=!!b(k,"flat"),Mt=O(k),ht=Le,Ze=[],fs=E.width*Mt.x,xs=E.height*Mt.y;ht--;)Ze.push($({x:fs,y:xs,angle:Z,spread:De,startVelocity:Be,color:hs[ht%hs.length],shape:ms[S(0,ms.length)],ticks:Ks,decay:zs,gravity:$s,drift:Vs,scalar:Hs,flat:Qs}));return se?se.addFettis(Ze):(se=V(E,Ze,ee,ne,Se),se.promise)}function fe(k){var ne=G||b(k,"disableForReducedMotion",Boolean),Se=b(k,"zIndex",Number);if(ne&&H)return d(function(Be){Be()});I&&se?E=se.canvas:I&&!E&&(E=F(Se),document.body.appendChild(E)),C&&!ie&&ee(E);var Le={width:E.width,height:E.height};q&&!ie&&q.init(E),ie=!0,q&&(E.__confetti_initialized=!0);function Z(){if(q){var Be={getBoundingClientRect:function(){if(!I)return E.getBoundingClientRect()}};ee(Be),q.postMessage({resize:{width:Be.width,height:Be.height}});return}Le.width=Le.height=null}function De(){se=null,C&&(M=!1,s.removeEventListener("resize",Z)),I&&E&&(document.body.contains(E)&&document.body.removeChild(E),E=null,ie=!1)}return C&&!M&&(M=!0,s.addEventListener("resize",Z,!1)),q?q.fire(k,Le,De):de(k,Le,De)}return fe.reset=function(){q&&q.reset(),se&&se.reset()},fe}var L;function me(){return L||(L=Y(null,{useWorker:!0,resize:!0})),L}function be(E,w,I,C,M,G,U){var q=new Path2D(E),ee=new Path2D;ee.addPath(q,new DOMMatrix(w));var ie=new Path2D;return ie.addPath(ee,new DOMMatrix([Math.cos(U)*M,Math.sin(U)*M,-Math.sin(U)*G,Math.cos(U)*G,I,C])),ie}function Ae(E){if(!o)throw new Error("path confetti are not supported in this browser");var w,I;typeof E=="string"?w=E:(w=E.path,I=E.matrix);var C=new Path2D(w),M=document.createElement("canvas"),G=M.getContext("2d");if(!I){for(var U=1e3,q=U,ee=U,ie=0,H=0,se,de,fe=0;fe<U;fe+=2)for(var k=0;k<U;k+=2)G.isPointInPath(C,fe,k,"nonzero")&&(q=Math.min(q,fe),ee=Math.min(ee,k),ie=Math.max(ie,fe),H=Math.max(H,k));se=ie-q,de=H-ee;var ne=10,Se=Math.min(ne/se,ne/de);I=[Se,0,0,Se,-Math.round(se/2+q)*Se,-Math.round(de/2+ee)*Se]}return{type:"path",path:w,matrix:I}}function ye(E){var w,I=1,C="#000000",M='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof E=="string"?w=E:(w=E.text,I="scalar"in E?E.scalar:I,M="fontFamily"in E?E.fontFamily:M,C="color"in E?E.color:C);var G=10*I,U=""+G+"px "+M,q=new OffscreenCanvas(G,G),ee=q.getContext("2d");ee.font=U;var ie=ee.measureText(w),H=Math.ceil(ie.actualBoundingBoxRight+ie.actualBoundingBoxLeft),se=Math.ceil(ie.actualBoundingBoxAscent+ie.actualBoundingBoxDescent),de=2,fe=ie.actualBoundingBoxLeft+de,k=ie.actualBoundingBoxAscent+de;H+=de+de,se+=de+de,q=new OffscreenCanvas(H,se),ee=q.getContext("2d"),ee.font=U,ee.fillStyle=C,ee.fillText(w,fe,k);var ne=1/I;return{type:"bitmap",bitmap:q.transferToImageBitmap(),matrix:[ne,0,0,ne,-H*ne/2,-se*ne/2]}}n.exports=function(){return me().apply(this,arguments)},n.exports.reset=function(){me().reset()},n.exports.create=Y,n.exports.shapeFromPath=Ae,n.exports.shapeFromText=ye})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),wn,!1);const Mi=wn.exports;wn.exports.create;const Ri={particleCount:350,spread:120,origin:{y:.6},angle:90},Gi={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Ft=e=>{let s=Gi[e];s||(s={});const n={...Ri,...s};Mi(n)},Ui=()=>{const[e]=Q.useTheme(),{mutate:s,isPending:n}=bn(),{mutateAsync:a,isPending:r}=fa(),i=()=>{a({settings:{theme:e}})},o=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{Ft("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"})]})},Bt=()=>{const e=X(),s=re();return R.useQuery({queryKey:[_.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Fi=e=>{const s=X(),n=re(),a=Ye();return R.useQuery({queryKey:[_.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:_.GET_WEBSITE_PAGES,data:{lang:e}})||[];return g.keyBy(g.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})};function qt(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=ge.atom(null),qi=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}=qi(e);return s};function zi(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 $i=e=>e&&ct(e),Mn=(e,s)=>{const n=ct(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function Nn({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:o}){const[l,u]=x.useState(e),[d,h]=x.useState(null);x.useEffect(()=>{u(e)},[e]);const m=y=>{const p=y.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),f=(p.match(/\./g)||[]).length,b=f<=1;f>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(b),u(p),s(p)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"mb-1 flex items-center",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent: ",t.jsx("span",{className:"font-mono text-gray-900",children:$i(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:l,onChange:m,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"mt-1 text-xs text-red-500",children:d})]}),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 Ta=({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:le.LANGUAGE}),t.jsxs("select",{value:e?"":s,disabled:e||!n.length,onChange:l=>{const u=l.target.value;r(u),!e&&(g.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?le.CHOOSE_LANGUAGE:le.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(l=>t.jsx("option",{value:l,children:Ne[l]||l},l))]})]}),ka=({lang:e,name:s,setName:n,parentHasSelectedLanguagePage:a})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"name",children:le.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?le.ENTER_PAGE_NAME:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),Vi=({dynamic:e,isNonSlugPageType:s,isRootPage:n,lang:a,useLanguagePrefix:r,setUseLanguagePrefix:i,isHomePage:o,parentSlug:l,parentHasSelectedLanguagePage:u,slug:d,setSlug:h,setIsSlugValid:m,getSlug:y})=>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:j=>i(j.target.checked),className:"rounded border-gray-300"}),t.jsxs(c.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",a]}),") as slug prefix"]})]}),t.jsx(c.Label,{htmlFor:"slug",children:le.SLUG}),e?t.jsx(c.Alert,{variant:"default",className:"p-2 text-xs font-medium italic text-muted-foreground",children:"This page will use dynamic slug as defined in primary page"}):t.jsx(Nn,{disabled:!a||!u,value:d,onChange:h,placeholder:a?o&&r?"Leave empty for home page":le.ENTER_PAGE_SLUG:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:l,onValidationChange:m,fullSlug:y()})]}),Pa=({parentHasSelectedLanguagePage:e,name:s,lang:n,slug:a,edit:r,id:i,primaryPageObject:o,pages:l,isNonSlugPageType:u,isHomePage:d,useLanguagePrefix:h,isSlugValid:m,isPending:y})=>{const j=y||!s||!n||l.some(p=>(r?p.id!==i:!0)&&p.parent===(o==null?void 0:o.id)&&p.lang===n)||!u&&!(d&&h)&&(!m||!a);return t.jsx(c.DialogFooter,{children:e?t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{type:"submit",disabled:j&&!o.dynamic,children:y?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?le.UPDATING:le.ADDING]}):r?le.UPDATE:le.ADD_NEW_LANGUAGE}),l.some(p=>(r?p.id!==i:!0)&&p.parent===(o==null?void 0:o.id)&&p.lang===n)&&t.jsx("p",{className:"mt-2 text-xs text-red-500",children:"A page for this language already exists."})]}):n&&t.jsx(c.Alert,{variant:"destructive",children:t.jsxs("p",{className:"mx-auto w-5/6 text-center",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:Ne[n]})," page in the parent to add here."]})})})},Ki=({onSubmit:e,edit:s,lang:n,languages:a,name:r,setLang:i,setName:o,primaryPageObject:l,parentHasSelectedLanguagePage:u,id:d,pages:h,isNonSlugPageType:m,isHomePage:y,useLanguagePrefix:j,slug:p,isSlugValid:f,isPending:b})=>t.jsxs("form",{onSubmit:e,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(Ta,{edit:s,lang:n,languages:a,name:r,setLang:i,setName:o,primaryPageObject:l}),t.jsx(ka,{lang:n,name:r,setName:o,parentHasSelectedLanguagePage:u})]}),t.jsx(Pa,{parentHasSelectedLanguagePage:u,name:r,lang:n,slug:p,edit:s,id:d,primaryPageObject:l,pages:h,isNonSlugPageType:m,isHomePage:y,useLanguagePrefix:j,isSlugValid:f,isPending:b})]}),Hi=({loading:e,onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u,parentHasSelectedLanguagePage:d,isNonSlugPageType:h,isRootPage:m,useLanguagePrefix:y,setUseLanguagePrefix:j,isHomePage:p,parentSlug:f,slug:b,setSlug:v,isSlugValid:S,setIsSlugValid:P,getSlug:z,isPending:B,id:O,pages:W})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(N.Loader,{className:"animate-spin"})}):h?t.jsx(Ki,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u,parentHasSelectedLanguagePage:d,id:O,pages:W,isNonSlugPageType:h,isHomePage:p,useLanguagePrefix:y,slug:b,isSlugValid:S,isPending:B}):t.jsxs("form",{onSubmit:s,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(Ta,{edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u}),t.jsx(ka,{lang:a,name:i,setName:l,parentHasSelectedLanguagePage:d}),t.jsx(Vi,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:h,isRootPage:m,lang:a,useLanguagePrefix:y,setUseLanguagePrefix:j,isHomePage:p,parentSlug:f,parentHasSelectedLanguagePage:d,slug:b,setSlug:v,isSlugValid:S,setIsSlugValid:P,getSlug:z})]}),t.jsx(Pa,{parentHasSelectedLanguagePage:d,name:i,lang:a,slug:b,edit:n,id:O,primaryPageObject:u,pages:W,isNonSlugPageType:h,isHomePage:p,useLanguagePrefix:y,isSlugValid:S,isPending:B})]}),Qi=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:o=[]}=Bt(),l=x.useMemo(()=>o.find(H=>H.id===a),[o,a]),[u,d]=x.useState(""),[h,m]=x.useState(""),[y,j]=x.useState(""),[p,f]=x.useState(!0),[b,v]=x.useState(!0),{mutate:S,isPending:P}=Aa(),{mutate:z,isPending:B}=vn(),O=P||B,{data:W,isFetching:D}=Ve(),F=Ye(),{data:T,isFetching:$}=Re(a),{data:K=[],isFetching:V}=Re(l==null?void 0:l.parent),{data:Y=[],isFetching:L}=ke(),{setSelectedLang:me}=Q.useLanguages(),[,be]=Ie(),[,Ae]=Q.useSidebarActivePanel(),ye=D||$||V||L,E=x.useMemo(()=>g.filter(W==null?void 0:W.languages,H=>!g.find(T,{lang:H})),[W,T]),w=x.useMemo(()=>Y.find(H=>H.key===(l==null?void 0:l.pageType)),[Y,l==null?void 0:l.pageType]),I=!(w!=null&&w.hasSlug),C=(l==null?void 0:l.slug)==="/";x.useEffect(()=>{if(!r&&l&&i&&(m(i),d(`${l.name} - ${Ne[i]}`)),!r||!l)return;const H=T==null?void 0:T.find(k=>k.id===e);if(!H)return;d(H.name),m(H.lang);const se=H.slug||"",{initSlug:de,prefix:fe}=zi(se,l);j(de),v(fe)},[r,e,T,l,i]),x.useEffect(()=>{if(i)m(i);else if((E==null?void 0:E.length)===1&&!r){const H=E[0];if(!H||!Ne[H])return;m(H),(!u||u===(l==null?void 0:l.name))&&d(`${l==null?void 0:l.name} - ${Ne[H]}`)}},[i,E,r,u,l]);const{parentSlug:M,isRootPage:G}=x.useMemo(()=>{if(C||!h)return{parentSlug:void 0,isRootPage:!(l!=null&&l.parent)};if(!(l!=null&&l.parent))return{parentSlug:b?`/${h}`:void 0,isRootPage:!0};const H=K==null?void 0:K.find(se=>se.lang===h);return{parentSlug:H==null?void 0:H.slug,isRootPage:!1}},[l==null?void 0:l.parent,K,b,h,C]),U=x.useMemo(()=>G?!0:!!(K!=null&&K.some(H=>(H==null?void 0:H.lang)===h)),[h,K,G]),q=()=>{let H="";return G?H=`/${b?[h,y].filter(Boolean).join("/"):y}`:H=`${ct(M)}/${y}`,H.replace(/\/{2,}/g,"/").replace(/\/$/,"")},ee=H=>{const se=new URLSearchParams(window.location.search);F&&H===F?se.delete("lang"):se.set("lang",H),be(se),window.dispatchEvent(new PopStateEvent("popstate"))},ie=H=>{H.preventDefault();const se={name:u,lang:h,primaryPage:l==null?void 0:l.id,slug:I?"":q(),pageType:l==null?void 0:l.pageType,...r&&{id:e}},de=()=>{!r&&h&&(me(h),ee(h)),Ae("outline"),n()};r?z(se,{onSuccess:de}):S(se,{onSuccess:de})};return t.jsx(c.Dialog,{open:s,onOpenChange:n,children:t.jsxs(c.DialogContent,{className:"text-slate-600 sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:r?le.EDIT_LANGUAGE:le.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:le.ENTER_LANGUAGE_DETAILS})]}),t.jsx(Hi,{id:e,pages:o,loading:ye,onSubmit:ie,edit:r,lang:h,languages:E,name:u,setLang:m,setName:d,primaryPageObject:l,parentHasSelectedLanguagePage:U,isNonSlugPageType:I,isRootPage:G,useLanguagePrefix:b,setUseLanguagePrefix:v,isHomePage:C,parentSlug:M,slug:y,setSlug:j,isSlugValid:p,setIsSlugValid:f,getSlug:q,isPending:O})]})})},Wi=ua("expandedPagesState",[]),Sn=e=>g.flatMap(e,s=>[s,...s.children?Sn(s.children):[]]),Ji=(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)||[]},Ia=(e,s)=>{if(!s)return[];const n=Sn(e),a=g.find(n,r=>r.id===s);if(a){if(a.parent)return[...Ia(e,a.parent),s];const r=Ji(e,s);if(!g.isEmpty(r))return r}return[s]},Yi=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&&!g.isEmpty(i.children)&&n(i.children,o)})};return n(e),Array.from(s)},Rs=e=>{const[s,n]=ge.useAtom(Wi),a=e?g.includes(s,e):!1,r=x.useCallback(()=>{n(d=>a?g.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=x.useCallback((d,h)=>{if(!h||g.isEmpty(d))return;const m=Sn(d),y=Ia(m,h);if(!Array.isArray(y)||g.isEmpty(y))return;const j=y.slice(0,-1);g.isEmpty(j)||n(p=>g.uniq([...p,...j]))},[n]),o=x.useCallback(d=>{if(g.isEmpty(d))return;const h=Yi(d);g.isEmpty(h)||n(m=>g.union(m,h))},[n]),l=x.useCallback(d=>{if(g.isEmpty(d))return;const h=g.flatMap(d,m=>{const y=j=>[j.id,...j.children?g.flatMap(j.children,y):[]];return y(m)});n(h)},[n]),u=x.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:o,setExpandedPages:n,expandAll:l,collapseAll:u}},Rn=(e,s)=>!e||!Array.isArray(e)?[]:g.isEmpty(s)?e:g.compact(g.filter(e,n=>{const a=g.toLower(s);return g.includes(g.toLower((n==null?void 0:n.name)||""),a)||g.includes(g.toLower((n==null?void 0:n.slug)||""),a)})),Xi=(e,s)=>{const n=new Set,a=g.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])},nn=(e,s,n)=>g.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?nn(a.children,s,n):[]};const r=a.children&&a.children.some(i=>g.includes(g.toLower(i.name||""),g.toLower(s))||g.includes(g.toLower(i.slug||""),g.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?nn(a.children,s,n):[]}}),Zi=e=>{if(!e||!e.length)return[];const s={};e.forEach(a=>{s[a.id]={...a,children:[]}});const n=[];return Object.values(s).forEach(a=>{a.parent&&s[a.parent]?s[a.parent].children.push(a):n.push(a)}),n},Da=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Da(n.children):[]})),el=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=g.compact(g.filter(e,{pageType:n}))),g.isEmpty(s))r=Rn(r,s);else{const h=Rn(r,s),m=Xi(e,h);r=g.uniqBy([...h,...m],"id")}const i=Da(Zi(r)),o=nn(i,s,a),l=g.filter(o,h=>a(h.pageType)).sort((h,m)=>(h.name||"").localeCompare(m.name||"")),u=g.filter(o,h=>!a(h.pageType));let d=[];if(n==="all"){const h=g.keyBy(u,"pageType");d=Object.values(g.mapValues(h,(m,y)=>({...m,id:y,name:g.startCase(y),isPartialGroup:!0,children:o.filter(j=>j.pageType===y)})))}else d=u.sort((h,m)=>(h.name||"").localeCompare(m.name||""));return[...l,...d]},tl=({selectedPageType:e,setSelectedPageType:s})=>{const[n,a]=x.useState(""),{data:r}=ke(),i=l=>{if(!n)return!0;const u=n.toLowerCase(),d=h=>String(g.get(l,h,"")).toLowerCase().includes(u);return d("name")||d("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(N.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(N.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"}),!g.isEmpty(g.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"}),g.map([...g.filter(r,l=>l.hasSlug&&i(l))].sort((l,u)=>g.get(l,"name","").localeCompare(g.get(u,"name",""))),l=>t.jsx(c.SelectItem,{value:g.get(l,"key"),children:g.get(l,"name")},g.get(l,"key")))]}),!g.isEmpty(g.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"}),g.map([...g.filter(r,l=>!l.hasSlug&&i(l))].sort((l,u)=>g.get(l,"name","").localeCompare(g.get(u,"name",""))),l=>t.jsx(c.SelectItem,{value:g.get(l,"key"),children:g.get(l,"name")},g.get(l,"key")))]}),g.isEmpty(g.filter(r,i))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})},sl=({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(N.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"})]}),nl=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Rs(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(N.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(N.ChevronsDownUp,{})})}),t.jsx(c.TooltipContent,{children:"Collapse All"})]})]})},_a=({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(N.Star,{size:4,className:`p-0.5 ${s===a?"fill-white":"fill-black"}`}),Ne[r]||""]},r))})},Gn=()=>{const e=R.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:[_.GET_WEBSITE_PAGES]}),className:"mt-1 h-6 w-6",children:t.jsx(N.RefreshCw,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Refresh pages list"})]})},al=({pages:e,search:s,setSearch:n,languages:a,onAddPage:r,selectedLanguage:i,setSelectedLanguage:o,selectedPageType:l,setSelectedPageType:u,showUntranslatedPages:d,setShowUntranslatedPages:h})=>{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(tl,{selectedPageType:l,setSelectedPageType:u}),t.jsx(sl,{search:s,setSearch:n}),t.jsx(nl,{pages:e}),t.jsxs(c.Button,{variant:"default",onClick:r,className:"rounded px-3 font-normal",children:[t.jsx(N.Plus,{strokeWidth:2,className:"stroke-white stroke-[3]"}),t.jsx("span",{className:"font-normal text-white",children:"Add Page"})]}),!m&&t.jsx(Gn,{})]}),m?t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(_a,{languages:a,selectedLanguage:i,setSelectedLanguage:y=>{o(y),h(d&&(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:()=>h(!d),className:"h-6 rounded px-3 py-1 text-xs font-normal",children:d?t.jsx(N.FilterXIcon,{}):t.jsx(N.Filter,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Toggle Untranslated Pages"})]}),t.jsx(Gn,{})]})]}):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 La=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:o,children:l,isLanguagePage:u})=>{const{hasPermission:d}=Q.usePermissions(),{data:h}=ke(),m=x.useMemo(()=>g.find(h,{key:e.pageType}),[h,e.pageType]),y=x.useMemo(()=>!!e.isTemplate,[e.isTemplate]),j=x.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!d(ve.EDIT_PAGE)&&!d(ve.DELETE_PAGE)&&!d(ve.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:f=>f.stopPropagation(),children:l}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[d(ve.ADD_PAGE)&&!u&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:f=>{f.stopPropagation(),s(e)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),d(ve.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:f=>{f.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&d(ve.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:f=>{f.stopPropagation(),a(e)},children:[t.jsx(N.Power,{className:"size-3"}),le.UNPUBLISH]}),d(ve.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:f=>{f.stopPropagation(),r(e)},children:[t.jsx(N.Trash,{className:"size-3"}),le.DELETE]}),d(ve.MARK_AS_TEMPLATE)&&j&&!u&&t.jsx(t.Fragment,{children:y?t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:f=>{f.stopPropagation(),o(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),le.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:f=>{f.stopPropagation(),i(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),le.MARK_AS_TEMPLATE]})})]})]})},rl=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Rs(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(N.ChevronRight,{size:12,className:`stroke-[4] transition-transform duration-200 ${s?"rotate-90":""}`})})},il=({page:e,pageType:s})=>t.jsx("div",{className:"flex h-full items-center justify-center gap-x-1",children:e.dynamic?t.jsx(N.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(N.File,{size:12,className:"stroke-[1] text-slate-500"}):t.jsx(N.Globe,{size:12,className:"stroke-[1] text-slate-500"})}),ll=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),ol=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i,showUntranslatedPages:o})=>{const[l]=wa(),u=Ye(),d=n===e.id,h=!!e.isTemplate,m=x.useMemo(()=>g.find(s,{key:e.pageType}),[s,e.pageType]),y=l==null?void 0:l[e.id],{data:j}=Je(y),p=j?j==null?void 0:j.name:null;let f=g.get(r,e==null?void 0:e.id);f=g.get(f,"lang")===i?f:null;const b=i===u||!!f,v=(f==null?void 0:f.name)||(e==null?void 0:e.name)||"No name";let S=(f==null?void 0:f.slug)||(e==null?void 0:e.slug)||"";const P=S+(e!=null&&e.dynamic?`/${m==null?void 0:m.dynamicSlug}`:"")+(e!=null&&e.dynamicSlugCustom?`${e.dynamicSlugCustom}`:"");if(S.startsWith("/")&&!o){const B=S.split("/").pop();S=S.endsWith(B)&&e.dynamic?"":`/${B}`}const z=x.useMemo(()=>{const B="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]",O=`${d?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return b?`${B} ${O} ${p?"opacity-60":""}`:`${B} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[b,d,p]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&b&&a("select",e==null?void 0:e.id),className:z,children:[t.jsx(rl,{page:e}),!e.isPartialGroup&&t.jsx(ll,{isOnline:f?f.online:e.online}),t.jsx(il,{page:e,pageType:m}),t.jsx(ot,{content:v,side:"top",showTooltip:v.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:v})}),(S||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:[S,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]})]})}),h&&t.jsx(ot,{content:"Template",side:"top",children:t.jsx("span",{className:"text-blue-500",children:t.jsx(N.NotepadText,{size:16})})}),!e.isPartialGroup&&b&&!p?t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(La,{isLanguagePage:!!f,page:f||e,setDuplicatePage:B=>a("duplicate",B),setAddEditPage:B=>a("edit",f||B),setUnpublishPage:B=>a("unpublish",B),setDeletePage:B=>a("delete",f||B),setMarkAsTemplate:B=>a("markAsTemplate",B),setUnmarkAsTemplate:B=>a("unmarkAsTemplate",B),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(N.MoreHorizontal,{className:"h-4 w-4",onClick:B=>B.stopPropagation()})})})}):p?t.jsx("span",{className:"duration absolute right-1.5 top-1/2 -translate-y-1/2 text-xs text-gray-500",children:t.jsx(N.Lock,{className:"h-3.5 w-3.5 fill-red-200 text-red-500"})}):null]}),t.jsx(t.Fragment,{children:p&&t.jsxs("button",{className:"absolute right-0 top-0 flex h-full items-center gap-x-1 rounded bg-red-50 px-2 py-0.5 text-xs font-light text-red-500 opacity-0 group-hover:opacity-100",children:[t.jsx(N.Edit,{size:12,className:"stroke-[3]"})," ",t.jsx("span",{className:"font-medium",children:p})," is editing this page"]})}),t.jsx(t.Fragment,{children:!b&&!e.isPartialGroup&&!p&&t.jsxs("button",{onClick:B=>{B.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(N.Plus,{size:12,className:"stroke-[3]"})," ",t.jsxs("span",{className:"text-[10px]",children:["Add ",g.get(Ne,i)," Page"]})]})})]})},Ba=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l})=>{const{expandedPages:u}=Rs();return t.jsx("div",{className:"space-y-0.5",style:{paddingLeft:`${s*10}px`},children:e.map(d=>t.jsxs(t.Fragment,{children:[t.jsx(ol,{page:d,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l}),d.children&&d.children.length>0&&(u==null?void 0:u.includes(d.id))&&t.jsx(Ba,{pages:d.children,tier:s+1,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l})]},d.id))})};function cl({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,o]=x.useState(null),l=x.useRef(null),[u,d]=x.useState(a+e);x.useEffect(()=>{d(a+e)},[e,a]);const h=j=>{const p=j.target.value;if(!p.startsWith(a)){const z=p.replace(a,""),B=a+z;d(B),s(z);return}const b=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),v=(b.match(/\./g)||[]).length,S=v<=1;v>1?o("Invalid slug. Only one dot (.) is allowed in the slug"):o(null),r&&r(S);const P=a+b;d(P),s(b)},m=()=>{if(l.current){const j=l.current;setTimeout(()=>{const p=a.length;j.setSelectionRange(p,p)},0)}},y=j=>{const p=j.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const b=a.length;p.setSelectionRange(b,b)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:l,value:u,onChange:h,onFocus:m,onClick:y,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})},Js=(...e)=>e.filter(Boolean).join(" ");function ul({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage",currentPage:i}){const[o,l]=x.useState(!1),[u,d]=x.useState(""),h=Q.useChaiFeatureFlag("enable-add-page-dropdown");h||(a="w-full rounded-md border border-gray-300 px-3 py-2");const m=x.useMemo(()=>!e||e.length===0?[]:e.filter(S=>!g.isEmpty(S.slug)).filter(S=>S.slug!=="/").sort((S,P)=>S.slug.localeCompare(P.slug)),[e]),y=x.useMemo(()=>{if(!u.trim())return m;const v=u.toLowerCase();return m.filter(S=>S.name.toLowerCase().includes(v)||S.slug.toLowerCase().includes(v))},[m,u]),j=v=>Math.max(0,(v.match(/\//g)||[]).length-1),p=v=>"    ".repeat(v),f=v=>{if(v==="/")return"/";const S=v.split("/").filter(Boolean);if(S.length<=1){const P=S[0]||"";return`/${ct(P)}`}return`/${ct(S[S.length-1])}`},b=()=>{if(!s||s==="none")return"None";const v=m.find(S=>S.id===s);return v?`${v.name} (${f(v.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),h?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:Js("w-full justify-between",a),"data-testid":"parent-page-selector",children:[b(),t.jsx(N.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(N.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:v=>d(v.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),d("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(N.Check,{className:Js("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),y.map(v=>{const S=p(j(v.slug)),P=f(v.slug),z=t.jsxs("span",{className:"flex items-center text-sm",children:[S,v.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",P,")"]})]});return t.jsxs(c.CommandItem,{value:v.id,onSelect:()=>{n(v.id),l(!1),d("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:z}),t.jsx(N.Check,{className:Js("mr-2 h-4 w-4 shrink-0",s===v.id?"opacity-100":"opacity-0")})]},v.id)})]})]})]})})]}):t.jsxs("select",{id:r,value:s||"none",onChange:v=>n(v.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),m.map(v=>{const S=j(v.slug),P=S>0?p(S):"",z=f(v.slug);return(i==null?void 0:i.id)===v.id||v.slug.startsWith(i==null?void 0:i.slug)?null:t.jsxs("option",{value:v.id,children:[P,v.name," (",z,")"]},v.id)})]})]})}const dl=(...e)=>e.filter(Boolean).join(" "),hl=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=x.useState(""),[o,l]=x.useState(!1),[u,d]=x.useState(""),h=Q.useChaiFeatureFlag("enable-add-page-dropdown");if(x.useEffect(()=>{if(s){const f=e.find(b=>b.id===s);i((f==null?void 0:f.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(f=>{const b=f.libraryName;m[b]||(m[b]=[]),m[b].push(f)});const y=Object.entries(m).reduce((f,[b,v])=>{const S=v.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())||b.toLowerCase().includes(u.toLowerCase()));return S.length>0&&(f[b]=S),f},{}),j=e.find(f=>f.id===s),p=j?g.startCase(j.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[h?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:[p,t.jsx(N.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(N.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:f=>d(f.target.value)})]})}),t.jsxs(Es,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(y).map(([f,b])=>t.jsx(c.CommandGroup,{heading:f,children:b.map(v=>t.jsxs(c.CommandItem,{value:v.id,onSelect:()=>{n(v.id),l(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[g.startCase(v.name),t.jsx(N.Check,{className:dl("mr-2 h-4 w-4",s===v.id?"opacity-100":"opacity-0")})]},v.id))},f))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:f=>n(f.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(m).map(([f,b])=>t.jsx("optgroup",{label:f,children:b.map(v=>t.jsx("option",{value:v.id,children:g.startCase(v.name)},v.id))},f))]}),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"})]})]})},ml=()=>{const e=re(),s=X();return R.useQuery({queryKey:[_.GET_LIBRARIES],queryFn:async()=>await s(e,{action:_.GET_LIBRARIES})||[]})},fl=e=>{const s=re(),n=X();return R.useQuery({queryKey:[_.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:_.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?g.filter(a,{pageType:e}):a)||[]}})},xl=e=>{const{data:s=[],isLoading:n}=fl(e),{data:a=[],isLoading:r}=ml(),i=x.useMemo(()=>n||r?[]:s.map(l=>{const u=g.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=x.useMemo(()=>g.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:o,isLoading:n||r}},En=()=>{const[,e]=Ie();return x.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},zt=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:"",metaOther:""},jsonLD:{},metaOther:{}};e!=null&&e.defaultSeo&&(g.has(e.defaultSeo,s)&&g.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};e!=null&&e.defaultJSONLD&&(g.has(e.defaultJSONLD,s)&&g.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],g.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,g.set(n,"seo.jsonLD",JSON.stringify(a))));let r={};return e!=null&&e.defaultMetaTags&&(g.has(e.defaultMetaTags,s)&&g.isObject(e.defaultMetaTags[s])?(r=e.defaultMetaTags[s],g.set(n,"seo.metaOther",JSON.stringify(r))):(r=e.defaultMetaTags,g.set(n,"seo.metaOther",JSON.stringify(r)))),{seo:n.seo,jsonLD:n.jsonLD,metaOther:r}},at=(...e)=>e.filter(Boolean).join(" ");function gl({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var fs,xs;const r=En(),i=!!(e!=null&&e.id),{data:o}=Bt(),{mutate:l,isPending:u}=Aa(),{mutate:d,isPending:h}=vn(),[m,y]=x.useState(null),[j,p]=x.useState(!0),[f,b]=x.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:v}=Q.usePermissions(),S=v(ve.CHANGE_PAGE_TYPE),[P,z]=x.useState(!1),[B,O]=x.useState(""),{selectedLang:W,fallbackLang:D}=Q.useLanguages(),F=W||D,[T,$]=x.useState(""),[K,V]=x.useState(!1),Y=x.useMemo(()=>{const A=s.find(oe=>oe.key===f);return(A==null?void 0:A.hasSlug)===!1},[f,s]),[L,me]=x.useState((e==null?void 0:e.parent)??""),[be,Ae]=x.useState((e==null?void 0:e.name)??""),[ye,E]=x.useState((e==null?void 0:e.dynamic)??!1),[w,I]=x.useState(ye?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[C,M]=x.useState((e==null?void 0:e.dynamicSlugCustom)??""),[G,U]=x.useState(!0),[q,ee]=x.useState(!1),[ie,H]=x.useState(""),{data:se,isLoading:de}=xl(f),fe=u||h,k=Q.useChaiFeatureFlag("enable-add-page-dropdown"),ne=x.useMemo(()=>!i||!(e!=null&&e.id)||!o?null:o.find(A=>A.id===e.id),[i,e==null?void 0:e.id,o]),Se=(ne==null?void 0:ne.online)||!1,Le=x.useMemo(()=>!i||!(e!=null&&e.id)||!o?!1:o.some(A=>A.parent===e.id),[i,e==null?void 0:e.id,o]),Z=s.find(A=>A.key===f),De=A=>{if(i&&f!==A){O(A),z(!0),$(""),V(!1);return}b(A),$(""),V(!1)},Be=()=>{b(B),z(!1),E(!1)},zs=A=>{E(A),A?I(""):M("")},$s=A=>{if(me(A),A&&A!=="none"){const oe=o==null?void 0:o.find(_e=>_e.id===A),Fe=(oe==null?void 0:oe.slug)||"";if(w.startsWith(Fe)){const _e=w.slice(Fe.length).replace(/^\/+/,"");I(_e)}else I(w.replace(/^\/+/,""))}else I(w?`${w}`:"")},Vs=A=>{H(A)},hs=()=>be.trim()?ye&&!g.isEmpty(w)?(y("Slug must be empty when using dynamic slug"),!1):ye&&!G?(y("Dynamic slug is invalid"),!1):!0:(J.toast.error("Name is required"),!1),Ks=()=>{const A={pageType:Z==null?void 0:Z.key,name:be,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:be},{onSuccess:()=>{J.toast.success((Z==null?void 0:Z.name)+" updated successfully"),n()}}):l(A,{onSuccess:oe=>{n(),r(oe.page.id,a)}})},ms=(A,oe)=>{if(!A.trim()&&!ye)return y("Child page slug is required"),!1;const Fe=ct(oe),_e=Mn(Fe,A);return Object.keys(Ne).some(gs=>_e===`/${gs}`||(_e==null?void 0:_e.startsWith(`/${gs}/`)))?(y("Slugs cannot start with a language code for primary page"),!1):!0},Hs=(A,oe)=>{const Fe=ct(oe),_e=Mn(Fe,A),Me={pageType:f,name:be,slug:_e.replace(/\/$/,""),parent:L,dynamic:ye,hasSlug:!0,template:ie||void 0,tracking:{},seo:{},jsonLD:{}};if(ye&&(Me.dynamicSlugCustom=C),i){const qe=g.pick(Me,["pageType","parent","name","slug","dynamic","dynamicSlugCustom"]);d({id:e==null?void 0:e.id,...qe},{onSuccess:()=>{J.toast.success("Page updated successfully"),n()}})}else{const qe=g.find(s,{key:f});qe!=null&&qe.trackingDefault&&(Me.tracking=qe.trackingDefault);const{seo:gs,jsonLD:Rr}=zt(qe,F);g.set(Me,"seo",gs),g.set(Me,"jsonLD",Rr),l(Me,{onSuccess:Gr=>{n(),r(Gr.page.id,a)}})}},Qs=()=>{const A={pageType:f,name:be,slug:w===""?"/":`/${w.replace(/\/$/,"")}`,template:ie||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...A},{onSuccess:()=>{J.toast.success("Page updated successfully"),n()}});else{const oe=g.find(s,{key:f});oe!=null&&oe.trackingDefault&&(A.tracking=oe.trackingDefault);const{seo:Fe,jsonLD:_e}=zt(oe,F);g.set(A,"seo",Fe),g.set(A,"jsonLD",_e),l(A,{onSuccess:Me=>{var qe;(qe=Me==null?void 0:Me.page)!=null&&qe.id&&r(Me.page.id,a),n()}})}},Mt=A=>{if(A.preventDefault(),y(null),!!hs()){if(!(Z!=null&&Z.hasSlug)){Ks();return}if(L&&L!=="none"){const oe=o==null?void 0:o.find(_e=>_e.id===L),Fe=(oe==null?void 0:oe.slug)||"";if(!ms(w,Fe))return;Hs(w,Fe)}else Qs()}},{pagesType:ht,partialsType:Ze}=x.useMemo(()=>{const A=oe=>T?oe.name.toLowerCase().includes(T.toLowerCase())||oe.key.toLowerCase().includes(T.toLowerCase()):!0;return{pagesType:s.filter(oe=>oe.hasSlug!==!1&&A(oe)),partialsType:s.filter(oe=>oe.hasSlug===!1&&A(oe))}},[s,T]);return Z!=null&&Z.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:K,onOpenChange:V,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!S,className:at("w-full justify-between",i&&!S?"cursor-not-allowed text-gray-500":""),children:[(Z==null?void 0:Z.name)||"Select page type",t.jsx(N.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(N.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:T,onChange:A=>$(A.target.value)})]})}),t.jsxs(Es,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),i?Y?t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>De(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",f===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:ht.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>De(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",f===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsxs(t.Fragment,{children:[ht.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:ht.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>De(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",f===A.key?"opacity-100":"opacity-0")})]},A.key))}),Ze.length>0&&t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>De(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",f===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:f,disabled:i&&!S,onChange:A=>De(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!S?"cursor-not-allowed text-gray-500":""}`,children:i?Y?t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.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:()=>z(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]})]}),!i&&(Z==null?void 0:Z.hasSlug)&&se.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(hl,{templates:se,selectedTemplateId:ie,onSelectTemplate:Vs,isLoading:de})]}),t.jsx(ul,{pages:o,selectedParentId:L,onChange:$s,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:be,onChange:A=>Ae(A.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(Z==null?void 0:Z.dynamicSegments)&&L&&L!=="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:ye,onChange:A=>zs(A.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ye&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(cl,{value:C,onChange:M,dynamicPattern:(Z==null?void 0:Z.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:U})})})]}),(!(Z!=null&&Z.dynamicSegments)||!ye)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Nn,{value:w,onChange:A=>{var oe;I(A),i&&A!==(((oe=e==null?void 0:e.slug)==null?void 0:oe.split("/").pop())||"")?ee(!!(Se||Le)):ee(!1)},placeholder:L&&L!=="none"?"Enter page slug":f==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:L&&L!=="none"?(xs=o==null?void 0:o.find(A=>A.id===L))==null?void 0:xs.slug:void 0,onValidationChange:p}),m&&t.jsx("p",{className:"text-xs text-red-500",children:m}),q&&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:fe||!j&&(!(Z!=null&&Z.dynamicSegments)||!ye)||ye&&!G,type:"submit",className:"w-full",children:i?fe?"Updating...":"Update page":fe?"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:K,onOpenChange:V,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!S,className:at("w-full justify-between",i&&!S?"cursor-not-allowed text-gray-500":""),children:[(Z==null?void 0:Z.name)||"Select page type",t.jsx(N.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(N.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:T,onChange:A=>$(A.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(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>{De(A.key),V(!1)},className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",f===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:f,disabled:i&&!S,onChange:A=>De(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!S?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.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:()=>z(!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(A=>A.key===f))==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:be,onChange:A=>Ae(A.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:fe,type:"submit",className:"w-full",children:i?fe?"Updating...":"Update "+(Z==null?void 0:Z.name):fe?"Creating...":"Create "+(Z==null?void 0:Z.name)})]})}const Oa=({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(gl,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function Cn({page:e,onClose:s}){const[,n]=Ie(),{mutate:a,isPending:r}=Di(),{data:i}=ke(),{setSelectedLang:o,fallbackLang:l}=Q.useLanguages(),[,u]=Q.useSidebarActivePanel(),d=()=>{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()}})},h=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)})," ",h!=null&&h.hasSlug?(h==null?void 0:h.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:g.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:d,children:r?"Deleting...":"Delete"})]})]})})}const pl=()=>{const e=re(),s=R.useQueryClient(),n=X();return R.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:[_.GET_WEBSITE_PAGES]}),J.toast.success("Page duplicated successfully")},onError:a=>{J.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Ma=({page:e,onClose:s,closePanel:n=()=>{}})=>{const{mutate:a,isPending:r}=pl(),[i,o]=x.useState(null),[l,u]=x.useState(`${e.name} (Copy)`),d=En(),h=g.isEmpty(e.slug),[m,y]=x.useState(h?"":`${e.slug.split("/").pop()}-copy`),j=h?"":g.initial(e.slug.split("/")).join("/"),[p,f]=x.useState(!1),b=v=>{if(v.preventDefault(),!l.trim()){o("Name is required");return}if(!h&&!m.trim()){o("Slug is required");return}o(null),f(!0);const S={pageId:e.id,name:l};h||(S.slug=`${j}/${m}`),a(S,{onSuccess:P=>{f(!1),s(),d(P.id,n)},onError:P=>{f(!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]}),!h&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:b,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:v=>u(v.target.value),required:!0})]}),!h&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Nn,{value:m,onChange:v=>y(v),parentSlug:j,onValidationChange:v=>{o(v?null:"Invalid slug")}})]}),i&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(N.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()||!h&&!m.trim()||r||p,children:r||p?"Duplicating...":"Duplicate"})]})]})]})})},yl=1*1024*1024,Ra=({page:e,onClose:s})=>{const[n,a]=x.useState(!1),[r,i]=x.useState(""),[o,l]=x.useState(""),[u,d]=x.useState(!1),h=x.useRef(null),m=Li(),{data:y}=ke(),j=y==null?void 0:y.find(P=>P.key===e.pageType),p=(j==null?void 0:j.name)||g.startCase(e.pageType),f=x.useCallback(P=>{var B;const z=(B=P.target.files)==null?void 0:B[0];if(z){if(z.size>yl){J.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(z.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const O=new FileReader;O.onloadend=()=>{l(O.result),d(!1)},O.readAsDataURL(z)}catch(O){console.error("Error reading file:",O),d(!1),J.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),b=()=>{l(""),h.current&&(h.current.value="")},v=()=>{var P;(P=h.current)==null||P.click()},S=()=>{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(N.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:g.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:P=>i(P.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:h,onChange:f,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:v,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(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),o&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:b,children:t.jsx(N.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:S,children:"Mark as template"})]})]})})},Ga=({page:e,onClose:s})=>{const[n,a]=x.useState(!1),r=Bi(),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"})]})]})})},Gs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=_i(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[le.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:r,children:a?le.UPDATING:le.UNPUBLISH})]})]})})},Ua=({close:e})=>{const{languages:s,setSelectedLang:n}=Q.useLanguages(),{data:a}=ke(),{data:r,isFetching:i}=Bt(),[o,l]=Ie(),{updateForSelectedPage:u,expandPagesOnSearch:d}=Rs(null),h=Ye(),m=o.get("page"),[y,j]=x.useState(""),[p,f]=x.useState(null),[b,v]=x.useState(null),[S,P]=x.useState(null),[z,B]=x.useState(null),[O,W]=x.useState(""),[D,F]=x.useState(null),[T,$]=x.useState(null),[K,V]=x.useState(h),[Y,L]=x.useState(!1),[,me]=ge.useAtom(ds),be=Y&&K!==h,{data:Ae,isFetching:ye}=Fi(K),E=x.useCallback(G=>{var U;return(U=g.find(a,{key:G}))==null?void 0:U.hasSlug},[a]),w=x.useMemo(()=>r?be?g.filter(r,G=>!(Ae!=null&&Ae[G.id])):el(r,y,O,E):[],[r,E,y,O,Ae,be]);x.useEffect(()=>{n(h)},[h,n]),x.useEffect(()=>{if(!g.isEmpty(O))return;const G=sessionStorage.getItem("pageTypeFilter")||"all";!g.isEmpty(a)&&G&&(g.find(a,{key:G})?W(G):W("all"))},[a,O]),x.useEffect(()=>{if(m&&!i&&!g.find(r,{id:m})){const U=g.find(r,{slug:"/"});if(U){const q=new URLSearchParams({page:U.id});qt(q,l)}else qt(new URLSearchParams({}),l,!0)}},[r,m,i,l]),x.useEffect(()=>{m&&!i&&!g.isEmpty(w)&&u(w,m)},[m,i,w,u]),x.useEffect(()=>{!g.isEmpty(y)&&!g.isEmpty(w)&&d(w)},[y,w,d]);const{setSelectedLang:I}=Q.useLanguages(),C=x.useCallback(G=>{const U=new URLSearchParams({page:G});K!==h?(U.set("lang",K),I(K)):I(""),qt(U,l),e()},[e,l,I,K,h]),M=(G,U)=>{var q;if(U)switch(G){case"add":v(U);break;case"select":C(U);break;case"edit":K!==h?me({edit:!0,id:U==null?void 0:U.id,primaryPage:U==null?void 0:U.primaryPage}):v(U);break;case"delete":f(U);break;case"unpublish":P(U);break;case"markAsTemplate":B(U);break;case"unmarkAsTemplate":$(U);break;case"duplicate":F(U);break;case"addLanguagePage":me({edit:!1,primaryPage:((q=U==null?void 0:U.page)==null?void 0:q.id)||"",preselectedLang:(U==null?void 0:U.language)||K});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(al,{pages:w,search:y,setSearch:j,languages:[h,...s],selectedLanguage:K,setSelectedLanguage:V,selectedPageType:O,setSelectedPageType:W,onAddPage:G=>M("add",G),showUntranslatedPages:be,setShowUntranslatedPages:L}),t.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-6 pt-2",children:i||ye?t.jsx("div",{className:"space-y-2",children:g.map([...Array(15).keys()],G=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},G))}):g.isEmpty(w)?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(N.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx(Ba,{tier:0,pages:w,pageTypes:a,currentPage:m||"",onClickAction:M,languagePages:Ae,selectedLanguage:K,showUntranslatedPages:be})})]}),b&&t.jsx(Oa,{closePanel:e,editPage:C,addEditPage:b,setAddEditPage:v}),p&&t.jsx(Cn,{page:p,onClose:()=>f(null)}),S&&t.jsx(Gs,{page:S,onClose:()=>P(null)}),z&&t.jsx(Ra,{page:z,onClose:()=>B(null)}),T&&t.jsx(Ga,{page:T,onClose:()=>$(null)}),D&&t.jsx(Ma,{page:D,onClose:()=>F(null),closePanel:e})]})},jl=()=>{const e=Ue("topLeftCorner",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:x.createElement(e,{})}):null},vl=()=>{const[e,s]=Ie(),n=e.get("page"),{data:a,isFetching:r}=Ce(),{data:i,isFetching:o}=Bt(),[l,u]=x.useState(!1),[d,h]=x.useState(!0),{savePage:m}=Q.useSavePage(),y=!!n&&!g.isEmpty(a),j=x.useMemo(()=>{if(!i||o)return!1;const v=i.find(S=>S.slug==="/");return v==null?void 0:v.id},[i,o]);x.useEffect(()=>{if(o||!j||i.some(P=>P.id===n))return;const S=new URLSearchParams({page:j});qt(S,s),!o&&i&&h(!1)},[n,o,i,j,s]);const p=!d&&!n,f=!d&&!r&&g.isEmpty(a),b=l||p||f;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(N.LogsIcon,{className:"h-4 w-4"})},"template-viewer")}),t.jsx(c.TooltipContent,{side:"right",children:t.jsx("p",{children:"Open pages manager"})})]})})}),t.jsx(c.Sheet,{open:b,onOpenChange:v=>!v&&y&&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 ${y?"":"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(N.Folder,{className:"h-4 w-4"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs font-normal text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:`${b?"h-[calc(100vh-80px)] overflow-y-auto":"h-[calc(100vh-70px)] overflow-y-auto"}`,children:t.jsx(Ua,{close:()=>u(!1)})})]})})]})},An=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=Q.useLanguages(),o=g.isEmpty(r)?n:r,[,l]=Ie(),{isLocked:u}=Ke();x.useEffect(()=>{const b=new URLSearchParams(window.location.search),v=b.get("lang");v&&(a.includes(v)?i(v):(b.delete("lang"),l(b),i("")))},[a,l,i]);const[,d]=ge.useAtom(ds),{data:h}=Ce(),{data:m}=Ve(),{data:y}=Re(),j=x.useMemo(()=>{const b=g.compact(g.map(g.get(m,"languages"),v=>{const S=g.find(y,{lang:v});return{key:v,value:g.get(Ne,v,v),isLangPageAdded:!!S}})).filter(Boolean);return[{key:n,value:g.get(Ne,n),isLangPageAdded:!0},...b]},[n,y,m]),p=b=>{if(document.querySelector('[data-panel-id="seo"]')){const S=new CustomEvent("seo-language-switch-check",{detail:{fromLang:o,toLang:b,switchHandler:()=>f(b)}});window.dispatchEvent(S);return}f(b)},f=b=>{i(b);const v=new URLSearchParams(window.location.search);b===n?v.delete("lang"):v.set("lang",b),qt(v,l)};return g.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(N.Languages,{className:"h-4 w-4"}),g.get(Ne,o,o),t.jsx(N.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(N.Languages,{className:"h-4 w-4"}),g.get(Ne,o,o),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[g.map(j.filter(b=>b.isLangPageAdded),b=>t.jsxs(c.DropdownMenuItem,{className:Q.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",b.key===o&&"!bg-gray-200 text-gray-700"),onClick:()=>p(b.key),children:[t.jsx("div",{className:"text-slate-600",children:b.value}),b.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(N.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},b.value)),e&&!g.isEmpty(j.filter(b=>!b.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{h&&d({edit:!1,primaryPage:h.id})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(N.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]})})};function bl(){const[e,s]=ge.useAtom(ds);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(jl,{}),t.jsx(vl,{}),e&&t.jsx(Qi,{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 wl(e,s){const n=re(),a=X();return R.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=>g.replace(l.uid,`${l.label}:`,"");return await a(n,{action:_.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 Nl=({version:e})=>{const s=e==null?void 0:e.item,{data:n}=Je(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")})]})]})},Un=({version:e})=>t.jsx(Nl,{version:e});function Sl(e,s,n="data.json"){const a=JSON.stringify(e,null,2),r=JSON.stringify(s,null,2),i=a.split(`
3
- `),o=r.split(`
4
- `);let l=`--- a/${n}
5
- `;l+=`+++ b/${n}
6
- `;const u=[];let d=0,h=0;for(;d<i.length||h<o.length;){const j=i[d]||"",p=o[h]||"";if(j===p)u.push(` ${j}`),d++,h++;else{let f=-1,b=-1;for(let v=d+1;v<i.length;v++)if(o[h]===i[v]){f=v;break}for(let v=h+1;v<o.length;v++)if(i[d]===o[v]){b=v;break}if(f!==-1&&(b===-1||f-d<=b-h)){for(let v=d;v<f;v++)u.push(`-${i[v]}`);d=f}else if(b!==-1){for(let v=h;v<b;v++)u.push(`+${o[v]}`);h=b}else j&&u.push(`-${j}`),p&&u.push(`+${p}`),d++,h++}}const m=i.length,y=o.length;return l+=`@@ -1,${m} +1,${y} @@
7
- `,l+=u.join(`
8
- `)+`
9
- `,l}function $t(e,s=!0,n=!1){if(g.isString(e)){const a=g.trim(e);if(g.startsWith(a,"{")||g.startsWith(a,"[")||s&&(a==="true"||a==="false"||a==="null"||/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(a)))try{const i=JSON.parse(a);return $t(i,s,n)}catch{if(n)throw new Error(`Invalid JSON string: ${a}`);return{}}return e}return g.isArray(e)?g.map(e,a=>$t(a,s,n)):g.isPlainObject(e)?g.mapValues(e,a=>$t(a,s,n)):e}const El=e=>{switch(e){case"blocks":return"Blocks";case"seo":return"SEO";case"tracking":return"Tracking";default:return e}},Cl=(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:El(o)})).filter(o=>o.key.length>0)},Al=(e,s=3)=>{const n=new Set;e.map((o,l)=>({change:o,index:l})).filter(({change:o})=>o.type!=="normal").map(({index:o})=>o).forEach(o=>{const l=Math.max(0,o-s),u=Math.min(e.length-1,o+s);for(let d=l;d<=u;d++)n.add(d)});const r=[];let i=-1;return e.forEach((o,l)=>{if(n.has(l)){if(i!==-1&&l-i>1){const u=e[i].lineNumber!=null?e[i].lineNumber+1:i+2,d=e[l].lineNumber!=null?e[l].lineNumber-1:l;r.push({content:t.jsx(c.Badge,{className:"pointer-events-none w-60 -translate-x-1/2 cursor-default border-none bg-transparent py-1 shadow-none",children:t.jsxs("span",{className:"rounded border border-border bg-muted px-3 py-1 text-xs font-light leading-none text-muted-foreground",children:["No changes from ",u," to ",d," line"]})})})}r.push(o),i=l}}),r};function Tl({open:e,compare:s,onOpenChange:n}){const a=s[0],r=s[1],[i,o]=x.useState(null),[l,u]=x.useState("split"),[d,h]=x.useState(!1),[m,y]=x.useState(!1),[j,p]=x.useState("blocks"),{data:f,isLoading:b}=wl(a,r),{leftData:v,rightData:S,options:P}=x.useMemo(()=>{var V,Y;const D=(V=f==null?void 0:f.version1)==null?void 0:V[j],F=(Y=f==null?void 0:f.version2)==null?void 0:Y[j],T=$t(D),$=$t(F),K=Cl(f==null?void 0:f.version1,f==null?void 0:f.version2);return{leftData:T,rightData:$,options:K}},[f,j]),z=x.useMemo(()=>!v||!S?"":Sl(v,S),[v,S]),B=x.useMemo(()=>{if(!z)return[];try{return Ws.parseDiff(z)}catch(D){return console.error("Failed to parse diff:",D),[]}},[z]),O=async(D,F)=>{try{await navigator.clipboard.writeText(JSON.stringify(D,null,2)),o(F),setTimeout(()=>o(null),2e3)}catch(T){console.error("Failed to copy:",T)}},W=D=>JSON.stringify(D,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(N.FileJson,{className:"h-5 w-5"}),"Compare","",P.map(D=>t.jsx("div",{className:`cursor-pointer rounded-full border px-2.5 py-1 text-xs leading-none ${j===D.key?"border-blue-500 bg-blue-500 text-white":"border-gray-600 text-gray-600 hover:bg-gray-200"}`,onClick:()=>p(D.key),children:D.label},D.key))]}),t.jsx("div",{className:"flex flex-1 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:d,checked:d?!0:l==="split",onCheckedChange:D=>u(D?"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:d,onCheckedChange:D=>h(D)}),t.jsx("label",{className:"text-sm",children:"Show Raw Data"})]}),t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[t.jsx(c.Switch,{checked:m,onCheckedChange:D=>y(D)}),t.jsx("label",{className:"text-sm",children:"Hide Common Data"})]})]})})]})}),b?t.jsx("div",{className:"flex h-full w-full items-center justify-center",children:t.jsx(N.Loader,{className:"h-6 w-6 animate-spin text-primary"})}):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(Un,{version:a})}),t.jsx("div",{className:"flex w-1/2 items-center justify-center gap-2",children:t.jsx(Un,{version:r})})]}),d?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:()=>O(v,"left"),children:[i==="left"?t.jsx(N.Check,{className:"text-green-500"}):t.jsx(N.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(v)})})]}),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:()=>O(S,"right"),children:[i==="right"?t.jsx(N.Check,{className:"text-green-500"}):t.jsx(N.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(S)})})]})]}):t.jsx(c.ScrollArea,{className:"h-full overflow-y-auto rounded-lg border bg-slate-50 text-xs dark:bg-slate-900",children:B.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(N.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:B.map((D,F)=>t.jsx("div",{className:"relative mb-4",children:t.jsx(Ws.Diff,{viewType:l,diffType:D.type,hunks:D.hunks,className:"rounded-lg text-xs",children:T=>T.map(($,K)=>{const V=m?Al($.changes):$.changes;return(V==null?void 0:V.length)===0?t.jsx("div",{className:"absolute h-full w-full border-l pt-64 text-center font-sans text-sm",children:t.jsx("span",{children:"No difference found"})}):t.jsx(Ws.Hunk,{hunk:{...$,changes:V}},K)})},m?"hide-common-data":"show-common-data")},F))})})]})})]})})}const Oe=({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 kl(e){const s=re(),n=X();return R.useQuery({queryKey:["revisions",e],queryFn:async()=>await n(s,{action:_.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Pl=()=>{const e=re(),s=X(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>await s(e,{action:_.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},Il=()=>{const e=re(),s=X(),n=R.useQueryClient();return R.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:_.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(N.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(N.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 Dl({compare:e,setCompare:s,isComparisonEnabled:n}){const{data:a}=Ce(),{saveState:r}=Q.useSavePage(),[i]=Ms();if(!a)return null;const o=!!e.find(d=>{var h;return(h=d==null?void 0:d.uid)==null?void 0:h.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:!g.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(Fa,{checked:o,disabled:l,onChange:()=>{s(o?e.filter(d=>d.uid!==`draft:${a==null?void 0:a.id}`):[...e,{uid:`draft:${a==null?void 0:a.id}`,label:"draft",item:{createdAt:Date.now()}}])}})]})}function _l(){var V,Y;const[e,s]=je.useState([]),[n,a]=je.useState(!1),[r,i]=je.useState(null),[o,l]=je.useState(!1),[u,d]=je.useState(!1),{data:h}=Ce(),{data:m,isFetching:y,error:j,refetch:p}=kl(h==null?void 0:h.id),{mutate:f,isPending:b}=Pl(),{mutate:v,isPending:S}=Il(),P=R.useQueryClient(),z=va(),B=Q.useChaiFeatureFlag("enable-page-revisions-compare"),{selectedLang:O,fallbackLang:W}=Q.useLanguages(),D=O||W;x.useEffect(()=>s([]),[h==null?void 0:h.id]);const F=L=>{r&&v({revisionId:r.uid,discardCurrent:L},{onSuccess:()=>{l(!1),i(null),P.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]})}})},T=L=>{i(L),l(!0)},$=L=>{i(L),d(!0)},K=()=>{r&&f(r.uid,{onSuccess:()=>{d(!1),i(null)}})};return x.useEffect(()=>{n&&p()},[n,p]),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(N.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"}),(h==null?void 0:h.createdAt)&&t.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Page created on ",ut.format(new Date(h.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),y?t.jsx(Ll,{}):j?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:[B&&t.jsx(Bl,{lang:D,compare:e,setCompare:s,pageId:h==null?void 0:h.id}),t.jsx(Dl,{compare:e,setCompare:s,isComparisonEnabled:B}),(V=m==null?void 0:m.filter(L=>L.uid==="current"))==null?void 0:V.map((L,me)=>t.jsx(Fn,{lang:D,pageId:h==null?void 0:h.id,revision:L,isLatest:!0,onRestore:()=>T(L),onDelete:()=>$(L),revisionNumber:me,compare:e,setCompare:s,pageLiveFullSlug:z,isComparisonEnabled:B},L.uid)),t.jsx(c.ScrollArea,{className:"min-h-0 flex-1",children:t.jsx("div",{className:"space-y-2",children:(Y=m==null?void 0:m.filter(L=>L.uid!=="current"))==null?void 0:Y.map((L,me)=>t.jsx(Fn,{lang:D,pageId:h==null?void 0:h.id,revision:L,isLatest:L.uid==="current",onRestore:()=>T(L),onDelete:()=>$(L),revisionNumber:me+1,compare:e,setCompare:s,pageLiveFullSlug:z,isComparisonEnabled:B},L.uid))})})]})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Ml,{open:o,onOpenChange:l,revision:r,onRestore:F,isRestoring:S}),t.jsx(Rl,{open:u,onOpenChange:d,revision:r,onDelete:K,isDeleting:b})]})}function Ll(){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 Fn({revision:e,isLatest:s,onRestore:n,onDelete:a,revisionNumber:r,compare:i,setCompare:o,pageId:l,pageLiveFullSlug:u,isComparisonEnabled:d,lang:h}){const{data:m}=Je(e.currentEditor),y=(m==null?void 0:m.name)||"Unknown",j=!!i.find(f=>{var b;return s?(b=f==null?void 0:f.uid)==null?void 0:b.startsWith("live"):(f==null?void 0:f.uid)===e.uid}),p=i.length>=2&&!j;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:[d&&t.jsx(rt,{tag:s?"live":`#${r}`}),e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"text-xs font-bold",children:y}),!d&&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"&&d&&t.jsx("a",{target:"_blank",href:s?u:`/revision/revision:${e.uid}:${r}?lang=${h}`,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-4 w-4 hover:text-blue-500",children:[t.jsx(N.Eye,{className:"h-3 w-3"}),t.jsx("span",{className:"sr-only",children:"View this version"})]})}),t.jsx(Oe,{permissions:[ve.RESTORE_REVISION,ve.DELETE_REVISION],children:t.jsx(Ol,{revision:e,onRestore:n,onDelete:a})})]}),d&&t.jsx(Fa,{checked:j,disabled:p,onChange:()=>{o(j?i.filter(f=>s?f.uid!==`live:${l}`:f.uid!==e.uid):[...i,{uid:s?`live:${l}`:e.uid,label:s?"live":`#${r}`,item:e}].sort((f,b)=>new Date(f.item.createdAt).getTime()-new Date(b.item.createdAt).getTime()))}})]})}function Bl({compare:e,setCompare:s,pageId:n}){const[a,r]=x.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(d=>d.uid!==u.uid)),"aria-label":"Remove selection 1",children:t.jsx(N.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(N.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(Tl,{open:a,onOpenChange:r,compare:e})]})}function Fa({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 Ol({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(N.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(Oe,{permission:ve.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer text-sm",children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Oe,{permission:ve.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(N.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function Ml({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=Je((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(N.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(N.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function Rl({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=Je((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(N.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Gl=()=>{const e=re(),s=X();return R.useQuery({queryKey:[_.GET_CHANGES],queryFn:async()=>s(e,{action:_.GET_CHANGES})})},Ul=({page:e,selectedPages:s,handleCheckboxChange:n,getPageType:a,hasSlug:r,currentOwnerId:i})=>{const{data:o}=Je(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(N.Lock,{className:"h-4 w-4 fill-red-200 text-red-500"}):t.jsx("input",{checked:g.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(N.File,{className:"h-4 w-4"}):t.jsx(N.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:g.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(N.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 Fl({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n]=wa(),[a,r]=x.useState([]),i=Ye(),[o,l]=x.useState(i),{data:u,isFetching:d}=Gl(),{data:h}=ke(),m=x.useCallback(T=>{var $;return($=g.find(h,{key:T}))==null?void 0:$.hasSlug},[h]),y=x.useMemo(()=>g.filter(h,T=>!m(T.key)).map(T=>T.key),[m,h]),p=g.uniq(g.map(u,"lang")).filter(Boolean),f=x.useMemo(()=>g.filter(u,T=>T.pageType==="theme"?!1:o===i?T.lang===o||T.lang==="":T.lang===o),[u,o,i]),b=x.useMemo(()=>g.filter(f,T=>!y.includes(T.pageType)),[f,y]),v=x.useMemo(()=>g.filter(f,T=>y.includes(T.pageType)),[f,y]),{mutate:S,isPending:P}=bn();x.useEffect(()=>{const T=g.map(g.filter(f,{online:!0}),"id");r(T)},[f]),x.useEffect(()=>{const T=Object.keys(n);r($=>g.filter($,K=>!g.includes(T,K)))},[n]);const z=a.length===(f==null?void 0:f.length),B=T=>{r($=>g.includes($,T)?g.filter($,K=>K!==T):g.concat($,T))},O=()=>{r(z?[]:g.map(f,"id"))},W=()=>{S({ids:g.uniq(a)},{onSuccess:()=>{s(),Ft("CENTER_CENTER"),l(i)}})},D=T=>{if(T==="theme")return"Theme";const $=g.find(h,{key:T});return $?$==null?void 0:$.name:T},F=x.useMemo(()=>{const T=[{label:"Updated",top:"pt-2"},...g.orderBy(g.filter(b,{online:!0}),"pageType"),...g.orderBy(g.filter(v,{online:!0}),"pageType")].filter(K=>K.pageType!=="theme"),$=[{label:"Offline",top:"pt-6"},...g.orderBy(g.filter(b,{online:!1}),"pageType"),...g.orderBy(g.filter(v,{online:!1}),"pageType")];return[...T,...$]},[b,v]);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."})]}),p.length>0&&t.jsx("div",{className:"my-[2px] mt-0",children:t.jsx(_a,{languages:[i,...p],selectedLanguage:o,setSelectedLanguage:l})}),t.jsx("div",{className:"no-scrollbar relative -mx-4 -mt-4 h-full max-h-full overflow-y-auto",children:d?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:z,onClick:T=>{T.stopPropagation(),O()},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:g.map(F,T=>T.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:`relative px-6 py-2 text-xs font-medium text-gray-800 ${T.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:T.label})})]})},"separator"):t.jsx(Ul,{page:T,selectedPages:a,handleCheckboxChange:B,getPageType:D,hasSlug:m,currentOwnerId:n[(T==null?void 0:T.primaryPage)||(T==null?void 0:T.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||d||g.isEmpty(a),onClick:W,children:P?"Publishing...":"Publish Selected"})]})]})})}const ql=({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"})]})]})})},zl=()=>{const e=X(),s=re();return R.useQuery({queryKey:[_.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_DATA,data:{draft:!0}})})};function $l({onClose:e}){const{data:s,isFetching:n}=zl(),{mutateAsync:a,isPending:r}=ti(),i=Ue("settingComponent",null),o=g.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:x.createElement(i,{data:s||{},onSave:r?()=>{}:o,cancel:r?()=>{}:e})})]})}):null}const Vl=()=>{const{selectedLang:e,fallbackLang:s}=Q.useLanguages(),n=Ue("getPreviewUrl",async m=>m),[a,r]=x.useState(""),{data:i}=Ce(),{data:o}=Re(),{data:l}=ke(),u=x.useMemo(()=>{var m;return(m=o==null?void 0:o.find(y=>(y==null?void 0:y.lang)===e))==null?void 0:m.slug},[e,o]),d=x.useCallback(m=>{var y;return(y=g.find(l,{key:m}))==null?void 0:y.hasSlug},[l]),h=e===s?"":e;return x.useEffect(()=>{(async()=>{if(typeof n=="function"){const m=!d(i==null?void 0:i.pageType),y=await n(m?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(y)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,h]),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(N.Eye,{className:"h-4 w-4"})," ",le.PREVIEW]})})})},Kl=()=>{const[e,s]=Q.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(ot,{content:le.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(N.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},Hl=()=>{const[e,s]=x.useState(!1),{isLocked:n}=Ke(),{savePageAsync:a,saveState:r}=Q.useSavePage();x.useEffect(()=>{const d=h=>{r==="UNSAVED"&&(h.preventDefault(),h.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[r]);const i=x.useCallback(async()=>{e||(s(!0),await a(),s(!1))},[a,e]),{buttonIcon:o,buttonClass:l,tooltipContent:u}=x.useMemo(()=>{switch(r){case"UNSAVED":return{tooltipContent:le.SAVEDRAFT,buttonIcon:t.jsx(N.Save,{className:"h-4 w-4"}),buttonClass:"gap-x-1"};case"SAVING":return{tooltipContent:le.SAVING,buttonIcon:t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-sky-700"}),buttonClass:"gap-x-1"};case"SAVED":return{tooltipContent:le.SAVED,buttonIcon:t.jsx(N.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}=We(),{data:n}=Re(),[a,r]=x.useState(!1),[i,o]=x.useState(!1),[l,u]=x.useState(null),{savePageAsync:d}=Q.useSavePage(),[h,m]=x.useState(!1),{data:y}=Ce(),{mutate:j,isPending:p}=bn(),{needTranslations:f}=Q.useSavePage(),b=f(),{buttonText:v,buttonClassName:S,isPublished:P}=x.useMemo(()=>{const F=y&&(y==null?void 0:y.online);return{buttonClassName:F?"hover:bg-green-600 bg-green-500":"",isPublished:F,buttonText:F?le.PUBLISHED:le.PUBLISH}},[y]),z=async()=>{if(b){m(!0);return}B()},B=()=>{const F=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];j({ids:g.compact(F)},{onSuccess:()=>Ft("TOP_RIGHT")})},O=()=>{m(!1),B()},W=async()=>{m(!1),await d()},D=x.useMemo(()=>g.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:z,disabled:p||!(y!=null&&y.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${S}`,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(N.Send,{className:"h-4 w-4"}):t.jsx(N.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(N.Rocket,{className:"h-4 w-4"}):t.jsx(N.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:v}),e?`(${g.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:p||!(y!=null&&y.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${S}`,children:t.jsx(N.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(c.DropdownMenuItem,{disabled:p,className:"cursor-pointer text-xs",onClick:()=>j({ids:D},{onSuccess:()=>Ft("TOP_RIGHT")}),children:[le.PUBLISH," with translation pages"]}),!P&&t.jsxs(c.DropdownMenuItem,{disabled:p,className:"cursor-pointer text-xs",onClick:()=>j({ids:[y==null?void 0:y.id]},{onSuccess:()=>Ft("TOP_RIGHT")}),children:[le.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[le.OPEN," publish menu"]}),P&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[le.UNPUBLISH," page ",e?`(${g.upperCase(e)})`:""]})]})]})]}),t.jsx(Fl,{showModal:a,onClose:()=>r(!1)}),l&&t.jsx(Gs,{page:l,onClose:()=>u(null)}),t.jsx(ql,{isOpen:h,onClose:W,onContinue:O,isPending:p})]})},Wl=()=>{const e=Ue("settingComponent",null),[s,n]=x.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(ot,{content:le.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(N.Settings,{className:"h-4 w-4"})})}),s&&t.jsx($l,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Jl(){const{isLocked:e}=Ke(),[s]=Ie(),n=s.get("lang"),a=ga(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(_l,{}),t.jsx(Oe,{permission:ve.EDIT_THEME,children:t.jsx(Kl,{})}),t.jsx(Oe,{permission:ve.EDIT_SETTINGS,children:t.jsx(Wl,{})}),t.jsx(Vl,{}),t.jsx(Oe,{permission:ve.SAVE_PAGE,children:t.jsx(Hl,{})}),t.jsx(Oe,{permission:ve.PUBLISH_PAGE,children:t.jsx(Ql,{})})]})}const Yl=({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()}),Xl=({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?g.get(e,"name"):"Select Page",t.jsx(N.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(Yl,{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))]})]})},Zl=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:o,onChangeLanguage:l}=ja(),u=x.useRef(void 0);return x.useEffect(()=>{u.current!==a&&e&&(l(),u.current=a)},[a,s]),t.jsx("div",{className:"relative",children:t.jsx(Xl,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:o,dynamicPages:n})})},eo=()=>{const[e,s]=x.useState(null),[n,a]=x.useState(null),[r,i]=x.useState(null),[o,l]=x.useState(null),[u,d]=x.useState(null),[h,m]=x.useState(null),[y,j]=x.useState(!1),{data:p,isFetching:f}=We(),{selectedLang:b,fallbackLang:v}=Q.useLanguages(),{data:S}=Re(),P=S==null?void 0:S.find(F=>F.lang===b),{isLocked:z}=Ke(),B=!(p!=null&&p.slug),[,O]=ge.useAtom(ds),{savePage:W}=Q.useSavePage();if(!p)return null;const D=F=>{b.length>0&&b!==v?O({edit:!0,id:F==null?void 0:F.id,primaryPage:F==null?void 0:F.primaryPage}):m(F)};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:()=>{W(),j(!0)},children:f?t.jsx(N.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:[B?t.jsx(N.Globe,{className:"mr-1 h-4 w-4"}):t.jsx(N.File,{className:"mr-1 h-4 w-4"}),g.get(P||p,"name")??""]})}),z?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(N.MoreHorizontal,{className:"h-4 w-4"})}):t.jsx(La,{page:p,setDuplicatePage:F=>d(F),setAddEditPage:F=>D(F),setUnpublishPage:F=>a(F),setDeletePage:F=>s(F),setMarkAsTemplate:F=>i(F),setUnmarkAsTemplate:F=>l(F),isLanguagePage:b.length>0&&b!==v,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 rounded",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})})]}),h&&t.jsx(Oa,{closePanel:()=>m(null),editPage:()=>{},addEditPage:h,setAddEditPage:m}),e&&t.jsx(Cn,{page:e,onClose:()=>s(null)}),n&&t.jsx(Gs,{page:n,onClose:()=>a(null)}),r&&t.jsx(Ra,{page:r,onClose:()=>i(null)}),o&&t.jsx(Ga,{page:o,onClose:()=>l(null)}),u&&t.jsx(Ma,{page:u,onClose:()=>d(null),closePanel:()=>m(null)}),t.jsx(c.Sheet,{open:y,onOpenChange:j,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(N.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(Ua,{close:()=>j(!1)})})]})})]})},to=({hasDynamicPage:e})=>t.jsx(Dt,{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"})]})}),so=()=>{const{data:e}=We(),s=pn(),{data:n,isFetching:a}=Ce(),r=g.get(n,"dynamic",!1),i=Q.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:o,allLangPages:l}=ja(),u=l.length>0,d=e==null?void 0:e.slug,h=!d,m=va(),j=(h?`Partial: ${e==null?void 0:e.name} `:`${d}${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(eo,{})}),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"+(h?" pr-2":""),a&&"pointer-events-none cursor-not-allowed opacity-50"),children:[t.jsx(An,{}),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 ${h?"italic text-gray-400":"font-mono text-gray-500"}`,children:j==="/"?t.jsxs("span",{className:"text-gray-900",children:["/",t.jsx("span",{className:"text-[11px] font-light italic text-gray-400",children:"(Homepage)"})]}):j}),!h&&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(N.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})]}),r&&!a&&i&&t.jsxs("div",{className:"relative",children:[!o&&t.jsx(to,{hasDynamicPage:u}),t.jsx(Zl,{})]})]})},no=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(bl,{}),t.jsx(so,{}),t.jsx(Jl,{})]}),ao=()=>{const e=re(),{aiContext:s}=pa(),n=X();return x.useCallback(async(a,r,i,o)=>n(e,{action:_.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:o}}),[e,s,n])},ro=(e,s)=>s.map(n=>{if(g.has(e,n._type)){const a=oa.getDefaultBlockProps(n._type);return{...a,...g.pick(n,[...g.keys(a),"_type","_id","_name","_parent","_bindings"]),...g.pickBy(n,(r,i)=>g.endsWith(i,"_attrs")),...n}}return n}),io=e=>{const s=oa.useRegisteredChaiBlocks();return x.useMemo(()=>{if(!e||g.isEmpty(e))return{blocks:[]};const n=g.filter(e,a=>!g.includes(a==null?void 0:a._type,"@chai/"));return{blocks:ro(s,n)}},[e,s])},qn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=g.get(a,"html",""),i=g.get(a,"blocks",[]);return g.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),[]}}},lo=()=>{const e=re(),s=X();return R.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=>qn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>qn.getUILibraryBlock(i,s,e)})}),a}})},qa=()=>{const e=Os(),s=X(),{user:n}=Ge(),a=n==null?void 0:n.id;return R.useQuery({queryKey:["permissions",a],queryFn:()=>s(e,{action:_.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},oo=()=>{const e=re(),s=X(),{setCurrentEditor:n}=Ke(),[,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(d=>({...d,lastSaved:new Date().toISOString()})),u)}catch(u){return console.error(u),new Error("Failed to save blocks")}}}},co=()=>{const{data:e}=Bt(),s=re(),n=X();return{getPartialBlocks:x.useCallback(async()=>{const a={};for(const r of e??[])g.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:g.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:x.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return g.filter(r.blocks,i=>g.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},zn=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"})}),uo=()=>{const{setUser:e,logout:s}=Ge(),n=Os(),[a,r]=x.useState(""),[i,o]=x.useState(""),[l,u]=x.useState({}),[d,h]=x.useState(!1),[m,y]=x.useState(""),j=R.useMutation({mutationFn:async b=>{y("");const v=await xn(n,{action:"LOGIN",data:b});if(!v.ok){const P=await v.json();throw new Error(P.error||"Login failed")}const S=await v.json();if(g.has(S,"id")&&g.has(S,"email")&&g.has(S,"accessToken")&&g.has(S,"refreshToken"))e(S);else throw s(),new Error("Something went wrong. Please try again.");return S},onSuccess:()=>{u({}),y("")},onError:b=>{u({email:" ",password:" "}),y(b.message?"Invalid email or password":"Something went wrong")}}),p=async b=>{b.preventDefault(),u({});const v={email:a,password:i};try{const S=zn.parse(v);j.mutate(S)}catch(S){if(S instanceof bs.z.ZodError){const P=S.issues.reduce((z,B)=>{const O=B.path[0];return z[O]=B.message,z},{});u(P)}}},f=zn.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:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:b=>r(b.target.value),className: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:d?"text":"password",value:i,onChange:b=>o(b.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:()=>h(!d),children:d?t.jsx(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.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:!f||j.isPending,children:j.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{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 an=uo;const ho=()=>x.useMemo(()=>an,[an]),mo=e=>{an=e},$n=()=>{const e=ho();return t.jsx(x.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},fo=({page:e,onClose:s})=>{const[n,a]=x.useState(e.slug||""),{mutate:r,isPending:i}=Oi(),{data:o}=ke(),l=g.find(o,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Ne).some(j=>n===`/${j}`||g.startsWith(n,`/${j}/`))){J.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(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(N.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 /",d]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:h=>{const m=h.target.value;g.startsWith(m,`/${d}`)&&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||!g.startsWith(n,`/${d}`)||g.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},xo=()=>{const[,e]=ge.useAtom(ds),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=Q.useLanguages(),{data:r,isFetching:i}=Re(),{data:o}=Ce(),{data:l}=ke(),u=x.useMemo(()=>{const v=l==null?void 0:l.find(S=>S.key===(o==null?void 0:o.pageType));return o!=null&&o.dynamic?v==null?void 0:v.dynamicSlug:""},[l,o==null?void 0:o.pageType,o==null?void 0:o.dynamic]),[d,h]=x.useState(null),[m,y]=x.useState(null),[j,p]=x.useState(null),{data:f}=Ve(),b=g.filter(g.get(f,"languages")||["en"],v=>!g.find(r,{lang:v})&&v!==g.get(f,"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"})]}):g.map(r,v=>{const S=v.lang,P=v.slug,z=!v.primaryPage,B=S===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 ${B?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(S),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 ${v.online?"bg-green-300":"bg-gray-300"}`}),g.get(Ne,z?n:S,S)]}),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:[" ",v.name," "]})]})]})]}),z?t.jsxs("div",{className:"flex items-center gap-x-1 text-[11px] text-orange-500",children:[t.jsx(N.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(Oe,{permissions:[ve.EDIT_PAGE,ve.DELETE_PAGE,ve.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:O=>O.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"z-[9999] text-sm",children:[t.jsx(Oe,{permissions:[ve.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:O=>{O.stopPropagation(),e({edit:!0,id:v.id,primaryPage:v.primaryPage})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),le.EDIT]})}),t.jsx(Oe,{permissions:[ve.UNPUBLISH_PAGE],children:(v==null?void 0:v.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:O=>{O.stopPropagation(),y(v)},children:[t.jsx(N.Power,{className:"size-3"}),le.UNPUBLISH]})}),t.jsx(Oe,{permissions:[ve.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:O=>{O.stopPropagation(),h(v)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),le.DELETE]})})]})]})})})]},v.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Oe,{permissions:[ve.ADD_PAGE],children:t.jsx("div",{className:"flex w-full justify-center",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:g.isEmpty(b),onClick:()=>{e({primaryPage:o==null?void 0:o.id,edit:!1})},children:le.ADD_NEW_LANGUAGE})})}),d&&t.jsx(Cn,{page:d,onClose:()=>h(null)}),m&&t.jsx(Gs,{page:m,onClose:()=>y(null)}),j&&t.jsx(fo,{page:j,onClose:()=>p(null)})]})},go=({isActive:e,show:s})=>{const{data:n}=Ve();return!g.has(n,"languages")||!g.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},za="lang",po={id:za,label:"Languages",position:"top",panel:xo,button:go,view:"modal",width:400};function He({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=je.useState(!1),[o,l]=je.useState([]),[u,d]=je.useState(e);je.useEffect(()=>{r||l([]),d(e)},[e,r]);const h=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",m=je.useCallback(p=>{const f=b=>n==="value"?b==="value"||b==="object":n==="array"?b==="array":b===n;p.type==="object"?(l(b=>[...b,p.key]),d(p.value)):f(p.type)&&(s([...o,p.key].join(".")),i(!1))},[o,s,n]),y=je.useCallback(()=>{if(o.length>0){const p=o.slice(0,-1);l(p),d(p.reduce((f,b)=>f[b],e))}},[o,e]),j=je.useMemo(()=>Object.entries(u).map(([p,f])=>({key:p,value:f,type:h(f)})).filter(p=>n==="value"?p.type==="value"||p.type==="object":n==="array"?p.type==="array"||p.type==="object":n==="object"?p.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("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24px",height:"24px",viewBox:"0 0 24 24",fill:"none",children:t.jsx("path",{d:"M9.5 5H9C7.89543 5 7 5.89543 7 7V9C7 10 6.4 12 4 12C5 12 7 12.6 7 15V17.0002C7 18.1048 7.89543 19 9 19H9.5M14.5 5H15C16.1046 5 17 5.89543 17 7V9C17 10 17.6 12 20 12C19 12 17 12.6 17 15V17.0002C17 18.1048 16.1046 19 15 19H14.5",stroke:"#000000",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"z-[9999] w-[200px] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:p=>{try{p.preventDefault();const f=p.currentTarget;f.scrollTop+=p.deltaY}catch{p.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[o.length>0&&t.jsxs(c.CommandItem,{onSelect:y,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"mr-2 h-4 w-4"}),"Back"]}),j.map(p=>t.jsxs(c.CommandItem,{onSelect:()=>m(p),className:"flex items-center justify-between",children:[t.jsx("span",{children:p.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&p.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:f=>{f.stopPropagation(),s([...o,p.key].join(".")),i(!1)},children:"Select"}),(p.type==="object"||p.type==="array")&&t.jsx("div",{className:"cursor-pointer rounded p-1 hover:bg-muted",children:t.jsx(N.ChevronRight,{className:"h-4 w-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const yo=()=>{const{selectedLang:e}=Q.useLanguages(),{data:s,isFetching:n}=Re();return{data:x.useMemo(()=>g.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},jo=()=>{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=re(),{selectedLang:i,fallbackLang:o}=Q.useLanguages(),{mutate:l,isPending:u}=R.useMutation({mutationFn:async()=>{const d=jo();return await a(r,{action:_.GENERATE_SEO_FIELD,data:{pageContext:"",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:u,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>l(),children:u?t.jsx(N.Loader,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(N.Wand2Icon,{className:"text-yellow-500"})})},vo=({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"})]})]})})},bo=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Cs=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 d,h;if(u!==void 0){const m=a.substring(0,u).split(`
10
- `);d=m.length,h=m[m.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:o.message,line:d,column:h,position:u}}}},wo=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const o=`"__placeholder_${i}__"`,l=new RegExp(bo(o),"g");a=a.replace(l,r)}),a},No=(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=g.get(s,i,null);n=n.replace(r[0],o)}return n},$a=()=>{const e=re(),s=X();return R.useQuery({queryKey:[_.GET_APP_SHARED_JSONLD],queryFn:async()=>await s(e,{action:_.GET_APP_SHARED_JSONLD})||[],initialData:[],retry:2})},Va=()=>{const e=re(),s=X(),{data:n}=We(),a=R.useQueryClient();return R.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:_.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[_.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})};function So(){const{data:e}=Ce(),s=g.get(e,"metadata",{})||{},[n,a]=x.useState(g.get(s,"sharedJsonLD",[])||[]),[r,i]=x.useState({show:!1,data:null}),{mutateAsync:o}=Va(),[l,u]=x.useState(null),{data:d,isLoading:h}=$a(),{mutateAsync:m}=xa(),y=async f=>{await o({...s,sharedJsonLD:f}),a(f),u(null)},j=async f=>{u(f);let b=[...n];g.includes(n,f)?b=b.filter(v=>v!==f):b=[...b||[],f],await y(b)},p=async f=>{u(f);try{const b=d==null?void 0:d.filter(v=>v.id!==f);await m(b),a(b),u(null)}catch{u(null)}};return t.jsxs("div",{className:"rounded border bg-muted p-2",children:[t.jsxs("div",{className:"flex items-center justify-between pb-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-medium",children:"Shared JSON-LD Templates"}),t.jsx("div",{className:"w-full text-xs text-gray-500",children:"Manage reusable JSON-LD schemas that can be applied across multiple pages"})]}),t.jsxs(c.Tooltip,{delayDuration:0,children:[t.jsx(c.TooltipTrigger,{type:"button",disabled:h,className:"rounded-full bg-primary p-1 text-primary-foreground hover:bg-primary/80",onClick:f=>{f.stopPropagation(),i({show:!0,data:null})},children:h?t.jsx(N.Loader,{className:"h-4 w-4 animate-spin"}):t.jsx(N.Plus,{className:"h-4 w-4"})}),t.jsx(c.TooltipContent,{children:"Add new schema"})]})]}),t.jsxs(c.ScrollArea,{className:"max-h-96 overflow-y-auto",children:[t.jsxs("div",{className:"space-y-2 pb-4",children:[(!d||(d==null?void 0:d.length)===0)&&!h&&t.jsx("div",{className:"flex items-center justify-center px-2 py-4 text-xs",children:"No shared JSON-LD found"}),d==null?void 0:d.map(f=>{const b=Cs(f.content),v=b.isValid?b.parsed:"",S=g.includes(n,f.id);return t.jsxs(c.Card,{className:`relative p-0 shadow-none transition-all ${l===f.id?"pointer-events-none":""}`,children:[l===f.id&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 flex items-center justify-center rounded-xl bg-white/80",children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin text-primary"})}),t.jsx(c.CardHeader,{className:"p-2",children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsxs("div",{children:[t.jsx(c.CardTitle,{className:"flex items-center gap-2 text-sm leading-none",children:f.name}),(f==null?void 0:f.description)&&t.jsx("p",{className:"mt-1 text-xs leading-none text-muted-foreground",children:f==null?void 0:f.description})]})}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Switch,{checked:S,onCheckedChange:()=>j(f.id)}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"h-5 w-5 p-0",onClick:()=>i({show:!0,data:f}),children:t.jsx(N.Edit,{className:"h-4 w-4"})}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{className:"flex h-5 w-5 items-center justify-center rounded-md text-red-500 hover:bg-red-100 hover:text-red-800",children:t.jsx(N.Trash,{className:"h-4 w-4"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Delete Schema"}),t.jsxs(c.AlertDialogDescription,{children:["Are you sure you want to delete ",t.jsx("span",{className:"font-medium",children:f.name}),"? This action cannot be undone."]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{type:"button",children:"Cancel"}),t.jsx(c.AlertDialogAction,{type:"button",onClick:()=>p(f.id),className:"bg-red-500 text-white hover:bg-red-600",children:"Delete"})]})]})]})]})]})}),t.jsx(c.CardContent,{className:"px-2 pb-2",children:t.jsx(c.Textarea,{id:f.id,rows:1,readOnly:!0,value:JSON.stringify(v,null,2),className:"no-scrollbar cursor-text rounded-md border border-input bg-gray-100 text-xs"})})]})})]}),h&&t.jsx("div",{className:"flex items-center justify-center p-4",children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin"})})]}),t.jsx(Eo,{data:r==null?void 0:r.data,show:r==null?void 0:r.show,onClose:f=>{f&&p(f),i({show:!1,data:null})}})]})}const Eo=({data:e,show:s,onClose:n})=>t.jsx(c.Dialog,{open:s,onOpenChange:()=>n(null),children:s&&t.jsx(Co,{data:e,show:s,onClose:n})}),Co=({data:e,show:s,onClose:n})=>{const[a,r]=x.useState(!1),[i,o]=x.useState("edit"),[l,u]=x.useState(""),[d,h]=x.useState({name:"",content:"",description:""}),{data:m}=$a(),{mutateAsync:y,isPending:j}=xa();x.useEffect(()=>{o("edit"),h({name:"",description:"",content:""}),e&&h({name:e.name,description:e.description,content:e.content})},[e,s]),x.useEffect(()=>{const f=Cs(d.content);u(f.isValid?JSON.stringify(f.parsed,null,2):"")},[d.content]);const p=async()=>{if(!d.name||!d.content){J.toast.error("Please enter a name and content");return}const f={id:e?e.id:crypto.randomUUID(),name:d.name,description:d.description,content:d.content};e?await y([...(m||[]).map(b=>b.id===e.id?f:b)]):await y([...m||[],f]),n==null||n(a?f==null?void 0:f.id:null)};return t.jsxs(c.DialogContent,{className:"max-h-[80vh] max-w-lg overflow-y-auto",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Add New Shared JSON-LD Schema"})}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"new-name",children:"Schema Name"}),t.jsx(c.Input,{id:"new-name",value:d.name,onChange:f=>h({...d,name:f.target.value}),placeholder:"e.g., Product Schema"})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"new-description",children:"Description"}),t.jsx(c.Input,{id:"new-description",value:d.description||"",onChange:f=>h({...d,description:f.target.value}),placeholder:"Brief description of this schema"})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"new-content",children:"JSON-LD Content"}),t.jsxs(c.Tabs,{value:i,onValueChange:o,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex w-full items-center justify-between",children:[t.jsxs(c.TabsList,{className:"w-max",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(N.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!l,children:[t.jsx(N.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),t.jsx("div",{className:"flex items-center gap-2",children:i==="edit"&&t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>h({...d,content:l}),disabled:!l,children:"Format"})})]}),t.jsxs(c.TabsContent,{value:"edit",children:[t.jsx(c.Textarea,{id:"new-content",value:d.content||"",onChange:f=>h({...d,content:f.target.value}),className:"font-mono text-sm",placeholder:"Enter JSON-LD markup...",rows:12}),!l&&d.content?t.jsx("p",{className:"pt-px text-xs text-red-500",children:"Invalid JSON-LD"}):t.jsx("p",{})]}),t.jsx(c.TabsContent,{value:"preview",children:t.jsx(c.Textarea,{id:"new-content",value:l||"",className:"bg-muted font-mono text-sm",placeholder:"{}",rows:12,readOnly:!0})})]})]}),t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx(c.Switch,{id:"new-enabled",checked:a,onCheckedChange:f=>r(f)}),t.jsx(c.Label,{htmlFor:"new-enabled",children:"Enable by default"})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{disabled:j,variant:"outline",type:"button",size:"sm",onClick:()=>n(),children:"Cancel"}),t.jsx(c.Button,{disabled:j||!l,type:"button",size:"sm",onClick:p,className:"w-32",children:j?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 animate-spin"})," ",e?"Updating":"Adding"]}):e?"Update Schema":"Add Schema"})]})]})]})]})},rn=({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[d,h]=x.useState("edit"),[m,y]=x.useState(null),[j,p]=x.useState(""),f=x.useRef(null),[b]=gn(),v=g.get(b,"features.sharedJSONLD",!1);x.useEffect(()=>{e.trim()===""&&s("{}")},[e,s]);const S=O=>{if(a)return;const W=O.target.value;s(W)},P=O=>{if(O.key==="Tab"){O.preventDefault();const W=O.currentTarget,D=W.selectionStart,F=W.selectionEnd;if(D!==F){const $=e.substring(D,F).split(`
11
- `);if(O.shiftKey){const V=$.map(L=>L.startsWith(" ")?L.substring(2):L).join(`
12
- `),Y=e.substring(0,D)+V+e.substring(F);s(Y),setTimeout(()=>{W.selectionStart=D,W.selectionEnd=D+V.length},0)}else{const V=$.map(L=>` ${L}`).join(`
13
- `),Y=e.substring(0,D)+V+e.substring(F);s(Y),setTimeout(()=>{W.selectionStart=D,W.selectionEnd=D+V.length},0)}}else{const T=e.substring(0,D)+" "+e.substring(F);s(T),setTimeout(()=>{W.selectionStart=W.selectionEnd=D+2},0)}}};x.useEffect(()=>{const O=Cs(e);if(O.isValid)if(y(null),O.parsed){const W=No(O.parsed,l);p(W)}else p("");else y(O.error),p("")},[e,l]);const z=()=>{const O=Cs(e);if(O.isValid&&O.parsed){const W=wo(O.parsed,O.placeholders);s(W)}},B=()=>{m!=null&&m.position&&f.current&&(f.current.focus(),f.current.setSelectionRange(m.position,m.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(c.Tabs,{value:d,onValueChange:h,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(c.TabsList,{className:"w-max",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(N.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(N.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]}),v&&t.jsxs(c.TabsTrigger,{value:"shared",className:"flex items-center gap-1",disabled:!e.trim()||m!==null,children:[t.jsx(N.Share2,{className:"h-4 w-4"}),t.jsx("span",{children:"Shared"})]})]}),d==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(He,{dataType:"value",data:l??{},onSelect:O=>u&&u(O,o)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:z,disabled:!e.trim()||n||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:f,id:o,name:o,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:S,onKeyDown:P,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),m&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.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:B,children:"Show position"})]})]})]}),t.jsxs(c.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(c.Textarea,{rows:i,value:j,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."})]}),v&&t.jsx(c.TabsContent,{value:"shared",className:"mt-0",children:t.jsx(So,{})})]})})},Vn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},Ao=(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,d=n+0+l.length;return{value:u,newCursorPos:d}},Ka=()=>{const{t:e}=Q.useTranslation(),[,s]=Q.useSidebarActivePanel(),{data:n}=Ce(),{data:a}=jn(),{data:r,isFetching:i}=yo(),o=r==null?void 0:r.seo,l=x.useRef(null),[u,d]=x.useState("seo"),h=n==null?void 0:n.id,m=n==null?void 0:n.pageType,y=Ca(m),{selectedLang:j,fallbackLang:p}=Q.useLanguages(),f=j||p,[b,v]=x.useState(!1),[S,P]=x.useState(!1),[z,B]=x.useState(!1),[O,W]=x.useState(null),[D,F]=x.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",metaOther:"{}",...o}),T=x.useRef({}),{mutate:$,isPending:K}=vn(),V=K||b||S,{hasPermission:Y}=Q.usePermissions(),L=Y(ve.EDIT_SEO);x.useEffect(()=>{if(!i&&o&&h){const C={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",metaOther:"",...o};F(C),T.current[f]=C}},[i,o,f,h]),x.useEffect(()=>{const C=M=>{const{fromLang:G,toLang:U,switchHandler:q}=M.detail,ee=T.current[f];(ee?!g.isEqual(ee,D):!1)?(W({fromLang:G,toLang:U,switchHandler:q}),B(!0)):q()};return window.addEventListener("seo-language-switch-check",C),()=>{window.removeEventListener("seo-language-switch-check",C)}},[h,D,f]);const me=async()=>{if(!(!y||!f))try{v(!0);const C=zt(y,f),M={...D,keyword:g.get(C,"seo.keyword",""),title:g.get(C,"seo.title",""),description:g.get(C,"seo.description",""),cononicalUrl:g.get(C,"seo.canonicalUrl",""),noIndex:g.get(C,"seo.noIndex",!1),noFollow:g.get(C,"seo.noFollow",!1),ogTitle:g.get(C,"seo.ogTitle",""),ogDescription:g.get(C,"seo.ogDescription","")};F(M),J.toast.success(e("SEO fields reset to defaults"))}catch(C){J.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",C)}finally{v(!1)}},be=async()=>{if(!(!y||!f))try{P(!0);const C=zt(y,f),M={...D,jsonLD:g.get(C,"seo.jsonLD","")};F(M),J.toast.success(e("JSON-LD reset to default"))}catch(C){J.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",C)}finally{P(!1)}},Ae=async()=>{if(!(!y||!f))try{v(!0);const C=zt(y,f),M={...D,ogTitle:g.get(C,"seo.ogTitle",""),ogDescription:g.get(C,"seo.ogDescription",""),ogImage:g.get(C,"seo.ogImage",""),ogImageId:g.get(C,"seo.ogImageId",""),metaOther:g.get(C,"seo.metaOther","{}")};F(M),J.toast.success(e("Meta Tag fields reset to defaults"))}catch(C){J.toast.error(e("Failed to reset Meta Tag fields")),console.error("Reset Meta Tag error:",C)}finally{v(!1)}},ye=async()=>{$({id:r==null?void 0:r.id,seo:D,primaryPage:h},{onSuccess:()=>{console.log("SEO & JSON-LD updated successfully",D),T.current[f]=D,J.toast.success("SEO & JSON-LD updated successfully")}})},E=(C,M)=>{const G=document.getElementById(M);if(G){const{value:U,newCursorPos:q}=Ao(G,C);l.current={id:M,position:q},G.tagName.toLowerCase()==="input"?(G.value=U,F(H=>({...H,[G.name]:U})),G.focus(),G.setSelectionRange(q,q),[0,10,50,100,200].forEach(H=>{setTimeout(()=>{const se=document.getElementById(M);se&&(se.focus(),se.setSelectionRange(q,q))},H)})):(F(ie=>({...ie,[G.name]:U})),requestAnimationFrame(()=>{const ie=document.getElementById(M);ie&&(ie.focus(),ie.setSelectionRange(q,q),setTimeout(()=>{const H=document.getElementById(M);H&&(H.focus(),H.setSelectionRange(q,q))},50))}))}},w=C=>{const M={...D,[C.target.name]:C.target.name==="noIndex"||C.target.name==="noFollow"?C.target.checked:C.target.value};F(M)},I=C=>M=>{g.isEmpty(M.fieldValue)||w({target:{name:C,value:typeof M.fieldValue=="string"?M.fieldValue.replace(/^"(.*)"$/,"$1"):M.fieldValue}}),M.error&&J.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:M.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!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(An,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Tabs,{value:u,onValueChange:d,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("div",{className:u==="seo"?"":"sr-only",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:me,disabled:V||!L||!y,children:e(b?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),L&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>E(C,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:D.keyword,onChange:w,disabled:V||!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:D.keyword,onComplete:I("title"),field:"title"}),L&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>E(C,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:D.title,onChange:w,disabled:V||!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:D.keyword,onComplete:I("description"),field:"description"}),L&&t.jsx(He,{data:a??{},onSelect:C=>E(C,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:D.description,onChange:w,disabled:V||!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(He,{dataType:"value",data:a??{},onSelect:C=>E(C,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:D.canonicalUrl,onChange:w,disabled:V||!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:D.noIndex,onChange:w,disabled:V||!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:D.noFollow,onChange:w,disabled:V||!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("div",{className:u==="opengraph"?"":"sr-only",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:Ae,disabled:V||!L||!y,children:e(b?"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:D.keyword,onComplete:I("ogTitle"),field:"ogTitle"}),L&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>E(C,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:D.ogTitle,onChange:w,disabled:V||!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:D.keyword,onComplete:I("ogDescription"),field:"ogDescription"}),L&&t.jsx(He,{dataType:"value",data:a??{},onSelect:C=>E(C,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:D.ogDescription,onChange:w,disabled:V||!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(He,{dataType:"value",data:a??{},onSelect:C=>{F({...D,ogImage:`{{${C}}}`,ogImageId:""})}})]}),t.jsx(Bs,{assetId:D.ogImageId,assetUrl:D.ogImage,onChange:C=>{F({...D,ogImage:C.url,ogImageId:C.id})},disabled:V||!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:D.keyword,onComplete:I("metaOther"),field:"metaOther"})})]}),t.jsx(rn,{id:"metaOther",value:D.metaOther,onChange:C=>{w({target:{name:"metaOther",value:C}})},placeholder:e("Enter Meta Tags JSON"),disabled:V||!L,readOnly:!L,pageData:a||{},rows:8,handleFieldInsert:E})]})]})]})]})}),t.jsx("div",{className:u==="jsonld"?"":"sr-only",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:be,disabled:V||!L||!y,children:e(S?"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:D.keyword,onComplete:I("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(rn,{id:"jsonLD",value:D.jsonLD,onChange:C=>{w({target:{name:"jsonLD",value:C}})},placeholder:e("Enter JSON-LD"),disabled:V||!L,readOnly:!L,pageData:a||{},rows:12,handleFieldInsert:E})]})]})})]})})]}),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:[Vn(D.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:ye,disabled:!Vn(D==null?void 0:D.jsonLD)||(T.current[f]?g.isEqual(T.current[f],D):!1)||V||!L,children:e(K?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(vo,{isOpen:z,onClose:()=>{B(!1),W(null)},onSave:async()=>{O&&(await ye(),O.switchHandler(),B(!1),W(null))},onDiscard:()=>{if(O){const C=T.current[f];C&&F(C),O.switchHandler(),B(!1),W(null)}},isSaving:K,fromLanguage:(O==null?void 0:O.fromLang)||f,toLanguage:(O==null?void 0:O.toLang)||""})]})};Ka.displayName="SeoPanel";const Ha="seo",To=({isActive:e,show:s})=>{const{data:n}=Ce(),a=Ca(n==null?void 0:n.pageType);return!g.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"icon",className:"my-1 p-0",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{stroke:"currentColor",fill:"none",style:{height:"20px",width:"20px"},strokeWidth:"2",viewBox:"0 0 24 24",strokeLinecap:"round",strokeLinejoin:"round",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"})]})})},ko={id:Ha,label:"SEO",panel:Ka,button:To,position:"top",width:600,view:"modal"},Qa="user-info",Po=()=>{const{user:e,logout:s}=Ge(),n=Ue("onLogout",g.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(N.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(),g.isFunction(n)&&n()},children:"Logout"})]})]})]})]})]}):null},Io={id:Qa,label:"User Info",button:Po,position:"bottom"},Do=()=>{Q.registerChaiSidebarPanel(Ha,ko),Q.registerChaiSidebarPanel(za,po),Q.registerChaiSidebarPanel(Qa,Io)};var ae={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Kn(this.context.count)},getNextContextId(){return Kn(this.context.count++)}};function Kn(e){const s=String(e),n=s.length-1;return ae.context.id+(n?String.fromCharCode(96+n):"")+s}function Rt(e){ae.context=e}var Wa=!1,_o=(e,s)=>e===s,As=Symbol("solid-proxy"),Ja=typeof Proxy=="function",Tn=Symbol("solid-track"),Ts={equals:_o},Ya=rr,Xe=1,ks=2,Xa={owned:null,cleanups:null,context:null,owner:null},Ys={},ce=null,Xs=null,Lo=null,xe=null,Pe=null,Qe=null,Us=0;function tt(e,s){const n=xe,a=ce,r=e.length===0,i=s===void 0?a:s,o=r?Xa:{owned:null,cleanups:null,context:i?i.context:null,owner:i},l=r?e:()=>e(()=>Te(()=>Ht(o)));ce=o,xe=null;try{return $e(l,!0)}finally{xe=n,ce=a}}function we(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)),ar(n,r));return[nr.bind(n),a]}function Za(e,s,n){const a=Fs(e,s,!0,Xe);Ot(a)}function st(e,s,n){const a=Fs(e,s,!1,Xe);Ot(a)}function kn(e,s,n){Ya=Ho;const a=Fs(e,s,!1,Xe);(!n||!n.render)&&(a.user=!0),Qe?Qe.push(a):Ot(a)}function Ee(e,s,n){n=n?Object.assign({},Ts,n):Ts;const a=Fs(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Ot(a),nr.bind(a)}function Bo(e){return e&&typeof e=="object"&&"then"in e}function Oo(e,s,n){let a,r,i;a=!0,r=e,i={};let o=null,l=Ys,u=null,d=!1,h="initialValue"in i,m=typeof a=="function"&&Ee(a);const y=new Set,[j,p]=(i.storage||we)(i.initialValue),[f,b]=we(void 0),[v,S]=we(void 0,{equals:!1}),[P,z]=we(h?"ready":"unresolved");ae.context&&(u=ae.getNextContextId(),i.ssrLoadFrom==="initial"?l=i.initialValue:ae.load&&ae.has(u)&&(l=ae.load(u)));function B(T,$,K,V){return o===T&&(o=null,V!==void 0&&(h=!0),(T===l||$===l)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(V,{value:$})),l=Ys,O($,K)),$}function O(T,$){$e(()=>{$===void 0&&p(()=>T),z($!==void 0?"errored":h?"ready":"unresolved"),b($);for(const K of y.keys())K.decrement();y.clear()},!1)}function W(){const T=$o,$=j(),K=f();if(K!==void 0&&!o)throw K;return xe&&xe.user,$}function D(T=!0){if(T!==!1&&d)return;d=!1;const $=m?m():a;if($==null||$===!1){B(o,Te(j));return}let K;const V=l!==Ys?l:Te(()=>{try{return r($,{value:j(),refetching:T})}catch(Y){K=Y}});if(K!==void 0){B(o,void 0,ws(K),$);return}else if(!Bo(V))return B(o,V,void 0,$),V;return o=V,"v"in V?(V.s===1?B(o,V.v,void 0,$):B(o,void 0,ws(V.v),$),V):(d=!0,queueMicrotask(()=>d=!1),$e(()=>{z(h?"refreshing":"pending"),S()},!1),V.then(Y=>B(V,Y,void 0,$),Y=>B(V,void 0,ws(Y),$)))}Object.defineProperties(W,{state:{get:()=>P()},error:{get:()=>f()},loading:{get(){const T=P();return T==="pending"||T==="refreshing"}},latest:{get(){if(!h)return W();const T=f();if(T&&!o)throw T;return j()}}});let F=ce;return m?Za(()=>(F=ce,D(!1))):D(!1),[W,{refetch:T=>tr(F,()=>D(T)),mutate:p}]}function Mo(e){return $e(e,!1)}function Te(e){if(xe===null)return e();const s=xe;xe=null;try{return e()}finally{xe=s}}function Ro(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 d=0;d<e.length;d++)l[d]=e[d]()}else l=e();if(i)return i=!1,o;const u=Te(()=>s(l,r,o));return r=l,u}}function er(e){kn(()=>Te(e))}function _t(e){return ce===null||(ce.cleanups===null?ce.cleanups=[e]:ce.cleanups.push(e)),e}function Hn(){return ce}function tr(e,s){const n=ce,a=xe;ce=e,xe=null;try{return $e(s,!0)}catch(r){Pn(r)}finally{ce=n,xe=a}}function Go(e){const s=xe,n=ce;return Promise.resolve().then(()=>{xe=s,ce=n;let a;return $e(e,!1),xe=ce=null,a?a.done:void 0})}var[Uo,td]=we(!1);function Fo(){return[Uo,Go]}function qo(e,s){const n=Symbol("context");return{id:n,Provider:Qo(n),defaultValue:e}}function zo(e){let s;return ce&&ce.context&&(s=ce.context[e.id])!==void 0?s:e.defaultValue}function sr(e){const s=Ee(e),n=Ee(()=>ln(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var $o;function nr(){if(this.sources&&this.state)if(this.state===Xe)Ot(this);else{const e=Pe;Pe=null,$e(()=>Is(this),!1),Pe=e}if(xe){const e=this.observers?this.observers.length:0;xe.sources?(xe.sources.push(this),xe.sourceSlots.push(e)):(xe.sources=[this],xe.sourceSlots=[e]),this.observers?(this.observers.push(xe),this.observerSlots.push(xe.sources.length-1)):(this.observers=[xe],this.observerSlots=[xe.sources.length-1])}return this.value}function ar(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=Xs&&Xs.running;o&&Xs.disposed.has(i),(o?!i.tState:!i.state)&&(i.pure?Pe.push(i):Qe.push(i),i.observers&&ir(i)),o||(i.state=Xe)}if(Pe.length>1e6)throw Pe=[],new Error},!1)),s}function Ot(e){if(!e.fn)return;Ht(e);const s=Us;Vo(e,e.value,s)}function Vo(e,s,n){let a;const r=ce,i=xe;xe=ce=e;try{a=e.fn(s)}catch(o){return e.pure&&(e.state=Xe,e.owned&&e.owned.forEach(Ht),e.owned=null),e.updatedAt=n+1,Pn(o)}finally{xe=i,ce=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?ar(e,a):e.value=a,e.updatedAt=n)}function Fs(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:ce,context:ce?ce.context:null,pure:n};return ce===null||ce!==Xa&&(ce.owned?ce.owned.push(i):ce.owned=[i]),i}function Ps(e){if(e.state===0)return;if(e.state===ks)return Is(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<Us);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Xe)Ot(e);else if(e.state===ks){const a=Pe;Pe=null,$e(()=>Is(e,s[0]),!1),Pe=a}}function $e(e,s){if(Pe)return e();let n=!1;s||(Pe=[]),Qe?n=!0:Qe=[],Us++;try{const a=e();return Ko(n),a}catch(a){n||(Qe=null),Pe=null,Pn(a)}}function Ko(e){if(Pe&&(rr(Pe),Pe=null),e)return;const s=Qe;Qe=null,s.length&&$e(()=>Ya(s),!1)}function rr(e){for(let s=0;s<e.length;s++)Ps(e[s])}function Ho(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:Ps(a)}if(ae.context){if(ae.count){ae.effects||(ae.effects=[]),ae.effects.push(...e.slice(0,n));return}Rt()}for(ae.effects&&(ae.done||!ae.count)&&(e=[...ae.effects,...e],n+=ae.effects.length,delete ae.effects),s=0;s<n;s++)Ps(e[s])}function Is(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===Xe?a!==s&&(!a.updatedAt||a.updatedAt<Us)&&Ps(a):r===ks&&Is(a,s)}}}function ir(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ks,n.pure?Pe.push(n):Qe.push(n),n.observers&&ir(n))}}function Ht(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),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--)Ht(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Ht(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function ws(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Pn(e,s=ce){throw ws(e)}function ln(e){if(typeof e=="function"&&!e.length)return ln(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=ln(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Qo(e,s){return function(a){let r;return st(()=>r=Te(()=>(ce.context={...ce.context,[e]:a.value},sr(()=>a.children))),void 0),r}}var on=Symbol("fallback");function Ds(e){for(let s=0;s<e.length;s++)e[s]()}function Wo(e,s,n={}){let a=[],r=[],i=[],o=0,l=s.length>1?[]:null;return _t(()=>Ds(i)),()=>{let u=e()||[],d=u.length,h,m;return u[Tn],Te(()=>{let j,p,f,b,v,S,P,z,B;if(d===0)o!==0&&(Ds(i),i=[],a=[],r=[],o=0,l&&(l=[])),n.fallback&&(a=[on],r[0]=tt(O=>(i[0]=O,n.fallback())),o=1);else if(o===0){for(r=new Array(d),m=0;m<d;m++)a[m]=u[m],r[m]=tt(y);o=d}else{for(f=new Array(d),b=new Array(d),l&&(v=new Array(d)),S=0,P=Math.min(o,d);S<P&&a[S]===u[S];S++);for(P=o-1,z=d-1;P>=S&&z>=S&&a[P]===u[z];P--,z--)f[z]=r[P],b[z]=i[P],l&&(v[z]=l[P]);for(j=new Map,p=new Array(z+1),m=z;m>=S;m--)B=u[m],h=j.get(B),p[m]=h===void 0?-1:h,j.set(B,m);for(h=S;h<=P;h++)B=a[h],m=j.get(B),m!==void 0&&m!==-1?(f[m]=r[h],b[m]=i[h],l&&(v[m]=l[h]),m=p[m],j.set(B,m)):i[h]();for(m=S;m<d;m++)m in f?(r[m]=f[m],i[m]=b[m],l&&(l[m]=v[m],l[m](m))):r[m]=tt(y);r=r.slice(0,o=d),a=u.slice(0)}return r});function y(j){if(i[m]=j,l){const[p,f]=we(m);return l[m]=f,s(u[m],p)}return s(u[m])}}}function Jo(e,s,n={}){let a=[],r=[],i=[],o=[],l=0,u;return _t(()=>Ds(i)),()=>{const d=e()||[],h=d.length;return d[Tn],Te(()=>{if(h===0)return l!==0&&(Ds(i),i=[],a=[],r=[],l=0,o=[]),n.fallback&&(a=[on],r[0]=tt(y=>(i[0]=y,n.fallback())),l=1),r;for(a[0]===on&&(i[0](),i=[],a=[],r=[],l=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?o[u](()=>d[u]):u>=a.length&&(r[u]=tt(m));for(;u<a.length;u++)i[u]();return l=o.length=i.length=h,a=d.slice(0),r=r.slice(0,l)});function m(y){i[u]=y;const[j,p]=we(d[u]);return o[u]=p,s(j,u)}}}function In(e,s){return Te(()=>e(s||{}))}function ys(){return!0}var cn={get(e,s,n){return s===As?n:e.get(s)},has(e,s){return s===As?!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 Zs(e){return(e=typeof e=="function"?e():e)?e:{}}function Yo(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function Dn(...e){let s=!1;for(let o=0;o<e.length;o++){const l=e[o];s=s||!!l&&As in l,e[o]=typeof l=="function"?(s=!0,Ee(l)):l}if(Ja&&s)return new Proxy({get(o){for(let l=e.length-1;l>=0;l--){const u=Zs(e[l])[o];if(u!==void 0)return u}},has(o){for(let l=e.length-1;l>=0;l--)if(o in Zs(e[l]))return!0;return!1},keys(){const o=[];for(let l=0;l<e.length;l++)o.push(...Object.keys(Zs(e[l])));return[...new Set(o)]}},cn);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 d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const m=Object.getOwnPropertyDescriptor(l,h);if(!a[h])a[h]=m.get?{enumerable:!0,configurable:!0,get:Yo.bind(n[h]=[m.get.bind(l)])}:m.value!==void 0?m:void 0;else{const y=n[h];y&&(m.get?y.push(m.get.bind(l)):m.value!==void 0&&y.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 lr(e,...s){if(Ja&&As 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)}},cn));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))}},cn)),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 d of s)d.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 or(e){let s,n;const a=r=>{const i=ae.context;if(i){const[l,u]=we();ae.count||(ae.count=0),ae.count++,(n||(n=e())).then(d=>{!ae.done&&Rt(i),ae.count--,u(()=>d.default),Rt()}),s=l}else if(!s){const[l]=Oo(()=>(n||(n=e())).then(u=>u.default));s=l}let o;return Ee(()=>(o=s())?Te(()=>{if(!i||ae.done)return o(r);const l=ae.context;Rt(i);const u=o(r);return Rt(l),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Xo=0;function Zo(){return ae.context?ae.getNextContextId():`cl-${Xo++}`}var cr=e=>`Stale read from <${e}>.`;function ec(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ee(Wo(()=>e.each,e.children,s||void 0))}function tc(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ee(Jo(()=>e.each,e.children,s||void 0))}function sc(e){const s=e.keyed,n=Ee(()=>e.when,void 0,void 0),a=s?n:Ee(n,void 0,{equals:(r,i)=>!r==!i});return Ee(()=>{const r=a();if(r){const i=e.children;return typeof i=="function"&&i.length>0?Te(()=>i(s?r:()=>{if(!Te(a))throw cr("Show");return n()})):i}return e.fallback},void 0,void 0)}function nc(e){const s=sr(()=>e.children),n=Ee(()=>{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],d=i,h=Ee(()=>d()?void 0:u.when,void 0,void 0),m=u.keyed?h:Ee(h,void 0,{equals:(y,j)=>!y==!j});i=()=>d()||(m()?[l,h,u]:void 0)}return i});return Ee(()=>{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 d;if(((d=Te(n)())==null?void 0:d[0])!==r)throw cr("Match");return i()})):l},void 0,void 0)}function ac(e){return e}var rc=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","hidden","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected"],ic=new Set(["className","value","readOnly","noValidate","formNoValidate","isMap","noModule","playsInline",...rc]),lc=new Set(["innerHTML","textContent","innerText","children"]),oc=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),cc=Object.assign(Object.create(null),{class:"className",novalidate:{$:"noValidate",FORM:1},formnovalidate:{$:"formNoValidate",BUTTON:1,INPUT:1},ismap:{$:"isMap",IMG:1},nomodule:{$:"noModule",SCRIPT:1},playsinline:{$:"playsInline",VIDEO:1},readonly:{$:"readOnly",INPUT:1,TEXTAREA:1}});function uc(e,s){const n=cc[e];return typeof n=="object"?n[s]?n.$:void 0:n}var dc=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),hc=new Set(["altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","hkern","image","line","linearGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tref","tspan","use","view","vkern"]),mc={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},fc=e=>Ee(()=>e());function xc(e,s,n){let a=n.length,r=s.length,i=a,o=0,l=0,u=s[r-1].nextSibling,d=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 h=i<a?l?n[l-1].nextSibling:n[i-l]:u;for(;l<i;)e.insertBefore(n[l++],h)}else if(i===l)for(;o<r;)(!d||!d.has(s[o]))&&s[o].remove(),o++;else if(s[o]===n[i-1]&&n[l]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[l++],s[o++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let m=l;for(;m<i;)d.set(n[m],m++)}const h=d.get(s[o]);if(h!=null)if(l<h&&h<i){let m=o,y=1,j;for(;++m<r&&m<i&&!((j=d.get(s[m]))==null||j!==h+y);)y++;if(y>h-l){const p=s[o];for(;l<h;)e.insertBefore(n[l++],p)}else e.replaceChild(n[l++],s[o++])}else o++;else s[o++].remove()}}}var Vt="_$DX_DELEGATE";function ur(e,s,n,a={}){let r;return tt(i=>{r=i,s===document?e():Ls(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function gc(e,s,n,a){let r;const i=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},o=()=>(r||(r=i())).cloneNode(!0);return o.cloneNode=o,o}function dr(e,s=window.document){const n=s[Vt]||(s[Vt]=new Set);for(let a=0,r=e.length;a<r;a++){const i=e[a];n.has(i)||(n.add(i),s.addEventListener(i,gr))}}function pc(e=window.document){if(e[Vt]){for(let s of e[Vt].keys())e.removeEventListener(s,gr);delete e[Vt]}}function _s(e,s,n){dt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function yc(e,s,n,a){dt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function jc(e,s,n){dt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function hr(e,s){dt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function mr(e,s,n,a){if(a)Array.isArray(n)?(e[`$$${s}`]=n[0],e[`$$${s}Data`]=n[1]):e[`$$${s}`]=n;else if(Array.isArray(n)){const r=n[0];e.addEventListener(s,n[0]=i=>r.call(e,n[1],i))}else e.addEventListener(s,n,typeof n!="function"&&n)}function vc(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,o;for(i=0,o=r.length;i<o;i++){const l=r[i];!l||l==="undefined"||s[l]||(Qn(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||(Qn(e,l,!0),n[l]=u)}return n}function bc(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 fr(e,s={},n,a){const r={};return a||st(()=>r.children=Qt(e,s.children,r.children)),st(()=>typeof s.ref=="function"&&xr(s.ref,e)),st(()=>wc(e,s,n,!0,r,!0)),r}function xr(e,s,n){return Te(()=>e(s,n))}function Ls(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Qt(e,s,a,n);st(r=>Qt(e,s(),r,n),a)}function wc(e,s,n,a,r={},i=!1){s||(s={});for(const o in r)if(!(o in s)){if(o==="children")continue;r[o]=Wn(e,o,null,r[o],n,i,s)}for(const o in s){if(o==="children")continue;const l=s[o];r[o]=Wn(e,o,l,r[o],n,i,s)}}function Nc(e){let s,n;return!dt()||!(s=ae.registry.get(n=Ec()))?e():(ae.completed&&ae.completed.add(s),ae.registry.delete(n),s)}function dt(e){return!!ae.context&&!ae.done&&(!e||e.isConnected)}function Sc(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Qn(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 Wn(e,s,n,a,r,i,o){let l,u,d,h,m;if(s==="style")return bc(e,n,a);if(s==="classList")return vc(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const y=s.slice(3);a&&e.removeEventListener(y,a,typeof a!="function"&&a),n&&e.addEventListener(y,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const y=s.slice(10);a&&e.removeEventListener(y,a,!0),n&&e.addEventListener(y,n,!0)}else if(s.slice(0,2)==="on"){const y=s.slice(2).toLowerCase(),j=dc.has(y);if(!j&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(y,p)}(j||n)&&(mr(e,y,n,j),j&&dr([y]))}else if(s.slice(0,5)==="attr:")_s(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")jc(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(d=lc.has(s))||!r&&((h=uc(s,e.tagName))||(u=ic.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"?hr(e,n):l&&!u&&!d?e[Sc(s)]=n:e[h||s]=n}else{const y=r&&s.indexOf(":")>-1&&mc[s.split(":")[0]];y?yc(e,y,s,n):_s(e,oc[s]||s,n)}return n}function gr(e){if(ae.registry&&ae.events&&ae.events.find(([u,d])=>d===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 d=s[`${n}Data`];if(d!==void 0?u.call(s,d,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}}),ae.registry&&!ae.done&&(ae.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!o());d++){if(s._$host){s=s._$host,l();break}if(s.parentNode===r)break}}else l();i(a)}function Qt(e,s,n,a,r){const i=dt(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const h=n[d];h.nodeType===8&&h.data.slice(0,2)==="!$"?h.remove():u.push(h)}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=Qt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(un(u,s,n,r))return st(()=>n=Qt(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let h=u[0];if(h.parentNode!==e)return n;const m=[h];for(;(h=h.nextSibling)!==a;)m.push(h);return n=m}if(u.length===0){if(n=ft(e,n,a),l)return n}else d?n.length===0?Jn(e,u,a):xc(e,n,u):(n&&ft(e),Jn(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 un(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],d;if(!(l==null||l===!0||l===!1))if((d=typeof l)=="object"&&l.nodeType)e.push(l);else if(Array.isArray(l))r=un(e,l,u)||r;else if(d==="function")if(a){for(;typeof l=="function";)l=l();r=un(e,Array.isArray(l)?l:[l],Array.isArray(u)?u:[u])||r}else e.push(l),r=!0;else{const h=String(l);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function Jn(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 Ec(){return ae.getNextContextId()}var Cc="http://www.w3.org/2000/svg";function pr(e,s=!1){return s?document.createElementNS(Cc,e):document.createElement(e)}function Ac(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Hn();let i,o=!!ae.context;return kn(()=>{o&&(Hn().user=o=!1),i||(i=tr(r,()=>Ee(()=>e.children)));const l=a();if(l instanceof HTMLHeadElement){const[u,d]=we(!1),h=()=>d(!0);tt(m=>Ls(l,()=>u()?m():i(),null)),_t(h)}else{const u=pr(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),Ls(d,i),l.appendChild(u),e.ref&&e.ref(u),_t(()=>l.removeChild(u))}},void 0,{render:!o}),n}function Tc(e,s){const n=Ee(e);return Ee(()=>{const a=n();switch(typeof a){case"function":return Te(()=>a(s));case"string":const r=hc.has(a),i=ae.context?Nc():pr(a,r);return fr(i,s,r),i}})}function kc(e){const[,s]=lr(e,["component"]);return Tc(()=>e.component,s)}var Pc=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,s){this.keyToValue.set(e,s),this.valueToKey.set(s,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},yr=class{constructor(e){this.generateIdentifier=e,this.kv=new Pc}register(e,s){this.kv.getByValue(e)||(s||(s=this.generateIdentifier(e)),this.kv.set(s,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},Ic=class extends yr{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,s){typeof s=="object"?(s.allowProps&&this.classToAllowedProps.set(e,s.allowProps),super.register(e,s.identifier)):super.register(e,s)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function Dc(e){if("values"in Object)return Object.values(e);const s=[];for(const n in e)e.hasOwnProperty(n)&&s.push(e[n]);return s}function _c(e,s){const n=Dc(e);if("find"in n)return n.find(s);const a=n;for(let r=0;r<a.length;r++){const i=a[r];if(s(i))return i}}function Lt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Ns(e,s){return e.indexOf(s)!==-1}function Yn(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Lc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return _c(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Bc=e=>Object.prototype.toString.call(e).slice(8,-1),jr=e=>typeof e>"u",Oc=e=>e===null,Wt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,dn=e=>Wt(e)&&Object.keys(e).length===0,nt=e=>Array.isArray(e),Mc=e=>typeof e=="string",Rc=e=>typeof e=="number"&&!isNaN(e),Gc=e=>typeof e=="boolean",Uc=e=>e instanceof RegExp,Jt=e=>e instanceof Map,Yt=e=>e instanceof Set,vr=e=>Bc(e)==="Symbol",Fc=e=>e instanceof Date&&!isNaN(e.valueOf()),qc=e=>e instanceof Error,Xn=e=>typeof e=="number"&&isNaN(e),zc=e=>Gc(e)||Oc(e)||jr(e)||Rc(e)||Mc(e)||vr(e),$c=e=>typeof e=="bigint",Vc=e=>e===1/0||e===-1/0,Kc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Hc=e=>e instanceof URL,br=e=>e.replace(/\./g,"\\."),en=e=>e.map(String).map(br).join("."),Kt=e=>{const s=[];let n="";for(let r=0;r<e.length;r++){let i=e.charAt(r);if(i==="\\"&&e.charAt(r+1)==="."){n+=".",r++;continue}if(i==="."){s.push(n),n="";continue}n+=i}const a=n;return s.push(a),s};function ze(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var wr=[ze(jr,"undefined",()=>null,()=>{}),ze($c,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),ze(Fc,"Date",e=>e.toISOString(),e=>new Date(e)),ze(qc,"Error",(e,s)=>{const n={name:e.name,message:e.message};return s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n},(e,s)=>{const n=new Error(e.message);return n.name=e.name,n.stack=e.stack,s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n}),ze(Uc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),ze(Yt,"set",e=>[...e.values()],e=>new Set(e)),ze(Jt,"map",e=>[...e.entries()],e=>new Map(e)),ze(e=>Xn(e)||Vc(e),"number",e=>Xn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),ze(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),ze(Hc,"URL",e=>e.toString(),e=>new URL(e))];function qs(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Nr=qs((e,s)=>vr(e)?!!s.symbolRegistry.getIdentifier(e):!1,(e,s)=>["symbol",s.symbolRegistry.getIdentifier(e)],e=>e.description,(e,s,n)=>{const a=n.symbolRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown symbol");return a}),Qc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),Sr=qs(Kc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Qc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function Er(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var Cr=qs(Er,(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)}),Ar=qs((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Wc=[Cr,Nr,Ar,Sr],Zn=(e,s)=>{const n=Yn(Wc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=Yn(wr,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},Tr={};wr.forEach(e=>{Tr[e.annotation]=e});var Jc=(e,s,n)=>{if(nt(s))switch(s[0]){case"symbol":return Nr.untransform(e,s,n);case"class":return Cr.untransform(e,s,n);case"custom":return Ar.untransform(e,s,n);case"typed-array":return Sr.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=Tr[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 kr(e){if(Ns(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Ns(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Ns(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Yc=(e,s)=>{kr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Yt(e))e=gt(e,+a);else if(Jt(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},hn=(e,s,n)=>{if(kr(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(Wt(a))a=a[o];else if(Yt(a)){const l=+o;a=gt(a,l)}else if(Jt(a)){if(i===s.length-2)break;const u=+o,d=+s[++i]==0?"key":"value",h=gt(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(nt(a)?a[+r]=n(a[+r]):Wt(a)&&(a[r]=n(a[r])),Yt(a)){const i=gt(a,+r),o=n(i);i!==o&&(a.delete(i),a.add(o))}if(Jt(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 mn(e,s,n=[]){if(!e)return;if(!nt(e)){Lt(e,(i,o)=>mn(i,s,[...n,...Kt(o)]));return}const[a,r]=e;r&&Lt(r,(i,o)=>{mn(i,s,[...n,...Kt(o)])}),s(a,n)}function Xc(e,s,n){return mn(s,(a,r)=>{e=hn(e,r,i=>Jc(i,a,n))}),e}function Zc(e,s){function n(a,r){const i=Yc(e,Kt(r));a.map(Kt).forEach(o=>{e=hn(e,o,()=>i)})}if(nt(s)){const[a,r]=s;a.forEach(i=>{e=hn(e,Kt(i),()=>e)}),r&&Lt(r,n)}else Lt(s,n);return e}var eu=(e,s)=>Wt(e)||nt(e)||Jt(e)||Yt(e)||Er(e,s);function tu(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function su(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(l=>l.map(String)).sort((l,u)=>l.length-u.length));const[i,...o]=r;i.length===0?a=o.map(en):n[en(i)]=o.map(en)}),a?dn(n)?[a]:[a,n]:dn(n)?void 0:n}var Pr=(e,s,n,a,r=[],i=[],o=new Map)=>{const l=zc(e);if(!l){tu(e,r,s);const j=o.get(e);if(j)return a?{transformedValue:null}:j}if(!eu(e,n)){const j=Zn(e,n),p=j?{transformedValue:j.value,annotations:[j.type]}:{transformedValue:e};return l||o.set(e,p),p}if(Ns(i,e))return{transformedValue:null};const u=Zn(e,n),d=(u==null?void 0:u.value)??e,h=nt(d)?[]:{},m={};Lt(d,(j,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const f=Pr(j,s,n,a,[...r,p],[...i,e],o);h[p]=f.transformedValue,nt(f.annotations)?m[p]=f.annotations:Wt(f.annotations)&&Lt(f.annotations,(b,v)=>{m[br(p)+"."+v]=b})});const y=dn(m)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,m]:m};return l||o.set(e,y),y};function Ir(e){return Object.prototype.toString.call(e).slice(8,-1)}function ea(e){return Ir(e)==="Array"}function nu(e){if(Ir(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function au(e,s,n,a,r){const i={}.propertyIsEnumerable.call(a,s)?"enumerable":"nonenumerable";i==="enumerable"&&(e[s]=n),r&&i==="nonenumerable"&&Object.defineProperty(e,s,{value:n,enumerable:!1,writable:!0,configurable:!0})}function fn(e,s={}){if(ea(e))return e.map(r=>fn(r,s));if(!nu(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(ea(s.props)&&!s.props.includes(i))return r;const o=e[i],l=fn(o,s);return au(r,i,l,e,s.nonenumerable),r},{})}var pe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Ic,this.symbolRegistry=new yr(s=>s.description??""),this.customTransformerRegistry=new Lc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Pr(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=su(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=fn(s);return n!=null&&n.values&&(a=Xc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Zc(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};pe.defaultInstance=new pe;pe.serialize=pe.defaultInstance.serialize.bind(pe.defaultInstance);pe.deserialize=pe.defaultInstance.deserialize.bind(pe.defaultInstance);pe.stringify=pe.defaultInstance.stringify.bind(pe.defaultInstance);pe.parse=pe.defaultInstance.parse.bind(pe.defaultInstance);pe.registerClass=pe.defaultInstance.registerClass.bind(pe.defaultInstance);pe.registerSymbol=pe.defaultInstance.registerSymbol.bind(pe.defaultInstance);pe.registerCustom=pe.defaultInstance.registerCustom.bind(pe.defaultInstance);pe.allowErrorProps=pe.defaultInstance.allowErrorProps.bind(pe.defaultInstance);var Dr=pe.serialize,ru=pe.stringify;function iu(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function lu(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function ou({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function cu({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function uu(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var du=(e,s=!1)=>{const{json:n}=Dr(e);return JSON.stringify(n,null,s?2:void 0)},js=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,hu=(e,s)=>e.queryHash.localeCompare(s.queryHash),_r=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,mu=(e,s)=>js(e)===js(s)?_r(e,s):js(e)>js(s)?1:-1,fu={status:mu,"query hash":hu,"last updated":_r},vs=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Lr=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,xu=(e,s)=>vs(e)===vs(s)?Lr(e,s):vs(e)>vs(s)?1:-1,gu={status:xu,"last updated":Lr},pu=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),yu=()=>{const[e,s]=we("dark");return er(()=>{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},Gt=(e,s,n)=>{if(s.length===0)return n;if(e instanceof Map){const a=new Map(e);if(s.length===1)return a.set(s[0],n),a;const[r,...i]=s;return a.set(r,Gt(a.get(r),i,n)),a}if(e instanceof Set){const a=Gt(Array.from(e),s,n);return new Set(a)}if(Array.isArray(e)){const a=[...e];if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Gt(a[r],i,n),a}if(e instanceof Object){const a={...e};if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Gt(a[r],i,n),a}return e},Ut=(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,Ut(n.get(a),r)),n}if(e instanceof Set){const n=Ut(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]=Ut(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]=Ut(n[a],r),n}return e},Br=(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,Xt,Zt,es,it,ts,yt,jt,vt,bt,wt,ss,Nt,ns,ia,ju=(ia=class{constructor(e){he(this,pt);he(this,Xt);he(this,Zt);he(this,es);he(this,it,!1);he(this,ts);he(this,yt);he(this,jt);he(this,vt);he(this,bt);he(this,wt);he(this,ss);he(this,Nt);he(this,ns);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:d,shadowDOMTarget:h,hideDisabledQueries:m}=e;ue(this,pt,we(s)),ue(this,Zt,n),ue(this,es,a),ue(this,Xt,r),ue(this,ts,d),ue(this,yt,h),ue(this,jt,we(i)),ue(this,vt,we(o)),ue(this,bt,we(l)),ue(this,wt,we(u)),ue(this,ss,we(m))}setButtonPosition(e){te(this,jt)[1](e)}setPosition(e){te(this,vt)[1](e)}setInitialIsOpen(e){te(this,bt)[1](e)}setErrorTypes(e){te(this,wt)[1](e)}setClient(e){te(this,pt)[1](e)}mount(e){if(te(this,it))throw new Error("Devtools is already mounted");const s=ur(()=>{const n=this,[a]=te(this,jt),[r]=te(this,vt),[i]=te(this,bt),[o]=te(this,wt),[l]=te(this,ss),[u]=te(this,pt);let d;return te(this,Nt)?d=te(this,Nt):(d=or(()=>Promise.resolve().then(()=>require("./NCMVHL6D-CQOgtexk.cjs"))),ue(this,Nt,d)),Br(te(this,ts),te(this,yt)),In(d,Dn({get queryFlavor(){return te(n,Zt)},get version(){return te(n,es)},get onlineManager(){return te(n,Xt)},get shadowDOMTarget(){return te(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);ue(this,it,!0),ue(this,ns,s)}unmount(){var e;if(!te(this,it))throw new Error("Devtools is not mounted");(e=te(this,ns))==null||e.call(this),ue(this,it,!1)}},pt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,es=new WeakMap,it=new WeakMap,ts=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,ss=new WeakMap,Nt=new WeakMap,ns=new WeakMap,ia),St,as,rs,is,lt,ls,Et,Ct,At,Tt,kt,os,Pt,It,cs,la,vu=(la=class{constructor(e){he(this,St);he(this,as);he(this,rs);he(this,is);he(this,lt,!1);he(this,ls);he(this,Et);he(this,Ct);he(this,At);he(this,Tt);he(this,kt);he(this,os);he(this,Pt);he(this,It);he(this,cs);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:m,hideDisabledQueries:y}=e;ue(this,St,we(s)),ue(this,rs,n),ue(this,is,a),ue(this,as,r),ue(this,ls,d),ue(this,Et,h),ue(this,Ct,we(i)),ue(this,At,we(o)),ue(this,Tt,we(l)),ue(this,kt,we(u)),ue(this,os,we(y)),ue(this,Pt,we(m))}setButtonPosition(e){te(this,Ct)[1](e)}setPosition(e){te(this,At)[1](e)}setInitialIsOpen(e){te(this,Tt)[1](e)}setErrorTypes(e){te(this,kt)[1](e)}setClient(e){te(this,St)[1](e)}setOnClose(e){te(this,Pt)[1](()=>e)}mount(e){if(te(this,lt))throw new Error("Devtools is already mounted");const s=ur(()=>{const n=this,[a]=te(this,Ct),[r]=te(this,At),[i]=te(this,Tt),[o]=te(this,kt),[l]=te(this,os),[u]=te(this,St),[d]=te(this,Pt);let h;return te(this,It)?h=te(this,It):(h=or(()=>Promise.resolve().then(()=>require("./2AITGKQY-BEGIO0Jl.cjs"))),ue(this,It,h)),Br(te(this,ls),te(this,Et)),In(h,Dn({get queryFlavor(){return te(n,rs)},get version(){return te(n,is)},get onlineManager(){return te(n,as)},get shadowDOMTarget(){return te(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 d()}}))},e);ue(this,lt,!0),ue(this,cs,s)}unmount(){var e;if(!te(this,lt))throw new Error("Devtools is not mounted");(e=te(this,cs))==null||e.call(this),ue(this,lt,!1)}},St=new WeakMap,as=new WeakMap,rs=new WeakMap,is=new WeakMap,lt=new WeakMap,ls=new WeakMap,Et=new WeakMap,Ct=new WeakMap,At=new WeakMap,Tt=new WeakMap,kt=new WeakMap,os=new WeakMap,Pt=new WeakMap,It=new WeakMap,cs=new WeakMap,la);function bu(e){const s=R.useQueryClient(e.client),n=je.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u,hideDisabledQueries:d}=e,[h]=je.useState(new ju({client:s,queryFlavor:"React Query",version:"5",onlineManager:R.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u,hideDisabledQueries:d}));return je.useEffect(()=>{h.setClient(s)},[s,h]),je.useEffect(()=>{a&&h.setButtonPosition(a)},[a,h]),je.useEffect(()=>{r&&h.setPosition(r)},[r,h]),je.useEffect(()=>{h.setInitialIsOpen(i||!1)},[i,h]),je.useEffect(()=>{h.setErrorTypes(o||[])},[o,h]),je.useEffect(()=>(n.current&&h.mount(n.current),()=>{h.unmount()}),[h]),t.jsx("div",{dir:"ltr",className:"tsqd-parent-container",ref:n})}function wu(e){const s=R.useQueryClient(e.client),n=je.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i,hideDisabledQueries:o}=e,[l]=je.useState(new vu({client:s,queryFlavor:"React Query",version:"5",onlineManager:R.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose,hideDisabledQueries:o}));return je.useEffect(()=>{l.setClient(s)},[s,l]),je.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),je.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),je.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 ta=process.env.NODE_ENV!=="development"?function(){return null}:bu;process.env.NODE_ENV;const Nu=()=>{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"})},Su=()=>{const e=re(),s=X();return R.useQuery({queryKey:[_.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:_.GET_COLLECTIONS})})},Eu=()=>{const{data:e}=Ce(),{data:s}=We(),{data:n}=Ve(),a=re(),r=X(),i=x.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return R.useMutation({mutationFn:async({block:o})=>r(a,{action:_.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}}})})},Or=()=>{const e=En();return x.useCallback(({pageId:s})=>{e(s)},[e])},sa={},Ss=(e,s)=>{g.has(sa,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),g.set(sa,e,{id:e,...s})},Cu=x.createContext(null),tn={didCatch:!1,error:null};class Au extends x.Component{constructor(s){super(s),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=tn}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(tn)}}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&&Tu(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(tn)}}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=x.createElement(a,u);else if(r!==void 0)l=r;else throw o}return x.createElement(Cu.Provider,{value:{didCatch:i,error:o,resetErrorBoundary:this.resetErrorBoundary}},l)}}function Tu(){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 ku=()=>{const e=us(),s=R.useQueryClient(),n=X();return R.useMutation({mutationFn:async a=>{const r=a.map(async o=>n(e,{action:_.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:[_.GET_ASSETS]});const i=a==null?void 0:a.length;J.toast.success(`${i===1?"Asset":i+" Assets"} uploaded successfully`)}},onError:()=>{J.toast.error("Failed to upload asset")}})},Pu=()=>{const e=us(),s=R.useQueryClient(),n=X();return R.useMutation({mutationFn:async a=>n(e,{action:_.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[_.GET_ASSETS]}),J.toast.success("Asset deleted successfully")},onError:()=>{J.toast.error("Failed to delete asset")}})},Iu=()=>{const e=us(),s=R.useQueryClient(),n=X();return R.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[_.GET_ASSETS]}),J.toast.success("Asset updated successfully")},onError:()=>{J.toast.error("Failed to update asset")}})};function Du({currentPage:e,totalPages:s,onPageChange:n,pageRangeDisplayed:a=3,showPageInput:r=!0,className:i=""}){const[o,l]=x.useState(String(e)),u=x.useMemo(()=>{const p=Math.floor(a/2);let f=Math.max(1,e-p),b=Math.min(s,e+p);b-f+1<a&&(f===1?b=Math.min(s,f+a-1):b===s&&(f=Math.max(1,b-a+1)));const v=[];f>1&&(v.push(1),f>2&&v.push("..."));for(let S=f;S<=b;S++)v.push(S);return b<s&&(b<s-1&&v.push("..."),v.push(s)),v},[e,s,a]),d=p=>{p!==e&&p>=1&&p<=s&&(n(p),l(String(p)))},h=()=>{e>1&&d(e-1)},m=()=>{e<s&&d(e+1)},y=()=>{const p=Number(o);!isNaN(p)&&p>=1&&p<=s&&d(p)},j=p=>{p.key==="Enter"&&y()};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:h,disabled:e===1,className:"px-2 py-1 text-sm hover:bg-gray-50",children:[t.jsx(N.ChevronLeft,{className:" h-4 w-4"}),"Previous"]}),t.jsx("div",{className:"flex items-center gap-2",children:u.map((p,f)=>{if(p==="...")return t.jsx("span",{className:"px-2 text-muted-foreground",children:"..."},`ellipsis-${f}`);const b=p,v=b===e;return t.jsx(c.Button,{variant:v?"default":"outline",size:"sm",onClick:()=>d(b),className:v?"border-blue-600 bg-blue-600 px-3 py-1 text-sm text-white":"border px-3 py-1 text-sm hover:bg-gray-50 hover:text-black",children:b},b)})}),t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:m,disabled:e===s,className:"px-2 py-1 text-sm hover:bg-gray-50",children:["Next",t.jsx(N.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:p=>{const f=p.target.value.replace(/[^\d]/g,"");l(f)},onKeyDown:j,className:"h-8 w-16 px-2 py-1"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:y,disabled:o===""||Number(o)<1||Number(o)>s,children:"Go"})]})]})}const _u=(e={})=>{const s=us(),n=X(),{search:a,page:r=1,limit:i=30}=e;return R.useQuery({queryKey:[_.GET_ASSETS,a,r,i],queryFn:async()=>{const o=await n(s,{action:_.GET_ASSETS,data:{search:a,page:r,limit:i}});return o.page=r,o.limit=i,o},staleTime:1e3*60*5,retry:1})},Lu=e=>{const s=us(),n=X();return R.useQuery({queryKey:[_.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:_.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Bu(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function na(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 aa(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 Ou=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,y,j;const{data:i,isLoading:o,isError:l}=Lu(e||""),[u,d]=x.useState(""),h=async(p,f)=>{try{await navigator.clipboard.writeText(p),J.toast.success(`${f} copied to clipboard`)}catch(b){J.toast.error(`Failed to copy ${f}`,{description:b==null?void 0:b.message})}};return x.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),o?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(N.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(N.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(N.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:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(N.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(N.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:((y=i.metadata)==null?void 0:y.format)||i.type,capitalize:!0},{label:"Size",value:Bu(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:na(i.createdAt)},{label:"Updated",value:na(((j=i.metadata)==null?void 0:j.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(p.value,p.label),children:t.jsx(N.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,f)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},f))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>d(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!aa(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!aa(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},Mu=x.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs"))),Ru=25*1024*1024,Gu=({isUpdatingAsset:e,allowedTypes:s,uploadAssets:n,isUploadingAsset:a,onUploaded:r})=>{const[i,o]=x.useState(()=>{const j=localStorage.getItem("chai_optimize_images");return j!==null?j==="true":!0});x.useEffect(()=>{localStorage.setItem("chai_optimize_images",i.toString())},[i]);const l=e||a,u=x.useCallback(async j=>{try{const p=j;if(!p.every(S=>S.type.startsWith("image/")))return J.toast.error("Invalid file type. Please upload a valid file."),Promise.reject(new Error("Invalid file type"));const f=p.map(async S=>{let P=S;return S.type.startsWith("image/")&&(P=await Ea(S)),new Promise((z,B)=>{const O=new FileReader;O.readAsDataURL(P),O.onload=async()=>{z({file:O.result,folderId:void 0,name:S.name,optimize:i})},O.onerror=()=>B(null)})}),b=await Promise.all(f),v=await n(b);return(v==null?void 0:v.length)===1&&r(v[0]),v}catch(p){return Promise.reject(p)}},[n,i,r]),d=j=>{const p=[];let f=0;return j.forEach(b=>{b.size>Ru?f++:p.push(b)}),f>0&&J.toast.error(`${f===1&&j.length===1?"File":f+(f===1?" file":" files")} exceed the maximum size limit of 10MB.`),g.isEmpty(p)?[]:u(p)},{getRootProps:h,getInputProps:m,isDragActive:y}=zr.useDropzone({onDrop:d,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",{...h(),className:Q.mergeClasses("flex h-max w-full cursor-pointer flex-col justify-center rounded-lg text-center",l?"items-start":"items-center",y?"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(N.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(N.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:j=>{o(j)},onClick:j=>{j.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(N.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 Mr({close:e,onSelect:s,mode:n="image",assetId:a}){const o=x.useMemo(()=>[n],[n]),[l,u]=x.useState(null),[d,h]=x.useState(null),[m,y]=x.useState(null),[j,p]=x.useState({show:!1,file:""}),[f,b]=x.useState(!1),[v,S]=x.useState(a?"details":"grid"),[P,z]=x.useState(""),[B,O]=x.useState(""),[W,D]=x.useState(1),[F]=x.useState(30),[T,$]=x.useState([]);x.useEffect(()=>{a&&(u(a),S("details"))},[a]),x.useEffect(()=>{const k=setTimeout(()=>{z(B),D(1)},300);return()=>clearTimeout(k)},[B]);const{data:K,isLoading:V}=_u({search:P.toLowerCase().trim(),page:W,limit:F}),Y=(K==null?void 0:K.assets)||[],L=(K==null?void 0:K.total)||0,me=Math.ceil(L/F);x.useEffect(()=>{V||me<=0||D(k=>k>me?me:k<1?1:k)},[V,me]);const be=(Y==null?void 0:Y.length)>0,{mutate:Ae}=Pu(),{mutateAsync:ye,isPending:E}=ku(),{mutate:w,isPending:I}=Iu(),C=x.useCallback(k=>{const ne=Math.min(Math.max(1,k),Math.max(1,me));ne!==W&&D(ne)},[me,W]),M=k=>{O(k.target.value)},G=x.useCallback(k=>{$(ne=>g.find(ne,{id:k.id})?[]:[k])},[!1]),U=x.useCallback(()=>{$([])},[]),q=k=>{(k==null?void 0:k.length)!==0&&(s(g.pick(g.first(k||T),["id","url","width","height","description"])),e())},ee=async k=>{h(k)},ie=async()=>{d&&(y(d==null?void 0:d.id),await Ae(d.id,{onSuccess:()=>{y(null),h(null)},onError:()=>{y(null)}}),h(null))},H=k=>{u(k.id),S("details")},se=async(k,ne)=>{try{const Se=localStorage.getItem("chai_optimize_images")!=="false";ne?(await ye([{file:k,folderId:void 0,name:j.name||"",optimize:Se}]),p({show:!1,file:""})):(await w({id:j.id||"",file:k}),p({show:!1,file:""}))}catch(Se){console.error("Error saving edited image:",Se)}},de=x.useCallback(k=>{$([k])},[]),fe=x.useCallback(k=>{C(k)},[C]);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"}),v==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Gu,{maxFileSize:10,allowedTypes:o,uploadAssets:ye,isUpdatingAsset:I,isUploadingAsset:E,onUploaded:de}),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(N.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${B.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:M,value:B,className:"pl-8"})]}),T.length>0?t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("div",{className:"flex items-center gap-2",children:[T.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:()=>q(T),disabled:T.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:V?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"})]}):!V&&!be?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(N.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:Y==null?void 0:Y.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",T.some(ne=>ne.id===k.id)?"border-blue-500":"hover:border-black/90",m&&(d==null?void 0:d.id)===k.id?"pointer-events-none opacity-50":"",m===k.id?"pointer-events-none opacity-50":""),onClick:()=>G(k),onDoubleClick:()=>q([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(N.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 ${T.some(ne=>ne.id===k.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex h-full items-center justify-center",children:[t.jsx(N.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:sn((k==null?void 0:k.size)||0)})})]}),!T.some(ne=>ne.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:ne=>{ne.stopPropagation(),H(k)},children:t.jsx(N.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:ne=>{ne.stopPropagation(),navigator.clipboard.writeText(k.url),J.toast.success("Asset URL copied to clipboard")},children:t.jsx(N.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:ne=>{ne.stopPropagation(),p({id:k.id,show:!0,file:k.url,name:k.name})},children:t.jsx(N.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:ne=>{ne.stopPropagation(),ee(k)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),T.some(ne=>ne.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(N.Check,{className:"h-3 w-3 text-white",strokeWidth:5})})]},k.id))})}),me>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 border-t bg-white p-4",children:t.jsx(Au,{fallback:t.jsx("div",{className:"text-red-500",children:"Error loading pagination"}),children:t.jsx(Du,{currentPage:W,totalPages:me,onPageChange:fe,pageRangeDisplayed:3,showPageInput:!0})})})]})]}):t.jsx(Ou,{assetId:l||a||"",onBack:()=>{S("grid"),u(null)},onEdit:k=>{p({id:k.id,show:!0,file:k.url,name:k.name})},onSave:async k=>{if(l){b(!0);try{const ne=Y.find(Se=>Se.id===l);ne&&await w(g.merge(ne,{description:k}))}finally{b(!1)}}},isSaving:f})]}),j.show&&t.jsx(x.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Mu,{imageUrl:j.file,onSave:se,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:j.name,isEditing:!!j.id})}),d&&t.jsx(c.Dialog,{open:!!d,onOpenChange:()=>h(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 "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:ie,children:"Delete"})]})]})})]})}const Uu=Object.freeze(Object.defineProperty({__proto__:null,default:Mr},Symbol.toStringTag,{value:"Module"})),Bs=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[o,l]=x.useState(!1),u=()=>{i||l(!0)},d=()=>{l(!1)},h=j=>{const p=Array.isArray(j)?j[0]:j;p!=null&&p.url&&n(g.pick(p,["url","id"])),l(!1)},m=()=>{n({url:"",id:""})},y=(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:[y?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:y?t.jsx(N.X,{className:"h-4 w-4"}):t.jsx(N.Trash2,{className:"h-4 w-4"})}),!y&&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(N.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(N.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:d,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"h-full flex-1 p-4",children:t.jsx(Mr,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Fu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),qu=()=>{const[e,s]=x.useState({logoUrl:"",logoId:"",faviconUrl:"",faviconId:""}),[n,a]=x.useState(!1),r=()=>{a(!0),setTimeout(()=>{a(!1),console.log("Branding settings saved:",e)},1e3)};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Branding Settings"}),t.jsxs("div",{className:"rounded space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Logo"}),t.jsx(Bs,{assetId:e.logoId,assetUrl:e.logoUrl,onChange:i=>{s({...e,logoUrl:i.url,logoId:i.id})},placeholder:"Select logo image",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 200x50px"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Favicon"}),t.jsx(Bs,{assetId:e.faviconId,assetUrl:e.faviconUrl,onChange:i=>{s({...e,faviconUrl:i.url,faviconId:i.id})},placeholder:"Select favicon",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 32x32px"})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:r,disabled:n,className:"w-full",children:n?"Saving...":"Save Branding Settings"})})]})]})},zu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),$u=()=>{const[e,s]=x.useState({contactEmail:"",contactPhone:"",contactAddress:""}),[n,a]=x.useState([]),[r,i]=x.useState({isOpen:!1,platform:"",url:"",customName:""}),[o,l]=x.useState(!1),u=[{value:"facebook",label:"Facebook"},{value:"twitter",label:"Twitter"},{value:"linkedin",label:"LinkedIn"},{value:"instagram",label:"Instagram"},{value:"youtube",label:"YouTube"},{value:"other",label:"Other"}],d=f=>s(b=>({...b,[f.target.name]:f.target.value})),h=()=>{const{platform:f,url:b,customName:v}=r;if(!b.trim()||!f)return;const S=f==="other"?v:f;S.trim()&&(a(P=>[...P,{platform:S,url:b,isCustom:f==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=f=>a(b=>b.filter((v,S)=>S!==f)),y=()=>i({isOpen:!1,platform:"",url:"",customName:""}),j=()=>{l(!0);const f={};n.forEach(v=>{f[v.platform.toLowerCase().replace(/\s+/g,"_")]=v.url});const b={...e,socialLinks:f};setTimeout(()=>{l(!1),console.log("Contact & Social settings saved:",b),s({contactEmail:"",contactPhone:"",contactAddress:""}),a([]),i({isOpen:!1,platform:"",url:"",customName:""})},1e3)},p=e.contactEmail.trim()||e.contactPhone.trim()||e.contactAddress.trim();return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Contact & Social Settings"}),t.jsxs("div",{className:"space-y-4 rounded",children:[t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Email"}),t.jsx("input",{type:"email",name:"contactEmail",value:e.contactEmail,onChange:d,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:d,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:d,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(f=>({...f,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:f=>i(b=>({...b,platform:f.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",children:[t.jsx("option",{value:"",children:"Select platform"}),u.map(f=>t.jsx("option",{value:f.value,children:f.label},f.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:f=>i(b=>({...b,customName:f.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:f=>i(b=>({...b,url:f.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:h,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:y,className:"flex-1",children:"Cancel"})]})]}),n.length>0&&t.jsx("div",{className:"space-y-2",children:n.map((f,b)=>t.jsxs("div",{className:"flex items-center justify-between rounded border p-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-sm font-medium capitalize",children:f.platform}),t.jsx("p",{className:"max-w-xs truncate text-xs text-gray-500",children:f.url})]}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m(b),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},b))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:j,disabled:!p||o,className:"w-full",children:o?"Saving...":"Save Contact & Social Settings"})})]})]})},Vu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),Ku=()=>{const[e,s]=x.useState({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),[n,a]=x.useState([]),[r,i]=x.useState(""),[o,l]=x.useState(!1),u=j=>{const{name:p,value:f}=j.target;s(b=>({...b,[p]:f}))},d=()=>{r.trim()&&(a(j=>[...j,{id:Date.now().toString(),content:r}]),i(""))},h=j=>{a(p=>p.filter(f=>f.id!==j))},m=()=>{l(!0);const j={...e,customTrackingScripts:n.map(p=>p.content)};setTimeout(()=>{l(!1),console.log("Analytics & Tracking settings saved:",j),s({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),a([])},1e3)},y=Object.values(e).some(j=>j.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:j=>i(j.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:d,disabled:!r.trim(),children:"Add Script"})]})]})]}),n.length>0&&t.jsx("div",{className:"mb-3 space-y-2",children:n.map(j=>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:j.content.length>100?`${j.content.substring(0,100)}...`:j.content})}),t.jsx(c.Button,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>h(j.id),children:"Remove"})]},j.id))}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:m,disabled:!y||o,className:"w-full",children:o?"Saving...":"Save Settings"})})]})]})},Hu=()=>{Ss("branding",{label:"Branding",button:Fu,panel:qu}),Ss("contact-social",{label:"Contact & Social",button:zu,panel:$u}),Ss("analytics-tracking",{label:"Analytics & Tracking",button:Vu,panel:Ku})},Qu=x.lazy(()=>Promise.resolve().then(()=>Uu));Nu();$r.loadWebBlocks();Q.registerChaiTopBar(no);Do();Hu();Q.registerChaiMediaManager(Qu);Q.registerChaiSaveToLibrary(ki);const ra=e=>{const s=x.useRef([]),[n]=Ie(),a=n.get("page"),{data:r}=Ce(),{data:i={role:"",permissions:null}}=qa();lo(),xi();const{data:o,isFetching:l}=Sa(),{blocks:u}=io(o),{data:d}=ke(),{mutateAsync:h}=fa(),m=ao(),{onSave:y}=oo(),{getPartialBlocks:j,getPartialBlockBlocks:p}=co(),{mutateAsync:f}=Ii(),[b,v]=x.useState(!1),{data:S}=Ve(),P=Ye(),{data:z}=jn(),{data:B}=Su(),{mutateAsync:O}=Eu(),W=Or();ni(),x.useEffect(()=>{const Y=()=>{document.hidden?v(!0):v(!1)};return window.addEventListener("visibilitychange",Y),()=>window.removeEventListener("visibilitychange",Y)},[]),s.current=u;const D=x.useMemo(()=>{const Y={};return i&&(Y.permissions=g.get(i,"permissions",null),Y.role=g.get(i,"role","user")),Y},[i]),F=x.useCallback(async(Y,L)=>await f({pageType:Y,query:L}),[f]),T=x.useMemo(()=>g.get(S,"theme",{})||{},[S]),{lockingStatus:$,pageLock:K}=Ke(),V=g.isEmpty($)&&(K==null?void 0:K.status)==="editing";return t.jsxs(t.Fragment,{children:[l&&t.jsx(Dt,{children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin text-primary"})}),t.jsx(Q.ChaiBuilderEditor,{gotoPage:W,collections:B??[],getBlockAsyncProps:O,pageExternalData:z,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:l,fallbackLang:P,languages:(S==null?void 0:S.languages)||[],brandingOptions:(S==null?void 0:S.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSave:!b&&V&&(e.autoSave??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:j,blocks:l?[]:u,theme:g.cloneDeep(T),pageTypes:d,searchPageTypeItems:F,askAiCallBack:m,onSave:async({blocks:Y,theme:L,needTranslations:me})=>{if(!a)return!0;s.current=Y;const be=[...Y];return await y({page:a,blocks:be,needTranslations:me}),s.current=be,g.isEqual(L,T)||await h({settings:{theme:L}}),!0},themePanelComponent:Ui,...D}),t.jsxs("div",{children:[t.jsx(yi,{isFetchingPage:l}),t.jsx(ji,{})]})]})},Wu=new R.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Ju=e=>{const{isLoggedIn:s}=Ge(),[,n]=gn(),[a,r]=x.useState(!1);return x.useEffect(()=>(n(g.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","topLeftCorner","onLogout","getAccessToken","supabaseInstance","features"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?g.get(e,"hasReactQueryProvider",!1)===!0?t.jsxs(t.Fragment,{children:[s?t.jsx(ra,{...e}):t.jsx($n,{}),t.jsx(ta,{})]}):t.jsxs(R.QueryClientProvider,{client:Wu,children:[s?t.jsx(ra,{...e}):t.jsx($n,{}),t.jsx(ta,{})]}):t.jsx("div",{})},Yu=()=>{const{savePageAsync:e}=Q.useSavePage(),s=R.useQueryClient();return x.useCallback(async()=>{await e(),s.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]}),s.invalidateQueries({queryKey:[_.GET_BUILDER_PAGE_DATA]})},[e,s])},Xu=()=>{const e=R.useQueryClient();return x.useCallback(()=>{e.clear()},[e])},Zu=()=>{const{logout:e}=Ge(),{getAccessToken:s}=ha();return x.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=Ju;exports.ChaiBuilderPagesRealtime=ba;exports.Dynamic=kc;exports.For=ec;exports.ImagePicker=Bs;exports.Index=tc;exports.LanguageSwitcher=An;exports.Match=ac;exports.NestedPathSelector=He;exports.PermissionChecker=Oe;exports.Portal=Ac;exports.Show=sc;exports.SmartJsonInput=rn;exports.Switch=nc;exports.addEventListener=mr;exports.batch=Mo;exports.className=hr;exports.clearDelegatedEvents=pc;exports.convertRemToPixels=pu;exports.createComponent=In;exports.createComputed=Za;exports.createContext=qo;exports.createEffect=kn;exports.createMemo=Ee;exports.createRenderEffect=st;exports.createRoot=tt;exports.createSignal=we;exports.createUniqueId=Zo;exports.delegateEvents=dr;exports.deleteNestedDataByPath=Ut;exports.displayValue=du;exports.getMutationStatusColor=cu;exports.getPreferredColorScheme=yu;exports.getQueryStatusColor=ou;exports.getQueryStatusColorByLabel=uu;exports.getQueryStatusLabel=iu;exports.getSidedProp=lu;exports.insert=Ls;exports.memo=fc;exports.mergeProps=Dn;exports.mutationSortFns=gu;exports.on=Ro;exports.onCleanup=_t;exports.onMount=er;exports.registerChaiSiteSetting=Ss;exports.registerLoginComponent=mo;exports.serialize=Dr;exports.setAttribute=_s;exports.sortFns=fu;exports.splitProps=lr;exports.spread=fr;exports.stringify=ru;exports.template=gc;exports.untrack=Te;exports.updateNestedDataByPath=Gt;exports.use=xr;exports.useActivePage=We;exports.useBuilderPageData=jn;exports.useChaiAuth=Ge;exports.useChaiFetch=Zu;exports.useChaiUserInfo=Je;exports.useClearAll=Xu;exports.useContext=zo;exports.useCurrentPage=Ce;exports.useFallbackLang=Ye;exports.useFetch=X;exports.useGotoPage=Or;exports.useLanguagePages=Re;exports.usePageTypes=ke;exports.useReloadPage=Yu;exports.useTransition=Fo;exports.useUpdateActivePageMetadata=Va;exports.useUserRoleAndPermissions=qa;exports.useWebsitePages=Bt;exports.useWebsiteSetting=Ve;