@chaibuilder/pages 0.6.10 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +0,0 @@
1
- "use strict";var Zs=e=>{throw TypeError(e)};var en=(e,s,n)=>s.has(e)||Zs("Cannot "+n);var Z=(e,s,n)=>(en(e,s,"read from private field"),n?n.call(e):s.get(e)),fe=(e,s,n)=>s.has(e)?Zs("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),me=(e,s,n,a)=>(en(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),h=require("lodash-es"),g=require("react"),qe=require("jotai"),G=require("@tanstack/react-query"),K=require("sonner"),J=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),wt=require("date-fns"),w=require("lucide-react"),Sn=require("@chaibuilder/runtime"),as=require("zod"),Ua=require("react-dropzone"),Fa=require("@chaibuilder/sdk/web-blocks");function qa(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const ve=qa(g),Le={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",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},Q="chaibuilder";let za=0;function tn(e,s){const n=`atom${++za}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=$a,a.write=Va),s&&(a.write=s),a}function $a(e){return e(this)}function Va(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const Ha=Symbol(""),Ka=e=>typeof(e==null?void 0:e.then)=="function";function Wa(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var m,f;const b=y=>{if(y=y||"",a!==y){try{r=JSON.parse(y,s==null?void 0:s.reviver)}catch{return d}a=y}return r},x=(f=(m=e())==null?void 0:m.getItem(u))!=null?f:null;return Ka(x)?x.then(b):b(x)},setItem:(u,d)=>{var m;return(m=e())==null?void 0:m.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,m,f)=>u(d,b=>{let x;try{x=JSON.parse(b||"")}catch{x=f}m(x)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const m=f=>{f.storageArea===e()&&f.key===u&&d(f.newValue)};return window.addEventListener("storage",m),()=>{window.removeEventListener("storage",m)}}),o&&(i.subscribe=l(o)),i}const Qa=Wa();function En(e,s,n=Qa,a){const r=tn(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},tn(l=>l(r),(l,o,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===Ha?(o(r,s),n.removeItem(e)):d instanceof Promise?d.then(m=>(o(r,m),n.setItem(e,m))):(o(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const wn="__logged_in_user",Ya=En(wn,null),ze=()=>{const[e,s]=qe.useAtom(Ya),n=g.useCallback(()=>{s(null),localStorage.removeItem(wn)},[s]),a=g.useMemo(()=>{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}},Gs=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),X=()=>{const{user:e,logout:s}=ze(),n=G.useQueryClient(),a=e==null?void 0:e.accessToken;return g.useCallback(async(r,i,l={})=>{if(!a)return null;try{const o=h.get(i,"action","").toLowerCase(),u=await Gs(r+(o?`?action=${o}`:""),i,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[Q]}),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(o){throw console.error("API request failed:",i,o),o}},[a,s,n])},Nn=()=>{const e=ae(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:_.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Q,_.GET_DRAFT_PAGE]})}})},An=()=>{const e=ae(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||K.toast.success("Website settings updated successfully.")},onError:a=>{K.toast.error("Failed to update website settings",{description:a.message})}})},Ja=()=>{const e=ae(),s=G.useQueryClient(),n=X();return G.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_DATA]}),K.toast.success("Website data updated successfully.")},onError:a=>{K.toast.error("Failed to update website data",{description:a.message})}})};function ke(){const[e,s]=g.useState(new URLSearchParams(window.location.search));return g.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Xa=qe.atom({}),Cn=()=>qe.useAtom(Xa),Za=()=>{const[e]=ke(),s=e.get("page"),n=g.useRef(""),{mutate:a}=Nn();g.useEffect(()=>{!h.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Xe=(e,s)=>{const[n]=Cn();return g.useMemo(()=>h.get(n,e,s),[n,e,s])},ae=()=>Xe("apiUrl","/chai/api"),gs=()=>Xe("usersApiUrl","/chai/users"),Qt=()=>Xe("assetsApiUrl","/chai/assets"),Ve=e=>{const s=ae(),[n]=ke(),a=e??n.get("page"),r=X();return G.useQuery({queryKey:[Q,_.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=ae(),s=X();return G.useQuery({queryKey:[Q,_.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:_.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},Tn=e=>{const{fallbackLang:s}=J.useLanguages(),{data:n}=Ze(),{data:a,isFetching:r}=Ve(),i=g.useMemo(()=>{const l={[s]:!0};return h.each(h.get(n,"languages"),o=>{const u=h.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||h.isEmpty(e)||e&&i[e]},Os=()=>{const e=G.useQueryClient(),{data:s}=G.useQuery({queryKey:[Q,_.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:g.useCallback(a=>{e.setQueryData([Q,_.AI_CONTEXT],a)},[e]),aiContext:s}},Yt=()=>{const e=X(),s=ae();return G.useQuery({queryKey:[Q,_.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},er=qe.atom({lastSaved:void 0}),ps=()=>qe.useAtom(er),Me=()=>{const[e]=ke(),s=e.get("page"),[n]=Pn(),{data:a,isFetching:r}=Yt();return{data:g.useMemo(()=>({...h.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},Nt=()=>{const[e]=ke(),s=e.get("lang")??"",{data:n,isFetching:a}=Ve();return{data:g.useMemo(()=>h.find(n,{lang:s})||{},[n,s]),isFetching:a}},tr=qe.atom({}),Pn=()=>qe.useAtom(tr),st=e=>{const s=gs(),n=X();return G.useQuery({queryKey:[Q,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:_.GET_CHAI_USER,data:{userId:e}}),enabled:!h.isEmpty(e)})},sr=qe.atom(void 0),Jt=()=>{const[e]=ke(),s=e.get("page"),{user:n}=ze(),[a,r]=qe.useAtom(sr);return g.useMemo(()=>({isLocked:s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:i=>r(i)}),[n==null?void 0:n.id,a,s,r])},Rs=()=>{const{data:e}=Ze();return g.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},kn=()=>{const[e]=ke(),s=e.get("page"),n=ae(),{setAiContext:a}=Os(),{setCurrentEditor:r}=Jt(),[,i]=ps(),[,l]=Pn(),o=X();return G.useQuery({queryKey:[Q,_.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await o(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(f=>({...f,lastSaved:u.lastSaved})),l(h.get(u,"metadata",{})),d},enabled:!!s})},Us=()=>{const{data:e}=Me(),{data:s}=Nt(),n=ae(),a=X(),r=Rs();return G.useQuery({queryKey:[Q,_.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id],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,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)})};function nr({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r}){const[i,l]=g.useState(!1),o=()=>{l(!1),r()};return t.jsx("div",{className:"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.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(w.LockIcon,{className:"w-6 h-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(c.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:"w-12 h-12 border border-gray-300 rounded-full"}):t.jsx(w.UserIcon,{className:"w-12 h-12 p-2 border border-gray-300 rounded-full"}),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:"," ",wt.formatDistanceToNow(new Date(a),{addSuffix:!0})]})]})]}),t.jsx("div",{className:"text-sm mt-4",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(c.CardFooter,{children:t.jsxs(c.AlertDialog,{open:i,onOpenChange:l,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take Over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(w.AlertTriangleIcon,{className:"w-5 h-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:o,children:"Yes, Take Over"})]})]})]})})]})})}const ar=()=>{const{isLocked:e,currentEditor:s}=Jt(),{data:n}=st(s),[a]=ke(),r=a.get("page"),{mutate:i}=Nn(),{isFetching:l}=kn(),[o]=ps(),u=g.useCallback(()=>{i({id:r})},[r,i]);return!e||l?t.jsx("div",{className:""}):t.jsx(nr,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",lastSaved:(o==null?void 0:o.lastSaved)||"",onTakeOver:u})},rr=()=>{const[e,s]=ke(),n=e.get("lang"),a=Tn(n),{setSelectedLang:r}=J.useLanguages(),i=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(o),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=h.get(Le,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-12 bg-black/30 backdrop-blur-sm",children:t.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(w.LockIcon,{className:"w-6 h-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(c.CardFooter,{children:t.jsx(c.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},ir=e=>{const s=ae(),n=X();return G.useMutation({mutationFn:async a=>n(s,{action:_.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),K.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},lr=e=>{const s=ae(),n=X();return G.useQuery({queryKey:[Q,"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})},or=e=>{const s=ae(),n=X();return G.useMutation({mutationFn:async a=>n(s,{action:_.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),K.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},cr=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=g.useState(!1),u=J.useUpdateBlocksPropsRealtime(),d=or(()=>{u([e],{_libBlockId:void 0}),K.toast.success("Block deleted successfully"),o(!1),a()}),m=()=>{o(!0),d.mutate(s)},f=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:l,children:[t.jsx(w.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:b=>!b&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:i||f}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:m,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},ur=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=g.useState(!1);return t.jsx(cr,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{o(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>o(!0),children:[t.jsx(w.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},dr=()=>{const e=ae(),s=X(),n=G.useQueryClient(),{data:a=[],isLoading:r,error:i}=G.useQuery({queryKey:[Q,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:o}=G.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return s(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:[Q,"library-groups"]}),K.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),K.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:o}},hr=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),l=g.useRef(null),{groups:o}=dr(),[u,d]=g.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),m=g.useMemo(()=>[...o,...u.filter(x=>!o.some(y=>y.id===x.id))],[o,u]),f=()=>{const x=r.trim();if(!x)return;const y={id:x,name:x};d(A=>[...A,y]),s(y.id),i(""),a(!1)};g.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const b=x=>{x.key==="Enter"&&(x.preventDefault(),f())};return g.useEffect(()=>{e&&!m.some(x=>x.id===e)&&s("")},[e,m,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:x=>i(x.target.value),onKeyDown:b}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:f,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:x=>s(x.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(x=>t.jsx("option",{value:x.id,children:x.name},`lib-${x.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(x=>!o.some(y=>y.id===x.id)).map(x=>t.jsx("option",{value:x.id,children:x.name},`local-${x.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(w.Plus,{className:"h-4 w-4"})})]})},mr=10*1024*1024,fr=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useCallback(u=>{var m;const d=(m=u.target.files)==null?void 0:m[0];if(d){if(d.size>mr){K.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const f=new FileReader;f.onloadend=()=>{s(f.result),a(!1)},f.readAsDataURL(d)}catch(f){console.error("Error reading file:",f),a(!1),K.toast.error("Failed to process image",{description:f instanceof Error?f.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},o=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"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(w.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(w.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"})})]})},ye={...J.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"},gr=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=J.usePartailBlocksStore(),i=s.find(C=>C._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=g.useMemo(()=>s.some(C=>C._type==="PartialBlock"||C._type==="GlobalBlock"),[s]),d=g.useMemo(()=>{let C=[];for(const D of s)if(D._type==="PartialBlock"||D._type==="GlobalBlock"){let U=r(D.partialBlockId);D._parent&&(U==null?void 0:U.length)>0&&(U=U.map(E=>(h.isEmpty(E._parent)&&h.set(E,"_parent",D._parent),E))),C=[...C,...U]}else C.push(D);return C},[s,r]),[m,f]=g.useState(""),[b,x]=g.useState(""),[y,A]=g.useState(""),[v,N]=g.useState(""),[P,L]=g.useState({}),[S,T]=g.useState(!1),[O,Y]=g.useState(o),[z,re]=g.useState(!1),{hasPermission:W}=J.usePermissions(),$=W(ye.DELETE_LIBRARY_BLOCK),te=J.useUpdateBlocksPropsRealtime(),F=()=>{te([a],{_libBlockId:void 0}),K.toast.success("Block delinked from library"),n()},{data:ne,isLoading:B,isError:q}=lr(l);g.useEffect(()=>{q&&o&&(re(!0),Y(!1))},[q,o]),g.useEffect(()=>{ne&&!B&&(f(ne.name||""),x(ne.group||""),A(ne.description||""),N(ne.preview||""),Y(!1))},[ne,B]),g.useEffect(()=>{const C=m.trim().length>=2,D=b.trim()!=="";T(C&&D)},[m,b]);const oe=()=>{const C={};return m.trim()?m.length<2&&(C.name="Name must be at least 2 characters"):C.name="Name is required",b||(C.group="Group is required"),L(C),Object.keys(C).length===0},{resetLibrary:ce}=J.useLibraryBlocks({id:""}),V=ir(C=>{o||te([a],{_libBlockId:C.id}),K.toast.success(`Block ${o?"updated":"saved"} successfully`),ce(C.library),n()}),j=async C=>{if(C.preventDefault(),!oe())return;const D=d.map(U=>(h.has(U,"_libBlockId")&&delete U._libBlockId,U));V.mutate({name:m.trim(),group:b,blocks:D,description:y.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...o?{id:l}:{}})},p=V.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"})}):z?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:F,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(w.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:P.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:m,onChange:C=>f(C.target.value),className:P.name?"border-destructive":""}),P.name&&t.jsx("p",{className:"text-xs text-destructive",children:P.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:P.group?"text-destructive":"",children:"Group"}),t.jsx(hr,{value:b,onChange:x}),P.group&&t.jsx("p",{className:"text-xs text-destructive",children:P.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:y,onChange:C=>A(C.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(fr,{value:v,onChange:N})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&$&&t.jsx(ur,{blockId:a,libBlockId:l,blockName:m,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:p,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:p||!S,children:p?"Saving...":o?"Update Block":"Save Block"})]})]})]})},se={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."},pr={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ce=()=>{const e=ae(),s=X();return G.useQuery({queryKey:[Q,_.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:_.GET_PAGE_TYPES})})},In=e=>{const{data:s}=Ce();return g.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},xr=()=>{const e=ae(),s=X();return G.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),[]}}})},_n=()=>{const e=ae(),s=G.useQueryClient(),n=X(),{data:a}=Ce();return G.useMutation({mutationFn:async r=>await n(e,{action:_.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Q,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=h.find(a,{key:i.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";K.toast.success(l)},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});K.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:h.get(pr,r.message,r.message)})}})},Fs=()=>{const e=ae(),s=G.useQueryClient(),n=X(),{data:a}=Ce();return G.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:[Q,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});K.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},yr=()=>{const e=ae(),s=G.useQueryClient(),n=X(),{data:a}=Ce();return G.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"){K.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Q,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});K.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},jr=()=>{const e=ae(),s=G.useQueryClient(),n=X(),{data:a}=Ce();return G.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:[Q,_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_PAGES]});const l=h.find(a,{key:i.pageType});K.toast.success(l!=null&&l.hasSlug?se.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=h.find(a,{key:i.pageType});K.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},qs=()=>{const e=ae(),s=X(),n=G.useQueryClient(),{data:a}=Me();return G.useMutation({mutationFn:async({ids:r})=>s(e,{action:_.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,_.GET_CHANGES]}),n.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[Q,_.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{K.toast.error("Failed to publish pages.")}})},vr=()=>{const e=ae(),s=X(),n=G.useQueryClient();return G.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:[Q,_.GET_WEBSITE_PAGES]}),K.toast.success("Page marked as template successfully.")},onError:()=>{K.toast.error("Failed to mark page as template.")}})},br=()=>{const e=ae(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async a=>s(e,{action:_.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_PAGES]}),K.toast.success("Page unmarked as template successfully.")},onError:()=>{K.toast.error("Failed to unmark page as template.")}})},Sr=()=>{const e=ae(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:_.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{K.toast.success(se.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[Q,_.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[Q,_.GET_WEBSITE_PAGES]})},onError:()=>{K.toast.error("Failed to change slug")}})};var zs={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!s.OffscreenCanvas)return!1;var j=new OffscreenCanvas(1,1),p=j.getContext("2d");p.fillRect(0,0,1,1);var C=j.transferToImageBitmap();try{p.createPattern(C,"no-repeat")}catch{return!1}return!0}();function u(){}function d(j){var p=n.exports.Promise,C=p!==void 0?p:s.Promise;return typeof C=="function"?new C(j):(j(u,u),null)}var m=function(j,p){return{transform:function(C){if(j)return C;if(p.has(C))return p.get(C);var D=new OffscreenCanvas(C.width,C.height),U=D.getContext("2d");return U.drawImage(C,0,0),p.set(C,D),D},clear:function(){p.clear()}}}(o,new Map),f=function(){var j=Math.floor(16.666666666666668),p,C,D={},U=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(p=function(E){var H=Math.random();return D[H]=requestAnimationFrame(function R(M){U===M||U+j-1<M?(U=M,delete D[H],E()):D[H]=requestAnimationFrame(R)}),H},C=function(E){D[E]&&cancelAnimationFrame(D[E])}):(p=function(E){return setTimeout(E,j)},C=function(E){return clearTimeout(E)}),{frame:p,cancel:C}}(),b=function(){var j,p,C={};function D(U){function E(H,R){U.postMessage({options:H||{},callback:R})}U.init=function(R){var M=R.transferControlToOffscreen();U.postMessage({canvas:M},[M])},U.fire=function(R,M,ue){if(p)return E(R,null),p;var xe=Math.random().toString(36).slice(2);return p=d(function(he){function je(we){we.data.callback===xe&&(delete C[xe],U.removeEventListener("message",je),p=null,m.clear(),ue(),he())}U.addEventListener("message",je),E(R,xe),C[xe]=je.bind(null,{data:{callback:xe}})}),p},U.reset=function(){U.postMessage({reset:!0});for(var R in C)C[R](),delete C[R]}}return function(){if(j)return j;if(!a&&i){var U=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
2
- `);try{j=new Worker(URL.createObjectURL(new Blob([U])))}catch(E){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",E),null}D(j)}return j}}(),x={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 y(j,p){return p?p(j):j}function A(j){return j!=null}function v(j,p,C){return y(j&&A(j[p])?j[p]:x[p],C)}function N(j){return j<0?0:Math.floor(j)}function P(j,p){return Math.floor(Math.random()*(p-j))+j}function L(j){return parseInt(j,16)}function S(j){return j.map(T)}function T(j){var p=String(j).replace(/[^0-9a-f]/gi,"");return p.length<6&&(p=p[0]+p[0]+p[1]+p[1]+p[2]+p[2]),{r:L(p.substring(0,2)),g:L(p.substring(2,4)),b:L(p.substring(4,6))}}function O(j){var p=v(j,"origin",Object);return p.x=v(p,"x",Number),p.y=v(p,"y",Number),p}function Y(j){j.width=document.documentElement.clientWidth,j.height=document.documentElement.clientHeight}function z(j){var p=j.getBoundingClientRect();j.width=p.width,j.height=p.height}function re(j){var p=document.createElement("canvas");return p.style.position="fixed",p.style.top="0px",p.style.left="0px",p.style.pointerEvents="none",p.style.zIndex=j,p}function W(j,p,C,D,U,E,H,R,M){j.save(),j.translate(p,C),j.rotate(E),j.scale(D,U),j.arc(0,0,1,H,R,M),j.restore()}function $(j){var p=j.angle*(Math.PI/180),C=j.spread*(Math.PI/180);return{x:j.x,y:j.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:j.startVelocity*.5+Math.random()*j.startVelocity,angle2D:-p+(.5*C-Math.random()*C),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:j.color,shape:j.shape,tick:0,totalTicks:j.ticks,decay:j.decay,drift:j.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:j.gravity*3,ovalScalar:.6,scalar:j.scalar,flat:j.flat}}function te(j,p){p.x+=Math.cos(p.angle2D)*p.velocity+p.drift,p.y+=Math.sin(p.angle2D)*p.velocity+p.gravity,p.velocity*=p.decay,p.flat?(p.wobble=0,p.wobbleX=p.x+10*p.scalar,p.wobbleY=p.y+10*p.scalar,p.tiltSin=0,p.tiltCos=0,p.random=1):(p.wobble+=p.wobbleSpeed,p.wobbleX=p.x+10*p.scalar*Math.cos(p.wobble),p.wobbleY=p.y+10*p.scalar*Math.sin(p.wobble),p.tiltAngle+=.1,p.tiltSin=Math.sin(p.tiltAngle),p.tiltCos=Math.cos(p.tiltAngle),p.random=Math.random()+2);var C=p.tick++/p.totalTicks,D=p.x+p.random*p.tiltCos,U=p.y+p.random*p.tiltSin,E=p.wobbleX+p.random*p.tiltCos,H=p.wobbleY+p.random*p.tiltSin;if(j.fillStyle="rgba("+p.color.r+", "+p.color.g+", "+p.color.b+", "+(1-C)+")",j.beginPath(),l&&p.shape.type==="path"&&typeof p.shape.path=="string"&&Array.isArray(p.shape.matrix))j.fill(oe(p.shape.path,p.shape.matrix,p.x,p.y,Math.abs(E-D)*.1,Math.abs(H-U)*.1,Math.PI/10*p.wobble));else if(p.shape.type==="bitmap"){var R=Math.PI/10*p.wobble,M=Math.abs(E-D)*.1,ue=Math.abs(H-U)*.1,xe=p.shape.bitmap.width*p.scalar,he=p.shape.bitmap.height*p.scalar,je=new DOMMatrix([Math.cos(R)*M,Math.sin(R)*M,-Math.sin(R)*ue,Math.cos(R)*ue,p.x,p.y]);je.multiplySelf(new DOMMatrix(p.shape.matrix));var we=j.createPattern(m.transform(p.shape.bitmap),"no-repeat");we.setTransform(je),j.globalAlpha=1-C,j.fillStyle=we,j.fillRect(p.x-xe/2,p.y-he/2,xe,he),j.globalAlpha=1}else if(p.shape==="circle")j.ellipse?j.ellipse(p.x,p.y,Math.abs(E-D)*p.ovalScalar,Math.abs(H-U)*p.ovalScalar,Math.PI/10*p.wobble,0,2*Math.PI):W(j,p.x,p.y,Math.abs(E-D)*p.ovalScalar,Math.abs(H-U)*p.ovalScalar,Math.PI/10*p.wobble,0,2*Math.PI);else if(p.shape==="star")for(var ie=Math.PI/2*3,Ne=4*p.scalar,Ie=8*p.scalar,k=p.x,le=p.y,Se=5,Ge=Math.PI/Se;Se--;)k=p.x+Math.cos(ie)*Ie,le=p.y+Math.sin(ie)*Ie,j.lineTo(k,le),ie+=Ge,k=p.x+Math.cos(ie)*Ne,le=p.y+Math.sin(ie)*Ne,j.lineTo(k,le),ie+=Ge;else j.moveTo(Math.floor(p.x),Math.floor(p.y)),j.lineTo(Math.floor(p.wobbleX),Math.floor(U)),j.lineTo(Math.floor(E),Math.floor(H)),j.lineTo(Math.floor(D),Math.floor(p.wobbleY));return j.closePath(),j.fill(),p.tick<p.totalTicks}function F(j,p,C,D,U){var E=p.slice(),H=j.getContext("2d"),R,M,ue=d(function(xe){function he(){R=M=null,H.clearRect(0,0,D.width,D.height),m.clear(),U(),xe()}function je(){a&&!(D.width===r.width&&D.height===r.height)&&(D.width=j.width=r.width,D.height=j.height=r.height),!D.width&&!D.height&&(C(j),D.width=j.width,D.height=j.height),H.clearRect(0,0,D.width,D.height),E=E.filter(function(we){return te(H,we)}),E.length?R=f.frame(je):he()}R=f.frame(je),M=he});return{addFettis:function(xe){return E=E.concat(xe),ue},canvas:j,promise:ue,reset:function(){R&&f.cancel(R),M&&M()}}}function ne(j,p){var C=!j,D=!!v(p||{},"resize"),U=!1,E=v(p,"disableForReducedMotion",Boolean),H=i&&!!v(p||{},"useWorker"),R=H?b():null,M=C?Y:z,ue=j&&R?!!j.__confetti_initialized:!1,xe=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,he;function je(ie,Ne,Ie){for(var k=v(ie,"particleCount",N),le=v(ie,"angle",Number),Se=v(ie,"spread",Number),Ge=v(ie,"startVelocity",Number),Xt=v(ie,"decay",Number),I=v(ie,"gravity",Number),be=v(ie,"drift",Number),Be=v(ie,"colors",S),Te=v(ie,"ticks",Number),_e=v(ie,"shapes"),Re=v(ie,"scalar"),at=!!v(ie,"flat"),Zt=O(ie),es=k,bs=[],Oa=j.width*Zt.x,Ra=j.height*Zt.y;es--;)bs.push($({x:Oa,y:Ra,angle:le,spread:Se,startVelocity:Ge,color:Be[es%Be.length],shape:_e[P(0,_e.length)],ticks:Te,decay:Xt,gravity:I,drift:be,scalar:Re,flat:at}));return he?he.addFettis(bs):(he=F(j,bs,M,Ne,Ie),he.promise)}function we(ie){var Ne=E||v(ie,"disableForReducedMotion",Boolean),Ie=v(ie,"zIndex",Number);if(Ne&&xe)return d(function(Ge){Ge()});C&&he?j=he.canvas:C&&!j&&(j=re(Ie),document.body.appendChild(j)),D&&!ue&&M(j);var k={width:j.width,height:j.height};R&&!ue&&R.init(j),ue=!0,R&&(j.__confetti_initialized=!0);function le(){if(R){var Ge={getBoundingClientRect:function(){if(!C)return j.getBoundingClientRect()}};M(Ge),R.postMessage({resize:{width:Ge.width,height:Ge.height}});return}k.width=k.height=null}function Se(){he=null,D&&(U=!1,s.removeEventListener("resize",le)),C&&j&&(document.body.contains(j)&&document.body.removeChild(j),j=null,ue=!1)}return D&&!U&&(U=!0,s.addEventListener("resize",le,!1)),R?R.fire(ie,k,Se):je(ie,k,Se)}return we.reset=function(){R&&R.reset(),he&&he.reset()},we}var B;function q(){return B||(B=ne(null,{useWorker:!0,resize:!0})),B}function oe(j,p,C,D,U,E,H){var R=new Path2D(j),M=new Path2D;M.addPath(R,new DOMMatrix(p));var ue=new Path2D;return ue.addPath(M,new DOMMatrix([Math.cos(H)*U,Math.sin(H)*U,-Math.sin(H)*E,Math.cos(H)*E,C,D])),ue}function ce(j){if(!l)throw new Error("path confetti are not supported in this browser");var p,C;typeof j=="string"?p=j:(p=j.path,C=j.matrix);var D=new Path2D(p),U=document.createElement("canvas"),E=U.getContext("2d");if(!C){for(var H=1e3,R=H,M=H,ue=0,xe=0,he,je,we=0;we<H;we+=2)for(var ie=0;ie<H;ie+=2)E.isPointInPath(D,we,ie,"nonzero")&&(R=Math.min(R,we),M=Math.min(M,ie),ue=Math.max(ue,we),xe=Math.max(xe,ie));he=ue-R,je=xe-M;var Ne=10,Ie=Math.min(Ne/he,Ne/je);C=[Ie,0,0,Ie,-Math.round(he/2+R)*Ie,-Math.round(je/2+M)*Ie]}return{type:"path",path:p,matrix:C}}function V(j){var p,C=1,D="#000000",U='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof j=="string"?p=j:(p=j.text,C="scalar"in j?j.scalar:C,U="fontFamily"in j?j.fontFamily:U,D="color"in j?j.color:D);var E=10*C,H=""+E+"px "+U,R=new OffscreenCanvas(E,E),M=R.getContext("2d");M.font=H;var ue=M.measureText(p),xe=Math.ceil(ue.actualBoundingBoxRight+ue.actualBoundingBoxLeft),he=Math.ceil(ue.actualBoundingBoxAscent+ue.actualBoundingBoxDescent),je=2,we=ue.actualBoundingBoxLeft+je,ie=ue.actualBoundingBoxAscent+je;xe+=je+je,he+=je+je,R=new OffscreenCanvas(xe,he),M=R.getContext("2d"),M.font=H,M.fillStyle=D,M.fillText(p,we,ie);var Ne=1/C;return{type:"bitmap",bitmap:R.transferToImageBitmap(),matrix:[Ne,0,0,Ne,-xe*Ne/2,-he*Ne/2]}}n.exports=function(){return q().apply(this,arguments)},n.exports.reset=function(){q().reset()},n.exports.create=ne,n.exports.shapeFromPath=ce,n.exports.shapeFromText=V})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),zs,!1);const Er=zs.exports;zs.exports.create;const wr={particleCount:350,spread:120,origin:{y:.6},angle:90},Nr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},It=e=>{let s=Nr[e];s||(s={});const n={...wr,...s};Er(n)},Ar=()=>{const[e]=J.useTheme(),{mutate:s,isPending:n}=qs(),{mutateAsync:a,isPending:r}=An(),i=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{It("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(c.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},Cr=({page:e,onClose:s})=>{const[n,a]=g.useState(e.slug||""),{mutate:r,isPending:i}=Sr(),{data:l}=Ce(),o=h.find(l,{key:e==null?void 0:e.pageType}),u=m=>{if(m.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Le).some(x=>n===`/${x}`||h.startsWith(n,`/${x}/`))){K.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(w.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:m=>{const f=m.target.value;h.startsWith(f,`/${d}`)&&a(f)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!h.startsWith(n,`/${d}`)||h.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})};function $s({page:e,onClose:s}){const[,n]=ke(),{mutate:a,isPending:r}=yr(),{data:i}=Ce(),{setSelectedLang:l,fallbackLang:o}=J.useLanguages(),[,u]=J.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(o),u("outline"),s()}})},m=i==null?void 0:i.find(f=>f.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",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(Le,e.lang,e.lang)})]})]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:r,onClick:d,children:r?"Deleting...":"Delete"})]})]})})}const Oe=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=J.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},xs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=jr(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[se.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:r,children:a?se.UPDATING:se.UNPUBLISH})]})]})})},Tr=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}},Ye=e=>{if(!e)return e;const{base:s}=Tr(e);return s},Pr=e=>e&&Ye(e),sn=(e,s)=>{const n=Ye(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function Vs({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[o,u]=g.useState(e),[d,m]=g.useState(null);g.useEffect(()=>{u(e)},[e]);const f=b=>{const y=b.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),A=(y.match(/\./g)||[]).length,v=A<=1;A>1?m("Invalid slug. Only one dot (.) is allowed in the slug"):m(null),r&&r(v),u(y),s(y)};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:Pr(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:o,onChange:f,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:d})]}),l&&t.jsx("div",{className:"flex items-center mt-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const Ln=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Me(),{data:r}=Ce(),[i,l]=g.useState(e.name||""),[o,u]=g.useState(e.edit?e.lang:""),[d,m]=g.useState(e.edit?e.slug:""),[f,b]=g.useState(!0),[x,y]=g.useState(!0),{mutate:A,isPending:v}=_n(),{mutate:N,isPending:P}=Fs(),{data:L}=Ve(a==null?void 0:a.parent),{setSelectedLang:S,fallbackLang:T}=J.useLanguages(),[,O]=ke(),[,Y]=J.useSidebarActivePanel(),z=g.useMemo(()=>r==null?void 0:r.find(V=>V.key===e.pageType),[r,e.pageType]),re=!(z!=null&&z.hasSlug),W=(a==null?void 0:a.slug)==="/",$=v||P,{parentSlug:te,isRootPage:F}=g.useMemo(()=>{if(W||!o)return{parentSlug:void 0,isRootPage:!(a!=null&&a.parent)};if(!(a!=null&&a.parent))return{parentSlug:x?`/${o}`:void 0,isRootPage:!(a!=null&&a.parent)};const V=L==null?void 0:L.find(j=>j.lang===o);return{parentSlug:V==null?void 0:V.slug,isRootPage:!1}},[a==null?void 0:a.parent,L,x,o,W]);g.useEffect(()=>{if(!e.edit)return;const j=(e.slug||"").split("/").filter(Boolean);let p="";const C=D=>y(D);if(W){const D=j.pop()||"";if(Le[D])C(!0);else{p=D;const U=j.pop()||"";C(!!Le[U])}}else if(F){if(j.length){p=j.pop()||"";const D=j.pop()||"";C(!!Le[D])}}else j.length&&(p=j.pop()||"");m(p)},[e,W,F]);const ne=g.useMemo(()=>F?!0:!!(L!=null&&L.find(V=>(V==null?void 0:V.lang)===o)),[o,L,F]),B=()=>{let V="";return F?V=`/${x?[o,d].filter(Boolean).join("/"):d}`:V=`${Ye(te)}/${d}`,V.replace(/\/{2,}/g,"/")},q=(V,j)=>{const p=new URLSearchParams(window.location.search);j&&V===j?p.delete("lang"):p.set("lang",V);const C=p.toString(),D=`${window.location.pathname}${C?`?${C}`:""}`;window.history.pushState({},"",D),O(p),window.dispatchEvent(new PopStateEvent("popstate"))},oe=V=>{V.preventDefault();const j={name:i,lang:o,primaryPage:a==null?void 0:a.id,slug:B(),pageType:a==null?void 0:a.pageType,tracking:{}};j.pageType=e.pageType,e.edit&&(j.id=e==null?void 0:e.id),e.edit?N(j,{onSuccess:s}):A(j,{onSuccess:()=>{o&&(S(o),q(o,T)),Y("outline"),s()}})},ce=$||h.isEmpty(i)||h.isEmpty(o)||(re||W&&x?!1:!f||h.isEmpty(d));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:e.edit?se.EDIT_LANGUAGE:se.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:se.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:oe,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",className:"text-right",children:se.LANGUAGE}),t.jsxs("select",{value:o,disabled:e.edit||h.isEmpty(n),onChange:V=>{const j=V.target.value;u(j),!e.edit&&h.startsWith(i,e.name)&&l(`${e.name} - ${Le[j]}`)},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(Le,e.lang,e.lang):h.isEmpty(n)?se.ALL_AVAILABLE_LANGUAGE_PAGE:se.CHOOSE_LANGUAGE}),h.map(n,V=>t.jsx("option",{value:V,children:h.get(Le,V,V)},V))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-right",children:se.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:o?i:"",onChange:V=>l(V.target.value),className:"col-span-3",required:!0,placeholder:o?se.ENTER_PAGE_NAME:se.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!ne||!o})]}),!re&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"space-y-1",children:[F&&o&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:x,onChange:V=>y(V.target.checked),className:"rounded border-gray-300"}),t.jsxs(c.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",o]}),") as slug prefix"]})]}),t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:[se.SLUG," "]}),t.jsx(Vs,{disabled:h.isEmpty(o)||!ne,value:d,onChange:m,placeholder:h.isEmpty(o)?se.CHOOSE_LANGUAGE_TO_ADD_SLUG:W&&x?"Leave empty for home page":se.ENTER_PAGE_SLUG,parentSlug:te,onValidationChange:b,fullSlug:ce?"":B()})]})})]}),t.jsx(c.DialogFooter,{children:ne?t.jsx(c.Button,{type:"submit",disabled:ce,children:$?e.edit?se.UPDATING:se.ADDING:e.edit?se.UPDATE:se.ADD_NEW_LANGUAGE}):o&&t.jsx(c.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:Le[o]})," page in the parent to add here."]})})})]})]})})},kr=()=>{const[e,s]=g.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:r}=J.useLanguages(),{data:i,isFetching:l}=Ve(),{data:o}=Me(),[u,d]=g.useState(null),[m,f]=g.useState(null),[b,x]=g.useState(null),{data:y}=Ze(),A=h.filter(h.get(y,"languages")||["en"],v=>!h.find(i,{lang:v})&&v!==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,v=>{const N=v.lang,P=v.slug,L=!v.primaryPage,S=N===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 ${S?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>r(N),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 ${v.online?"bg-green-300":"bg-gray-300"}`}),h.get(Le,L?a:N,N)]}),t.jsxs("div",{children:[P&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium",children:P})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",v.name," "]})]})]})]}),L?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(w.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(Oe,{permissions:[ye.EDIT_PAGE,ye.DELETE_PAGE,ye.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:T=>T.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(w.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[t.jsx(Oe,{permissions:[ye.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:T=>{T.stopPropagation(),s({...v,edit:!0})},children:[t.jsx(w.PencilIcon,{className:"size-3"}),se.EDIT]})}),t.jsx(Oe,{permissions:[ye.UNPUBLISH_PAGE],children:(v==null?void 0:v.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:T=>{T.stopPropagation(),f(v)},children:[t.jsx(w.Power,{className:"size-3"}),se.UNPUBLISH]})}),t.jsx(Oe,{permissions:[ye.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:T=>{T.stopPropagation(),d(v)},children:[t.jsx(w.TrashIcon,{className:"size-3"}),se.DELETE]})})]})]})})})]},v.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Oe,{permissions:[ye.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:h.isEmpty(A),onClick:()=>{s({name:o==null?void 0:o.name,pageType:o==null?void 0:o.pageType,lang:"",slug:"",edit:!1})},children:se.ADD_NEW_LANGUAGE})})}),e&&t.jsx(Ln,{languages:A,langProps:e,onClose:()=>s(null)}),u&&t.jsx($s,{page:u,onClose:()=>d(null)}),m&&t.jsx(xs,{page:m,onClose:()=>f(null)}),b&&t.jsx(Cr,{page:b,onClose:()=>x(null)})]})};function Ir({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=g.useState(null),o=g.useRef(null),[u,d]=g.useState(a+e);g.useEffect(()=>{d(a+e)},[e,a]);const m=x=>{const y=x.target.value;if(!y.startsWith(a)){const S=y.replace(a,""),T=a+S;d(T),s(S);return}const v=y.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),N=(v.match(/\./g)||[]).length,P=N<=1;N>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(P);const L=a+v;d(L),s(v)},f=()=>{if(o.current){const x=o.current;setTimeout(()=>{const y=a.length;x.setSelectionRange(y,y)},0)}},b=x=>{const y=x.currentTarget;(y.selectionStart||0)<=a.length&&setTimeout(()=>{const v=a.length;y.setSelectionRange(v,v)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:o,value:u,onChange:m,onFocus:f,onClick:b,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}function _r({pages:e,selectedParentId:s,onChange:n,className:a="w-full rounded-md border border-gray-300 px-3 py-2",id:r="parentPage"}){const i=g.useMemo(()=>!e||e.length===0?[]:e.filter(m=>!h.isEmpty(m.slug)).filter(m=>m.slug!=="/").sort((m,f)=>m.slug.localeCompare(f.slug)),[e]),l=d=>Math.max(0,(d.match(/\//g)||[]).length-1),o=d=>"    ".repeat(d),u=d=>{if(d==="/")return"/";const m=d.split("/").filter(Boolean);if(m.length<=1){const x=m[0]||"";return`/${Ye(x)}`}const f=m[m.length-1];return`/${Ye(f)}`};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),t.jsxs("select",{id:r,value:s||"none",onChange:d=>n(d.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),i.map(d=>{const m=l(d.slug),f=m>0?o(m):"",b=u(d.slug);return t.jsxs("option",{value:d.id,children:[f,d.name," (",b,")"]},d.id)})]})]})}const Lr=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=g.useState("");if(g.useEffect(()=>{if(s){const o=e.find(u=>u.id===s);i((o==null?void 0:o.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex items-center justify-center h-fit text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const l={};return e.forEach(o=>{const u=o.libraryName;l[u]||(l[u]=[]),l[u].push(o)}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:o=>n(o.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(l).map(([o,u])=>t.jsx("optgroup",{label:o,children:u.map(d=>t.jsx("option",{value:d.id,children:h.startCase(d.name)},d.id))},o))]}),r&&t.jsxs("div",{className:"mt-3 border rounded overflow-hidden",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:"p-2 text-xs text-gray-500 bg-gray-50 border-t",children:"Template preview"})]})]})},Dr=()=>{const e=ae(),s=X();return G.useQuery({queryKey:[Q,_.GET_LIBRARIES],queryFn:async()=>await s(e,{action:_.GET_LIBRARIES})||[]})},Mr=e=>{const s=ae(),n=X();return G.useQuery({queryKey:[Q,_.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)||[]}})},Br=e=>{const{data:s=[],isLoading:n}=Mr(e),{data:a=[],isLoading:r}=Dr(),i=g.useMemo(()=>n||r?[]:s.map(o=>{const u=h.find(a,{id:o.library});return{...o,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=g.useMemo(()=>h.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},Hs=()=>{const[,e]=ke();return g.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},is=(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}};function Gr({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var Ge,Xt;const r=Hs(),i=!!(e!=null&&e.id),{data:l}=Yt(),{mutate:o,isPending:u}=_n(),{mutate:d,isPending:m}=Fs(),[f,b]=g.useState(null),[x,y]=g.useState(!0),[A,v]=g.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:N}=J.usePermissions(),P=N(ye.CHANGE_PAGE_TYPE),[L,S]=g.useState(!1),[T,O]=g.useState(""),{selectedLang:Y,fallbackLang:z}=J.useLanguages(),re=Y||z,W=g.useMemo(()=>{const I=s.find(be=>be.key===A);return(I==null?void 0:I.hasSlug)===!1},[A,s]),[$,te]=g.useState((e==null?void 0:e.parent)??""),[F,ne]=g.useState((e==null?void 0:e.name)??""),[B,q]=g.useState((e==null?void 0:e.dynamic)??!1),[oe,ce]=g.useState(B?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[V,j]=g.useState((e==null?void 0:e.dynamicSlugCustom)??""),[p,C]=g.useState(!0),[D,U]=g.useState(""),{data:E,isLoading:H}=Br(A),R=u||m,M=s.find(I=>I.key===A),ue=I=>{if(i&&A!==I){O(I),S(!0);return}v(I)},xe=()=>{v(T),S(!1),q(!1)},he=I=>{q(I),I?ce(""):j("")},je=I=>{if(te(I),I&&I!=="none"){const be=l==null?void 0:l.find(Te=>Te.id===I),Be=(be==null?void 0:be.slug)||"";if(oe.startsWith(Be)){const Te=oe.slice(Be.length).replace(/^\/+/,"");ce(Te)}else ce(oe.replace(/^\/+/,""))}else ce(oe?`${oe}`:"")},we=I=>{U(I)},ie=()=>F.trim()?B&&!h.isEmpty(oe)?(b("Slug must be empty when using dynamic slug"),!1):B&&!p?(b("Dynamic slug is invalid"),!1):!0:(K.toast.error("Name is required"),!1),Ne=()=>{const I={pageType:M==null?void 0:M.key,name:F,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:F},{onSuccess:()=>{K.toast.success((M==null?void 0:M.name)+" updated successfully"),n()}}):o(I,{onSuccess:be=>{n(),r(be.page.id,a)}})},Ie=(I,be)=>{if(!I.trim()&&!B)return b("Child page slug is required"),!1;const Be=Ye(be),Te=sn(Be,I);return Object.keys(Le).some(at=>Te===`/${at}`||(Te==null?void 0:Te.startsWith(`/${at}/`)))?(b("Slugs cannot start with a language code for primary page"),!1):!0},k=(I,be)=>{const Be=Ye(be),Te=sn(Be,I),_e={pageType:A,name:F,slug:Te.replace(/\/$/,""),parent:$,dynamic:B,hasSlug:!0,template:D||void 0,tracking:{},seo:{},jsonLD:{}};if(B&&(_e.dynamicSlugCustom=V),i)d({id:e==null?void 0:e.id,..._e},{onSuccess:()=>{K.toast.success("Page updated successfully"),n()}});else{const Re=h.find(s,{key:A});Re!=null&&Re.trackingDefault&&(_e.tracking=Re.trackingDefault);const{seo:at,jsonLD:Zt}=is(Re,re);h.set(_e,"seo",at),h.set(_e,"jsonLD",Zt),o(_e,{onSuccess:es=>{n(),r(es.page.id,a)}})}},le=()=>{const I={pageType:A,name:F,slug:oe===""?"/":`/${oe.replace(/\/$/,"")}`,template:D||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...I},{onSuccess:()=>{K.toast.success("Page updated successfully"),n()}});else{const be=h.find(s,{key:A});be!=null&&be.trackingDefault&&(I.tracking=be.trackingDefault);const{seo:Be,jsonLD:Te}=is(be,re);h.set(I,"seo",Be),h.set(I,"jsonLD",Te),o(I,{onSuccess:_e=>{var Re;(Re=_e==null?void 0:_e.page)!=null&&Re.id&&r(_e.page.id,a),n()}})}},Se=I=>{if(I.preventDefault(),b(null),!!ie()){if(!(M!=null&&M.hasSlug)){Ne();return}if($&&$!=="none"){const be=l==null?void 0:l.find(Te=>Te.id===$),Be=(be==null?void 0:be.slug)||"";if(!Ie(oe,Be))return;k(oe,Be)}else le()}};return i&&!(M!=null&&M.hasSlug)?t.jsxs("form",{onSubmit:Se,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:A,disabled:i&&!P,onChange:I=>ue(I.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!P?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(I=>I.hasSlug===!1).map(I=>t.jsx("option",{value:I.key,children:I.name},I.key))})}),L&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:xe,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(Ge=s.find(I=>I.key===A))==null?void 0:Ge.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:F,onChange:I=>ne(I.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:R,type:"submit",className:"w-full",children:i?R?"Updating...":"Update "+(M==null?void 0:M.name):R?"Creating...":"Create "+(M==null?void 0:M.name)})]}):t.jsxs("form",{onSubmit:Se,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:A,disabled:i&&!P,onChange:I=>ue(I.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!P?"cursor-not-allowed text-gray-500":""}`,children:i?W?t.jsx("optgroup",{label:"Partials",children:s.filter(I=>I.hasSlug===!1).map(I=>t.jsx("option",{value:I.key,children:I.name},I.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(I=>I.hasSlug!==!1).map(I=>t.jsx("option",{value:I.key,children:I.name},I.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(I=>I.hasSlug!==!1).map(I=>t.jsx("option",{value:I.key,children:I.name},I.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(I=>I.hasSlug===!1).map(I=>t.jsx("option",{value:I.key,children:I.name},I.key))})]})}),L&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:xe,children:"Confirm"})]})]})]}),!i&&(M==null?void 0:M.hasSlug)&&E.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(Lr,{templates:E,selectedTemplateId:D,onSelectTemplate:we,isLoading:H})]}),t.jsx(_r,{pages:l,selectedParentId:$,onChange:je}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:F,onChange:I=>ne(I.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(M==null?void 0:M.dynamicSegments)&&$&&$!=="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:B,onChange:I=>he(I.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),B&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(Ir,{value:V,onChange:j,dynamicPattern:(M==null?void 0:M.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:C})})})]}),(!(M!=null&&M.dynamicSegments)||!B)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Vs,{value:oe,onChange:ce,placeholder:$&&$!=="none"?"Enter page slug":A==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:$&&$!=="none"?(Xt=l==null?void 0:l.find(I=>I.id===$))==null?void 0:Xt.slug:void 0,onValidationChange:y}),f&&t.jsx("p",{className:"text-xs text-red-500",children:f})]}),t.jsx(c.Button,{disabled:R||!x&&(!(M!=null&&M.dynamicSegments)||!B)||B&&!p,type:"submit",className:"w-full",children:i?R?"Updating...":"Update page":R?"Creating...":"Create Page"})]})}const Dn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Ce(),r=!!(e!=null&&e.id);return t.jsx(c.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsxs(c.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(c.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(Gr,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},Or=()=>{const e=ae(),s=G.useQueryClient(),n=X();return G.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:[Q,_.GET_WEBSITE_PAGES]}),K.toast.success("Page duplicated successfully")},onError:a=>{K.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Mn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Or(),[r,i]=g.useState(null),[l,o]=g.useState(`${e.name} (Copy)`),u=h.isEmpty(e.slug),[d,m]=g.useState(u?"":`${e.slug.split("/").pop()}-copy`),f=u?"":h.initial(e.slug.split("/")).join("/"),[b,x]=g.useState(!1),y=A=>{if(A.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),x(!0);const v={pageId:e.id,name:l};u||(v.slug=`${f}/${d}`),n(v,{onSuccess:()=>{x(!1),s()},onError:N=>{x(!1),N.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):N.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):N.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(N.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Duplicate Page"}),t.jsx(c.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!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:y,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:A=>o(A.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Vs,{value:d,onChange:A=>m(A),parentSlug:f,onValidationChange:A=>{i(A?null:"Invalid slug")}})]}),r&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(w.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(c.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||b,children:a||b?"Duplicating...":"Duplicate"})]})]})]})})},Rr=1*1024*1024,Bn=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),[l,o]=g.useState(""),[u,d]=g.useState(!1),m=g.useRef(null),f=vr(),{data:b}=Ce(),x=b==null?void 0:b.find(L=>L.key===e.pageType),y=(x==null?void 0:x.name)||h.startCase(e.pageType),A=g.useCallback(L=>{var T;const S=(T=L.target.files)==null?void 0:T[0];if(S){if(S.size>Rr){K.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(S.size/1024).toFixed(2)}KB.`}),m.current&&(m.current.value="");return}try{d(!0);const O=new FileReader;O.onloadend=()=>{o(O.result),d(!1)},O.readAsDataURL(S)}catch(O){console.error("Error reading file:",O),d(!1),K.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),v=()=>{o(""),m.current&&(m.current.value="")},N=()=>{var L;(L=m.current)==null||L.click()},P=()=>{a(!0),f.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(w.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(w.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:y})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:L=>i(L.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:m,onChange:A,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:N,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(w.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:v,children:t.jsx(w.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:L=>{L.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:P,children:"Mark as template"})]})]})})},Gn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:o})=>{const{hasPermission:u}=J.usePermissions(),{data:d}=Ce(),m=g.useMemo(()=>h.find(d,{key:e.pageType}),[d,e.pageType]),f=g.useMemo(()=>!!e.isTemplate,[e.isTemplate]),b=g.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!u(ye.EDIT_PAGE)&&!u(ye.DELETE_PAGE)&&!u(ye.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:y=>y.stopPropagation(),children:o}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[u(ye.ADD_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:y=>{y.stopPropagation(),s(e)},children:[t.jsx(w.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),u(ye.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:y=>{y.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(w.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&u(ye.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:y=>{y.stopPropagation(),a(e)},children:[t.jsx(w.Power,{className:"size-3"}),se.UNPUBLISH]}),u(ye.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:y=>{y.stopPropagation(),r(e)},children:[t.jsx(w.Trash,{className:"size-3"}),se.DELETE]}),u(ye.MARK_AS_TEMPLATE)&&b&&t.jsx(t.Fragment,{children:f?t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:y=>{y.stopPropagation(),l(e)},children:[t.jsx(w.SquareLibrary,{className:"size-3"}),se.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:y=>{y.stopPropagation(),i(e)},children:[t.jsx(w.SquareLibrary,{className:"size-3"}),se.MARK_AS_TEMPLATE]})})]})]})},On=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),r=br(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Unmark as template"}),t.jsx(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},Ur=En("expandedPagesState",[]),Ks=e=>h.flatMap(e,s=>[s,...s.children?Ks(s.children):[]]),Fr=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const l=[...r,i.id];if(i.id===s)return l;if(i.children&&i.children.length>0){const o=n(i.children,l);if(o)return o}}return null};return n(e)||[]},Rn=(e,s)=>{if(!s)return[];const n=Ks(e),a=h.find(n,r=>r.id===s);if(a){if(a.parent)return[...Rn(e,a.parent),s];const r=Fr(e,s);if(!h.isEmpty(r))return r}return[s]},qr=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(o=>s.add(o)),i.children&&!h.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},Un=e=>{const[s,n]=qe.useAtom(Ur),a=e?h.includes(s,e):!1,r=g.useCallback(()=>{n(d=>a?h.filter(d,m=>m!==e):[...d,e])},[n,a,e]),i=g.useCallback((d,m)=>{if(!m||h.isEmpty(d))return;const f=Ks(d),b=Rn(f,m);if(!Array.isArray(b)||h.isEmpty(b))return;const x=b.slice(0,-1);h.isEmpty(x)||n(y=>h.uniq([...y,...x]))},[n]),l=g.useCallback(d=>{if(h.isEmpty(d))return;const m=qr(d);h.isEmpty(m)||n(f=>h.union(f,m))},[n]),o=g.useCallback(d=>{if(h.isEmpty(d))return;const m=h.flatMap(d,f=>{const b=x=>[x.id,...x.children?h.flatMap(x.children,b):[]];return b(f)});n(m)},[n]),u=g.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:o,collapseAll:u}},nn=(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)})),zr=(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])},As=(e,s,n)=>h.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?As(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?As(a.children,s,n):[]}}),$r=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},Fn=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Fn(n.children):[]})),Vr=(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=nn(r,s);else{const m=nn(r,s),f=zr(e,m);r=h.uniqBy([...m,...f],"id")}const i=Fn($r(r)),l=As(i,s,a),o=h.filter(l,m=>a(m.pageType)).sort((m,f)=>(m.name||"").localeCompare(f.name||"")),u=h.keyBy(h.filter(l,m=>!a(m.pageType)),"pageType"),d=Object.values(h.mapValues(u,(m,f)=>({...m,name:h.startCase(f),isPartialGroup:!0,children:l.filter(b=>b.pageType===f)})));return[...o,...d]},Hr=({currentEditor:e})=>{const{user:s}=ze(),{data:n}=st(e);return!n||!e||e===(s==null?void 0:s.id)?null:t.jsx("span",{className:"ml-2 text-xs font-light text-gray-500 flex items-center gap-1",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(w.LockIcon,{className:"w-3 h-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},Kr=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:m,isExpanded:f,onToggleExpand:b})=>{const x=Hs(),{data:y}=Ce(),[,A]=J.useSidebarActivePanel(),v=g.useMemo(()=>h.find(y,{key:s.pageType}),[y,s.pageType]),N=g.useMemo(()=>{const T=h.get(s,"slug",""),O=e?Ye(e):"",Y=O?T.replace(O,""):T;return Y||"/"},[s,e]),P=g.useMemo(()=>!!s.isTemplate,[s.isTemplate]),L=g.useCallback(()=>{A("outline"),x(h.get(s,"id"),a)},[x,a,s,A]),S=g.useCallback(T=>{T.stopPropagation(),b()},[b]);return t.jsxs("div",{onClick:L,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:S,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(w.ChevronRight,{size:16,className:`w-4 h-5 transition-transform duration-200 ${f?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(w.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):v!=null&&v.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:v.icon}}):v!=null&&v.hasSlug?t.jsx(w.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(w.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}),v!=null&&v.hasSlug?t.jsxs(c.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:[N,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[h.endsWith(N,"/")?`${v==null?void 0:v.dynamicSlug}`:`/${v==null?void 0:v.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(c.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:v==null?void 0:v.name}),P&&t.jsx(c.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(Hr,{currentEditor:s.currentEditor}),t.jsx(Gn,{page:s,setDuplicatePage:d,setAddEditPage:l,setUnpublishPage:r,setDeletePage:i,setMarkAsTemplate:o,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"p-0.5 m-0 hover:bg-white rounded duration-100 cursor-pointer",children:t.jsx(w.MoreHorizontal,{className:"w-4 h-4",onClick:T=>T.stopPropagation()})})})]})]})},Wr=({close:e,isOpen:s})=>{const[,n]=g.useState([]),[a,r]=g.useState(null),[i,l]=g.useState(""),[o,u]=g.useState(""),[d,m]=g.useState(null),f=E=>o?String(h.get(E,"name","")).toLowerCase().includes(o.toLowerCase())||String(h.get(E,"key","")).toLowerCase().includes(o.toLowerCase()):!0,[b,x]=g.useState(null),[y,A]=g.useState(null),[v,N]=g.useState(null),[P,L]=g.useState(null),{data:S,isFetching:T,refetch:O}=Yt(),[Y,z]=g.useState(""),{hasPermission:re}=J.usePermissions(),{updateForSelectedPage:W,expandPagesOnSearch:$,expandAll:te,collapseAll:F}=Un(null),[ne,B]=ke(),q=ne.get("page"),oe=g.useRef(null),{data:ce}=Ce(),V=g.useCallback(E=>{var H;return(H=h.find(ce,{key:E}))==null?void 0:H.hasSlug},[ce]);g.useEffect(()=>{s&&O()},[s,O]),g.useEffect(()=>{if(!h.isEmpty(Y))return;const E=sessionStorage.getItem("pageTypeFilter")||"all";!h.isEmpty(ce)&&E&&(h.find(ce,{key:E})?z(E):z("all"))},[ce,Y]);const j=E=>{z(E),sessionStorage.setItem("pageTypeFilter",E),u("")},p=g.useCallback(E=>{const R=new URLSearchParams(window.location.search).get("lang"),M=new URLSearchParams({page:E});R&&M.set("lang",R),window.history.pushState({},"",`?${M.toString()}`),B(M),window.dispatchEvent(new PopStateEvent("popstate")),e()},[B,e]);g.useEffect(()=>{if(q&&!T){const E=h.find(S,{id:q});E&&(E!=null&&E.pageType)?n(H=>[...H,E==null?void 0:E.pageType]):(window.history.replaceState(null,"","/"),B(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[S,q,T,B]);const C=g.useMemo(()=>S?Vr(S,i,Y,V):[],[S,i,Y,V]);g.useEffect(()=>{q&&!T&&!h.isEmpty(C)&&(W(C,q),oe.current&&oe.current.scrollIntoView({behavior:"smooth",block:"end"}))},[q,T,C,W]),g.useEffect(()=>{!h.isEmpty(i)&&!h.isEmpty(C)&&$(C)},[i,C,$]);const D=g.useCallback(()=>{te(C)},[te,C]),U=g.useCallback(()=>{F()},[F]);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(w.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:i,onChange:E=>l(E.target.value)}),!h.isEmpty(Y)&&t.jsxs(c.Select,{value:Y,onValueChange:j,children:[t.jsx(c.SelectTrigger,{className:`${Y==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} min-w-[120px] h-max p-0 py-1 pl-2 pr-1 top-1.5 -mt-px absolute text-gray-600 right-1.5 w-max text-xs whitespace-nowrap ring-0 focus:ring-0 shadow-none`,children:t.jsx(c.SelectValue,{placeholder:"Select page type"})}),t.jsxs(c.SelectContent,{align:"end",children:[t.jsx("div",{className:"px-3 py-2 sticky top-0 bg-white z-10",children:t.jsxs("div",{className:"relative",children:[t.jsx(w.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"pl-8 h-8 text-xs",value:o,onChange:E=>u(E.target.value),onClick:E=>E.stopPropagation(),onKeyDown:E=>E.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!h.isEmpty(h.filter(ce,E=>E.hasSlug&&f(E)))&&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(ce,E=>E.hasSlug&&f(E))].sort((E,H)=>h.get(E,"name","").localeCompare(h.get(H,"name",""))),E=>t.jsx(c.SelectItem,{value:h.get(E,"key"),children:h.get(E,"name")},h.get(E,"key")))]}),!h.isEmpty(h.filter(ce,E=>!E.hasSlug&&f(E)))&&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(ce,E=>!E.hasSlug&&f(E))].sort((E,H)=>h.get(E,"name","").localeCompare(h.get(H,"name",""))),E=>t.jsx(c.SelectItem,{value:h.get(E,"key"),children:h.get(E,"name")},h.get(E,"key")))]}),h.isEmpty(h.filter(ce,f))&&t.jsx("div",{className:"px-3 py-2 text-sm text-gray-500 text-center",children:"No matching page types found"})]})]})]}),t.jsxs("div",{className:"flex gap-1 ",children:[t.jsx(c.Button,{variant:"outline",size:"icon",onClick:D,className:"p-1 ",children:t.jsx(w.ChevronsUpDown,{size:14})}),t.jsx(c.Button,{variant:"outline",size:"icon",onClick:U,className:"p-1 ",children:t.jsx(w.ChevronsDownUp,{size:14})})]})]}),T?t.jsx("div",{className:"space-y-2",children:h.map([...Array(5).keys()],E=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},E))}):h.isEmpty(C)?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(w.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(C,E=>{const H=E.id===q;return t.jsx("div",{ref:H?oe:null,children:t.jsx(qn,{item:E,currentPage:q,close:e,setUnpublishPage:x,setDeletePage:m,setAddEditPage:A,setMarkAsTemplate:N,setUnmarkAsTemplate:L,setDuplicatePage:r,level:0})},`page-item-${E.id}`)})})]}),re(ye.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex text-sm gap-x-2",onClick:()=>{A({slug:"",name:"",pageType:Y==="all"?"page":Y})},children:[t.jsx(w.Plus,{className:"w-4 h-4"})," Add New"]}),y&&t.jsx(Dn,{closePanel:e,editPage:p,addEditPage:y,setAddEditPage:A}),d&&t.jsx($s,{page:d,onClose:()=>m(null)}),b&&t.jsx(xs,{page:b,onClose:()=>x(null)}),v&&t.jsx(Bn,{page:v,onClose:()=>N(null)}),P&&t.jsx(On,{page:P,onClose:()=>L(null)}),a&&t.jsx(Mn,{page:a,onClose:()=>r(null)})]})},qn=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:d,level:m=0})=>{const f=!h.isEmpty(e==null?void 0:e.children),{isExpanded:b,toggleExpanded:x}=Un(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(Kr,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:f,isExpanded:b,onToggleExpand:x}),f&&b&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:h.map(h.get(e,"children",[]),y=>t.jsx(qn,{item:y,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:m+1},y.id||`child-${m}-${y.key}`))})]},e.id||`level-${m}-${e.key}`)},Qr=({page:e})=>{const[s,n]=g.useState(null),[a,r]=g.useState(null),[i,l]=g.useState(null),[o,u]=g.useState(null),[d,m]=g.useState(null),[f,b]=g.useState(null);return e?t.jsxs(t.Fragment,{children:[t.jsx(Gn,{page:e,setDuplicatePage:x=>m(x),setAddEditPage:x=>b(x),setUnpublishPage:x=>r(x),setDeletePage:x=>n(x),setMarkAsTemplate:x=>l(x),setUnmarkAsTemplate:x=>u(x),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(w.MoreHorizontal,{className:"w-4 h-4",onClick:x=>x.stopPropagation()})})}),f&&t.jsx(Dn,{closePanel:()=>b(null),editPage:()=>{},addEditPage:f,setAddEditPage:b}),s&&t.jsx($s,{page:s,onClose:()=>n(null)}),a&&t.jsx(xs,{page:a,onClose:()=>r(null)}),i&&t.jsx(Bn,{page:i,onClose:()=>l(null)}),o&&t.jsx(On,{page:o,onClose:()=>u(null)}),d&&t.jsx(Mn,{page:d,onClose:()=>m(null)})]}):null},Yr=()=>{const e=Xe("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:g.createElement(e,{})}):null},Jr=()=>{const[e]=ke(),s=e.get("page"),{data:n,isFetching:a}=Me(),[r,i]=g.useState(!1),{savePage:l}=J.useSavePage(),o=!!s&&!h.isEmpty(n),u=!s||!a&&h.isEmpty(n)||r;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"relative",children:[t.jsxs(c.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(w.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(w.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(Qr,{page:n})]}),t.jsx(c.Sheet,{open:u,onOpenChange:d=>!d&&o&&i(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`z-50 w-full !max-w-screen-md border-border ${o?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:"mb-3",children:[t.jsxs(c.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(w.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(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(Wr,{isOpen:u,close:()=>i(!1)})})]})})]})},zn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=J.useLanguages(),l=h.isEmpty(r)?n:r,[,o]=ke();g.useEffect(()=>{const v=new URLSearchParams(window.location.search),N=v.get("lang");N&&(a.includes(N)?i(N):(v.delete("lang"),o(v),i("")))},[a,o,i]);const[u,d]=g.useState(null),{data:m}=Me(),{data:f}=Ze(),{data:b,isFetching:x}=Ve(),y=g.useMemo(()=>{const v=h.compact(h.map(h.get(f,"languages"),N=>{const P=h.find(b,{lang:N});return{key:N,value:h.get(Le,N,N),isLangPageAdded:!!P}})).filter(Boolean);return[{key:n,value:h.get(Le,n),isLangPageAdded:!0},...v]},[n,b,f]),A=v=>{i(v);const N=new URLSearchParams(window.location.search);v===n?N.delete("lang"):N.set("lang",v);const P=N.toString(),L=`${window.location.pathname}${P?`?${P}`:""}`;window.history.pushState({},"",L),o(N),window.dispatchEvent(new PopStateEvent("popstate"))};return h.isEmpty(a)||x?null:t.jsxs(t.Fragment,{children:[t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{variant:s,size:"sm",className:"gap-2",children:[t.jsx(w.Languages,{className:"h-4 w-4"}),h.get(Le,l,l),t.jsx(w.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[h.map(y.filter(v=>v.isLangPageAdded),v=>t.jsxs(c.DropdownMenuItem,{className:J.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",v.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>A(v.key),children:[t.jsx("div",{className:"text-slate-600",children:v.value}),v.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(w.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},v.value)),e&&!h.isEmpty(y.filter(v=>!v.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.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(w.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]}),u&&t.jsx(Ln,{languages:a,langProps:u,onClose:()=>d(null)})]})};function Xr(){return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(Yr,{}),t.jsx(Jr,{})]})}function Zr(e){const s=ae(),n=X();return G.useQuery({queryKey:[Q,"revisions",e],queryFn:async()=>await n(s,{action:_.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const ei=()=>{const e=ae(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async a=>await s(e,{action:_.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,"revisions"]})}})},ti=()=>{const e=ae(),s=X(),n=G.useQueryClient();return G.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:_.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,"revisions"]})}})};function si(){const{data:e}=Me(),{saveState:s}=J.useSavePage(),[n]=ps();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"," ",wt.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(w.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(w.Save,{className:"h-3 w-3"}),t.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function ni(){const[e,s]=ve.useState(!1),[n,a]=ve.useState(null),[r,i]=ve.useState(!1),[l,o]=ve.useState(!1),{data:u}=Me(),{data:d,isFetching:m,error:f,refetch:b}=Zr(u==null?void 0:u.id),{mutate:x,isPending:y}=ei(),{mutate:A,isPending:v}=ti(),N=G.useQueryClient(),P=O=>{n&&A({revisionId:n.uid,discardCurrent:O},{onSuccess:()=>{i(!1),a(null),N.invalidateQueries({queryKey:[Q,_.GET_DRAFT_PAGE]})}})},L=O=>{a(O),i(!0)},S=O=>{a(O),o(!0)},T=()=>{n&&x(n.uid,{onSuccess:()=>{o(!1),a(null)}})};return g.useEffect(()=>{e&&b()},[e,b]),t.jsxs(t.Fragment,{children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:e,onOpenChange:s,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(w.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(c.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(c.SheetHeader,{className:"pb-2",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(w.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"," ",wt.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(c.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:m?t.jsx(ai,{}):f?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 space-y-2",children:[t.jsx(si,{}),d==null?void 0:d.map(O=>t.jsx(ri,{revision:O,isLatest:O.uid==="current",onRestore:()=>L(O),onDelete:()=>S(O)},O.uid))]})})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(li,{open:r,onOpenChange:i,revision:n,onRestore:P,isRestoring:v}),t.jsx(oi,{open:l,onOpenChange:o,revision:n,onDelete:T,isDeleting:y})]})}function ai(){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(c.Skeleton,{className:"h-4 w-3/4"}),t.jsx(c.Skeleton,{className:"h-3 w-1/2"}),t.jsx(c.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function ri({revision:e,isLatest:s,onRestore:n,onDelete:a}){const{data:r}=st(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:wt.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(w.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(w.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(Oe,{permissions:[ye.RESTORE_REVISION,ye.DELETE_REVISION],children:e.uid!=="current"&&t.jsx(ii,{revision:e,onRestore:n,onDelete:a})})]})}function ii({revision:e,onRestore:s,onDelete:n}){return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(w.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Oe,{permission:ye.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(w.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Oe,{permission:ye.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(c.DropdownMenuSeparator,{}),t.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(w.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function li({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=st((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Restore Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",wt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(w.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(w.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function oi({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=st((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",wt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(w.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const ci=()=>{const e=ae(),s=X();return G.useQuery({queryKey:[Q,_.GET_CHANGES],queryFn:async()=>s(e,{action:_.GET_CHANGES})})},ui=({currentEditor:e})=>{const{data:s}=st(e);return s==null?void 0:s.name};function di({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=g.useState([]),{data:r,isFetching:i}=ci(),{data:l}=Ce(),o=g.useCallback(S=>{var T;return(T=h.find(l,{key:S}))==null?void 0:T.hasSlug},[l]),u=g.useMemo(()=>h.filter(l,S=>!o(S.key)).map(S=>S.key),[o,l]),d=g.useMemo(()=>h.filter(r,S=>!u.includes(S.pageType)),[r,u]),m=g.useMemo(()=>h.filter(r,S=>u.includes(S.pageType)),[r,u]),f=g.useMemo(()=>h.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:b,isPending:x}=qs();g.useEffect(()=>{const S=h.map(h.filter(r,{online:!0}),"id");f&&S.push(f==null?void 0:f.id),a(S)},[r,f]);const y=n.length===(r==null?void 0:r.length),A=S=>{a(T=>h.includes(T,S)?h.filter(T,O=>O!==S):h.concat(T,S))},v=()=>{a(y?[]:h.map(r,"id"))},N=()=>{b({ids:h.uniq(n)},{onSuccess:()=>{s(),It("CENTER_CENTER")}})},P=S=>{if(S==="theme")return"Theme";const T=h.find(l,{key:S});return T?T==null?void 0:T.name:S},L=g.useMemo(()=>{const S=[{label:"Updated",top:"pt-2"},...h.orderBy(h.filter(d,{online:!0}),"pageType"),...h.orderBy(h.filter(m,{online:!0}),"pageType")].filter(Y=>Y.pageType!=="theme"),T=[{label:"Offline",top:"pt-6"},...h.orderBy(h.filter(d,{online:!1}),"pageType"),...h.orderBy(h.filter(m,{online:!1}),"pageType")],O=f?[{label:"Theme",top:"pt-6"},f]:[];return[...S,...O,...T]},[d,m,f]);return t.jsx(c.Dialog,{open:e,onOpenChange:x?()=>{}:s,children:t.jsxs(c.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),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:y,onClick:S=>{S.stopPropagation(),v()},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(L,S=>S.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${S.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:S.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,S==null?void 0:S.id),onClick:T=>{T.stopPropagation(),A(S==null?void 0:S.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",o(S.pageType)?t.jsx(w.File,{className:"w-4 h-4"}):t.jsx(w.GlobeIcon,{className:"w-4 h-4"}),S.name,S.slug&&t.jsxs("span",{className:"text-xs text-gray-500",children:["(",S.slug,")"]}),S.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(ui,{currentEditor:S.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:S.lang}),t.jsx("td",{className:"px-2",children:P(S==null?void 0:S.pageType)}),t.jsx("td",{className:"px-4 text-right",children:h.first(S.changes)||""})]},S==null?void 0:S.id))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10",children:[t.jsx(c.Button,{disabled:x,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:x||i||h.isEmpty(r),onClick:N,children:x?"Publishing...":"Publish"})]})]})})}const hi=()=>{const e=X(),s=ae();return G.useQuery({queryKey:[_.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_DATA,data:{draft:!0}})})};function mi({onClose:e}){const{data:s,isFetching:n}=hi(),{mutateAsync:a,isPending:r}=Ja(),i=Xe("settingComponent",null),l=h.debounce(async o=>(await a({data:o}),!0),300);return i?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:g.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function $n({children:e,content:s}){return t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:e}),t.jsx(c.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const fi=()=>{const{selectedLang:e,fallbackLang:s}=J.useLanguages(),n=Xe("getPreviewUrl",async f=>f),[a,r]=g.useState(""),{data:i}=Me(),{data:l}=Ve(),{data:o}=Ce(),u=g.useMemo(()=>{var f;return(f=l==null?void 0:l.find(b=>(b==null?void 0:b.lang)===e))==null?void 0:f.slug},[e,l]),d=g.useCallback(f=>{var b;return(b=h.find(o,{key:f}))==null?void 0:b.hasSlug},[o]),m=e===s?"":e;return g.useEffect(()=>{(async()=>{if(typeof n=="function"){const f=!d(i==null?void 0:i.pageType),b=await n(f?`${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(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(w.Eye,{className:"h-4 w-4"})," ",se.PREVIEW]})})})},gi=()=>{const[e,s]=J.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx($n,{content:se.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(w.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},pi=()=>{const[e,s]=g.useState(!1),{isLocked:n}=Jt(),{savePage:a,saveState:r}=J.useSavePage();g.useEffect(()=>{const m=f=>{r==="UNSAVED"&&(f.preventDefault(),f.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",m),()=>{window.removeEventListener("beforeunload",m)}},[r]);const i=g.useCallback(async()=>{s(!0),await a(!1)},[a]);g.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=g.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:o,buttonClass:u,tooltipContent:d}=g.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:se.SAVEDRAFT,buttonIcon:t.jsx(w.Save,{className:"h-4 w-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:se.SAVING,buttonIcon:t.jsx(w.Loader,{className:"h-4 w-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:se.SAVED,buttonIcon:t.jsx(w.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[o," ",d]})},xi=()=>{const{selectedLang:e}=J.useLanguages(),{data:s}=Nt(),{data:n}=Ve(),[a,r]=g.useState(!1),[i,l]=g.useState(!1),[o,u]=g.useState(null),{data:d}=Me(),{mutate:m,isPending:f}=qs(),{buttonText:b,buttonClassName:x,isPublished:y}=g.useMemo(()=>{const N=d&&(d==null?void 0:d.online);return{buttonClassName:N?"hover:bg-green-600 bg-green-500":"",isPublished:N,buttonText:N?se.PUBLISHED:se.PUBLISH}},[d]),A=async()=>{const N=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];m({ids:h.compact(N)},{onSuccess:()=>It("TOP_RIGHT")})},v=g.useMemo(()=>h.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:A,disabled:f||!(d!=null&&d.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${x}`,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:y?t.jsx(w.Send,{className:"h-4 w-4"}):t.jsx(w.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:y?t.jsx(w.Rocket,{className:"h-4 w-4"}):t.jsx(w.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:b}),e?`(${h.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:f||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${x}`,children:t.jsx(w.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(c.DropdownMenuItem,{disabled:f,className:"cursor-pointer text-xs",onClick:()=>m({ids:v},{onSuccess:()=>It("TOP_RIGHT")}),children:[se.PUBLISH," with translation pages"]}),!y&&t.jsxs(c.DropdownMenuItem,{disabled:f,className:"cursor-pointer text-xs",onClick:()=>m({ids:[d==null?void 0:d.id]},{onSuccess:()=>It("TOP_RIGHT")}),children:[se.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[se.OPEN," publish menu"]}),y&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[se.UNPUBLISH," page ",e?`(${h.upperCase(e)})`:""]})]})]})]}),t.jsx(di,{showModal:a,onClose:()=>r(!1)}),o&&t.jsx(xs,{page:o,onClose:()=>u(null)})]})},yi=()=>{const e=Xe("settingComponent",null),[s,n]=g.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx($n,{content:se.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(w.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(mi,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function ji(){const{isLocked:e}=Jt(),[s]=ke(),n=s.get("lang"),a=Tn(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(ni,{}),t.jsx(Oe,{permission:ye.EDIT_THEME,children:t.jsx(gi,{})}),t.jsx(Oe,{permission:ye.EDIT_SETTINGS,children:t.jsx(yi,{})}),t.jsx(fi,{}),t.jsx(Oe,{permission:ye.SAVE_PAGE,children:t.jsx(pi,{})}),t.jsx(Oe,{permission:ye.PUBLISH_PAGE,children:t.jsx(xi,{})})]})}function vi(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 bi=()=>{const{data:e}=Nt(),s=e==null?void 0:e.slug,n=!s,a=window.location.host+(s?s.endsWith("/")?s.slice(0,-1):s:""),r=n?`Partial: ${e==null?void 0:e.name} `:vi(s);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"+(n?" pr-2":""),children:[t.jsx(zn,{}),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 text-sm ${n?"italic text-gray-400":"text-gray-500"}`,children:r})}),!n&&t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"ml-2 flex-shrink-0 px-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(w.ExternalLink,{className:"h-4 w-4"})})})]})},Si=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(Xr,{}),t.jsx(bi,{}),t.jsx(ji,{})]}),Ei=()=>{const e=ae(),{aiContext:s}=Os(),n=X();return g.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])},wi=(e,s)=>s.map(n=>{if(h.has(e,n._type)){const a=Sn.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}),Ni=e=>{const s=Sn.useRegisteredChaiBlocks();return g.useMemo(()=>{if(!e||h.isEmpty(e))return{blocks:[]};const n=h.filter(e,a=>!h.includes(a==null?void 0:a._type,"@chai/"));return{blocks:wi(s,n)}},[e,s])},an={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:J.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),[]}}},Ai=()=>{const e=ae(),s=X();return G.useQuery({queryKey:[Q,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{J.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>an.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>an.getUILibraryBlock(i,s,e)})}),a}})},Vn=()=>{const e=gs(),s=X(),{user:n}=ze(),a=n==null?void 0:n.id;return G.useQuery({queryKey:[Q,"permissions",a],queryFn:()=>s(e,{action:_.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},Ci=()=>{const e=ae(),s=X(),{setCurrentEditor:n}=Jt(),[,a]=ps();return{onSave:async({page:i,blocks:l})=>{try{const o=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return o.code==="PAGE_LOCKED"?(n(o.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),o)}catch(o){return console.error(o),new Error("Failed to save blocks")}}}},Ti=()=>{const{data:e}=Yt(),s=ae(),n=X();return{getPartialBlocks:g.useCallback(async()=>{const a={};for(const r of e??[])h.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:h.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:g.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return h.filter(r.blocks,i=>h.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},rn=as.z.object({email:as.z.string().email({message:"Please enter a valid email address"}),password:as.z.string().min(6,{message:"Password must be at least 6 characters"})}),Pi=()=>{const{setUser:e,logout:s}=ze(),n=gs(),[a,r]=g.useState(""),[i,l]=g.useState(""),[o,u]=g.useState({}),[d,m]=g.useState(!1),[f,b]=g.useState(""),x=G.useMutation({mutationFn:async v=>{b("");const N=await Gs(n,{action:"LOGIN",data:v});if(!N.ok){const L=await N.json();throw new Error(L.error||"Login failed")}const P=await N.json();if(h.has(P,"id")&&h.has(P,"email")&&h.has(P,"accessToken")&&h.has(P,"refreshToken"))e(P);else throw s(),new Error("Something went wrong. Please try again.");return P},onSuccess:()=>{u({}),b("")},onError:v=>{u({email:" ",password:" "}),b(v.message||"Something went wrong")}}),y=async v=>{v.preventDefault(),u({});const N={email:a,password:i};try{const P=rn.parse(N);x.mutate(P)}catch(P){if(P instanceof as.z.ZodError){const L=P.errors.reduce((S,T)=>{const O=T.path[0];return S[O]=T.message,S},{});u(L)}}},A=rn.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(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:y,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:v=>r(v.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:v=>l(v.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>m(!d),children:d?t.jsx(w.EyeOff,{className:"h-4 w-4"}):t.jsx(w.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:f})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!A||x.isPending,children:x.isPending?t.jsxs(t.Fragment,{children:[t.jsx(w.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center 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 Cs=Pi;const ki=()=>g.useMemo(()=>Cs,[Cs]),Ii=e=>{Cs=e},_i=()=>{const e=ki();return t.jsx(g.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},Li=({isActive:e,show:s})=>{const{data:n}=Ze();return!h.has(n,"languages")||!h.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(w.LanguagesIcon,{className:"w-4 h-4"})})},Hn="lang",Di={id:Hn,label:"Languages",position:"top",panel:kr,button:Li,view:"modal",width:400};function Ke({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=ve.useState(!1),[l,o]=ve.useState([]),[u,d]=ve.useState(e);ve.useEffect(()=>{r||o([]),d(e)},[e,r]);const m=y=>Array.isArray(y)?"array":typeof y=="object"&&y!==null?"object":"value",f=ve.useCallback(y=>{const A=v=>n==="value"?v==="value"||v==="object":n==="array"?v==="array":v===n;y.type==="object"?(o(v=>[...v,y.key]),d(y.value)):A(y.type)&&(s([...l,y.key].join(".")),i(!1))},[l,s,n]),b=ve.useCallback(()=>{if(l.length>0){const y=l.slice(0,-1);o(y),d(y.reduce((A,v)=>A[v],e))}},[l,e]),x=ve.useMemo(()=>Object.entries(u).map(([y,A])=>({key:y,value:A,type:m(A)})).filter(y=>n==="value"?y.type==="value"||y.type==="object":n==="array"?y.type==="array"||y.type==="object":n==="object"?y.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(w.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:y=>{try{y.preventDefault();const A=y.currentTarget;A.scrollTop+=y.deltaY}catch{y.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:b,className:"flex items-center text-sm",children:[t.jsx(w.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),x.map(y=>t.jsxs(c.CommandItem,{onSelect:()=>f(y),className:"flex items-center justify-between",children:[t.jsx("span",{children:y.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&y.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:A=>{A.stopPropagation(),s([...l,y.key].join(".")),i(!1)},children:"Select"}),(y.type==="object"||y.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(w.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},y.key))]})]})]})})]})}const Mi=()=>{const{selectedLang:e}=J.useLanguages(),{data:s,isFetching:n}=Ve();return{data:g.useMemo(()=>h.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Bi=()=>{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(o=>o.remove()),a.querySelectorAll("*").forEach(o=>{Array.from(o.attributes).forEach(u=>o.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(o=>`<${o.tagName.toLowerCase()}>${o.innerHTML}</${o.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},Ct=({keyword:e,onComplete:s,field:n})=>{const a=X(),r=ae(),{selectedLang:i,fallbackLang:l}=J.useLanguages(),o=J.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=G.useMutation({mutationFn:async()=>{const m=Bi();return await a(r,{action:_.GENERATE_SEO_FIELD,data:{pageContext:o,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(c.Button,{disabled:d,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:d?t.jsx(w.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(w.Sparkle,{className:"text-yellow-500"})})},Gi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ln=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,o=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:o,position:l}),a=a.replace(i,o)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,o=l.message.match(/position (\d+)/),u=o?parseInt(o[1]):void 0;let d,m;if(u!==void 0){const f=a.substring(0,u).split(`
3
- `);d=f.length,m=f[f.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:d,column:m,position:u}}}},Oi=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,o=new RegExp(Gi(l),"g");a=a.replace(o,r)}),a},Ri=(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},Ui=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:l="json-input",pageData:o={},handleFieldInsert:u})=>{const[d,m]=g.useState("edit"),[f,b]=g.useState(null),[x,y]=g.useState(""),A=g.useRef(null),v=S=>{if(a)return;const T=S.target.value;s(T)},N=S=>{if(S.key==="Tab"){S.preventDefault();const T=S.currentTarget,O=T.selectionStart,Y=T.selectionEnd;if(O!==Y){const re=e.substring(O,Y).split(`
4
- `);if(S.shiftKey){const $=re.map(F=>F.startsWith(" ")?F.substring(2):F).join(`
5
- `),te=e.substring(0,O)+$+e.substring(Y);s(te),setTimeout(()=>{T.selectionStart=O,T.selectionEnd=O+$.length},0)}else{const $=re.map(F=>` ${F}`).join(`
6
- `),te=e.substring(0,O)+$+e.substring(Y);s(te),setTimeout(()=>{T.selectionStart=O,T.selectionEnd=O+$.length},0)}}else{const z=e.substring(0,O)+" "+e.substring(Y);s(z),setTimeout(()=>{T.selectionStart=T.selectionEnd=O+2},0)}}};g.useEffect(()=>{const S=ln(e);if(S.isValid)if(b(null),S.parsed){const T=Ri(S.parsed,o);y(T)}else y("");else b(S.error),y("")},[e,o]);const P=()=>{const S=ln(e);if(S.isValid&&S.parsed){const T=Oi(S.parsed,S.placeholders);s(T)}},L=()=>{f!=null&&f.position&&A.current&&(A.current.focus(),A.current.setSelectionRange(f.position,f.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(c.Tabs,{value:d,onValueChange:m,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(c.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(w.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||f!==null,children:[t.jsx(w.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(Ke,{dataType:"value",data:o??{},onSelect:S=>u&&u(S,"jsonLD")}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:P,disabled:!e.trim()||n||f!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:A,id:l,name:l,className:`rounded-md border border-input text-xs ${f?"border-red-500":""}`,onChange:v,onKeyDown:N,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),f&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(w.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(c.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:f.message}),f.line&&f.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",f.line,", column ",f.column]}),t.jsx(c.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:L,children:"Show position"})]})]})]}),t.jsxs(c.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(c.Textarea,{rows:i,value:x,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."})]})]})})},on=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},Fi=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),o=`{{${s}}}`,u=i+""+o+l,d=n+0+o.length;return{value:u,newCursorPos:d}},Kn=()=>{const{t:e}=J.useTranslation(),[,s]=J.useSidebarActivePanel(),{data:n}=Me(),{data:a}=Us(),{data:r,isFetching:i}=Mi(),l=r==null?void 0:r.seo,o=g.useRef(null),u=n==null?void 0:n.pageType,d=In(u),{selectedLang:m,fallbackLang:f}=J.useLanguages(),b=m||f,[x,y]=g.useState(!1),[A,v]=g.useState(!1),[N,P]=g.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),L=g.useRef({initial:N,updated:N}),{mutate:S,isPending:T}=Fs(),O=T||x||A,{hasPermission:Y}=J.usePermissions(),z=Y(ye.EDIT_SEO);g.useEffect(()=>{!i&&l&&P({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const re=async()=>{if(!(!d||!b))try{y(!0);const B=is(d,b),q={...N,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","")};P(q),L.current.updated=q,K.toast.success(e("SEO fields reset to defaults"))}catch(B){K.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",B)}finally{y(!1)}},W=async()=>{if(!(!d||!b))try{v(!0);const B=is(d,b),q={...N,jsonLD:h.get(B,"seo.jsonLD","")};P(q),L.current.updated=q,K.toast.success(e("JSON-LD reset to default"))}catch(B){K.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",B)}finally{v(!1)}},$=async()=>{S({id:r==null?void 0:r.id,seo:N},{onSuccess:()=>{L.current.initial=N,L.current.updated=N,s("outline"),K.toast.success("SEO & JSON-LD updated successfully")}})},te=(B,q)=>{const oe=document.getElementById(q);if(oe){const{value:ce,newCursorPos:V}=Fi(oe,B);o.current={id:q,position:V},oe.tagName.toLowerCase()==="input"?(oe.value=ce,P(C=>({...C,[oe.name]:ce})),oe.focus(),oe.setSelectionRange(V,V),[0,10,50,100,200].forEach(C=>{setTimeout(()=>{const D=document.getElementById(q);D&&(D.focus(),D.setSelectionRange(V,V))},C)})):(P(p=>({...p,[oe.name]:ce})),requestAnimationFrame(()=>{const p=document.getElementById(q);p&&(p.focus(),p.setSelectionRange(V,V),setTimeout(()=>{const C=document.getElementById(q);C&&(C.focus(),C.setSelectionRange(V,V))},50))}))}},F=B=>{const q={...N,[B.target.name]:B.target.name==="noIndex"||B.target.name==="noFollow"?B.target.checked:B.target.value};P(q),L.current.updated=q},ne=B=>q=>{h.isEmpty(q.fieldValue)||F({target:{name:B,value:typeof q.fieldValue=="string"?q.fieldValue.replace(/^"(.*)"$/,"$1"):q.fieldValue}}),q.error&&K.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:q.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col",children:[!z&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm",children:t.jsx(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"no-scrollbar flex-grow overflow-y-auto px-2 pb-20",children:[t.jsxs("div",{className:"mb-4 flex w-full items-center justify-between rounded-md bg-gray-100 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(zn,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(c.TabsList,{className:"mb-4 grid w-full grid-cols-2",children:[t.jsx(c.TabsTrigger,{value:"seo",children:e("SEO Fields")}),t.jsx(c.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(c.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[z&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:re,disabled:O||!z||!d,children:e(x?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),z&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:B=>te(B,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:N.keyword,onChange:F,disabled:O||!z,placeholder:e("Enter keyword"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(Ct,{keyword:N.keyword,onComplete:ne("title"),field:"title"}),z&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:B=>te(B,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:N.title,onChange:F,disabled:O||!z,placeholder:e("Enter SEO title"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ct,{keyword:N.keyword,onComplete:ne("description"),field:"description"}),z&&t.jsx(Ke,{data:a??{},onSelect:B=>te(B,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:N.description,onChange:F,disabled:O||!z,placeholder:e("Enter SEO description"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),z&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:B=>te(B,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:N.canonicalUrl,onChange:F,disabled:O||!z,placeholder:e("Enter Canonical URL"),readOnly:!z})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:N.noIndex,onChange:F,disabled:O||!z,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:N.noFollow,onChange:F,disabled:O||!z,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to follow links on this page.")})]}),t.jsxs("div",{children:[t.jsx("h3",{className:"mb-4 font-semibold text-slate-700",children:e("Open Graph")}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ct,{keyword:N.keyword,onComplete:ne("ogTitle"),field:"ogTitle"}),z&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:B=>te(B,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:N.ogTitle,onChange:F,disabled:O||!z,placeholder:e("Enter OG title"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ct,{keyword:N.keyword,onComplete:ne("ogDescription"),field:"ogDescription"}),z&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:B=>te(B,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:N.ogDescription,onChange:F,disabled:O||!z,placeholder:e("Enter OG description"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Ga,{assetId:N.ogImageId,assetUrl:N.ogImage,onChange:B=>{P({...N,ogImage:B.url,ogImageId:B.id})},disabled:O||!z,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[z&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:W,disabled:O||!z||!d,children:e(A?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(Ct,{keyword:N.keyword,onComplete:ne("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(Ui,{id:"jsonLD",value:N.jsonLD,onChange:B=>{F({target:{name:"jsonLD",value:B}})},placeholder:e("Enter JSON-LD"),disabled:O||!z,readOnly:!z,pageData:a||{},rows:12,handleFieldInsert:te})]})]})})]})})]}),z&&t.jsxs("div",{className:"fixed bottom-0 left-0 right-0 flex w-full flex-shrink-0 items-center justify-between border-t bg-background p-4",children:[on(N.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:e("Invalid JSON. Please check.")}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(c.Button,{onClick:$,disabled:!on(N==null?void 0:N.jsonLD)||h.isEqual(L.current.initial,N)||O||!z,children:e(T?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]})]})};Kn.displayName="SeoPanel";const Wn="seo",qi=({isActive:e,show:s})=>{const{data:n}=Me(),a=In(n==null?void 0:n.pageType);return!h.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{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"})]})})},zi={id:Wn,label:"SEO & JSON-LD",panel:Kn,button:qi,position:"top",width:600,view:"modal"},$i="user-info",Vi=()=>{const{user:e,logout:s}=ze(),n=G.useQueryClient(),a=Xe("onLogout",h.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(w.User,{className:"w-4 h-4"})})}),t.jsxs(c.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(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[Q]}),h.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},Hi={id:$i,label:"User Info",button:Vi,position:"bottom"},Ki=()=>{J.registerChaiSidebarPanel(Wn,zi),J.registerChaiSidebarPanel(Hn,Di),J.registerChaiSidebarPanel("user-info",Hi)};var ee={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return cn(this.context.count)},getNextContextId(){return cn(this.context.count++)}};function cn(e){const s=String(e),n=s.length-1;return ee.context.id+(n?String.fromCharCode(96+n):"")+s}function Tt(e){ee.context=e}var Wi=(e,s)=>e===s,ls=Symbol("solid-proxy"),Qn=typeof Proxy=="function",Ws=Symbol("solid-track"),os={equals:Wi},Yn=na,He=1,cs=2,Jn={owned:null,cleanups:null,context:null,owner:null},Ss={},de=null,Es=null,Qi=null,ge=null,Pe=null,$e=null,ys=0;function We(e,s){const n=ge,a=de,r=e.length===0,i=s===void 0?a:s,l=r?Jn:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Ae(()=>Dt(l)));de=l,ge=null;try{return Fe(o,!0)}finally{ge=n,de=a}}function Ee(e,s){s=s?Object.assign({},os,s):os;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),sa(n,r));return[ta.bind(n),a]}function Xn(e,s,n){const a=js(e,s,!0,He);At(a)}function Qe(e,s,n){const a=js(e,s,!1,He);At(a)}function Qs(e,s,n){Yn=cl;const a=js(e,s,!1,He);(!n||!n.render)&&(a.user=!0),$e?$e.push(a):At(a)}function De(e,s,n){n=n?Object.assign({},os,n):os;const a=js(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,At(a),ta.bind(a)}function Yi(e){return e&&typeof e=="object"&&"then"in e}function Ji(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,o=Ss,u=null,d=!1,m="initialValue"in i,f=typeof a=="function"&&De(a);const b=new Set,[x,y]=(i.storage||Ee)(i.initialValue),[A,v]=Ee(void 0),[N,P]=Ee(void 0,{equals:!1}),[L,S]=Ee(m?"ready":"unresolved");ee.context&&(u=ee.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:ee.load&&ee.has(u)&&(o=ee.load(u)));function T(re,W,$,te){return l===re&&(l=null,te!==void 0&&(m=!0),(re===o||W===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(te,{value:W})),o=Ss,O(W,$)),W}function O(re,W){Fe(()=>{W===void 0&&y(()=>re),S(W!==void 0?"errored":m?"ready":"unresolved"),v(W);for(const $ of b.keys())$.decrement();b.clear()},!1)}function Y(){const re=il,W=x(),$=A();if($!==void 0&&!l)throw $;return ge&&ge.user,W}function z(re=!0){if(re!==!1&&d)return;d=!1;const W=f?f():a;if(W==null||W===!1){T(l,Ae(x));return}const $=o!==Ss?o:Ae(()=>r(W,{value:x(),refetching:re}));return Yi($)?(l=$,"value"in $?($.status==="success"?T(l,$.value,void 0,W):T(l,void 0,Ts($.value),W),$):(d=!0,queueMicrotask(()=>d=!1),Fe(()=>{S(m?"refreshing":"pending"),P()},!1),$.then(te=>T($,te,void 0,W),te=>T($,void 0,Ts(te),W)))):(T(l,$,void 0,W),$)}return Object.defineProperties(Y,{state:{get:()=>L()},error:{get:()=>A()},loading:{get(){const re=L();return re==="pending"||re==="refreshing"}},latest:{get(){if(!m)return Y();const re=A();if(re&&!l)throw re;return x()}}}),f?Xn(()=>z(!1)):z(!1),[Y,{refetch:z,mutate:y}]}function Xi(e){return Fe(e,!1)}function Ae(e){if(ge===null)return e();const s=ge;ge=null;try{return e()}finally{ge=s}}function Zi(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let o;if(a){o=Array(e.length);for(let d=0;d<e.length;d++)o[d]=e[d]()}else o=e();if(i)return i=!1,l;const u=Ae(()=>s(o,r,l));return r=o,u}}function Zn(e){Qs(()=>Ae(e))}function St(e){return de===null||(de.cleanups===null?de.cleanups=[e]:de.cleanups.push(e)),e}function un(){return de}function el(e,s){const n=de,a=ge;de=e,ge=null;try{return Fe(s,!0)}catch(r){Ys(r)}finally{de=n,ge=a}}function tl(e){const s=ge,n=de;return Promise.resolve().then(()=>{ge=s,de=n;let a;return Fe(e,!1),ge=de=null,a?a.done:void 0})}var[sl,lc]=Ee(!1);function nl(){return[sl,tl]}function al(e,s){const n=Symbol("context");return{id:n,Provider:ul(n),defaultValue:e}}function rl(e){let s;return de&&de.context&&(s=de.context[e.id])!==void 0?s:e.defaultValue}function ea(e){const s=De(e),n=De(()=>Ps(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var il;function ta(){if(this.sources&&this.state)if(this.state===He)At(this);else{const e=Pe;Pe=null,Fe(()=>ds(this),!1),Pe=e}if(ge){const e=this.observers?this.observers.length:0;ge.sources?(ge.sources.push(this),ge.sourceSlots.push(e)):(ge.sources=[this],ge.sourceSlots=[e]),this.observers?(this.observers.push(ge),this.observerSlots.push(ge.sources.length-1)):(this.observers=[ge],this.observerSlots=[ge.sources.length-1])}return this.value}function sa(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&Fe(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=Es&&Es.running;l&&Es.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Pe.push(i):$e.push(i),i.observers&&aa(i)),l||(i.state=He)}if(Pe.length>1e6)throw Pe=[],new Error},!1)),s}function At(e){if(!e.fn)return;Dt(e);const s=ys;ll(e,e.value,s)}function ll(e,s,n){let a;const r=de,i=ge;ge=de=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=He,e.owned&&e.owned.forEach(Dt),e.owned=null),e.updatedAt=n+1,Ys(l)}finally{ge=i,de=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?sa(e,a):e.value=a,e.updatedAt=n)}function js(e,s,n,a=He,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:de,context:de?de.context:null,pure:n};return de===null||de!==Jn&&(de.owned?de.owned.push(i):de.owned=[i]),i}function us(e){if(e.state===0)return;if(e.state===cs)return ds(e);if(e.suspense&&Ae(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<ys);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===He)At(e);else if(e.state===cs){const a=Pe;Pe=null,Fe(()=>ds(e,s[0]),!1),Pe=a}}function Fe(e,s){if(Pe)return e();let n=!1;s||(Pe=[]),$e?n=!0:$e=[],ys++;try{const a=e();return ol(n),a}catch(a){n||($e=null),Pe=null,Ys(a)}}function ol(e){if(Pe&&(na(Pe),Pe=null),e)return;const s=$e;$e=null,s.length&&Fe(()=>Yn(s),!1)}function na(e){for(let s=0;s<e.length;s++)us(e[s])}function cl(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:us(a)}if(ee.context){if(ee.count){ee.effects||(ee.effects=[]),ee.effects.push(...e.slice(0,n));return}Tt()}for(ee.effects&&(ee.done||!ee.count)&&(e=[...ee.effects,...e],n+=ee.effects.length,delete ee.effects),s=0;s<n;s++)us(e[s])}function ds(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===He?a!==s&&(!a.updatedAt||a.updatedAt<ys)&&us(a):r===cs&&ds(a,s)}}}function aa(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=cs,n.pure?Pe.push(n):$e.push(n),n.observers&&aa(n))}}function Dt(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--)Dt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Dt(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 Ts(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Ys(e,s=de){throw Ts(e)}function Ps(e){if(typeof e=="function"&&!e.length)return Ps(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Ps(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function ul(e,s){return function(a){let r;return Qe(()=>r=Ae(()=>(de.context={...de.context,[e]:a.value},ea(()=>a.children))),void 0),r}}var ks=Symbol("fallback");function hs(e){for(let s=0;s<e.length;s++)e[s]()}function dl(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return St(()=>hs(i)),()=>{let u=e()||[],d=u.length,m,f;return u[Ws],Ae(()=>{let x,y,A,v,N,P,L,S,T;if(d===0)l!==0&&(hs(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[ks],r[0]=We(O=>(i[0]=O,n.fallback())),l=1);else if(l===0){for(r=new Array(d),f=0;f<d;f++)a[f]=u[f],r[f]=We(b);l=d}else{for(A=new Array(d),v=new Array(d),o&&(N=new Array(d)),P=0,L=Math.min(l,d);P<L&&a[P]===u[P];P++);for(L=l-1,S=d-1;L>=P&&S>=P&&a[L]===u[S];L--,S--)A[S]=r[L],v[S]=i[L],o&&(N[S]=o[L]);for(x=new Map,y=new Array(S+1),f=S;f>=P;f--)T=u[f],m=x.get(T),y[f]=m===void 0?-1:m,x.set(T,f);for(m=P;m<=L;m++)T=a[m],f=x.get(T),f!==void 0&&f!==-1?(A[f]=r[m],v[f]=i[m],o&&(N[f]=o[m]),f=y[f],x.set(T,f)):i[m]();for(f=P;f<d;f++)f in A?(r[f]=A[f],i[f]=v[f],o&&(o[f]=N[f],o[f](f))):r[f]=We(b);r=r.slice(0,l=d),a=u.slice(0)}return r});function b(x){if(i[f]=x,o){const[y,A]=Ee(f);return o[f]=A,s(u[f],y)}return s(u[f])}}}function hl(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return St(()=>hs(i)),()=>{const d=e()||[],m=d.length;return d[Ws],Ae(()=>{if(m===0)return o!==0&&(hs(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[ks],r[0]=We(b=>(i[0]=b,n.fallback())),o=1),r;for(a[0]===ks&&(i[0](),i=[],a=[],r=[],o=0),u=0;u<m;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=We(f));for(;u<a.length;u++)i[u]();return o=l.length=i.length=m,a=d.slice(0),r=r.slice(0,o)});function f(b){i[u]=b;const[x,y]=Ee(d[u]);return l[u]=y,s(x,u)}}}function Js(e,s){return Ae(()=>e(s||{}))}function ts(){return!0}var Is={get(e,s,n){return s===ls?n:e.get(s)},has(e,s){return s===ls?!0:e.has(s)},set:ts,deleteProperty:ts,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:ts,deleteProperty:ts}},ownKeys(e){return e.keys()}};function ws(e){return(e=typeof e=="function"?e():e)?e:{}}function ml(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function Xs(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&ls in o,e[l]=typeof o=="function"?(s=!0,De(o)):o}if(Qn&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=ws(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in ws(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(ws(e[o])));return[...new Set(l)]}},Is);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let d=u.length-1;d>=0;d--){const m=u[d];if(m==="__proto__"||m==="constructor")continue;const f=Object.getOwnPropertyDescriptor(o,m);if(!a[m])a[m]=f.get?{enumerable:!0,configurable:!0,get:ml.bind(n[m]=[f.get.bind(o)])}:f.value!==void 0?f:void 0;else{const b=n[m];b&&(f.get?b.push(f.get.bind(o)):f.value!==void 0&&b.push(()=>f.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const o=i[l],u=a[o];u&&u.get?Object.defineProperty(r,o,u):r[o]=u?u.value:void 0}return r}function ra(e,...s){if(Qn&&ls in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(o){return l.includes(o)?e[o]:void 0},has(o){return l.includes(o)&&o in e},keys(){return l.filter(o=>o in e)}},Is));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))}},Is)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let o=!1,u=0;for(const d of s)d.includes(r)&&(o=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;o||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function ia(e){let s,n;const a=r=>{const i=ee.context;if(i){const[o,u]=Ee();ee.count||(ee.count=0),ee.count++,(n||(n=e())).then(d=>{!ee.done&&Tt(i),ee.count--,u(()=>d.default),Tt()}),s=o}else if(!s){const[o]=Ji(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return De(()=>(l=s())?Ae(()=>{if(!i||ee.done)return l(r);const o=ee.context;Tt(i);const u=l(r);return Tt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var fl=0;function gl(){return ee.context?ee.getNextContextId():`cl-${fl++}`}var la=e=>`Stale read from <${e}>.`;function pl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return De(dl(()=>e.each,e.children,s||void 0))}function xl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return De(hl(()=>e.each,e.children,s||void 0))}function yl(e){const s=e.keyed,n=De(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return De(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Ae(()=>r(s?a:()=>{if(!Ae(n))throw la("Show");return e.when})):r}return e.fallback},void 0,void 0)}function jl(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=ea(()=>e.children),r=De(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const o=i[l].when;if(o)return s=!!i[l].keyed,[l,o,i[l]]}return[-1]},void 0,{equals:n});return De(()=>{const[i,l,o]=r();if(i<0)return e.fallback;const u=o.children;return typeof u=="function"&&u.length>0?Ae(()=>u(s?l:()=>{if(Ae(r)[0]!==i)throw la("Match");return o.when})):u},void 0,void 0)}function vl(e){return e}var bl=["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"],Sl=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...bl]),El=new Set(["innerHTML","textContent","innerText","children"]),wl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Nl=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 Al(e,s){const n=Nl[e];return typeof n=="object"?n[s]?n.$:void 0:n}var Cl=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Tl=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"]),Pl={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function kl(e,s,n){let a=n.length,r=s.length,i=a,l=0,o=0,u=s[r-1].nextSibling,d=null;for(;l<r||o<i;){if(s[l]===n[o]){l++,o++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const m=i<a?o?n[o-1].nextSibling:n[i-o]:u;for(;o<i;)e.insertBefore(n[o++],m)}else if(i===o)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[o]===s[r-1]){const m=s[--r].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--i],m),s[r]=n[i]}else{if(!d){d=new Map;let f=o;for(;f<i;)d.set(n[f],f++)}const m=d.get(s[l]);if(m!=null)if(o<m&&m<i){let f=l,b=1,x;for(;++f<r&&f<i&&!((x=d.get(s[f]))==null||x!==m+b);)b++;if(b>m-o){const y=s[l];for(;o<m;)e.insertBefore(n[o++],y)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var _t="_$DX_DELEGATE";function oa(e,s,n,a={}){let r;return We(i=>{r=i,s===document?e():fs(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function Il(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 ca(e,s=window.document){const n=s[_t]||(s[_t]=new Set);for(let a=0,r=e.length;a<r;a++){const i=e[a];n.has(i)||(n.add(i),s.addEventListener(i,fa))}}function _l(e=window.document){if(e[_t]){for(let s of e[_t].keys())e.removeEventListener(s,fa);delete e[_t]}}function ms(e,s,n){nt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function Ll(e,s,n,a){nt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function Dl(e,s,n){nt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function ua(e,s){nt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function da(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 Ml(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const o=r[i];!o||o==="undefined"||s[o]||(dn(e,o,!1),delete n[o])}for(i=0,l=a.length;i<l;i++){const o=a[i],u=!!s[o];!o||o==="undefined"||n[o]===u||!u||(dn(e,o,!0),n[o]=u)}return n}function Bl(e,s,n){if(!s)return n?ms(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 ha(e,s={},n,a){const r={};return a||Qe(()=>r.children=Mt(e,s.children,r.children)),Qe(()=>typeof s.ref=="function"&&ma(s.ref,e)),Qe(()=>Gl(e,s,n,!0,r,!0)),r}function ma(e,s,n){return Ae(()=>e(s,n))}function fs(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Mt(e,s,a,n);Qe(r=>Mt(e,s(),r,n),a)}function Gl(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=hn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=hn(e,l,o,r[l],n,i,s)}}function Ol(e){let s,n;return!nt()||!(s=ee.registry.get(n=Ul()))?e():(ee.completed&&ee.completed.add(s),ee.registry.delete(n),s)}function nt(e){return!!ee.context&&!ee.done&&(!e||e.isConnected)}function Rl(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function dn(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 hn(e,s,n,a,r,i,l){let o,u,d,m,f;if(s==="style")return Bl(e,n,a);if(s==="classList")return Ml(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(),x=Cl.has(b);if(!x&&a){const y=Array.isArray(a)?a[0]:a;e.removeEventListener(b,y)}(x||n)&&(da(e,b,n,x),x&&ca([b]))}else if(s.slice(0,5)==="attr:")ms(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")Dl(e,s.slice(5),n);else if((f=s.slice(0,5)==="prop:")||(d=El.has(s))||!r&&((m=Al(s,e.tagName))||(u=Sl.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(f)s=s.slice(5),u=!0;else if(nt(e))return n;s==="class"||s==="className"?ua(e,n):o&&!u&&!d?e[Rl(s)]=n:e[m||s]=n}else{const b=r&&s.indexOf(":")>-1&&Pl[s.split(":")[0]];b?Ll(e,b,s,n):ms(e,wl[s]||s,n)}return n}function fa(e){if(ee.registry&&ee.events&&ee.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},o=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),ee.registry&&!ee.done&&(ee.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,o();break}if(s.parentNode===r)break}}else o();i(a)}function Mt(e,s,n,a,r){const i=nt(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,o=a!==void 0;if(e=o&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(o){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=rt(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=rt(e,n,a)}else{if(l==="function")return Qe(()=>{let u=s();for(;typeof u=="function";)u=u();n=Mt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(_s(u,s,n,r))return Qe(()=>n=Mt(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let m=u[0];if(m.parentNode!==e)return n;const f=[m];for(;(m=m.nextSibling)!==a;)f.push(m);return n=f}if(u.length===0){if(n=rt(e,n,a),o)return n}else d?n.length===0?mn(e,u,a):kl(e,n,u):(n&&rt(e),mn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=o?[s]:s;if(Array.isArray(n)){if(o)return n=rt(e,n,a,s);rt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function _s(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let o=s[i],u=n&&n[e.length],d;if(!(o==null||o===!0||o===!1))if((d=typeof o)=="object"&&o.nodeType)e.push(o);else if(Array.isArray(o))r=_s(e,o,u)||r;else if(d==="function")if(a){for(;typeof o=="function";)o=o();r=_s(e,Array.isArray(o)?o:[o],Array.isArray(u)?u:[u])||r}else e.push(o),r=!0;else{const m=String(o);u&&u.nodeType===3&&u.data===m?e.push(u):e.push(document.createTextNode(m))}}return r}function mn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function rt(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const o=s[l];if(r!==o){const u=o.parentNode===e;!i&&!l?u?e.replaceChild(r,o):e.insertBefore(r,n):u&&o.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function Ul(){return ee.getNextContextId()}var Fl="http://www.w3.org/2000/svg";function ga(e,s=!1){return s?document.createElementNS(Fl,e):document.createElement(e)}function ql(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=un();let i,l=!!ee.context;return Qs(()=>{l&&(un().user=l=!1),i||(i=el(r,()=>De(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,d]=Ee(!1),m=()=>d(!0);We(f=>fs(o,()=>u()?f():i(),null)),St(m)}else{const u=ga(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}),fs(d,i),o.appendChild(u),e.ref&&e.ref(u),St(()=>o.removeChild(u))}},void 0,{render:!l}),n}function zl(e){const[s,n]=ra(e,["component"]),a=De(()=>s.component);return De(()=>{const r=a();switch(typeof r){case"function":return Ae(()=>r(n));case"string":const i=Tl.has(r),l=ee.context?Ol():ga(r,i);return ha(l,n,i),l}})}var $l=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()}},pa=class{constructor(e){this.generateIdentifier=e,this.kv=new $l}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)}},Vl=class extends pa{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 Hl(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 Kl(e,s){const n=Hl(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 rs(e,s){return e.indexOf(s)!==-1}function fn(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Wl=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Kl(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Ql=e=>Object.prototype.toString.call(e).slice(8,-1),xa=e=>typeof e>"u",Yl=e=>e===null,Bt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Ls=e=>Bt(e)&&Object.keys(e).length===0,Je=e=>Array.isArray(e),Jl=e=>typeof e=="string",Xl=e=>typeof e=="number"&&!isNaN(e),Zl=e=>typeof e=="boolean",eo=e=>e instanceof RegExp,Gt=e=>e instanceof Map,Ot=e=>e instanceof Set,ya=e=>Ql(e)==="Symbol",to=e=>e instanceof Date&&!isNaN(e.valueOf()),so=e=>e instanceof Error,gn=e=>typeof e=="number"&&isNaN(e),no=e=>Zl(e)||Yl(e)||xa(e)||Xl(e)||Jl(e)||ya(e),ao=e=>typeof e=="bigint",ro=e=>e===1/0||e===-1/0,io=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),lo=e=>e instanceof URL,ja=e=>e.replace(/\./g,"\\."),Ns=e=>e.map(String).map(ja).join("."),Lt=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 Ue(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var va=[Ue(xa,"undefined",()=>null,()=>{}),Ue(ao,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),Ue(to,"Date",e=>e.toISOString(),e=>new Date(e)),Ue(so,"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}),Ue(eo,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),Ue(Ot,"set",e=>[...e.values()],e=>new Set(e)),Ue(Gt,"map",e=>[...e.entries()],e=>new Map(e)),Ue(e=>gn(e)||ro(e),"number",e=>gn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),Ue(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),Ue(lo,"URL",e=>e.toString(),e=>new URL(e))];function vs(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var ba=vs((e,s)=>ya(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}),oo=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),Sa=vs(io,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=oo[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function Ea(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var wa=vs(Ea,(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)}),Na=vs((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)}),co=[wa,ba,Na,Sa],pn=(e,s)=>{const n=fn(co,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=fn(va,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},Aa={};va.forEach(e=>{Aa[e.annotation]=e});var uo=(e,s,n)=>{if(Je(s))switch(s[0]){case"symbol":return ba.untransform(e,s,n);case"class":return wa.untransform(e,s,n);case"custom":return Na.untransform(e,s,n);case"typed-array":return Sa.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=Aa[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},it=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function Ca(e){if(rs(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(rs(e,"prototype"))throw new Error("prototype is not allowed as a property");if(rs(e,"constructor"))throw new Error("constructor is not allowed as a property")}var ho=(e,s)=>{Ca(s);for(let n=0;n<s.length;n++){const a=s[n];if(Ot(e))e=it(e,+a);else if(Gt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=it(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Ds=(e,s,n)=>{if(Ca(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Je(a)){const o=+l;a=a[o]}else if(Bt(a))a=a[l];else if(Ot(a)){const o=+l;a=it(a,o)}else if(Gt(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",m=it(a,u);switch(d){case"key":a=m;break;case"value":a=a.get(m);break}}}const r=s[s.length-1];if(Je(a)?a[+r]=n(a[+r]):Bt(a)&&(a[r]=n(a[r])),Ot(a)){const i=it(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Gt(a)){const i=+s[s.length-2],l=it(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 Ms(e,s,n=[]){if(!e)return;if(!Je(e)){Et(e,(i,l)=>Ms(i,s,[...n,...Lt(l)]));return}const[a,r]=e;r&&Et(r,(i,l)=>{Ms(i,s,[...n,...Lt(l)])}),s(a,n)}function mo(e,s,n){return Ms(s,(a,r)=>{e=Ds(e,r,i=>uo(i,a,n))}),e}function fo(e,s){function n(a,r){const i=ho(e,Lt(r));a.map(Lt).forEach(l=>{e=Ds(e,l,()=>i)})}if(Je(s)){const[a,r]=s;a.forEach(i=>{e=Ds(e,Lt(i),()=>e)}),r&&Et(r,n)}else Et(s,n);return e}var go=(e,s)=>Bt(e)||Je(e)||Gt(e)||Ot(e)||Ea(e,s);function po(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function xo(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(o=>o.map(String)).sort((o,u)=>o.length-u.length));const[i,...l]=r;i.length===0?a=l.map(Ns):n[Ns(i)]=l.map(Ns)}),a?Ls(n)?[a]:[a,n]:Ls(n)?void 0:n}var Ta=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=no(e);if(!o){po(e,r,s);const x=l.get(e);if(x)return a?{transformedValue:null}:x}if(!go(e,n)){const x=pn(e,n),y=x?{transformedValue:x.value,annotations:[x.type]}:{transformedValue:e};return o||l.set(e,y),y}if(rs(i,e))return{transformedValue:null};const u=pn(e,n),d=(u==null?void 0:u.value)??e,m=Je(d)?[]:{},f={};Et(d,(x,y)=>{if(y==="__proto__"||y==="constructor"||y==="prototype")throw new Error(`Detected property ${y}. This is a prototype pollution risk, please remove it from your object.`);const A=Ta(x,s,n,a,[...r,y],[...i,e],l);m[y]=A.transformedValue,Je(A.annotations)?f[y]=A.annotations:Bt(A.annotations)&&Et(A.annotations,(v,N)=>{f[ja(y)+"."+N]=v})});const b=Ls(f)?{transformedValue:m,annotations:u?[u.type]:void 0}:{transformedValue:m,annotations:u?[u.type,f]:f};return o||l.set(e,b),b};function Pa(e){return Object.prototype.toString.call(e).slice(8,-1)}function xn(e){return Pa(e)==="Array"}function yo(e){if(Pa(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function jo(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 Bs(e,s={}){if(xn(e))return e.map(r=>Bs(r,s));if(!yo(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(xn(s.props)&&!s.props.includes(i))return r;const l=e[i],o=Bs(l,s);return jo(r,i,o,e,s.nonenumerable),r},{})}var pe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Vl,this.symbolRegistry=new pa(s=>s.description??""),this.customTransformerRegistry=new Wl,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Ta(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=xo(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=Bs(s);return n!=null&&n.values&&(a=mo(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 ka=pe.serialize,vo=pe.stringify;function bo(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function So(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function Eo({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function wo({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function No(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var Ao=(e,s=!1)=>{const{json:n}=ka(e);return JSON.stringify(n,null,s?2:void 0)},ss=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,Co=(e,s)=>e.queryHash.localeCompare(s.queryHash),Ia=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,To=(e,s)=>ss(e)===ss(s)?Ia(e,s):ss(e)>ss(s)?1:-1,Po={status:To,"query hash":Co,"last updated":Ia},ns=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,_a=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,ko=(e,s)=>ns(e)===ns(s)?_a(e,s):ns(e)>ns(s)?1:-1,Io={status:ko,"last updated":_a},_o=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),Lo=()=>{const[e,s]=Ee("dark");return Zn(()=>{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},Pt=(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,Pt(a.get(r),i,n)),a}if(e instanceof Set){const a=Pt(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]=Pt(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]=Pt(a[r],i,n),a}return e},kt=(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,kt(n.get(a),r)),n}if(e instanceof Set){const n=kt(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]=kt(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]=kt(n[a],r),n}return e},La=(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)},lt,Rt,Ut,Ft,et,qt,ot,ct,ut,dt,ht,mt,zt,vn,Do=(vn=class{constructor(e){fe(this,lt);fe(this,Rt);fe(this,Ut);fe(this,Ft);fe(this,et,!1);fe(this,qt);fe(this,ot);fe(this,ct);fe(this,ut);fe(this,dt);fe(this,ht);fe(this,mt);fe(this,zt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:m}=e;me(this,lt,Ee(s)),me(this,Ut,n),me(this,Ft,a),me(this,Rt,r),me(this,qt,d),me(this,ot,m),me(this,ct,Ee(i)),me(this,ut,Ee(l)),me(this,dt,Ee(o)),me(this,ht,Ee(u))}setButtonPosition(e){Z(this,ct)[1](e)}setPosition(e){Z(this,ut)[1](e)}setInitialIsOpen(e){Z(this,dt)[1](e)}setErrorTypes(e){Z(this,ht)[1](e)}setClient(e){Z(this,lt)[1](e)}mount(e){if(Z(this,et))throw new Error("Devtools is already mounted");const s=oa(()=>{const n=this,[a]=Z(this,ct),[r]=Z(this,ut),[i]=Z(this,dt),[l]=Z(this,ht),[o]=Z(this,lt);let u;return Z(this,mt)?u=Z(this,mt):(u=ia(()=>Promise.resolve().then(()=>require("./HO4MOOFI-DAE_aO4G.cjs"))),me(this,mt,u)),La(Z(this,qt),Z(this,ot)),Js(u,Xs({get queryFlavor(){return Z(n,Ut)},get version(){return Z(n,Ft)},get onlineManager(){return Z(n,Rt)},get shadowDOMTarget(){return Z(n,ot)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);me(this,et,!0),me(this,zt,s)}unmount(){var e;if(!Z(this,et))throw new Error("Devtools is not mounted");(e=Z(this,zt))==null||e.call(this),me(this,et,!1)}},lt=new WeakMap,Rt=new WeakMap,Ut=new WeakMap,Ft=new WeakMap,et=new WeakMap,qt=new WeakMap,ot=new WeakMap,ct=new WeakMap,ut=new WeakMap,dt=new WeakMap,ht=new WeakMap,mt=new WeakMap,zt=new WeakMap,vn),ft,$t,Vt,Ht,tt,Kt,gt,pt,xt,yt,jt,vt,bt,Wt,bn,Mo=(bn=class{constructor(e){fe(this,ft);fe(this,$t);fe(this,Vt);fe(this,Ht);fe(this,tt,!1);fe(this,Kt);fe(this,gt);fe(this,pt);fe(this,xt);fe(this,yt);fe(this,jt);fe(this,vt);fe(this,bt);fe(this,Wt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:m,onClose:f}=e;me(this,ft,Ee(s)),me(this,Vt,n),me(this,Ht,a),me(this,$t,r),me(this,Kt,d),me(this,gt,m),me(this,pt,Ee(i)),me(this,xt,Ee(l)),me(this,yt,Ee(o)),me(this,jt,Ee(u)),me(this,vt,Ee(f))}setButtonPosition(e){Z(this,pt)[1](e)}setPosition(e){Z(this,xt)[1](e)}setInitialIsOpen(e){Z(this,yt)[1](e)}setErrorTypes(e){Z(this,jt)[1](e)}setClient(e){Z(this,ft)[1](e)}setOnClose(e){Z(this,vt)[1](()=>e)}mount(e){if(Z(this,tt))throw new Error("Devtools is already mounted");const s=oa(()=>{const n=this,[a]=Z(this,pt),[r]=Z(this,xt),[i]=Z(this,yt),[l]=Z(this,jt),[o]=Z(this,ft),[u]=Z(this,vt);let d;return Z(this,bt)?d=Z(this,bt):(d=ia(()=>Promise.resolve().then(()=>require("./HUY7CZI3-CgZgvc1q.cjs"))),me(this,bt,d)),La(Z(this,Kt),Z(this,gt)),Js(d,Xs({get queryFlavor(){return Z(n,Vt)},get version(){return Z(n,Ht)},get onlineManager(){return Z(n,$t)},get shadowDOMTarget(){return Z(n,gt)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);me(this,tt,!0),me(this,Wt,s)}unmount(){var e;if(!Z(this,tt))throw new Error("Devtools is not mounted");(e=Z(this,Wt))==null||e.call(this),me(this,tt,!1)}},ft=new WeakMap,$t=new WeakMap,Vt=new WeakMap,Ht=new WeakMap,tt=new WeakMap,Kt=new WeakMap,gt=new WeakMap,pt=new WeakMap,xt=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,Wt=new WeakMap,bn);function Bo(e){const s=G.useQueryClient(e.client),n=ve.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}=e,[d]=ve.useState(new Do({client:s,queryFlavor:"React Query",version:"5",onlineManager:G.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}));return ve.useEffect(()=>{d.setClient(s)},[s,d]),ve.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),ve.useEffect(()=>{r&&d.setPosition(r)},[r,d]),ve.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),ve.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),ve.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function Go(e){const s=G.useQueryClient(e.client),n=ve.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=ve.useState(new Mo({client:s,queryFlavor:"React Query",version:"5",onlineManager:G.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose}));return ve.useEffect(()=>{l.setClient(s)},[s,l]),ve.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),ve.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),ve.useEffect(()=>(n.current&&l.mount(n.current),()=>{l.unmount()}),[l]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var Oo=process.env.NODE_ENV!=="development"?function(){return null}:Bo;process.env.NODE_ENV;const Da=()=>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(w.Loader2,{className:"size-5 animate-spin"})})}),Ro=()=>{const e=ae(),s=X();return G.useQuery({queryKey:[Q,_.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:_.GET_COLLECTIONS})})},Uo=()=>{const{data:e}=Me(),{data:s}=Nt(),{data:n}=Ze(),a=ae(),r=X(),i=g.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return G.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}}})})},Ma=()=>{const e=Hs();return g.useCallback(({pageId:s})=>{e(s)},[e])},Fo=60*5;function qo(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:r}=ze(),i=gs(),l=g.useRef(null),o=g.useCallback(async()=>{if(!(!h.has(e,"accessToken")||!h.has(e,"refreshToken")))try{const u=await Gs(i,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!u.ok){n();return}const d=await u.json();h.has(d,"id")&&h.has(d,"email")&&h.has(d,"accessToken")&&h.has(d,"refreshToken")?s(d):n()}catch{n()}},[e,n,s,i]);return g.useEffect(()=>{a&&r&&o()},[r,a,o]),g.useEffect(()=>{if(!a||!h.has(e,"expiresAt")||!h.has(e,"refreshToken")||!h.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!h.has(e,"expiresAt"))return;const u=Math.floor(Date.now()/1e3),d=e.expiresAt-u;d<Fo&&d>0&&o()},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 zo=g.lazy(()=>Promise.resolve().then(()=>ac));Fa.loadWebBlocks();J.registerChaiTopBar(Si);Ki();J.registerChaiMediaManager(zo);J.registerChaiSaveToLibrary(gr);const $o=e=>{const s=g.useRef([]),[n]=ke(),a=n.get("page"),{data:r}=Me(),{data:i={role:"",permissions:null}}=Vn();Ai();const{data:l,isFetching:o}=kn(),{blocks:u}=Ni(l),{data:d}=Ce(),{mutateAsync:m}=An(),f=Ei(),{onSave:b}=Ci(),{getPartialBlocks:x,getPartialBlockBlocks:y}=Ti(),{aiContext:A,setAiContext:v}=Os(),{mutateAsync:N}=xr(),[P,L]=g.useState(!1),{data:S}=Ze(),T=Rs(),{data:O}=Us(),{data:Y}=Ro(),{mutateAsync:z}=Uo(),re=Ma();Za(),g.useEffect(()=>{const F=()=>{document.hidden?L(!0):L(!1)};return window.addEventListener("visibilitychange",F),()=>window.removeEventListener("visibilitychange",F)},[]),s.current=u;const W=g.useMemo(()=>{const F={};return i&&(F.permissions=h.get(i,"permissions",null),F.role=h.get(i,"role","user")),F},[i]),$=g.useCallback(async(F,ne)=>await N({pageType:F,query:ne}),[N]),te=g.useMemo(()=>h.get(S,"theme",{})||{},[S]);return t.jsxs(t.Fragment,{children:[o&&t.jsx(Da,{}),t.jsx(J.ChaiBuilderEditor,{gotoPage:re,collections:Y??[],getBlockAsyncProps:z,pageExternalData:O,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:T,languages:(S==null?void 0:S.languages)||[],brandingOptions:(S==null?void 0:S.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!P&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:y,getPartialBlocks:x,blocks:o?[]:u,theme:h.cloneDeep(te),pageTypes:d,searchPageTypeItems:$,saveAiContextCallback:async F=>{if(!a)return!0;const ne=s.current,B={_type:"@chai/ai-context",_value:h.isString(F)?F:""},q=[...ne,B];return await b({page:a,blocks:q}),v(F),!0},aiContext:A,askAiCallBack:f,onSave:async({blocks:F,theme:ne})=>{if(!a)return!0;s.current=F;const B={_type:"@chai/ai-context",_value:h.isString(A)?A:""},q=[...F,B];return await b({page:a,blocks:q}),s.current=q,h.isEqual(ne,te)||await m({settings:{theme:ne}}),!0},themePanelComponent:Ar,...W}),t.jsxs("div",{children:[t.jsx(ar,{}),t.jsx(rr,{})]})]})},Vo=new G.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Ho=e=>{qo();const{isLoggedIn:s,isSessionExpired:n}=ze(),[,a]=Cn(),[r,i]=g.useState(!1);return g.useEffect(()=>(a(h.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout"])),setTimeout(()=>{i(!0)},200),()=>{i(!1),a({})}),[e,a]),r?t.jsxs(G.QueryClientProvider,{client:Vo,children:[s?n?t.jsx(Da,{}):t.jsx($o,{...e}):t.jsx(_i,{}),t.jsx(Oo,{}),t.jsx(K.Toaster,{richColors:!0})]}):t.jsx("div",{})},Ko=()=>{const e=ae(),s=X(),{data:n}=Nt(),a=G.useQueryClient();return G.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:_.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[Q,_.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[Q,_.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},Wo=()=>{const e=Qt(),s=G.useQueryClient(),n=X();return G.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:[Q,_.GET_ASSETS]}),K.toast.success("Asset uploaded successfully")},onError:()=>{K.toast.error("Failed to upload asset")}})},Qo=()=>{const e=Qt(),s=G.useQueryClient(),n=X();return G.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:[Q,_.GET_ASSETS]}),K.toast.success("Asset deleted successfully")},onError:()=>{K.toast.error("Failed to delete asset")}})},Yo=()=>{const e=Qt(),s=G.useQueryClient(),n=X();return G.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:[Q,_.GET_ASSETS]}),K.toast.success("Asset updated successfully")},onError:()=>{K.toast.error("Failed to update asset")}})},Jo=(e={})=>{const s=Qt(),n=X(),{search:a,page:r=1,limit:i=30}=e;return G.useQuery({queryKey:[Q,_.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})},Xo=e=>{const s=Qt(),n=X();return G.useQuery({queryKey:[Q,_.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:_.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Zo(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 yn(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 jn(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 ec=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var f,b,x;const{data:i,isLoading:l,isError:o}=Xo(e||""),[u,d]=g.useState(""),m=async(y,A)=>{try{await navigator.clipboard.writeText(y),K.toast.success(`${A} copied to clipboard`)}catch(v){K.toast.error(`Failed to copy ${A}`,{description:v==null?void 0:v.message})}};return g.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(w.Loader,{className:"h-8 w-8 animate-spin"})}):o||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(w.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(w.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>m(i.url,"Asset URL"),disabled:r,children:[t.jsx(w.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(w.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((f=i.metadata)==null?void 0:f.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((b=i.metadata)==null?void 0:b.format)||i.type,capitalize:!0},{label:"Size",value:Zo(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:yn(i.createdAt)},{label:"Updated",value:yn(((x=i.metadata)==null?void 0:x.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(y=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:y.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(y.capitalize?" capitalize":""),children:y.value}),y.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>m(y.value,y.label),children:t.jsx(w.Link,{className:"h-3 w-3"})})]})]},y.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((y,A)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:y.name}),t.jsxs("div",{className:"text-gray-500",children:["(",y.slug,")"]})]},A))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:y=>d(y.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||!jn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!jn(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(w.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},tc=g.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function sc(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 nc=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,o]=g.useState(()=>{const x=localStorage.getItem("chai_optimize_images");return x!==null?x==="true":!0});g.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=g.useCallback(async x=>new Promise((y,A)=>{const v=x[0],N=new FileReader;N.readAsDataURL(v),N.onload=async()=>{a({file:N.result,folderId:void 0,name:v.name,optimize:l},{onSuccess:P=>{i&&i(P),y(P)},onError:P=>{A(P)}})},N.onerror=P=>A(P)}),[a,l,i]),{getRootProps:m,getInputProps:f,isDragActive:b}=Ua.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:J.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",{...f()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(w.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(w.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(c.Switch,{checked:l,onCheckedChange:x=>{o(x)},onClick:x=>{x.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(w.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(c.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 Ba({close:e,onSelect:s,mode:n="image",assetId:a}){const l=g.useMemo(()=>[n],[n]),[o,u]=g.useState(null),[d,m]=g.useState(null),[f,b]=g.useState(null),[x,y]=g.useState({show:!1,file:""}),[A,v]=g.useState(!1),[N,P]=g.useState(a?"details":"grid"),[L,S]=g.useState(""),[T,O]=g.useState(""),[Y,z]=g.useState(1),[re]=g.useState(30),[W,$]=g.useState([]);g.useEffect(()=>{a&&(u(a),P("details"))},[a]),g.useEffect(()=>{const k=setTimeout(()=>{S(T),z(1)},300);return()=>clearTimeout(k)},[T]);const{data:te,isLoading:F}=Jo({search:L.toLowerCase().trim(),page:Y,limit:re}),ne=(te==null?void 0:te.assets)||[],B=(te==null?void 0:te.total)||0,q=Math.ceil(B/re),oe=Y<q,ce=Y>1,V=(ne==null?void 0:ne.length)>0,{mutate:j}=Qo(),{mutate:p,isPending:C}=Wo(),{mutate:D,isPending:U}=Yo(),E=g.useCallback(k=>{k>=1&&k<=q&&z(k)},[q]),H=g.useCallback(()=>{oe&&E(Y+1)},[Y,oe,E]),R=g.useCallback(()=>{ce&&E(Y-1)},[Y,ce,E]),M=k=>{O(k.target.value)},ue=g.useCallback(k=>{$(le=>h.find(le,{id:k.id})?[]:[k])},[!1]),xe=g.useCallback(()=>{$([])},[]),he=k=>{(k==null?void 0:k.length)!==0&&(s(h.pick(h.first(k||W),["id","url","width","height","description"])),e())},je=async k=>{m(k)},we=async()=>{d&&(b(d==null?void 0:d.id),await j(d.id,{onSuccess:()=>{b(null),m(null)},onError:()=>{b(null)}}),m(null))},ie=k=>{u(k.id),P("details")},Ne=async(k,le)=>{try{const Se=localStorage.getItem("chai_optimize_images")!=="false";le?(await p({file:k,folderId:void 0,name:x.name||"",optimize:Se}),y({show:!1,file:""})):(await D({id:x.id||"",file:k}),y({show:!1,file:""}))}catch(Se){console.error("Error saving edited image:",Se)}},Ie=g.useCallback(k=>{$([k])},[]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"max-w-[1232px] max-h-[1232px] w-[80vw] h-[80vh] space-y-4 flex flex-col",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),N==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(nc,{maxFileSize:10,allowedTypes:l,uploadAsset:p,isUpdatingAsset:U,isUploadingAsset:C,onUploaded:Ie}),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(w.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${T.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:M,value:T,className:"pl-8"})]}),W.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[W.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>xe(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>he(W),disabled:W.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:F?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"})]}):!F&&!V?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(w.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:L.length>0?"No assets found for your search: "+L:"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(k=>t.jsxs("div",{className:J.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",W.some(le=>le.id===k.id)?"border-blue-500":"hover:border-black/90",f&&(d==null?void 0:d.id)===k.id?"opacity-50 pointer-events-none":"",f===k.id?"opacity-50 pointer-events-none":""),onClick:()=>ue(k),onDoubleClick:()=>he([k]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[f===k.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(w.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,k.type==="image"?t.jsx("img",{src:`${k.thumbnailUrl||"/placeholder.svg"}?v=${(k==null?void 0:k.updatedAt)||k.createdAt}`,alt:k.name,className:`object-contain w-full h-full min-h-[80px] ${W.some(le=>le.id===k.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(w.Film,{className:"h-12 w-12 text-muted-foreground"}),k.thumbnailUrl&&t.jsx("img",{src:`${k.thumbnailUrl||"/placeholder.svg"}?v=${(k==null?void 0:k.updatedAt)||k.createdAt}`,alt:k.name,className:"absolute inset-0 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:k.name,children:k.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:sc((k==null?void 0:k.size)||0)})})]}),!W.some(le=>le.id===k.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(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),ie(k)},children:t.jsx(w.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),navigator.clipboard.writeText(k.url),K.toast.success("Asset URL copied to clipboard")},children:t.jsx(w.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),y({id:k.id,show:!0,file:k.url,name:k.name})},children:t.jsx(w.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),je(k)},children:t.jsx(w.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),W.some(le=>le.id===k.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(w.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},k.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(c.Button,{variant:"outline",size:"sm",onClick:R,disabled:!ce,children:"Previous"}),Array.from({length:Math.min(5,q)},(k,le)=>{const Se=le+1;return t.jsx(c.Button,{variant:Y===Se?"default":"outline",size:"sm",onClick:()=>E(Se),children:Se},Se)}),q>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(c.Button,{variant:Y===q?"default":"outline",size:"sm",onClick:()=>E(q),children:q})]}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:H,disabled:!oe,children:"Next"})]})})]})]}):t.jsx(ec,{assetId:o||a||"",onBack:()=>{P("grid"),u(null)},onEdit:k=>{y({id:k.id,show:!0,file:k.url,name:k.name})},onSave:async k=>{if(o){v(!0);try{const le=ne.find(Se=>Se.id===o);le&&await D(h.merge(le,{description:k}))}finally{v(!1)}}},isSaving:A})]}),x.show&&t.jsx(g.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(w.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(tc,{imageUrl:x.file,onSave:Ne,onClose:()=>y({show:!1,file:""}),defaultSavedImageName:x.name,isEditing:!!x.id})}),d&&t.jsx(c.Dialog,{open:!!d,onOpenChange:()=>m(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:we,children:"Delete"})]})]})})]})}const ac=Object.freeze(Object.defineProperty({__proto__:null,default:Ba},Symbol.toStringTag,{value:"Module"})),Ga=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,o]=g.useState(!1),u=()=>{i||o(!0)},d=()=>{o(!1)},m=b=>{const x=Array.isArray(b)?b[0]:b;x!=null&&x.url&&n(h.pick(x,["url","id"])),o(!1)},f=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:f,disabled:i,children:t.jsx(w.Trash2,{className:"h-4 w-4"})}),t.jsx(c.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(w.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(w.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(c.Dialog,{open:l,onOpenChange:o,children:t.jsxs(c.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(c.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(w.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(Ba,{close:d,onSelect:m,mode:"image",assetId:e})})]})})]})},rc=()=>{const{user:e,logout:s}=ze(),n=e==null?void 0:e.accessToken;return g.useCallback(async({url:a,method:r="GET",body:i={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const o=await fetch(a,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(i)});if(o.status===401)return console.log("Session expired",o),await s(),null;if(o.status===400)throw new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",o),o}},[n,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Ws;exports.ChaiBuilderPages=Ho;exports.Dynamic=zl;exports.For=pl;exports.ImagePicker=Ga;exports.Index=xl;exports.Match=vl;exports.NestedPathSelector=Ke;exports.PermissionChecker=Oe;exports.Portal=ql;exports.Show=yl;exports.Switch=jl;exports.addEventListener=da;exports.batch=Xi;exports.className=ua;exports.clearDelegatedEvents=_l;exports.convertRemToPixels=_o;exports.createComponent=Js;exports.createComputed=Xn;exports.createContext=al;exports.createEffect=Qs;exports.createMemo=De;exports.createRenderEffect=Qe;exports.createRoot=We;exports.createSignal=Ee;exports.createUniqueId=gl;exports.delegateEvents=ca;exports.deleteNestedDataByPath=kt;exports.displayValue=Ao;exports.getMutationStatusColor=wo;exports.getPreferredColorScheme=Lo;exports.getQueryStatusColor=Eo;exports.getQueryStatusColorByLabel=No;exports.getQueryStatusLabel=bo;exports.getSidedProp=So;exports.insert=fs;exports.mergeProps=Xs;exports.mutationSortFns=Io;exports.on=Zi;exports.onCleanup=St;exports.onMount=Zn;exports.registerLoginComponent=Ii;exports.serialize=ka;exports.setAttribute=ms;exports.sortFns=Po;exports.splitProps=ra;exports.spread=ha;exports.stringify=vo;exports.template=Il;exports.untrack=Ae;exports.updateNestedDataByPath=Pt;exports.use=ma;exports.useActivePage=Nt;exports.useBuilderPageData=Us;exports.useChaiAuth=ze;exports.useChaiFetch=rc;exports.useChaiUserInfo=st;exports.useContext=rl;exports.useCurrentPage=Me;exports.useFallbackLang=Rs;exports.useFetch=X;exports.useGotoPage=Ma;exports.useLanguagePages=Ve;exports.usePageTypes=Ce;exports.useTransition=nl;exports.useUpdateActivePageMetadata=Ko;exports.useUserRoleAndPermissions=Vn;exports.useWebsitePages=Yt;exports.useWebsiteSetting=Ze;