@chaibuilder/pages 0.7.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +0,0 @@
1
- "use strict";var tr=Object.defineProperty;var un=e=>{throw TypeError(e)};var sr=(e,s,n)=>s in e?tr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Ts=(e,s,n)=>sr(e,typeof s!="symbol"?s+"":s,n),dn=(e,s,n)=>s.has(e)||un("Cannot "+n);var X=(e,s,n)=>(dn(e,s,"read from private field"),n?n.call(e):s.get(e)),ge=(e,s,n)=>s.has(e)?un("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),fe=(e,s,n,a)=>(dn(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),h=require("lodash-es"),f=require("react"),_e=require("jotai"),M=require("@tanstack/react-query"),H=require("sonner"),U=require("@chaibuilder/sdk"),o=require("@chaibuilder/sdk/ui"),Nt=require("date-fns"),N=require("lucide-react"),In=require("@chaibuilder/runtime"),ls=require("zod"),nr=require("react-dropzone"),ar=require("@chaibuilder/sdk/web-blocks");function rr(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=rr(f),ke={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},_={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_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"},Y="chaibuilder";let ir=0;function hn(e,s){const n=`atom${++ir}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=lr,a.write=or),s&&(a.write=s),a}function lr(e){return e(this)}function or(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const cr=Symbol(""),ur=e=>typeof(e==null?void 0:e.then)=="function";function dr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var m,g;const b=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},j=(g=(m=e())==null?void 0:m.getItem(u))!=null?g:null;return ur(j)?j.then(b):b(j)},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,g)=>u(d,b=>{let j;try{j=JSON.parse(b||"")}catch{j=g}m(j)});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=g=>{g.storageArea===e()&&g.key===u&&d(g.newValue)};return window.addEventListener("storage",m),()=>{window.removeEventListener("storage",m)}}),c&&(i.subscribe=l(c)),i}const hr=dr();function Dn(e,s,n=hr,a){const r=hn(s);return r.onMount=l=>{l(n.getItem(e,s));let c;return n.subscribe&&(c=n.subscribe(e,l,s)),c},hn(l=>l(r),(l,c,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===cr?(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 Bn="__logged_in_user",mr=Dn(Bn,null),Ue=()=>{const[e,s]=_e.useAtom(mr),n=f.useCallback(()=>{s(null),localStorage.removeItem(Bn)},[s]),a=f.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=M.useQueryClient(),a=e==null?void 0:e.accessToken;return f.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:[Y]}),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])},Mn=()=>{const e=ie(),s=M.useQueryClient(),n=J();return M.useMutation({mutationFn:async a=>n(e,{action:_.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,_.GET_DRAFT_PAGE]})}})},On=()=>{const e=ie(),s=M.useQueryClient(),n=J();return M.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||H.toast.success("Website settings updated successfully.")},onError:a=>{H.toast.error("Failed to update website settings",{description:a.message})}})},fr=()=>{const e=ie(),s=M.useQueryClient(),n=J();return M.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_DATA]}),H.toast.success("Website data updated successfully.")},onError:a=>{H.toast.error("Failed to update website data",{description:a.message})}})};function Ie(){const[e,s]=f.useState(new URLSearchParams(window.location.search));return f.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const gr=_e.atom({}),Gn=()=>_e.useAtom(gr),xr=()=>{const[e]=Ie(),s=e.get("page"),n=f.useRef(""),{mutate:a}=Mn();f.useEffect(()=>{!h.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},He=(e,s)=>{const[n]=Gn();return f.useMemo(()=>h.get(n,e,s),[n,e,s])},ie=()=>He("apiUrl","/chai/api"),js=()=>He("usersApiUrl","/chai/users"),Xt=()=>He("assetsApiUrl","/chai/assets"),Rn=()=>He("realtimeInstance",null),Ke=e=>{const s=ie(),[n]=Ie(),a=e??n.get("page"),r=J();return M.useQuery({queryKey:[Y,_.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:_.GET_LANGUAGE_PAGES,data:{id:a}});return h.reverse(h.sortBy(i,"primaryPage"))},enabled:!!a})},Ze=()=>{const e=ie(),s=J();return M.useQuery({queryKey:[Y,_.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:_.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},Un=e=>{const{fallbackLang:s}=U.useLanguages(),{data:n}=Ze(),{data:a,isFetching:r}=Ke(),i=f.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=M.useQueryClient(),{data:s}=M.useQuery({queryKey:[Y,_.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:f.useCallback(a=>{e.setQueryData([Y,_.AI_CONTEXT],a)},[e]),aiContext:s}},Zt=()=>{const e=J(),s=ie();return M.useQuery({queryKey:[Y,_.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},pr=_e.atom({lastSaved:void 0}),vs=()=>_e.useAtom(pr),Ae=()=>{const[e]=Ie(),s=e.get("page"),[n]=Fn(),{data:a,isFetching:r}=Zt();return{data:f.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}=Ke();return{data:f.useMemo(()=>h.find(n,{lang:s})||{},[n,s]),isFetching:a}},yr=_e.atom({}),Fn=()=>_e.useAtom(yr),et=e=>{const s=js(),n=J();return M.useQuery({queryKey:[Y,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:_.GET_CHAI_USER,data:{userId:e}}),enabled:!h.isEmpty(e)})},jr=_e.atom(void 0),Ks=_e.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1}),es=()=>{const[e]=Ie(),s=e.get("page"),{user:n}=Ue(),[a,r]=_e.useAtom(jr),[i]=_e.useAtom(Ks),l=U.useChaiFeatureFlag("realtime-page-lock");return f.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])},vr=()=>{const e=Rn(),{data:s}=Ae(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=_e.useAtom(Ks),l=f.useRef(!1),c=U.useChaiFeatureFlag("realtime-page-lock");return f.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]),f.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]),{}},qn=()=>{const e=Rn(),{data:s}=Ae(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=_e.useAtom(Ks),{saveState:l,savePage:c}=U.useSavePage(),u=M.useQueryClient(),d=f.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",()=>{H.toast.success("Your Page Take Over Request Accepted",{position:"top-center"}),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}),u.invalidateQueries({queryKey:[Y,_.GET_DRAFT_PAGE]})}),e==null||e.listenEvent("TAKE_OVER_REQUEST_REJECTED",()=>{i({...r,isTakeOverRequested:!1}),H.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=f.useCallback(async()=>{!e||!a||!(n!=null&&n.id)||(l!=="SAVED"&&(c(),await new Promise(b=>setTimeout(b,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]),g=f.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:g}},Qs=()=>{const{data:e}=Ze();return f.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},br=_e.atom(null),$n=()=>_e.useAtom(br),zn=()=>{const[e]=$n();return(e==null?void 0:e.slug)||""};function wr(e,s){const[n,a]=f.useState(e);return f.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const Sr=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=U.useLanguages(),{data:r}=Ae(),i=r==null?void 0:r.pageType,l=ie(),c=J(),{data:u,isFetching:d}=M.useQuery({queryKey:[_.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await c(l,{action:_.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[]}),m=f.useMemo(()=>n===""?u.filter(g=>g.lang===""||g.lang===a):u.filter(g=>g.lang===n),[n,a,u]);return{allLangPages:u,data:m,isFetching:d}},Er=()=>{const{selectedLang:e,fallbackLang:s}=U.useLanguages(),[n,a]=$n(),[r,i]=f.useState(""),l=wr(r,500),{allLangPages:c,data:u,isFetching:d}=Sr({query:l}),m=f.useCallback(j=>a(j),[a]),g=f.useCallback(j=>i(j),[i]),b=f.useCallback(()=>{if(!n)return;const j=!(n!=null&&n.primaryPage),p=e.length===0,S=j?n==null?void 0:n.id:n==null?void 0:n.primaryPage,w=c.filter(C=>(C==null?void 0:C.primaryPage)===S||C.id===S).find(C=>p?C.lang===e||C.lang===s:C.lang===e);a(w||n)},[n,e,c,a,s]);return{isPending:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:c,updateDynamicPage:m,updateSearchQuery:g,onChangeLanguage:b}},Vn=()=>{const[e]=Ie(),s=e.get("page"),n=ie(),{setAiContext:a}=Hs(),{setCurrentEditor:r}=es(),[,i]=vs(),[,l]=Fn(),c=J();return M.useQuery({queryKey:[Y,_.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await c(n,{action:_.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(g=>({...g,lastSaved:u.lastSaved})),l(h.get(u,"metadata",{})),d},enabled:!!s})},Ws=()=>{const{data:e}=Ae(),{data:s}=Ct(),n=ie(),a=J(),r=Qs(),i=zn();return M.useQuery({queryKey:[Y,_.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:_.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),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"]})})]})})},mn=({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]=f.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}=qn();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(mn,{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(mn,{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}=Mn(),{isFetching:l}=Vn(),[c]=vs(),{pageLock:u,requestTakeOver:d}=qn(),m=U.useChaiFeatureFlag("realtime-page-lock"),g=f.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:g,pageLock:u,realtimePageLockEnabled:m})},Pr=()=>{const[e,s]=Ie(),n=e.get("lang"),a=Un(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(ke,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 M.useMutation({mutationFn:async a=>n(s,{action:_.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),H.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},Lr=e=>{const s=ie(),n=J();return M.useQuery({queryKey:[Y,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:_.GET_LIBRARY_ITEM,data:{id:e}})}catch(a){throw console.error(a),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},_r=e=>{const s=ie(),n=J();return M.useMutation({mutationFn:async a=>n(s,{action:_.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),H.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},Ir=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,c]=f.useState(!1),u=U.useUpdateBlocksPropsRealtime(),d=_r(()=>{u([e],{_libBlockId:void 0}),H.toast.success("Block deleted successfully"),c(!1),a()}),m=()=>{c(!0),d.mutate(s)},g=t.jsxs(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:l,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(o.Popover,{open:n,onOpenChange:b=>!b&&a(),children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:i||g}),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]=f.useState(!1);return t.jsx(Ir,{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=M.useQueryClient(),{data:a=[],isLoading:r,error:i}=M.useQuery({queryKey:[Y,"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}=M.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:[Y,"library-groups"]}),H.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),H.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]=f.useState(!1),[r,i]=f.useState(""),l=f.useRef(null),{groups:c}=Br(),[u,d]=f.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),m=f.useMemo(()=>[...c,...u.filter(j=>!c.some(p=>p.id===j.id))],[c,u]),g=()=>{const j=r.trim();if(!j)return;const p={id:j,name:j};d(S=>[...S,p]),s(p.id),i(""),a(!1)};f.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const b=j=>{j.key==="Enter"&&(j.preventDefault(),g())};return f.useEffect(()=>{e&&!m.some(j=>j.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:j=>i(j.target.value),onKeyDown:b}),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:g,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:j=>s(j.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),c.length>0&&t.jsx("optgroup",{label:"Library Groups",children:c.map(j=>t.jsx("option",{value:j.id,children:j.name},`lib-${j.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(j=>!c.some(p=>p.id===j.id)).map(j=>t.jsx("option",{value:j.id,children:j.name},`local-${j.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]=f.useState(!1),r=f.useRef(null),i=f.useCallback(u=>{var m;const d=(m=u.target.files)==null?void 0:m[0];if(d){if(d.size>Or){H.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 g=new FileReader;g.onloadend=()=>{s(g.result),a(!1)},g.readAsDataURL(d)}catch(g){console.error("Error reading file:",g),a(!1),H.toast.error("Failed to process image",{description:g instanceof Error?g.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=f.useMemo(()=>s.some(T=>T._type==="PartialBlock"||T._type==="GlobalBlock"),[s]),d=f.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,g]=f.useState(""),[b,j]=f.useState(""),[p,S]=f.useState(""),[y,w]=f.useState(""),[C,I]=f.useState({}),[E,k]=f.useState(!1),[O,z]=f.useState(c),[V,ae]=f.useState(!1),{hasPermission:K}=U.usePermissions(),Q=K(ve.DELETE_LIBRARY_BLOCK),se=U.useUpdateBlocksPropsRealtime(),W=()=>{se([a],{_libBlockId:void 0}),H.toast.success("Block delinked from library"),n()},{data:ne,isLoading:B,isError:q}=Lr(l);f.useEffect(()=>{q&&c&&(ae(!0),z(!1))},[q,c]),f.useEffect(()=>{ne&&!B&&(g(ne.name||""),j(ne.group||""),S(ne.description||""),w(ne.preview||""),z(!1))},[ne,B]),f.useEffect(()=>{const T=m.trim().length>=2,L=b.trim()!=="";k(T&&L)},[m,b]);const me=()=>{const T={};return m.trim()?m.length<2&&(T.name="Name must be at least 2 characters"):T.name="Name is required",b||(T.group="Group is required"),I(T),Object.keys(T).length===0},{resetLibrary:ye}=U.useLibraryBlocks({id:""}),ue=kr(T=>{c||se([a],{_libBlockId:T.id}),H.toast.success(`Block ${c?"updated":"saved"} successfully`),ye(T.library),n()}),v=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:b,blocks:L,description:p.trim(),...y&&y.startsWith("data:")?{previewImage:y}:{},...c?{id:l}:{}})},x=ue.isPending;return O||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"})}):V?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:W,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:v,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:C.name?"text-destructive":"",children:"Name"}),t.jsx(o.Input,{id:"name",placeholder:"Enter block name",value:m,onChange:T=>g(T.target.value),className:C.name?"border-destructive":""}),C.name&&t.jsx("p",{className:"text-xs text-destructive",children:C.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"group",className:C.group?"text-destructive":"",children:"Group"}),t.jsx(Mr,{value:b,onChange:j}),C.group&&t.jsx("p",{className:"text-xs text-destructive",children:C.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=>S(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:w})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[c&&Q&&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."},Te=()=>{const e=ie(),s=J();return M.useQuery({queryKey:[Y,_.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:_.GET_PAGE_TYPES})})},Hn=e=>{const{data:s}=Te();return f.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Fr=()=>{const e=ie(),s=J();return M.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:_.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Kn=()=>{const e=ie(),s=M.useQueryClient(),n=J(),{data:a}=Te();return M.useMutation({mutationFn:async r=>await n(e,{action:_.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var c;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,_.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";H.toast.success(l)},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});H.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=M.useQueryClient(),n=J(),{data:a}=Te();return M.useMutation({mutationFn:async r=>await n(e,{action:_.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?s.invalidateQueries({queryKey:[Y,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});H.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},qr=()=>{const e=ie(),s=M.useQueryClient(),n=J(),{data:a}=Te();return M.useMutation({mutationFn:async r=>n(e,{action:_.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){H.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});H.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},$r=()=>{const e=ie(),s=M.useQueryClient(),n=J(),{data:a}=Te();return M.useMutation({mutationFn:async r=>n(e,{action:_.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_PAGES]});const l=h.find(a,{key:i.pageType});H.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});H.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Js=()=>{const e=ie(),s=J(),n=M.useQueryClient(),{data:a}=Ae();return M.useMutation({mutationFn:async({ids:r})=>s(e,{action:_.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,_.GET_CHANGES]}),n.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[Y,_.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{H.toast.error("Failed to publish pages.")}})},zr=()=>{const e=ie(),s=J(),n=M.useQueryClient();return M.useMutation({mutationFn:async a=>{var r;return s(e,{action:_.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_PAGES]}),H.toast.success("Page marked as template successfully.")},onError:()=>{H.toast.error("Failed to mark page as template.")}})},Vr=()=>{const e=ie(),s=J(),n=M.useQueryClient();return M.useMutation({mutationFn:async a=>s(e,{action:_.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_PAGES]}),H.toast.success("Page unmarked as template successfully.")},onError:()=>{H.toast.error("Failed to unmark page as template.")}})},Hr=()=>{const e=ie(),s=J(),n=M.useQueryClient();return M.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:_.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{H.toast.success(re.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[Y,_.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[Y,_.GET_WEBSITE_PAGES]})},onError:()=>{H.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 v=new OffscreenCanvas(1,1),x=v.getContext("2d");x.fillRect(0,0,1,1);var T=v.transferToImageBitmap();try{x.createPattern(T,"no-repeat")}catch{return!1}return!0}();function u(){}function d(v){var x=n.exports.Promise,T=x!==void 0?x:s.Promise;return typeof T=="function"?new T(v):(v(u,u),null)}var m=function(v,x){return{transform:function(T){if(v)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),g=function(){var v=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+v-1<Z?(G=Z,delete L[P],$()):L[P]=requestAnimationFrame(R)}),P},T=function($){L[$]&&cancelAnimationFrame(L[$])}):(x=function($){return setTimeout($,v)},T=function($){return clearTimeout($)}),{frame:x,cancel:T}}(),b=function(){var v,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(v)return v;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{v=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(v)}return v}}(),j={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function p(v,x){return x?x(v):v}function S(v){return v!=null}function y(v,x,T){return p(v&&S(v[x])?v[x]:j[x],T)}function w(v){return v<0?0:Math.floor(v)}function C(v,x){return Math.floor(Math.random()*(x-v))+v}function I(v){return parseInt(v,16)}function E(v){return v.map(k)}function k(v){var x=String(v).replace(/[^0-9a-f]/gi,"");return x.length<6&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:I(x.substring(0,2)),g:I(x.substring(2,4)),b:I(x.substring(4,6))}}function O(v){var x=y(v,"origin",Object);return x.x=y(x,"x",Number),x.y=y(x,"y",Number),x}function z(v){v.width=document.documentElement.clientWidth,v.height=document.documentElement.clientHeight}function V(v){var x=v.getBoundingClientRect();v.width=x.width,v.height=x.height}function ae(v){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=v,x}function K(v,x,T,L,G,$,P,R,Z){v.save(),v.translate(x,T),v.rotate($),v.scale(L,G),v.arc(0,0,1,P,R,Z),v.restore()}function Q(v){var x=v.angle*(Math.PI/180),T=v.spread*(Math.PI/180);return{x:v.x,y:v.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:v.startVelocity*.5+Math.random()*v.startVelocity,angle2D:-x+(.5*T-Math.random()*T),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:v.color,shape:v.shape,tick:0,totalTicks:v.ticks,decay:v.decay,drift:v.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:v.gravity*3,ovalScalar:.6,scalar:v.scalar,flat:v.flat}}function se(v,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(v.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-T)+")",v.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))v.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=v.createPattern(m.transform(x.shape.bitmap),"no-repeat");F.setTransform(je),v.globalAlpha=1-T,v.fillStyle=F,v.fillRect(x.x-be/2,x.y-ce/2,be,ce),v.globalAlpha=1}else if(x.shape==="circle")v.ellipse?v.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):K(v,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,Ne=4*x.scalar,De=8*x.scalar,D=x.x,le=x.y,Ee=5,Re=Math.PI/Ee;Ee--;)D=x.x+Math.cos(ee)*De,le=x.y+Math.sin(ee)*De,v.lineTo(D,le),ee+=Re,D=x.x+Math.cos(ee)*Ne,le=x.y+Math.sin(ee)*Ne,v.lineTo(D,le),ee+=Re;else v.moveTo(Math.floor(x.x),Math.floor(x.y)),v.lineTo(Math.floor(x.wobbleX),Math.floor(G)),v.lineTo(Math.floor($),Math.floor(P)),v.lineTo(Math.floor(L),Math.floor(x.wobbleY));return v.closePath(),v.fill(),x.tick<x.totalTicks}function W(v,x,T,L,G){var $=x.slice(),P=v.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=v.width=r.width,L.height=v.height=r.height),!L.width&&!L.height&&(T(v),L.width=v.width,L.height=v.height),P.clearRect(0,0,L.width,L.height),$=$.filter(function(F){return se(P,F)}),$.length?R=g.frame(je):ce()}R=g.frame(je),Z=ce});return{addFettis:function(be){return $=$.concat(be),oe},canvas:v,promise:oe,reset:function(){R&&g.cancel(R),Z&&Z()}}}function ne(v,x){var T=!v,L=!!y(x||{},"resize"),G=!1,$=y(x,"disableForReducedMotion",Boolean),P=i&&!!y(x||{},"useWorker"),R=P?b():null,Z=T?z:V,oe=v&&R?!!v.__confetti_initialized:!1,be=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,ce;function je(ee,Ne,De){for(var D=y(ee,"particleCount",w),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"),A=O(ee),de=D,Be=[],Pe=v.width*A.x,Oe=v.height*A.y;de--;)Be.push(Q({x:Pe,y:Oe,angle:le,spread:Ee,startVelocity:Re,color:Tt[de%Tt.length],shape:tt[C(0,tt.length)],ticks:Pt,decay:Ns,gravity:Cs,drift:As,scalar:ts,flat:ss}));return ce?ce.addFettis(Be):(ce=W(v,Be,Z,Ne,De),ce.promise)}function F(ee){var Ne=$||y(ee,"disableForReducedMotion",Boolean),De=y(ee,"zIndex",Number);if(Ne&&be)return d(function(Re){Re()});T&&ce?v=ce.canvas:T&&!v&&(v=ae(De),document.body.appendChild(v)),L&&!oe&&Z(v);var D={width:v.width,height:v.height};R&&!oe&&R.init(v),oe=!0,R&&(v.__confetti_initialized=!0);function le(){if(R){var Re={getBoundingClientRect:function(){if(!T)return v.getBoundingClientRect()}};Z(Re),R.postMessage({resize:{width:Re.width,height:Re.height}});return}D.width=D.height=null}function Ee(){ce=null,L&&(G=!1,s.removeEventListener("resize",le)),T&&v&&(document.body.contains(v)&&document.body.removeChild(v),v=null,oe=!1)}return L&&!G&&(G=!0,s.addEventListener("resize",le,!1)),R?R.fire(ee,D,Ee):je(ee,D,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(v,x,T,L,G,$,P){var R=new Path2D(v),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(v){if(!l)throw new Error("path confetti are not supported in this browser");var x,T;typeof v=="string"?x=v:(x=v.path,T=v.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 Ne=10,De=Math.min(Ne/ce,Ne/je);T=[De,0,0,De,-Math.round(ce/2+R)*De,-Math.round(je/2+Z)*De]}return{type:"path",path:x,matrix:T}}function ue(v){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 v=="string"?x=v:(x=v.text,T="scalar"in v?v.scalar:T,G="fontFamily"in v?v.fontFamily:G,L="color"in v?v.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 Ne=1/T;return{type:"bitmap",bitmap:R.transferToImageBitmap(),matrix:[Ne,0,0,Ne,-be*Ne/2,-ce*Ne/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}=On(),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"})]})},Jr=({page:e,onClose:s})=>{const[n,a]=f.useState(e.slug||""),{mutate:r,isPending:i}=Hr(),{data:l}=Te(),c=h.find(l,{key:e==null?void 0:e.pageType}),u=m=>{if(m.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(ke).some(j=>n===`/${j}`||h.startsWith(n,`/${j}/`))){H.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 g=m.target.value;h.startsWith(g,`/${d}`)&&a(g)},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"})})]})]})})};function Zs({page:e,onClose:s}){const[,n]=Ie(),{mutate:a,isPending:r}=qr(),{data:i}=Te(),{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(g=>g.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(ke,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 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},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})]})]})})},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}},Ve=e=>{if(!e)return e;const{base:s}=Xr(e);return s},Zr=e=>e&&Ve(e),fn=(e,s)=>{const n=Ve(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function en({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[c,u]=f.useState(e),[d,m]=f.useState(null);f.useEffect(()=>{u(e)},[e]);const g=b=>{const p=b.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),S=(p.match(/\./g)||[]).length,y=S<=1;S>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:g,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 Qn=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Ae(),r=a==null?void 0:a.dynamic,{data:i}=Te(),[l,c]=f.useState(e.name||""),[u,d]=f.useState(e.edit?e.lang:""),[m,g]=f.useState(e.edit?e.slug:""),[b,j]=f.useState(!0),[p,S]=f.useState(!0),{mutate:y,isPending:w}=Kn(),{mutate:C,isPending:I}=Ys(),{data:E}=Ke(a==null?void 0:a.parent),{setSelectedLang:k,fallbackLang:O}=U.useLanguages(),[,z]=Ie(),[,V]=U.useSidebarActivePanel(),ae=f.useMemo(()=>i==null?void 0:i.find(v=>v.key===e.pageType),[i,e.pageType]),K=r||!(ae!=null&&ae.hasSlug),Q=(a==null?void 0:a.slug)==="/",se=w||I,{parentSlug:W,isRootPage:ne}=f.useMemo(()=>{if(Q||!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 v=E==null?void 0:E.find(x=>x.lang===u);return{parentSlug:v==null?void 0:v.slug,isRootPage:!1}},[a==null?void 0:a.parent,E,p,u,Q]);f.useEffect(()=>{if(!e.edit)return;const x=(e.slug||"").split("/").filter(Boolean);let T="";const L=G=>S(G);if(Q){const G=x.pop()||"";if(ke[G])L(!0);else{T=G;const $=x.pop()||"";L(!!ke[$])}}else if(ne){if(x.length){T=x.pop()||"";const G=x.pop()||"";L(!!ke[G])}}else x.length&&(T=x.pop()||"");g(T)},[e,Q,ne]);const B=f.useMemo(()=>ne?!0:!!(E!=null&&E.find(v=>(v==null?void 0:v.lang)===u)),[u,E,ne]),q=()=>{let v="";return ne?v=`/${p?[u,m].filter(Boolean).join("/"):m}`:v=`${Ve(W)}/${m}`,v.replace(/\/{2,}/g,"/").replace(/\/$/,"")},me=(v,x)=>{const T=new URLSearchParams(window.location.search);x&&v===x?T.delete("lang"):T.set("lang",v);const L=T.toString(),G=`${window.location.pathname}${L?`?${L}`:""}`;window.history.pushState({},"",G),z(T),window.dispatchEvent(new PopStateEvent("popstate"))},ye=v=>{v.preventDefault();const x={name:l,lang:u,primaryPage:a==null?void 0:a.id,slug: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?C(x,{onSuccess:s}):y(x,{onSuccess:()=>{u&&(k(u),me(u,O)),V("outline"),s()}})},ue=se||h.isEmpty(l)||h.isEmpty(u)||(K||Q&&p?!1:!b||h.isEmpty(m));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px] text-slate-600",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:v=>{const x=v.target.value;d(x),!e.edit&&h.startsWith(l,e.name)&&c(`${e.name} - ${ke[x]}`)},className:"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 col-span-3",children:[t.jsx("option",{value:"",disabled:!0,selected:!0,children:e.edit?h.get(ke,e.lang,e.lang):h.isEmpty(n)?re.ALL_AVAILABLE_LANGUAGE_PAGE:re.CHOOSE_LANGUAGE}),h.map(n,v=>t.jsx("option",{value:v,children:h.get(ke,v,v)},v))]})]}),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:v=>c(v.target.value),className:"col-span-3",required:!0,placeholder:u?re.ENTER_PAGE_NAME:re.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!B||!u})]}),!K&&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:v=>S(v.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(en,{disabled:h.isEmpty(u)||!B,value:m,onChange:g,placeholder:h.isEmpty(u)?re.CHOOSE_LANGUAGE_TO_ADD_SLUG:Q&&p?"Leave empty for home page":re.ENTER_PAGE_SLUG,parentSlug:W,onValidationChange:j,fullSlug:ue?"":q()})]})}),r&&u&&B&&t.jsxs("p",{className:"text-sm pb-2",children:[t.jsx(o.Label,{children:"Dynamic Slug: "})," ",t.jsx("span",{className:"font-mono font-light",children:`${Ve(W)}/${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:"text-center w-5/6 mx-auto",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:ke[u]})," page in the parent to add here."]})})})]})]})})},ei=()=>{const[e,s]=f.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:r}=U.useLanguages(),{data:i,isFetching:l}=Ke(),{data:c}=Ae(),{data:u}=Te(),d=f.useMemo(()=>{const C=u==null?void 0:u.find(I=>I.key===(c==null?void 0:c.pageType));return C==null?void 0:C.dynamicSlug},[u,c==null?void 0:c.pageType]),[m,g]=f.useState(null),[b,j]=f.useState(null),[p,S]=f.useState(null),{data:y}=Ze(),w=h.filter(h.get(y,"languages")||["en"],C=>!h.find(i,{lang:C})&&C!==h.get(y,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:l?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"})]}):h.map(i,C=>{const I=C.lang,E=C.slug,k=!C.primaryPage,O=I===n;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`text-slate-500 w-full p-2 rounded cursor-pointer flex items-center justify-between ${O?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>r(I),children:[t.jsxs("div",{className:" flex-1 gap-x-3",children:[t.jsxs("div",{className:"text-[13px] text-slate-800 flex items-center gap-x-2",children:[t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${C.online?"bg-green-300":"bg-gray-300"}`}),h.get(ke,k?a:I,I)]}),t.jsxs("div",{children:[E&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium font-mono",children:d?`${E}/${d}`:E})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",C.name," "]})]})]})]}),k?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(N.StarIcon,{fill:"orange",className:"w-3 h-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:z=>z.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:"text-sm z-[9999]",children:[t.jsx(Ge,{permissions:[ve.EDIT_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),s({...C,edit:!0})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),re.EDIT]})}),t.jsx(Ge,{permissions:[ve.UNPUBLISH_PAGE],children:(C==null?void 0:C.online)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),j(C)},children:[t.jsx(N.Power,{className:"size-3"}),re.UNPUBLISH]})}),t.jsx(Ge,{permissions:[ve.DELETE_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),g(C)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),re.DELETE]})})]})]})})})]},C.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Ge,{permissions:[ve.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(o.Button,{variant:"default",size:"sm",disabled:h.isEmpty(w),onClick:()=>{s({name:c==null?void 0:c.name,pageType:c==null?void 0:c.pageType,lang:"",slug:"",edit:!1})},children:re.ADD_NEW_LANGUAGE})})}),e&&t.jsx(Qn,{languages:w,langProps:e,onClose:()=>s(null)}),m&&t.jsx(Zs,{page:m,onClose:()=>g(null)}),b&&t.jsx(bs,{page:b,onClose:()=>j(null)}),p&&t.jsx(Jr,{page:p,onClose:()=>S(null)})]})};function ti({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=f.useState(null),c=f.useRef(null),[u,d]=f.useState(a+e);f.useEffect(()=>{d(a+e)},[e,a]);const m=j=>{const p=j.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(),w=(y.match(/\./g)||[]).length,C=w<=1;w>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(C);const I=a+y;d(I),s(y)},g=()=>{if(c.current){const j=c.current;setTimeout(()=>{const p=a.length;j.setSelectionRange(p,p)},0)}},b=j=>{const p=j.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:g,onClick:b,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const cs=({children:e,onWheel:s,...n})=>{const a=r=>{try{r.preventDefault();const i=r.currentTarget;i.scrollTop+=r.deltaY}catch{r.preventDefault()}s&&s(r)};return t.jsx(o.CommandList,{...n,onWheel:a,children:e})},Ps=(...e)=>e.filter(Boolean).join(" ");function si({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage"}){const[i,l]=f.useState(!1),[c,u]=f.useState(""),d=U.useChaiFeatureFlag("enable-add-page-dropdown");d||(a="w-full rounded-md border border-gray-300 px-3 py-2");const m=f.useMemo(()=>!e||e.length===0?[]:e.filter(w=>!h.isEmpty(w.slug)).filter(w=>w.slug!=="/").sort((w,C)=>w.slug.localeCompare(C.slug)),[e]),g=f.useMemo(()=>{if(!c.trim())return m;const y=c.toLowerCase();return m.filter(w=>w.name.toLowerCase().includes(y)||w.slug.toLowerCase().includes(y))},[m,c]),b=y=>Math.max(0,(y.match(/\//g)||[]).length-1),j=y=>"    ".repeat(y),p=y=>{if(y==="/")return"/";const w=y.split("/").filter(Boolean);if(w.length<=1){const C=w[0]||"";return`/${Ve(C)}`}return`/${Ve(w[w.length-1])}`},S=()=>{if(!s||s==="none")return"None";const y=m.find(w=>w.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:[S(),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")})]}),g.map(y=>{const w=j(b(y.slug)),C=p(y.slug),I=t.jsxs("span",{className:"flex items-center text-sm",children:[w,y.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",C,")"]})]});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:I}),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 w=b(y.slug),C=w>0?j(w):"",I=p(y.slug);return t.jsxs("option",{value:y.id,children:[C,y.name," (",I,")"]},y.id)})]})]})}const ni=(...e)=>e.filter(Boolean).join(" "),ai=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=f.useState(""),[l,c]=f.useState(!1),[u,d]=f.useState(""),m=U.useChaiFeatureFlag("enable-add-page-dropdown");if(f.useEffect(()=>{if(s){const S=e.find(y=>y.id===s);i((S==null?void 0:S.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 g={};e.forEach(S=>{const y=S.libraryName;g[y]||(g[y]=[]),g[y].push(S)});const b=Object.entries(g).reduce((S,[y,w])=>{const C=w.filter(I=>I.name.toLowerCase().includes(u.toLowerCase())||y.toLowerCase().includes(u.toLowerCase()));return C.length>0&&(S[y]=C),S},{}),j=e.find(S=>S.id===s),p=j?h.startCase(j.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:S=>d(S.target.value)})]})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No templates found."}),Object.entries(b).map(([S,y])=>t.jsx(o.CommandGroup,{heading:S,children:y.map(w=>t.jsxs(o.CommandItem,{value:w.id,onSelect:()=>{n(w.id),c(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[h.startCase(w.name),t.jsx(N.Check,{className:ni("mr-2 h-4 w-4",s===w.id?"opacity-100":"opacity-0")})]},w.id))},S))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:S=>n(S.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(g).map(([S,y])=>t.jsx("optgroup",{label:S,children:y.map(w=>t.jsx("option",{value:w.id,children:h.startCase(w.name)},w.id))},S))]}),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"})]})]})},ri=()=>{const e=ie(),s=J();return M.useQuery({queryKey:[Y,_.GET_LIBRARIES],queryFn:async()=>await s(e,{action:_.GET_LIBRARIES})||[]})},ii=e=>{const s=ie(),n=J();return M.useQuery({queryKey:[Y,_.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:_.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?h.filter(a,{pageType:e}):a)||[]}})},li=e=>{const{data:s=[],isLoading:n}=ii(e),{data:a=[],isLoading:r}=ri(),i=f.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=f.useMemo(()=>h.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},tn=()=>{const[,e]=Ie();return f.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},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 oi({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var ts,ss;const r=tn(),i=!!(e!=null&&e.id),{data:l}=Zt(),{mutate:c,isPending:u}=Kn(),{mutate:d,isPending:m}=Ys(),[g,b]=f.useState(null),[j,p]=f.useState(!0),[S,y]=f.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:w}=U.usePermissions(),C=w(ve.CHANGE_PAGE_TYPE),[I,E]=f.useState(!1),[k,O]=f.useState(""),{selectedLang:z,fallbackLang:V}=U.useLanguages(),ae=z||V,[K,Q]=f.useState(""),[se,W]=f.useState(!1),ne=f.useMemo(()=>{const A=s.find(de=>de.key===S);return(A==null?void 0:A.hasSlug)===!1},[S,s]),[B,q]=f.useState((e==null?void 0:e.parent)??""),[me,ye]=f.useState((e==null?void 0:e.name)??""),[ue,v]=f.useState((e==null?void 0:e.dynamic)??!1),[x,T]=f.useState(ue?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[L,G]=f.useState((e==null?void 0:e.dynamicSlugCustom)??""),[$,P]=f.useState(!0),[R,Z]=f.useState(""),{data:oe,isLoading:be}=li(S),ce=u||m,je=U.useChaiFeatureFlag("enable-add-page-dropdown"),F=s.find(A=>A.key===S),ee=A=>{if(i&&S!==A){O(A),E(!0),Q(""),W(!1);return}y(A),Q(""),W(!1)},Ne=()=>{y(k),E(!1),v(!1)},De=A=>{v(A),A?T(""):G("")},D=A=>{if(q(A),A&&A!=="none"){const de=l==null?void 0:l.find(Pe=>Pe.id===A),Be=(de==null?void 0:de.slug)||"";if(x.startsWith(Be)){const Pe=x.slice(Be.length).replace(/^\/+/,"");T(Pe)}else T(x.replace(/^\/+/,""))}else T(x?`${x}`:"")},le=A=>{Z(A)},Ee=()=>me.trim()?ue&&!h.isEmpty(x)?(b("Slug must be empty when using dynamic slug"),!1):ue&&!$?(b("Dynamic slug is invalid"),!1):!0:(H.toast.error("Name is required"),!1),Re=()=>{const A={pageType:F==null?void 0:F.key,name:me,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:me},{onSuccess:()=>{H.toast.success((F==null?void 0:F.name)+" updated successfully"),n()}}):c(A,{onSuccess:de=>{n(),r(de.page.id,a)}})},Ns=(A,de)=>{if(!A.trim()&&!ue)return b("Child page slug is required"),!1;const Be=Ve(de),Pe=fn(Be,A);return Object.keys(ke).some(ns=>Pe===`/${ns}`||(Pe==null?void 0:Pe.startsWith(`/${ns}/`)))?(b("Slugs cannot start with a language code for primary page"),!1):!0},Cs=(A,de)=>{const Be=Ve(de),Pe=fn(Be,A),Oe={pageType:S,name:me,slug:Pe.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:()=>{H.toast.success("Page updated successfully"),n()}});else{const $e=h.find(s,{key:S});$e!=null&&$e.trackingDefault&&(Oe.tracking=$e.trackingDefault);const{seo:ns,jsonLD:Za}=us($e,ae);h.set(Oe,"seo",ns),h.set(Oe,"jsonLD",Za),c(Oe,{onSuccess:er=>{n(),r(er.page.id,a)}})}},As=()=>{const A={pageType:S,name:me,slug:x===""?"/":`/${x.replace(/\/$/,"")}`,template:R||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...A},{onSuccess:()=>{H.toast.success("Page updated successfully"),n()}});else{const de=h.find(s,{key:S});de!=null&&de.trackingDefault&&(A.tracking=de.trackingDefault);const{seo:Be,jsonLD:Pe}=us(de,ae);h.set(A,"seo",Be),h.set(A,"jsonLD",Pe),c(A,{onSuccess:Oe=>{var $e;($e=Oe==null?void 0:Oe.page)!=null&&$e.id&&r(Oe.page.id,a),n()}})}},Tt=A=>{if(A.preventDefault(),b(null),!!Ee()){if(!(F!=null&&F.hasSlug)){Re();return}if(B&&B!=="none"){const de=l==null?void 0:l.find(Pe=>Pe.id===B),Be=(de==null?void 0:de.slug)||"";if(!Ns(x,Be))return;Cs(x,Be)}else As()}},{pagesType:Pt,partialsType:tt}=f.useMemo(()=>{const A=de=>K?de.name.toLowerCase().includes(K.toLowerCase())||de.key.toLowerCase().includes(K.toLowerCase()):!0;return{pagesType:s.filter(de=>de.hasSlug!==!1&&A(de)),partialsType:s.filter(de=>de.hasSlug===!1&&A(de))}},[s,K]);return i&&!(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:W,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:st("w-full justify-between",i&&!C?"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:K,onChange:A=>Q(A.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(A=>t.jsxs(o.CommandItem,{value:A.key,onSelect:()=>{ee(A.key),W(!1)},className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",S===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:S,disabled:i&&!C,onChange:A=>ee(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!C?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})}),I&&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:Ne,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(ts=s.find(A=>A.key===S))==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:A=>ye(A.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)})]}):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:W,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:st("w-full justify-between",i&&!C?"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:K,onChange:A=>Q(A.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(A=>t.jsxs(o.CommandItem,{value:A.key,onSelect:()=>ee(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",S===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsx(o.CommandGroup,{heading:"Pages",children:Pt.map(A=>t.jsxs(o.CommandItem,{value:A.key,onSelect:()=>ee(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",S===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsxs(t.Fragment,{children:[Pt.length>0&&t.jsx(o.CommandGroup,{heading:"Pages",children:Pt.map(A=>t.jsxs(o.CommandItem,{value:A.key,onSelect:()=>ee(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",S===A.key?"opacity-100":"opacity-0")})]},A.key))}),tt.length>0&&t.jsx(o.CommandGroup,{heading:"Partials",children:tt.map(A=>t.jsxs(o.CommandItem,{value:A.key,onSelect:()=>ee(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:st("mr-2 h-4 w-4",S===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:S,disabled:i&&!C,onChange:A=>ee(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!C?"cursor-not-allowed text-gray-500":""}`,children:i?ne?t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})]})}),I&&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:Ne,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(ai,{templates:oe,selectedTemplateId:R,onSelectTemplate:le,isLoading:be})]}),t.jsx(si,{pages:l,selectedParentId:B,onChange:D}),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:A=>ye(A.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:A=>De(A.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(ti,{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(en,{value:x,onChange:T,placeholder:B&&B!=="none"?"Enter page slug":S==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:B&&B!=="none"?(ss=l==null?void 0:l.find(A=>A.id===B))==null?void 0:ss.slug:void 0,onValidationChange:p}),g&&t.jsx("p",{className:"text-xs text-red-500",children:g})]}),t.jsx(o.Button,{disabled:ce||!j&&(!(F!=null&&F.dynamicSegments)||!ue)||ue&&!$,type:"submit",className:"w-full",children:i?ce?"Updating...":"Update page":ce?"Creating...":"Create Page"})]})}const Wn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Te(),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(oi,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},ci=()=>{const e=ie(),s=M.useQueryClient(),n=J();return M.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:[Y,_.GET_WEBSITE_PAGES]}),H.toast.success("Page duplicated successfully")},onError:a=>{H.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Yn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=ci(),[r,i]=f.useState(null),[l,c]=f.useState(`${e.name} (Copy)`),u=h.isEmpty(e.slug),[d,m]=f.useState(u?"":`${e.slug.split("/").pop()}-copy`),g=u?"":h.initial(e.slug.split("/")).join("/"),[b,j]=f.useState(!1),p=S=>{if(S.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),j(!0);const y={pageId:e.id,name:l};u||(y.slug=`${g}/${d}`),n(y,{onSuccess:()=>{j(!1),s()},onError:w=>{j(!1),w.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):w.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):w.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(w.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:S=>c(S.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(en,{value:d,onChange:S=>m(S),parentSlug:g,onValidationChange:S=>{i(S?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||b,children:a||b?"Duplicating...":"Duplicate"})]})]})]})})},ui=1*1024*1024,Jn=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),[l,c]=f.useState(""),[u,d]=f.useState(!1),m=f.useRef(null),g=zr(),{data:b}=Te(),j=b==null?void 0:b.find(I=>I.key===e.pageType),p=(j==null?void 0:j.name)||h.startCase(e.pageType),S=f.useCallback(I=>{var k;const E=(k=I.target.files)==null?void 0:k[0];if(E){if(E.size>ui){H.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 O=new FileReader;O.onloadend=()=>{c(O.result),d(!1)},O.readAsDataURL(E)}catch(O){console.error("Error reading file:",O),d(!1),H.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),y=()=>{c(""),m.current&&(m.current.value="")},w=()=>{var I;(I=m.current)==null||I.click()},C=()=>{a(!0),g.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:I=>i(I.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:S,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:w,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(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:I=>{I.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:C,children:"Mark as template"})]})]})})},Xn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:c})=>{const{hasPermission:u}=U.usePermissions(),{data:d}=Te(),m=f.useMemo(()=>h.find(d,{key:e.pageType}),[d,e.pageType]),g=f.useMemo(()=>!!e.isTemplate,[e.isTemplate]),b=f.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)&&b&&t.jsx(t.Fragment,{children:g?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]})})]})]})},Zn=({page:e,onClose:s})=>{const[n,a]=f.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"})]})]})})},di=Dn("expandedPagesState",[]),sn=e=>h.flatMap(e,s=>[s,...s.children?sn(s.children):[]]),hi=(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)||[]},ea=(e,s)=>{if(!s)return[];const n=sn(e),a=h.find(n,r=>r.id===s);if(a){if(a.parent)return[...ea(e,a.parent),s];const r=hi(e,s);if(!h.isEmpty(r))return r}return[s]},mi=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)},ta=e=>{const[s,n]=_e.useAtom(di),a=e?h.includes(s,e):!1,r=f.useCallback(()=>{n(d=>a?h.filter(d,m=>m!==e):[...d,e])},[n,a,e]),i=f.useCallback((d,m)=>{if(!m||h.isEmpty(d))return;const g=sn(d),b=ea(g,m);if(!Array.isArray(b)||h.isEmpty(b))return;const j=b.slice(0,-1);h.isEmpty(j)||n(p=>h.uniq([...p,...j]))},[n]),l=f.useCallback(d=>{if(h.isEmpty(d))return;const m=mi(d);h.isEmpty(m)||n(g=>h.union(g,m))},[n]),c=f.useCallback(d=>{if(h.isEmpty(d))return;const m=h.flatMap(d,g=>{const b=j=>[j.id,...j.children?h.flatMap(j.children,b):[]];return b(g)});n(m)},[n]),u=f.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:c,collapseAll:u}},gn=(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)})),fi=(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):[]}}),gi=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},sa=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?sa(n.children):[]})),xi=(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=gn(r,s);else{const m=gn(r,s),g=fi(e,m);r=h.uniqBy([...m,...g],"id")}const i=sa(gi(r)),l=Ds(i,s,a),c=h.filter(l,m=>a(m.pageType)).sort((m,g)=>(m.name||"").localeCompare(g.name||"")),u=h.keyBy(h.filter(l,m=>!a(m.pageType)),"pageType"),d=Object.values(h.mapValues(u,(m,g)=>({...m,name:h.startCase(g),isPartialGroup:!0,children:l.filter(b=>b.pageType===g)})));return[...c,...d]},pi=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:c,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:m,isExpanded:g,onToggleExpand:b})=>{const j=tn(),{data:p}=Te(),[,S]=U.useSidebarActivePanel(),y=f.useMemo(()=>h.find(p,{key:s.pageType}),[p,s.pageType]),w=f.useMemo(()=>{const k=h.get(s,"slug",""),O=e?Ve(e):"",z=O?k.replace(O,""):k;return z||"/"},[s,e]),C=f.useMemo(()=>!!s.isTemplate,[s.isTemplate]),I=f.useCallback(()=>{S("outline"),j(h.get(s,"id"),a)},[j,a,s,S]),E=f.useCallback(k=>{k.stopPropagation(),b()},[b]);return t.jsxs("div",{onClick:I,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 ${g?"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:[w,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[h.endsWith(w,"/")?`${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}),C&&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(Xn,{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()})})})]})]})},yi=({close:e,isOpen:s})=>{const[,n]=f.useState([]),[a,r]=f.useState(null),[i,l]=f.useState(""),[c,u]=f.useState(""),[d,m]=f.useState(null),g=P=>c?String(h.get(P,"name","")).toLowerCase().includes(c.toLowerCase())||String(h.get(P,"key","")).toLowerCase().includes(c.toLowerCase()):!0,[b,j]=f.useState(null),[p,S]=f.useState(null),[y,w]=f.useState(null),[C,I]=f.useState(null),{data:E,isFetching:k,refetch:O}=Zt(),[z,V]=f.useState(""),{hasPermission:ae}=U.usePermissions(),{updateForSelectedPage:K,expandPagesOnSearch:Q,expandAll:se,collapseAll:W}=ta(null),[ne,B]=Ie(),q=ne.get("page"),me=f.useRef(null),{data:ye}=Te(),ue=U.useChaiFeatureFlag("enable-add-page-dropdown"),v=f.useCallback(P=>{var R;return(R=h.find(ye,{key:P}))==null?void 0:R.hasSlug},[ye]);f.useEffect(()=>{s&&O()},[s,O]),f.useEffect(()=>{if(!h.isEmpty(z))return;const P=sessionStorage.getItem("pageTypeFilter")||"all";!h.isEmpty(ye)&&P&&(h.find(ye,{key:P})?V(P):V("all"))},[ye,z]);const x=P=>{V(P),sessionStorage.setItem("pageTypeFilter",P),u("")},T=f.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]);f.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=f.useMemo(()=>E?xi(E,i,z,v):[],[E,i,z,v]);f.useEffect(()=>{q&&!k&&!h.isEmpty(L)&&(K(L,q),me.current&&me.current.scrollIntoView({behavior:"smooth",block:"end"}))},[q,k,L,K]),f.useEffect(()=>{!h.isEmpty(i)&&!h.isEmpty(L)&&Q(L)},[i,L,Q]);const G=f.useCallback(()=>{se(L)},[se,L]),$=f.useCallback(()=>{W()},[W]);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(z)&&t.jsxs(o.Select,{value:z,onValueChange:x,children:[t.jsx(o.SelectTrigger,{className:`${z==="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&&g(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&&g(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&&g(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&&g(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,g))&&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(na,{item:P,currentPage:q,close:e,setUnpublishPage:j,setDeletePage:m,setAddEditPage:S,setMarkAsTemplate:w,setUnmarkAsTemplate:I,setDuplicatePage:r,level:0})},`page-item-${P.id}`)})})]}),ae(ve.ADD_PAGE)&&t.jsxs(o.Button,{className:"flex text-sm gap-x-2",onClick:()=>{S({slug:"",name:"",pageType:z==="all"?"page":z})},children:[t.jsx(N.Plus,{className:"w-4 h-4"})," Add New"]}),p&&t.jsx(Wn,{closePanel:e,editPage:T,addEditPage:p,setAddEditPage:S}),d&&t.jsx(Zs,{page:d,onClose:()=>m(null)}),b&&t.jsx(bs,{page:b,onClose:()=>j(null)}),y&&t.jsx(Jn,{page:y,onClose:()=>w(null)}),C&&t.jsx(Zn,{page:C,onClose:()=>I(null)}),a&&t.jsx(Yn,{page:a,onClose:()=>r(null)})]})},na=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:d,level:m=0})=>{const g=!h.isEmpty(e==null?void 0:e.children),{isExpanded:b,toggleExpanded:j}=ta(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(pi,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:g,isExpanded:b,onToggleExpand:j}),g&&b&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:h.map(h.get(e,"children",[]),p=>t.jsx(na,{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}`)},ji=({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}),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(ji,{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.jsxs("div",{className:"w-full text-xs whitespace-nowrap p-1",children:[t.jsxs("div",{children:["Name : ",t.jsx("span",{className:"font-medium",children:u.name})]}),u.lang&&t.jsxs("div",{children:["Language : ",t.jsx("span",{className:"font-medium",children:ke[u.lang]})]}),t.jsxs("div",{children:["Slug :",t.jsxs("span",{className:"font-mono font-medium",children:[" ",u.slug]})]})]})},u.id))]})]})},bi=({children:e})=>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",children:t.jsx("div",{className:"bg-white rounded-md p-4 shadow-xl min-w-[300px] max-w-[400px] flex flex-col items-center justify-center",children:e})}),wi=()=>{const{isPending:e,dynamicPage:s,dynamicPages:n,allLangPages:a,selectedLang:r,searchQuery:i,updateDynamicPage:l,updateSearchQuery:c,onChangeLanguage:u}=Er(),d=f.useRef(void 0);f.useEffect(()=>{d.current!==r&&s&&(u(),d.current=r)},[r,n]);const m=a.length>0;return t.jsxs("div",{className:"relative",children:[!e&&!s&&t.jsxs(bi,{children:[t.jsx("h1",{className:"text-lg font-medium",children:m?"Select a page":"No pages found"}),t.jsx("p",{className:"text-sm text-center text-gray-600 pt-4",children:m?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]}),t.jsx(vi,{dynamicPage:s,setDynamicPage:l,searchQuery:i,setSearchQuery:c,dynamicPages:a})]})},Si=({page:e})=>{const[s,n]=f.useState(null),[a,r]=f.useState(null),[i,l]=f.useState(null),[c,u]=f.useState(null),[d,m]=f.useState(null),[g,b]=f.useState(null);return e?t.jsxs(t.Fragment,{children:[t.jsx(Xn,{page:e,setDuplicatePage:j=>m(j),setAddEditPage:j=>b(j),setUnpublishPage:j=>r(j),setDeletePage:j=>n(j),setMarkAsTemplate:j=>l(j),setUnmarkAsTemplate:j=>u(j),children:t.jsx("div",{className:"p-0 m-0 w-6 h-6 p-1 absolute right-2 top-1/2 -translate-y-1/2 hover:bg-gray-200 rounded duration-100 cursor-pointer",children:t.jsx(N.MoreHorizontal,{className:"w-4 h-4",onClick:j=>j.stopPropagation()})})}),g&&t.jsx(Wn,{closePanel:()=>b(null),editPage:()=>{},addEditPage:g,setAddEditPage:b}),s&&t.jsx(Zs,{page:s,onClose:()=>n(null)}),a&&t.jsx(bs,{page:a,onClose:()=>r(null)}),i&&t.jsx(Jn,{page:i,onClose:()=>l(null)}),c&&t.jsx(Zn,{page:c,onClose:()=>u(null)}),d&&t.jsx(Yn,{page:d,onClose:()=>m(null)})]}):null},Ei=()=>{const e=He("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:f.createElement(e,{})}):null},Ni=()=>{const[e]=Ie(),s=e.get("page"),{data:n,isFetching:a}=Ae(),[r,i]=f.useState(!1),{savePage:l}=U.useSavePage(),c=h.get(n,"dynamic",!1),u=!!s&&!h.isEmpty(n),d=!s||!a&&h.isEmpty(n)||r,m=U.useChaiFeatureFlag("dynamic-page-selector");return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-x-1",children:[t.jsxs("div",{className:"relative",children:[t.jsxs(o.Button,{variant:"outline",className:"flex w-full items-center space-x-2 py-1",onClick:()=>{l(),i(!0)},children:[t.jsx("div",{children:t.jsx(N.Logs,{className:"h-4 w-4"})}),t.jsxs("span",{className:"flex max-w-[200px] items-center truncate leading-tight",children:[t.jsx("span",{className:"pr-1 font-light text-slate-600",children:"Editing:"}),a?t.jsx(N.Loader,{className:"ml-2 h-4 w-4 animate-spin text-slate-400"}):h.startCase(h.get(n,"name"))??""]}),t.jsx("div",{className:`${a?"hidden":"w-2"}`})]},"template-viewer"),!a&&t.jsx(Si,{page:n})]}),c&&!a&&m&&t.jsxs(t.Fragment,{children:[t.jsx(N.ChevronRight,{size:14,className:"text-slate-500"}),t.jsx(wi,{})]})]}),t.jsx(o.Sheet,{open:d,onOpenChange:g=>!g&&u&&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 ${u?"":"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(yi,{isOpen:d,close:()=>i(!1)})})]})})]})},nn=({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();f.useEffect(()=>{const y=new URLSearchParams(window.location.search),w=y.get("lang");w&&(a.includes(w)?i(w):(y.delete("lang"),c(y),i("")))},[a,c,i]);const[u,d]=f.useState(null),{data:m}=Ae(),{data:g}=Ze(),{data:b,isFetching:j}=Ke(),p=f.useMemo(()=>{const y=h.compact(h.map(h.get(g,"languages"),w=>{const C=h.find(b,{lang:w});return{key:w,value:h.get(ke,w,w),isLangPageAdded:!!C}})).filter(Boolean);return[{key:n,value:h.get(ke,n),isLangPageAdded:!0},...y]},[n,b,g]),S=y=>{i(y);const w=new URLSearchParams(window.location.search);y===n?w.delete("lang"):w.set("lang",y);const C=w.toString(),I=`${window.location.pathname}${C?`?${C}`:""}`;window.history.pushState({},"",I),c(w),window.dispatchEvent(new PopStateEvent("popstate"))};return h.isEmpty(a)||j?null:t.jsxs(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(ke,l,l),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"space-y-1 border-border",children:[h.map(p.filter(y=>y.isLangPageAdded),y=>t.jsxs(o.DropdownMenuItem,{className:U.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",y.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>S(y.key),children:[t.jsx("div",{className:"text-slate-600",children:y.value}),y.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"]})]},y.value)),e&&!h.isEmpty(p.filter(y=>!y.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(o.Separator,{}),t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:()=>{d({name:m==null?void 0:m.name,pageType:m==null?void 0:m.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"]})]})]})]}),u&&t.jsx(Qn,{languages:a,langProps:u,onClose:()=>d(null)})]})};function Ci(){return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(Ei,{}),t.jsx(Ni,{})]})}function Ai(e){const s=ie(),n=J();return M.useQuery({queryKey:[Y,"revisions",e],queryFn:async()=>await n(s,{action:_.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Ti=()=>{const e=ie(),s=J(),n=M.useQueryClient();return M.useMutation({mutationFn:async a=>await s(e,{action:_.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})},Pi=()=>{const e=ie(),s=J(),n=M.useQueryClient();return M.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:_.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})};function ki(){const{data:e}=Ae(),{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 Li(){const[e,s]=we.useState(!1),[n,a]=we.useState(null),[r,i]=we.useState(!1),[l,c]=we.useState(!1),{data:u}=Ae(),{data:d,isFetching:m,error:g,refetch:b}=Ai(u==null?void 0:u.id),{mutate:j,isPending:p}=Ti(),{mutate:S,isPending:y}=Pi(),w=M.useQueryClient(),C=O=>{n&&S({revisionId:n.uid,discardCurrent:O},{onSuccess:()=>{i(!1),a(null),w.invalidateQueries({queryKey:[Y,_.GET_DRAFT_PAGE]})}})},I=O=>{a(O),i(!0)},E=O=>{a(O),c(!0)},k=()=>{n&&j(n.uid,{onSuccess:()=>{c(!1),a(null)}})};return f.useEffect(()=>{e&&b()},[e,b]),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(_i,{}):g?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(ki,{}),d==null?void 0:d.map(O=>t.jsx(Ii,{revision:O,isLatest:O.uid==="current",onRestore:()=>I(O),onDelete:()=>E(O)},O.uid))]})})]})]}),t.jsx(o.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Bi,{open:r,onOpenChange:i,revision:n,onRestore:C,isRestoring:y}),t.jsx(Mi,{open:l,onOpenChange:c,revision:n,onDelete:k,isDeleting:p})]})}function _i(){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 Ii({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(Di,{revision:e,onRestore:n,onDelete:a})})]})}function Di({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 Bi({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 Mi({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 Oi=()=>{const e=ie(),s=J();return M.useQuery({queryKey:[Y,_.GET_CHANGES],queryFn:async()=>s(e,{action:_.GET_CHANGES})})},Gi=({currentEditor:e})=>{const{data:s}=et(e);return s==null?void 0:s.name};function Ri({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=f.useState([]),{data:r,isFetching:i}=Oi(),{data:l}=Te(),c=f.useCallback(E=>{var k;return(k=h.find(l,{key:E}))==null?void 0:k.hasSlug},[l]),u=f.useMemo(()=>h.filter(l,E=>!c(E.key)).map(E=>E.key),[c,l]),d=f.useMemo(()=>h.filter(r,E=>!u.includes(E.pageType)),[r,u]),m=f.useMemo(()=>h.filter(r,E=>u.includes(E.pageType)),[r,u]),g=f.useMemo(()=>h.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:b,isPending:j}=Js();f.useEffect(()=>{const E=h.map(h.filter(r,{online:!0}),"id");g&&E.push(g==null?void 0:g.id),a(E)},[r,g]);const p=n.length===(r==null?void 0:r.length),S=E=>{a(k=>h.includes(k,E)?h.filter(k,O=>O!==E):h.concat(k,E))},y=()=>{a(p?[]:h.map(r,"id"))},w=()=>{b({ids:h.uniq(n)},{onSuccess:()=>{s(),Dt("CENTER_CENTER")}})},C=E=>{if(E==="theme")return"Theme";const k=h.find(l,{key:E});return k?k==null?void 0:k.name:E},I=f.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(z=>z.pageType!=="theme"),k=[{label:"Offline",top:"pt-6"},...h.orderBy(h.filter(d,{online:!1}),"pageType"),...h.orderBy(h.filter(m,{online:!1}),"pageType")],O=g?[{label:"Theme",top:"pt-6"},g]:[];return[...E,...O,...k]},[d,m,g]);return t.jsx(o.Dialog,{open:e,onOpenChange:j?()=>{}: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(I,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(),S(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(Gi,{currentEditor:E.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:E.lang}),t.jsx("td",{className:"px-2",children:C(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:j,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{disabled:j||i||h.isEmpty(r),onClick:w,children:j?"Publishing...":"Publish"})]})]})})}const Ui=()=>{const e=J(),s=ie();return M.useQuery({queryKey:[_.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_DATA,data:{draft:!0}})})};function Fi({onClose:e}){const{data:s,isFetching:n}=Ui(),{mutateAsync:a,isPending:r}=fr(),i=He("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:f.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function aa({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 qi=()=>{const{selectedLang:e,fallbackLang:s}=U.useLanguages(),n=He("getPreviewUrl",async g=>g),[a,r]=f.useState(""),{data:i}=Ae(),{data:l}=Ke(),{data:c}=Te(),u=f.useMemo(()=>{var g;return(g=l==null?void 0:l.find(b=>(b==null?void 0:b.lang)===e))==null?void 0:g.slug},[e,l]),d=f.useCallback(g=>{var b;return(b=h.find(c,{key:g}))==null?void 0:b.hasSlug},[c]),m=e===s?"":e;return f.useEffect(()=>{(async()=>{if(typeof n=="function"){const g=!d(i==null?void 0:i.pageType),b=await n(g?`${m!==""?m+"/":""}${i==null?void 0:i.id}`:u||"");r(b)}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]})})})},$i=()=>{const[e,s]=U.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(aa,{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"})]})},zi=()=>{const[e,s]=f.useState(!1),{isLocked:n}=es(),{savePage:a,saveState:r}=U.useSavePage();f.useEffect(()=>{const m=g=>{r==="UNSAVED"&&(g.preventDefault(),g.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",m),()=>{window.removeEventListener("beforeunload",m)}},[r]);const i=f.useCallback(async()=>{s(!0),await a(!1)},[a]);f.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=f.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:c,buttonClass:u,tooltipContent:d}=f.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]})},Vi=()=>{const{selectedLang:e}=U.useLanguages(),{data:s}=Ct(),{data:n}=Ke(),[a,r]=f.useState(!1),[i,l]=f.useState(!1),[c,u]=f.useState(null),{data:d}=Ae(),{mutate:m,isPending:g}=Js(),{buttonText:b,buttonClassName:j,isPublished:p}=f.useMemo(()=>{const w=d&&(d==null?void 0:d.online);return{buttonClassName:w?"hover:bg-green-600 bg-green-500":"",isPublished:w,buttonText:w?re.PUBLISHED:re.PUBLISH}},[d]),S=async()=>{const w=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];m({ids:h.compact(w)},{onSuccess:()=>Dt("TOP_RIGHT")})},y=f.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:S,disabled:g||!(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 ${j}`,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:b}),e?`(${h.upperCase(e)})`:""]}),t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",disabled:g||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${j}`,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:g,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:g,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(Ri,{showModal:a,onClose:()=>r(!1)}),c&&t.jsx(bs,{page:c,onClose:()=>u(null)})]})},Hi=()=>{const e=He("settingComponent",null),[s,n]=f.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(aa,{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(Fi,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Ki(){const{isLocked:e}=es(),[s]=Ie(),n=s.get("lang"),a=Un(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Li,{}),t.jsx(Ge,{permission:ve.EDIT_THEME,children:t.jsx($i,{})}),t.jsx(Ge,{permission:ve.EDIT_SETTINGS,children:t.jsx(Hi,{})}),t.jsx(qi,{}),t.jsx(Ge,{permission:ve.SAVE_PAGE,children:t.jsx(zi,{})}),t.jsx(Ge,{permission:ve.PUBLISH_PAGE,children:t.jsx(Vi,{})})]})}function Qi(e){const s=window.location.host,n=e?e.endsWith("/")?e.slice(0,-1):e:"";let a="";if(n.length>=60)a="..."+n.slice(-60);else if(s.length+n.length>60){const r=60-n.length-3;a=(r>0?"..."+s.slice(s.length-r):"...")+n}else a=s+n;return a}const Wi=()=>{const{data:e}=Ct(),s=zn(),n=e==null?void 0:e.slug,a=!n;let r=window.location.origin+(n?n.endsWith("/")?n.slice(0,-1):n:"");s&&(r+=s);const l=(a?`Partial: ${e==null?void 0:e.name} `:Qi(s?`${n}${s}`:n)).replace(window.location.host,"");return 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"+(a?" pr-2":""),children:[t.jsx(nn,{}),t.jsx("div",{className:"flex w-full items-center overflow-hidden",children:t.jsx("div",{className:`w-full overflow-hidden overflow-ellipsis whitespace-nowrap pl-1 font-mono text-xs ${a?"italic text-gray-400":"text-gray-500"}`,children:l===""?"/(Homepage)":l})}),!a&&t.jsx("a",{href:r,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})})})]})},Yi=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(Ci,{}),t.jsx(Wi,{}),t.jsx(Ki,{})]}),Ji=()=>{const e=ie(),{aiContext:s}=Hs(),n=J();return f.useCallback(async(a,r,i,l)=>n(e,{action:_.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=In.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=In.useRegisteredChaiBlocks();return f.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])},xn={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 M.useQuery({queryKey:[Y,"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=>xn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>xn.getUILibraryBlock(i,s,e)})}),a}})},ra=()=>{const e=js(),s=J(),{user:n}=Ue(),a=n==null?void 0:n.id;return M.useQuery({queryKey:[Y,"permissions",a],queryFn:()=>s(e,{action:_.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:f.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:f.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return h.filter(r.blocks,i=>h.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},pn=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]=f.useState(""),[i,l]=f.useState(""),[c,u]=f.useState({}),[d,m]=f.useState(!1),[g,b]=f.useState(""),j=M.useMutation({mutationFn:async y=>{b("");const w=await Vs(n,{action:"LOGIN",data:y});if(!w.ok){const I=await w.json();throw new Error(I.error||"Login failed")}const C=await w.json();if(h.has(C,"id")&&h.has(C,"email")&&h.has(C,"accessToken")&&h.has(C,"refreshToken"))e(C);else throw s(),new Error("Something went wrong. Please try again.");return C},onSuccess:()=>{u({}),b("")},onError:y=>{u({email:" ",password:" "}),b(y.message||"Something went wrong")}}),p=async y=>{y.preventDefault(),u({});const w={email:a,password:i};try{const C=pn.parse(w);j.mutate(C)}catch(C){if(C instanceof ls.z.ZodError){const I=C.errors.reduce((E,k)=>{const O=k.path[0];return E[O]=k.message,E},{});u(I)}}},S=pn.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:g})}),t.jsx(o.Button,{type:"submit",className:"w-full",disabled:!S||j.isPending,children:j.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=()=>f.useMemo(()=>Bs,[Bs]),rl=e=>{Bs=e},il=()=>{const e=al();return t.jsx(f.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},ll=({isActive:e,show:s})=>{const{data:n}=Ze();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"})})},ia="lang",ol={id:ia,label:"Languages",position:"top",panel:ei,button:ll,view:"modal",width:400};function We({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",g=we.useCallback(p=>{const S=y=>n==="value"?y==="value"||y==="object":n==="array"?y==="array":y===n;p.type==="object"?(c(y=>[...y,p.key]),d(p.value)):S(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),b=we.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);c(p),d(p.reduce((S,y)=>S[y],e))}},[l,e]),j=we.useMemo(()=>Object.entries(u).map(([p,S])=>({key:p,value:S,type:m(S)})).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 S=p.currentTarget;S.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:b,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),j.map(p=>t.jsxs(o.CommandItem,{onSelect:()=>g(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:S=>{S.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}=Ke();return{data:f.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}=M.useMutation({mutationFn:async()=>{const m=ul();return await a(r,{action:_.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,"\\$&"),yn=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 g=a.substring(0,u).split(`
3
- `);d=g.length,m=g[g.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},la=({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]=f.useState("edit"),[g,b]=f.useState(null),[j,p]=f.useState(""),S=f.useRef(null),y=E=>{if(a)return;const k=E.target.value;s(k)},w=E=>{if(E.key==="Tab"){E.preventDefault();const k=E.currentTarget,O=k.selectionStart,z=k.selectionEnd;if(O!==z){const ae=e.substring(O,z).split(`
4
- `);if(E.shiftKey){const Q=ae.map(W=>W.startsWith(" ")?W.substring(2):W).join(`
5
- `),se=e.substring(0,O)+Q+e.substring(z);s(se),setTimeout(()=>{k.selectionStart=O,k.selectionEnd=O+Q.length},0)}else{const Q=ae.map(W=>` ${W}`).join(`
6
- `),se=e.substring(0,O)+Q+e.substring(z);s(se),setTimeout(()=>{k.selectionStart=O,k.selectionEnd=O+Q.length},0)}}else{const V=e.substring(0,O)+" "+e.substring(z);s(V),setTimeout(()=>{k.selectionStart=k.selectionEnd=O+2},0)}}};f.useEffect(()=>{const E=yn(e);if(E.isValid)if(b(null),E.parsed){const k=ml(E.parsed,c);p(k)}else p("");else b(E.error),p("")},[e,c]);const C=()=>{const E=yn(e);if(E.isValid&&E.parsed){const k=hl(E.parsed,E.placeholders);s(k)}},I=()=>{g!=null&&g.position&&S.current&&(S.current.focus(),S.current.setSelectionRange(g.position,g.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()||g!==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(We,{dataType:"value",data:c??{},onSelect:E=>u&&u(E,l)}),t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:!e.trim()||n||g!==null,children:"Format"})]})]}),t.jsxs(o.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(o.Textarea,{ref:S,id:l,name:l,className:`rounded-md border border-input text-xs ${g?"border-red-500":""}`,onChange:y,onKeyDown:w,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),g&&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:g.message}),g.line&&g.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",g.line,", column ",g.column]}),t.jsx(o.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:I,children:"Show position"})]})]})]}),t.jsxs(o.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(o.Textarea,{rows:i,value:j,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]})]})})},jn=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}},oa=()=>{const{t:e}=U.useTranslation(),[,s]=U.useSidebarActivePanel(),{data:n}=Ae(),{data:a}=Ws(),{data:r,isFetching:i}=cl(),l=r==null?void 0:r.seo,c=f.useRef(null),u=n==null?void 0:n.pageType,d=Hn(u),{selectedLang:m,fallbackLang:g}=U.useLanguages(),b=m||g,[j,p]=f.useState(!1),[S,y]=f.useState(!1),[w,C]=f.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),I=f.useRef({initial:w,updated:w}),{mutate:E,isPending:k}=Ys(),O=k||j||S,{hasPermission:z}=U.usePermissions(),V=z(ve.EDIT_SEO);f.useEffect(()=>{!i&&l&&C({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const ae=async()=>{if(!(!d||!b))try{p(!0);const B=us(d,b),q={...w,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","")};C(q),I.current.updated=q,H.toast.success(e("SEO fields reset to defaults"))}catch(B){H.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",B)}finally{p(!1)}},K=async()=>{if(!(!d||!b))try{y(!0);const B=us(d,b),q={...w,jsonLD:h.get(B,"seo.jsonLD","")};C(q),I.current.updated=q,H.toast.success(e("JSON-LD reset to default"))}catch(B){H.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",B)}finally{y(!1)}},Q=async()=>{E({id:r==null?void 0:r.id,seo:w},{onSuccess:()=>{I.current.initial=w,I.current.updated=w,s("outline"),H.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,C(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)})):(C(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))}))}},W=B=>{const q={...w,[B.target.name]:B.target.name==="noIndex"||B.target.name==="noFollow"?B.target.checked:B.target.value};C(q),I.current.updated=q},ne=B=>q=>{h.isEmpty(q.fieldValue)||W({target:{name:B,value:typeof q.fieldValue=="string"?q.fieldValue.replace(/^"(.*)"$/,"$1"):q.fieldValue}}),q.error&&H.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:[!V&&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(nn,{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:[V&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:ae,disabled:O||!V||!d,children:e(j?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),V&&t.jsx(We,{dataType:"value",data:a??{},onSelect:B=>se(B,"keyword")})]}),t.jsx(o.Input,{type:"text",id:"keyword",name:"keyword",value:w.keyword,onChange:W,disabled:O||!V,placeholder:e("Enter keyword"),readOnly:!V})]}),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:w.keyword,onComplete:ne("title"),field:"title"}),V&&t.jsx(We,{dataType:"value",data:a??{},onSelect:B=>se(B,"title")})]})]}),t.jsx(o.Input,{type:"text",id:"title",name:"title",value:w.title,onChange:W,disabled:O||!V,placeholder:e("Enter SEO title"),readOnly:!V})]}),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:w.keyword,onComplete:ne("description"),field:"description"}),V&&t.jsx(We,{data:a??{},onSelect:B=>se(B,"description")})]})]}),t.jsx(o.Textarea,{id:"description",name:"description",rows:5,value:w.description,onChange:W,disabled:O||!V,placeholder:e("Enter SEO description"),readOnly:!V})]}),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")}),V&&t.jsx(We,{dataType:"value",data:a??{},onSelect:B=>se(B,"canonicalUrl")})]}),t.jsx(o.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:w.canonicalUrl,onChange:W,disabled:O||!V,placeholder:e("Enter Canonical URL"),readOnly:!V})]}),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:w.noIndex,onChange:W,disabled:O||!V,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:w.noFollow,onChange:W,disabled:O||!V,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:w.keyword,onComplete:ne("ogTitle"),field:"ogTitle"}),V&&t.jsx(We,{dataType:"value",data:a??{},onSelect:B=>se(B,"ogTitle")})]})]}),t.jsx(o.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:w.ogTitle,onChange:W,disabled:O||!V,placeholder:e("Enter OG title"),readOnly:!V})]}),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:w.keyword,onComplete:ne("ogDescription"),field:"ogDescription"}),V&&t.jsx(We,{dataType:"value",data:a??{},onSelect:B=>se(B,"ogDescription")})]})]}),t.jsx(o.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:w.ogDescription,onChange:W,disabled:O||!V,placeholder:e("Enter OG description"),readOnly:!V})]}),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(Xa,{assetId:w.ogImageId,assetUrl:w.ogImage,onChange:B=>{C({...w,ogImage:B.url,ogImageId:B.id})},disabled:O||!V,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(o.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[V&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{variant:"outline",size:"sm",type:"button",onClick:K,disabled:O||!V||!d,children:e(S?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(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:w.keyword,onComplete:ne("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(la,{id:"jsonLD",value:w.jsonLD,onChange:B=>{W({target:{name:"jsonLD",value:B}})},placeholder:e("Enter JSON-LD"),disabled:O||!V,readOnly:!V,pageData:a||{},rows:12,handleFieldInsert:se})]})]})})]})})]}),V&&t.jsxs("div",{className:"fixed bottom-0 left-0 right-0 flex w-full flex-shrink-0 items-center justify-between border-t bg-background p-4",children:[jn(w.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:Q,disabled:!jn(w==null?void 0:w.jsonLD)||h.isEqual(I.current.initial,w)||O||!V,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")})]})]})]})};oa.displayName="SeoPanel";const ca="seo",gl=({isActive:e,show:s})=>{const{data:n}=Ae(),a=Hn(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:ca,label:"SEO & JSON-LD",panel:oa,button:gl,position:"top",width:600,view:"modal"},pl="user-info",yl=()=>{const{user:e,logout:s}=Ue(),n=M.useQueryClient(),a=He("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:[Y]}),h.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},jl={id:pl,label:"User Info",button:yl,position:"bottom"},vl=()=>{U.registerChaiSidebarPanel(ca,xl),U.registerChaiSidebarPanel(ia,ol),U.registerChaiSidebarPanel("user-info",jl)};var te={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return vn(this.context.count)},getNextContextId(){return vn(this.context.count++)}};function vn(e){const s=String(e),n=s.length-1;return 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"),ua=typeof Proxy=="function",an=Symbol("solid-track"),hs={equals:bl},da=ya,Qe=1,ms=2,ha={owned:null,cleanups:null,context:null,owner:null},ks={},he=null,Ls=null,wl=null,xe=null,Le=null,ze=null,ws=0;function Ye(e,s){const n=xe,a=he,r=e.length===0,i=s===void 0?a:s,l=r?ha:{owned:null,cleanups:null,context:i?i.context:null,owner:i},c=r?e:()=>e(()=>Ce(()=>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)),pa(n,r));return[xa.bind(n),a]}function ma(e,s,n){const a=Ss(e,s,!0,Qe);At(a)}function Je(e,s,n){const a=Ss(e,s,!1,Qe);At(a)}function rn(e,s,n){da=Ml;const a=Ss(e,s,!1,Qe);(!n||!n.render)&&(a.user=!0),ze?ze.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),xa.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,g=typeof a=="function"&&Me(a);const b=new Set,[j,p]=(i.storage||Se)(i.initialValue),[S,y]=Se(void 0),[w,C]=Se(void 0,{equals:!1}),[I,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,K,Q,se){return l===ae&&(l=null,se!==void 0&&(m=!0),(ae===c||K===c)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(se,{value:K})),c=ks,O(K,Q)),K}function O(ae,K){qe(()=>{K===void 0&&p(()=>ae),E(K!==void 0?"errored":m?"ready":"unresolved"),y(K);for(const Q of b.keys())Q.decrement();b.clear()},!1)}function z(){const ae=Il,K=j(),Q=S();if(Q!==void 0&&!l)throw Q;return xe&&xe.user,K}function V(ae=!0){if(ae!==!1&&d)return;d=!1;const K=g?g():a;if(K==null||K===!1){k(l,Ce(j));return}const Q=c!==ks?c:Ce(()=>r(K,{value:j(),refetching:ae}));return Sl(Q)?(l=Q,"value"in Q?(Q.status==="success"?k(l,Q.value,void 0,K):k(l,void 0,Ms(Q.value),K),Q):(d=!0,queueMicrotask(()=>d=!1),qe(()=>{E(m?"refreshing":"pending"),C()},!1),Q.then(se=>k(Q,se,void 0,K),se=>k(Q,void 0,Ms(se),K)))):(k(l,Q,void 0,K),Q)}return Object.defineProperties(z,{state:{get:()=>I()},error:{get:()=>S()},loading:{get(){const ae=I();return ae==="pending"||ae==="refreshing"}},latest:{get(){if(!m)return z();const ae=S();if(ae&&!l)throw ae;return j()}}}),g?ma(()=>V(!1)):V(!1),[z,{refetch:V,mutate:p}]}function Nl(e){return qe(e,!1)}function Ce(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=Ce(()=>s(c,r,l));return r=c,u}}function fa(e){rn(()=>Ce(e))}function St(e){return he===null||(he.cleanups===null?he.cleanups=[e]:he.cleanups.push(e)),e}function bn(){return he}function Al(e,s){const n=he,a=xe;he=e,xe=null;try{return qe(s,!0)}catch(r){ln(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 _l(e){let s;return he&&he.context&&(s=he.context[e.id])!==void 0?s:e.defaultValue}function ga(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 Il;function xa(){if(this.sources&&this.state)if(this.state===Qe)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 pa(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):ze.push(i),i.observers&&ja(i)),l||(i.state=Qe)}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=Qe,e.owned&&e.owned.forEach(Ot),e.owned=null),e.updatedAt=n+1,ln(l)}finally{xe=i,he=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?pa(e,a):e.value=a,e.updatedAt=n)}function Ss(e,s,n,a=Qe,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!==ha&&(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&&Ce(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===Qe)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=[]),ze?n=!0:ze=[],ws++;try{const a=e();return Bl(n),a}catch(a){n||(ze=null),Le=null,ln(a)}}function Bl(e){if(Le&&(ya(Le),Le=null),e)return;const s=ze;ze=null,s.length&&qe(()=>da(s),!1)}function ya(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===Qe?a!==s&&(!a.updatedAt||a.updatedAt<ws)&&fs(a):r===ms&&gs(a,s)}}}function ja(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):ze.push(n),n.observers&&ja(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 ln(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 Je(()=>r=Ce(()=>(he.context={...he.context,[e]:a.value},ga(()=>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,g;return u[an],Ce(()=>{let j,p,S,y,w,C,I,E,k;if(d===0)l!==0&&(xs(i),i=[],a=[],r=[],l=0,c&&(c=[])),n.fallback&&(a=[Gs],r[0]=Ye(O=>(i[0]=O,n.fallback())),l=1);else if(l===0){for(r=new Array(d),g=0;g<d;g++)a[g]=u[g],r[g]=Ye(b);l=d}else{for(S=new Array(d),y=new Array(d),c&&(w=new Array(d)),C=0,I=Math.min(l,d);C<I&&a[C]===u[C];C++);for(I=l-1,E=d-1;I>=C&&E>=C&&a[I]===u[E];I--,E--)S[E]=r[I],y[E]=i[I],c&&(w[E]=c[I]);for(j=new Map,p=new Array(E+1),g=E;g>=C;g--)k=u[g],m=j.get(k),p[g]=m===void 0?-1:m,j.set(k,g);for(m=C;m<=I;m++)k=a[m],g=j.get(k),g!==void 0&&g!==-1?(S[g]=r[m],y[g]=i[m],c&&(w[g]=c[m]),g=p[g],j.set(k,g)):i[m]();for(g=C;g<d;g++)g in S?(r[g]=S[g],i[g]=y[g],c&&(c[g]=w[g],c[g](g))):r[g]=Ye(b);r=r.slice(0,l=d),a=u.slice(0)}return r});function b(j){if(i[g]=j,c){const[p,S]=Se(g);return c[g]=S,s(u[g],p)}return s(u[g])}}}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[an],Ce(()=>{if(m===0)return c!==0&&(xs(i),i=[],a=[],r=[],c=0,l=[]),n.fallback&&(a=[Gs],r[0]=Ye(b=>(i[0]=b,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]=Ye(g));for(;u<a.length;u++)i[u]();return c=l.length=i.length=m,a=d.slice(0),r=r.slice(0,c)});function g(b){i[u]=b;const[j,p]=Se(d[u]);return l[u]=p,s(j,u)}}}function on(e,s){return Ce(()=>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 _s(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 cn(...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(ua&&s)return new Proxy({get(l){for(let c=e.length-1;c>=0;c--){const u=_s(e[c])[l];if(u!==void 0)return u}},has(l){for(let c=e.length-1;c>=0;c--)if(l in _s(e[c]))return!0;return!1},keys(){const l=[];for(let c=0;c<e.length;c++)l.push(...Object.keys(_s(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 g=Object.getOwnPropertyDescriptor(c,m);if(!a[m])a[m]=g.get?{enumerable:!0,configurable:!0,get:Ul.bind(n[m]=[g.get.bind(c)])}:g.value!==void 0?g:void 0;else{const b=n[m];b&&(g.get?b.push(g.get.bind(c)):g.value!==void 0&&b.push(()=>g.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 va(e,...s){if(ua&&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 ba(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())?Ce(()=>{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 wa=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?Ce(()=>r(s?a:()=>{if(!Ce(n))throw wa("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=ga(()=>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?Ce(()=>u(s?l:()=>{if(Ce(r)[0]!==i)throw wa("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 g=c;for(;g<i;)d.set(n[g],g++)}const m=d.get(s[l]);if(m!=null)if(c<m&&m<i){let g=l,b=1,j;for(;++g<r&&g<i&&!((j=d.get(s[g]))==null||j!==m+b);)b++;if(b>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 Sa(e,s,n,a={}){let r;return Ye(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 Ea(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,Pa))}}function ro(e=window.document){if(e[Bt]){for(let s of e[Bt].keys())e.removeEventListener(s,Pa);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 Na(e,s){rt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Ca(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]||(wn(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||(wn(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 Aa(e,s={},n,a){const r={};return a||Je(()=>r.children=Gt(e,s.children,r.children)),Je(()=>typeof s.ref=="function"&&Ta(s.ref,e)),Je(()=>uo(e,s,n,!0,r,!0)),r}function Ta(e,s,n){return Ce(()=>e(s,n))}function ys(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Gt(e,s,a,n);Je(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]=Sn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const c=s[l];r[l]=Sn(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 wn(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 Sn(e,s,n,a,r,i,l){let c,u,d,m,g;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 b=s.slice(3);a&&e.removeEventListener(b,a,typeof a!="function"&&a),n&&e.addEventListener(b,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const b=s.slice(10);a&&e.removeEventListener(b,a,!0),n&&e.addEventListener(b,n,!0)}else if(s.slice(0,2)==="on"){const b=s.slice(2).toLowerCase(),j=eo.has(b);if(!j&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(b,p)}(j||n)&&(Ca(e,b,n,j),j&&Ea([b]))}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((g=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(g)s=s.slice(5),u=!0;else if(rt(e))return n;s==="class"||s==="className"?Na(e,n):c&&!u&&!d?e[mo(s)]=n:e[m||s]=n}else{const b=r&&s.indexOf(":")>-1&&so[s.split(":")[0]];b?io(e,b,s,n):ps(e,Jl[s]||s,n)}return n}function Pa(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 Je(()=>{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 Je(()=>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 g=[m];for(;(m=m.nextSibling)!==a;)g.push(m);return n=g}if(u.length===0){if(n=it(e,n,a),c)return n}else d?n.length===0?En(e,u,a):no(e,n,u):(n&&it(e),En(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 En(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 ka(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=bn();let i,l=!!te.context;return rn(()=>{l&&(bn().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);Ye(g=>ys(c,()=>u()?g():i(),null)),St(m)}else{const u=ka(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]=va(e,["component"]),a=Me(()=>s.component);return Me(()=>{const r=a();switch(typeof r){case"function":return Ce(()=>r(n));case"string":const i=to.has(r),l=te.context?ho():ka(r,i);return Aa(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()}},La=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 La{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 Nn(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,Xe=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,Ia=e=>So(e)==="Symbol",Po=e=>e instanceof Date&&!isNaN(e.valueOf()),ko=e=>e instanceof Error,Cn=e=>typeof e=="number"&&isNaN(e),Lo=e=>Ao(e)||Eo(e)||_a(e)||Co(e)||No(e)||Ia(e),_o=e=>typeof e=="bigint",Io=e=>e===1/0||e===-1/0,Do=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Bo=e=>e instanceof URL,Da=e=>e.replace(/\./g,"\\."),Is=e=>e.map(String).map(Da).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 Ba=[Fe(_a,"undefined",()=>null,()=>{}),Fe(_o,"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=>Cn(e)||Io(e),"number",e=>Cn(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 Ma=Es((e,s)=>Ia(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),{}),Oa=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 Ga(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var Ra=Es(Ga,(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)}),Ua=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=[Ra,Ma,Ua,Oa],An=(e,s)=>{const n=Nn(Oo,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=Nn(Ba,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},Fa={};Ba.forEach(e=>{Fa[e.annotation]=e});var Go=(e,s,n)=>{if(Xe(s))switch(s[0]){case"symbol":return Ma.untransform(e,s,n);case"class":return Ra.untransform(e,s,n);case"custom":return Ua.untransform(e,s,n);case"typed-array":return Oa.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=Fa[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 qa(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)=>{qa(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(qa(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Xe(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(Xe(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(!Xe(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(Xe(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)||Xe(e)||Ut(e)||Ft(e)||Ga(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(Is):n[Is(i)]=l.map(Is)}),a?Fs(n)?[a]:[a,n]:Fs(n)?void 0:n}var $a=(e,s,n,a,r=[],i=[],l=new Map)=>{const c=Lo(e);if(!c){$o(e,r,s);const j=l.get(e);if(j)return a?{transformedValue:null}:j}if(!qo(e,n)){const j=An(e,n),p=j?{transformedValue:j.value,annotations:[j.type]}:{transformedValue:e};return c||l.set(e,p),p}if(os(i,e))return{transformedValue:null};const u=An(e,n),d=(u==null?void 0:u.value)??e,m=Xe(d)?[]:{},g={};Et(d,(j,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const S=$a(j,s,n,a,[...r,p],[...i,e],l);m[p]=S.transformedValue,Xe(S.annotations)?g[p]=S.annotations:Rt(S.annotations)&&Et(S.annotations,(y,w)=>{g[Da(p)+"."+w]=y})});const b=Fs(g)?{transformedValue:m,annotations:u?[u.type]:void 0}:{transformedValue:m,annotations:u?[u.type,g]:g};return c||l.set(e,b),b};function za(e){return Object.prototype.toString.call(e).slice(8,-1)}function Tn(e){return za(e)==="Array"}function Vo(e){if(za(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(Tn(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(Tn(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 La(s=>s.description??""),this.customTransformerRegistry=new wo,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=$a(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 Va=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}=Va(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),Ha=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,tc=(e,s)=>rs(e)===rs(s)?Ha(e,s):rs(e)>rs(s)?1:-1,sc={status:tc,"query hash":ec,"last updated":Ha},is=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Ka=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,nc=(e,s)=>is(e)===is(s)?Ka(e,s):is(e)>is(s)?1:-1,ac={status:nc,"last updated":Ka},rc=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),ic=()=>{const[e,s]=Se("dark");return fa(()=>{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},_t=(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,_t(a.get(r),i,n)),a}if(e instanceof Set){const a=_t(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]=_t(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]=_t(a[r],i,n),a}return e},It=(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,It(n.get(a),r)),n}if(e instanceof Set){const n=It(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]=It(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]=It(n[a],r),n}return e},Qa=(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,Ln,lc=(Ln=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=Sa(()=>{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=ba(()=>Promise.resolve().then(()=>require("./HO4MOOFI-OOt5FGah.cjs"))),fe(this,ft,u)),Qa(X(this,Vt),X(this,ct)),on(u,cn({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,Ln),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:g}=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(g))}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=Sa(()=>{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=ba(()=>Promise.resolve().then(()=>require("./HUY7CZI3-BUe0zzsC.cjs"))),fe(this,wt,d)),Qa(X(this,Yt),X(this,xt)),on(d,cn({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=M.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:M.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=M.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:M.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 Wa=()=>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 M.useQuery({queryKey:[Y,_.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:_.GET_COLLECTIONS})})},fc=()=>{const{data:e}=Ae(),{data:s}=Ct(),{data:n}=Ze(),a=ie(),r=J(),i=f.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return M.useMutation({mutationFn:async({block:l})=>r(a,{action:_.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}}})})},Ya=()=>{const e=tn();return f.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=f.useRef(null),c=f.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 f.useEffect(()=>{a&&r&&c()},[r,a,c]),f.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=f.lazy(()=>Promise.resolve().then(()=>_c));hc();ar.loadWebBlocks();U.registerChaiTopBar(Yi);vl();U.registerChaiMediaManager(pc);U.registerChaiSaveToLibrary(Rr);const yc=e=>{const s=f.useRef([]),[n]=Ie(),a=n.get("page"),{data:r}=Ae(),{data:i={role:"",permissions:null}}=ra();el(),vr();const{data:l,isFetching:c}=Vn(),{blocks:u}=Zi(l),{data:d}=Te(),{mutateAsync:m}=On(),g=Ji(),{onSave:b}=tl(),{getPartialBlocks:j,getPartialBlockBlocks:p}=sl(),{aiContext:S,setAiContext:y}=Hs(),{mutateAsync:w}=Fr(),[C,I]=f.useState(!1),{data:E}=Ze(),k=Qs(),{data:O}=Ws(),{data:z}=mc(),{mutateAsync:V}=fc(),ae=Ya();xr(),f.useEffect(()=>{const W=()=>{document.hidden?I(!0):I(!1)};return window.addEventListener("visibilitychange",W),()=>window.removeEventListener("visibilitychange",W)},[]),s.current=u;const K=f.useMemo(()=>{const W={};return i&&(W.permissions=h.get(i,"permissions",null),W.role=h.get(i,"role","user")),W},[i]),Q=f.useCallback(async(W,ne)=>await w({pageType:W,query:ne}),[w]),se=f.useMemo(()=>h.get(E,"theme",{})||{},[E]);return t.jsxs(t.Fragment,{children:[c&&t.jsx(Wa,{}),t.jsx(U.ChaiBuilderEditor,{gotoPage:ae,collections:z??[],getBlockAsyncProps:V,pageExternalData:O,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:!C&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:j,blocks:c?[]:u,theme:h.cloneDeep(se),pageTypes:d,searchPageTypeItems:Q,saveAiContextCallback:async W=>{if(!a)return!0;const ne=s.current,B={_type:"@chai/ai-context",_value:h.isString(W)?W:""},q=[...ne,B];return await b({page:a,blocks:q}),y(W),!0},aiContext:S,askAiCallBack:g,onSave:async({blocks:W,theme:ne})=>{if(!a)return!0;s.current=W;const B={_type:"@chai/ai-context",_value:h.isString(S)?S:""},q=[...W,B];return await b({page:a,blocks:q}),s.current=q,h.isEqual(ne,se)||await m({settings:{theme:ne}}),!0},themePanelComponent:Yr,...K}),t.jsxs("div",{children:[t.jsx(Tr,{}),t.jsx(Pr,{})]})]})},jc=new M.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),vc=e=>{xc();const{isLoggedIn:s,isSessionExpired:n}=Ue(),[,a]=Gn(),[r,i]=f.useState(!1);return f.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(M.QueryClientProvider,{client:jc,children:[s?n?t.jsx(Wa,{}):t.jsx(yc,{...e}):t.jsx(il,{}),t.jsx(dc,{}),t.jsx(H.Toaster,{richColors:!0})]}):t.jsx("div",{})},bc=()=>{const e=ie(),s=J(),{data:n}=Ct(),a=M.useQueryClient();return M.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:_.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[Y,_.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[Y,_.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},wc=()=>{const e=Xt(),s=M.useQueryClient(),n=J();return M.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:_.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:[Y,_.GET_ASSETS]}),H.toast.success("Asset uploaded successfully")},onError:()=>{H.toast.error("Failed to upload asset")}})},Sc=()=>{const e=Xt(),s=M.useQueryClient(),n=J();return M.useMutation({mutationFn:async a=>n(e,{action:_.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,_.GET_ASSETS]}),H.toast.success("Asset deleted successfully")},onError:()=>{H.toast.error("Failed to delete asset")}})},Ec=()=>{const e=Xt(),s=M.useQueryClient(),n=J();return M.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,_.GET_ASSETS]}),H.toast.success("Asset updated successfully")},onError:()=>{H.toast.error("Failed to update asset")}})},Nc=(e={})=>{const s=Xt(),n=J(),{search:a,page:r=1,limit:i=30}=e;return M.useQuery({queryKey:[Y,_.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:_.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 M.useQuery({queryKey:[Y,_.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:_.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 Pn(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 kn(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 g,b,j;const{data:i,isLoading:l,isError:c}=Cc(e||""),[u,d]=f.useState(""),m=async(p,S)=>{try{await navigator.clipboard.writeText(p),H.toast.success(`${S} copied to clipboard`)}catch(y){H.toast.error(`Failed to copy ${S}`,{description:y==null?void 0:y.message})}};return f.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=${((g=i.metadata)==null?void 0:g.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:((b=i.metadata)==null?void 0:b.format)||i.type,capitalize:!0},{label:"Size",value:Ac(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:Pn(i.createdAt)},{label:"Updated",value:Pn(((j=i.metadata)==null?void 0:j.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(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,S)=>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,")"]})]},S))})]}),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||!kn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!kn(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=f.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]=f.useState(()=>{const j=localStorage.getItem("chai_optimize_images");return j!==null?j==="true":!0});f.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=f.useCallback(async j=>new Promise((p,S)=>{const y=j[0],w=new FileReader;w.readAsDataURL(y),w.onload=async()=>{a({file:w.result,folderId:void 0,name:y.name,optimize:l},{onSuccess:C=>{i&&i(C),p(C)},onError:C=>{S(C)}})},w.onerror=C=>S(C)}),[a,l,i]),{getRootProps:m,getInputProps:g,isDragActive:b}=nr.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",b?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...g()}),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:j=>{c(j)},onClick:j=>{j.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 Ja({close:e,onSelect:s,mode:n="image",assetId:a}){const l=f.useMemo(()=>[n],[n]),[c,u]=f.useState(null),[d,m]=f.useState(null),[g,b]=f.useState(null),[j,p]=f.useState({show:!1,file:""}),[S,y]=f.useState(!1),[w,C]=f.useState(a?"details":"grid"),[I,E]=f.useState(""),[k,O]=f.useState(""),[z,V]=f.useState(1),[ae]=f.useState(30),[K,Q]=f.useState([]);f.useEffect(()=>{a&&(u(a),C("details"))},[a]),f.useEffect(()=>{const D=setTimeout(()=>{E(k),V(1)},300);return()=>clearTimeout(D)},[k]);const{data:se,isLoading:W}=Nc({search:I.toLowerCase().trim(),page:z,limit:ae}),ne=(se==null?void 0:se.assets)||[],B=(se==null?void 0:se.total)||0,q=Math.ceil(B/ae),me=z<q,ye=z>1,ue=(ne==null?void 0:ne.length)>0,{mutate:v}=Sc(),{mutate:x,isPending:T}=wc(),{mutate:L,isPending:G}=Ec(),$=f.useCallback(D=>{D>=1&&D<=q&&V(D)},[q]),P=f.useCallback(()=>{me&&$(z+1)},[z,me,$]),R=f.useCallback(()=>{ye&&$(z-1)},[z,ye,$]),Z=D=>{O(D.target.value)},oe=f.useCallback(D=>{Q(le=>h.find(le,{id:D.id})?[]:[D])},[!1]),be=f.useCallback(()=>{Q([])},[]),ce=D=>{(D==null?void 0:D.length)!==0&&(s(h.pick(h.first(D||K),["id","url","width","height","description"])),e())},je=async D=>{m(D)},F=async()=>{d&&(b(d==null?void 0:d.id),await v(d.id,{onSuccess:()=>{b(null),m(null)},onError:()=>{b(null)}}),m(null))},ee=D=>{u(D.id),C("details")},Ne=async(D,le)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";le?(await x({file:D,folderId:void 0,name:j.name||"",optimize:Ee}),p({show:!1,file:""})):(await L({id:j.id||"",file:D}),p({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},De=f.useCallback(D=>{Q([D])},[]);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"}),w==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Lc,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:G,isUploadingAsset:T,onUploaded:De}),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"})]}),K.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[K.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(K),disabled:K.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:W?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"})]}):!W&&!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:I.length>0?"No assets found for your search: "+I:"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(D=>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",K.some(le=>le.id===D.id)?"border-blue-500":"hover:border-black/90",g&&(d==null?void 0:d.id)===D.id?"opacity-50 pointer-events-none":"",g===D.id?"opacity-50 pointer-events-none":""),onClick:()=>oe(D),onDoubleClick:()=>ce([D]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[g===D.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,D.type==="image"?t.jsx("img",{src:`${D.thumbnailUrl||"/placeholder.svg"}?v=${(D==null?void 0:D.updatedAt)||D.createdAt}`,alt:D.name,className:`object-contain w-full h-full min-h-[80px] ${K.some(le=>le.id===D.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"}),D.thumbnailUrl&&t.jsx("img",{src:`${D.thumbnailUrl||"/placeholder.svg"}?v=${(D==null?void 0:D.updatedAt)||D.createdAt}`,alt:D.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:D.name,children:D.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((D==null?void 0:D.size)||0)})})]}),!K.some(le=>le.id===D.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(D)},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(D.url),H.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:D.id,show:!0,file:D.url,name:D.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(D)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),K.some(le=>le.id===D.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})})]},D.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)},(D,le)=>{const Ee=le+1;return t.jsx(o.Button,{variant:z===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:z===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:()=>{C("grid"),u(null)},onEdit:D=>{p({id:D.id,show:!0,file:D.url,name:D.name})},onSave:async D=>{if(c){y(!0);try{const le=ne.find(Ee=>Ee.id===c);le&&await L(h.merge(le,{description:D}))}finally{y(!1)}}},isSaving:S})]}),j.show&&t.jsx(f.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:j.file,onSave:Ne,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:j.name,isEditing:!!j.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 _c=Object.freeze(Object.defineProperty({__proto__:null,default:Ja},Symbol.toStringTag,{value:"Module"})),Xa=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,c]=f.useState(!1),u=()=>{i||c(!0)},d=()=>{c(!1)},m=b=>{const j=Array.isArray(b)?b[0]:b;j!=null&&j.url&&n(h.pick(j,["url","id"])),c(!1)},g=()=>{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:g,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(Ja,{close:d,onSelect:m,mode:"image",assetId:e})})]})})]})},Ic=()=>{const{user:e,logout:s}=Ue(),n=e==null?void 0:e.accessToken;return f.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=an;exports.ChaiBuilderPages=vc;exports.ChaiBuilderPagesRealtime=Dc;exports.Dynamic=po;exports.For=$l;exports.ImagePicker=Xa;exports.Index=zl;exports.LanguageSwitcher=nn;exports.Match=Kl;exports.NestedPathSelector=We;exports.PermissionChecker=Ge;exports.Portal=xo;exports.Show=Vl;exports.SmartJsonInput=la;exports.Switch=Hl;exports.addEventListener=Ca;exports.batch=Nl;exports.className=Na;exports.clearDelegatedEvents=ro;exports.convertRemToPixels=rc;exports.createComponent=on;exports.createComputed=ma;exports.createContext=Ll;exports.createEffect=rn;exports.createMemo=Me;exports.createRenderEffect=Je;exports.createRoot=Ye;exports.createSignal=Se;exports.createUniqueId=ql;exports.delegateEvents=Ea;exports.deleteNestedDataByPath=It;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=cn;exports.mutationSortFns=ac;exports.on=Cl;exports.onCleanup=St;exports.onMount=fa;exports.registerLoginComponent=rl;exports.serialize=Va;exports.setAttribute=ps;exports.sortFns=sc;exports.splitProps=va;exports.spread=Aa;exports.stringify=Ko;exports.template=ao;exports.untrack=Ce;exports.updateNestedDataByPath=_t;exports.use=Ta;exports.useActivePage=Ct;exports.useBuilderPageData=Ws;exports.useChaiAuth=Ue;exports.useChaiFetch=Ic;exports.useChaiUserInfo=et;exports.useContext=_l;exports.useCurrentPage=Ae;exports.useFallbackLang=Qs;exports.useFetch=J;exports.useGotoPage=Ya;exports.useLanguagePages=Ke;exports.usePageTypes=Te;exports.useTransition=kl;exports.useUpdateActivePageMetadata=bc;exports.useUserRoleAndPermissions=ra;exports.useWebsitePages=Zt;exports.useWebsiteSetting=Ze;