@chaibuilder/pages 0.7.2 → 0.7.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.
- package/dist/{B4MFY5CR-DYwDWUG-.cjs → B4MFY5CR-BEIFs0Pr.cjs} +1 -1
- package/dist/{B4MFY5CR-BqG9q9zR.js → B4MFY5CR-DXuFUDsi.js} +1 -1
- package/dist/{HO4MOOFI-CY1H4sV7.js → HO4MOOFI-BRq_OLiZ.js} +2 -2
- package/dist/{HO4MOOFI-OOt5FGah.cjs → HO4MOOFI-qasqgyBd.cjs} +1 -1
- package/dist/{HUY7CZI3-BYhzdTjj.js → HUY7CZI3-D2lleu1k.js} +2 -2
- package/dist/{HUY7CZI3-BUe0zzsC.cjs → HUY7CZI3-DnWtCer3.cjs} +1 -1
- package/dist/index-DDfYmBLS.cjs +6 -0
- package/dist/{index-1oRhGjYc.js → index-i9uaUEg8.js} +2598 -2659
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/index-DuDuROy_.cjs +0 -6
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";var sr=Object.defineProperty;var dn=e=>{throw TypeError(e)};var nr=(e,s,n)=>s in e?sr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Ts=(e,s,n)=>nr(e,typeof s!="symbol"?s+"":s,n),hn=(e,s,n)=>s.has(e)||dn("Cannot "+n);var X=(e,s,n)=>(hn(e,s,"read from private field"),n?n.call(e):s.get(e)),ge=(e,s,n)=>s.has(e)?dn("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),fe=(e,s,n,a)=>(hn(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),h=require("lodash-es"),g=require("react"),Ne=require("jotai"),O=require("@tanstack/react-query"),V=require("sonner"),U=require("@chaibuilder/sdk"),o=require("@chaibuilder/sdk/ui"),Nt=require("date-fns"),N=require("lucide-react"),Dn=require("@chaibuilder/runtime"),ls=require("zod"),ar=require("react-dropzone"),rr=require("@chaibuilder/sdk/web-blocks");function ir(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const we=ir(g),Be={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"},I={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_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},W="chaibuilder";let lr=0;function mn(e,s){const n=`atom${++lr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=or,a.write=cr),s&&(a.write=s),a}function or(e){return e(this)}function cr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const ur=Symbol(""),dr=e=>typeof(e==null?void 0:e.then)=="function";function hr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var m,f;const w=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},v=(f=(m=e())==null?void 0:m.getItem(u))!=null?f:null;return dr(v)?v.then(w):w(v)},setItem:(u,d)=>{var m;return(m=e())==null?void 0:m.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,m,f)=>u(d,w=>{let v;try{v=JSON.parse(w||"")}catch{v=f}m(v)});let c;try{c=(n=e())==null?void 0:n.subscribe}catch{}return!c&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(c=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const m=f=>{f.storageArea===e()&&f.key===u&&d(f.newValue)};return window.addEventListener("storage",m),()=>{window.removeEventListener("storage",m)}}),c&&(i.subscribe=l(c)),i}const mr=hr();function Bn(e,s,n=mr,a){const r=mn(s);return r.onMount=l=>{l(n.getItem(e,s));let c;return n.subscribe&&(c=n.subscribe(e,l,s)),c},mn(l=>l(r),(l,c,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===ur?(c(r,s),n.removeItem(e)):d instanceof Promise?d.then(m=>(c(r,m),n.setItem(e,m))):(c(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const Mn="__logged_in_user",fr=Bn(Mn,null),Ue=()=>{const[e,s]=Ne.useAtom(fr),n=g.useCallback(()=>{s(null),localStorage.removeItem(Mn)},[s]),a=g.useMemo(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const r=Math.floor(Date.now()/1e3);return e.expiresAt-r<=0},[e]);return{isLoggedIn:!!e,isSessionExpired:a,user:e,setUser:s,logout:n}},Vs=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),J=()=>{const{user:e,logout:s}=Ue(),n=O.useQueryClient(),a=e==null?void 0:e.accessToken;return g.useCallback(async(r,i,l={})=>{if(!a)return null;try{const c=h.get(i,"action","").toLowerCase(),u=await Vs(r+(c?`?action=${c}`:""),i,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[W]}),s(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(c){throw console.error("API request failed:",i,c),c}},[a,s,n])},On=()=>{const e=ie(),s=O.useQueryClient(),n=J();return O.useMutation({mutationFn:async a=>n(e,{action:I.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[W,I.GET_DRAFT_PAGE]})}})},Gn=()=>{const e=ie(),s=O.useQueryClient(),n=J();return O.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||V.toast.success("Website settings updated successfully.")},onError:a=>{V.toast.error("Failed to update website settings",{description:a.message})}})},gr=()=>{const e=ie(),s=O.useQueryClient(),n=J();return O.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_DATA]}),V.toast.success("Website data updated successfully.")},onError:a=>{V.toast.error("Failed to update website data",{description:a.message})}})};function Ie(){const[e,s]=g.useState(new URLSearchParams(window.location.search));return g.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const xr=Ne.atom({}),Rn=()=>Ne.useAtom(xr),pr=()=>{const[e]=Ie(),s=e.get("page"),n=g.useRef(""),{mutate:a}=On();g.useEffect(()=>{!h.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Ke=(e,s)=>{const[n]=Rn();return g.useMemo(()=>h.get(n,e,s),[n,e,s])},ie=()=>Ke("apiUrl","/chai/api"),js=()=>Ke("usersApiUrl","/chai/users"),Xt=()=>Ke("assetsApiUrl","/chai/assets"),Un=()=>Ke("realtimeInstance",null),$e=e=>{const s=ie(),[n]=Ie(),a=e??n.get("page"),r=J();return O.useQuery({queryKey:[W,I.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:I.GET_LANGUAGE_PAGES,data:{id:a}});return h.reverse(h.sortBy(i,"primaryPage"))},enabled:!!a})},Qe=()=>{const e=ie(),s=J();return O.useQuery({queryKey:[W,I.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:I.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},Fn=e=>{const{fallbackLang:s}=U.useLanguages(),{data:n}=Qe(),{data:a,isFetching:r}=$e(),i=g.useMemo(()=>{const l={[s]:!0};return h.each(h.get(n,"languages"),c=>{const u=h.find(a,{lang:c});l[c]=!!u}),l},[s,a,n]);return r||h.isEmpty(e)||e&&i[e]},Hs=()=>{const e=O.useQueryClient(),{data:s}=O.useQuery({queryKey:[W,I.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:g.useCallback(a=>{e.setQueryData([W,I.AI_CONTEXT],a)},[e]),aiContext:s}},Zt=()=>{const e=J(),s=ie();return O.useQuery({queryKey:[W,I.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},yr=Ne.atom({lastSaved:void 0}),vs=()=>Ne.useAtom(yr),Ce=()=>{const[e]=Ie(),s=e.get("page"),[n]=qn(),{data:a,isFetching:r}=Zt();return{data:g.useMemo(()=>({...h.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},Ct=()=>{const[e]=Ie(),s=e.get("lang")??"",{data:n,isFetching:a}=$e();return{data:g.useMemo(()=>h.find(n,{lang:s})||{},[n,s]),isFetching:a}},jr=Ne.atom({}),qn=()=>Ne.useAtom(jr),et=e=>{const s=js(),n=J();return O.useQuery({queryKey:[W,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:I.GET_CHAI_USER,data:{userId:e}}),enabled:!h.isEmpty(e)})},vr=Ne.atom(void 0),Ks=Ne.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1}),es=()=>{const[e]=Ie(),s=e.get("page"),{user:n}=Ue(),[a,r]=Ne.useAtom(vr),[i]=Ne.useAtom(Ks),l=U.useChaiFeatureFlag("realtime-page-lock");return g.useMemo(()=>({isLocked:l?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:c=>r(c)}),[l,s,i.status,n==null?void 0:n.id,a,r])},br=()=>{const e=Un(),{data:s}=Ce(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=Ne.useAtom(Ks),l=g.useRef(!1),c=U.useChaiFeatureFlag("realtime-page-lock");return g.useEffect(()=>{r.status==="locked"||!a||!(n!=null&&n.id)||!e||!c||l.current||setTimeout(()=>{l.current||(l.current=!0,e==null||e.listenEvent("TAKE_OVER_REQUESTED",u=>{(u==null?void 0:u.requesterUserId)!==(n==null?void 0:n.id)&&i({...r,requestedBy:u==null?void 0:u.requesterUserId})}))},1e3)},[r,e,i,a,c,n==null?void 0:n.id]),g.useEffect(()=>{if(!c||!e||!a||!(n!=null&&n.id))return;async function u(){const d=await(e==null?void 0:e.joinPage(a,n==null?void 0:n.id));i({...r,status:d?"editing":"locked",requestedBy:""})}return u(),()=>{e==null||e.leavePage(a,n==null?void 0:n.id)}},[a,c]),{}},$n=()=>{const e=Un(),{data:s}=Ce(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=Ne.useAtom(Ks),{saveState:l,savePage:c}=U.useSavePage(),u=O.useQueryClient(),d=g.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(i({...r,isTakeOverRequested:!0}),e==null||e.requestTakeOver(a,n==null?void 0:n.id),e==null||e.listenEvent("TAKE_OVER_REQUEST_ACCEPTED",()=>{V.toast.success("Your Page Take Over Request Accepted",{position:"top-center"}),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}),u.invalidateQueries({queryKey:[W,I.GET_DRAFT_PAGE]})}),e==null||e.listenEvent("TAKE_OVER_REQUEST_REJECTED",()=>{i({...r,isTakeOverRequested:!1}),V.toast.warning("Your Page Take Over Request Rejected",{position:"top-center",closeButton:!0,duration:1/0})}))},[e,a,n==null?void 0:n.id,i,r,u]),m=g.useCallback(async()=>{!e||!a||!(n!=null&&n.id)||(l!=="SAVED"&&(c(),await new Promise(w=>setTimeout(w,1500))),e==null||e.acceptTakeOver(a,n==null?void 0:n.id),i({status:"locked",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i,c,l]),f=g.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(e==null||e.rejectTakeOver(a,n==null?void 0:n.id),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i]);return{pageLock:r,requestTakeOver:d,acceptTakeOver:m,rejectTakeOver:f}},Qs=()=>{const{data:e}=Qe();return g.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},wr=Ne.atom(null),zn=()=>Ne.useAtom(wr),Vn=()=>{const[e]=zn();return(e==null?void 0:e.slug)||""};function Sr(e,s){const[n,a]=g.useState(e);return g.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const Er=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=U.useLanguages(),{data:r}=Ce(),i=r==null?void 0:r.pageType,l=ie(),c=J(),{data:u,isFetching:d}=O.useQuery({queryKey:[I.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await c(l,{action:I.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[]}),m=g.useMemo(()=>n===""?u.filter(f=>f.lang===""||f.lang===a):u.filter(f=>f.lang===n),[n,a,u]);return{allLangPages:u,data:m,isFetching:d}},Hn=()=>{const{selectedLang:e,fallbackLang:s}=U.useLanguages(),[n,a]=zn(),[r,i]=g.useState(""),l=Sr(r,500),{allLangPages:c,data:u,isFetching:d}=Er({query:l}),m=g.useCallback(v=>a(v),[a]),f=g.useCallback(v=>i(v),[i]),w=g.useCallback(()=>{if(!n)return;const v=!(n!=null&&n.primaryPage),p=e.length===0,b=v?n==null?void 0:n.id:n==null?void 0:n.primaryPage,S=c.filter(A=>(A==null?void 0:A.primaryPage)===b||A.id===b).find(A=>p?A.lang===e||A.lang===s:A.lang===e);a(S||n)},[n,e,c,a,s]);return{isPending:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:c,updateDynamicPage:m,updateSearchQuery:f,onChangeLanguage:w}},Kn=()=>{const[e]=Ie(),s=e.get("page"),n=ie(),{setAiContext:a}=Hs(),{setCurrentEditor:r}=es(),[,i]=vs(),[,l]=qn(),c=J();return O.useQuery({queryKey:[W,I.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await c(n,{action:I.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],m=h.find(d,{_type:"@chai/ai-context"});return a(h.get(m,"_value","")||""),i(f=>({...f,lastSaved:u.lastSaved})),l(h.get(u,"metadata",{})),d},enabled:!!s})},Ws=()=>{const{data:e}=Ce(),{data:s}=Ct(),n=ie(),a=J(),r=Qs(),i=Vn();return O.useQuery({queryKey:[W,I.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:I.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})},Nr=({currentEditor:e})=>{const{user:s}=Ue(),{data:n}=et(e);return!n||!e||e===(s==null?void 0:s.id)?null:t.jsx("span",{className:"ml-2 flex items-center gap-1 text-xs font-light text-gray-500",children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{children:t.jsx(N.LockIcon,{className:"h-3 w-3"})}),t.jsx(o.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},fn=({userId:e})=>{const{data:s}=et(e);return(s==null?void 0:s.name)||"Unknown"};function Cr({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,pageLock:i,realtimePageLockEnabled:l}){const[c,u]=g.useState(!1),d=()=>{u(!1),r()};return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"h-6 w-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"h-12 w-12 rounded-full border border-gray-300"}):t.jsx(N.UserIcon,{className:"h-12 w-12 rounded-full border border-gray-300 p-2"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n}),a&&t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",Nt.formatDistanceToNow(new Date(a),{addSuffix:!0})]})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(o.CardFooter,{children:l?t.jsx(o.Button,{disabled:i.isTakeOverRequested,onClick:d,className:"w-full",variant:"destructive",children:i.isTakeOverRequested?"Page take is requested.":"Request take over"}):t.jsxs(o.AlertDialog,{open:c,onOpenChange:u,children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(o.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(o.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(o.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(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:d,children:"Yes, Take Over"})]})]})]})})]})})}const Ar=()=>{const{pageLock:e,acceptTakeOver:s,rejectTakeOver:n}=$n();return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.AccessibilityIcon,{className:"h-6 w-6 text-yellow-500"}),t.jsx(fn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page"]})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{children:[t.jsx(fn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page. Do you want to accept the request?"]})})})}),t.jsxs(o.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(o.Button,{onClick:s,children:"Yes"}),t.jsx(o.Button,{variant:"outline",onClick:n,children:"No"})]})]})})},Tr=()=>{const{isLocked:e,currentEditor:s}=es(),{data:n}=et(s),[a]=Ie(),r=a.get("page"),{mutate:i}=On(),{isFetching:l}=Kn(),[c]=vs(),{pageLock:u,requestTakeOver:d}=$n(),m=U.useChaiFeatureFlag("realtime-page-lock"),f=g.useCallback(()=>{m?d():i({id:r})},[r,i,d,m]);return m&&(u!=null&&u.requestedBy)?t.jsx(Ar,{}):(m?u.status!=="locked":!e||l)?t.jsx("div",{className:""}):t.jsx(Cr,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",lastSaved:(c==null?void 0:c.lastSaved)||"",onTakeOver:f,pageLock:u,realtimePageLockEnabled:m})},Pr=()=>{const[e,s]=Ie(),n=e.get("lang"),a=Fn(n),{setSelectedLang:r}=U.useLanguages(),i=()=>{const c=new URLSearchParams(window.location.search);c.delete("lang");const u=c.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(c),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=h.get(Be,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-12 z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.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 "',l,'" language.']})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(o.CardFooter,{children:t.jsx(o.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},kr=e=>{const s=ie(),n=J();return O.useMutation({mutationFn:async a=>n(s,{action:I.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),V.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},Lr=e=>{const s=ie(),n=J();return O.useQuery({queryKey:[W,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:I.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})},Ir=e=>{const s=ie(),n=J();return O.useMutation({mutationFn:async a=>n(s,{action:I.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),V.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},_r=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,c]=g.useState(!1),u=U.useUpdateBlocksPropsRealtime(),d=Ir(()=>{u([e],{_libBlockId:void 0}),V.toast.success("Block deleted successfully"),c(!1),a()}),m=()=>{c(!0),d.mutate(s)},f=t.jsxs(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:w=>w.preventDefault(),disabled:l,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(o.Popover,{open:n,onOpenChange:w=>!w&&a(),children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:i||f}),t.jsx(o.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(o.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:m,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},Dr=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,c]=g.useState(!1);return t.jsx(_r,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{c(!1),i()},blockName:n,trigger:t.jsxs(o.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>c(!0),children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Br=()=>{const e=ie(),s=J(),n=O.useQueryClient(),{data:a=[],isLoading:r,error:i}=O.useQuery({queryKey:[W,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:c}=O.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:[W,"library-groups"]}),V.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),V.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:c}},Mr=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),l=g.useRef(null),{groups:c}=Br(),[u,d]=g.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"}]),m=g.useMemo(()=>[...c,...u.filter(v=>!c.some(p=>p.id===v.id))],[c,u]),f=()=>{const v=r.trim();if(!v)return;const p={id:v,name:v};d(b=>[...b,p]),s(p.id),i(""),a(!1)};g.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const w=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return g.useEffect(()=>{e&&!m.some(v=>v.id===e)&&s("")},[e,m,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:v=>i(v.target.value),onKeyDown:w}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(o.Button,{size:"sm",onClick:f,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:v=>s(v.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),c.length>0&&t.jsx("optgroup",{label:"Library Groups",children:c.map(v=>t.jsx("option",{value:v.id,children:v.name},`lib-${v.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(v=>!c.some(p=>p.id===v.id)).map(v=>t.jsx("option",{value:v.id,children:v.name},`local-${v.id}`))})]}),t.jsx(o.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(N.Plus,{className:"h-4 w-4"})})]})},Or=10*1024*1024,Gr=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useCallback(u=>{var m;const d=(m=u.target.files)==null?void 0:m[0];if(d){if(d.size>Or){V.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const f=new FileReader;f.onloadend=()=>{s(f.result),a(!1)},f.readAsDataURL(d)}catch(f){console.error("Error reading file:",f),a(!1),V.toast.error("Failed to process image",{description:f instanceof Error?f.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},c=()=>{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(o.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:c,disabled:n,className:"w-full",children:n?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"]})}),e&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},ve={...U.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"},Rr=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=U.usePartailBlocksStore(),i=s.find(T=>T._id===a),l=i==null?void 0:i._libBlockId,c=!!l,u=g.useMemo(()=>s.some(T=>T._type==="PartialBlock"||T._type==="GlobalBlock"),[s]),d=g.useMemo(()=>{let T=[];for(const L of s)if(L._type==="PartialBlock"||L._type==="GlobalBlock"){let G=r(L.partialBlockId);L._parent&&(G==null?void 0:G.length)>0&&(G=G.map($=>(h.isEmpty($._parent)&&h.set($,"_parent",L._parent),$))),T=[...T,...G]}else T.push(L);return T},[s,r]),[m,f]=g.useState(""),[w,v]=g.useState(""),[p,b]=g.useState(""),[y,S]=g.useState(""),[A,M]=g.useState({}),[E,k]=g.useState(!1),[D,Y]=g.useState(c),[z,ae]=g.useState(!1),{hasPermission:H}=U.usePermissions(),K=H(ve.DELETE_LIBRARY_BLOCK),se=U.useUpdateBlocksPropsRealtime(),Q=()=>{se([a],{_libBlockId:void 0}),V.toast.success("Block delinked from library"),n()},{data:ne,isLoading:B,isError:q}=Lr(l);g.useEffect(()=>{q&&c&&(ae(!0),Y(!1))},[q,c]),g.useEffect(()=>{ne&&!B&&(f(ne.name||""),v(ne.group||""),b(ne.description||""),S(ne.preview||""),Y(!1))},[ne,B]),g.useEffect(()=>{const T=m.trim().length>=2,L=w.trim()!=="";k(T&&L)},[m,w]);const me=()=>{const T={};return m.trim()?m.length<2&&(T.name="Name must be at least 2 characters"):T.name="Name is required",w||(T.group="Group is required"),M(T),Object.keys(T).length===0},{resetLibrary:ye}=U.useLibraryBlocks({id:""}),ue=kr(T=>{c||se([a],{_libBlockId:T.id}),V.toast.success(`Block ${c?"updated":"saved"} successfully`),ye(T.library),n()}),j=async T=>{if(T.preventDefault(),!me())return;const L=d.map(G=>(h.has(G,"_libBlockId")&&delete G._libBlockId,G));ue.mutate({name:m.trim(),group:w,blocks:L,description:p.trim(),...y&&y.startsWith("data:")?{previewImage:y}:{},...c?{id:l}:{}})},x=ue.isPending;return D||B?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"})}):z?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(o.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(o.Button,{onClick:Q,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:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:A.name?"text-destructive":"",children:"Name"}),t.jsx(o.Input,{id:"name",placeholder:"Enter block name",value:m,onChange:T=>f(T.target.value),className:A.name?"border-destructive":""}),A.name&&t.jsx("p",{className:"text-xs text-destructive",children:A.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"group",className:A.group?"text-destructive":"",children:"Group"}),t.jsx(Mr,{value:w,onChange:v}),A.group&&t.jsx("p",{className:"text-xs text-destructive",children:A.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(o.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:T=>b(T.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Gr,{value:y,onChange:S})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[c&&K&&t.jsx(Dr,{blockId:a,libBlockId:l,blockName:m,className:"mr-auto",close:n}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:n,disabled:x,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:x||!E,children:x?"Saving...":c?"Update Block":"Save Block"})]})]})]})},re={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},Ur={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Pe=()=>{const e=ie(),s=J();return O.useQuery({queryKey:[W,I.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:I.GET_PAGE_TYPES})})},Qn=e=>{const{data:s}=Pe();return g.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Fr=()=>{const e=ie(),s=J();return O.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:I.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Wn=()=>{const e=ie(),s=O.useQueryClient(),n=J(),{data:a}=Pe();return O.useMutation({mutationFn:async r=>await n(e,{action:I.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var c;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((c=h.find(a,{key:i.pageType}))==null?void 0:c.name)+" added successfully":"New page added successfully";V.toast.success(l)},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});V.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:h.get(Ur,r.message,r.message)})}})},Ys=()=>{const e=ie(),s=O.useQueryClient(),n=J(),{data:a}=Pe();return O.useMutation({mutationFn:async r=>await n(e,{action:I.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});V.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},qr=()=>{const e=ie(),s=O.useQueryClient(),n=J(),{data:a}=Pe();return O.useMutation({mutationFn:async r=>n(e,{action:I.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){V.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});V.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},$r=()=>{const e=ie(),s=O.useQueryClient(),n=J(),{data:a}=Pe();return O.useMutation({mutationFn:async r=>n(e,{action:I.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]});const l=h.find(a,{key:i.pageType});V.toast.success(l!=null&&l.hasSlug?re.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});V.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Js=()=>{const e=ie(),s=J(),n=O.useQueryClient(),{data:a}=Ce();return O.useMutation({mutationFn:async({ids:r})=>s(e,{action:I.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[W,I.GET_CHANGES]}),n.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{V.toast.error("Failed to publish pages.")}})},zr=()=>{const e=ie(),s=J(),n=O.useQueryClient();return O.useMutation({mutationFn:async a=>{var r;return s(e,{action:I.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:[W,I.GET_WEBSITE_PAGES]}),V.toast.success("Page marked as template successfully.")},onError:()=>{V.toast.error("Failed to mark page as template.")}})},Vr=()=>{const e=ie(),s=J(),n=O.useQueryClient();return O.useMutation({mutationFn:async a=>s(e,{action:I.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]}),V.toast.success("Page unmarked as template successfully.")},onError:()=>{V.toast.error("Failed to unmark page as template.")}})},Hr=()=>{const e=ie(),s=J(),n=O.useQueryClient();return O.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:I.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{V.toast.success(re.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})},onError:()=>{V.toast.error("Failed to change slug")}})};var Xs={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",c=function(){if(!s.OffscreenCanvas)return!1;var j=new OffscreenCanvas(1,1),x=j.getContext("2d");x.fillRect(0,0,1,1);var T=j.transferToImageBitmap();try{x.createPattern(T,"no-repeat")}catch{return!1}return!0}();function u(){}function d(j){var x=n.exports.Promise,T=x!==void 0?x:s.Promise;return typeof T=="function"?new T(j):(j(u,u),null)}var m=function(j,x){return{transform:function(T){if(j)return T;if(x.has(T))return x.get(T);var L=new OffscreenCanvas(T.width,T.height),G=L.getContext("2d");return G.drawImage(T,0,0),x.set(T,L),L},clear:function(){x.clear()}}}(c,new Map),f=function(){var j=Math.floor(16.666666666666668),x,T,L={},G=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(x=function($){var P=Math.random();return L[P]=requestAnimationFrame(function R(Z){G===Z||G+j-1<Z?(G=Z,delete L[P],$()):L[P]=requestAnimationFrame(R)}),P},T=function($){L[$]&&cancelAnimationFrame(L[$])}):(x=function($){return setTimeout($,j)},T=function($){return clearTimeout($)}),{frame:x,cancel:T}}(),w=function(){var j,x,T={};function L(G){function $(P,R){G.postMessage({options:P||{},callback:R})}G.init=function(R){var Z=R.transferControlToOffscreen();G.postMessage({canvas:Z},[Z])},G.fire=function(R,Z,oe){if(x)return $(R,null),x;var be=Math.random().toString(36).slice(2);return x=d(function(ce){function je(F){F.data.callback===be&&(delete T[be],G.removeEventListener("message",je),x=null,m.clear(),oe(),ce())}G.addEventListener("message",je),$(R,be),T[be]=je.bind(null,{data:{callback:be}})}),x},G.reset=function(){G.postMessage({reset:!0});for(var R in T)T[R](),delete T[R]}}return function(){if(j)return j;if(!a&&i){var G=["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{j=new Worker(URL.createObjectURL(new Blob([G])))}catch($){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",$),null}L(j)}return j}}(),v={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(j,x){return x?x(j):j}function b(j){return j!=null}function y(j,x,T){return p(j&&b(j[x])?j[x]:v[x],T)}function S(j){return j<0?0:Math.floor(j)}function A(j,x){return Math.floor(Math.random()*(x-j))+j}function M(j){return parseInt(j,16)}function E(j){return j.map(k)}function k(j){var x=String(j).replace(/[^0-9a-f]/gi,"");return x.length<6&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:M(x.substring(0,2)),g:M(x.substring(2,4)),b:M(x.substring(4,6))}}function D(j){var x=y(j,"origin",Object);return x.x=y(x,"x",Number),x.y=y(x,"y",Number),x}function Y(j){j.width=document.documentElement.clientWidth,j.height=document.documentElement.clientHeight}function z(j){var x=j.getBoundingClientRect();j.width=x.width,j.height=x.height}function ae(j){var x=document.createElement("canvas");return x.style.position="fixed",x.style.top="0px",x.style.left="0px",x.style.pointerEvents="none",x.style.zIndex=j,x}function H(j,x,T,L,G,$,P,R,Z){j.save(),j.translate(x,T),j.rotate($),j.scale(L,G),j.arc(0,0,1,P,R,Z),j.restore()}function K(j){var x=j.angle*(Math.PI/180),T=j.spread*(Math.PI/180);return{x:j.x,y:j.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:j.startVelocity*.5+Math.random()*j.startVelocity,angle2D:-x+(.5*T-Math.random()*T),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:j.color,shape:j.shape,tick:0,totalTicks:j.ticks,decay:j.decay,drift:j.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:j.gravity*3,ovalScalar:.6,scalar:j.scalar,flat:j.flat}}function se(j,x){x.x+=Math.cos(x.angle2D)*x.velocity+x.drift,x.y+=Math.sin(x.angle2D)*x.velocity+x.gravity,x.velocity*=x.decay,x.flat?(x.wobble=0,x.wobbleX=x.x+10*x.scalar,x.wobbleY=x.y+10*x.scalar,x.tiltSin=0,x.tiltCos=0,x.random=1):(x.wobble+=x.wobbleSpeed,x.wobbleX=x.x+10*x.scalar*Math.cos(x.wobble),x.wobbleY=x.y+10*x.scalar*Math.sin(x.wobble),x.tiltAngle+=.1,x.tiltSin=Math.sin(x.tiltAngle),x.tiltCos=Math.cos(x.tiltAngle),x.random=Math.random()+2);var T=x.tick++/x.totalTicks,L=x.x+x.random*x.tiltCos,G=x.y+x.random*x.tiltSin,$=x.wobbleX+x.random*x.tiltCos,P=x.wobbleY+x.random*x.tiltSin;if(j.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-T)+")",j.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))j.fill(me(x.shape.path,x.shape.matrix,x.x,x.y,Math.abs($-L)*.1,Math.abs(P-G)*.1,Math.PI/10*x.wobble));else if(x.shape.type==="bitmap"){var R=Math.PI/10*x.wobble,Z=Math.abs($-L)*.1,oe=Math.abs(P-G)*.1,be=x.shape.bitmap.width*x.scalar,ce=x.shape.bitmap.height*x.scalar,je=new DOMMatrix([Math.cos(R)*Z,Math.sin(R)*Z,-Math.sin(R)*oe,Math.cos(R)*oe,x.x,x.y]);je.multiplySelf(new DOMMatrix(x.shape.matrix));var F=j.createPattern(m.transform(x.shape.bitmap),"no-repeat");F.setTransform(je),j.globalAlpha=1-T,j.fillStyle=F,j.fillRect(x.x-be/2,x.y-ce/2,be,ce),j.globalAlpha=1}else if(x.shape==="circle")j.ellipse?j.ellipse(x.x,x.y,Math.abs($-L)*x.ovalScalar,Math.abs(P-G)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI):H(j,x.x,x.y,Math.abs($-L)*x.ovalScalar,Math.abs(P-G)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI);else if(x.shape==="star")for(var ee=Math.PI/2*3,Ae=4*x.scalar,_e=8*x.scalar,_=x.x,le=x.y,Ee=5,Re=Math.PI/Ee;Ee--;)_=x.x+Math.cos(ee)*_e,le=x.y+Math.sin(ee)*_e,j.lineTo(_,le),ee+=Re,_=x.x+Math.cos(ee)*Ae,le=x.y+Math.sin(ee)*Ae,j.lineTo(_,le),ee+=Re;else j.moveTo(Math.floor(x.x),Math.floor(x.y)),j.lineTo(Math.floor(x.wobbleX),Math.floor(G)),j.lineTo(Math.floor($),Math.floor(P)),j.lineTo(Math.floor(L),Math.floor(x.wobbleY));return j.closePath(),j.fill(),x.tick<x.totalTicks}function Q(j,x,T,L,G){var $=x.slice(),P=j.getContext("2d"),R,Z,oe=d(function(be){function ce(){R=Z=null,P.clearRect(0,0,L.width,L.height),m.clear(),G(),be()}function je(){a&&!(L.width===r.width&&L.height===r.height)&&(L.width=j.width=r.width,L.height=j.height=r.height),!L.width&&!L.height&&(T(j),L.width=j.width,L.height=j.height),P.clearRect(0,0,L.width,L.height),$=$.filter(function(F){return se(P,F)}),$.length?R=f.frame(je):ce()}R=f.frame(je),Z=ce});return{addFettis:function(be){return $=$.concat(be),oe},canvas:j,promise:oe,reset:function(){R&&f.cancel(R),Z&&Z()}}}function ne(j,x){var T=!j,L=!!y(x||{},"resize"),G=!1,$=y(x,"disableForReducedMotion",Boolean),P=i&&!!y(x||{},"useWorker"),R=P?w():null,Z=T?Y:z,oe=j&&R?!!j.__confetti_initialized:!1,be=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,ce;function je(ee,Ae,_e){for(var _=y(ee,"particleCount",S),le=y(ee,"angle",Number),Ee=y(ee,"spread",Number),Re=y(ee,"startVelocity",Number),Ns=y(ee,"decay",Number),Cs=y(ee,"gravity",Number),As=y(ee,"drift",Number),Tt=y(ee,"colors",E),Pt=y(ee,"ticks",Number),tt=y(ee,"shapes"),ts=y(ee,"scalar"),ss=!!y(ee,"flat"),C=D(ee),de=_,De=[],ke=j.width*C.x,Oe=j.height*C.y;de--;)De.push(K({x:ke,y:Oe,angle:le,spread:Ee,startVelocity:Re,color:Tt[de%Tt.length],shape:tt[A(0,tt.length)],ticks:Pt,decay:Ns,gravity:Cs,drift:As,scalar:ts,flat:ss}));return ce?ce.addFettis(De):(ce=Q(j,De,Z,Ae,_e),ce.promise)}function F(ee){var Ae=$||y(ee,"disableForReducedMotion",Boolean),_e=y(ee,"zIndex",Number);if(Ae&&be)return d(function(Re){Re()});T&&ce?j=ce.canvas:T&&!j&&(j=ae(_e),document.body.appendChild(j)),L&&!oe&&Z(j);var _={width:j.width,height:j.height};R&&!oe&&R.init(j),oe=!0,R&&(j.__confetti_initialized=!0);function le(){if(R){var Re={getBoundingClientRect:function(){if(!T)return j.getBoundingClientRect()}};Z(Re),R.postMessage({resize:{width:Re.width,height:Re.height}});return}_.width=_.height=null}function Ee(){ce=null,L&&(G=!1,s.removeEventListener("resize",le)),T&&j&&(document.body.contains(j)&&document.body.removeChild(j),j=null,oe=!1)}return L&&!G&&(G=!0,s.addEventListener("resize",le,!1)),R?R.fire(ee,_,Ee):je(ee,_,Ee)}return F.reset=function(){R&&R.reset(),ce&&ce.reset()},F}var B;function q(){return B||(B=ne(null,{useWorker:!0,resize:!0})),B}function me(j,x,T,L,G,$,P){var R=new Path2D(j),Z=new Path2D;Z.addPath(R,new DOMMatrix(x));var oe=new Path2D;return oe.addPath(Z,new DOMMatrix([Math.cos(P)*G,Math.sin(P)*G,-Math.sin(P)*$,Math.cos(P)*$,T,L])),oe}function ye(j){if(!l)throw new Error("path confetti are not supported in this browser");var x,T;typeof j=="string"?x=j:(x=j.path,T=j.matrix);var L=new Path2D(x),G=document.createElement("canvas"),$=G.getContext("2d");if(!T){for(var P=1e3,R=P,Z=P,oe=0,be=0,ce,je,F=0;F<P;F+=2)for(var ee=0;ee<P;ee+=2)$.isPointInPath(L,F,ee,"nonzero")&&(R=Math.min(R,F),Z=Math.min(Z,ee),oe=Math.max(oe,F),be=Math.max(be,ee));ce=oe-R,je=be-Z;var Ae=10,_e=Math.min(Ae/ce,Ae/je);T=[_e,0,0,_e,-Math.round(ce/2+R)*_e,-Math.round(je/2+Z)*_e]}return{type:"path",path:x,matrix:T}}function ue(j){var x,T=1,L="#000000",G='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof j=="string"?x=j:(x=j.text,T="scalar"in j?j.scalar:T,G="fontFamily"in j?j.fontFamily:G,L="color"in j?j.color:L);var $=10*T,P=""+$+"px "+G,R=new OffscreenCanvas($,$),Z=R.getContext("2d");Z.font=P;var oe=Z.measureText(x),be=Math.ceil(oe.actualBoundingBoxRight+oe.actualBoundingBoxLeft),ce=Math.ceil(oe.actualBoundingBoxAscent+oe.actualBoundingBoxDescent),je=2,F=oe.actualBoundingBoxLeft+je,ee=oe.actualBoundingBoxAscent+je;be+=je+je,ce+=je+je,R=new OffscreenCanvas(be,ce),Z=R.getContext("2d"),Z.font=P,Z.fillStyle=L,Z.fillText(x,F,ee);var Ae=1/T;return{type:"bitmap",bitmap:R.transferToImageBitmap(),matrix:[Ae,0,0,Ae,-be*Ae/2,-ce*Ae/2]}}n.exports=function(){return q().apply(this,arguments)},n.exports.reset=function(){q().reset()},n.exports.create=ne,n.exports.shapeFromPath=ye,n.exports.shapeFromText=ue})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Xs,!1);const Kr=Xs.exports;Xs.exports.create;const Qr={particleCount:350,spread:120,origin:{y:.6},angle:90},Wr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Dt=e=>{let s=Wr[e];s||(s={});const n={...Qr,...s};Kr(n)},Yr=()=>{const[e]=U.useTheme(),{mutate:s,isPending:n}=Js(),{mutateAsync:a,isPending:r}=Gn(),i=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{Dt("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(o.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(o.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})};function Jr({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=g.useState(null),c=g.useRef(null),[u,d]=g.useState(a+e);g.useEffect(()=>{d(a+e)},[e,a]);const m=v=>{const p=v.target.value;if(!p.startsWith(a)){const E=p.replace(a,""),k=a+E;d(k),s(E);return}const y=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),S=(y.match(/\./g)||[]).length,A=S<=1;S>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(A);const M=a+y;d(M),s(y)},f=()=>{if(c.current){const v=c.current;setTimeout(()=>{const p=a.length;v.setSelectionRange(p,p)},0)}},w=v=>{const p=v.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const y=a.length;p.setSelectionRange(y,y)},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(o.Input,{ref:c,value:u,onChange:m,onFocus:f,onClick:w,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const Xr=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}},He=e=>{if(!e)return e;const{base:s}=Xr(e);return s},Zr=e=>e&&He(e),gn=(e,s)=>{const n=He(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`},cs=({children:e,onWheel:s,...n})=>{const a=r=>{try{r.preventDefault();const i=r.currentTarget;i.scrollTop+=r.deltaY}catch{r.preventDefault()}s&&s(r)};return t.jsx(o.CommandList,{...n,onWheel:a,children:e})},Ps=(...e)=>e.filter(Boolean).join(" ");function ei({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage"}){const[i,l]=g.useState(!1),[c,u]=g.useState(""),d=U.useChaiFeatureFlag("enable-add-page-dropdown");d||(a="w-full rounded-md border border-gray-300 px-3 py-2");const m=g.useMemo(()=>!e||e.length===0?[]:e.filter(S=>!h.isEmpty(S.slug)).filter(S=>S.slug!=="/").sort((S,A)=>S.slug.localeCompare(A.slug)),[e]),f=g.useMemo(()=>{if(!c.trim())return m;const y=c.toLowerCase();return m.filter(S=>S.name.toLowerCase().includes(y)||S.slug.toLowerCase().includes(y))},[m,c]),w=y=>Math.max(0,(y.match(/\//g)||[]).length-1),v=y=>" ".repeat(y),p=y=>{if(y==="/")return"/";const S=y.split("/").filter(Boolean);if(S.length<=1){const A=S[0]||"";return`/${He(A)}`}return`/${He(S[S.length-1])}`},b=()=>{if(!s||s==="none")return"None";const y=m.find(S=>S.id===s);return y?`${y.name} (${p(y.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),d?t.jsxs(o.Popover,{open:i,onOpenChange:l,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{id:r,variant:"outline",role:"combobox",className:Ps("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(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.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(o.Input,{placeholder:"Search pages...",className:"h-8 pl-8 text-xs",value:c,onChange:y=>u(y.target.value)})]})})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No pages found."}),t.jsxs(o.CommandGroup,{children:[t.jsxs(o.CommandItem,{value:"none",onSelect:()=>{n(""),l(!1),u("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(N.Check,{className:Ps("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),f.map(y=>{const S=v(w(y.slug)),A=p(y.slug),M=t.jsxs("span",{className:"flex items-center text-sm",children:[S,y.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",A,")"]})]});return t.jsxs(o.CommandItem,{value:y.id,onSelect:()=>{n(y.id),l(!1),u("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:M}),t.jsx(N.Check,{className:Ps("mr-2 h-4 w-4 shrink-0",s===y.id?"opacity-100":"opacity-0")})]},y.id)})]})]})]})})]}):t.jsxs("select",{id:r,value:s||"none",onChange:y=>n(y.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),m.map(y=>{const S=w(y.slug),A=S>0?v(S):"",M=p(y.slug);return t.jsxs("option",{value:y.id,children:[A,y.name," (",M,")"]},y.id)})]})]})}function Zs({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[c,u]=g.useState(e),[d,m]=g.useState(null);g.useEffect(()=>{u(e)},[e]);const f=w=>{const p=w.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),b=(p.match(/\./g)||[]).length,y=b<=1;b>1?m("Invalid slug. Only one dot (.) is allowed in the slug"):m(null),r&&r(y),u(p),s(p)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"flex items-center mb-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:Zr(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{disabled:i,value:c,onChange:f,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:d})]}),l&&t.jsx("div",{className:"flex items-center mt-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const ti=(...e)=>e.filter(Boolean).join(" "),si=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=g.useState(""),[l,c]=g.useState(!1),[u,d]=g.useState(""),m=U.useChaiFeatureFlag("enable-add-page-dropdown");if(g.useEffect(()=>{if(s){const b=e.find(y=>y.id===s);i((b==null?void 0:b.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 f={};e.forEach(b=>{const y=b.libraryName;f[y]||(f[y]=[]),f[y].push(b)});const w=Object.entries(f).reduce((b,[y,S])=>{const A=S.filter(M=>M.name.toLowerCase().includes(u.toLowerCase())||y.toLowerCase().includes(u.toLowerCase()));return A.length>0&&(b[y]=A),b},{}),v=e.find(b=>b.id===s),p=v?h.startCase(v.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[m?t.jsxs(o.Popover,{open:l,onOpenChange:c,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.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(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.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(o.Input,{placeholder:"Search templates...",className:"h-8 pl-8 text-xs",value:u,onChange:b=>d(b.target.value)})]})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No templates found."}),Object.entries(w).map(([b,y])=>t.jsx(o.CommandGroup,{heading:b,children:y.map(S=>t.jsxs(o.CommandItem,{value:S.id,onSelect:()=>{n(S.id),c(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[h.startCase(S.name),t.jsx(N.Check,{className:ti("mr-2 h-4 w-4",s===S.id?"opacity-100":"opacity-0")})]},S.id))},b))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:b=>n(b.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(f).map(([b,y])=>t.jsx("optgroup",{label:b,children:y.map(S=>t.jsx("option",{value:S.id,children:h.startCase(S.name)},S.id))},b))]}),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"})]})]})},ni=()=>{const e=ie(),s=J();return O.useQuery({queryKey:[W,I.GET_LIBRARIES],queryFn:async()=>await s(e,{action:I.GET_LIBRARIES})||[]})},ai=e=>{const s=ie(),n=J();return O.useQuery({queryKey:[W,I.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:I.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?h.filter(a,{pageType:e}):a)||[]}})},ri=e=>{const{data:s=[],isLoading:n}=ai(e),{data:a=[],isLoading:r}=ni(),i=g.useMemo(()=>n||r?[]:s.map(c=>{const u=h.find(a,{id:c.library});return{...c,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=g.useMemo(()=>h.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},en=()=>{const[,e]=Ie();return g.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])},us=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:""},jsonLD:{}};e!=null&&e.defaultSeo&&(h.has(e.defaultSeo,s)&&h.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};return e!=null&&e.defaultJSONLD&&(h.has(e.defaultJSONLD,s)&&h.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],h.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,h.set(n,"seo.jsonLD",JSON.stringify(a)))),{seo:n.seo,jsonLD:a}},st=(...e)=>e.filter(Boolean).join(" ");function ii({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var ts,ss;const r=en(),i=!!(e!=null&&e.id),{data:l}=Zt(),{mutate:c,isPending:u}=Wn(),{mutate:d,isPending:m}=Ys(),[f,w]=g.useState(null),[v,p]=g.useState(!0),[b,y]=g.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:S}=U.usePermissions(),A=S(ve.CHANGE_PAGE_TYPE),[M,E]=g.useState(!1),[k,D]=g.useState(""),{selectedLang:Y,fallbackLang:z}=U.useLanguages(),ae=Y||z,[H,K]=g.useState(""),[se,Q]=g.useState(!1),ne=g.useMemo(()=>{const C=s.find(de=>de.key===b);return(C==null?void 0:C.hasSlug)===!1},[b,s]),[B,q]=g.useState((e==null?void 0:e.parent)??""),[me,ye]=g.useState((e==null?void 0:e.name)??""),[ue,j]=g.useState((e==null?void 0:e.dynamic)??!1),[x,T]=g.useState(ue?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[L,G]=g.useState((e==null?void 0:e.dynamicSlugCustom)??""),[$,P]=g.useState(!0),[R,Z]=g.useState(""),{data:oe,isLoading:be}=ri(b),ce=u||m,je=U.useChaiFeatureFlag("enable-add-page-dropdown"),F=s.find(C=>C.key===b),ee=C=>{if(i&&b!==C){D(C),E(!0),K(""),Q(!1);return}y(C),K(""),Q(!1)},Ae=()=>{y(k),E(!1),j(!1)},_e=C=>{j(C),C?T(""):G("")},_=C=>{if(q(C),C&&C!=="none"){const de=l==null?void 0:l.find(ke=>ke.id===C),De=(de==null?void 0:de.slug)||"";if(x.startsWith(De)){const ke=x.slice(De.length).replace(/^\/+/,"");T(ke)}else T(x.replace(/^\/+/,""))}else T(x?`${x}`:"")},le=C=>{Z(C)},Ee=()=>me.trim()?ue&&!h.isEmpty(x)?(w("Slug must be empty when using dynamic slug"),!1):ue&&!$?(w("Dynamic slug is invalid"),!1):!0:(V.toast.error("Name is required"),!1),Re=()=>{const C={pageType:F==null?void 0:F.key,name:me,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:me},{onSuccess:()=>{V.toast.success((F==null?void 0:F.name)+" updated successfully"),n()}}):c(C,{onSuccess:de=>{n(),r(de.page.id,a)}})},Ns=(C,de)=>{if(!C.trim()&&!ue)return w("Child page slug is required"),!1;const De=He(de),ke=gn(De,C);return Object.keys(Be).some(ns=>ke===`/${ns}`||(ke==null?void 0:ke.startsWith(`/${ns}/`)))?(w("Slugs cannot start with a language code for primary page"),!1):!0},Cs=(C,de)=>{const De=He(de),ke=gn(De,C),Oe={pageType:b,name:me,slug:ke.replace(/\/$/,""),parent:B,dynamic:ue,hasSlug:!0,template:R||void 0,tracking:{},seo:{},jsonLD:{}};if(ue&&(Oe.dynamicSlugCustom=L),i)d({id:e==null?void 0:e.id,...Oe},{onSuccess:()=>{V.toast.success("Page updated successfully"),n()}});else{const ze=h.find(s,{key:b});ze!=null&&ze.trackingDefault&&(Oe.tracking=ze.trackingDefault);const{seo:ns,jsonLD:er}=us(ze,ae);h.set(Oe,"seo",ns),h.set(Oe,"jsonLD",er),c(Oe,{onSuccess:tr=>{n(),r(tr.page.id,a)}})}},As=()=>{const C={pageType:b,name:me,slug:x===""?"/":`/${x.replace(/\/$/,"")}`,template:R||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...C},{onSuccess:()=>{V.toast.success("Page updated successfully"),n()}});else{const de=h.find(s,{key:b});de!=null&&de.trackingDefault&&(C.tracking=de.trackingDefault);const{seo:De,jsonLD:ke}=us(de,ae);h.set(C,"seo",De),h.set(C,"jsonLD",ke),c(C,{onSuccess:Oe=>{var ze;(ze=Oe==null?void 0:Oe.page)!=null&&ze.id&&r(Oe.page.id,a),n()}})}},Tt=C=>{if(C.preventDefault(),w(null),!!Ee()){if(!(F!=null&&F.hasSlug)){Re();return}if(B&&B!=="none"){const de=l==null?void 0:l.find(ke=>ke.id===B),De=(de==null?void 0:de.slug)||"";if(!Ns(x,De))return;Cs(x,De)}else As()}},{pagesType:Pt,partialsType:tt}=g.useMemo(()=>{const C=de=>H?de.name.toLowerCase().includes(H.toLowerCase())||de.key.toLowerCase().includes(H.toLowerCase()):!0;return{pagesType:s.filter(de=>de.hasSlug!==!1&&C(de)),partialsType:s.filter(de=>de.hasSlug===!1&&C(de))}},[s,H]);return F!=null&&F.hasSlug?t.jsxs("form",{onSubmit:Tt,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),je?t.jsxs(o.Popover,{open:se,onOpenChange:Q,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!A,className:st("w-full justify-between",i&&!A?"cursor-not-allowed text-gray-500":""),children:[(F==null?void 0:F.name)||"Select page type",t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.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(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:H,onChange:C=>K(C.target.value)})]})}),t.jsxs(cs,{className:"overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),i?ne?t.jsx(o.CommandGroup,{heading:"Partials",children:tt.map(C=>t.jsxs(o.CommandItem,{value:C.key,onSelect:()=>ee(C.key),className:"flex cursor-pointer items-center justify-between",children:[C.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",b===C.key?"opacity-100":"opacity-0")})]},C.key))}):t.jsx(o.CommandGroup,{heading:"Pages",children:Pt.map(C=>t.jsxs(o.CommandItem,{value:C.key,onSelect:()=>ee(C.key),className:"flex cursor-pointer items-center justify-between",children:[C.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",b===C.key?"opacity-100":"opacity-0")})]},C.key))}):t.jsxs(t.Fragment,{children:[Pt.length>0&&t.jsx(o.CommandGroup,{heading:"Pages",children:Pt.map(C=>t.jsxs(o.CommandItem,{value:C.key,onSelect:()=>ee(C.key),className:"flex cursor-pointer items-center justify-between",children:[C.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",b===C.key?"opacity-100":"opacity-0")})]},C.key))}),tt.length>0&&t.jsx(o.CommandGroup,{heading:"Partials",children:tt.map(C=>t.jsxs(o.CommandItem,{value:C.key,onSelect:()=>ee(C.key),className:"flex cursor-pointer items-center justify-between",children:[C.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",b===C.key?"opacity-100":"opacity-0")})]},C.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:b,disabled:i&&!A,onChange:C=>ee(C.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!A?"cursor-not-allowed text-gray-500":""}`,children:i?ne?t.jsx("optgroup",{label:"Partials",children:s.filter(C=>C.hasSlug===!1).map(C=>t.jsx("option",{value:C.key,children:C.name},C.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(C=>C.hasSlug!==!1).map(C=>t.jsx("option",{value:C.key,children:C.name},C.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(C=>C.hasSlug!==!1).map(C=>t.jsx("option",{value:C.key,children:C.name},C.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(C=>C.hasSlug===!1).map(C=>t.jsx("option",{value:C.key,children:C.name},C.key))})]})}),M&&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(o.Button,{variant:"outline",size:"sm",onClick:()=>E(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:Ae,children:"Confirm"})]})]})]}),!i&&(F==null?void 0:F.hasSlug)&&oe.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(si,{templates:oe,selectedTemplateId:R,onSelectTemplate:le,isLoading:be})]}),t.jsx(ei,{pages:l,selectedParentId:B,onChange:_}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:me,onChange:C=>ye(C.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(F==null?void 0:F.dynamicSegments)&&B&&B!=="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:ue,onChange:C=>_e(C.target.checked),className:"rounded border-gray-300"}),t.jsx(o.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ue&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(Jr,{value:L,onChange:G,dynamicPattern:(F==null?void 0:F.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:P})})})]}),(!(F!=null&&F.dynamicSegments)||!ue)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Zs,{value:x,onChange:T,placeholder:B&&B!=="none"?"Enter page slug":b==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:B&&B!=="none"?(ss=l==null?void 0:l.find(C=>C.id===B))==null?void 0:ss.slug:void 0,onValidationChange:p}),f&&t.jsx("p",{className:"text-xs text-red-500",children:f})]}),t.jsx(o.Button,{disabled:ce||!v&&(!(F!=null&&F.dynamicSegments)||!ue)||ue&&!$,type:"submit",className:"w-full",children:i?ce?"Updating...":"Update page":ce?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Tt,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),je?t.jsxs(o.Popover,{open:se,onOpenChange:Q,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!A,className:st("w-full justify-between",i&&!A?"cursor-not-allowed text-gray-500":""),children:[(F==null?void 0:F.name)||"Select page type",t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.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(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:H,onChange:C=>K(C.target.value)})]})}),t.jsxs(cs,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),t.jsx(o.CommandGroup,{heading:"Partials",children:tt.map(C=>t.jsxs(o.CommandItem,{value:C.key,onSelect:()=>{ee(C.key),Q(!1)},className:"flex cursor-pointer items-center justify-between",children:[C.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",b===C.key?"opacity-100":"opacity-0")})]},C.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:b,disabled:i&&!A,onChange:C=>ee(C.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!A?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(C=>C.hasSlug===!1).map(C=>t.jsx("option",{value:C.key,children:C.name},C.key))})}),M&&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(o.Button,{variant:"outline",size:"sm",onClick:()=>E(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:Ae,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(ts=s.find(C=>C.key===b))==null?void 0:ts.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:me,onChange:C=>ye(C.target.value),required:!0,"aria-required":"true"})]}),t.jsx(o.Button,{disabled:ce,type:"submit",className:"w-full",children:i?ce?"Updating...":"Update "+(F==null?void 0:F.name):ce?"Creating...":"Create "+(F==null?void 0:F.name)})]})}const Yn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Pe(),r=!!(e!=null&&e.id);return t.jsx(o.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsxs(o.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(o.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(ii,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function tn({page:e,onClose:s}){const[,n]=Ie(),{mutate:a,isPending:r}=qr(),{data:i}=Pe(),{setSelectedLang:l,fallbackLang:c}=U.useLanguages(),[,u]=U.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")),l(c),u("outline"),s()}})},m=i==null?void 0:i.find(f=>f.key===(e==null?void 0:e.pageType));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(o.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)})," ",m!=null&&m.hasSlug?(m==null?void 0:m.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:h.get(Be,e.lang,e.lang)})]})]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:r,onClick:d,children:r?"Deleting...":"Delete"})]})]})})}const li=()=>{const e=ie(),s=O.useQueryClient(),n=J();return O.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const l={pageId:a,name:r};return i&&(l.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]}),V.toast.success("Page duplicated successfully")},onError:a=>{V.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Jn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=li(),[r,i]=g.useState(null),[l,c]=g.useState(`${e.name} (Copy)`),u=h.isEmpty(e.slug),[d,m]=g.useState(u?"":`${e.slug.split("/").pop()}-copy`),f=u?"":h.initial(e.slug.split("/")).join("/"),[w,v]=g.useState(!1),p=b=>{if(b.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),v(!0);const y={pageId:e.id,name:l};u||(y.slug=`${f}/${d}`),n(y,{onSuccess:()=>{v(!1),s()},onError:S=>{v(!1),S.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):S.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):S.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(S.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Duplicate Page"}),t.jsx(o.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]}),!u&&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:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:l,onChange:b=>c(b.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Zs,{value:d,onChange:b=>m(b),parentSlug:f,onValidationChange:b=>{i(b?null:"Invalid slug")}})]}),r&&t.jsxs(o.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:r})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||w,children:a||w?"Duplicating...":"Duplicate"})]})]})]})})},oi=1*1024*1024,Xn=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState(!1),m=g.useRef(null),f=zr(),{data:w}=Pe(),v=w==null?void 0:w.find(M=>M.key===e.pageType),p=(v==null?void 0:v.name)||h.startCase(e.pageType),b=g.useCallback(M=>{var k;const E=(k=M.target.files)==null?void 0:k[0];if(E){if(E.size>oi){V.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(E.size/1024).toFixed(2)}KB.`}),m.current&&(m.current.value="");return}try{d(!0);const D=new FileReader;D.onloadend=()=>{c(D.result),d(!1)},D.readAsDataURL(E)}catch(D){console.error("Error reading file:",D),d(!1),V.toast.error("Failed to process image",{description:D instanceof Error?D.message:"Unknown error"})}}},[]),y=()=>{c(""),m.current&&(m.current.value="")},S=()=>{var M;(M=m.current)==null||M.click()},A=()=>{a(!0),f.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Mark as template"}),t.jsxs(o.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:h.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(o.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(o.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:M=>i(M.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.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(o.Input,{type:"file",id:"previewImage",ref:m,onChange:b,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:S,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"]})}),l&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:y,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:M=>{M.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:A,children:"Mark as template"})]})]})})},Zn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:c})=>{const{hasPermission:u}=U.usePermissions(),{data:d}=Pe(),m=g.useMemo(()=>h.find(d,{key:e.pageType}),[d,e.pageType]),f=g.useMemo(()=>!!e.isTemplate,[e.isTemplate]),w=g.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!u(ve.EDIT_PAGE)&&!u(ve.DELETE_PAGE)&&!u(ve.UNPUBLISH_PAGE)||!e?null:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:c}),t.jsxs(o.DropdownMenuContent,{align:"center",className:"text-sm",children:[u(ve.ADD_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),u(ve.EDIT_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&u(ve.UNPUBLISH_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(N.Power,{className:"size-3"}),re.UNPUBLISH]}),u(ve.DELETE_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(N.Trash,{className:"size-3"}),re.DELETE]}),u(ve.MARK_AS_TEMPLATE)&&w&&t.jsx(t.Fragment,{children:f?t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),re.UNMARK_AS_TEMPLATE]}):t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),re.MARK_AS_TEMPLATE]})})]})]})},ea=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),r=Vr(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Unmark as template"}),t.jsx(o.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(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},bs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=$r(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm action"}),t.jsxs(o.DialogDescription,{children:[re.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:a,onClick:r,children:a?re.UPDATING:re.UNPUBLISH})]})]})})},ci=Bn("expandedPagesState",[]),sn=e=>h.flatMap(e,s=>[s,...s.children?sn(s.children):[]]),ui=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const l=[...r,i.id];if(i.id===s)return l;if(i.children&&i.children.length>0){const c=n(i.children,l);if(c)return c}}return null};return n(e)||[]},ta=(e,s)=>{if(!s)return[];const n=sn(e),a=h.find(n,r=>r.id===s);if(a){if(a.parent)return[...ta(e,a.parent),s];const r=ui(e,s);if(!h.isEmpty(r))return r}return[s]},di=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(c=>s.add(c)),i.children&&!h.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},sa=e=>{const[s,n]=Ne.useAtom(ci),a=e?h.includes(s,e):!1,r=g.useCallback(()=>{n(d=>a?h.filter(d,m=>m!==e):[...d,e])},[n,a,e]),i=g.useCallback((d,m)=>{if(!m||h.isEmpty(d))return;const f=sn(d),w=ta(f,m);if(!Array.isArray(w)||h.isEmpty(w))return;const v=w.slice(0,-1);h.isEmpty(v)||n(p=>h.uniq([...p,...v]))},[n]),l=g.useCallback(d=>{if(h.isEmpty(d))return;const m=di(d);h.isEmpty(m)||n(f=>h.union(f,m))},[n]),c=g.useCallback(d=>{if(h.isEmpty(d))return;const m=h.flatMap(d,f=>{const w=v=>[v.id,...v.children?h.flatMap(v.children,w):[]];return w(f)});n(m)},[n]),u=g.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:c,collapseAll:u}},xn=(e,s)=>!e||!Array.isArray(e)?[]:h.isEmpty(s)?e:h.compact(h.filter(e,n=>{const a=h.toLower(s);return h.includes(h.toLower((n==null?void 0:n.name)||""),a)||h.includes(h.toLower((n==null?void 0:n.slug)||""),a)})),hi=(e,s)=>{const n=new Set,a=h.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])},Ds=(e,s,n)=>h.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?Ds(a.children,s,n):[]};const r=a.children&&a.children.some(i=>h.includes(h.toLower(i.name||""),h.toLower(s))||h.includes(h.toLower(i.slug||""),h.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?Ds(a.children,s,n):[]}}),mi=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},na=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?na(n.children):[]})),fi=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=h.compact(h.filter(e,{pageType:n}))),h.isEmpty(s))r=xn(r,s);else{const m=xn(r,s),f=hi(e,m);r=h.uniqBy([...m,...f],"id")}const i=na(mi(r)),l=Ds(i,s,a),c=h.filter(l,m=>a(m.pageType)).sort((m,f)=>(m.name||"").localeCompare(f.name||"")),u=h.keyBy(h.filter(l,m=>!a(m.pageType)),"pageType"),d=Object.values(h.mapValues(u,(m,f)=>({...m,name:h.startCase(f),isPartialGroup:!0,children:l.filter(w=>w.pageType===f)})));return[...c,...d]},gi=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:c,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:m,isExpanded:f,onToggleExpand:w})=>{const v=en(),{data:p}=Pe(),[,b]=U.useSidebarActivePanel(),y=g.useMemo(()=>h.find(p,{key:s.pageType}),[p,s.pageType]),S=g.useMemo(()=>{const k=h.get(s,"slug",""),D=e?He(e):"",Y=D?k.replace(D,""):k;return Y||"/"},[s,e]),A=g.useMemo(()=>!!s.isTemplate,[s.isTemplate]),M=g.useCallback(()=>{b("outline"),v(h.get(s,"id"),a)},[v,a,s,b]),E=g.useCallback(k=>{k.stopPropagation(),w()},[w]);return t.jsxs("div",{onClick:M,className:`rounded flex p-1.5 items-center justify-between leading-none cursor-pointer px-3 py-1.5 ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("button",{onClick:E,disabled:!m,className:`flex items-center justify-center w-4 h-5 text-gray-400 hover:text-gray-500 transition-colors ${m?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(N.ChevronRight,{size:16,className:`w-4 h-5 transition-transform duration-200 ${f?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(N.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):y!=null&&y.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:y.icon}}):y!=null&&y.hasSlug?t.jsx(N.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(N.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),!s.isPartialGroup&&t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:s.name}),y!=null&&y.hasSlug?t.jsxs(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:[S,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[h.endsWith(S,"/")?`${y==null?void 0:y.dynamicSlug}`:`/${y==null?void 0:y.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:y==null?void 0:y.name}),A&&t.jsx(o.Badge,{variant:"outline",className:"ml-2 text-xs py-0 font-normal text-blue-500 border border-blue-200 bg-blue-50",children:"Template"})]}),!s.isPartialGroup&&t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(Nr,{currentEditor:s.currentEditor}),t.jsx(Zn,{page:s,setDuplicatePage:d,setAddEditPage:l,setUnpublishPage:r,setDeletePage:i,setMarkAsTemplate:c,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"p-0.5 m-0 hover:bg-white rounded duration-100 cursor-pointer",children:t.jsx(N.MoreHorizontal,{className:"w-4 h-4",onClick:k=>k.stopPropagation()})})})]})]})},xi=({close:e,isOpen:s})=>{const[,n]=g.useState([]),[a,r]=g.useState(null),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,m]=g.useState(null),f=P=>c?String(h.get(P,"name","")).toLowerCase().includes(c.toLowerCase())||String(h.get(P,"key","")).toLowerCase().includes(c.toLowerCase()):!0,[w,v]=g.useState(null),[p,b]=g.useState(null),[y,S]=g.useState(null),[A,M]=g.useState(null),{data:E,isFetching:k,refetch:D}=Zt(),[Y,z]=g.useState(""),{hasPermission:ae}=U.usePermissions(),{updateForSelectedPage:H,expandPagesOnSearch:K,expandAll:se,collapseAll:Q}=sa(null),[ne,B]=Ie(),q=ne.get("page"),me=g.useRef(null),{data:ye}=Pe(),ue=U.useChaiFeatureFlag("enable-add-page-dropdown"),j=g.useCallback(P=>{var R;return(R=h.find(ye,{key:P}))==null?void 0:R.hasSlug},[ye]);g.useEffect(()=>{s&&D()},[s,D]),g.useEffect(()=>{if(!h.isEmpty(Y))return;const P=sessionStorage.getItem("pageTypeFilter")||"all";!h.isEmpty(ye)&&P&&(h.find(ye,{key:P})?z(P):z("all"))},[ye,Y]);const x=P=>{z(P),sessionStorage.setItem("pageTypeFilter",P),u("")},T=g.useCallback(P=>{const Z=new URLSearchParams(window.location.search).get("lang"),oe=new URLSearchParams({page:P});Z&&oe.set("lang",Z),window.history.pushState({},"",`?${oe.toString()}`),B(oe),window.dispatchEvent(new PopStateEvent("popstate")),e()},[B,e]);g.useEffect(()=>{if(q&&!k){const P=h.find(E,{id:q});P&&(P!=null&&P.pageType)?n(R=>[...R,P==null?void 0:P.pageType]):(window.history.replaceState(null,"","/"),B(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[E,q,k,B]);const L=g.useMemo(()=>E?fi(E,i,Y,j):[],[E,i,Y,j]);g.useEffect(()=>{q&&!k&&!h.isEmpty(L)&&(H(L,q),me.current&&me.current.scrollIntoView({behavior:"smooth",block:"end"}))},[q,k,L,H]),g.useEffect(()=>{!h.isEmpty(i)&&!h.isEmpty(L)&&K(L)},[i,L,K]);const G=g.useCallback(()=>{se(L)},[se,L]),$=g.useCallback(()=>{Q()},[Q]);return t.jsxs("div",{className:"flex flex-col justify-between h-full",children:[t.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[t.jsxs("div",{className:"flex gap-1 items-center justify-between",children:[t.jsxs("div",{className:"relative flex item-center gap-x-4 flex-1",children:[t.jsx(N.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:i,onChange:P=>l(P.target.value)}),!h.isEmpty(Y)&&t.jsxs(o.Select,{value:Y,onValueChange:x,children:[t.jsx(o.SelectTrigger,{className:`${Y==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} min-w-[120px] h-max p-0 py-1 pl-2 pr-1 top-1.5 -mt-px absolute text-gray-600 right-1.5 w-max text-xs whitespace-nowrap ring-0 focus:ring-0 shadow-none`,children:t.jsx(o.SelectValue,{placeholder:"Select page type"})}),t.jsxs(o.SelectContent,{align:"end",children:[ue&&t.jsx("div",{className:"px-3 py-2 sticky top-0 bg-white z-10",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(o.Input,{placeholder:"Search page types...",className:"pl-8 h-8 text-xs",value:c,onChange:P=>u(P.target.value),onKeyDown:P=>P.stopPropagation()})]})}),t.jsx(o.SelectItem,{value:"all",children:"All"},"all"),!h.isEmpty(h.filter(ye,P=>P.hasSlug&&f(P)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Pages"}),h.map([...h.filter(ye,P=>P.hasSlug&&f(P))].sort((P,R)=>h.get(P,"name","").localeCompare(h.get(R,"name",""))),P=>t.jsx(o.SelectItem,{value:h.get(P,"key"),children:h.get(P,"name")},h.get(P,"key")))]}),!h.isEmpty(h.filter(ye,P=>!P.hasSlug&&f(P)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Partials"}),h.map([...h.filter(ye,P=>!P.hasSlug&&f(P))].sort((P,R)=>h.get(P,"name","").localeCompare(h.get(R,"name",""))),P=>t.jsx(o.SelectItem,{value:h.get(P,"key"),children:h.get(P,"name")},h.get(P,"key")))]}),h.isEmpty(h.filter(ye,f))&&t.jsx("div",{className:"px-3 py-2 text-sm text-gray-500 text-center",children:"No matching page types found"})]})]})]}),t.jsxs("div",{className:"flex gap-1 ",children:[t.jsx(o.Button,{variant:"outline",size:"icon",onClick:G,className:"p-1 text-gray-500",children:t.jsx(N.ChevronsUpDown,{})}),t.jsx(o.Button,{variant:"outline",size:"icon",onClick:$,className:"p-1 text-gray-500",children:t.jsx(N.ChevronsDownUp,{})})]})]}),k?t.jsx("div",{className:"space-y-2",children:h.map([...Array(5).keys()],P=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},P))}):h.isEmpty(L)?t.jsxs("div",{className:"h-[70vh] flex flex-col gap-y-1 items-center justify-center text-slate-500 text-sm font-medium",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("div",{className:"text-sm text-slate-700 space-y-2 h-[70vh] overflow-y-auto",children:h.map(L,P=>{const R=P.id===q;return t.jsx("div",{ref:R?me:null,children:t.jsx(aa,{item:P,currentPage:q,close:e,setUnpublishPage:v,setDeletePage:m,setAddEditPage:b,setMarkAsTemplate:S,setUnmarkAsTemplate:M,setDuplicatePage:r,level:0})},`page-item-${P.id}`)})})]}),ae(ve.ADD_PAGE)&&t.jsxs(o.Button,{className:"flex text-sm gap-x-2",onClick:()=>{b({slug:"",name:"",pageType:Y==="all"?"page":Y})},children:[t.jsx(N.Plus,{className:"w-4 h-4"})," Add New"]}),p&&t.jsx(Yn,{closePanel:e,editPage:T,addEditPage:p,setAddEditPage:b}),d&&t.jsx(tn,{page:d,onClose:()=>m(null)}),w&&t.jsx(bs,{page:w,onClose:()=>v(null)}),y&&t.jsx(Xn,{page:y,onClose:()=>S(null)}),A&&t.jsx(ea,{page:A,onClose:()=>M(null)}),a&&t.jsx(Jn,{page:a,onClose:()=>r(null)})]})},aa=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:d,level:m=0})=>{const f=!h.isEmpty(e==null?void 0:e.children),{isExpanded:w,toggleExpanded:v}=sa(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(gi,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:f,isExpanded:w,onToggleExpand:v}),f&&w&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:h.map(h.get(e,"children",[]),p=>t.jsx(aa,{item:p,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:e.slug,level:m+1},p.id||`child-${m}-${p.key}`))})]},e.id||`level-${m}-${e.key}`)},nn=Ne.atom(null),pi=({page:e,onClose:s})=>{const[n,a]=g.useState(e.slug||""),{mutate:r,isPending:i}=Hr(),{data:l}=Pe(),c=h.find(l,{key:e==null?void 0:e.pageType}),u=m=>{if(m.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Be).some(v=>n===`/${v}`||h.startsWith(n,`/${v}/`))){V.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(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Change Slug"}),t.jsx(o.DialogDescription,{className:"text-xs",children:t.jsxs(o.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:[" ",(c==null?void 0:c.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(o.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(o.Input,{id:"slug",value:n,onChange:m=>{const f=m.target.value;h.startsWith(f,`/${d}`)&&a(f)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(o.DialogFooter,{children:t.jsx(o.Button,{type:"submit",disabled:i||!h.startsWith(n,`/${d}`)||h.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},Ge=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=U.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},yi=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Ce(),r=a==null?void 0:a.dynamic,{data:i}=Pe(),[l,c]=g.useState(e.name||""),[u,d]=g.useState(e.edit?e.lang:""),[m,f]=g.useState(e.edit?e.slug:""),[w,v]=g.useState(!0),[p,b]=g.useState(!0),{mutate:y,isPending:S}=Wn(),{mutate:A,isPending:M}=Ys(),{data:E}=$e(a==null?void 0:a.parent),{setSelectedLang:k,fallbackLang:D}=U.useLanguages(),[,Y]=Ie(),[,z]=U.useSidebarActivePanel(),ae=g.useMemo(()=>i==null?void 0:i.find(j=>j.key===e.pageType),[i,e.pageType]),H=r||!(ae!=null&&ae.hasSlug),K=(a==null?void 0:a.slug)==="/",se=S||M,{parentSlug:Q,isRootPage:ne}=g.useMemo(()=>{if(K||!u)return{parentSlug:void 0,isRootPage:!(a!=null&&a.parent)};if(!(a!=null&&a.parent))return{parentSlug:p?`/${u}`:void 0,isRootPage:!(a!=null&&a.parent)};const j=E==null?void 0:E.find(x=>x.lang===u);return{parentSlug:j==null?void 0:j.slug,isRootPage:!1}},[a==null?void 0:a.parent,E,p,u,K]);g.useEffect(()=>{if(!e.edit)return;const x=(e.slug||"").split("/").filter(Boolean);let T="";const L=G=>b(G);if(K){const G=x.pop()||"";if(Be[G])L(!0);else{T=G;const $=x.pop()||"";L(!!Be[$])}}else if(ne){if(x.length){T=x.pop()||"";const G=x.pop()||"";L(!!Be[G])}}else x.length&&(T=x.pop()||"");f(T)},[e,K,ne]);const B=g.useMemo(()=>ne?!0:!!(E!=null&&E.find(j=>(j==null?void 0:j.lang)===u)),[u,E,ne]),q=()=>{let j="";return ne?j=`/${p?[u,m].filter(Boolean).join("/"):m}`:j=`${He(Q)}/${m}`,j.replace(/\/{2,}/g,"/").replace(/\/$/,"")},me=(j,x)=>{const T=new URLSearchParams(window.location.search);x&&j===x?T.delete("lang"):T.set("lang",j);const L=T.toString(),G=`${window.location.pathname}${L?`?${L}`:""}`;window.history.pushState({},"",G),Y(T),window.dispatchEvent(new PopStateEvent("popstate"))},ye=j=>{j.preventDefault();const x={name:l,lang:u,primaryPage:a==null?void 0:a.id,slug:H?"":q(),pageType:a==null?void 0:a.pageType,tracking:{}};x.pageType=e.pageType,e.edit&&(x.id=e==null?void 0:e.id),e.edit?A(x,{onSuccess:s}):y(x,{onSuccess:()=>{u&&(k(u),me(u,D)),z("outline"),s()}})},ue=se||h.isEmpty(l)||h.isEmpty(u)||(H||K&&p?!1:!w||h.isEmpty(m));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"text-slate-600 sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:e.edit?re.EDIT_LANGUAGE:re.ADD_NEW_LANGUAGE}),t.jsx(o.DialogDescription,{className:"font-light",children:re.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:ye,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"lang",className:"text-right",children:re.LANGUAGE}),t.jsxs("select",{value:u,disabled:e.edit||h.isEmpty(n),onChange:j=>{const x=j.target.value;d(x),!e.edit&&h.startsWith(l,e.name)&&c(`${e.name} - ${Be[x]}`)},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,selected:!0,children:e.edit?h.get(Be,e.lang,e.lang):h.isEmpty(n)?re.ALL_AVAILABLE_LANGUAGE_PAGE:re.CHOOSE_LANGUAGE}),h.map(n,j=>t.jsx("option",{value:j,children:h.get(Be,j,j)},j))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-right",children:re.PAGE_NAME}),t.jsx(o.Input,{id:"name",value:u?l:"",onChange:j=>c(j.target.value),className:"col-span-3",required:!0,placeholder:u?re.ENTER_PAGE_NAME:re.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!B||!u})]}),!H&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"space-y-1",children:[ne&&u&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:p,onChange:j=>b(j.target.checked),className:"rounded border-gray-300"}),t.jsxs(o.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",u]}),") as slug prefix"]})]}),t.jsxs(o.Label,{htmlFor:"slug",className:"text-right",children:[re.SLUG," "]}),t.jsx(Zs,{disabled:h.isEmpty(u)||!B,value:m,onChange:f,placeholder:h.isEmpty(u)?re.CHOOSE_LANGUAGE_TO_ADD_SLUG:K&&p?"Leave empty for home page":re.ENTER_PAGE_SLUG,parentSlug:Q,onValidationChange:v,fullSlug:ue?"":q()})]})}),r&&u&&B&&t.jsxs("p",{className:"pb-2 text-sm",children:[t.jsx(o.Label,{children:"Dynamic Slug: "})," ",t.jsx("span",{className:"font-mono font-light",children:`${He(Q)}/${ae==null?void 0:ae.dynamicSlug}`})]})]}),t.jsx(o.DialogFooter,{children:B?t.jsx(o.Button,{type:"submit",disabled:ue,children:se?e.edit?re.UPDATING:re.ADDING:e.edit?re.UPDATE:re.ADD_NEW_LANGUAGE}):u&&t.jsx(o.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:Be[u]})," page in the parent to add here."]})})})]})]})})},ji=()=>{const[,e]=Ne.useAtom(nn),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=U.useLanguages(),{data:r,isFetching:i}=$e(),{data:l}=Ce(),{data:c}=Pe(),u=g.useMemo(()=>{const S=c==null?void 0:c.find(A=>A.key===(l==null?void 0:l.pageType));return S==null?void 0:S.dynamicSlug},[c,l==null?void 0:l.pageType]),[d,m]=g.useState(null),[f,w]=g.useState(null),[v,p]=g.useState(null),{data:b}=Qe(),y=h.filter(h.get(b,"languages")||["en"],S=>!h.find(r,{lang:S})&&S!==h.get(b,"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"})]}):h.map(r,S=>{const A=S.lang,M=S.slug,E=!S.primaryPage,k=A===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 ${k?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(A),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 ${S.online?"bg-green-300":"bg-gray-300"}`}),h.get(Be,E?n:A,A)]}),t.jsxs("div",{children:[M&&t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Slug: ",t.jsx("b",{className:"font-mono font-medium",children:u?`${M}/${u}`:M})]}),t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",S.name," "]})]})]})]}),E?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(Ge,{permissions:[ve.EDIT_PAGE,ve.DELETE_PAGE,ve.UNPUBLISH_PAGE],children:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:D=>D.stopPropagation(),children:t.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"z-[9999] text-sm",children:[t.jsx(Ge,{permissions:[ve.EDIT_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:D=>{D.stopPropagation(),e({...S,edit:!0})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),re.EDIT]})}),t.jsx(Ge,{permissions:[ve.UNPUBLISH_PAGE],children:(S==null?void 0:S.online)&&t.jsxs(o.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:D=>{D.stopPropagation(),w(S)},children:[t.jsx(N.Power,{className:"size-3"}),re.UNPUBLISH]})}),t.jsx(Ge,{permissions:[ve.DELETE_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:D=>{D.stopPropagation(),m(S)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),re.DELETE]})})]})]})})})]},S.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Ge,{permissions:[ve.ADD_PAGE],children:t.jsx("div",{className:"flex w-full justify-center",children:t.jsx(o.Button,{variant:"default",size:"sm",disabled:h.isEmpty(y),onClick:()=>{e({name:l==null?void 0:l.name,pageType:l==null?void 0:l.pageType,lang:"",slug:"",edit:!1})},children:re.ADD_NEW_LANGUAGE})})}),d&&t.jsx(tn,{page:d,onClose:()=>m(null)}),f&&t.jsx(bs,{page:f,onClose:()=>w(null)}),v&&t.jsx(pi,{page:v,onClose:()=>p(null)})]})},vi=()=>{const e=Ke("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:g.createElement(e,{})}):null},bi=()=>{const[e]=Ie(),s=e.get("page"),{data:n,isFetching:a}=Ce(),[r,i]=g.useState(!1),{savePage:l}=U.useSavePage(),c=!!s&&!h.isEmpty(n),u=!s||!a&&h.isEmpty(n)||r;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(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"outline",className:"flex w-full items-center space-x-2 py-1",onClick:()=>{l(),i(!0)},children:t.jsx(N.LogsIcon,{className:"h-4 w-4"})},"template-viewer")}),t.jsx(o.TooltipContent,{side:"right",children:t.jsx("p",{children:"Open pages manager"})})]})})}),t.jsx(o.Sheet,{open:u,onOpenChange:d=>!d&&c&&i(!1),children:t.jsxs(o.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`z-50 w-full !max-w-screen-md border-border ${c?"":"sheet-hide-close-btn"}`,children:[t.jsxs(o.SheetHeader,{className:"mb-3",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("div",{className:"rounded-md bg-primary p-2 text-primary-foreground",children:t.jsx(N.File,{className:"h-6 w-6"})}),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 text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(o.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(xi,{isOpen:u,close:()=>i(!1)})})]})})]})},an=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=U.useLanguages(),l=h.isEmpty(r)?n:r,[,c]=Ie();g.useEffect(()=>{const b=new URLSearchParams(window.location.search),y=b.get("lang");y&&(a.includes(y)?i(y):(b.delete("lang"),c(b),i("")))},[a,c,i]);const[,u]=Ne.useAtom(nn),{data:d}=Ce(),{data:m}=Qe(),{data:f,isFetching:w}=$e(),v=g.useMemo(()=>{const b=h.compact(h.map(h.get(m,"languages"),y=>{const S=h.find(f,{lang:y});return{key:y,value:h.get(Be,y,y),isLangPageAdded:!!S}})).filter(Boolean);return[{key:n,value:h.get(Be,n),isLangPageAdded:!0},...b]},[n,f,m]),p=b=>{i(b);const y=new URLSearchParams(window.location.search);b===n?y.delete("lang"):y.set("lang",b);const S=y.toString(),A=`${window.location.pathname}${S?`?${S}`:""}`;window.history.pushState({},"",A),c(y),window.dispatchEvent(new PopStateEvent("popstate"))};return h.isEmpty(a)||w?null:t.jsx(t.Fragment,{children:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(o.Button,{variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(N.Languages,{className:"h-4 w-4"}),h.get(Be,l,l),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"space-y-1 border-border",children:[h.map(v.filter(b=>b.isLangPageAdded),b=>t.jsxs(o.DropdownMenuItem,{className:U.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",b.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>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&&!h.isEmpty(v.filter(b=>!b.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(o.Separator,{}),t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:()=>{d&&u({name:d.name||"",pageType:d.pageType||"",lang:"",slug:"",edit:!1})},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 wi(){const[e,s]=Ne.useAtom(nn),{data:n}=$e(),{data:a}=Qe(),r=h.filter(h.get(a,"languages")||["en"],i=>!h.find(n,{lang:i})&&i!==h.get(a,"fallbackLang"));return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(vi,{}),t.jsx(bi,{}),e&&t.jsx(yi,{languages:r,langProps:e,onClose:()=>s(null)})]})}function Si(e){const s=ie(),n=J();return O.useQuery({queryKey:[W,"revisions",e],queryFn:async()=>await n(s,{action:I.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Ei=()=>{const e=ie(),s=J(),n=O.useQueryClient();return O.useMutation({mutationFn:async a=>await s(e,{action:I.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[W,"revisions"]})}})},Ni=()=>{const e=ie(),s=J(),n=O.useQueryClient();return O.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:I.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[W,"revisions"]})}})};function Ci(){const{data:e}=Ce(),{saveState:s}=U.useSavePage(),[n]=vs();return e?t.jsx("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50 bg-primary/5 mb-4",children:t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:t.jsx("span",{className:"font-bold",children:"Currently editing"})})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:!h.isEmpty(n.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",Nt.formatDistanceToNow(new Date(n.lastSaved),{addSuffix:!0})]})}),t.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[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.jsx(N.Edit,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]}),s==="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",{children:" Unsaved changes"})]}):null]})]})}):null}function Ai(){const[e,s]=we.useState(!1),[n,a]=we.useState(null),[r,i]=we.useState(!1),[l,c]=we.useState(!1),{data:u}=Ce(),{data:d,isFetching:m,error:f,refetch:w}=Si(u==null?void 0:u.id),{mutate:v,isPending:p}=Ei(),{mutate:b,isPending:y}=Ni(),S=O.useQueryClient(),A=D=>{n&&b({revisionId:n.uid,discardCurrent:D},{onSuccess:()=>{i(!1),a(null),S.invalidateQueries({queryKey:[W,I.GET_DRAFT_PAGE]})}})},M=D=>{a(D),i(!0)},E=D=>{a(D),c(!0)},k=()=>{n&&v(n.uid,{onSuccess:()=>{c(!1),a(null)}})};return g.useEffect(()=>{e&&w()},[e,w]),t.jsxs(t.Fragment,{children:[t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsxs(o.Sheet,{open:e,onOpenChange:s,children:[t.jsx(o.SheetTrigger,{asChild:!0,children:t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(o.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:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(o.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(o.SheetHeader,{className:"pb-2",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(N.History,{className:"h-5 w-5"}),"Revision History"]}),(u==null?void 0:u.createdAt)&&t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Page created on"," ",Nt.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(o.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:m?t.jsx(Ti,{}):f?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 space-y-2",children:[t.jsx(Ci,{}),d==null?void 0:d.map(D=>t.jsx(Pi,{revision:D,isLatest:D.uid==="current",onRestore:()=>M(D),onDelete:()=>E(D)},D.uid))]})})]})]}),t.jsx(o.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Li,{open:r,onOpenChange:i,revision:n,onRestore:A,isRestoring:y}),t.jsx(Ii,{open:l,onOpenChange:c,revision:n,onDelete:k,isDeleting:p})]})}function Ti(){return t.jsx("div",{className:"space-y-2 mt-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(o.Skeleton,{className:"h-4 w-3/4"}),t.jsx(o.Skeleton,{className:"h-3 w-1/2"}),t.jsx(o.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(o.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Pi({revision:e,isLatest:s,onRestore:n,onDelete:a}){const{data:r}=et(e.currentEditor),i=(r==null?void 0:r.name)||"Unknown";return t.jsxs("div",{className:"flex items-start gap-3 rounded-md border 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("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:[e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"font-bold",children:i}),s&&t.jsxs("span",{className:"ml-2 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:"mr-1 relative flex h-2 w-2",children:[t.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]}),"Live"]})]})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:t.jsx("span",{children:Nt.format(e.createdAt,"MMM d, h:mm a")})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:e.type==="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.ArrowUpRight,{className:"h-3 w-3"}),t.jsx("span",{children:"Published"})]}):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.jsx(N.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(Ge,{permissions:[ve.RESTORE_REVISION,ve.DELETE_REVISION],children:e.uid!=="current"&&t.jsx(ki,{revision:e,onRestore:n,onDelete:a})})]})}function ki({revision:e,onRestore:s,onDelete:n}){return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(N.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Ge,{permission:ve.RESTORE_REVISION,children:t.jsxs(o.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Ge,{permission:ve.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(o.DropdownMenuSeparator,{}),t.jsxs(o.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 Li({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=et((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Restore Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",Nt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.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(o.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 Ii({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=et((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",Nt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(o.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 _i=()=>{const e=ie(),s=J();return O.useQuery({queryKey:[W,I.GET_CHANGES],queryFn:async()=>s(e,{action:I.GET_CHANGES})})},Di=({currentEditor:e})=>{const{data:s}=et(e);return s==null?void 0:s.name};function Bi({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=g.useState([]),{data:r,isFetching:i}=_i(),{data:l}=Pe(),c=g.useCallback(E=>{var k;return(k=h.find(l,{key:E}))==null?void 0:k.hasSlug},[l]),u=g.useMemo(()=>h.filter(l,E=>!c(E.key)).map(E=>E.key),[c,l]),d=g.useMemo(()=>h.filter(r,E=>!u.includes(E.pageType)),[r,u]),m=g.useMemo(()=>h.filter(r,E=>u.includes(E.pageType)),[r,u]),f=g.useMemo(()=>h.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:w,isPending:v}=Js();g.useEffect(()=>{const E=h.map(h.filter(r,{online:!0}),"id");f&&E.push(f==null?void 0:f.id),a(E)},[r,f]);const p=n.length===(r==null?void 0:r.length),b=E=>{a(k=>h.includes(k,E)?h.filter(k,D=>D!==E):h.concat(k,E))},y=()=>{a(p?[]:h.map(r,"id"))},S=()=>{w({ids:h.uniq(n)},{onSuccess:()=>{s(),Dt("CENTER_CENTER")}})},A=E=>{if(E==="theme")return"Theme";const k=h.find(l,{key:E});return k?k==null?void 0:k.name:E},M=g.useMemo(()=>{const E=[{label:"Updated",top:"pt-2"},...h.orderBy(h.filter(d,{online:!0}),"pageType"),...h.orderBy(h.filter(m,{online:!0}),"pageType")].filter(Y=>Y.pageType!=="theme"),k=[{label:"Offline",top:"pt-6"},...h.orderBy(h.filter(d,{online:!1}),"pageType"),...h.orderBy(h.filter(m,{online:!1}),"pageType")],D=f?[{label:"Theme",top:"pt-6"},f]:[];return[...E,...D,...k]},[d,m,f]);return t.jsx(o.Dialog,{open:e,onOpenChange:v?()=>{}:s,children:t.jsxs(o.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Publish changes"}),t.jsx(o.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),t.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:i?t.jsxs("div",{className:"px-1 space-y-2",children:[t.jsx("div",{className:"w-full h-6 mt-2 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"})]}):t.jsxs("table",{className:"w-full text-xs text-left text-gray-500 rtl:text-right dark:text-gray-400",children:[t.jsx("thead",{className:"text-gray-700 border-b bg-gray-50 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"px-6 py-3 flex items-center gap-x-2 w-[1 50px]",children:[t.jsx("input",{checked:p,onClick:E=>{E.stopPropagation(),y()},type:"checkbox",className:"mt-1 rounded cursor-pointer focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Language"}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Type"}),t.jsx("th",{scope:"col",className:"px-4 py-3 w-[150px] text-right",children:"Status"})]})}),t.jsx("tbody",{children:h.map(M,E=>E.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${E.top}`,children:[t.jsx("div",{className:"absolute inset-0 flex items-center left-6",children:t.jsx("div",{className:"w-full order-gray-300"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"pr-2 bg-gray-50",children:E.label})})]})},"separator"):t.jsxs("tr",{className:"border-b group hover:bg-gray-50 last:border-b-0",children:[t.jsxs("td",{scope:"row",className:"flex items-center px-6 py-2 text-gray-900 whitespace-nowrap dark:text-white gap-x-1",children:[t.jsx("input",{checked:h.includes(n,E==null?void 0:E.id),onClick:k=>{k.stopPropagation(),b(E==null?void 0:E.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",c(E.pageType)?t.jsx(N.File,{className:"w-4 h-4"}):t.jsx(N.GlobeIcon,{className:"w-4 h-4"}),E.name,E.slug&&t.jsxs("span",{className:"text-xs text-gray-500",children:["(",E.slug,")"]}),E.currentEditor&&t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsxs("span",{className:"flex text-xs font-bold text-gray-500",children:[" ","-"," ",t.jsx(Di,{currentEditor:E.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:E.lang}),t.jsx("td",{className:"px-2",children:A(E==null?void 0:E.pageType)}),t.jsx("td",{className:"px-4 text-right",children:h.first(E.changes)||""})]},E==null?void 0:E.id))})]})}),t.jsxs(o.DialogFooter,{className:"mt-10",children:[t.jsx(o.Button,{disabled:v,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{disabled:v||i||h.isEmpty(r),onClick:S,children:v?"Publishing...":"Publish"})]})]})})}const Mi=()=>{const e=J(),s=ie();return O.useQuery({queryKey:[I.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_DATA,data:{draft:!0}})})};function Oi({onClose:e}){const{data:s,isFetching:n}=Mi(),{mutateAsync:a,isPending:r}=gr(),i=Ke("settingComponent",null),l=h.debounce(async c=>(await a({data:c}),!0),300);return i?t.jsx(o.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(o.DialogContent,{className:"w-full",children:[t.jsx(o.DialogHeader,{children:t.jsx(o.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:g.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function ra({children:e,content:s}){return t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:e}),t.jsx(o.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const Gi=()=>{const{selectedLang:e,fallbackLang:s}=U.useLanguages(),n=Ke("getPreviewUrl",async f=>f),[a,r]=g.useState(""),{data:i}=Ce(),{data:l}=$e(),{data:c}=Pe(),u=g.useMemo(()=>{var f;return(f=l==null?void 0:l.find(w=>(w==null?void 0:w.lang)===e))==null?void 0:f.slug},[e,l]),d=g.useCallback(f=>{var w;return(w=h.find(c,{key:f}))==null?void 0:w.hasSlug},[c]),m=e===s?"":e;return g.useEffect(()=>{(async()=>{if(typeof n=="function"){const f=!d(i==null?void 0:i.pageType),w=await n(f?`${m!==""?m+"/":""}${i==null?void 0:i.id}`:u||"");r(w)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,m]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(o.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Eye,{className:"h-4 w-4"})," ",re.PREVIEW]})})})},Ri=()=>{const[e,s]=U.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(ra,{content:re.THEME,children:t.jsx(o.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"})]})},Ui=()=>{const[e,s]=g.useState(!1),{isLocked:n}=es(),{savePage:a,saveState:r}=U.useSavePage();g.useEffect(()=>{const m=f=>{r==="UNSAVED"&&(f.preventDefault(),f.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",m),()=>{window.removeEventListener("beforeunload",m)}},[r]);const i=g.useCallback(async()=>{s(!0),await a(!1)},[a]);g.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=g.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:c,buttonClass:u,tooltipContent:d}=g.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:re.SAVEDRAFT,buttonIcon:t.jsx(N.Save,{className:"h-4 w-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:re.SAVING,buttonIcon:t.jsx(N.Loader,{className:"h-4 w-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:re.SAVED,buttonIcon:t.jsx(N.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[c," ",d]})},Fi=()=>{const{selectedLang:e}=U.useLanguages(),{data:s}=Ct(),{data:n}=$e(),[a,r]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState(null),{data:d}=Ce(),{mutate:m,isPending:f}=Js(),{buttonText:w,buttonClassName:v,isPublished:p}=g.useMemo(()=>{const S=d&&(d==null?void 0:d.online);return{buttonClassName:S?"hover:bg-green-600 bg-green-500":"",isPublished:S,buttonText:S?re.PUBLISHED:re.PUBLISH}},[d]),b=async()=>{const S=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];m({ids:h.compact(S)},{onSuccess:()=>Dt("TOP_RIGHT")})},y=g.useMemo(()=>h.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(o.Button,{size:"sm",onClick:b,disabled:f||!(d!=null&&d.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${v}`,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${i?"-translate-y-10":""}`,children:p?t.jsx(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:w}),e?`(${h.upperCase(e)})`:""]}),t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",disabled:f||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${v}`,children:t.jsx(N.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(o.DropdownMenuItem,{disabled:f,className:"cursor-pointer text-xs",onClick:()=>m({ids:y},{onSuccess:()=>Dt("TOP_RIGHT")}),children:[re.PUBLISH," with translation pages"]}),!p&&t.jsxs(o.DropdownMenuItem,{disabled:f,className:"cursor-pointer text-xs",onClick:()=>m({ids:[d==null?void 0:d.id]},{onSuccess:()=>Dt("TOP_RIGHT")}),children:[re.PUBLISH," page"]}),t.jsxs(o.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[re.OPEN," publish menu"]}),p&&t.jsxs(o.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[re.UNPUBLISH," page ",e?`(${h.upperCase(e)})`:""]})]})]})]}),t.jsx(Bi,{showModal:a,onClose:()=>r(!1)}),c&&t.jsx(bs,{page:c,onClose:()=>u(null)})]})},qi=()=>{const e=Ke("settingComponent",null),[s,n]=g.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(ra,{content:re.WEBSITEDATA,children:t.jsx(o.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(N.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(Oi,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function $i(){const{isLocked:e}=es(),[s]=Ie(),n=s.get("lang"),a=Fn(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Ai,{}),t.jsx(Ge,{permission:ve.EDIT_THEME,children:t.jsx(Ri,{})}),t.jsx(Ge,{permission:ve.EDIT_SETTINGS,children:t.jsx(qi,{})}),t.jsx(Gi,{}),t.jsx(Ge,{permission:ve.SAVE_PAGE,children:t.jsx(Ui,{})}),t.jsx(Ge,{permission:ve.PUBLISH_PAGE,children:t.jsx(Fi,{})})]})}const zi=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(o.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()}),Vi=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=U.useLanguages(),c=(i==null?void 0:i.length)===0;return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.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?h.get(e,"name"):"Select Page",t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(o.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(zi,{isDefaultLang:c,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(o.DropdownMenuItem,{onClick:()=>s(u),disabled:c?l!==u.lang:i!==u.lang,className:`flex flex-col justify-start cursor-pointer overflow-x-auto whitespace-nowrap no-scrollbar ${u.id===(e==null?void 0:e.id)?"bg-blue-50":"hover:bg-gray-50"}`,children:t.jsx("div",{className:"w-full text-xs whitespace-nowrap px-2 py-[2px]",children:t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("span",{className:"font-medium",children:u.name}),t.jsx("span",{className:"font-mono font-medium text-gray-500 text-xs rounded-full px-2 py-[1px] border border-gray-300 truncate",children:u.slug})]})})},u.id))]})]})},Hi=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:l,onChangeLanguage:c}=Hn(),u=g.useRef(void 0);return g.useEffect(()=>{u.current!==a&&e&&(c(),u.current=a)},[a,s]),t.jsx("div",{className:"relative",children:t.jsx(Vi,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:l,dynamicPages:n})})},Ki=()=>{const[e,s]=g.useState(null),[n,a]=g.useState(null),[r,i]=g.useState(null),[l,c]=g.useState(null),[u,d]=g.useState(null),[m,f]=g.useState(null),{data:w,isFetching:v}=Ce();return w?t.jsxs(t.Fragment,{children:[t.jsx(Zn,{page:w,setDuplicatePage:p=>d(p),setAddEditPage:p=>f(p),setUnpublishPage:p=>a(p),setDeletePage:p=>s(p),setMarkAsTemplate:p=>i(p),setUnmarkAsTemplate:p=>c(p),children:t.jsxs("div",{className:"flex cursor-pointer items-center justify-center space-x-2 rounded px-2 py-1 duration-100 hover:bg-gray-200",children:[t.jsx("span",{className:"flex max-w-[200px] items-center truncate text-xs font-medium leading-tight",children:v?t.jsx(N.Loader,{className:"ml-2 h-4 w-4 animate-spin text-slate-400"}):h.get(w,"name")??""}),t.jsx(N.MoreHorizontal,{className:"h-4 w-4",onClick:p=>p.stopPropagation()})]})}),m&&t.jsx(Yn,{closePanel:()=>f(null),editPage:()=>{},addEditPage:m,setAddEditPage:f}),e&&t.jsx(tn,{page:e,onClose:()=>s(null)}),n&&t.jsx(bs,{page:n,onClose:()=>a(null)}),r&&t.jsx(Xn,{page:r,onClose:()=>i(null)}),l&&t.jsx(ea,{page:l,onClose:()=>c(null)}),u&&t.jsx(Jn,{page:u,onClose:()=>d(null)})]}):null},Qi=({hasDynamicPage:e,className:s=""})=>t.jsx("div",{className:`z-[9999] fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-[50px] bg-black/30 backdrop-blur-sm ${s}`,children:t.jsxs("div",{className:"bg-white rounded-md p-4 shadow-xl min-w-[300px] max-w-[400px] flex flex-col items-center justify-center",children:[t.jsx("h1",{className:"text-lg font-medium",children:e?"Select a page":"No pages found"}),t.jsx("p",{className:"pt-4 text-center text-sm 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"})]})}),Wi=()=>{const{data:e}=Ct(),s=Vn(),{data:n,isFetching:a}=Ce(),r=h.get(n,"dynamic",!1),i=U.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:l,allLangPages:c}=Hn(),u=c.length>0,d=e==null?void 0:e.slug,m=!d;let f=window.location.origin+(d?d.endsWith("/")?d.slice(0,-1):d:"");s&&(f+=s);const v=(m?`Partial: ${e==null?void 0:e.name} `:`${d}${s}`).replace(window.location.host,"");return t.jsxs("div",{className:"flex items-center gap-x-1 relative z-10",children:[!a&&t.jsx("div",{className:"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",children:t.jsx(Ki,{})}),!a&&t.jsxs("div",{className:"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"+(m?" pr-2":""),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 font-mono text-xs ${m?"italic text-gray-400":"text-gray-500"}`,children:v===""?"/(Homepage)":v}),!m&&t.jsx("a",{href:f,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:[!l&&t.jsx(Qi,{hasDynamicPage:u}),t.jsx(Hi,{})]})]})},Yi=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(wi,{}),t.jsx(Wi,{}),t.jsx($i,{})]}),Ji=()=>{const e=ie(),{aiContext:s}=Hs(),n=J();return g.useCallback(async(a,r,i,l)=>n(e,{action:I.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},Xi=(e,s)=>s.map(n=>{if(h.has(e,n._type)){const a=Dn.getDefaultBlockProps(n._type);return{...a,...h.pick(n,[...h.keys(a),"_type","_id","_name","_parent","_bindings"]),...h.pickBy(n,(r,i)=>h.endsWith(i,"_attrs")),...n}}return n}),Zi=e=>{const s=Dn.useRegisteredChaiBlocks();return g.useMemo(()=>{if(!e||h.isEmpty(e))return{blocks:[]};const n=h.filter(e,a=>!h.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Xi(s,n)}},[e,s])},pn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=h.get(a,"html",""),i=h.get(a,"blocks",[]);return h.isArray(i)?i:U.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),[]}}},el=()=>{const e=ie(),s=J();return O.useQuery({queryKey:[W,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{U.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>pn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>pn.getUILibraryBlock(i,s,e)})}),a}})},ia=()=>{const e=js(),s=J(),{user:n}=Ue(),a=n==null?void 0:n.id;return O.useQuery({queryKey:[W,"permissions",a],queryFn:()=>s(e,{action:I.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},tl=()=>{const e=ie(),s=J(),{setCurrentEditor:n}=es(),[,a]=vs();return{onSave:async({page:i,blocks:l})=>{try{const c=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return c.code==="PAGE_LOCKED"?(n(c.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),c)}catch(c){return console.error(c),new Error("Failed to save blocks")}}}},sl=()=>{const{data:e}=Zt(),s=ie(),n=J();return{getPartialBlocks:g.useCallback(async()=>{const a={};for(const r of e??[])h.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:h.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:g.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return h.filter(r.blocks,i=>h.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},yn=ls.z.object({email:ls.z.string().email({message:"Please enter a valid email address"}),password:ls.z.string().min(6,{message:"Password must be at least 6 characters"})}),nl=()=>{const{setUser:e,logout:s}=Ue(),n=js(),[a,r]=g.useState(""),[i,l]=g.useState(""),[c,u]=g.useState({}),[d,m]=g.useState(!1),[f,w]=g.useState(""),v=O.useMutation({mutationFn:async y=>{w("");const S=await Vs(n,{action:"LOGIN",data:y});if(!S.ok){const M=await S.json();throw new Error(M.error||"Login failed")}const A=await S.json();if(h.has(A,"id")&&h.has(A,"email")&&h.has(A,"accessToken")&&h.has(A,"refreshToken"))e(A);else throw s(),new Error("Something went wrong. Please try again.");return A},onSuccess:()=>{u({}),w("")},onError:y=>{u({email:" ",password:" "}),w(y.message||"Something went wrong")}}),p=async y=>{y.preventDefault(),u({});const S={email:a,password:i};try{const A=yn.parse(S);v.mutate(A)}catch(A){if(A instanceof ls.z.ZodError){const M=A.errors.reduce((E,k)=>{const D=k.path[0];return E[D]=k.message,E},{});u(M)}}},b=yn.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(o.Card,{className:"w-full max-w-md",children:[t.jsxs(o.CardHeader,{children:[t.jsx(o.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(o.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(o.CardContent,{children:t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"email",children:"Email"}),t.jsx(o.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:y=>r(y.target.value),className:c.email?"border-destructive":""}),c.email&&t.jsx("p",{className:"text-sm text-destructive",children:c.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:y=>l(y.target.value),className:c.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>m(!d),children:d?t.jsx(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.Eye,{className:"h-4 w-4"})})]}),c.password&&t.jsx("p",{className:"text-sm text-destructive",children:c.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:f})}),t.jsx(o.Button,{type:"submit",className:"w-full",disabled:!b||v.isPending,children:v.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(o.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 border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let Bs=nl;const al=()=>g.useMemo(()=>Bs,[Bs]),rl=e=>{Bs=e},il=()=>{const e=al();return t.jsx(g.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},ll=({isActive:e,show:s})=>{const{data:n}=Qe();return!h.has(n,"languages")||!h.get(n,"languages",[]).length?null:t.jsx(o.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},la="lang",ol={id:la,label:"Languages",position:"top",panel:ji,button:ll,view:"modal",width:400};function Ye({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=we.useState(!1),[l,c]=we.useState([]),[u,d]=we.useState(e);we.useEffect(()=>{r||c([]),d(e)},[e,r]);const m=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",f=we.useCallback(p=>{const b=y=>n==="value"?y==="value"||y==="object":n==="array"?y==="array":y===n;p.type==="object"?(c(y=>[...y,p.key]),d(p.value)):b(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),w=we.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);c(p),d(p.reduce((b,y)=>b[y],e))}},[l,e]),v=we.useMemo(()=>Object.entries(u).map(([p,b])=>({key:p,value:b,type:m(b)})).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(o.Popover,{open:r,onOpenChange:i,children:[t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsx(o.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(N.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(o.TooltipContent,{children:"Add field"})]}),t.jsx(o.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(o.Command,{children:[t.jsx(o.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(o.CommandList,{onWheel:p=>{try{p.preventDefault();const b=p.currentTarget;b.scrollTop+=p.deltaY}catch{p.preventDefault()}},children:[t.jsx(o.CommandEmpty,{children:"No option found."}),t.jsxs(o.CommandGroup,{children:[l.length>0&&t.jsxs(o.CommandItem,{onSelect:w,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),v.map(p=>t.jsxs(o.CommandItem,{onSelect:()=>f(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(o.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:b=>{b.stopPropagation(),s([...l,p.key].join(".")),i(!1)},children:"Select"}),(p.type==="object"||p.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(N.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const cl=()=>{const{selectedLang:e}=U.useLanguages(),{data:s,isFetching:n}=$e();return{data:g.useMemo(()=>h.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},ul=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg").forEach(c=>c.remove()),a.querySelectorAll("*").forEach(c=>{Array.from(c.attributes).forEach(u=>c.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(c=>`<${c.tagName.toLowerCase()}>${c.innerHTML}</${c.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},kt=({keyword:e,onComplete:s,field:n})=>{const a=J(),r=ie(),{selectedLang:i,fallbackLang:l}=U.useLanguages(),c=U.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=O.useMutation({mutationFn:async()=>{const m=ul();return await a(r,{action:I.GENERATE_SEO_FIELD,data:{pageContext:c,dynamic:!1,field:n,lang:i||l,pageContent:m,keyword:e}})},onSuccess:m=>{s({fieldValue:m.field})},onError:m=>{s({fieldValue:null,error:m.message})}});return t.jsx(o.Button,{disabled:d,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:d?t.jsx(N.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(N.Sparkle,{className:"text-yellow-500"})})},dl=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),jn=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,c=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:c,position:l}),a=a.replace(i,c)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,c=l.message.match(/position (\d+)/),u=c?parseInt(c[1]):void 0;let d,m;if(u!==void 0){const f=a.substring(0,u).split(`
|
|
3
|
+
`);d=f.length,m=f[f.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:d,column:m,position:u}}}},hl=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,c=new RegExp(dl(l),"g");a=a.replace(c,r)}),a},ml=(e,s)=>{if(!e)return"";let n=JSON.stringify(e,null,2);const a=/{{([^{}]+)}}/g;let r;for(;(r=a.exec(n))!==null;){const i=r[1],l=h.get(s,i,null);n=n.replace(r[0],l)}return n},oa=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:l="json-input",pageData:c={},handleFieldInsert:u})=>{const[d,m]=g.useState("edit"),[f,w]=g.useState(null),[v,p]=g.useState(""),b=g.useRef(null),y=E=>{if(a)return;const k=E.target.value;s(k)},S=E=>{if(E.key==="Tab"){E.preventDefault();const k=E.currentTarget,D=k.selectionStart,Y=k.selectionEnd;if(D!==Y){const ae=e.substring(D,Y).split(`
|
|
4
|
+
`);if(E.shiftKey){const K=ae.map(Q=>Q.startsWith(" ")?Q.substring(2):Q).join(`
|
|
5
|
+
`),se=e.substring(0,D)+K+e.substring(Y);s(se),setTimeout(()=>{k.selectionStart=D,k.selectionEnd=D+K.length},0)}else{const K=ae.map(Q=>` ${Q}`).join(`
|
|
6
|
+
`),se=e.substring(0,D)+K+e.substring(Y);s(se),setTimeout(()=>{k.selectionStart=D,k.selectionEnd=D+K.length},0)}}else{const z=e.substring(0,D)+" "+e.substring(Y);s(z),setTimeout(()=>{k.selectionStart=k.selectionEnd=D+2},0)}}};g.useEffect(()=>{const E=jn(e);if(E.isValid)if(w(null),E.parsed){const k=ml(E.parsed,c);p(k)}else p("");else w(E.error),p("")},[e,c]);const A=()=>{const E=jn(e);if(E.isValid&&E.parsed){const k=hl(E.parsed,E.placeholders);s(k)}},M=()=>{f!=null&&f.position&&b.current&&(b.current.focus(),b.current.setSelectionRange(f.position,f.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(o.Tabs,{value:d,onValueChange:m,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(o.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(o.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(o.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||f!==null,children:[t.jsx(N.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),d==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{dataType:"value",data:c??{},onSelect:E=>u&&u(E,l)}),t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:!e.trim()||n||f!==null,children:"Format"})]})]}),t.jsxs(o.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(o.Textarea,{ref:b,id:l,name:l,className:`rounded-md border border-input text-xs ${f?"border-red-500":""}`,onChange:y,onKeyDown:S,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),f&&t.jsxs(o.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(o.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:f.message}),f.line&&f.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",f.line,", column ",f.column]}),t.jsx(o.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:M,children:"Show position"})]})]})]}),t.jsxs(o.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(o.Textarea,{rows:i,value:v,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."})]})]})})},vn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},fl=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),c=`{{${s}}}`,u=i+""+c+l,d=n+0+c.length;return{value:u,newCursorPos:d}},ca=()=>{const{t:e}=U.useTranslation(),[,s]=U.useSidebarActivePanel(),{data:n}=Ce(),{data:a}=Ws(),{data:r,isFetching:i}=cl(),l=r==null?void 0:r.seo,c=g.useRef(null),u=n==null?void 0:n.pageType,d=Qn(u),{selectedLang:m,fallbackLang:f}=U.useLanguages(),w=m||f,[v,p]=g.useState(!1),[b,y]=g.useState(!1),[S,A]=g.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),M=g.useRef({initial:S,updated:S}),{mutate:E,isPending:k}=Ys(),D=k||v||b,{hasPermission:Y}=U.usePermissions(),z=Y(ve.EDIT_SEO);g.useEffect(()=>{!i&&l&&A({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const ae=async()=>{if(!(!d||!w))try{p(!0);const B=us(d,w),q={...S,keyword:h.get(B,"seo.keyword",""),title:h.get(B,"seo.title",""),description:h.get(B,"seo.description",""),cononicalUrl:h.get(B,"seo.canonicalUrl",""),noIndex:h.get(B,"seo.noIndex",!1),noFollow:h.get(B,"seo.noFollow",!1),ogTitle:h.get(B,"seo.ogTitle",""),ogDescription:h.get(B,"seo.ogDescription","")};A(q),M.current.updated=q,V.toast.success(e("SEO fields reset to defaults"))}catch(B){V.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",B)}finally{p(!1)}},H=async()=>{if(!(!d||!w))try{y(!0);const B=us(d,w),q={...S,jsonLD:h.get(B,"seo.jsonLD","")};A(q),M.current.updated=q,V.toast.success(e("JSON-LD reset to default"))}catch(B){V.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",B)}finally{y(!1)}},K=async()=>{E({id:r==null?void 0:r.id,seo:S},{onSuccess:()=>{M.current.initial=S,M.current.updated=S,s("outline"),V.toast.success("SEO & JSON-LD updated successfully")}})},se=(B,q)=>{const me=document.getElementById(q);if(me){const{value:ye,newCursorPos:ue}=fl(me,B);c.current={id:q,position:ue},me.tagName.toLowerCase()==="input"?(me.value=ye,A(T=>({...T,[me.name]:ye})),me.focus(),me.setSelectionRange(ue,ue),[0,10,50,100,200].forEach(T=>{setTimeout(()=>{const L=document.getElementById(q);L&&(L.focus(),L.setSelectionRange(ue,ue))},T)})):(A(x=>({...x,[me.name]:ye})),requestAnimationFrame(()=>{const x=document.getElementById(q);x&&(x.focus(),x.setSelectionRange(ue,ue),setTimeout(()=>{const T=document.getElementById(q);T&&(T.focus(),T.setSelectionRange(ue,ue))},50))}))}},Q=B=>{const q={...S,[B.target.name]:B.target.name==="noIndex"||B.target.name==="noFollow"?B.target.checked:B.target.value};A(q),M.current.updated=q},ne=B=>q=>{h.isEmpty(q.fieldValue)||Q({target:{name:B,value:typeof q.fieldValue=="string"?q.fieldValue.replace(/^"(.*)"$/,"$1"):q.fieldValue}}),q.error&&V.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:q.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col",children:[!z&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm",children:t.jsx(o.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(o.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 p-2 text-left text-sm font-bold",children:[t.jsxs("span",{children:[r==null?void 0:r.name," ",t.jsx("br",{}),t.jsx("span",{className:"text-xs 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(o.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(o.TabsList,{className:"mb-4 grid w-full grid-cols-2",children:[t.jsx(o.TabsTrigger,{value:"seo",children:e("SEO Fields")}),t.jsx(o.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(o.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[z&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:ae,disabled:D||!z||!d,children:e(v?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),z&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:B=>se(B,"keyword")})]}),t.jsx(o.Input,{type:"text",id:"keyword",name:"keyword",value:S.keyword,onChange:Q,disabled:D||!z,placeholder:e("Enter keyword"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(kt,{keyword:S.keyword,onComplete:ne("title"),field:"title"}),z&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:B=>se(B,"title")})]})]}),t.jsx(o.Input,{type:"text",id:"title",name:"title",value:S.title,onChange:Q,disabled:D||!z,placeholder:e("Enter SEO title"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:S.keyword,onComplete:ne("description"),field:"description"}),z&&t.jsx(Ye,{data:a??{},onSelect:B=>se(B,"description")})]})]}),t.jsx(o.Textarea,{id:"description",name:"description",rows:5,value:S.description,onChange:Q,disabled:D||!z,placeholder:e("Enter SEO description"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),z&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:B=>se(B,"canonicalUrl")})]}),t.jsx(o.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:S.canonicalUrl,onChange:Q,disabled:D||!z,placeholder:e("Enter Canonical URL"),readOnly:!z})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(o.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:S.noIndex,onChange:Q,disabled:D||!z,className:"h-4 w-4"}),t.jsx(o.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(o.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:S.noFollow,onChange:Q,disabled:D||!z,className:"h-4 w-4"}),t.jsx(o.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.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(o.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:S.keyword,onComplete:ne("ogTitle"),field:"ogTitle"}),z&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:B=>se(B,"ogTitle")})]})]}),t.jsx(o.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:S.ogTitle,onChange:Q,disabled:D||!z,placeholder:e("Enter OG title"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:S.keyword,onComplete:ne("ogDescription"),field:"ogDescription"}),z&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:B=>se(B,"ogDescription")})]})]}),t.jsx(o.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:S.ogDescription,onChange:Q,disabled:D||!z,placeholder:e("Enter OG description"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(o.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Za,{assetId:S.ogImageId,assetUrl:S.ogImage,onChange:B=>{A({...S,ogImage:B.url,ogImageId:B.id})},disabled:D||!z,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(o.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[z&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{variant:"outline",size:"sm",type:"button",onClick:H,disabled:D||!z||!d,children:e(b?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(kt,{keyword:S.keyword,onComplete:ne("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(oa,{id:"jsonLD",value:S.jsonLD,onChange:B=>{Q({target:{name:"jsonLD",value:B}})},placeholder:e("Enter JSON-LD"),disabled:D||!z,readOnly:!z,pageData:a||{},rows:12,handleFieldInsert:se})]})]})})]})})]}),z&&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(S.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(o.Button,{onClick:K,disabled:!vn(S==null?void 0:S.jsonLD)||h.isEqual(M.current.initial,S)||D||!z,children:e(k?"Saving...":"Save")}),t.jsx(o.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]})]})};ca.displayName="SeoPanel";const ua="seo",gl=({isActive:e,show:s})=>{const{data:n}=Ce(),a=Qn(n==null?void 0:n.pageType);return!h.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(o.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},xl={id:ua,label:"SEO & JSON-LD",panel:ca,button:gl,position:"top",width:600,view:"modal"},pl="user-info",yl=()=>{const{user:e,logout:s}=Ue(),n=O.useQueryClient(),a=Ke("onLogout",h.noop);return e?t.jsxs(o.HoverCard,{children:[t.jsx(o.HoverCardTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(N.User,{className:"w-4 h-4"})})}),t.jsxs(o.HoverCardContent,{className:"w-auto p-4 space-y-2",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(o.AlertDialog,{children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(o.AlertDialogContent,{children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(o.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[W]}),h.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},jl={id:pl,label:"User Info",button:yl,position:"bottom"},vl=()=>{U.registerChaiSidebarPanel(ua,xl),U.registerChaiSidebarPanel(la,ol),U.registerChaiSidebarPanel("user-info",jl)};var te={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return bn(this.context.count)},getNextContextId(){return bn(this.context.count++)}};function bn(e){const s=String(e),n=s.length-1;return te.context.id+(n?String.fromCharCode(96+n):"")+s}function Lt(e){te.context=e}var bl=(e,s)=>e===s,ds=Symbol("solid-proxy"),da=typeof Proxy=="function",rn=Symbol("solid-track"),hs={equals:bl},ha=ja,We=1,ms=2,ma={owned:null,cleanups:null,context:null,owner:null},ks={},he=null,Ls=null,wl=null,xe=null,Le=null,Ve=null,ws=0;function Je(e,s){const n=xe,a=he,r=e.length===0,i=s===void 0?a:s,l=r?ma:{owned:null,cleanups:null,context:i?i.context:null,owner:i},c=r?e:()=>e(()=>Te(()=>Ot(l)));he=l,xe=null;try{return qe(c,!0)}finally{xe=n,he=a}}function Se(e,s){s=s?Object.assign({},hs,s):hs;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),ya(n,r));return[pa.bind(n),a]}function fa(e,s,n){const a=Ss(e,s,!0,We);At(a)}function Xe(e,s,n){const a=Ss(e,s,!1,We);At(a)}function ln(e,s,n){ha=Ml;const a=Ss(e,s,!1,We);(!n||!n.render)&&(a.user=!0),Ve?Ve.push(a):At(a)}function Me(e,s,n){n=n?Object.assign({},hs,n):hs;const a=Ss(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,At(a),pa.bind(a)}function Sl(e){return e&&typeof e=="object"&&"then"in e}function El(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,c=ks,u=null,d=!1,m="initialValue"in i,f=typeof a=="function"&&Me(a);const w=new Set,[v,p]=(i.storage||Se)(i.initialValue),[b,y]=Se(void 0),[S,A]=Se(void 0,{equals:!1}),[M,E]=Se(m?"ready":"unresolved");te.context&&(u=te.getNextContextId(),i.ssrLoadFrom==="initial"?c=i.initialValue:te.load&&te.has(u)&&(c=te.load(u)));function k(ae,H,K,se){return l===ae&&(l=null,se!==void 0&&(m=!0),(ae===c||H===c)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(se,{value:H})),c=ks,D(H,K)),H}function D(ae,H){qe(()=>{H===void 0&&p(()=>ae),E(H!==void 0?"errored":m?"ready":"unresolved"),y(H);for(const K of w.keys())K.decrement();w.clear()},!1)}function Y(){const ae=_l,H=v(),K=b();if(K!==void 0&&!l)throw K;return xe&&xe.user,H}function z(ae=!0){if(ae!==!1&&d)return;d=!1;const H=f?f():a;if(H==null||H===!1){k(l,Te(v));return}const K=c!==ks?c:Te(()=>r(H,{value:v(),refetching:ae}));return Sl(K)?(l=K,"value"in K?(K.status==="success"?k(l,K.value,void 0,H):k(l,void 0,Ms(K.value),H),K):(d=!0,queueMicrotask(()=>d=!1),qe(()=>{E(m?"refreshing":"pending"),A()},!1),K.then(se=>k(K,se,void 0,H),se=>k(K,void 0,Ms(se),H)))):(k(l,K,void 0,H),K)}return Object.defineProperties(Y,{state:{get:()=>M()},error:{get:()=>b()},loading:{get(){const ae=M();return ae==="pending"||ae==="refreshing"}},latest:{get(){if(!m)return Y();const ae=b();if(ae&&!l)throw ae;return v()}}}),f?fa(()=>z(!1)):z(!1),[Y,{refetch:z,mutate:p}]}function Nl(e){return qe(e,!1)}function Te(e){if(xe===null)return e();const s=xe;xe=null;try{return e()}finally{xe=s}}function Cl(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let c;if(a){c=Array(e.length);for(let d=0;d<e.length;d++)c[d]=e[d]()}else c=e();if(i)return i=!1,l;const u=Te(()=>s(c,r,l));return r=c,u}}function ga(e){ln(()=>Te(e))}function St(e){return he===null||(he.cleanups===null?he.cleanups=[e]:he.cleanups.push(e)),e}function wn(){return he}function Al(e,s){const n=he,a=xe;he=e,xe=null;try{return qe(s,!0)}catch(r){on(r)}finally{he=n,xe=a}}function Tl(e){const s=xe,n=he;return Promise.resolve().then(()=>{xe=s,he=n;let a;return qe(e,!1),xe=he=null,a?a.done:void 0})}var[Pl,Mc]=Se(!1);function kl(){return[Pl,Tl]}function Ll(e,s){const n=Symbol("context");return{id:n,Provider:Ol(n),defaultValue:e}}function Il(e){let s;return he&&he.context&&(s=he.context[e.id])!==void 0?s:e.defaultValue}function xa(e){const s=Me(e),n=Me(()=>Os(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var _l;function pa(){if(this.sources&&this.state)if(this.state===We)At(this);else{const e=Le;Le=null,qe(()=>gs(this),!1),Le=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 ya(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&qe(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=Ls&&Ls.running;l&&Ls.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Le.push(i):Ve.push(i),i.observers&&va(i)),l||(i.state=We)}if(Le.length>1e6)throw Le=[],new Error},!1)),s}function At(e){if(!e.fn)return;Ot(e);const s=ws;Dl(e,e.value,s)}function Dl(e,s,n){let a;const r=he,i=xe;xe=he=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=We,e.owned&&e.owned.forEach(Ot),e.owned=null),e.updatedAt=n+1,on(l)}finally{xe=i,he=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?ya(e,a):e.value=a,e.updatedAt=n)}function Ss(e,s,n,a=We,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:he,context:he?he.context:null,pure:n};return he===null||he!==ma&&(he.owned?he.owned.push(i):he.owned=[i]),i}function fs(e){if(e.state===0)return;if(e.state===ms)return gs(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<ws);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===We)At(e);else if(e.state===ms){const a=Le;Le=null,qe(()=>gs(e,s[0]),!1),Le=a}}function qe(e,s){if(Le)return e();let n=!1;s||(Le=[]),Ve?n=!0:Ve=[],ws++;try{const a=e();return Bl(n),a}catch(a){n||(Ve=null),Le=null,on(a)}}function Bl(e){if(Le&&(ja(Le),Le=null),e)return;const s=Ve;Ve=null,s.length&&qe(()=>ha(s),!1)}function ja(e){for(let s=0;s<e.length;s++)fs(e[s])}function Ml(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:fs(a)}if(te.context){if(te.count){te.effects||(te.effects=[]),te.effects.push(...e.slice(0,n));return}Lt()}for(te.effects&&(te.done||!te.count)&&(e=[...te.effects,...e],n+=te.effects.length,delete te.effects),s=0;s<n;s++)fs(e[s])}function gs(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===We?a!==s&&(!a.updatedAt||a.updatedAt<ws)&&fs(a):r===ms&&gs(a,s)}}}function va(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ms,n.pure?Le.push(n):Ve.push(n),n.observers&&va(n))}}function Ot(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),l=n.observerSlots.pop();a<r.length&&(i.sourceSlots[l]=a,r[a]=i,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Ot(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Ot(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 Ms(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function on(e,s=he){throw Ms(e)}function Os(e){if(typeof e=="function"&&!e.length)return Os(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Os(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Ol(e,s){return function(a){let r;return Xe(()=>r=Te(()=>(he.context={...he.context,[e]:a.value},xa(()=>a.children))),void 0),r}}var Gs=Symbol("fallback");function xs(e){for(let s=0;s<e.length;s++)e[s]()}function Gl(e,s,n={}){let a=[],r=[],i=[],l=0,c=s.length>1?[]:null;return St(()=>xs(i)),()=>{let u=e()||[],d=u.length,m,f;return u[rn],Te(()=>{let v,p,b,y,S,A,M,E,k;if(d===0)l!==0&&(xs(i),i=[],a=[],r=[],l=0,c&&(c=[])),n.fallback&&(a=[Gs],r[0]=Je(D=>(i[0]=D,n.fallback())),l=1);else if(l===0){for(r=new Array(d),f=0;f<d;f++)a[f]=u[f],r[f]=Je(w);l=d}else{for(b=new Array(d),y=new Array(d),c&&(S=new Array(d)),A=0,M=Math.min(l,d);A<M&&a[A]===u[A];A++);for(M=l-1,E=d-1;M>=A&&E>=A&&a[M]===u[E];M--,E--)b[E]=r[M],y[E]=i[M],c&&(S[E]=c[M]);for(v=new Map,p=new Array(E+1),f=E;f>=A;f--)k=u[f],m=v.get(k),p[f]=m===void 0?-1:m,v.set(k,f);for(m=A;m<=M;m++)k=a[m],f=v.get(k),f!==void 0&&f!==-1?(b[f]=r[m],y[f]=i[m],c&&(S[f]=c[m]),f=p[f],v.set(k,f)):i[m]();for(f=A;f<d;f++)f in b?(r[f]=b[f],i[f]=y[f],c&&(c[f]=S[f],c[f](f))):r[f]=Je(w);r=r.slice(0,l=d),a=u.slice(0)}return r});function w(v){if(i[f]=v,c){const[p,b]=Se(f);return c[f]=b,s(u[f],p)}return s(u[f])}}}function Rl(e,s,n={}){let a=[],r=[],i=[],l=[],c=0,u;return St(()=>xs(i)),()=>{const d=e()||[],m=d.length;return d[rn],Te(()=>{if(m===0)return c!==0&&(xs(i),i=[],a=[],r=[],c=0,l=[]),n.fallback&&(a=[Gs],r[0]=Je(w=>(i[0]=w,n.fallback())),c=1),r;for(a[0]===Gs&&(i[0](),i=[],a=[],r=[],c=0),u=0;u<m;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=Je(f));for(;u<a.length;u++)i[u]();return c=l.length=i.length=m,a=d.slice(0),r=r.slice(0,c)});function f(w){i[u]=w;const[v,p]=Se(d[u]);return l[u]=p,s(v,u)}}}function cn(e,s){return Te(()=>e(s||{}))}function as(){return!0}var Rs={get(e,s,n){return s===ds?n:e.get(s)},has(e,s){return s===ds?!0:e.has(s)},set:as,deleteProperty:as,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:as,deleteProperty:as}},ownKeys(e){return e.keys()}};function Is(e){return(e=typeof e=="function"?e():e)?e:{}}function Ul(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function un(...e){let s=!1;for(let l=0;l<e.length;l++){const c=e[l];s=s||!!c&&ds in c,e[l]=typeof c=="function"?(s=!0,Me(c)):c}if(da&&s)return new Proxy({get(l){for(let c=e.length-1;c>=0;c--){const u=Is(e[c])[l];if(u!==void 0)return u}},has(l){for(let c=e.length-1;c>=0;c--)if(l in Is(e[c]))return!0;return!1},keys(){const l=[];for(let c=0;c<e.length;c++)l.push(...Object.keys(Is(e[c])));return[...new Set(l)]}},Rs);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const c=e[l];if(!c)continue;const u=Object.getOwnPropertyNames(c);for(let d=u.length-1;d>=0;d--){const m=u[d];if(m==="__proto__"||m==="constructor")continue;const f=Object.getOwnPropertyDescriptor(c,m);if(!a[m])a[m]=f.get?{enumerable:!0,configurable:!0,get:Ul.bind(n[m]=[f.get.bind(c)])}:f.value!==void 0?f:void 0;else{const w=n[m];w&&(f.get?w.push(f.get.bind(c)):f.value!==void 0&&w.push(()=>f.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const c=i[l],u=a[c];u&&u.get?Object.defineProperty(r,c,u):r[c]=u?u.value:void 0}return r}function ba(e,...s){if(da&&ds in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(c){return l.includes(c)?e[c]:void 0},has(c){return l.includes(c)&&c in e},keys(){return l.filter(c=>c in e)}},Rs));return i.push(new Proxy({get(l){return r.has(l)?void 0:e[l]},has(l){return r.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!r.has(l))}},Rs)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let c=!1,u=0;for(const d of s)d.includes(r)&&(c=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;c||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function wa(e){let s,n;const a=r=>{const i=te.context;if(i){const[c,u]=Se();te.count||(te.count=0),te.count++,(n||(n=e())).then(d=>{!te.done&&Lt(i),te.count--,u(()=>d.default),Lt()}),s=c}else if(!s){const[c]=El(()=>(n||(n=e())).then(u=>u.default));s=c}let l;return Me(()=>(l=s())?Te(()=>{if(!i||te.done)return l(r);const c=te.context;Lt(i);const u=l(r);return Lt(c),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Fl=0;function ql(){return te.context?te.getNextContextId():`cl-${Fl++}`}var Sa=e=>`Stale read from <${e}>.`;function $l(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Me(Gl(()=>e.each,e.children,s||void 0))}function zl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Me(Rl(()=>e.each,e.children,s||void 0))}function Vl(e){const s=e.keyed,n=Me(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Me(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Te(()=>r(s?a:()=>{if(!Te(n))throw Sa("Show");return e.when})):r}return e.fallback},void 0,void 0)}function Hl(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=xa(()=>e.children),r=Me(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const c=i[l].when;if(c)return s=!!i[l].keyed,[l,c,i[l]]}return[-1]},void 0,{equals:n});return Me(()=>{const[i,l,c]=r();if(i<0)return e.fallback;const u=c.children;return typeof u=="function"&&u.length>0?Te(()=>u(s?l:()=>{if(Te(r)[0]!==i)throw Sa("Match");return c.when})):u},void 0,void 0)}function Kl(e){return e}var Ql=["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"],Wl=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...Ql]),Yl=new Set(["innerHTML","textContent","innerText","children"]),Jl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Xl=Object.assign(Object.create(null),{class:"className",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 Zl(e,s){const n=Xl[e];return typeof n=="object"?n[s]?n.$:void 0:n}var eo=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),to=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"]),so={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function no(e,s,n){let a=n.length,r=s.length,i=a,l=0,c=0,u=s[r-1].nextSibling,d=null;for(;l<r||c<i;){if(s[l]===n[c]){l++,c++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const m=i<a?c?n[c-1].nextSibling:n[i-c]:u;for(;c<i;)e.insertBefore(n[c++],m)}else if(i===c)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[c]===s[r-1]){const m=s[--r].nextSibling;e.insertBefore(n[c++],s[l++].nextSibling),e.insertBefore(n[--i],m),s[r]=n[i]}else{if(!d){d=new Map;let f=c;for(;f<i;)d.set(n[f],f++)}const m=d.get(s[l]);if(m!=null)if(c<m&&m<i){let f=l,w=1,v;for(;++f<r&&f<i&&!((v=d.get(s[f]))==null||v!==m+w);)w++;if(w>m-c){const p=s[l];for(;c<m;)e.insertBefore(n[c++],p)}else e.replaceChild(n[c++],s[l++])}else l++;else s[l++].remove()}}}var Bt="_$DX_DELEGATE";function Ea(e,s,n,a={}){let r;return Je(i=>{r=i,s===document?e():ys(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function ao(e,s,n){let a;const r=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},i=()=>(a||(a=r())).cloneNode(!0);return i.cloneNode=i,i}function Na(e,s=window.document){const n=s[Bt]||(s[Bt]=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,ka))}}function ro(e=window.document){if(e[Bt]){for(let s of e[Bt].keys())e.removeEventListener(s,ka);delete e[Bt]}}function ps(e,s,n){rt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function io(e,s,n,a){rt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function lo(e,s,n){rt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function Ca(e,s){rt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Aa(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 oo(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const c=r[i];!c||c==="undefined"||s[c]||(Sn(e,c,!1),delete n[c])}for(i=0,l=a.length;i<l;i++){const c=a[i],u=!!s[c];!c||c==="undefined"||n[c]===u||!u||(Sn(e,c,!0),n[c]=u)}return n}function co(e,s,n){if(!s)return n?ps(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 Ta(e,s={},n,a){const r={};return a||Xe(()=>r.children=Gt(e,s.children,r.children)),Xe(()=>typeof s.ref=="function"&&Pa(s.ref,e)),Xe(()=>uo(e,s,n,!0,r,!0)),r}function Pa(e,s,n){return Te(()=>e(s,n))}function ys(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Gt(e,s,a,n);Xe(r=>Gt(e,s(),r,n),a)}function uo(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=En(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const c=s[l];r[l]=En(e,l,c,r[l],n,i,s)}}function ho(e){let s,n;return!rt()||!(s=te.registry.get(n=fo()))?e():(te.completed&&te.completed.add(s),te.registry.delete(n),s)}function rt(e){return!!te.context&&!te.done&&(!e||e.isConnected)}function mo(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Sn(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 En(e,s,n,a,r,i,l){let c,u,d,m,f;if(s==="style")return co(e,n,a);if(s==="classList")return oo(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const w=s.slice(3);a&&e.removeEventListener(w,a,typeof a!="function"&&a),n&&e.addEventListener(w,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const w=s.slice(10);a&&e.removeEventListener(w,a,!0),n&&e.addEventListener(w,n,!0)}else if(s.slice(0,2)==="on"){const w=s.slice(2).toLowerCase(),v=eo.has(w);if(!v&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(w,p)}(v||n)&&(Aa(e,w,n,v),v&&Na([w]))}else if(s.slice(0,5)==="attr:")ps(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")lo(e,s.slice(5),n);else if((f=s.slice(0,5)==="prop:")||(d=Yl.has(s))||!r&&((m=Zl(s,e.tagName))||(u=Wl.has(s)))||(c=e.nodeName.includes("-")||"is"in l)){if(f)s=s.slice(5),u=!0;else if(rt(e))return n;s==="class"||s==="className"?Ca(e,n):c&&!u&&!d?e[mo(s)]=n:e[m||s]=n}else{const w=r&&s.indexOf(":")>-1&&so[s.split(":")[0]];w?io(e,w,s,n):ps(e,Jl[s]||s,n)}return n}function ka(e){if(te.registry&&te.events&&te.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}),l=()=>{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},c=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),te.registry&&!te.done&&(te.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,c();break}if(s.parentNode===r)break}}else c();i(a)}function Gt(e,s,n,a,r){const i=rt(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const m=n[d];m.nodeType===8&&m.data.slice(0,2)==="!$"?m.remove():u.push(m)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,c=a!==void 0;if(e=c&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(c){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=it(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(i)return n;n=it(e,n,a)}else{if(l==="function")return Xe(()=>{let u=s();for(;typeof u=="function";)u=u();n=Gt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Us(u,s,n,r))return Xe(()=>n=Gt(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let m=u[0];if(m.parentNode!==e)return n;const f=[m];for(;(m=m.nextSibling)!==a;)f.push(m);return n=f}if(u.length===0){if(n=it(e,n,a),c)return n}else d?n.length===0?Nn(e,u,a):no(e,n,u):(n&&it(e),Nn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=c?[s]:s;if(Array.isArray(n)){if(c)return n=it(e,n,a,s);it(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Us(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let c=s[i],u=n&&n[e.length],d;if(!(c==null||c===!0||c===!1))if((d=typeof c)=="object"&&c.nodeType)e.push(c);else if(Array.isArray(c))r=Us(e,c,u)||r;else if(d==="function")if(a){for(;typeof c=="function";)c=c();r=Us(e,Array.isArray(c)?c:[c],Array.isArray(u)?u:[u])||r}else e.push(c),r=!0;else{const m=String(c);u&&u.nodeType===3&&u.data===m?e.push(u):e.push(document.createTextNode(m))}}return r}function Nn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function it(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const c=s[l];if(r!==c){const u=c.parentNode===e;!i&&!l?u?e.replaceChild(r,c):e.insertBefore(r,n):u&&c.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function fo(){return te.getNextContextId()}var go="http://www.w3.org/2000/svg";function La(e,s=!1){return s?document.createElementNS(go,e):document.createElement(e)}function xo(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=wn();let i,l=!!te.context;return ln(()=>{l&&(wn().user=l=!1),i||(i=Al(r,()=>Me(()=>e.children)));const c=a();if(c instanceof HTMLHeadElement){const[u,d]=Se(!1),m=()=>d(!0);Je(f=>ys(c,()=>u()?f():i(),null)),St(m)}else{const u=La(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}),ys(d,i),c.appendChild(u),e.ref&&e.ref(u),St(()=>c.removeChild(u))}},void 0,{render:!l}),n}function po(e){const[s,n]=ba(e,["component"]),a=Me(()=>s.component);return Me(()=>{const r=a();switch(typeof r){case"function":return Te(()=>r(n));case"string":const i=to.has(r),l=te.context?ho():La(r,i);return Ta(l,n,i),l}})}var yo=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()}},Ia=class{constructor(e){this.generateIdentifier=e,this.kv=new yo}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)}},jo=class extends Ia{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 vo(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 bo(e,s){const n=vo(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 Et(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function os(e,s){return e.indexOf(s)!==-1}function Cn(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var wo=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return bo(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},So=e=>Object.prototype.toString.call(e).slice(8,-1),_a=e=>typeof e>"u",Eo=e=>e===null,Rt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Fs=e=>Rt(e)&&Object.keys(e).length===0,Ze=e=>Array.isArray(e),No=e=>typeof e=="string",Co=e=>typeof e=="number"&&!isNaN(e),Ao=e=>typeof e=="boolean",To=e=>e instanceof RegExp,Ut=e=>e instanceof Map,Ft=e=>e instanceof Set,Da=e=>So(e)==="Symbol",Po=e=>e instanceof Date&&!isNaN(e.valueOf()),ko=e=>e instanceof Error,An=e=>typeof e=="number"&&isNaN(e),Lo=e=>Ao(e)||Eo(e)||_a(e)||Co(e)||No(e)||Da(e),Io=e=>typeof e=="bigint",_o=e=>e===1/0||e===-1/0,Do=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Bo=e=>e instanceof URL,Ba=e=>e.replace(/\./g,"\\."),_s=e=>e.map(String).map(Ba).join("."),Mt=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 Fe(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Ma=[Fe(_a,"undefined",()=>null,()=>{}),Fe(Io,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),Fe(Po,"Date",e=>e.toISOString(),e=>new Date(e)),Fe(ko,"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}),Fe(To,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),Fe(Ft,"set",e=>[...e.values()],e=>new Set(e)),Fe(Ut,"map",e=>[...e.entries()],e=>new Map(e)),Fe(e=>An(e)||_o(e),"number",e=>An(e)?"NaN":e>0?"Infinity":"-Infinity",Number),Fe(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),Fe(Bo,"URL",e=>e.toString(),e=>new URL(e))];function Es(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Oa=Es((e,s)=>Da(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}),Mo=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),Ga=Es(Do,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Mo[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function Ra(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var Ua=Es(Ra,(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 - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");return Object.assign(Object.create(a.prototype),e)}),Fa=Es((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)}),Oo=[Ua,Oa,Fa,Ga],Tn=(e,s)=>{const n=Cn(Oo,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=Cn(Ma,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},qa={};Ma.forEach(e=>{qa[e.annotation]=e});var Go=(e,s,n)=>{if(Ze(s))switch(s[0]){case"symbol":return Oa.untransform(e,s,n);case"class":return Ua.untransform(e,s,n);case"custom":return Fa.untransform(e,s,n);case"typed-array":return Ga.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=qa[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},lt=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function $a(e){if(os(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(os(e,"prototype"))throw new Error("prototype is not allowed as a property");if(os(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Ro=(e,s)=>{$a(s);for(let n=0;n<s.length;n++){const a=s[n];if(Ft(e))e=lt(e,+a);else if(Ut(e)){const r=+a,i=+s[++n]==0?"key":"value",l=lt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},qs=(e,s,n)=>{if($a(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Ze(a)){const c=+l;a=a[c]}else if(Rt(a))a=a[l];else if(Ft(a)){const c=+l;a=lt(a,c)}else if(Ut(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",m=lt(a,u);switch(d){case"key":a=m;break;case"value":a=a.get(m);break}}}const r=s[s.length-1];if(Ze(a)?a[+r]=n(a[+r]):Rt(a)&&(a[r]=n(a[r])),Ft(a)){const i=lt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Ut(a)){const i=+s[s.length-2],l=lt(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(l);a.set(u,a.get(l)),u!==l&&a.delete(l);break}case"value":{a.set(l,n(a.get(l)));break}}}return e};function $s(e,s,n=[]){if(!e)return;if(!Ze(e)){Et(e,(i,l)=>$s(i,s,[...n,...Mt(l)]));return}const[a,r]=e;r&&Et(r,(i,l)=>{$s(i,s,[...n,...Mt(l)])}),s(a,n)}function Uo(e,s,n){return $s(s,(a,r)=>{e=qs(e,r,i=>Go(i,a,n))}),e}function Fo(e,s){function n(a,r){const i=Ro(e,Mt(r));a.map(Mt).forEach(l=>{e=qs(e,l,()=>i)})}if(Ze(s)){const[a,r]=s;a.forEach(i=>{e=qs(e,Mt(i),()=>e)}),r&&Et(r,n)}else Et(s,n);return e}var qo=(e,s)=>Rt(e)||Ze(e)||Ut(e)||Ft(e)||Ra(e,s);function $o(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function zo(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(c=>c.map(String)).sort((c,u)=>c.length-u.length));const[i,...l]=r;i.length===0?a=l.map(_s):n[_s(i)]=l.map(_s)}),a?Fs(n)?[a]:[a,n]:Fs(n)?void 0:n}var za=(e,s,n,a,r=[],i=[],l=new Map)=>{const c=Lo(e);if(!c){$o(e,r,s);const v=l.get(e);if(v)return a?{transformedValue:null}:v}if(!qo(e,n)){const v=Tn(e,n),p=v?{transformedValue:v.value,annotations:[v.type]}:{transformedValue:e};return c||l.set(e,p),p}if(os(i,e))return{transformedValue:null};const u=Tn(e,n),d=(u==null?void 0:u.value)??e,m=Ze(d)?[]:{},f={};Et(d,(v,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 b=za(v,s,n,a,[...r,p],[...i,e],l);m[p]=b.transformedValue,Ze(b.annotations)?f[p]=b.annotations:Rt(b.annotations)&&Et(b.annotations,(y,S)=>{f[Ba(p)+"."+S]=y})});const w=Fs(f)?{transformedValue:m,annotations:u?[u.type]:void 0}:{transformedValue:m,annotations:u?[u.type,f]:f};return c||l.set(e,w),w};function Va(e){return Object.prototype.toString.call(e).slice(8,-1)}function Pn(e){return Va(e)==="Array"}function Vo(e){if(Va(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Ho(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 zs(e,s={}){if(Pn(e))return e.map(r=>zs(r,s));if(!Vo(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(Pn(s.props)&&!s.props.includes(i))return r;const l=e[i],c=zs(l,s);return Ho(r,i,c,e,s.nonenumerable),r},{})}var pe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new jo,this.symbolRegistry=new Ia(s=>s.description??""),this.customTransformerRegistry=new wo,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=za(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=zo(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=zs(s);return n!=null&&n.values&&(a=Uo(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Fo(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 Ha=pe.serialize,Ko=pe.stringify;function Qo(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function Wo(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function Yo({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function Jo({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function Xo(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var Zo=(e,s=!1)=>{const{json:n}=Ha(e);return JSON.stringify(n,null,s?2:void 0)},rs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,ec=(e,s)=>e.queryHash.localeCompare(s.queryHash),Ka=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,tc=(e,s)=>rs(e)===rs(s)?Ka(e,s):rs(e)>rs(s)?1:-1,sc={status:tc,"query hash":ec,"last updated":Ka},is=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Qa=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,nc=(e,s)=>is(e)===is(s)?Qa(e,s):is(e)>is(s)?1:-1,ac={status:nc,"last updated":Qa},rc=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),ic=()=>{const[e,s]=Se("dark");return ga(()=>{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),St(()=>n.removeEventListener("change",a))}),e},It=(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,It(a.get(r),i,n)),a}if(e instanceof Set){const a=It(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]=It(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]=It(a[r],i,n),a}return e},_t=(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,_t(n.get(a),r)),n}if(e instanceof Set){const n=_t(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,l)=>l.toString()!==s[0]);const[a,...r]=s;return n[a]=_t(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]=_t(n[a],r),n}return e},Wa=(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)},ot,qt,$t,zt,nt,Vt,ct,ut,dt,ht,mt,ft,Ht,In,lc=(In=class{constructor(e){ge(this,ot);ge(this,qt);ge(this,$t);ge(this,zt);ge(this,nt,!1);ge(this,Vt);ge(this,ct);ge(this,ut);ge(this,dt);ge(this,ht);ge(this,mt);ge(this,ft);ge(this,Ht);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:m}=e;fe(this,ot,Se(s)),fe(this,$t,n),fe(this,zt,a),fe(this,qt,r),fe(this,Vt,d),fe(this,ct,m),fe(this,ut,Se(i)),fe(this,dt,Se(l)),fe(this,ht,Se(c)),fe(this,mt,Se(u))}setButtonPosition(e){X(this,ut)[1](e)}setPosition(e){X(this,dt)[1](e)}setInitialIsOpen(e){X(this,ht)[1](e)}setErrorTypes(e){X(this,mt)[1](e)}setClient(e){X(this,ot)[1](e)}mount(e){if(X(this,nt))throw new Error("Devtools is already mounted");const s=Ea(()=>{const n=this,[a]=X(this,ut),[r]=X(this,dt),[i]=X(this,ht),[l]=X(this,mt),[c]=X(this,ot);let u;return X(this,ft)?u=X(this,ft):(u=wa(()=>Promise.resolve().then(()=>require("./HO4MOOFI-qasqgyBd.cjs"))),fe(this,ft,u)),Wa(X(this,Vt),X(this,ct)),cn(u,un({get queryFlavor(){return X(n,$t)},get version(){return X(n,zt)},get onlineManager(){return X(n,qt)},get shadowDOMTarget(){return X(n,ct)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);fe(this,nt,!0),fe(this,Ht,s)}unmount(){var e;if(!X(this,nt))throw new Error("Devtools is not mounted");(e=X(this,Ht))==null||e.call(this),fe(this,nt,!1)}},ot=new WeakMap,qt=new WeakMap,$t=new WeakMap,zt=new WeakMap,nt=new WeakMap,Vt=new WeakMap,ct=new WeakMap,ut=new WeakMap,dt=new WeakMap,ht=new WeakMap,mt=new WeakMap,ft=new WeakMap,Ht=new WeakMap,In),gt,Kt,Qt,Wt,at,Yt,xt,pt,yt,jt,vt,bt,wt,Jt,_n,oc=(_n=class{constructor(e){ge(this,gt);ge(this,Kt);ge(this,Qt);ge(this,Wt);ge(this,at,!1);ge(this,Yt);ge(this,xt);ge(this,pt);ge(this,yt);ge(this,jt);ge(this,vt);ge(this,bt);ge(this,wt);ge(this,Jt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:m,onClose:f}=e;fe(this,gt,Se(s)),fe(this,Qt,n),fe(this,Wt,a),fe(this,Kt,r),fe(this,Yt,d),fe(this,xt,m),fe(this,pt,Se(i)),fe(this,yt,Se(l)),fe(this,jt,Se(c)),fe(this,vt,Se(u)),fe(this,bt,Se(f))}setButtonPosition(e){X(this,pt)[1](e)}setPosition(e){X(this,yt)[1](e)}setInitialIsOpen(e){X(this,jt)[1](e)}setErrorTypes(e){X(this,vt)[1](e)}setClient(e){X(this,gt)[1](e)}setOnClose(e){X(this,bt)[1](()=>e)}mount(e){if(X(this,at))throw new Error("Devtools is already mounted");const s=Ea(()=>{const n=this,[a]=X(this,pt),[r]=X(this,yt),[i]=X(this,jt),[l]=X(this,vt),[c]=X(this,gt),[u]=X(this,bt);let d;return X(this,wt)?d=X(this,wt):(d=wa(()=>Promise.resolve().then(()=>require("./HUY7CZI3-DnWtCer3.cjs"))),fe(this,wt,d)),Wa(X(this,Yt),X(this,xt)),cn(d,un({get queryFlavor(){return X(n,Qt)},get version(){return X(n,Wt)},get onlineManager(){return X(n,Kt)},get shadowDOMTarget(){return X(n,xt)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);fe(this,at,!0),fe(this,Jt,s)}unmount(){var e;if(!X(this,at))throw new Error("Devtools is not mounted");(e=X(this,Jt))==null||e.call(this),fe(this,at,!1)}},gt=new WeakMap,Kt=new WeakMap,Qt=new WeakMap,Wt=new WeakMap,at=new WeakMap,Yt=new WeakMap,xt=new WeakMap,pt=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,Jt=new WeakMap,_n);function cc(e){const s=O.useQueryClient(e.client),n=we.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}=e,[d]=we.useState(new lc({client:s,queryFlavor:"React Query",version:"5",onlineManager:O.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}));return we.useEffect(()=>{d.setClient(s)},[s,d]),we.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),we.useEffect(()=>{r&&d.setPosition(r)},[r,d]),we.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),we.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),we.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function uc(e){const s=O.useQueryClient(e.client),n=we.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=we.useState(new oc({client:s,queryFlavor:"React Query",version:"5",onlineManager:O.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose}));return we.useEffect(()=>{l.setClient(s)},[s,l]),we.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),we.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),we.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 dc=process.env.NODE_ENV!=="development"?function(){return null}:cc;process.env.NODE_ENV;const Ya=()=>t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/40",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(N.Loader2,{className:"size-5 animate-spin"})})}),hc=()=>{U.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),U.registerChaiFeatureFlag("realtime-page-lock",{description:"Realtime page lock"}),U.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"})},mc=()=>{const e=ie(),s=J();return O.useQuery({queryKey:[W,I.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:I.GET_COLLECTIONS})})},fc=()=>{const{data:e}=Ce(),{data:s}=Ct(),{data:n}=Qe(),a=ie(),r=J(),i=g.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return O.useMutation({mutationFn:async({block:l})=>r(a,{action:I.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},Ja=()=>{const e=en();return g.useCallback(({pageId:s})=>{e(s)},[e])},gc=60*5;function xc(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:r}=Ue(),i=js(),l=g.useRef(null),c=g.useCallback(async()=>{if(!(!h.has(e,"expiresAt")||!h.has(e,"accessToken")||!h.has(e,"refreshToken")))try{const u=await Vs(i,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!u.ok){n();return}const d=await u.json();h.has(d,"id")&&h.has(d,"email")&&h.has(d,"accessToken")&&h.has(d,"refreshToken")?s(d):n()}catch{n()}},[e,n,s,i]);return g.useEffect(()=>{a&&r&&c()},[r,a,c]),g.useEffect(()=>{if(!a||!h.has(e,"expiresAt")||!h.has(e,"refreshToken")||!h.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!h.has(e,"expiresAt")||!h.has(e,"refreshToken")||!h.has(e,"accessToken"))return;const u=Math.floor(Date.now()/1e3),d=e.expiresAt-u;d<gc&&d>0&&c()},1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[a,e==null?void 0:e.expiresAt,e==null?void 0:e.refreshToken,e==null?void 0:e.accessToken,i]),null}const pc=g.lazy(()=>Promise.resolve().then(()=>Ic));hc();rr.loadWebBlocks();U.registerChaiTopBar(Yi);vl();U.registerChaiMediaManager(pc);U.registerChaiSaveToLibrary(Rr);const yc=e=>{const s=g.useRef([]),[n]=Ie(),a=n.get("page"),{data:r}=Ce(),{data:i={role:"",permissions:null}}=ia();el(),br();const{data:l,isFetching:c}=Kn(),{blocks:u}=Zi(l),{data:d}=Pe(),{mutateAsync:m}=Gn(),f=Ji(),{onSave:w}=tl(),{getPartialBlocks:v,getPartialBlockBlocks:p}=sl(),{aiContext:b,setAiContext:y}=Hs(),{mutateAsync:S}=Fr(),[A,M]=g.useState(!1),{data:E}=Qe(),k=Qs(),{data:D}=Ws(),{data:Y}=mc(),{mutateAsync:z}=fc(),ae=Ja();pr(),g.useEffect(()=>{const Q=()=>{document.hidden?M(!0):M(!1)};return window.addEventListener("visibilitychange",Q),()=>window.removeEventListener("visibilitychange",Q)},[]),s.current=u;const H=g.useMemo(()=>{const Q={};return i&&(Q.permissions=h.get(i,"permissions",null),Q.role=h.get(i,"role","user")),Q},[i]),K=g.useCallback(async(Q,ne)=>await S({pageType:Q,query:ne}),[S]),se=g.useMemo(()=>h.get(E,"theme",{})||{},[E]);return t.jsxs(t.Fragment,{children:[c&&t.jsx(Ya,{}),t.jsx(U.ChaiBuilderEditor,{gotoPage:ae,collections:Y??[],getBlockAsyncProps:z,pageExternalData:D,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:c,fallbackLang:k,languages:(E==null?void 0:E.languages)||[],brandingOptions:(E==null?void 0:E.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!A&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:v,blocks:c?[]:u,theme:h.cloneDeep(se),pageTypes:d,searchPageTypeItems:K,saveAiContextCallback:async Q=>{if(!a)return!0;const ne=s.current,B={_type:"@chai/ai-context",_value:h.isString(Q)?Q:""},q=[...ne,B];return await w({page:a,blocks:q}),y(Q),!0},aiContext:b,askAiCallBack:f,onSave:async({blocks:Q,theme:ne})=>{if(!a)return!0;s.current=Q;const B={_type:"@chai/ai-context",_value:h.isString(b)?b:""},q=[...Q,B];return await w({page:a,blocks:q}),s.current=q,h.isEqual(ne,se)||await m({settings:{theme:ne}}),!0},themePanelComponent:Yr,...H}),t.jsxs("div",{children:[t.jsx(Tr,{}),t.jsx(Pr,{})]})]})},jc=new O.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),vc=e=>{xc();const{isLoggedIn:s,isSessionExpired:n}=Ue(),[,a]=Rn(),[r,i]=g.useState(!1);return g.useEffect(()=>(a(h.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","realtimeInstance"])),setTimeout(()=>{i(!0)},200),()=>{i(!1),a({})}),[e,a]),r?t.jsxs(O.QueryClientProvider,{client:jc,children:[s?n?t.jsx(Ya,{}):t.jsx(yc,{...e}):t.jsx(il,{}),t.jsx(dc,{}),t.jsx(V.Toaster,{richColors:!0})]}):t.jsx("div",{})},bc=()=>{const e=ie(),s=J(),{data:n}=Ct(),a=O.useQueryClient();return O.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:I.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[W,I.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},wc=()=>{const e=Xt(),s=O.useQueryClient(),n=J();return O.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:I.UPLOAD_ASSET,data:{file:a,folderId:r,name:i,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[W,I.GET_ASSETS]}),V.toast.success("Asset uploaded successfully")},onError:()=>{V.toast.error("Failed to upload asset")}})},Sc=()=>{const e=Xt(),s=O.useQueryClient(),n=J();return O.useMutation({mutationFn:async a=>n(e,{action:I.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[W,I.GET_ASSETS]}),V.toast.success("Asset deleted successfully")},onError:()=>{V.toast.error("Failed to delete asset")}})},Ec=()=>{const e=Xt(),s=O.useQueryClient(),n=J();return O.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[W,I.GET_ASSETS]}),V.toast.success("Asset updated successfully")},onError:()=>{V.toast.error("Failed to update asset")}})},Nc=(e={})=>{const s=Xt(),n=J(),{search:a,page:r=1,limit:i=30}=e;return O.useQuery({queryKey:[W,I.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:I.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},Cc=e=>{const s=Xt(),n=J();return O.useQuery({queryKey:[W,I.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:I.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Ac(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 kn(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 Ln(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 Tc=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var f,w,v;const{data:i,isLoading:l,isError:c}=Cc(e||""),[u,d]=g.useState(""),m=async(p,b)=>{try{await navigator.clipboard.writeText(p),V.toast.success(`${b} copied to clipboard`)}catch(y){V.toast.error(`Failed to copy ${b}`,{description:y==null?void 0:y.message})}};return g.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}):c||!(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:c?"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(o.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),c&&t.jsx(o.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(o.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(o.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(o.Button,{variant:"outline",onClick:()=>m(i.url,"Asset URL"),disabled:r,children:[t.jsx(N.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(o.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=${((f=i.metadata)==null?void 0:f.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(o.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:((w=i.metadata)==null?void 0:w.format)||i.type,capitalize:!0},{label:"Size",value:Ac(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:kn(i.createdAt)},{label:"Updated",value:kn(((v=i.metadata)==null?void 0:v.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.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(o.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>m(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(o.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,b)=>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,")"]})]},b))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(o.Label,{className:"w-full text-center",children:"Description"}),t.jsx(o.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||!Ln(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Ln(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"})})]})]})]})]})},Pc=g.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function kc(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"}const Lc=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,c]=g.useState(()=>{const v=localStorage.getItem("chai_optimize_images");return v!==null?v==="true":!0});g.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=g.useCallback(async v=>new Promise((p,b)=>{const y=v[0],S=new FileReader;S.readAsDataURL(y),S.onload=async()=>{a({file:S.result,folderId:void 0,name:y.name,optimize:l},{onSuccess:A=>{i&&i(A),p(A)},onError:A=>{b(A)}})},S.onerror=A=>b(A)}),[a,l,i]),{getRootProps:m,getInputProps:f,isDragActive:w}=ar.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},maxSize:n*1024*1024,disabled:e||r});return t.jsx("div",{className:`flex flex-col items-center justify-center w-full border-2 hover:border-black/50 border-dashed p-0 rounded-lg border-slate-300 py-2 h-[60px] ${u?"opacity-90 bg-gray-100 pointer-events-none":"hover:border-black/50 bg-gray-100 hover:bg-gray-100"}`,children:t.jsxs("div",{...m(),className:U.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",w?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...f()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",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 text-indigo-500 animate-spin"})}),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 text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",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:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(o.Switch,{checked:l,onCheckedChange:v=>{c(v)},onClick:v=>{v.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(N.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(o.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Xa({close:e,onSelect:s,mode:n="image",assetId:a}){const l=g.useMemo(()=>[n],[n]),[c,u]=g.useState(null),[d,m]=g.useState(null),[f,w]=g.useState(null),[v,p]=g.useState({show:!1,file:""}),[b,y]=g.useState(!1),[S,A]=g.useState(a?"details":"grid"),[M,E]=g.useState(""),[k,D]=g.useState(""),[Y,z]=g.useState(1),[ae]=g.useState(30),[H,K]=g.useState([]);g.useEffect(()=>{a&&(u(a),A("details"))},[a]),g.useEffect(()=>{const _=setTimeout(()=>{E(k),z(1)},300);return()=>clearTimeout(_)},[k]);const{data:se,isLoading:Q}=Nc({search:M.toLowerCase().trim(),page:Y,limit:ae}),ne=(se==null?void 0:se.assets)||[],B=(se==null?void 0:se.total)||0,q=Math.ceil(B/ae),me=Y<q,ye=Y>1,ue=(ne==null?void 0:ne.length)>0,{mutate:j}=Sc(),{mutate:x,isPending:T}=wc(),{mutate:L,isPending:G}=Ec(),$=g.useCallback(_=>{_>=1&&_<=q&&z(_)},[q]),P=g.useCallback(()=>{me&&$(Y+1)},[Y,me,$]),R=g.useCallback(()=>{ye&&$(Y-1)},[Y,ye,$]),Z=_=>{D(_.target.value)},oe=g.useCallback(_=>{K(le=>h.find(le,{id:_.id})?[]:[_])},[!1]),be=g.useCallback(()=>{K([])},[]),ce=_=>{(_==null?void 0:_.length)!==0&&(s(h.pick(h.first(_||H),["id","url","width","height","description"])),e())},je=async _=>{m(_)},F=async()=>{d&&(w(d==null?void 0:d.id),await j(d.id,{onSuccess:()=>{w(null),m(null)},onError:()=>{w(null)}}),m(null))},ee=_=>{u(_.id),A("details")},Ae=async(_,le)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";le?(await x({file:_,folderId:void 0,name:v.name||"",optimize:Ee}),p({show:!1,file:""})):(await L({id:v.id||"",file:_}),p({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},_e=g.useCallback(_=>{K([_])},[]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"max-w-[1232px] max-h-[1232px] w-[80vw] h-[80vh] space-y-4 flex flex-col",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),S==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Lc,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:G,isUploadingAsset:T,onUploaded:_e}),t.jsxs("div",{className:"border p-2 rounded-lg flex-1 flex flex-col gap-y-3 overflow-hidden relative",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 ${k.length>0?"text-indigo-800":""}`}),t.jsx(o.Input,{placeholder:"Search assets...",onChange:Z,value:k,className:"pl-8"})]}),H.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[H.length>0&&t.jsx(t.Fragment,{children:t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>be(),title:"Clear selection",children:"Clear"})}),t.jsx(o.Button,{size:"sm",onClick:()=>ce(H),disabled:H.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:Q?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"})]}):!Q&&!ue?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full border rounded-lg",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-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:M.length>0?"No assets found for your search: "+M:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:ne==null?void 0:ne.map(_=>t.jsxs("div",{className:U.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",H.some(le=>le.id===_.id)?"border-blue-500":"hover:border-black/90",f&&(d==null?void 0:d.id)===_.id?"opacity-50 pointer-events-none":"",f===_.id?"opacity-50 pointer-events-none":""),onClick:()=>oe(_),onDoubleClick:()=>ce([_]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[f===_.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,_.type==="image"?t.jsx("img",{src:`${_.thumbnailUrl||"/placeholder.svg"}?v=${(_==null?void 0:_.updatedAt)||_.createdAt}`,alt:_.name,className:`object-contain w-full h-full min-h-[80px] ${H.some(le=>le.id===_.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(N.Film,{className:"h-12 w-12 text-muted-foreground"}),_.thumbnailUrl&&t.jsx("img",{src:`${_.thumbnailUrl||"/placeholder.svg"}?v=${(_==null?void 0:_.updatedAt)||_.createdAt}`,alt:_.name,className:"absolute inset-0 object-cover w-full h-full"})]})]}),t.jsxs("div",{className:"py-1 px-2 flex items-end justify-between bg-white border-t-[1px] border-black/10",children:[t.jsx("div",{className:"text-xs truncate leading-tight",title:_.name,children:_.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:kc((_==null?void 0:_.size)||0)})})]}),!H.some(le=>le.id===_.id)&&t.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),ee(_)},children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),navigator.clipboard.writeText(_.url),V.toast.success("Asset URL copied to clipboard")},children:t.jsx(N.Copy,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),p({id:_.id,show:!0,file:_.url,name:_.name})},children:t.jsx(N.Edit,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),je(_)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),H.some(le=>le.id===_.id)&&t.jsx("div",{className:"absolute top-1 right-1 border border-white h-max rounded-full bg-blue-500 p-1",children:t.jsx(N.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},_.id))})}),q>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:R,disabled:!ye,children:"Previous"}),Array.from({length:Math.min(5,q)},(_,le)=>{const Ee=le+1;return t.jsx(o.Button,{variant:Y===Ee?"default":"outline",size:"sm",onClick:()=>$(Ee),children:Ee},Ee)}),q>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(o.Button,{variant:Y===q?"default":"outline",size:"sm",onClick:()=>$(q),children:q})]}),t.jsx(o.Button,{variant:"outline",size:"sm",onClick:P,disabled:!me,children:"Next"})]})})]})]}):t.jsx(Tc,{assetId:c||a||"",onBack:()=>{A("grid"),u(null)},onEdit:_=>{p({id:_.id,show:!0,file:_.url,name:_.name})},onSave:async _=>{if(c){y(!0);try{const le=ne.find(Ee=>Ee.id===c);le&&await L(h.merge(le,{description:_}))}finally{y(!1)}}},isSaving:b})]}),v.show&&t.jsx(g.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(Pc,{imageUrl:v.file,onSave:Ae,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:v.name,isEditing:!!v.id})}),d&&t.jsx(o.Dialog,{open:!!d,onOpenChange:()=>m(null),children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Asset"}),t.jsxs(o.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(o.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(o.Button,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",onClick:F,children:"Delete"})]})]})})]})}const Ic=Object.freeze(Object.defineProperty({__proto__:null,default:Xa},Symbol.toStringTag,{value:"Module"})),Za=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,c]=g.useState(!1),u=()=>{i||c(!0)},d=()=>{c(!1)},m=w=>{const v=Array.isArray(w)?w[0]:w;v!=null&&v.url&&n(h.pick(v,["url","id"])),c(!1)},f=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(o.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:f,disabled:i,children:t.jsx(N.Trash2,{className:"h-4 w-4"})}),t.jsx(o.Button,{type:"button",variant:"secondary",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 items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${i?"opacity-50 cursor-not-allowed":"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(o.Dialog,{open:l,onOpenChange:c,children:t.jsxs(o.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(o.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(o.DialogTitle,{children:"Select Image"}),t.jsx(o.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:"flex-1 p-4 h-full",children:t.jsx(Xa,{close:d,onSelect:m,mode:"image",assetId:e})})]})})]})},_c=()=>{const{user:e,logout:s}=Ue(),n=e==null?void 0:e.accessToken;return g.useCallback(async({url:a,method:r="GET",body:i={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const c=await fetch(a,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(i)});if(c.status===401)return console.log("Session expired",c),await s(),null;if(c.status===400)throw new Error((await c.json()).error);return await c.json()}catch(c){throw console.log("Something went wrong",c),c}},[n,s])};class Dc{constructor(s){Ts(this,"client");Ts(this,"channel",null);this.client=s}listenEvent(s,n){var a;(a=this.channel)==null||a.on("broadcast",{event:s},({payload:r})=>{n(r)}).subscribe()}async joinPage(s,n){const a=`PAGE:${s}`;return this.channel&&(await this.channel.untrack({userId:n}),await this.channel.unsubscribe()),this.channel=this.client.channel(a,{config:{presence:{key:n}}}),new Promise(r=>{var i;(i=this.channel)==null||i.on("presence",{event:"sync"},()=>{const l=this.getOnlineUsers();l.length>0?l.length===1&&l.includes(n)?r(!0):r(!1):r(!0)}).subscribe(async l=>{var c;l==="SUBSCRIBED"&&await((c=this.channel)==null?void 0:c.track({userId:n,online_at:new Date}))})})}async leavePage(){this.channel&&await this.channel.untrack()}async requestTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUESTED",payload:{pageId:s,requesterUserId:n,userId:n}}).then(()=>{a()})})}acceptTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_ACCEPTED",payload:{pageId:s,userId:n}}).then(()=>{this.leavePage(),a()})})}rejectTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_REJECTED",payload:{pageId:s,userId:n}}).then(()=>{a()})})}getOnlineUsers(){var s;return Object.keys(((s=this.channel)==null?void 0:s.presenceState())||{})}}if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=rn;exports.ChaiBuilderPages=vc;exports.ChaiBuilderPagesRealtime=Dc;exports.Dynamic=po;exports.For=$l;exports.ImagePicker=Za;exports.Index=zl;exports.LanguageSwitcher=an;exports.Match=Kl;exports.NestedPathSelector=Ye;exports.PermissionChecker=Ge;exports.Portal=xo;exports.Show=Vl;exports.SmartJsonInput=oa;exports.Switch=Hl;exports.addEventListener=Aa;exports.batch=Nl;exports.className=Ca;exports.clearDelegatedEvents=ro;exports.convertRemToPixels=rc;exports.createComponent=cn;exports.createComputed=fa;exports.createContext=Ll;exports.createEffect=ln;exports.createMemo=Me;exports.createRenderEffect=Xe;exports.createRoot=Je;exports.createSignal=Se;exports.createUniqueId=ql;exports.delegateEvents=Na;exports.deleteNestedDataByPath=_t;exports.displayValue=Zo;exports.getMutationStatusColor=Jo;exports.getPreferredColorScheme=ic;exports.getQueryStatusColor=Yo;exports.getQueryStatusColorByLabel=Xo;exports.getQueryStatusLabel=Qo;exports.getSidedProp=Wo;exports.insert=ys;exports.mergeProps=un;exports.mutationSortFns=ac;exports.on=Cl;exports.onCleanup=St;exports.onMount=ga;exports.registerLoginComponent=rl;exports.serialize=Ha;exports.setAttribute=ps;exports.sortFns=sc;exports.splitProps=ba;exports.spread=Ta;exports.stringify=Ko;exports.template=ao;exports.untrack=Te;exports.updateNestedDataByPath=It;exports.use=Pa;exports.useActivePage=Ct;exports.useBuilderPageData=Ws;exports.useChaiAuth=Ue;exports.useChaiFetch=_c;exports.useChaiUserInfo=et;exports.useContext=Il;exports.useCurrentPage=Ce;exports.useFallbackLang=Qs;exports.useFetch=J;exports.useGotoPage=Ja;exports.useLanguagePages=$e;exports.usePageTypes=Pe;exports.useTransition=kl;exports.useUpdateActivePageMetadata=bc;exports.useUserRoleAndPermissions=ia;exports.useWebsitePages=Zt;exports.useWebsiteSetting=Qe;
|