@chaibuilder/pages 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +0,0 @@
1
- "use strict";var Ds=e=>{throw TypeError(e)};var Ms=(e,t,n)=>t.has(e)||Ds("Cannot "+n);var G=(e,t,n)=>(Ms(e,t,"read from private field"),n?n.call(e):t.get(e)),ne=(e,t,n)=>t.has(e)?Ds("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),te=(e,t,n,r)=>(Ms(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);const s=require("react/jsx-runtime"),p=require("lodash-es"),ze=require("jotai"),y=require("react"),k=require("@tanstack/react-query"),$=require("sonner"),X=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),T=require("lucide-react"),Gt=require("date-fns"),Ws=require("@chaibuilder/runtime"),Ht=require("zod"),rr=require("@chaibuilder/sdk/web-blocks");function ar(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const ce=ar(y),Pe={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"},_={ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_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"},je="chaibuilder",Qs=async(e,t,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(t)});let ir=0;function Bs(e,t){const n=`atom${++ir}`,r={toString(){return n}};return typeof e=="function"?r.read=e:(r.init=e,r.read=or,r.write=lr),t&&(r.write=t),r}function or(e){return e(this)}function lr(e,t,n){return t(this,typeof n=="function"?n(e(this)):n)}const cr=Symbol(""),ur=e=>typeof(e==null?void 0:e.then)=="function";function dr(e=()=>{try{return window.localStorage}catch{return}},t){var n;let r,a;const i={getItem:(u,h)=>{var g,d;const b=x=>{if(x=x||"",r!==x){try{a=JSON.parse(x,t==null?void 0:t.reviver)}catch{return h}r=x}return a},v=(d=(g=e())==null?void 0:g.getItem(u))!=null?d:null;return ur(v)?v.then(b):b(v)},setItem:(u,h)=>{var g;return(g=e())==null?void 0:g.setItem(u,JSON.stringify(h,void 0))},removeItem:u=>{var h;return(h=e())==null?void 0:h.removeItem(u)}},o=u=>(h,g,d)=>u(h,b=>{let v;try{v=JSON.parse(b||"")}catch{v=d}g(v)});let l;try{l=(n=e())==null?void 0:n.subscribe}catch{}return!l&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(l=(u,h)=>{if(!(e()instanceof window.Storage))return()=>{};const g=d=>{d.storageArea===e()&&d.key===u&&h(d.newValue)};return window.addEventListener("storage",g),()=>{window.removeEventListener("storage",g)}}),l&&(i.subscribe=o(l)),i}const hr=dr();function mr(e,t,n=hr,r){const a=Bs(t);return a.onMount=o=>{o(n.getItem(e,t));let l;return n.subscribe&&(l=n.subscribe(e,o,t)),l},Bs(o=>o(a),(o,l,u)=>{const h=typeof u=="function"?u(o(a)):u;return h===cr?(l(a,t),n.removeItem(e)):h instanceof Promise?h.then(g=>(l(a,g),n.setItem(e,g))):(l(a,h),n.setItem(e,h))})}const fr=mr("__chai_user",null),Fe=()=>{const[e,t]=ze.useAtom(fr);return{isLoggedIn:!!e,user:e,setUser:t,logout:()=>{t(null)}}},gr=()=>{const{user:e,setUser:t,logout:n}=Fe(),r=es(),a=k.useQueryClient();return k.useQuery({queryKey:["refresh_token"],queryFn:async()=>{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e==null?void 0:e.accessToken}`},body:JSON.stringify({action:"REFRESH_TOKEN",data:{accessToken:e==null?void 0:e.accessToken,refreshToken:e==null?void 0:e.refreshToken}})});if(i.ok){const o=await i.json();t(o),a.invalidateQueries({queryKey:[je],refetchType:"all"})}else n()},retry:!1,enabled:!1})},pr=()=>{const{user:e}=Fe(),t=Ve("onSessionExpired"),n=y.useMemo(()=>e==null?void 0:e.accessToken,[e==null?void 0:e.accessToken]);return y.useCallback(async(r,a,i={})=>{if(!n){console.log("no auth token");return}try{const o=await fetch(r,{method:"POST",body:a,headers:{...i,Authorization:`Bearer ${n}`,"x-chai-upload":"true"}});if(o.status===401)throw console.log("session expired",a,o),t(),new Error("Session expired");if(o.status===400)throw console.log("Something went wrong",a,o),new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",a,o),o}},[n,t])},W=()=>{const{user:e}=Fe(),t=y.useMemo(()=>e==null?void 0:e.accessToken,[e==null?void 0:e.accessToken]),{refetch:n}=gr();return y.useCallback(async(r,a,i={})=>{if(t)try{const o=p.get(a,"action","").toLowerCase(),l=await Qs(r+(o?`?action=${o}`:""),a,{...i,Authorization:`Bearer ${t}`});if(l.status===401&&(console.log("Running refresh token",a,l),await n()),l.status===400)throw console.log("Something went wrong",a,l),new Error((await l.json()).error);return await l.json()}catch(o){throw console.log("Something went wrong",a,o),o}},[t,n])},Ys=()=>{const e=Z(),t=k.useQueryClient(),n=W();return k.useMutation({mutationFn:async r=>n(e,{action:_.RELEASE_LOCK,data:r}),onSuccess:(r,a)=>{t.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE,a.id??""]})}})},Xs=()=>{const e=Z(),t=k.useQueryClient(),n=W();return k.useMutation({mutationFn:async r=>n(e,{action:_.UPDATE_WEBSITE_SETTINGS,data:r}),onSuccess:(r,a)=>{var i;t.invalidateQueries({queryKey:[_.GET_WEBSITE_DRAFT_SETTINGS]}),(i=a==null?void 0:a.settings)!=null&&i.theme||$.toast.success("Website settings updated successfully.")},onError:r=>{$.toast.error("Failed to update website settings",{description:r.message})}})},xr=()=>{const e=Z(),t=k.useQueryClient(),n=W();return k.useMutation({mutationFn:async r=>n(e,{action:_.UPDATE_WEBSITE_DATA,data:r}),onSuccess:()=>{t.invalidateQueries({queryKey:[_.GET_WEBSITE_DATA]}),$.toast.success("Website data updated successfully.")},onError:r=>{$.toast.error("Failed to update website data",{description:r.message})}})};function Ae(){const[e,t]=y.useState(new URLSearchParams(window.location.search));return y.useEffect(()=>{const n=()=>{t(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,t]}const yr=ze.atom({}),Zs=()=>ze.useAtom(yr),vr=()=>{const[e]=Ae(),t=e.get("page"),n=y.useRef(""),{mutate:r}=Ys();y.useEffect(()=>{!p.isEmpty(n.current)&&t!==n.current&&r({id:n.current}),n.current=t},[t,r,n])},Ve=(e,t)=>{const[n]=Zs();return p.get(n,e,t)},Z=()=>Ve("apiUrl","/chai/api"),es=()=>Ve("usersApiUrl","/chai/users"),mt=()=>{const e=Z(),[t]=Ae(),n=t.get("page"),r=W();return k.useQuery({queryKey:[je,_.GET_LANGUAGE_PAGES,n],initialData:[],queryFn:async()=>{if(!n)return null;const a=await r(e,{action:_.GET_LANGUAGE_PAGES,data:{id:n}});return p.reverse(p.sortBy(a,"primaryPage"))},enabled:!!n})},ft=()=>{const e=Z(),t=W();return k.useQuery({queryKey:[_.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>t(e,{action:_.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},Js=e=>{const{fallbackLang:t}=X.useLanguages(),{data:n}=ft(),{data:r,isFetching:a}=mt(),i=y.useMemo(()=>{const o={[t]:!0};return p.each(p.get(n,"languages"),l=>{const u=p.find(r,{lang:l});o[l]=!!u}),o},[t,r,n]);return a||p.isEmpty(e)||e&&i[e]},vs=()=>{const e=k.useQueryClient(),{data:t}=k.useQuery({queryKey:["chaibuilder",_.AI_CONTEXT],initialData:"",queryFn:()=>""});return{setAiContext:y.useCallback(r=>{e.setQueryData([_.AI_CONTEXT],r)},[e]),aiContext:t}},Rt=()=>{const e=W(),t=Z();return k.useQuery({queryKey:[je,_.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(t,{action:_.GET_WEBSITE_PAGES})||[]})},Er=ze.atom({lastSaved:void 0}),Es=()=>ze.useAtom(Er),we=()=>{const[e]=Ae(),t=e.get("page"),{data:n,isFetching:r}=Rt();return{data:y.useMemo(()=>p.find(n,{id:t})||{},[n,t]),isFetching:r}},gt=e=>{const t=es(),n=W();return k.useQuery({queryKey:[je,"chaiUserInfo",e],queryFn:async()=>await n(t,{action:_.GET_CHAI_USER,data:{userId:e}}),enabled:!!e&&e!=="EXPIRED"})},br=ze.atom(void 0),Ut=()=>{const[e]=Ae(),t=e.get("page"),{user:n}=Fe(),[r,a]=ze.useAtom(br);return y.useMemo(()=>({isLocked:t&&(n==null?void 0:n.id)!==r,currentEditor:r,setCurrentEditor:i=>a(i)}),[n==null?void 0:n.id,r,t,a])},en=()=>{const[e]=Ae(),t=e.get("page"),n=Z(),{setAiContext:r}=vs(),{setCurrentEditor:a}=Ut(),[,i]=Es(),o=W();return k.useQuery({queryKey:[je,_.GET_DRAFT_PAGE,t],staleTime:1/0,gcTime:1/0,queryFn:async()=>{a("");const l=await o(n,{action:_.GET_DRAFT_PAGE,data:{id:t,draft:!0}});a(l.currentEditor);const u=l.blocks??[],h=p.find(u,{_type:"@chai/ai-context"});return r(p.get(h,"_value","")||""),i(g=>({...g,lastSaved:l.lastSaved})),u},enabled:!!t})},tn=({pageType:e,lang:t})=>{const n=Z(),r=W();return k.useQuery({queryKey:[je,_.GET_BUILDER_PAGE_DATA,e,t],initialData:{},queryFn:async()=>r(n,{action:_.GET_BUILDER_PAGE_DATA,data:{pageType:e,lang:t}}),enabled:!!e&&!!t})};function jr({avatar:e,name:t,email:n,onTakeOver:r,currentEditor:a}){const[i,o]=y.useState(!1),l=()=>{o(!1),r()};return s.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-14 bg-black/30 backdrop-blur-sm",children:s.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[s.jsx(c.CardHeader,{className:"space-y-1",children:s.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[s.jsx(T.LockIcon,{className:"w-6 h-6 text-yellow-500"}),a==="EXPIRED"?"Editing access timed out":"Page locked for editing"]})}),s.jsx(c.CardContent,{className:"grid gap-4",children:a==="EXPIRED"?s.jsx("div",{children:s.jsx("p",{children:"Your editing access has been paused due to inactivity. Please refresh the page to continue"})}):s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center space-x-4",children:[e?s.jsx("img",{src:e,alt:t,className:"w-12 h-12 border border-gray-300 rounded-full"}):s.jsx(T.UserIcon,{className:"w-12 h-12 p-2 border border-gray-300 rounded-full"}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h3",{className:"font-semibold",children:t}),n&&s.jsx("p",{className:"text-sm text-muted-foreground",children:n})]})]}),s.jsx("div",{className:"text-sm mt-4",children:s.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),s.jsx(c.CardFooter,{children:a==="EXPIRED"?s.jsx("div",{children:s.jsx(c.Button,{className:"w-full",onClick:()=>window.location.reload(),variant:"destructive",children:"Refresh"})}):s.jsxs(c.AlertDialog,{open:i,onOpenChange:o,children:[s.jsx(c.AlertDialogTrigger,{asChild:!0,children:s.jsxs("span",{className:"flex flex-col items-center",children:[s.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take Over"}),s.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."})]})}),s.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[s.jsxs(c.AlertDialogHeader,{children:[s.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),s.jsxs(c.AlertDialogDescription,{children:[s.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[s.jsx(T.AlertTriangleIcon,{className:"w-5 h-5"}),s.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),s.jsx("br",{}),s.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",t," will lose their editing access."]})]})]}),s.jsxs(c.AlertDialogFooter,{children:[s.jsx(c.AlertDialogCancel,{children:"Cancel"}),s.jsx(c.AlertDialogAction,{onClick:l,children:"Yes, Take Over"})]})]})]})})]})})}const Sr=()=>{const{isLocked:e,currentEditor:t}=Ut(),{data:n}=gt(t),[r]=Ae(),a=r.get("page"),{mutate:i}=Ys(),{isFetching:o}=en(),l=y.useCallback(()=>{i({id:a})},[a,i]);return!e||o?s.jsx("div",{className:""}):s.jsx(jr,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",currentEditor:t??null,onTakeOver:l})},wr=()=>{const[e,t]=Ae(),n=e.get("lang"),r=Js(n),{setSelectedLang:a}=X.useLanguages(),i=()=>{const l=new URLSearchParams(window.location.search);l.delete("lang");const u=l.toString(),h=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",h),t(l),a(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(r)return null;const o=p.get(Pe,n);return s.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-14 bg-black/30 backdrop-blur-sm",children:s.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[s.jsx(c.CardHeader,{className:"space-y-1",children:s.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[s.jsx(T.LockIcon,{className:"w-6 h-6 text-yellow-500"}),'Page missing for "',o,'" language.']})}),s.jsx(c.CardContent,{className:"grid gap-4",children:s.jsxs("div",{children:['Page is not available in the "',o,'" language. Either create the page in the "',o,'" language or switch to the base language.']})}),s.jsx(c.CardFooter,{children:s.jsx(c.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},Nr=e=>{const t=Z(),n=W();return k.useMutation({mutationFn:async r=>n(t,{action:_.UPSERT_LIBRARY_ITEM,data:r}),onSuccess:r=>{e(r)},onError:r=>{console.error("Error saving block:",r),$.toast.error("Failed to save block",{description:r instanceof Error?r.message:"Unknown error"})}})},Ar=e=>{const t=Z(),n=W();return k.useQuery({queryKey:[je,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(t,{action:_.GET_LIBRARY_ITEM,data:{id:e}})}catch(r){throw console.error(r),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},Tr=e=>{const t=Z(),n=W();return k.useMutation({mutationFn:async r=>n(t,{action:_.DELETE_LIBRARY_ITEM,data:{id:r}}),onSuccess:()=>{e()},onError:r=>{console.error("Error deleting block:",r),$.toast.error("Failed to delete block",{description:r instanceof Error?r.message:"Unknown error"})}})},Cr=({blockId:e,libBlockId:t,isOpen:n,onClose:r,blockName:a,trigger:i})=>{const[o,l]=y.useState(!1),u=X.useUpdateBlocksPropsRealtime(),h=Tr(()=>{u([e],{_libBlockId:void 0}),$.toast.success("Block deleted successfully"),l(!1),r()}),g=()=>{l(!0),h.mutate(t)},d=s.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:o,children:[s.jsx(T.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return s.jsxs(c.Popover,{open:n,onOpenChange:b=>!b&&r(),children:[s.jsx(c.PopoverTrigger,{asChild:!0,children:i||d}),s.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:s.jsxs("div",{className:"space-y-3",children:[s.jsx("h4",{className:"font-medium",children:"Delete Block"}),s.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",s.jsxs("span",{className:"font-medium",children:[' "',a,'"']}),"?"]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:r,disabled:o,children:"Cancel"}),s.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:g,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})},Pr=({blockId:e,libBlockId:t,blockName:n,size:r="sm",className:a="",close:i})=>{const[o,l]=y.useState(!1);return s.jsx(Cr,{blockId:e,libBlockId:t,isOpen:o,onClose:()=>{l(!1),i()},blockName:n,trigger:s.jsxs(c.Button,{type:"button",variant:"destructive",size:r,className:a,onClick:()=>l(!0),children:[s.jsx(T.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Ir=()=>{const e=Z(),t=W(),n=k.useQueryClient(),{data:r=[],isLoading:a,error:i}=k.useQuery({queryKey:[je,"library-groups"],queryFn:async()=>{try{return await t(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:o,isPending:l}=k.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return t(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:["library-groups"]}),$.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),$.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:r,isLoading:a,error:i,createGroup:o,isCreating:l}},_r=({value:e,onChange:t})=>{const[n,r]=y.useState(!1),[a,i]=y.useState(""),o=y.useRef(null),{groups:l}=Ir(),[u,h]=y.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"}]),g=y.useMemo(()=>[...l,...u.filter(v=>!l.some(x=>x.id===v.id))],[l,u]),d=()=>{const v=a.trim();if(!v)return;const x={id:v,name:v};h(w=>[...w,x]),t(x.id),i(""),r(!1)};y.useEffect(()=>{n&&o.current&&o.current.focus()},[n]);const b=v=>{v.key==="Enter"&&(v.preventDefault(),d())};return y.useEffect(()=>{e&&!g.some(v=>v.id===e)&&t("")},[e,g,t]),n?s.jsxs("div",{className:"space-y-2",children:[s.jsx(c.Input,{ref:o,placeholder:"Enter new group name",value:a,onChange:v=>i(v.target.value),onKeyDown:b}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>r(!1),children:"Cancel"}),s.jsx(c.Button,{size:"sm",onClick:d,children:"Create"})]})]}):s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:v=>t(v.target.value),children:[s.jsx("option",{value:"",children:"Select a group"}),l.length>0&&s.jsx("optgroup",{label:"Library Groups",children:l.map(v=>s.jsx("option",{value:v.id,children:v.name},`lib-${v.id}`))}),u.length>0&&s.jsx("optgroup",{label:"Predefined Groups",children:u.filter(v=>!l.some(x=>x.id===v.id)).map(v=>s.jsx("option",{value:v.id,children:v.name},`local-${v.id}`))})]}),s.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>r(!0),children:s.jsx(T.Plus,{className:"h-4 w-4"})})]})},kr=1*1024*1024,Lr=({value:e,onChange:t})=>{const[n,r]=y.useState(!1),a=y.useRef(null),i=y.useCallback(u=>{var g;const h=(g=u.target.files)==null?void 0:g[0];if(h){if(h.size>kr){$.toast.error("File too large",{description:`Maximum file size is 1mb. Selected file is ${(h.size/1024/1024).toFixed(2)}MB.`}),a.current&&(a.current.value="");return}try{r(!0);const d=new FileReader;d.onloadend=()=>{t(d.result),r(!1)},d.readAsDataURL(h)}catch(d){console.error("Error reading file:",d),r(!1),$.toast.error("Failed to process image",{description:d instanceof Error?d.message:"Unknown error"})}}},[t]),o=()=>{t(""),a.current&&(a.current.value="")},l=()=>{var u;(u=a.current)==null||u.click()};return s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(c.Input,{type:"file",ref:a,onChange:i,accept:"image/*",className:"hidden"}),s.jsx(c.Button,{type:"button",variant:"outline",onClick:l,disabled:n,className:"w-full",children:n?s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(T.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&s.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:o,children:s.jsx(T.X,{className:"h-4 w-4"})})]}),e&&s.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:s.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},ue={...X.PERMISSIONS,ADD_PAGE:"add_page",EDIT_PAGE:"edit_page",EDIT_SLUG:"edit_slug",DELETE_PAGE:"delete_page",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"},Dr=e=>{const{blocks:t,close:n,blockId:r}=e,{getPartailBlocks:a}=X.usePartailBlocksStore(),i=t.find(N=>N._id===r),o=i==null?void 0:i._libBlockId,l=!!o,u=y.useMemo(()=>t.some(N=>N._type==="PartialBlock"||N._type==="GlobalBlock"),[t]),h=y.useMemo(()=>{let N=[];for(const I of t)if(I._type==="PartialBlock"||I._type==="GlobalBlock"){const M=a(I.partialBlockId);p.set(M,"0._parent",I._parent),N=[...N,...M]}else N.push(I);return N},[t,a]),[g,d]=y.useState(""),[b,v]=y.useState(""),[x,w]=y.useState(""),[E,C]=y.useState(""),[R,j]=y.useState({}),[S,P]=y.useState(!1),[B,ee]=y.useState(l),[ie,L]=y.useState(!1),{hasPermission:H}=X.usePermissions(),A=H(ue.DELETE_LIBRARY_BLOCK),F=X.useUpdateBlocksPropsRealtime(),se=()=>{F([r],{_libBlockId:void 0}),$.toast.success("Block delinked from library"),n()},{data:he,isLoading:Q,isError:de}=Ar(o);y.useEffect(()=>{de&&l&&(L(!0),ee(!1))},[de,l]),y.useEffect(()=>{he&&!Q&&(d(he.name||""),v(he.group||""),w(he.description||""),C(he.preview||""),ee(!1))},[he,Q]),y.useEffect(()=>{const N=g.trim().length>=2,I=b.trim()!=="";P(N&&I&&!u)},[g,b,u]);const q=()=>{const N={};return g.trim()?g.length<2&&(N.name="Name must be at least 2 characters"):N.name="Name is required",b||(N.group="Group is required"),j(N),Object.keys(N).length===0&&!u},{resetLibrary:pe}=X.useLibraryBlocks({id:""}),Le=Nr(N=>{l||F([r],{_libBlockId:N.id}),$.toast.success(`Block ${l?"updated":"saved"} successfully`),pe(N.library),n()}),f=async N=>{if(N.preventDefault(),!q())return;const I=h.map(M=>(p.has(M,"_libBlockId")&&delete M._libBlockId,M));Le.mutate({name:g.trim(),group:b,blocks:I,description:x.trim(),...E&&E.startsWith("data:")?{previewImage:E}:{},...l?{id:o}:{}})},m=Le.isPending;return B||Q?s.jsx("div",{className:"flex items-center justify-center p-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):ie?s.jsxs("div",{className:"p-6 space-y-4",children:[s.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),s.jsx(c.Button,{onClick:se,variant:"destructive",children:"Delink Block"})]})]}):s.jsxs("div",{children:[u&&s.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[s.jsx(T.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),s.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"})]})]}),s.jsxs("form",{onSubmit:f,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(c.Label,{htmlFor:"name",className:R.name?"text-destructive":"",children:"Name"}),s.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:g,onChange:N=>d(N.target.value),className:R.name?"border-destructive":""}),R.name&&s.jsx("p",{className:"text-xs text-destructive",children:R.name})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(c.Label,{htmlFor:"group",className:R.group?"text-destructive":"",children:"Group"}),s.jsx(_r,{value:b,onChange:v}),R.group&&s.jsx("p",{className:"text-xs text-destructive",children:R.group})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),s.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:x,onChange:N=>w(N.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),s.jsx(Lr,{value:E,onChange:C}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[l&&A&&s.jsx(Pr,{blockId:r,libBlockId:o,blockName:g,className:"mr-auto",close:n}),s.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:m,children:"Cancel"}),s.jsx(c.Button,{type:"submit",disabled:m||!S,children:m?"Saving...":l?"Update Block":"Save Block"})]})]})]})},O={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."},Mr={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ee=()=>{const e=Z(),t=W();return k.useQuery({queryKey:[je,_.GET_PAGE_TYPES],initialData:[],queryFn:async()=>t(e,{action:_.GET_PAGE_TYPES})})},Br=e=>{const{data:t}=Ee();return y.useMemo(()=>t==null?void 0:t.find(n=>n.key===e),[t,e])},Gr=()=>{const e=Z(),t=W();return k.useMutation({mutationFn:async({pageType:n,query:r})=>{try{return t(e,{action:_.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(r)&&r.length>0?r[0]:r}})||[]}catch(a){return console.error(a),[]}}})},sn=()=>{const e=Z(),t=k.useQueryClient(),n=W(),{data:r}=Ee();return k.useMutation({mutationFn:async a=>(a.template&&console.log("Creating page from template:",a.template),n(e,{action:_.CREATE_PAGE,data:a})),onSuccess:(a,i)=>{var l;i&&(i!=null&&i.primaryPage)?t.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):t.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]});const o=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((l=p.find(r,{key:i.pageType}))==null?void 0:l.name)+" added successfully":"New page added successfully";$.toast.success(o)},onError:(a,i)=>{const o=p.find(r,{key:i.pageType});$.toast.error(`Failed to add new ${o!=null&&o.hasSlug?"page":o.name}.`,{description:p.get(Mr,a.message,a.message)})}})},bs=()=>{const e=Z(),t=k.useQueryClient(),n=W(),{data:r}=Ee();return k.useMutation({mutationFn:async a=>await n(e,{action:_.UPDATE_PAGE,data:a}),onSuccess:(a,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?t.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):t.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:(a,i)=>{const o=p.find(r,{key:i.pageType});$.toast.error(`Failed to update ${o!=null&&o.hasSlug?"page":o.name}.`,{description:a.message})}})},Rr=()=>{const e=Z(),t=k.useQueryClient(),n=W(),{data:r}=Ee();return k.useMutation({mutationFn:async a=>n(e,{action:_.DELETE_PAGE,data:{id:a==null?void 0:a.id}}),onSuccess:(a,i)=>{if(a.code==="PAGE_LOCKED"){$.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?t.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):t.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:(a,i)=>{const o=p.find(r,{key:i.pageType});$.toast.error(`Failed to delete ${o!=null&&o.hasSlug?"page":o.name}.`,{description:a.message})}})},Ur=()=>{const e=Z(),t=k.useQueryClient(),n=W(),{data:r}=Ee();return k.useMutation({mutationFn:async a=>n(e,{action:_.TAKE_OFFLINE,data:{id:a==null?void 0:a.id}}),onSuccess:(a,i)=>{i&&(i!=null&&i.primaryPage)?t.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):t.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]});const o=p.find(r,{key:i.pageType});$.toast.success(o!=null&&o.hasSlug?O.PAGE_UNPUBLISH_SUCCESS:"New "+o.name+" added successfully.")},onError:(a,i)=>{const o=p.find(r,{key:i.pageType});$.toast.error(`Failed to take offline ${o!=null&&o.hasSlug?"page":o.name}.`,{description:a.message})}})},js=()=>{const e=Z(),t=W(),n=k.useQueryClient(),{data:r}=we();return k.useMutation({mutationFn:async({ids:a})=>t(e,{action:_.PUBLISH_CHANGES,data:{ids:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[_.GET_CHANGES]}),n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,r==null?void 0:r.id]})},onError:()=>{$.toast.error("Failed to publish pages.")}})},Or=()=>{const e=Z(),t=W(),n=k.useQueryClient();return k.useMutation({mutationFn:async r=>{var a;return t(e,{action:_.MARK_AS_TEMPLATE,data:{id:(a=r.page)==null?void 0:a.id,name:r.name,description:r.description,pageType:r.pageType,previewImage:r.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),$.toast.success("Page marked as template successfully.")},onError:()=>{$.toast.error("Failed to mark page as template.")}})},Fr=()=>{const e=Z(),t=W(),n=k.useQueryClient();return k.useMutation({mutationFn:async r=>t(e,{action:_.UNMARK_AS_TEMPLATE,data:{id:r==null?void 0:r.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),$.toast.success("Page unmarked as template successfully.")},onError:()=>{$.toast.error("Failed to unmark page as template.")}})},qr=()=>{const e=Z(),t=W(),n=k.useQueryClient();return k.useMutation({mutationFn:async({id:r,slug:a})=>t(e,{action:_.CHANGE_SLUG,data:{id:r,slug:a}}),onSuccess:(r,{primaryPage:a})=>{$.toast.success(O.SLUG_CHANGE_SUCCESS),a?n.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,a]}):n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:()=>{$.toast.error("Failed to change slug")}})};var Ss={};(function e(t,n,r,a){var i=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),o=typeof Path2D=="function"&&typeof DOMMatrix=="function",l=function(){if(!t.OffscreenCanvas)return!1;var f=new OffscreenCanvas(1,1),m=f.getContext("2d");m.fillRect(0,0,1,1);var N=f.transferToImageBitmap();try{m.createPattern(N,"no-repeat")}catch{return!1}return!0}();function u(){}function h(f){var m=n.exports.Promise,N=m!==void 0?m:t.Promise;return typeof N=="function"?new N(f):(f(u,u),null)}var g=function(f,m){return{transform:function(N){if(f)return N;if(m.has(N))return m.get(N);var I=new OffscreenCanvas(N.width,N.height),M=I.getContext("2d");return M.drawImage(N,0,0),m.set(N,I),I},clear:function(){m.clear()}}}(l,new Map),d=function(){var f=Math.floor(16.666666666666668),m,N,I={},M=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(m=function(K){var z=Math.random();return I[z]=requestAnimationFrame(function D(V){M===V||M+f-1<V?(M=V,delete I[z],K()):I[z]=requestAnimationFrame(D)}),z},N=function(K){I[K]&&cancelAnimationFrame(I[K])}):(m=function(K){return setTimeout(K,f)},N=function(K){return clearTimeout(K)}),{frame:m,cancel:N}}(),b=function(){var f,m,N={};function I(M){function K(z,D){M.postMessage({options:z||{},callback:D})}M.init=function(D){var V=D.transferControlToOffscreen();M.postMessage({canvas:V},[V])},M.fire=function(D,V,oe){if(m)return K(D,null),m;var me=Math.random().toString(36).slice(2);return m=h(function(le){function fe(ye){ye.data.callback===me&&(delete N[me],M.removeEventListener("message",fe),m=null,g.clear(),oe(),le())}M.addEventListener("message",fe),K(D,me),N[me]=fe.bind(null,{data:{callback:me}})}),m},M.reset=function(){M.postMessage({reset:!0});for(var D in N)N[D](),delete N[D]}}return function(){if(f)return f;if(!r&&i){var M=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
2
- `);try{f=new Worker(URL.createObjectURL(new Blob([M])))}catch(K){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",K),null}I(f)}return f}}(),v={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function x(f,m){return m?m(f):f}function w(f){return f!=null}function E(f,m,N){return x(f&&w(f[m])?f[m]:v[m],N)}function C(f){return f<0?0:Math.floor(f)}function R(f,m){return Math.floor(Math.random()*(m-f))+f}function j(f){return parseInt(f,16)}function S(f){return f.map(P)}function P(f){var m=String(f).replace(/[^0-9a-f]/gi,"");return m.length<6&&(m=m[0]+m[0]+m[1]+m[1]+m[2]+m[2]),{r:j(m.substring(0,2)),g:j(m.substring(2,4)),b:j(m.substring(4,6))}}function B(f){var m=E(f,"origin",Object);return m.x=E(m,"x",Number),m.y=E(m,"y",Number),m}function ee(f){f.width=document.documentElement.clientWidth,f.height=document.documentElement.clientHeight}function ie(f){var m=f.getBoundingClientRect();f.width=m.width,f.height=m.height}function L(f){var m=document.createElement("canvas");return m.style.position="fixed",m.style.top="0px",m.style.left="0px",m.style.pointerEvents="none",m.style.zIndex=f,m}function H(f,m,N,I,M,K,z,D,V){f.save(),f.translate(m,N),f.rotate(K),f.scale(I,M),f.arc(0,0,1,z,D,V),f.restore()}function A(f){var m=f.angle*(Math.PI/180),N=f.spread*(Math.PI/180);return{x:f.x,y:f.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:f.startVelocity*.5+Math.random()*f.startVelocity,angle2D:-m+(.5*N-Math.random()*N),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:f.color,shape:f.shape,tick:0,totalTicks:f.ticks,decay:f.decay,drift:f.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:f.gravity*3,ovalScalar:.6,scalar:f.scalar,flat:f.flat}}function F(f,m){m.x+=Math.cos(m.angle2D)*m.velocity+m.drift,m.y+=Math.sin(m.angle2D)*m.velocity+m.gravity,m.velocity*=m.decay,m.flat?(m.wobble=0,m.wobbleX=m.x+10*m.scalar,m.wobbleY=m.y+10*m.scalar,m.tiltSin=0,m.tiltCos=0,m.random=1):(m.wobble+=m.wobbleSpeed,m.wobbleX=m.x+10*m.scalar*Math.cos(m.wobble),m.wobbleY=m.y+10*m.scalar*Math.sin(m.wobble),m.tiltAngle+=.1,m.tiltSin=Math.sin(m.tiltAngle),m.tiltCos=Math.cos(m.tiltAngle),m.random=Math.random()+2);var N=m.tick++/m.totalTicks,I=m.x+m.random*m.tiltCos,M=m.y+m.random*m.tiltSin,K=m.wobbleX+m.random*m.tiltCos,z=m.wobbleY+m.random*m.tiltSin;if(f.fillStyle="rgba("+m.color.r+", "+m.color.g+", "+m.color.b+", "+(1-N)+")",f.beginPath(),o&&m.shape.type==="path"&&typeof m.shape.path=="string"&&Array.isArray(m.shape.matrix))f.fill(q(m.shape.path,m.shape.matrix,m.x,m.y,Math.abs(K-I)*.1,Math.abs(z-M)*.1,Math.PI/10*m.wobble));else if(m.shape.type==="bitmap"){var D=Math.PI/10*m.wobble,V=Math.abs(K-I)*.1,oe=Math.abs(z-M)*.1,me=m.shape.bitmap.width*m.scalar,le=m.shape.bitmap.height*m.scalar,fe=new DOMMatrix([Math.cos(D)*V,Math.sin(D)*V,-Math.sin(D)*oe,Math.cos(D)*oe,m.x,m.y]);fe.multiplySelf(new DOMMatrix(m.shape.matrix));var ye=f.createPattern(g.transform(m.shape.bitmap),"no-repeat");ye.setTransform(fe),f.globalAlpha=1-N,f.fillStyle=ye,f.fillRect(m.x-me/2,m.y-le/2,me,le),f.globalAlpha=1}else if(m.shape==="circle")f.ellipse?f.ellipse(m.x,m.y,Math.abs(K-I)*m.ovalScalar,Math.abs(z-M)*m.ovalScalar,Math.PI/10*m.wobble,0,2*Math.PI):H(f,m.x,m.y,Math.abs(K-I)*m.ovalScalar,Math.abs(z-M)*m.ovalScalar,Math.PI/10*m.wobble,0,2*Math.PI);else if(m.shape==="star")for(var Y=Math.PI/2*3,Se=4*m.scalar,Te=8*m.scalar,Ce=m.x,De=m.y,qe=5,Ie=Math.PI/qe;qe--;)Ce=m.x+Math.cos(Y)*Te,De=m.y+Math.sin(Y)*Te,f.lineTo(Ce,De),Y+=Ie,Ce=m.x+Math.cos(Y)*Se,De=m.y+Math.sin(Y)*Se,f.lineTo(Ce,De),Y+=Ie;else f.moveTo(Math.floor(m.x),Math.floor(m.y)),f.lineTo(Math.floor(m.wobbleX),Math.floor(M)),f.lineTo(Math.floor(K),Math.floor(z)),f.lineTo(Math.floor(I),Math.floor(m.wobbleY));return f.closePath(),f.fill(),m.tick<m.totalTicks}function se(f,m,N,I,M){var K=m.slice(),z=f.getContext("2d"),D,V,oe=h(function(me){function le(){D=V=null,z.clearRect(0,0,I.width,I.height),g.clear(),M(),me()}function fe(){r&&!(I.width===a.width&&I.height===a.height)&&(I.width=f.width=a.width,I.height=f.height=a.height),!I.width&&!I.height&&(N(f),I.width=f.width,I.height=f.height),z.clearRect(0,0,I.width,I.height),K=K.filter(function(ye){return F(z,ye)}),K.length?D=d.frame(fe):le()}D=d.frame(fe),V=le});return{addFettis:function(me){return K=K.concat(me),oe},canvas:f,promise:oe,reset:function(){D&&d.cancel(D),V&&V()}}}function he(f,m){var N=!f,I=!!E(m||{},"resize"),M=!1,K=E(m,"disableForReducedMotion",Boolean),z=i&&!!E(m||{},"useWorker"),D=z?b():null,V=N?ee:ie,oe=f&&D?!!f.__confetti_initialized:!1,me=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,le;function fe(Y,Se,Te){for(var Ce=E(Y,"particleCount",C),De=E(Y,"angle",Number),qe=E(Y,"spread",Number),Ie=E(Y,"startVelocity",Number),Yn=E(Y,"decay",Number),Xn=E(Y,"gravity",Number),Zn=E(Y,"drift",Number),Is=E(Y,"colors",S),Jn=E(Y,"ticks",Number),_s=E(Y,"shapes"),er=E(Y,"scalar"),tr=!!E(Y,"flat"),ks=B(Y),Ls=Ce,rs=[],sr=f.width*ks.x,nr=f.height*ks.y;Ls--;)rs.push(A({x:sr,y:nr,angle:De,spread:qe,startVelocity:Ie,color:Is[Ls%Is.length],shape:_s[R(0,_s.length)],ticks:Jn,decay:Yn,gravity:Xn,drift:Zn,scalar:er,flat:tr}));return le?le.addFettis(rs):(le=se(f,rs,V,Se,Te),le.promise)}function ye(Y){var Se=K||E(Y,"disableForReducedMotion",Boolean),Te=E(Y,"zIndex",Number);if(Se&&me)return h(function(Ie){Ie()});N&&le?f=le.canvas:N&&!f&&(f=L(Te),document.body.appendChild(f)),I&&!oe&&V(f);var Ce={width:f.width,height:f.height};D&&!oe&&D.init(f),oe=!0,D&&(f.__confetti_initialized=!0);function De(){if(D){var Ie={getBoundingClientRect:function(){if(!N)return f.getBoundingClientRect()}};V(Ie),D.postMessage({resize:{width:Ie.width,height:Ie.height}});return}Ce.width=Ce.height=null}function qe(){le=null,I&&(M=!1,t.removeEventListener("resize",De)),N&&f&&(document.body.contains(f)&&document.body.removeChild(f),f=null,oe=!1)}return I&&!M&&(M=!0,t.addEventListener("resize",De,!1)),D?D.fire(Y,Ce,qe):fe(Y,Ce,qe)}return ye.reset=function(){D&&D.reset(),le&&le.reset()},ye}var Q;function de(){return Q||(Q=he(null,{useWorker:!0,resize:!0})),Q}function q(f,m,N,I,M,K,z){var D=new Path2D(f),V=new Path2D;V.addPath(D,new DOMMatrix(m));var oe=new Path2D;return oe.addPath(V,new DOMMatrix([Math.cos(z)*M,Math.sin(z)*M,-Math.sin(z)*K,Math.cos(z)*K,N,I])),oe}function pe(f){if(!o)throw new Error("path confetti are not supported in this browser");var m,N;typeof f=="string"?m=f:(m=f.path,N=f.matrix);var I=new Path2D(m),M=document.createElement("canvas"),K=M.getContext("2d");if(!N){for(var z=1e3,D=z,V=z,oe=0,me=0,le,fe,ye=0;ye<z;ye+=2)for(var Y=0;Y<z;Y+=2)K.isPointInPath(I,ye,Y,"nonzero")&&(D=Math.min(D,ye),V=Math.min(V,Y),oe=Math.max(oe,ye),me=Math.max(me,Y));le=oe-D,fe=me-V;var Se=10,Te=Math.min(Se/le,Se/fe);N=[Te,0,0,Te,-Math.round(le/2+D)*Te,-Math.round(fe/2+V)*Te]}return{type:"path",path:m,matrix:N}}function Le(f){var m,N=1,I="#000000",M='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof f=="string"?m=f:(m=f.text,N="scalar"in f?f.scalar:N,M="fontFamily"in f?f.fontFamily:M,I="color"in f?f.color:I);var K=10*N,z=""+K+"px "+M,D=new OffscreenCanvas(K,K),V=D.getContext("2d");V.font=z;var oe=V.measureText(m),me=Math.ceil(oe.actualBoundingBoxRight+oe.actualBoundingBoxLeft),le=Math.ceil(oe.actualBoundingBoxAscent+oe.actualBoundingBoxDescent),fe=2,ye=oe.actualBoundingBoxLeft+fe,Y=oe.actualBoundingBoxAscent+fe;me+=fe+fe,le+=fe+fe,D=new OffscreenCanvas(me,le),V=D.getContext("2d"),V.font=z,V.fillStyle=I,V.fillText(m,ye,Y);var Se=1/N;return{type:"bitmap",bitmap:D.transferToImageBitmap(),matrix:[Se,0,0,Se,-me*Se/2,-le*Se/2]}}n.exports=function(){return de().apply(this,arguments)},n.exports.reset=function(){de().reset()},n.exports.create=he,n.exports.shapeFromPath=pe,n.exports.shapeFromText=Le})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Ss,!1);const Hr=Ss.exports;Ss.exports.create;const Kr={particleCount:350,spread:120,origin:{y:.6},angle:90},zr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},zt=e=>{let t=zr[e];t||(t={});const n={...Kr,...t};Hr(n)},Vr=()=>{const[e]=X.useTheme(),{mutate:t,isPending:n}=js(),{mutateAsync:r,isPending:a}=Xs(),i=()=>{r({settings:{theme:e}})},o=()=>{t({ids:["THEME"]},{onSuccess:()=>{zt("BOTTOM_RIGHT")}})};return s.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[s.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||a,onClick:i,children:"Save draft"}),s.jsx(c.Button,{size:"sm",disabled:n||a,onClick:o,children:"Publish"})]})},$r=({page:e,onClose:t})=>{const[n,r]=y.useState(e.slug||""),{mutate:a,isPending:i}=qr(),{data:o}=Ee(),l=p.find(o,{key:e==null?void 0:e.pageType}),u=g=>{if(g.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Pe).some(v=>n===`/${v}`||p.startsWith(n,`/${v}/`))){$.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}a({...e,slug:n},{onSuccess:t})},h=(e==null?void 0:e.lang)||"";return s.jsx(c.Dialog,{open:!!e,onOpenChange:t,children:s.jsxs(c.DialogContent,{children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Change Slug"}),s.jsx(c.DialogDescription,{className:"text-xs",children:s.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[s.jsx(T.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),s.jsxs("form",{onSubmit:u,children:[s.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Type:"}),s.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(l==null?void 0:l.name)||(e==null?void 0:e.pageType)]})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Name:"}),s.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",s.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",h]})]}),s.jsx(c.Input,{id:"slug",value:n,onChange:g=>{const d=g.target.value;p.startsWith(d,`/${h}`)&&r(d)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),s.jsx(c.DialogFooter,{children:s.jsx(c.Button,{type:"submit",disabled:i||!p.startsWith(n,`/${h}`)||p.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})};function nn({page:e,onClose:t}){const[,n]=Ae(),{mutate:r,isPending:a}=Rr(),{data:i}=Ee(),o=()=>{r(e,{onSuccess:()=>{e!=null&&e.primaryPage||(window.history.replaceState(null,"","/"),n(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate"))),t()}})},l=i==null?void 0:i.find(u=>u.key===(e==null?void 0:e.pageType));return s.jsx(c.Dialog,{open:!!e,onOpenChange:t,children:s.jsxs(c.DialogContent,{children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Confirm Deletion"}),s.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[s.jsxs("div",{children:["Are you sure you want to remove ",s.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",l!=null&&l.hasSlug?(l==null?void 0:l.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&s.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",s.jsx("span",{className:"font-medium text-gray-500",children:p.get(Pe,e.lang,e.lang)})]})]})]}),s.jsxs(c.DialogFooter,{children:[s.jsx(c.Button,{variant:"outline",onClick:t,children:"Cancel"}),s.jsx(c.Button,{variant:"destructive",disabled:a,onClick:o,children:a?"Deleting...":"Delete"})]})]})})}const Ne=({permission:e,permissions:t,children:n,fallback:r=null})=>{const{hasPermission:a}=X.usePermissions();return e&&!a(e)||t&&!t.some(i=>a(i))?r:n},ws=({page:e,onClose:t})=>{const{mutate:n,isPending:r}=Ur(),a=async()=>{n(e,{onSuccess:t})};return s.jsx(c.Dialog,{open:!!e,onOpenChange:t,children:s.jsxs(c.DialogContent,{children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Confirm action"}),s.jsxs(c.DialogDescription,{children:[O.UNPUBLISH_MSG," ",s.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),s.jsxs(c.DialogFooter,{children:[s.jsx(c.Button,{variant:"outline",onClick:t,children:"Cancel"}),s.jsx(c.Button,{variant:"destructive",disabled:r,onClick:a,children:r?O.UPDATING:O.UNPUBLISH})]})]})})},rn=({langProps:e,onClose:t,languages:n})=>{const{data:r}=we(),{data:a}=Ee(),[i,o]=y.useState(e.name||""),[l,u]=y.useState(e.edit?e.lang:""),[h,g]=y.useState(e.edit?e.slug:""),{mutate:d,isPending:b}=sn(),{mutate:v,isPending:x}=bs(),w=y.useMemo(()=>a==null?void 0:a.find(j=>j.key===e.pageType),[a,e.pageType]),E=!(w!=null&&w.hasSlug),C=b||x,R=j=>{j.preventDefault();const S={name:i,lang:l,primaryPage:r==null?void 0:r.id,slug:h,pageType:r==null?void 0:r.pageType};S.pageType=e.pageType,e.edit&&(S.id=e==null?void 0:e.id),e.edit?v(S,{onSuccess:t}):d(S,{onSuccess:t})};return s.jsx(c.Dialog,{open:!!e,onOpenChange:t,children:s.jsxs(c.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:e.edit?O.EDIT_LANGUAGE:O.ADD_NEW_LANGUAGE}),s.jsx(c.DialogDescription,{className:"font-light",children:O.ENTER_LANGUAGE_DETAILS})]}),s.jsxs("form",{onSubmit:R,children:[s.jsxs("div",{className:"grid gap-4 py-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(c.Label,{htmlFor:"lang",className:"text-right",children:O.LANGUAGE}),s.jsxs("select",{value:l,disabled:e.edit||p.isEmpty(n),onChange:j=>{const S=j.target.value;u(S),!E&&g(`/${S}`)},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:[s.jsx("option",{value:"",disabled:!0,selected:!0,children:e.edit?p.get(Pe,e.lang,e.lang):p.isEmpty(n)?O.ALL_AVAILABLE_LANGUAGE_PAGE:O.CHOOSE_LANGUAGE}),p.map(n,j=>s.jsx("option",{value:j,children:p.get(Pe,j,j)},j))]})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(c.Label,{htmlFor:"slug",className:"text-right",children:O.PAGE_NAME}),s.jsx(c.Input,{id:"name",value:i,onChange:j=>o(j.target.value),className:"col-span-3",required:!0,placeholder:O.ENTER_PAGE_NAME})]}),!E&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:[O.SLUG," ",s.jsx("small",{className:"font-light",children:O.SLUG_SHOULD_START_WITH})]}),s.jsx(c.Input,{id:"slug",value:h,onChange:j=>{const S=j.target.value;p.startsWith(S,`/${l}`)&&g(p.toLower(p.trim(S)))},className:"col-span-3",required:!0,pattern:"^/.*",disabled:p.isEmpty(l),title:O.SLUG_MUST_START_WITH,placeholder:p.isEmpty(l)?O.CHOOSE_LANGUAGE_TO_ADD_SLUG:O.ENTER_PAGE_SLUG})]})]}),s.jsx(c.DialogFooter,{children:s.jsx(c.Button,{type:"submit",disabled:C||!i||!l||!E&&!p.startsWith(h,`/${l}`),children:C?e.edit?O.UPDATING:O.ADDING:e.edit?O.UPDATE:O.ADD_NEW_LANGUAGE})})]})]})})},Wr=()=>{const[e,t]=y.useState(null),{selectedLang:n,fallbackLang:r,setSelectedLang:a}=X.useLanguages(),{data:i,isFetching:o}=mt(),{data:l}=we(),[u,h]=y.useState(null),[g,d]=y.useState(null),[b,v]=y.useState(null),{data:x}=ft(),w=p.filter(p.get(x,"languages")||["en"],E=>!p.find(i,{lang:E})&&E!==p.get(x,"fallbackLang"));return s.jsxs("div",{className:"space-y-4",children:[s.jsx("ul",{className:"space-y-2",children:o?s.jsxs("div",{className:"w-full space-y-3 py-4",children:[s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):p.map(i,E=>{const C=E.lang,R=E.slug,j=!E.primaryPage,S=C===n;return s.jsxs(s.Fragment,{children:[s.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:()=>a(C),children:[s.jsxs("div",{className:" flex-1 gap-x-3",children:[s.jsxs("div",{className:"text-[13px] text-slate-800 flex items-center gap-x-2",children:[s.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${E.online?"bg-green-300":"bg-gray-300"}`}),p.get(Pe,j?r:C,C)]}),s.jsxs("div",{children:[R&&s.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",s.jsx("b",{className:"font-medium",children:R})]}),s.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",s.jsxs("b",{className:"font-medium",children:[" ",E.name," "]})]})]})]}),j?s.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[s.jsx(T.StarIcon,{fill:"orange",className:"w-3 h-3"}),s.jsx("b",{children:" Primary"})]}):s.jsx("div",{className:"flex items-center gap-x-3",children:s.jsx(Ne,{permissions:[ue.EDIT_PAGE,ue.DELETE_PAGE,ue.UNPUBLISH_PAGE],children:s.jsxs(c.DropdownMenu,{children:[s.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:P=>P.stopPropagation(),children:s.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:s.jsx(T.MoreHorizontal,{className:"h-4 w-4"})})}),s.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[s.jsx(Ne,{permissions:[ue.EDIT_PAGE],children:s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:P=>{P.stopPropagation(),t({...E,edit:!0})},children:[s.jsx(T.PencilIcon,{className:"size-3"}),O.EDIT]})}),s.jsx(Ne,{permissions:[ue.UNPUBLISH_PAGE],children:(E==null?void 0:E.online)&&s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:P=>{P.stopPropagation(),d(E)},children:[s.jsx(T.Power,{className:"size-3"}),O.UNPUBLISH]})}),s.jsx(Ne,{permissions:[ue.DELETE_PAGE],children:s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:P=>{P.stopPropagation(),h(E)},children:[s.jsx(T.TrashIcon,{className:"size-3"}),O.DELETE]})})]})]})})})]},E.id),s.jsx("div",{className:"h-1 w-full border-b"})]})})}),s.jsx(Ne,{permissions:[ue.ADD_PAGE],children:s.jsx("div",{className:"flex justify-center w-full",children:s.jsx(c.Button,{variant:"default",size:"sm",disabled:p.isEmpty(w),onClick:()=>{t({name:l==null?void 0:l.name,pageType:l==null?void 0:l.pageType,lang:"",slug:"",edit:!1})},children:O.ADD_NEW_LANGUAGE})})}),e&&s.jsx(rn,{languages:w,langProps:e,onClose:()=>t(null)}),u&&s.jsx(nn,{page:u,onClose:()=>h(null)}),g&&s.jsx(ws,{page:g,onClose:()=>d(null)}),b&&s.jsx($r,{page:b,onClose:()=>v(null)})]})};function Qr({pages:e,selectedParentId:t,onChange:n,className:r="w-full rounded-md border border-gray-300 px-3 py-2",id:a="parentPage"}){const i=y.useMemo(()=>!e||e.length===0?[]:e.filter(g=>!p.isEmpty(g.slug)).filter(g=>g.slug!=="/").sort((g,d)=>g.slug.localeCompare(d.slug)),[e]),o=h=>Math.max(0,(h.match(/\//g)||[]).length-1),l=h=>"    ".repeat(h),u=h=>{if(h==="/")return"/";const g=h.split("/").filter(Boolean);return g.length<=1?`/${g[0]||""}`:`/${g[g.length-1]}`};return s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(c.Label,{htmlFor:a,className:"text-sm",children:"Parent"}),s.jsxs("select",{id:a,value:t||"none",onChange:h=>n(h.target.value),className:r,"data-testid":"parent-page-selector",children:[s.jsx("option",{value:"none",children:"None"}),i.map(h=>{const g=o(h.slug),d=g>0?l(g):"",b=u(h.slug);return s.jsxs("option",{value:h.id,children:[d,h.name," (",b,")"]},h.id)})]})]})}const Yr=({templates:e,selectedTemplateId:t,onSelectTemplate:n,isLoading:r=!1})=>{const[a,i]=y.useState("");if(y.useEffect(()=>{if(t){const l=e.find(u=>u.id===t);i((l==null?void 0:l.preview)||"")}else i("")},[t,e]),r)return s.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 o={};return e.forEach(l=>{const u=l.libraryName;o[u]||(o[u]=[]),o[u].push(l)}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:t,onChange:l=>n(l.target.value),children:[s.jsx("option",{value:"",children:"No Template"}),Object.entries(o).map(([l,u])=>s.jsx("optgroup",{label:l,children:u.map(h=>s.jsx("option",{value:h.id,children:p.startCase(h.name)},h.id))},l))]}),a&&s.jsxs("div",{className:"mt-3 border rounded overflow-hidden",children:[s.jsx("div",{className:"max-h-[200px] overflow-auto",children:s.jsx("img",{src:a,alt:"Template Preview",className:"w-full object-contain"})}),s.jsx("div",{className:"p-2 text-xs text-gray-500 bg-gray-50 border-t",children:"Template preview"})]})]})},Xr=()=>{const e=Z(),t=W();return k.useQuery({queryKey:[je,_.GET_LIBRARIES],queryFn:async()=>await t(e,{action:_.GET_LIBRARIES})||[]})},Zr=e=>{const t=Z(),n=W();return k.useQuery({queryKey:[je,_.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const r=await n(t,{action:_.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?p.filter(r,{pageType:e}):r)||[]}})},Jr=e=>{const{data:t=[],isLoading:n}=Zr(e),{data:r=[],isLoading:a}=Xr(),i=y.useMemo(()=>n||a?[]:t.map(l=>{const u=p.find(r,{id:l.library});return{...l,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[t,r,n,a]),o=y.useMemo(()=>p.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:o,isLoading:n||a}};function ea({addEditPage:e,additionalPageTypes:t=[],close:n}){var pe,Le;const r=!!(e!=null&&e.id),{data:a}=Rt(),{mutate:i,isPending:o}=sn(),{mutate:l,isPending:u}=bs(),[h,g]=y.useState(null),[d,b]=y.useState((e==null?void 0:e.pageType)??"page"),[v,x]=y.useState(t.find(f=>f.key===d)),[w,E]=y.useState((e==null?void 0:e.parent)??""),[C,R]=y.useState((e==null?void 0:e.name)??""),[j,S]=y.useState(((e==null?void 0:e.slug)??"").split("/").pop()||""),[P,B]=y.useState((e==null?void 0:e.dynamic)??!1),[ee,ie]=y.useState(""),{data:L,isLoading:H}=Jr(d),A=o||u,F=t.find(f=>f.key===d),se=f=>{b(f),E(""),S(""),B(!1),ie(""),x(t.find(m=>m.key===f))},he=f=>{B(f),f&&S("")},Q=f=>{if(E(f),f&&f!=="none"){const m=a==null?void 0:a.find(I=>I.id===f),N=(m==null?void 0:m.slug)||"";if(j.startsWith(N)){const I=j.slice(N.length).replace(/^\/+/,"");S(I)}else S(j.replace(/^\/+/,""))}else S(j?`${j}`:"")},de=f=>{ie(f)},q=f=>{if(f.preventDefault(),j.length>0&&!P&&!j.match(/^[a-zA-Z0-9-_]+$/)){g("Slug can only contain letters, numbers, and hyphens");return}if(P&&j!==""){g("Slug must be empty when using dynamic slug");return}if(!C.trim()){$.toast.error("Name is required");return}if(!(v!=null&&v.hasSlug)){const m={pageType:v==null?void 0:v.key,name:C,slug:"",hasSlug:!1};if(r){l({id:e==null?void 0:e.id,name:C},{onSuccess:()=>{$.toast.success((v==null?void 0:v.name)+" updated successfully"),n()}});return}i(m,{onSuccess:()=>{n()}});return}if(w&&w!=="none"){if(!j.trim()&&!P){$.toast.error("Child page slug is required");return}const m=a==null?void 0:a.find(D=>D.id===w),N=(m==null?void 0:m.slug)||"",I=N==="/"?`/${j}`:`${N}/${j}`;if(Object.keys(Pe).some(D=>I===`/${D}`||(I==null?void 0:I.startsWith(`/${D}/`)))){$.toast.error("Slugs cannot start with a language code for primary page");return}const z={pageType:d,name:C,slug:I.replace(/\/$/,""),parent:w,dynamic:P,hasSlug:!0,templateId:ee||void 0};if(r){l({id:e==null?void 0:e.id,...z},{onSuccess:()=>{$.toast.success("Page updated successfully"),n()}});return}i(z,{onSuccess:()=>{n()}})}else{const m={pageType:d,name:C,slug:j===""?"/":`/${j.replace(/\/$/,"")}`,template:ee||void 0};if(r){l({id:e==null?void 0:e.id,...m},{onSuccess:()=>{$.toast.success("Page updated successfully"),n()}});return}i(m,{onSuccess:()=>{n()}})}};return v!=null&&v.hasSlug?s.jsxs("form",{onSubmit:q,className:"w-full max-w-md mx-auto space-y-4",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Page Type"}),s.jsxs("select",{id:"pageType",value:d,disabled:r,onChange:f=>se(f.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${r?"cursor-not-allowed text-gray-500":""}`,children:[s.jsx("optgroup",{label:"Pages",children:t.filter(f=>f.hasSlug!==!1).map(f=>s.jsx("option",{value:f.key,children:f.name},f.key))}),s.jsx("optgroup",{label:"Partials",children:t.filter(f=>f.hasSlug===!1).map(f=>s.jsx("option",{value:f.key,children:f.name},f.key))})]})]}),!r&&(v==null?void 0:v.hasSlug)&&L.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsx(c.Label,{className:"text-sm mb-1 block",children:"Template"}),s.jsx(Yr,{templates:L,selectedTemplateId:ee,onSelectTemplate:de,isLoading:H})]}),s.jsx(Qr,{pages:a,selectedParentId:w,onChange:Q}),s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),s.jsx(c.Input,{id:"name",value:C,onChange:f=>R(f.target.value),required:!0,"aria-required":"true"})]}),(F==null?void 0:F.dynamicSegments)&&w&&w!=="none"&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx("input",{type:"checkbox",id:"useDynamicSlug",checked:P,onChange:f=>he(f.target.checked),className:"rounded border-gray-300"}),s.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),P&&s.jsxs("div",{className:"text-sm text-gray-500",children:["Pages will use pattern: ",F==null?void 0:F.dynamicSlug]})]}),(!(F!=null&&F.dynamicSegments)||!P)&&s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs(c.Label,{htmlFor:"slug",className:"text-sm",children:["Slug",w&&w!=="none"&&s.jsxs("span",{className:"ml-2 text-sm text-gray-500",children:["Parent:"," ",(Le=a==null?void 0:a.find(f=>f.id===w))==null?void 0:Le.slug]})]}),s.jsx(c.Input,{id:"slug",value:j,onChange:f=>S(f.target.value),placeholder:w&&w!=="none"?"Enter page slug":d==="page"?"Leave empty for home page":"Required - e.g. /your-slug"}),h&&s.jsx("p",{className:"text-xs text-red-500",children:h})]}),s.jsx(c.Button,{disabled:A,type:"submit",className:"w-full",children:r?A?"Updating...":"Update page":A?"Creating...":"Create Page"})]}):s.jsxs("form",{onSubmit:q,className:"w-full max-w-md mx-auto space-y-4",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Page Type"}),s.jsxs("select",{id:"pageType",value:d,disabled:r,onChange:f=>se(f.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${r?"cursor-not-allowed text-gray-500":""}`,children:[s.jsx("optgroup",{label:"Pages",children:t.filter(f=>f.hasSlug!==!1).map(f=>s.jsx("option",{value:f.key,children:f.name},f.key))}),s.jsx("optgroup",{label:"Partials",children:t.filter(f=>f.hasSlug===!1).map(f=>s.jsx("option",{value:f.key,children:f.name},f.key))})]}),s.jsx("p",{className:"text-sm text-gray-500",children:(pe=t.find(f=>f.key===d))==null?void 0:pe.helpText})]}),s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),s.jsx(c.Input,{id:"name",value:C,onChange:f=>R(f.target.value),required:!0,"aria-required":"true"})]}),s.jsx(c.Button,{disabled:A,type:"submit",className:"w-full",children:r?A?"Updating...":"Update "+(v==null?void 0:v.name):A?"Creating...":"Create "+(v==null?void 0:v.name)})]})}const ta=({addEditPage:e,setAddEditPage:t})=>{const{data:n}=Ee(),r=!!(e!=null&&e.id);return s.jsx(c.Dialog,{open:!!e,onOpenChange:()=>t(void 0),children:s.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[s.jsxs(c.DialogHeader,{children:[s.jsxs(c.DialogTitle,{children:[r?"Edit":"Add New"," "]}),s.jsx(c.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),s.jsx(ea,{addEditPage:e,close:()=>t(void 0),additionalPageTypes:n??[]})]})})},sa=1*1024*1024,na=({page:e,onClose:t})=>{const[n,r]=y.useState(!1),[a,i]=y.useState(""),[o,l]=y.useState(""),[u,h]=y.useState(!1),g=y.useRef(null),d=Or(),{data:b}=Ee(),v=b==null?void 0:b.find(j=>j.key===e.pageType),x=(v==null?void 0:v.name)||p.startCase(e.pageType),w=y.useCallback(j=>{var P;const S=(P=j.target.files)==null?void 0:P[0];if(S){if(S.size>sa){$.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(S.size/1024).toFixed(2)}KB.`}),g.current&&(g.current.value="");return}try{h(!0);const B=new FileReader;B.onloadend=()=>{l(B.result),h(!1)},B.readAsDataURL(S)}catch(B){console.error("Error reading file:",B),h(!1),$.toast.error("Failed to process image",{description:B instanceof Error?B.message:"Unknown error"})}}},[]),E=()=>{l(""),g.current&&(g.current.value="")},C=()=>{var j;(j=g.current)==null||j.click()},R=()=>{r(!0),d.mutate({page:e,name:e.name,description:a.trim()||void 0,pageType:e.pageType,...o?{previewImage:o}:{}},{onSuccess:()=>{r(!1),t()},onError:()=>{r(!1)}})};return s.jsx(c.Dialog,{open:!0,onOpenChange:t,children:s.jsxs(c.DialogContent,{children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Mark as template"}),s.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?",s.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),s.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[s.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(T.Tag,{className:"w-4 h-4 text-slate-500"}),s.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),s.jsx("span",{className:"font-semibold",children:p.startCase(e.name)})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(T.File,{className:"w-4 h-4 text-slate-500"}),s.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),s.jsx("span",{className:"font-semibold",children:x})]})]}),s.jsxs("div",{children:[s.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),s.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:a,onChange:j=>i(j.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(c.Input,{type:"file",id:"previewImage",ref:g,onChange:w,accept:"image/*",className:"hidden"}),s.jsx(c.Button,{type:"button",variant:"outline",onClick:C,disabled:u,className:"w-full",children:u?s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(T.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),o&&s.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:E,children:s.jsx(T.X,{className:"h-4 w-4"})})]}),o&&s.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:s.jsx("img",{src:o,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),s.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[s.jsx(c.Button,{variant:"outline",onClick:j=>{j.stopPropagation(),t()},children:"Cancel"}),s.jsx(c.Button,{variant:"default",disabled:n,onClick:R,children:"Mark as template"})]})]})})},ra=({page:e,onClose:t})=>{const[n,r]=y.useState(!1),a=Fr(),i=()=>{r(!0),a.mutate(e,{onSuccess:()=>{r(!1),t()},onError:()=>{r(!1)}})};return s.jsx(c.Dialog,{open:!0,onOpenChange:t,children:s.jsxs(c.DialogContent,{children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Unmark as template"}),s.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?"})]}),s.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[s.jsx(c.Button,{variant:"outline",onClick:o=>{o.stopPropagation(),t()},children:"Cancel"}),s.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},as=({parentSlug:e,page:t,active:n,changeActivePage:r,setUnpublishPage:a,setDeletePage:i,setAddEditPage:o,setMarkAsTemplate:l,setUnmarkAsTemplate:u})=>{const{data:h}=Ee(),{hasPermission:g}=X.usePermissions(),d=y.useMemo(()=>p.find(h,{key:t.pageType}),[h,t.pageType]),b=p.get(t,"slug").replace(e,"")||"/",v=!g(ue.EDIT_PAGE)&&!g(ue.DELETE_PAGE)&&!g(ue.UNPUBLISH_PAGE),x=y.useMemo(()=>!!t.isTemplate,[t.isTemplate]),w=y.useMemo(()=>!!(d!=null&&d.hasSlug),[d==null?void 0:d.hasSlug]);return s.jsxs("div",{onClick:()=>r(p.get(t,"id")),className:`rounded flex p-1.5 items-center justify-between leading-none duration-300 cursor-pointer px-3 py-1.5 ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[s.jsxs("div",{className:"flex items-center gap-x-2",children:[t.dynamic?s.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:s.jsx(T.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):d!=null&&d.icon?s.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:d.icon}}):d!=null&&d.hasSlug?s.jsx(T.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):s.jsx(T.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),s.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.online?"bg-green-300":"bg-gray-300"}`}),s.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:p.startCase(t.name)??""}),d!=null&&d.hasSlug?s.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:[b,t.dynamic&&s.jsx("span",{className:"text-xs font-light leading-none text-slate-500",children:p.endsWith(b,"/")?`${d==null?void 0:d.dynamicSlug}`:`/${d==null?void 0:d.dynamicSlug}`})]}):s.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:d==null?void 0:d.name}),x&&s.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.jsx("div",{className:"flex items-center space-x-4",children:!v&&s.jsxs(c.DropdownMenu,{children:[s.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:E=>E.stopPropagation(),children:s.jsx(T.MoreHorizontal,{className:"h-4 w-4 hover:stroke-[3]"})}),s.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm",children:[g(ue.EDIT_PAGE)&&s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:E=>{E.stopPropagation(),o({...t,global:!(d!=null&&d.hasSlug)})},children:[s.jsx(T.Pencil,{className:"size-3"}),"Edit"]}),(t==null?void 0:t.online)&&g(ue.UNPUBLISH_PAGE)&&s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:E=>{E.stopPropagation(),a(t)},children:[s.jsx(T.Power,{className:"size-3"}),O.UNPUBLISH]}),g(ue.DELETE_PAGE)&&s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:E=>{E.stopPropagation(),i(t)},children:[s.jsx(T.Trash,{className:"size-3"}),O.DELETE]}),g(ue.MARK_AS_TEMPLATE)&&w&&s.jsx(s.Fragment,{children:x?s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:E=>{E.stopPropagation(),u(t)},children:[s.jsx(T.SquareLibrary,{className:"size-3"}),O.UNMARK_AS_TEMPLATE]}):s.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:E=>{E.stopPropagation(),l(t)},children:[s.jsx(T.SquareLibrary,{className:"size-3"}),O.MARK_AS_TEMPLATE]})})]})]})})]})},aa=({close:e})=>{const[,t]=y.useState([]),[n,r]=y.useState(""),[a,i]=y.useState(null),[o,l]=y.useState(null),[u,h]=y.useState(null),[g,d]=y.useState(null),[b,v]=y.useState(null),{data:x,isFetching:w}=Rt(),[E,C]=y.useState(""),{hasPermission:R}=X.usePermissions(),[j,S]=Ae(),P=j.get("page"),{data:B}=Ee(),ee=y.useCallback(A=>{var F;return(F=p.find(B,{key:A}))==null?void 0:F.hasSlug},[B]);y.useEffect(()=>{if(!p.isEmpty(E))return;const A=sessionStorage.getItem("pageTypeFilter")||"all";!p.isEmpty(B)&&A&&(p.find(B,{key:A})?C(A):C("all"))},[B,E]);const ie=A=>{C(A),sessionStorage.setItem("pageTypeFilter",A)},L=y.useCallback(A=>{const se=new URLSearchParams(window.location.search).get("lang"),he=new URLSearchParams({page:A});se&&he.set("lang",se),window.history.pushState({},"",`?${he.toString()}`),S(he),window.dispatchEvent(new PopStateEvent("popstate")),e()},[S,e]);y.useEffect(()=>{if(P&&!w){const A=p.find(x,{id:P});A&&(A!=null&&A.pageType)?t(F=>[...F,A==null?void 0:A.pageType]):(window.history.replaceState(null,"","/"),S(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[x,P,w,S]);const H=y.useMemo(()=>{const A=p.filter(x,q=>p.isEmpty(n)?!0:p.includes(p.toLower(q==null?void 0:q.name),p.toLower(n))||p.includes(p.toLower(q==null?void 0:q.slug),p.toLower(n)));if(E!=="all")return p.filter(A,{pageType:E});const F=new Map;A.forEach(q=>{F.set(q.id,{...q,children:[]})});const se=[],he=[];F.forEach(q=>{if(q.parent){const pe=F.get(q.parent);pe?pe.children.push(q):se.push(q)}else he.push(q)}),se.sort((q,pe)=>q.name.localeCompare(pe.name)),se.forEach(q=>{q.children.sort((pe,Le)=>pe.name.localeCompare(Le.name))});const Q=p.filter(he,q=>!ee(q.pageType)),de=p.filter(he,q=>ee(q.pageType)).sort((q,pe)=>q.name.localeCompare(pe.name));return p.compact([...de,...Q,...se])},[x,ee,n,E]);return s.jsxs("div",{className:"flex flex-col justify-between h-full",children:[s.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[s.jsxs("div",{className:"relative flex item-center gap-x-4",children:[s.jsx(T.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),s.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:n,onChange:A=>r(A.target.value)}),!p.isEmpty(E)&&s.jsxs(c.Select,{value:E,onValueChange:ie,children:[s.jsx(c.SelectTrigger,{className:`${E==="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:s.jsx(c.SelectValue,{placeholder:"Select page type"})}),s.jsx(c.SelectContent,{align:"end",children:p.map(p.concat([{key:"all",name:"All"}],B),A=>s.jsx(c.SelectItem,{value:p.get(A,"key"),children:p.get(A,"name")}))})]})]}),w?s.jsx("div",{className:"space-y-2",children:p.map([...Array(5).keys()],A=>s.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},A))}):p.isEmpty(H)?s.jsxs("div",{className:"h-[70vh] flex flex-col gap-y-1 items-center justify-center text-slate-500 text-sm font-medium",children:[s.jsx(T.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",s.jsx("span",{className:"font-light",children:"Add new page to start"})]}):s.jsx("div",{className:"text-sm text-slate-700 space-y-2 h-[70vh] overflow-y-auto",children:p.map(H,A=>p.isEmpty(A==null?void 0:A.children)?s.jsx(as,{changeActivePage:L,setUnpublishPage:l,setDeletePage:i,setAddEditPage:h,setMarkAsTemplate:d,setUnmarkAsTemplate:v,active:P===A.id,page:A},A.id):s.jsxs("div",{className:"border-0",children:[s.jsx(as,{changeActivePage:L,setUnpublishPage:l,setDeletePage:i,setAddEditPage:h,setMarkAsTemplate:d,setUnmarkAsTemplate:v,active:P===A.id,page:A}),s.jsx("div",{className:"pt-2 pl-6 bg-white",children:p.map(p.get(A,"children",[]),F=>{const se=P===p.get(F,"id");return s.jsx(as,{parentSlug:A.slug,changeActivePage:L,setUnpublishPage:l,setDeletePage:i,setAddEditPage:h,setMarkAsTemplate:d,setUnmarkAsTemplate:v,active:se,page:F},F.id)})})]},A.key))})]}),R(ue.ADD_PAGE)&&s.jsxs(c.Button,{className:"flex text-sm gap-x-2",onClick:()=>{h({slug:"",name:"",pageType:E==="all"?"page":E})},children:[s.jsx(T.Plus,{className:"w-4 h-4"})," Add New"]}),u&&s.jsx(ta,{editPage:L,addEditPage:u,setAddEditPage:h}),a&&s.jsx(nn,{page:a,onClose:()=>i(null)}),o&&s.jsx(ws,{page:o,onClose:()=>l(null)}),g&&s.jsx(na,{page:g,onClose:()=>d(null)}),b&&s.jsx(ra,{page:b,onClose:()=>v(null)})]})},ia=()=>{const e=Ve("logo",null);return e?s.jsx("div",{className:"w-full max-h-9 overflow-hidden pr-2",children:y.createElement(e,{})}):null},oa=()=>{const[e]=Ae(),t=e.get("page"),{data:n,isFetching:r}=we(),[a,i]=y.useState(!1),o=!!t&&!p.isEmpty(n),l=!t||!r&&p.isEmpty(n)||a;return s.jsxs(s.Fragment,{children:[s.jsxs(c.Button,{variant:"secondary",className:"flex items-center w-full space-x-2 py-1",onClick:()=>i(!0),children:[s.jsx("div",{children:s.jsx(T.Logs,{className:"h-4 w-4"})}),s.jsxs("span",{className:"truncate leading-tight flex items-center max-w-[200px]",children:[s.jsx("span",{className:"text-slate-600 pr-1 font-light",children:"Editing:"}),r?s.jsx(T.Loader,{className:"h-4 w-4 animate-spin text-slate-400 ml-2"}):p.startCase(p.get(n,"name"))??""]})]},"template-viewer"),s.jsx(c.Sheet,{open:l,onOpenChange:u=>!u&&o&&i(!1),children:s.jsxs(c.SheetContent,{side:"left",className:`!max-w-screen-md z-50 border-border w-full ${o?"":"sheet-hide-close-btn"}`,children:[s.jsx(c.SheetHeader,{className:"mb-3",children:s.jsxs(c.SheetTitle,{className:"text-sm flex items-center gap-2 font-semibold",children:[s.jsx("div",{className:"p-2 rounded-md bg-primary text-primary-foreground",children:s.jsx(T.File,{className:"w-6 h-6"})}),s.jsxs("div",{className:"flex flex-col",children:[s.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),s.jsx("span",{className:"text-xs text-muted-foreground",children:"Manage your site structure"})]})]})}),s.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:s.jsx(aa,{close:()=>i(!1)})})]})})]})},la=()=>{const{fallbackLang:e,languages:t,selectedLang:n,setSelectedLang:r}=X.useLanguages(),a=p.isEmpty(n)?e:n,[,i]=Ae();y.useEffect(()=>{const x=new URLSearchParams(window.location.search),w=x.get("lang");w&&(t.includes(w)?r(w):(x.delete("lang"),i(x),r("")))},[t,i,r]);const[o,l]=y.useState(null),{data:u}=we(),{data:h}=ft(),{data:g,isFetching:d}=mt(),b=y.useMemo(()=>{const x=p.compact(p.map(p.get(h,"languages"),w=>{const E=p.find(g,{lang:w});return{key:w,value:p.get(Pe,w,w),isLangPageAdded:!!E}})).filter(Boolean);return[{key:e,value:p.get(Pe,e),isLangPageAdded:!0},...x]},[e,g,h]),v=x=>{r(x);const w=new URLSearchParams(window.location.search);x===e?w.delete("lang"):w.set("lang",x);const E=w.toString(),C=`${window.location.pathname}${E?`?${E}`:""}`;window.history.pushState({},"",C),i(w),window.dispatchEvent(new PopStateEvent("popstate"))};return p.isEmpty(t)||d?null:s.jsxs(s.Fragment,{children:[s.jsxs(c.DropdownMenu,{children:[s.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:s.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[s.jsx(T.Languages,{className:"w-4 h-4"}),p.get(Pe,a,a),s.jsx(T.ChevronDown,{className:"w-4 h-4"})]})}),s.jsxs(c.DropdownMenuContent,{className:"border-border space-y-1",children:[p.map(b.filter(x=>x.isLangPageAdded),x=>s.jsxs(c.DropdownMenuItem,{className:X.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",x.key===a&&"!bg-gray-200 text-gray-700"),onClick:()=>v(x.key),children:[s.jsx("div",{className:"text-slate-600",children:x.value}),x.key===e&&s.jsxs("small",{className:"text-[9px] flex items-center gap-x-1 text-orange-500 leading-none",children:[s.jsx(T.Star,{fill:"orange",className:"w-2 h-2"}),"Primary"]})]},x.value)),!p.isEmpty(b.filter(x=>!x.isLangPageAdded))&&s.jsxs(s.Fragment,{children:[s.jsx(c.Separator,{}),s.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{l({name:u==null?void 0:u.name,pageType:u==null?void 0:u.pageType,lang:"",slug:"",edit:!1})},className:"hover:bg-slate-300 duration-200 font-normal text-xs hover:text-slate-800",children:[s.jsx(T.Plus,{className:"w-3 h-3 mr-1"})," Add Langauge"]})]})]})]}),o&&s.jsx(rn,{languages:t,langProps:o,onClose:()=>l(null)})]})};function ca(){return s.jsxs("div",{className:"flex relative z-10 items-center justify-end gap-1",children:[s.jsx(ia,{}),s.jsx(oa,{}),s.jsx(la,{})]})}function ua(e){const t=Z(),n=W();return k.useQuery({queryKey:[je,"revisions",e],queryFn:async()=>await n(t,{action:_.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const da=()=>{const e=Z(),t=W(),n=k.useQueryClient();return k.useMutation({mutationFn:async r=>await t(e,{action:_.DELETE_PAGE_REVISION,data:{revisionId:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},ha=()=>{const e=Z(),t=W(),n=k.useQueryClient();return k.useMutation({mutationFn:async({revisionId:r,discardCurrent:a})=>await t(e,{action:_.RESTORE_PAGE_REVISION,data:{revisionId:r,discardCurrent:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})};function ma(){const{data:e}=we(),{saveState:t}=X.useSavePage(),[n]=Es();return e?s.jsx("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50 bg-primary/5 mb-4",children:s.jsxs("div",{className:"flex-1 space-y-1",children:[s.jsx("div",{className:"flex items-center justify-between",children:s.jsx("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:s.jsx("span",{className:"font-bold",children:"Currently editing"})})}),s.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:!p.isEmpty(n.lastSaved)&&s.jsxs("span",{children:["Last updated"," ",Gt.formatDistanceToNow(new Date(n.lastSaved),{addSuffix:!0})]})}),s.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[s.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:[s.jsx(T.Edit,{className:"h-3 w-3"}),s.jsx("span",{children:"Draft"})]}),t==="UNSAVED"?s.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:[s.jsx(T.Save,{className:"h-3 w-3"}),s.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function fa(){const[e,t]=ce.useState(!1),[n,r]=ce.useState(null),[a,i]=ce.useState(!1),[o,l]=ce.useState(!1),{data:u}=we(),{data:h,isFetching:g,error:d,refetch:b}=ua(u==null?void 0:u.id),{mutate:v,isPending:x}=da(),{mutate:w,isPending:E}=ha(),C=k.useQueryClient(),R=B=>{n&&w({revisionId:n.uid,discardCurrent:B},{onSuccess:()=>{i(!1),r(null),C.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]})}})},j=B=>{r(B),i(!0)},S=B=>{r(B),l(!0)},P=()=>{n&&v(n.uid,{onSuccess:()=>{l(!1),r(null)}})};return y.useEffect(()=>{e&&b()},[e,b]),s.jsxs(s.Fragment,{children:[s.jsx(c.TooltipProvider,{children:s.jsxs(c.Tooltip,{children:[s.jsxs(c.Sheet,{open:e,onOpenChange:t,children:[s.jsx(c.SheetTrigger,{asChild:!0,children:s.jsx(c.TooltipTrigger,{asChild:!0,children:s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[s.jsx(T.History,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"View revision history"})]}),s.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),s.jsxs(c.SheetContent,{className:"sm:max-w-md p-4",children:[s.jsxs(c.SheetHeader,{className:"pb-2",children:[s.jsxs(c.SheetTitle,{className:"flex items-center gap-2",children:[s.jsx(T.History,{className:"h-5 w-5"}),"Revision History"]}),(u==null?void 0:u.createdAt)&&s.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Page created on"," ",Gt.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),s.jsx(c.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:g?s.jsx(ga,{}):d?s.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):s.jsxs("div",{className:"mt-2 space-y-2",children:[s.jsx(ma,{}),h==null?void 0:h.map(B=>s.jsx(pa,{revision:B,isLatest:B.uid==="current",onRestore:()=>j(B),onDelete:()=>S(B)},B.uid))]})})]})]}),s.jsx(c.TooltipContent,{side:"bottom",children:s.jsx("p",{children:"Revision history"})})]})}),s.jsx(ya,{open:a,onOpenChange:i,revision:n,onRestore:R,isRestoring:E}),s.jsx(va,{open:o,onOpenChange:l,revision:n,onDelete:P,isDeleting:x})]})}function ga(){return s.jsx("div",{className:"space-y-2 mt-2",children:Array.from({length:5}).map((e,t)=>s.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[s.jsxs("div",{className:"flex-1 space-y-1",children:[s.jsx(c.Skeleton,{className:"h-4 w-3/4"}),s.jsx(c.Skeleton,{className:"h-3 w-1/2"}),s.jsx(c.Skeleton,{className:"h-5 w-20 mt-1"})]}),s.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},t))})}function pa({revision:e,isLatest:t,onRestore:n,onDelete:r}){const{data:a}=gt(e.currentEditor),i=(a==null?void 0:a.name)||"Unknown";return s.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50",children:[s.jsxs("div",{className:"flex-1 space-y-1",children:[s.jsx("div",{className:"flex items-center justify-between",children:s.jsxs("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:[e.type==="published"?"Published":"Draft"," by ",s.jsx("span",{className:"font-bold",children:i}),t&&s.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:[s.jsxs("span",{className:"mr-1 relative flex h-2 w-2",children:[s.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),s.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]}),"Live"]})]})}),s.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:s.jsx("span",{children:Gt.format(e.createdAt,"MMM d, h:mm a")})}),s.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:e.type==="published"?s.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:[s.jsx(T.ArrowUpRight,{className:"h-3 w-3"}),s.jsx("span",{children:"Published"})]}):s.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:[s.jsx(T.Clock,{className:"h-3 w-3"}),s.jsx("span",{children:"Draft"})]})})]}),s.jsx(Ne,{permissions:[ue.RESTORE_REVISION,ue.DELETE_REVISION],children:s.jsx(xa,{revision:e,onRestore:n,onDelete:r})})]})}function xa({revision:e,onRestore:t,onDelete:n}){return s.jsxs(c.DropdownMenu,{children:[s.jsx(c.DropdownMenuTrigger,{asChild:!0,children:s.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[s.jsx(T.MoreHorizontal,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"More options"})]})}),s.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[s.jsx(Ne,{permission:ue.RESTORE_REVISION,children:s.jsxs(c.DropdownMenuItem,{onClick:t,className:"cursor-pointer",children:[s.jsx(T.Undo2,{className:"mr-2 h-4 w-4"}),s.jsx("span",{children:"Restore this version"})]})}),s.jsx(Ne,{permission:ue.DELETE_REVISION,children:e.uid!=="current"&&s.jsxs(s.Fragment,{children:[s.jsx(c.DropdownMenuSeparator,{}),s.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[s.jsx(T.Trash,{className:"mr-2 h-4 w-4"}),s.jsx("span",{children:"Delete this version"})]})]})})]})]})}function ya({open:e,onOpenChange:t,revision:n,onRestore:r,isRestoring:a}){const{data:i}=gt((n==null?void 0:n.currentEditor)||""),o=(i==null?void 0:i.name)||"Unknown";return n?s.jsx(c.Dialog,{open:e,onOpenChange:l=>{a||t(l)},children:s.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Restore Revision"}),s.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",Gt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",o]})]}),s.jsx("div",{className:"py-2",children:s.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),s.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[s.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>r(!1),disabled:a,children:a?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):s.jsxs(s.Fragment,{children:[s.jsx(T.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),s.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>r(!0),disabled:a,children:a?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):s.jsxs(s.Fragment,{children:[s.jsx(T.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function va({open:e,onOpenChange:t,revision:n,onDelete:r,isDeleting:a}){const{data:i}=gt((n==null?void 0:n.currentEditor)||""),o=(i==null?void 0:i.name)||"Unknown";return n?s.jsx(c.Dialog,{open:e,onOpenChange:l=>{a||t(l)},children:s.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Delete Revision"}),s.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",Gt.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",o]})]}),s.jsx("div",{className:"py-2",children:s.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),s.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[s.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>t(!1),disabled:a,children:"Cancel"}),s.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:r,disabled:a,children:a?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):s.jsxs(s.Fragment,{children:[s.jsx(T.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Ea=()=>{const e=Z(),t=W();return k.useQuery({queryKey:[je,_.GET_CHANGES],queryFn:async()=>t(e,{action:_.GET_CHANGES})})},ba=({currentEditor:e})=>{const{data:t}=gt(e);return t==null?void 0:t.name};function ja({showModal:e=!1,onClose:t=()=>console.log("Cancelled")}){const[n,r]=y.useState([]),{data:a,isFetching:i}=Ea(),{data:o}=Ee(),l=y.useCallback(S=>{var P;return(P=p.find(o,{key:S}))==null?void 0:P.hasSlug},[o]),u=y.useMemo(()=>p.filter(o,S=>!l(S.key)).map(S=>S.key),[l,o]),h=y.useMemo(()=>p.filter(a,S=>!u.includes(S.pageType)),[a,u]),g=y.useMemo(()=>p.filter(a,S=>u.includes(S.pageType)),[a,u]),d=y.useMemo(()=>p.find(a,{pageType:"theme",id:"THEME"}),[a]),{mutate:b,isPending:v}=js();y.useEffect(()=>{const S=p.map(p.filter(a,{online:!0}),"id");d&&S.push(d==null?void 0:d.id),r(S)},[a,d]);const x=n.length===(a==null?void 0:a.length),w=S=>{r(P=>p.includes(P,S)?p.filter(P,B=>B!==S):p.concat(P,S))},E=()=>{r(x?[]:p.map(a,"id"))},C=()=>{b({ids:p.uniq(n)},{onSuccess:()=>{t(),zt("CENTER_CENTER")}})},R=S=>{if(S==="theme")return"Theme";const P=p.find(o,{key:S});return P?P==null?void 0:P.name:S},j=y.useMemo(()=>{const S=[{label:"Updated",top:"pt-2"},...p.orderBy(p.filter(h,{online:!0}),"pageType"),...p.orderBy(p.filter(g,{online:!0}),"pageType")].filter(ee=>ee.pageType!=="theme"),P=[{label:"Offline",top:"pt-6"},...p.orderBy(p.filter(h,{online:!1}),"pageType"),...p.orderBy(p.filter(g,{online:!1}),"pageType")],B=d?[{label:"Theme",top:"pt-6"},d]:[];return[...S,...B,...P]},[h,g,d]);return s.jsx(c.Dialog,{open:e,onOpenChange:v?()=>{}:t,children:s.jsxs(c.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[s.jsxs(c.DialogHeader,{children:[s.jsx(c.DialogTitle,{children:"Publish changes"}),s.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),s.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:i?s.jsxs("div",{className:"px-1 space-y-2",children:[s.jsx("div",{className:"w-full h-6 mt-2 bg-gray-200 rounded animate-pulse"}),s.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),s.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),s.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"})]}):s.jsxs("table",{className:"w-full text-xs text-left text-gray-500 rtl:text-right dark:text-gray-400",children:[s.jsx("thead",{className:"text-gray-700 border-b bg-gray-50 dark:bg-gray-700 dark:text-gray-400",children:s.jsxs("tr",{children:[s.jsxs("th",{scope:"col",className:"px-6 py-3 flex items-center gap-x-2 w-[1 50px]",children:[s.jsx("input",{checked:x,onClick:S=>{S.stopPropagation(),E()},type:"checkbox",className:"mt-1 rounded cursor-pointer focus:outline-none focus:ring-0"}),"Name"]}),s.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Language"}),s.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Type"}),s.jsx("th",{scope:"col",className:"px-4 py-3 w-[150px] text-right",children:"Status"})]})}),s.jsx("tbody",{children:p.map(j,S=>S.label?s.jsx("tr",{children:s.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${S.top}`,children:[s.jsx("div",{className:"absolute inset-0 flex items-center left-6",children:s.jsx("div",{className:"w-full order-gray-300"})}),s.jsx("div",{className:"relative flex justify-start",children:s.jsx("span",{className:"pr-2 bg-gray-50",children:S.label})})]})},"separator"):s.jsxs("tr",{className:"border-b group hover:bg-gray-50 last:border-b-0",children:[s.jsxs("td",{scope:"row",className:"flex items-center px-6 py-2 text-gray-900 whitespace-nowrap dark:text-white gap-x-1",children:[s.jsx("input",{checked:p.includes(n,S==null?void 0:S.id),onClick:P=>{P.stopPropagation(),w(S==null?void 0:S.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",l(S.pageType)?s.jsx(T.File,{className:"w-4 h-4"}):s.jsx(T.GlobeIcon,{className:"w-4 h-4"}),S.name,S.slug&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",S.slug,")"]}),S.currentEditor&&s.jsx("div",{className:"flex items-center gap-x-1",children:s.jsxs("span",{className:"flex text-xs font-bold text-gray-500",children:[" ","-"," ",s.jsx(ba,{currentEditor:S.currentEditor})," ","is editing"]})})]}),s.jsx("td",{className:"px-2",children:S.lang}),s.jsx("td",{className:"px-2",children:R(S==null?void 0:S.pageType)}),s.jsx("td",{className:"px-4 text-right",children:p.first(S.changes)||""})]},S==null?void 0:S.id))})]})}),s.jsxs(c.DialogFooter,{className:"mt-10",children:[s.jsx(c.Button,{disabled:v,variant:"outline",onClick:t,children:"Cancel"}),s.jsx(c.Button,{disabled:v||i||p.isEmpty(a),onClick:C,children:v?"Publishing...":"Publish"})]})]})})}const Sa=()=>{const e=W(),t=Z();return k.useQuery({queryKey:[_.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(t,{action:_.GET_WEBSITE_DATA,data:{draft:!0}})})};function wa({onClose:e}){const{data:t,isFetching:n}=Sa(),{mutateAsync:r,isPending:a}=xr(),i=Ve("settingComponent",null),o=p.debounce(async l=>(await r({data:l}),!0),300);return i?s.jsx(c.Dialog,{open:!0,onOpenChange:e,children:s.jsxs(c.DialogContent,{className:"w-full",children:[s.jsx(c.DialogHeader,{children:s.jsx(c.DialogTitle,{children:"Website Settings"})}),n?s.jsxs("div",{className:"w-full space-y-3 py-4",children:[s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),s.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):s.jsx("div",{children:y.createElement(i,{data:t||{},onSave:a?()=>{}:o,cancel:a?()=>{}:e})})]})}):null}function an({children:e,content:t}){return s.jsx(c.TooltipProvider,{children:s.jsxs(c.Tooltip,{children:[s.jsx(c.TooltipTrigger,{asChild:!0,children:e}),s.jsx(c.TooltipContent,{side:"bottom",sideOffset:10,children:s.jsx("p",{children:t})})]})})}const Na=()=>{const{selectedLang:e}=X.useLanguages(),t=Ve("getPreviewUrl",async g=>g),[n,r]=y.useState(""),{data:a,isFetching:i}=we(),{data:o}=mt(),{data:l}=Ee(),u=y.useMemo(()=>{var g;return(g=o==null?void 0:o.find(d=>(d==null?void 0:d.lang)===e))==null?void 0:g.slug},[e,o]),h=y.useCallback(g=>{var d;return(d=p.find(l,{key:g}))==null?void 0:d.hasSlug},[l]);return y.useEffect(()=>{(async()=>{if(u&&typeof t=="function"){const g=await t(u||"");r(g)}else r("")})()},[t,u]),!n||!h(a==null?void 0:a.pageType)||i?null:s.jsx(s.Fragment,{children:s.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:s.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[s.jsx(T.Eye,{className:"w-4 h-4"})," ",O.PREVIEW]})})})},Aa=()=>{const[e,t]=X.useRightPanel();return s.jsxs(s.Fragment,{children:[s.jsx(an,{content:O.THEME,children:s.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>t(e==="theme"?"block":"theme"),children:s.jsx(T.Palette,{className:"w-4 h-4"})})}),s.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})},Ta=()=>{const[e,t]=y.useState(!1),{isLocked:n}=Ut(),{savePage:r,saveState:a}=X.useSavePage();y.useEffect(()=>{const g=d=>{a==="UNSAVED"&&(d.preventDefault(),d.returnValue=!1)};return a==="UNSAVED"&&window.addEventListener("beforeunload",g),()=>{window.removeEventListener("beforeunload",g)}},[a]);const i=y.useCallback(async()=>{t(!0),await r(!1)},[r]);y.useEffect(()=>{a==="SAVED"&&t(!1)},[a]);const o=y.useMemo(()=>{if(a==="SAVED"||a==="UNSAVED")return a;if(a==="SAVING")return e?a:"SAVED"},[e,a]),{buttonIcon:l,buttonClass:u,tooltipContent:h}=y.useMemo(()=>{switch(o){case"UNSAVED":return{tooltipContent:O.SAVEDRAFT,buttonIcon:s.jsx(T.Save,{className:"w-4 h-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:O.SAVING,buttonIcon:s.jsx(T.Loader,{className:"w-4 h-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:O.SAVED,buttonIcon:s.jsx(T.CheckCircle,{className:"w-4 h-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[o]);return n?null:s.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[l," ",h]})},Ca=()=>{const[e,t]=y.useState(!1),[n,r]=y.useState(!1),[a,i]=y.useState(null),{data:o}=we(),{mutate:l,isPending:u}=js(),[h]=X.useBlocksStore(),{buttonText:g,buttonClassName:d,isPublished:b}=y.useMemo(()=>{const x=o&&(o==null?void 0:o.online);return{buttonClassName:x?"hover:bg-green-600 bg-green-500":"",isPublished:x,buttonText:x?O.PUBLISHED:O.PUBLISH}},[o]),v=async()=>{var w,E;const x=((E=(w=h==null?void 0:h.filter(C=>(C==null?void 0:C._type)==="GlobalBlock"))==null?void 0:w.map(C=>C==null?void 0:C.globalBlock))==null?void 0:E.filter(C=>typeof C=="string"))||[];l({ids:[o==null?void 0:o.id,...x]},{onSuccess:()=>zt("TOP_RIGHT")})};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex",children:[s.jsxs(c.Button,{size:"sm",onClick:v,disabled:u||!(o!=null&&o.id),className:`relative overflow-hidden transition-all duration-300 ease-in-out text-white flex items-center gap-1 rounded-r-none ${d}`,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[s.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${n?"-translate-y-10":""}`,children:b?s.jsx(T.Send,{className:"w-4 h-4"}):s.jsx(T.Rocket,{className:"w-4 h-4"})}),s.jsx("span",{className:`absolute inset-0 flex items-center left-3 transition-transform duration-300 ease-in-out ${n?"":"translate-y-10"}`,children:b?s.jsx(T.Rocket,{className:"w-4 h-4"}):s.jsx(T.Send,{className:"w-4 h-4"})}),s.jsx("span",{children:g})]}),s.jsxs(c.DropdownMenu,{children:[s.jsx(c.DropdownMenuTrigger,{asChild:!0,children:s.jsx(c.Button,{size:"sm",disabled:u||!(o!=null&&o.id),className:`px-2 text-white border-l border-white/50 rounded-l-none ${d}`,children:s.jsx(T.ChevronDown,{className:"w-4 h-4"})})}),s.jsxs(c.DropdownMenuContent,{align:"end",className:"w-36",children:[!b&&s.jsxs(c.DropdownMenuItem,{disabled:u,className:"text-xs cursor-pointer",onClick:()=>l({ids:[o==null?void 0:o.id]},{onSuccess:()=>zt("TOP_RIGHT")}),children:[O.PUBLISH," page"]}),s.jsxs(c.DropdownMenuItem,{onClick:()=>t(!0),className:"text-xs cursor-pointer",children:[O.OPEN," publish menu"]}),b&&s.jsxs(c.DropdownMenuItem,{onClick:()=>i(o),className:"text-xs cursor-pointer",children:[O.UNPUBLISH," page"]})]})]})]}),s.jsx(ja,{showModal:e,onClose:()=>t(!1)}),a&&s.jsx(ws,{page:a,onClose:()=>i(null)})]})},Pa=()=>{const e=Ve("settingComponent",null),[t,n]=y.useState(!1);return e?s.jsxs(s.Fragment,{children:[s.jsx(an,{content:O.WEBSITEDATA,children:s.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:s.jsx(T.Settings,{className:"w-4 h-4"})})}),t&&s.jsx(wa,{onClose:()=>n(!1)}),s.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]}):null},Ia=()=>{const{data:e}=we(),t=e&&(e==null?void 0:e.online),{data:n}=Ee();return y.useCallback(a=>{var i;return(i=p.find(n,{key:a}))==null?void 0:i.hasSlug},[n])(e==null?void 0:e.pageType)?s.jsxs(c.Button,{onClick:()=>t&&window.open(`${window.location.origin}${e.slug}`,"_blank"),disabled:!t,variant:"ghost",size:"sm",className:"flex items-center gap-1",children:[s.jsx(T.ExternalLink,{className:"w-4 h-4"}),s.jsx("span",{className:"hidden sm:inline",children:O.OPEN})]}):null};function _a(){const{isLocked:e}=Ut(),[t]=Ae(),n=t.get("lang"),r=Js(n);return e||!r?null:s.jsxs("div",{className:"flex items-center justify-end gap-1",children:[s.jsx(fa,{}),s.jsx(Ne,{permission:ue.EDIT_THEME,children:s.jsx(Aa,{})}),s.jsx(Ne,{permission:ue.EDIT_SETTINGS,children:s.jsx(Pa,{})}),s.jsx(Na,{}),s.jsx(Ne,{permission:ue.SAVE_PAGE,children:s.jsx(Ta,{})}),s.jsx(Ne,{permission:ue.PUBLISH_PAGE,children:s.jsx(Ca,{})}),s.jsx(Ia,{})]})}const ka=()=>s.jsxs("div",{className:"flex px-2 h-full items-center justify-between w-full",children:[s.jsx(ca,{}),s.jsx(_a,{})]}),La=()=>{const e=Z(),{aiContext:t}=vs(),n=W();return y.useCallback(async(r,a,i,o)=>n(e,{action:_.ASK_AI,data:{type:r,prompt:a,blocks:i,context:t,lang:o}}),[e,t,n])},Da=(e,t)=>t.map(n=>{if(p.has(e,n._type)){const r=Ws.getDefaultBlockProps(n._type);return{...r,...p.pick(n,[...p.keys(r),"_type","_id","_name","_parent","_bindings"]),...p.pickBy(n,(a,i)=>p.endsWith(i,"_attrs")),...n}}return n}),Ma=e=>{const t=Ws.useRegisteredChaiBlocks();return y.useMemo(()=>{if(!e||p.isEmpty(e))return{blocks:[]};const n=p.filter(e,r=>!p.includes(r==null?void 0:r._type,"@chai/"));return{blocks:Da(t,n)}},[e,t])},Ba=()=>{const e=Z(),t=W();return k.useQuery({queryKey:[je,"uiLibraries"],initialData:[],queryFn:async()=>(await t(e,{action:"GET_LIBRARIES"})).map(r=>({...r}))})},on=()=>{const e=es(),t=W(),{user:n}=Fe(),r=n==null?void 0:n.id;return k.useQuery({queryKey:[je,"permissions",r],queryFn:()=>t(e,{action:_.GET_ROLE_AND_PERMISSIONS,data:{userId:r}}),enabled:!!r})},Ga=()=>{const e=Z(),t=W(),{setCurrentEditor:n}=Ut(),[,r]=Es();return{getUILibraryBlock:async(l,u)=>{const h=await t(e,{action:"GET_LIBRARY_ITEM",data:{id:u.id}}),g=p.get(h,"html",""),d=p.get(h,"blocks",[]);return p.isArray(d)?d:X.getBlocksFromHTML(g)},getUILibraryBlocks:async l=>{try{return(await t(e,{action:"GET_LIBRARY_ITEMS",data:{id:l.id}})).map(h=>({...h}))}catch(u){return console.error(u),[]}},onSave:async({page:l,blocks:u})=>{try{const h=await t(e,{action:"UPDATE_PAGE",data:{id:l,blocks:u}});return h.code==="PAGE_LOCKED"?(n(h.editor===null?"EXPIRED":h.editor),!0):(r(g=>({...g,lastSaved:new Date().toISOString()})),h)}catch(h){return console.error(h),new Error("Failed to save blocks")}}}},Ra=()=>{const{data:e}=Rt(),t=Z(),n=W();return{getPartialBlocks:y.useCallback(async()=>{const r={};for(const a of e??[])p.isEmpty(a==null?void 0:a.slug)&&(r[a.id]={type:a.pageType,name:p.startCase(a.name??a.slug),description:""});return r},[e]),getPartialBlockBlocks:y.useCallback(async r=>{if(!r)return[];try{const a=await n(t,{action:"GET_DRAFT_PAGE",data:{id:r,draft:!0,editor:!1}});return p.filter(a.blocks,i=>p.has(i,"_id"))}catch(a){return console.error(a),[]}},[n,t])}},Ua=Ht.z.object({email:Ht.z.string().email({message:"Please enter a valid email address"}),password:Ht.z.string().min(6,{message:"Password must be at least 6 characters"})}),Oa=({onLoginSuccess:e})=>{const t=es(),[n,r]=y.useState(""),[a,i]=y.useState(""),[o,l]=y.useState({}),[u,h]=y.useState(!1),g=k.useMutation({mutationFn:async b=>{const v=await Qs(t,{action:"LOGIN",data:b});if(!v.ok){const w=await v.json();throw new Error(w.message||"Login failed")}const x=await v.json();return e(x),x},onSuccess:()=>{console.log("Login successful"),l({})},onError:b=>{console.error("Login failed:",b.message),l({email:" ",password:b.message||"Something went wrong"})}}),d=async b=>{b.preventDefault(),l({});const v={email:n,password:a};try{const x=Ua.parse(v);g.mutate(x)}catch(x){if(x instanceof Ht.z.ZodError){const w=x.errors.reduce((E,C)=>{const R=C.path[0];return E[R]=C.message,E},{});l(w)}}};return s.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:s.jsxs(c.Card,{className:"w-full max-w-md",children:[s.jsxs(c.CardHeader,{children:[s.jsx(c.CardTitle,{className:"text-2xl",children:"Login"}),s.jsx(c.CardDescription,{children:"Enter your credentials to access your account"})]}),s.jsx(c.CardContent,{children:s.jsxs("form",{onSubmit:d,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(c.Label,{htmlFor:"email",children:"Email"}),s.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:n,onChange:b=>r(b.target.value),className:o.email?"border-destructive":""}),o.email&&s.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(c.Label,{htmlFor:"password",children:"Password"}),s.jsxs("div",{className:"relative",children:[s.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:u?"text":"password",value:a,onChange:b=>i(b.target.value),className:o.password?"border-destructive":""}),s.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!u),children:u?s.jsx(T.EyeOff,{className:"h-4 w-4"}):s.jsx(T.Eye,{className:"h-4 w-4"})})]}),o.password&&s.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),s.jsx(c.Button,{type:"submit",className:"w-full",disabled:g.isPending,children:g.isPending?s.jsxs(s.Fragment,{children:[s.jsx(T.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),s.jsx(c.CardFooter,{className:"flex justify-center",children:s.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",s.jsx("a",{href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]})})]})})},Fa=()=>{const{setUser:e}=Fe();return s.jsx(Oa,{onLoginSuccess:t=>{console.log("login success",t),e(t)}})},qa=({isActive:e,show:t})=>{const{data:n}=ft();return!p.has(n,"languages")||!p.get(n,"languages",[]).length?null:s.jsx(c.Button,{size:"sm",onClick:t,variant:e?"default":"ghost",children:s.jsx(T.LanguagesIcon,{className:"w-4 h-4"})})},ln="lang",Ha={id:ln,label:"Languages",position:"top",panel:Wr,button:qa,view:"modal",width:400};function Me({data:e,onSelect:t,dataType:n="value",disabled:r=!1}){const[a,i]=ce.useState(!1),[o,l]=ce.useState([]),[u,h]=ce.useState(e);ce.useEffect(()=>{a||l([]),h(e)},[e,a]);const g=x=>Array.isArray(x)?"array":typeof x=="object"&&x!==null?"object":"value",d=ce.useCallback(x=>{const w=E=>n==="value"?E==="value"||E==="object":n==="array"?E==="array":E===n;x.type==="object"?(l(E=>[...E,x.key]),h(x.value)):w(x.type)&&(t([...o,x.key].join(".")),i(!1))},[o,t,n]),b=ce.useCallback(()=>{if(o.length>0){const x=o.slice(0,-1);l(x),h(x.reduce((w,E)=>w[E],e))}},[o,e]),v=ce.useMemo(()=>Object.entries(u).map(([x,w])=>({key:x,value:w,type:g(w)})).filter(x=>n==="value"?x.type==="value"||x.type==="object":n==="array"?x.type==="array"||x.type==="object":n==="object"?x.type==="object":!0),[u,n]);return s.jsxs(c.Popover,{open:a,onOpenChange:i,children:[s.jsxs(c.Tooltip,{children:[s.jsx(c.TooltipTrigger,{asChild:!0,children:s.jsx(c.PopoverTrigger,{asChild:!0,children:s.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":a,disabled:r,children:s.jsx(T.DatabaseIcon,{className:"h-3 w-3"})})})}),s.jsx(c.TooltipContent,{children:"Add field"})]}),s.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:s.jsxs(c.Command,{children:[s.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),s.jsxs(c.CommandList,{children:[s.jsx(c.CommandEmpty,{children:"No option found."}),s.jsxs(c.CommandGroup,{children:[o.length>0&&s.jsxs(c.CommandItem,{onSelect:b,className:"flex items-center text-sm",children:[s.jsx(T.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),v.map(x=>s.jsxs(c.CommandItem,{onSelect:()=>d(x),className:"flex items-center justify-between",children:[s.jsx("span",{children:x.key}),s.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&x.type==="object"&&s.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:w=>{w.stopPropagation(),t([...o,x.key].join(".")),i(!1)},children:"Select"}),(x.type==="object"||x.type==="array")&&s.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:s.jsx(T.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},x.key))]})]})]})})]})}const Ka=()=>{const{selectedLang:e}=X.useLanguages(),{data:t,isFetching:n}=mt();return{data:y.useMemo(()=>p.find(t,{lang:e||""})||{},[t,e]),isFetching:n}},za=(e,t)=>{const n=e.selectionStart||0,r=e.selectionEnd||0,a=e.value,i=a.substring(0,n),o=a.substring(r);let l=!1;if(n>0&&i.length>0){const x=i.charAt(i.length-1);l=!/[\s.,!?;:()[\]{}]/.test(x)&&x!==""}let u=!1;if(o.length>0){const x=o.charAt(0);u=!/[\s.,!?;:()[\]{}]/.test(x)&&x!==""}const h=l?" ":"",g=u?" ":"",d=`{{${t}}}`,b=i+(l?h:"")+d+(u?g:"")+o,v=n+(l?1:0)+d.length;return{value:b,newCursorPos:v}},cn=()=>{const{t:e}=X.useTranslation(),{selectedLang:t,fallbackLang:n,languages:r}=X.useLanguages(),[,a]=X.useSidebarActivePanel(),{data:i}=we(),{data:o}=tn({lang:t||n,pageType:i==null?void 0:i.pageType}),{data:l,isFetching:u}=Ka(),h=l==null?void 0:l.seo,g=y.useRef(null),[d,b]=y.useState({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...h}),v=y.useRef({initial:d,updated:d}),x=t.length?t:n,{mutate:w,isPending:E}=bs(),C=E,{hasPermission:R}=X.usePermissions(),j=R(ue.EDIT_SEO);y.useEffect(()=>{!u&&h&&b({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...h})},[u,h]);const S=async()=>{w({id:l==null?void 0:l.id,seo:d},{onSuccess:()=>{v.current.initial=d,v.current.updated=d,a("outline")}})},P=()=>{b({...d,ogTitle:d.title,ogDescription:d.description})},B=()=>{b({...d,searchTitle:d.ogTitle,searchDescription:d.ogDescription})},ee=(L,H)=>{const A=document.getElementById(H);if(A){const{value:F,newCursorPos:se}=za(A,L);g.current={id:H,position:se},A.tagName.toLowerCase()==="input"?(A.value=F,b(de=>({...de,[A.name]:F})),A.focus(),A.setSelectionRange(se,se),[0,10,50,100,200].forEach(de=>{setTimeout(()=>{const q=document.getElementById(H);q&&(q.focus(),q.setSelectionRange(se,se))},de)})):(b(Q=>({...Q,[A.name]:F})),requestAnimationFrame(()=>{const Q=document.getElementById(H);Q&&(Q.focus(),Q.setSelectionRange(se,se),setTimeout(()=>{const de=document.getElementById(H);de&&(de.focus(),de.setSelectionRange(se,se))},50))}))}},ie=L=>{const H={...d,[L.target.name]:L.target.name==="noIndex"||L.target.name==="noFollow"?L.target.checked:L.target.value};b(H),v.current.updated=H};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[!j&&s.jsx("div",{className:"absolute inset-0 z-10 backdrop-blur-sm flex items-center justify-center",children:s.jsx(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:s.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),s.jsxs("div",{className:"flex-grow overflow-y-auto no-scrollbar px-2",children:[s.jsxs("div",{className:"p-2 text-xs text-left bg-gray-100 rounded-md mb-4",children:[e("Slug"),": ",l==null?void 0:l.slug,"  ",r.length>0&&s.jsxs("span",{className:"font-semibold text-blue-500",children:["(",p.get(Pe,x,x),")"]})]}),s.jsx("form",{className:"space-y-8",children:s.jsxs(c.Accordion,{type:"multiple",defaultValue:["page"],children:[s.jsxs(c.AccordionItem,{value:"page",children:[s.jsx(c.AccordionTrigger,{className:"font-semibold text-slate-700",children:e("SEO")}),s.jsx(c.AccordionContent,{className:"pt-2",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"title")})]}),s.jsx(c.Input,{type:"text",id:"title",name:"title",value:d.title,onChange:ie,disabled:C||!j,placeholder:e("Enter SEO title"),readOnly:!j})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),j&&s.jsx(Me,{data:o??{},onSelect:L=>ee(L,"description")})]}),s.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:d.description,onChange:ie,disabled:C||!j,placeholder:e("Enter SEO description"),readOnly:!j})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"canonicalUrl")})]}),s.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:d.canonicalUrl,onChange:ie,disabled:C||!j,placeholder:e("Enter Canonical URL"),readOnly:!j})]}),s.jsxs("div",{className:"",children:[s.jsxs("div",{className:"flex items-center gap-x-2",children:[s.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:d.noIndex,onChange:ie,disabled:C||!j,className:"w-4 h-4"}),s.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),s.jsx("p",{className:"mt-0 text-[10px] font-light text-gray-400 leading-4",children:e("Check this if you don't want search engines to index this page.")})]}),s.jsxs("div",{className:"",children:[s.jsxs("div",{className:"flex items-center gap-x-2",children:[s.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:d.noFollow,onChange:ie,disabled:C||!j,className:"w-4 h-4"}),s.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),s.jsx("p",{className:"text-[10px] font-light text-gray-400 leading-4",children:e("Check this if you don't want search engines to follow links on this page.")})]})]})})]}),s.jsxs(c.AccordionItem,{value:"og",children:[s.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Open Graph")}),s.jsx(c.AccordionContent,{children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"flex items-center justify-between",children:s.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:P,disabled:!j,children:e("Copy from SEO Settings")})}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"ogTitle")})]}),s.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:d.ogTitle,onChange:ie,disabled:C||!j,placeholder:e("Enter OG title"),readOnly:!j})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"ogDescription")})]}),s.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:d.ogDescription,onChange:ie,disabled:C||!j,placeholder:e("Enter OG description"),readOnly:!j})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image URL")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"ogImage")})]}),s.jsx(c.Input,{type:"text",id:"ogImage",name:"ogImage",value:d.ogImage,onChange:ie,disabled:C||!j,placeholder:e("Enter OG image URL"),readOnly:!j})]})]})})]}),s.jsxs(c.AccordionItem,{value:"search",children:[s.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Search")}),s.jsx(c.AccordionContent,{children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"flex items-center justify-between",children:s.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:B,disabled:!j,children:e("Copy from OG Settings")})}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"searchTitle",children:e("Search Title")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"searchTitle")})]}),s.jsx(c.Input,{type:"text",id:"searchTitle",name:"searchTitle",value:d.searchTitle,onChange:ie,disabled:C||!j,placeholder:e("Enter search title"),readOnly:!j})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"searchDescription",children:e("Search Description")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"searchDescription")})]}),s.jsx(c.Textarea,{id:"searchDescription",rows:5,name:"searchDescription",value:d.searchDescription,onChange:ie,placeholder:e("Enter search description"),disabled:C||!j,readOnly:!j})]})]})})]}),s.jsxs(c.AccordionItem,{value:"jsonLD",className:"border-none",children:[s.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("JSON-LD")}),s.jsx(c.AccordionContent,{children:s.jsx("div",{className:"space-y-4",children:s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),j&&s.jsx(Me,{dataType:"value",data:o??{},onSelect:L=>ee(L,"jsonLD")})]}),s.jsx(c.Textarea,{id:"jsonLD",name:"jsonLD",rows:6,value:d.jsonLD,onChange:ie,placeholder:e("Enter JSON-LD"),disabled:C||!j,readOnly:!j})]})})})]})]})})]}),j&&s.jsx("div",{className:"flex-shrink-0 flex items-center justify-end w-full p-4 bg-background border-t",children:s.jsx(c.Button,{size:"lg",variant:"default",onClick:S,disabled:p.isEqual(v.current.initial,d)||C||!j,children:e(E?"Saving...":"Save")})})]})};cn.displayName="SeoPanel";const un="seo",Va=({isActive:e,show:t})=>{const{data:n}=we(),r=Br(n==null?void 0:n.pageType);return!p.has(r,"hasSlug")||!r.hasSlug?null:s.jsx(c.Button,{size:"sm",className:"my-1",onClick:t,variant:e?"default":"ghost",children:s.jsxs("svg",{className:"w-4 h-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[s.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"}),s.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"})]})})},$a={id:un,label:"SEO",panel:cn,button:Va,position:"top",view:"modal",width:600},Wa=()=>{X.registerChaiSidebarPanel(un,$a),X.registerChaiSidebarPanel(ln,Ha)},Qa="user-info",Ya=()=>{const{user:e,logout:t}=Fe();return e?s.jsxs(c.HoverCard,{children:[s.jsx(c.HoverCardTrigger,{asChild:!0,children:s.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:s.jsx(T.User,{className:"w-4 h-4"})})}),s.jsxs(c.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[s.jsx("div",{className:"text-sm font-medium",children:e.name}),s.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),s.jsxs(c.AlertDialog,{children:[s.jsx(c.AlertDialogTrigger,{asChild:!0,children:s.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),s.jsxs(c.AlertDialogContent,{children:[s.jsxs(c.AlertDialogHeader,{children:[s.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),s.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),s.jsxs(c.AlertDialogFooter,{children:[s.jsx(c.AlertDialogCancel,{children:"Cancel"}),s.jsx(c.AlertDialogAction,{onClick:()=>t(),children:"Logout"})]})]})]})]})]}):null},Xa={id:Qa,label:"User Info",button:Ya,position:"bottom"},Za=e=>(console.log(e),s.jsx("h1",{children:"Hello"}));var U={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Gs(this.context.count)},getNextContextId(){return Gs(this.context.count++)}};function Gs(e){const t=String(e),n=t.length-1;return U.context.id+(n?String.fromCharCode(96+n):"")+t}function xt(e){U.context=e}var Ja=(e,t)=>e===t,Vt=Symbol("solid-proxy"),dn=typeof Proxy=="function",Ns=Symbol("solid-track"),$t={equals:Ja},hn=vn,Ge=1,Wt=2,mn={owned:null,cleanups:null,context:null,owner:null},is={},J=null,os=null,ei=null,re=null,ve=null,Be=null,ts=0;function Re(e,t){const n=re,r=J,a=e.length===0,i=t===void 0?r:t,o=a?mn:{owned:null,cleanups:null,context:i?i.context:null,owner:i},l=a?e:()=>e(()=>xe(()=>jt(o)));J=o,re=null;try{return ke(l,!0)}finally{re=n,J=r}}function ge(e,t){t=t?Object.assign({},$t,t):$t;const n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0},r=a=>(typeof a=="function"&&(a=a(n.value)),yn(n,a));return[xn.bind(n),r]}function fn(e,t,n){const r=ss(e,t,!0,Ge);pt(r)}function Ue(e,t,n){const r=ss(e,t,!1,Ge);pt(r)}function As(e,t,n){hn=fi;const r=ss(e,t,!1,Ge);(!n||!n.render)&&(r.user=!0),Be?Be.push(r):pt(r)}function be(e,t,n){n=n?Object.assign({},$t,n):$t;const r=ss(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,pt(r),xn.bind(r)}function ti(e){return e&&typeof e=="object"&&"then"in e}function si(e,t,n){let r,a,i;arguments.length===1?(r=!0,a=e,i={}):(r=e,a=t,i={});let o=null,l=is,u=null,h=!1,g="initialValue"in i,d=typeof r=="function"&&be(r);const b=new Set,[v,x]=(i.storage||ge)(i.initialValue),[w,E]=ge(void 0),[C,R]=ge(void 0,{equals:!1}),[j,S]=ge(g?"ready":"unresolved");U.context&&(u=U.getNextContextId(),i.ssrLoadFrom==="initial"?l=i.initialValue:U.load&&U.has(u)&&(l=U.load(u)));function P(L,H,A,F){return o===L&&(o=null,F!==void 0&&(g=!0),(L===l||H===l)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(F,{value:H})),l=is,B(H,A)),H}function B(L,H){ke(()=>{H===void 0&&x(()=>L),S(H!==void 0?"errored":g?"ready":"unresolved"),E(H);for(const A of b.keys())A.decrement();b.clear()},!1)}function ee(){const L=di,H=v(),A=w();if(A!==void 0&&!o)throw A;return re&&re.user,H}function ie(L=!0){if(L!==!1&&h)return;h=!1;const H=d?d():r;if(H==null||H===!1){P(o,xe(v));return}const A=l!==is?l:xe(()=>a(H,{value:v(),refetching:L}));return ti(A)?(o=A,"value"in A?(A.status==="success"?P(o,A.value,void 0,H):P(o,void 0,us(A.value),H),A):(h=!0,queueMicrotask(()=>h=!1),ke(()=>{S(g?"refreshing":"pending"),R()},!1),A.then(F=>P(A,F,void 0,H),F=>P(A,void 0,us(F),H)))):(P(o,A,void 0,H),A)}return Object.defineProperties(ee,{state:{get:()=>j()},error:{get:()=>w()},loading:{get(){const L=j();return L==="pending"||L==="refreshing"}},latest:{get(){if(!g)return ee();const L=w();if(L&&!o)throw L;return v()}}}),d?fn(()=>ie(!1)):ie(!1),[ee,{refetch:ie,mutate:x}]}function ni(e){return ke(e,!1)}function xe(e){if(re===null)return e();const t=re;re=null;try{return e()}finally{re=t}}function ri(e,t,n){const r=Array.isArray(e);let a,i=n&&n.defer;return o=>{let l;if(r){l=Array(e.length);for(let h=0;h<e.length;h++)l[h]=e[h]()}else l=e();if(i)return i=!1,o;const u=xe(()=>t(l,a,o));return a=l,u}}function gn(e){As(()=>xe(e))}function dt(e){return J===null||(J.cleanups===null?J.cleanups=[e]:J.cleanups.push(e)),e}function Rs(){return J}function ai(e,t){const n=J,r=re;J=e,re=null;try{return ke(t,!0)}catch(a){Ts(a)}finally{J=n,re=r}}function ii(e){const t=re,n=J;return Promise.resolve().then(()=>{re=t,J=n;let r;return ke(e,!1),re=J=null,r?r.done:void 0})}var[oi,Qo]=ge(!1);function li(){return[oi,ii]}function ci(e,t){const n=Symbol("context");return{id:n,Provider:gi(n),defaultValue:e}}function ui(e){let t;return J&&J.context&&(t=J.context[e.id])!==void 0?t:e.defaultValue}function pn(e){const t=be(e),n=be(()=>ds(t()));return n.toArray=()=>{const r=n();return Array.isArray(r)?r:r!=null?[r]:[]},n}var di;function xn(){if(this.sources&&this.state)if(this.state===Ge)pt(this);else{const e=ve;ve=null,ke(()=>Yt(this),!1),ve=e}if(re){const e=this.observers?this.observers.length:0;re.sources?(re.sources.push(this),re.sourceSlots.push(e)):(re.sources=[this],re.sourceSlots=[e]),this.observers?(this.observers.push(re),this.observerSlots.push(re.sources.length-1)):(this.observers=[re],this.observerSlots=[re.sources.length-1])}return this.value}function yn(e,t,n){let r=e.value;return(!e.comparator||!e.comparator(r,t))&&(e.value=t,e.observers&&e.observers.length&&ke(()=>{for(let a=0;a<e.observers.length;a+=1){const i=e.observers[a],o=os&&os.running;o&&os.disposed.has(i),(o?!i.tState:!i.state)&&(i.pure?ve.push(i):Be.push(i),i.observers&&En(i)),o||(i.state=Ge)}if(ve.length>1e6)throw ve=[],new Error},!1)),t}function pt(e){if(!e.fn)return;jt(e);const t=ts;hi(e,e.value,t)}function hi(e,t,n){let r;const a=J,i=re;re=J=e;try{r=e.fn(t)}catch(o){return e.pure&&(e.state=Ge,e.owned&&e.owned.forEach(jt),e.owned=null),e.updatedAt=n+1,Ts(o)}finally{re=i,J=a}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?yn(e,r):e.value=r,e.updatedAt=n)}function ss(e,t,n,r=Ge,a){const i={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:J,context:J?J.context:null,pure:n};return J===null||J!==mn&&(J.owned?J.owned.push(i):J.owned=[i]),i}function Qt(e){if(e.state===0)return;if(e.state===Wt)return Yt(e);if(e.suspense&&xe(e.suspense.inFallback))return e.suspense.effects.push(e);const t=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<ts);)e.state&&t.push(e);for(let n=t.length-1;n>=0;n--)if(e=t[n],e.state===Ge)pt(e);else if(e.state===Wt){const r=ve;ve=null,ke(()=>Yt(e,t[0]),!1),ve=r}}function ke(e,t){if(ve)return e();let n=!1;t||(ve=[]),Be?n=!0:Be=[],ts++;try{const r=e();return mi(n),r}catch(r){n||(Be=null),ve=null,Ts(r)}}function mi(e){if(ve&&(vn(ve),ve=null),e)return;const t=Be;Be=null,t.length&&ke(()=>hn(t),!1)}function vn(e){for(let t=0;t<e.length;t++)Qt(e[t])}function fi(e){let t,n=0;for(t=0;t<e.length;t++){const r=e[t];r.user?e[n++]=r:Qt(r)}if(U.context){if(U.count){U.effects||(U.effects=[]),U.effects.push(...e.slice(0,n));return}xt()}for(U.effects&&(U.done||!U.count)&&(e=[...U.effects,...e],n+=U.effects.length,delete U.effects),t=0;t<n;t++)Qt(e[t])}function Yt(e,t){e.state=0;for(let n=0;n<e.sources.length;n+=1){const r=e.sources[n];if(r.sources){const a=r.state;a===Ge?r!==t&&(!r.updatedAt||r.updatedAt<ts)&&Qt(r):a===Wt&&Yt(r,t)}}}function En(e){for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t];n.state||(n.state=Wt,n.pure?ve.push(n):Be.push(n),n.observers&&En(n))}}function jt(e){let t;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),r=e.sourceSlots.pop(),a=n.observers;if(a&&a.length){const i=a.pop(),o=n.observerSlots.pop();r<a.length&&(i.sourceSlots[o]=r,a[r]=i,n.observerSlots[r]=o)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)jt(e.tOwned[t]);delete e.tOwned}if(e.owned){for(t=e.owned.length-1;t>=0;t--)jt(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}e.state=0}function us(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Ts(e,t=J){throw us(e)}function ds(e){if(typeof e=="function"&&!e.length)return ds(e());if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++){const r=ds(e[n]);Array.isArray(r)?t.push.apply(t,r):t.push(r)}return t}return e}function gi(e,t){return function(r){let a;return Ue(()=>a=xe(()=>(J.context={...J.context,[e]:r.value},pn(()=>r.children))),void 0),a}}var hs=Symbol("fallback");function Xt(e){for(let t=0;t<e.length;t++)e[t]()}function pi(e,t,n={}){let r=[],a=[],i=[],o=0,l=t.length>1?[]:null;return dt(()=>Xt(i)),()=>{let u=e()||[],h=u.length,g,d;return u[Ns],xe(()=>{let v,x,w,E,C,R,j,S,P;if(h===0)o!==0&&(Xt(i),i=[],r=[],a=[],o=0,l&&(l=[])),n.fallback&&(r=[hs],a[0]=Re(B=>(i[0]=B,n.fallback())),o=1);else if(o===0){for(a=new Array(h),d=0;d<h;d++)r[d]=u[d],a[d]=Re(b);o=h}else{for(w=new Array(h),E=new Array(h),l&&(C=new Array(h)),R=0,j=Math.min(o,h);R<j&&r[R]===u[R];R++);for(j=o-1,S=h-1;j>=R&&S>=R&&r[j]===u[S];j--,S--)w[S]=a[j],E[S]=i[j],l&&(C[S]=l[j]);for(v=new Map,x=new Array(S+1),d=S;d>=R;d--)P=u[d],g=v.get(P),x[d]=g===void 0?-1:g,v.set(P,d);for(g=R;g<=j;g++)P=r[g],d=v.get(P),d!==void 0&&d!==-1?(w[d]=a[g],E[d]=i[g],l&&(C[d]=l[g]),d=x[d],v.set(P,d)):i[g]();for(d=R;d<h;d++)d in w?(a[d]=w[d],i[d]=E[d],l&&(l[d]=C[d],l[d](d))):a[d]=Re(b);a=a.slice(0,o=h),r=u.slice(0)}return a});function b(v){if(i[d]=v,l){const[x,w]=ge(d);return l[d]=w,t(u[d],x)}return t(u[d])}}}function xi(e,t,n={}){let r=[],a=[],i=[],o=[],l=0,u;return dt(()=>Xt(i)),()=>{const h=e()||[],g=h.length;return h[Ns],xe(()=>{if(g===0)return l!==0&&(Xt(i),i=[],r=[],a=[],l=0,o=[]),n.fallback&&(r=[hs],a[0]=Re(b=>(i[0]=b,n.fallback())),l=1),a;for(r[0]===hs&&(i[0](),i=[],r=[],a=[],l=0),u=0;u<g;u++)u<r.length&&r[u]!==h[u]?o[u](()=>h[u]):u>=r.length&&(a[u]=Re(d));for(;u<r.length;u++)i[u]();return l=o.length=i.length=g,r=h.slice(0),a=a.slice(0,l)});function d(b){i[u]=b;const[v,x]=ge(h[u]);return o[u]=x,t(v,u)}}}function Cs(e,t){return xe(()=>e(t||{}))}function Ot(){return!0}var ms={get(e,t,n){return t===Vt?n:e.get(t)},has(e,t){return t===Vt?!0:e.has(t)},set:Ot,deleteProperty:Ot,getOwnPropertyDescriptor(e,t){return{configurable:!0,enumerable:!0,get(){return e.get(t)},set:Ot,deleteProperty:Ot}},ownKeys(e){return e.keys()}};function ls(e){return(e=typeof e=="function"?e():e)?e:{}}function yi(){for(let e=0,t=this.length;e<t;++e){const n=this[e]();if(n!==void 0)return n}}function Ps(...e){let t=!1;for(let o=0;o<e.length;o++){const l=e[o];t=t||!!l&&Vt in l,e[o]=typeof l=="function"?(t=!0,be(l)):l}if(dn&&t)return new Proxy({get(o){for(let l=e.length-1;l>=0;l--){const u=ls(e[l])[o];if(u!==void 0)return u}},has(o){for(let l=e.length-1;l>=0;l--)if(o in ls(e[l]))return!0;return!1},keys(){const o=[];for(let l=0;l<e.length;l++)o.push(...Object.keys(ls(e[l])));return[...new Set(o)]}},ms);const n={},r=Object.create(null);for(let o=e.length-1;o>=0;o--){const l=e[o];if(!l)continue;const u=Object.getOwnPropertyNames(l);for(let h=u.length-1;h>=0;h--){const g=u[h];if(g==="__proto__"||g==="constructor")continue;const d=Object.getOwnPropertyDescriptor(l,g);if(!r[g])r[g]=d.get?{enumerable:!0,configurable:!0,get:yi.bind(n[g]=[d.get.bind(l)])}:d.value!==void 0?d:void 0;else{const b=n[g];b&&(d.get?b.push(d.get.bind(l)):d.value!==void 0&&b.push(()=>d.value))}}}const a={},i=Object.keys(r);for(let o=i.length-1;o>=0;o--){const l=i[o],u=r[l];u&&u.get?Object.defineProperty(a,l,u):a[l]=u?u.value:void 0}return a}function bn(e,...t){if(dn&&Vt in e){const a=new Set(t.length>1?t.flat():t[0]),i=t.map(o=>new Proxy({get(l){return o.includes(l)?e[l]:void 0},has(l){return o.includes(l)&&l in e},keys(){return o.filter(l=>l in e)}},ms));return i.push(new Proxy({get(o){return a.has(o)?void 0:e[o]},has(o){return a.has(o)?!1:o in e},keys(){return Object.keys(e).filter(o=>!a.has(o))}},ms)),i}const n={},r=t.map(()=>({}));for(const a of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,a),o=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let l=!1,u=0;for(const h of t)h.includes(a)&&(l=!0,o?r[u][a]=i.value:Object.defineProperty(r[u],a,i)),++u;l||(o?n[a]=i.value:Object.defineProperty(n,a,i))}return[...r,n]}function jn(e){let t,n;const r=a=>{const i=U.context;if(i){const[l,u]=ge();U.count||(U.count=0),U.count++,(n||(n=e())).then(h=>{!U.done&&xt(i),U.count--,u(()=>h.default),xt()}),t=l}else if(!t){const[l]=si(()=>(n||(n=e())).then(u=>u.default));t=l}let o;return be(()=>(o=t())?xe(()=>{if(!i||U.done)return o(a);const l=U.context;xt(i);const u=o(a);return xt(l),u}):"")};return r.preload=()=>n||((n=e()).then(a=>t=()=>a.default),n),r}var vi=0;function Ei(){return U.context?U.getNextContextId():`cl-${vi++}`}var Sn=e=>`Stale read from <${e}>.`;function bi(e){const t="fallback"in e&&{fallback:()=>e.fallback};return be(pi(()=>e.each,e.children,t||void 0))}function ji(e){const t="fallback"in e&&{fallback:()=>e.fallback};return be(xi(()=>e.each,e.children,t||void 0))}function Si(e){const t=e.keyed,n=be(()=>e.when,void 0,{equals:(r,a)=>t?r===a:!r==!a});return be(()=>{const r=n();if(r){const a=e.children;return typeof a=="function"&&a.length>0?xe(()=>a(t?r:()=>{if(!xe(n))throw Sn("Show");return e.when})):a}return e.fallback},void 0,void 0)}function wi(e){let t=!1;const n=(i,o)=>(t?i[1]===o[1]:!i[1]==!o[1])&&i[2]===o[2],r=pn(()=>e.children),a=be(()=>{let i=r();Array.isArray(i)||(i=[i]);for(let o=0;o<i.length;o++){const l=i[o].when;if(l)return t=!!i[o].keyed,[o,l,i[o]]}return[-1]},void 0,{equals:n});return be(()=>{const[i,o,l]=a();if(i<0)return e.fallback;const u=l.children;return typeof u=="function"&&u.length>0?xe(()=>u(t?o:()=>{if(xe(a)[0]!==i)throw Sn("Match");return l.when})):u},void 0,void 0)}function Ni(e){return e}var Ai=["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"],Ti=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...Ai]),Ci=new Set(["innerHTML","textContent","innerText","children"]),Pi=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Ii=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 _i(e,t){const n=Ii[e];return typeof n=="object"?n[t]?n.$:void 0:n}var ki=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Li=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"]),Di={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function Mi(e,t,n){let r=n.length,a=t.length,i=r,o=0,l=0,u=t[a-1].nextSibling,h=null;for(;o<a||l<i;){if(t[o]===n[l]){o++,l++;continue}for(;t[a-1]===n[i-1];)a--,i--;if(a===o){const g=i<r?l?n[l-1].nextSibling:n[i-l]:u;for(;l<i;)e.insertBefore(n[l++],g)}else if(i===l)for(;o<a;)(!h||!h.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[i-1]&&n[l]===t[a-1]){const g=t[--a].nextSibling;e.insertBefore(n[l++],t[o++].nextSibling),e.insertBefore(n[--i],g),t[a]=n[i]}else{if(!h){h=new Map;let d=l;for(;d<i;)h.set(n[d],d++)}const g=h.get(t[o]);if(g!=null)if(l<g&&g<i){let d=o,b=1,v;for(;++d<a&&d<i&&!((v=h.get(t[d]))==null||v!==g+b);)b++;if(b>g-l){const x=t[o];for(;l<g;)e.insertBefore(n[l++],x)}else e.replaceChild(n[l++],t[o++])}else o++;else t[o++].remove()}}}var Et="_$DX_DELEGATE";function wn(e,t,n,r={}){let a;return Re(i=>{a=i,t===document?e():Jt(t,e(),t.firstChild?null:void 0,n)},r.owner),()=>{a(),t.textContent=""}}function Bi(e,t,n){let r;const a=()=>{const o=document.createElement("template");return o.innerHTML=e,o.content.firstChild},i=()=>(r||(r=a())).cloneNode(!0);return i.cloneNode=i,i}function Nn(e,t=window.document){const n=t[Et]||(t[Et]=new Set);for(let r=0,a=e.length;r<a;r++){const i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,In))}}function Gi(e=window.document){if(e[Et]){for(let t of e[Et].keys())e.removeEventListener(t,In);delete e[Et]}}function Zt(e,t,n){$e(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function Ri(e,t,n,r){$e(e)||(r==null?e.removeAttributeNS(t,n):e.setAttributeNS(t,n,r))}function Ui(e,t,n){$e(e)||(n?e.setAttribute(t,""):e.removeAttribute(t))}function An(e,t){$e(e)||(t==null?e.removeAttribute("class"):e.className=t)}function Tn(e,t,n,r){if(r)Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n;else if(Array.isArray(n)){const a=n[0];e.addEventListener(t,n[0]=i=>a.call(e,n[1],i))}else e.addEventListener(t,n,typeof n!="function"&&n)}function Oi(e,t,n={}){const r=Object.keys(t||{}),a=Object.keys(n);let i,o;for(i=0,o=a.length;i<o;i++){const l=a[i];!l||l==="undefined"||t[l]||(Us(e,l,!1),delete n[l])}for(i=0,o=r.length;i<o;i++){const l=r[i],u=!!t[l];!l||l==="undefined"||n[l]===u||!u||(Us(e,l,!0),n[l]=u)}return n}function Fi(e,t,n){if(!t)return n?Zt(e,"style"):t;const r=e.style;if(typeof t=="string")return r.cssText=t;typeof n=="string"&&(r.cssText=n=void 0),n||(n={}),t||(t={});let a,i;for(i in n)t[i]==null&&r.removeProperty(i),delete n[i];for(i in t)a=t[i],a!==n[i]&&(r.setProperty(i,a),n[i]=a);return n}function Cn(e,t={},n,r){const a={};return r||Ue(()=>a.children=St(e,t.children,a.children)),Ue(()=>typeof t.ref=="function"&&Pn(t.ref,e)),Ue(()=>qi(e,t,n,!0,a,!0)),a}function Pn(e,t,n){return xe(()=>e(t,n))}function Jt(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!="function")return St(e,t,r,n);Ue(a=>St(e,t(),a,n),r)}function qi(e,t,n,r,a={},i=!1){t||(t={});for(const o in a)if(!(o in t)){if(o==="children")continue;a[o]=Os(e,o,null,a[o],n,i,t)}for(const o in t){if(o==="children")continue;const l=t[o];a[o]=Os(e,o,l,a[o],n,i,t)}}function Hi(e){let t,n;return!$e()||!(t=U.registry.get(n=zi()))?e():(U.completed&&U.completed.add(t),U.registry.delete(n),t)}function $e(e){return!!U.context&&!U.done&&(!e||e.isConnected)}function Ki(e){return e.toLowerCase().replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}function Us(e,t,n){const r=t.trim().split(/\s+/);for(let a=0,i=r.length;a<i;a++)e.classList.toggle(r[a],n)}function Os(e,t,n,r,a,i,o){let l,u,h,g,d;if(t==="style")return Fi(e,n,r);if(t==="classList")return Oi(e,n,r);if(n===r)return r;if(t==="ref")i||n(e);else if(t.slice(0,3)==="on:"){const b=t.slice(3);r&&e.removeEventListener(b,r,typeof r!="function"&&r),n&&e.addEventListener(b,n,typeof n!="function"&&n)}else if(t.slice(0,10)==="oncapture:"){const b=t.slice(10);r&&e.removeEventListener(b,r,!0),n&&e.addEventListener(b,n,!0)}else if(t.slice(0,2)==="on"){const b=t.slice(2).toLowerCase(),v=ki.has(b);if(!v&&r){const x=Array.isArray(r)?r[0]:r;e.removeEventListener(b,x)}(v||n)&&(Tn(e,b,n,v),v&&Nn([b]))}else if(t.slice(0,5)==="attr:")Zt(e,t.slice(5),n);else if(t.slice(0,5)==="bool:")Ui(e,t.slice(5),n);else if((d=t.slice(0,5)==="prop:")||(h=Ci.has(t))||!a&&((g=_i(t,e.tagName))||(u=Ti.has(t)))||(l=e.nodeName.includes("-")||"is"in o)){if(d)t=t.slice(5),u=!0;else if($e(e))return n;t==="class"||t==="className"?An(e,n):l&&!u&&!h?e[Ki(t)]=n:e[g||t]=n}else{const b=a&&t.indexOf(":")>-1&&Di[t.split(":")[0]];b?Ri(e,b,t,n):Zt(e,Pi[t]||t,n)}return n}function In(e){if(U.registry&&U.events&&U.events.find(([u,h])=>h===e))return;let t=e.target;const n=`$$${e.type}`,r=e.target,a=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),o=()=>{const u=t[n];if(u&&!t.disabled){const h=t[`${n}Data`];if(h!==void 0?u.call(t,h,e):u.call(t,e),e.cancelBubble)return}return t.host&&typeof t.host!="string"&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},l=()=>{for(;o()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return t||document}}),U.registry&&!U.done&&(U.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let h=0;h<u.length-2&&(t=u[h],!!o());h++){if(t._$host){t=t._$host,l();break}if(t.parentNode===a)break}}else l();i(r)}function St(e,t,n,r,a){const i=$e(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let h=0;h<n.length;h++){const g=n[h];g.nodeType===8&&g.data.slice(0,2)==="!$"?g.remove():u.push(g)}n=u}for(;typeof n=="function";)n=n();if(t===n)return n;const o=typeof t,l=r!==void 0;if(e=l&&n[0]&&n[0].parentNode||e,o==="string"||o==="number"){if(i||o==="number"&&(t=t.toString(),t===n))return n;if(l){let u=n[0];u&&u.nodeType===3?u.data!==t&&(u.data=t):u=document.createTextNode(t),n=We(e,n,r,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=t:n=e.textContent=t}else if(t==null||o==="boolean"){if(i)return n;n=We(e,n,r)}else{if(o==="function")return Ue(()=>{let u=t();for(;typeof u=="function";)u=u();n=St(e,u,n,r)}),()=>n;if(Array.isArray(t)){const u=[],h=n&&Array.isArray(n);if(fs(u,t,n,a))return Ue(()=>n=St(e,u,n,r,!0)),()=>n;if(i){if(!u.length)return n;if(r===void 0)return n=[...e.childNodes];let g=u[0];if(g.parentNode!==e)return n;const d=[g];for(;(g=g.nextSibling)!==r;)d.push(g);return n=d}if(u.length===0){if(n=We(e,n,r),l)return n}else h?n.length===0?Fs(e,u,r):Mi(e,n,u):(n&&We(e),Fs(e,u));n=u}else if(t.nodeType){if(i&&t.parentNode)return n=l?[t]:t;if(Array.isArray(n)){if(l)return n=We(e,n,r,t);We(e,n,null,t)}else n==null||n===""||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}}return n}function fs(e,t,n,r){let a=!1;for(let i=0,o=t.length;i<o;i++){let l=t[i],u=n&&n[e.length],h;if(!(l==null||l===!0||l===!1))if((h=typeof l)=="object"&&l.nodeType)e.push(l);else if(Array.isArray(l))a=fs(e,l,u)||a;else if(h==="function")if(r){for(;typeof l=="function";)l=l();a=fs(e,Array.isArray(l)?l:[l],Array.isArray(u)?u:[u])||a}else e.push(l),a=!0;else{const g=String(l);u&&u.nodeType===3&&u.data===g?e.push(u):e.push(document.createTextNode(g))}}return a}function Fs(e,t,n=null){for(let r=0,a=t.length;r<a;r++)e.insertBefore(t[r],n)}function We(e,t,n,r){if(n===void 0)return e.textContent="";const a=r||document.createTextNode("");if(t.length){let i=!1;for(let o=t.length-1;o>=0;o--){const l=t[o];if(a!==l){const u=l.parentNode===e;!i&&!o?u?e.replaceChild(a,l):e.insertBefore(a,n):u&&l.remove()}else i=!0}}else e.insertBefore(a,n);return[a]}function zi(){return U.getNextContextId()}var Vi="http://www.w3.org/2000/svg";function _n(e,t=!1){return t?document.createElementNS(Vi,e):document.createElement(e)}function $i(e){const{useShadow:t}=e,n=document.createTextNode(""),r=()=>e.mount||document.body,a=Rs();let i,o=!!U.context;return As(()=>{o&&(Rs().user=o=!1),i||(i=ai(a,()=>be(()=>e.children)));const l=r();if(l instanceof HTMLHeadElement){const[u,h]=ge(!1),g=()=>h(!0);Re(d=>Jt(l,()=>u()?d():i(),null)),dt(g)}else{const u=_n(e.isSVG?"g":"div",e.isSVG),h=t&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),Jt(h,i),l.appendChild(u),e.ref&&e.ref(u),dt(()=>l.removeChild(u))}},void 0,{render:!o}),n}function Wi(e){const[t,n]=bn(e,["component"]),r=be(()=>t.component);return be(()=>{const a=r();switch(typeof a){case"function":return xe(()=>a(n));case"string":const i=Li.has(a),o=U.context?Hi():_n(a,i);return Cn(o,n,i),o}})}var Qi=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},kn=class{constructor(e){this.generateIdentifier=e,this.kv=new Qi}register(e,t){this.kv.getByValue(e)||(t||(t=this.generateIdentifier(e)),this.kv.set(t,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},Yi=class extends kn{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,t){typeof t=="object"?(t.allowProps&&this.classToAllowedProps.set(e,t.allowProps),super.register(e,t.identifier)):super.register(e,t)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function Xi(e){if("values"in Object)return Object.values(e);const t=[];for(const n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function Zi(e,t){const n=Xi(e);if("find"in n)return n.find(t);const r=n;for(let a=0;a<r.length;a++){const i=r[a];if(t(i))return i}}function ht(e,t){Object.entries(e).forEach(([n,r])=>t(r,n))}function Kt(e,t){return e.indexOf(t)!==-1}function qs(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(t(r))return r}}var Ji=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Zi(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},eo=e=>Object.prototype.toString.call(e).slice(8,-1),Ln=e=>typeof e>"u",to=e=>e===null,wt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,gs=e=>wt(e)&&Object.keys(e).length===0,Oe=e=>Array.isArray(e),so=e=>typeof e=="string",no=e=>typeof e=="number"&&!isNaN(e),ro=e=>typeof e=="boolean",ao=e=>e instanceof RegExp,Nt=e=>e instanceof Map,At=e=>e instanceof Set,Dn=e=>eo(e)==="Symbol",io=e=>e instanceof Date&&!isNaN(e.valueOf()),oo=e=>e instanceof Error,Hs=e=>typeof e=="number"&&isNaN(e),lo=e=>ro(e)||to(e)||Ln(e)||no(e)||so(e)||Dn(e),co=e=>typeof e=="bigint",uo=e=>e===1/0||e===-1/0,ho=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),mo=e=>e instanceof URL,Mn=e=>e.replace(/\./g,"\\."),cs=e=>e.map(String).map(Mn).join("."),bt=e=>{const t=[];let n="";for(let a=0;a<e.length;a++){let i=e.charAt(a);if(i==="\\"&&e.charAt(a+1)==="."){n+=".",a++;continue}if(i==="."){t.push(n),n="";continue}n+=i}const r=n;return t.push(r),t};function _e(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Bn=[_e(Ln,"undefined",()=>null,()=>{}),_e(co,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),_e(io,"Date",e=>e.toISOString(),e=>new Date(e)),_e(oo,"Error",(e,t)=>{const n={name:e.name,message:e.message};return t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n},(e,t)=>{const n=new Error(e.message);return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n}),_e(ao,"regexp",e=>""+e,e=>{const t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),_e(At,"set",e=>[...e.values()],e=>new Set(e)),_e(Nt,"map",e=>[...e.entries()],e=>new Map(e)),_e(e=>Hs(e)||uo(e),"number",e=>Hs(e)?"NaN":e>0?"Infinity":"-Infinity",Number),_e(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),_e(mo,"URL",e=>e.toString(),e=>new URL(e))];function ns(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Gn=ns((e,t)=>Dn(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{const r=n.symbolRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown symbol");return r}),fo=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),Rn=ns(ho,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{const n=fo[t[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function Un(e,t){return e!=null&&e.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var On=ns(Un,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{const n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};const r={};return n.forEach(a=>{r[a]=e[a]}),r},(e,t,n)=>{const r=n.classRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");return Object.assign(Object.create(r.prototype),e)}),Fn=ns((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{const r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw new Error("Trying to deserialize unknown custom value");return r.deserialize(e)}),go=[On,Gn,Fn,Rn],Ks=(e,t)=>{const n=qs(go,a=>a.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};const r=qs(Bn,a=>a.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},qn={};Bn.forEach(e=>{qn[e.annotation]=e});var po=(e,t,n)=>{if(Oe(t))switch(t[0]){case"symbol":return Gn.untransform(e,t,n);case"class":return On.untransform(e,t,n);case"custom":return Fn.untransform(e,t,n);case"typed-array":return Rn.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{const r=qn[t];if(!r)throw new Error("Unknown transformation: "+t);return r.untransform(e,n)}},Qe=(e,t)=>{const n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function Hn(e){if(Kt(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Kt(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Kt(e,"constructor"))throw new Error("constructor is not allowed as a property")}var xo=(e,t)=>{Hn(t);for(let n=0;n<t.length;n++){const r=t[n];if(At(e))e=Qe(e,+r);else if(Nt(e)){const a=+r,i=+t[++n]==0?"key":"value",o=Qe(e,a);switch(i){case"key":e=o;break;case"value":e=e.get(o);break}}else e=e[r]}return e},ps=(e,t,n)=>{if(Hn(t),t.length===0)return n(e);let r=e;for(let i=0;i<t.length-1;i++){const o=t[i];if(Oe(r)){const l=+o;r=r[l]}else if(wt(r))r=r[o];else if(At(r)){const l=+o;r=Qe(r,l)}else if(Nt(r)){if(i===t.length-2)break;const u=+o,h=+t[++i]==0?"key":"value",g=Qe(r,u);switch(h){case"key":r=g;break;case"value":r=r.get(g);break}}}const a=t[t.length-1];if(Oe(r)?r[+a]=n(r[+a]):wt(r)&&(r[a]=n(r[a])),At(r)){const i=Qe(r,+a),o=n(i);i!==o&&(r.delete(i),r.add(o))}if(Nt(r)){const i=+t[t.length-2],o=Qe(r,i);switch(+a==0?"key":"value"){case"key":{const u=n(o);r.set(u,r.get(o)),u!==o&&r.delete(o);break}case"value":{r.set(o,n(r.get(o)));break}}}return e};function xs(e,t,n=[]){if(!e)return;if(!Oe(e)){ht(e,(i,o)=>xs(i,t,[...n,...bt(o)]));return}const[r,a]=e;a&&ht(a,(i,o)=>{xs(i,t,[...n,...bt(o)])}),t(r,n)}function yo(e,t,n){return xs(t,(r,a)=>{e=ps(e,a,i=>po(i,r,n))}),e}function vo(e,t){function n(r,a){const i=xo(e,bt(a));r.map(bt).forEach(o=>{e=ps(e,o,()=>i)})}if(Oe(t)){const[r,a]=t;r.forEach(i=>{e=ps(e,bt(i),()=>e)}),a&&ht(a,n)}else ht(t,n);return e}var Eo=(e,t)=>wt(e)||Oe(e)||Nt(e)||At(e)||Un(e,t);function bo(e,t,n){const r=n.get(e);r?r.push(t):n.set(e,[t])}function jo(e,t){const n={};let r;return e.forEach(a=>{if(a.length<=1)return;t||(a=a.map(l=>l.map(String)).sort((l,u)=>l.length-u.length));const[i,...o]=a;i.length===0?r=o.map(cs):n[cs(i)]=o.map(cs)}),r?gs(n)?[r]:[r,n]:gs(n)?void 0:n}var Kn=(e,t,n,r,a=[],i=[],o=new Map)=>{const l=lo(e);if(!l){bo(e,a,t);const v=o.get(e);if(v)return r?{transformedValue:null}:v}if(!Eo(e,n)){const v=Ks(e,n),x=v?{transformedValue:v.value,annotations:[v.type]}:{transformedValue:e};return l||o.set(e,x),x}if(Kt(i,e))return{transformedValue:null};const u=Ks(e,n),h=(u==null?void 0:u.value)??e,g=Oe(h)?[]:{},d={};ht(h,(v,x)=>{if(x==="__proto__"||x==="constructor"||x==="prototype")throw new Error(`Detected property ${x}. This is a prototype pollution risk, please remove it from your object.`);const w=Kn(v,t,n,r,[...a,x],[...i,e],o);g[x]=w.transformedValue,Oe(w.annotations)?d[x]=w.annotations:wt(w.annotations)&&ht(w.annotations,(E,C)=>{d[Mn(x)+"."+C]=E})});const b=gs(d)?{transformedValue:g,annotations:u?[u.type]:void 0}:{transformedValue:g,annotations:u?[u.type,d]:d};return l||o.set(e,b),b};function zn(e){return Object.prototype.toString.call(e).slice(8,-1)}function zs(e){return zn(e)==="Array"}function So(e){if(zn(e)!=="Object")return!1;const t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function wo(e,t,n,r,a){const i={}.propertyIsEnumerable.call(r,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=n),a&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function ys(e,t={}){if(zs(e))return e.map(a=>ys(a,t));if(!So(e))return e;const n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((a,i)=>{if(zs(t.props)&&!t.props.includes(i))return a;const o=e[i],l=ys(o,t);return wo(a,i,l,e,t.nonenumerable),a},{})}var ae=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Yi,this.symbolRegistry=new kn(t=>t.description??""),this.customTransformerRegistry=new Ji,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const t=new Map,n=Kn(e,t,this,this.dedupe),r={json:n.transformedValue};n.annotations&&(r.meta={...r.meta,values:n.annotations});const a=jo(t,this.dedupe);return a&&(r.meta={...r.meta,referentialEqualities:a}),r}deserialize(e){const{json:t,meta:n}=e;let r=ys(t);return n!=null&&n.values&&(r=yo(r,n.values,this)),n!=null&&n.referentialEqualities&&(r=vo(r,n.referentialEqualities)),r}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,t){this.classRegistry.register(e,t)}registerSymbol(e,t){this.symbolRegistry.register(e,t)}registerCustom(e,t){this.customTransformerRegistry.register({name:t,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};ae.defaultInstance=new ae;ae.serialize=ae.defaultInstance.serialize.bind(ae.defaultInstance);ae.deserialize=ae.defaultInstance.deserialize.bind(ae.defaultInstance);ae.stringify=ae.defaultInstance.stringify.bind(ae.defaultInstance);ae.parse=ae.defaultInstance.parse.bind(ae.defaultInstance);ae.registerClass=ae.defaultInstance.registerClass.bind(ae.defaultInstance);ae.registerSymbol=ae.defaultInstance.registerSymbol.bind(ae.defaultInstance);ae.registerCustom=ae.defaultInstance.registerCustom.bind(ae.defaultInstance);ae.allowErrorProps=ae.defaultInstance.allowErrorProps.bind(ae.defaultInstance);var Vn=ae.serialize,No=ae.stringify;function Ao(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function To(e,t){return`${e}${t.charAt(0).toUpperCase()+t.slice(1)}`}function Co({queryState:e,observerCount:t,isStale:n}){return e.fetchStatus==="fetching"?"blue":t?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function Po({status:e,isPaused:t}){return t?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function Io(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var _o=(e,t=!1)=>{const{json:n}=Vn(e);return JSON.stringify(n,null,t?2:void 0)},Ft=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,ko=(e,t)=>e.queryHash.localeCompare(t.queryHash),$n=(e,t)=>e.state.dataUpdatedAt<t.state.dataUpdatedAt?1:-1,Lo=(e,t)=>Ft(e)===Ft(t)?$n(e,t):Ft(e)>Ft(t)?1:-1,Do={status:Lo,"query hash":ko,"last updated":$n},qt=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Wn=(e,t)=>e.state.submittedAt<t.state.submittedAt?1:-1,Mo=(e,t)=>qt(e)===qt(t)?Wn(e,t):qt(e)>qt(t)?1:-1,Bo={status:Mo,"last updated":Wn},Go=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),Ro=()=>{const[e,t]=ge("dark");return gn(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");t(n.matches?"dark":"light");const r=a=>{t(a.matches?"dark":"light")};n.addEventListener("change",r),dt(()=>n.removeEventListener("change",r))}),e},yt=(e,t,n)=>{if(t.length===0)return n;if(e instanceof Map){const r=new Map(e);if(t.length===1)return r.set(t[0],n),r;const[a,...i]=t;return r.set(a,yt(r.get(a),i,n)),r}if(e instanceof Set){const r=yt(Array.from(e),t,n);return new Set(r)}if(Array.isArray(e)){const r=[...e];if(t.length===1)return r[t[0]]=n,r;const[a,...i]=t;return r[a]=yt(r[a],i,n),r}if(e instanceof Object){const r={...e};if(t.length===1)return r[t[0]]=n,r;const[a,...i]=t;return r[a]=yt(r[a],i,n),r}return e},vt=(e,t)=>{if(e instanceof Map){const n=new Map(e);if(t.length===1)return n.delete(t[0]),n;const[r,...a]=t;return n.set(r,vt(n.get(r),a)),n}if(e instanceof Set){const n=vt(Array.from(e),t);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(t.length===1)return n.filter((i,o)=>o.toString()!==t[0]);const[r,...a]=t;return n[r]=vt(n[r],a),n}if(e instanceof Object){const n={...e};if(t.length===1)return delete n[t[0]],n;const[r,...a]=t;return n[r]=vt(n[r],a),n}return e},Qn=(e,t)=>{if(!e||document.querySelector("#_goober")||(t==null?void 0:t.querySelector("#_goober")))return;const r=document.createElement("style"),a=document.createTextNode("");r.appendChild(a),r.id="_goober",r.setAttribute("nonce",e),t?t.appendChild(r):document.head.appendChild(r)},Ye,Tt,Ct,Pt,He,It,Xe,Ze,Je,et,tt,st,_t,Vs,Uo=(Vs=class{constructor(e){ne(this,Ye);ne(this,Tt);ne(this,Ct);ne(this,Pt);ne(this,He,!1);ne(this,It);ne(this,Xe);ne(this,Ze);ne(this,Je);ne(this,et);ne(this,tt);ne(this,st);ne(this,_t);const{client:t,queryFlavor:n,version:r,onlineManager:a,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:h,shadowDOMTarget:g}=e;te(this,Ye,ge(t)),te(this,Ct,n),te(this,Pt,r),te(this,Tt,a),te(this,It,h),te(this,Xe,g),te(this,Ze,ge(i)),te(this,Je,ge(o)),te(this,et,ge(l)),te(this,tt,ge(u))}setButtonPosition(e){G(this,Ze)[1](e)}setPosition(e){G(this,Je)[1](e)}setInitialIsOpen(e){G(this,et)[1](e)}setErrorTypes(e){G(this,tt)[1](e)}setClient(e){G(this,Ye)[1](e)}mount(e){if(G(this,He))throw new Error("Devtools is already mounted");const t=wn(()=>{const n=this,[r]=G(this,Ze),[a]=G(this,Je),[i]=G(this,et),[o]=G(this,tt),[l]=G(this,Ye);let u;return G(this,st)?u=G(this,st):(u=jn(()=>Promise.resolve().then(()=>require("./HO4MOOFI-CzFDjam4.cjs"))),te(this,st,u)),Qn(G(this,It),G(this,Xe)),Cs(u,Ps({get queryFlavor(){return G(n,Ct)},get version(){return G(n,Pt)},get onlineManager(){return G(n,Tt)},get shadowDOMTarget(){return G(n,Xe)}},{get client(){return l()},get buttonPosition(){return r()},get position(){return a()},get initialIsOpen(){return i()},get errorTypes(){return o()}}))},e);te(this,He,!0),te(this,_t,t)}unmount(){var e;if(!G(this,He))throw new Error("Devtools is not mounted");(e=G(this,_t))==null||e.call(this),te(this,He,!1)}},Ye=new WeakMap,Tt=new WeakMap,Ct=new WeakMap,Pt=new WeakMap,He=new WeakMap,It=new WeakMap,Xe=new WeakMap,Ze=new WeakMap,Je=new WeakMap,et=new WeakMap,tt=new WeakMap,st=new WeakMap,_t=new WeakMap,Vs),nt,kt,Lt,Dt,Ke,Mt,rt,at,it,ot,lt,ct,ut,Bt,$s,Oo=($s=class{constructor(e){ne(this,nt);ne(this,kt);ne(this,Lt);ne(this,Dt);ne(this,Ke,!1);ne(this,Mt);ne(this,rt);ne(this,at);ne(this,it);ne(this,ot);ne(this,lt);ne(this,ct);ne(this,ut);ne(this,Bt);const{client:t,queryFlavor:n,version:r,onlineManager:a,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:h,shadowDOMTarget:g,onClose:d}=e;te(this,nt,ge(t)),te(this,Lt,n),te(this,Dt,r),te(this,kt,a),te(this,Mt,h),te(this,rt,g),te(this,at,ge(i)),te(this,it,ge(o)),te(this,ot,ge(l)),te(this,lt,ge(u)),te(this,ct,ge(d))}setButtonPosition(e){G(this,at)[1](e)}setPosition(e){G(this,it)[1](e)}setInitialIsOpen(e){G(this,ot)[1](e)}setErrorTypes(e){G(this,lt)[1](e)}setClient(e){G(this,nt)[1](e)}setOnClose(e){G(this,ct)[1](()=>e)}mount(e){if(G(this,Ke))throw new Error("Devtools is already mounted");const t=wn(()=>{const n=this,[r]=G(this,at),[a]=G(this,it),[i]=G(this,ot),[o]=G(this,lt),[l]=G(this,nt),[u]=G(this,ct);let h;return G(this,ut)?h=G(this,ut):(h=jn(()=>Promise.resolve().then(()=>require("./HUY7CZI3-B_YPIkQ9.cjs"))),te(this,ut,h)),Qn(G(this,Mt),G(this,rt)),Cs(h,Ps({get queryFlavor(){return G(n,Lt)},get version(){return G(n,Dt)},get onlineManager(){return G(n,kt)},get shadowDOMTarget(){return G(n,rt)}},{get client(){return l()},get buttonPosition(){return r()},get position(){return a()},get initialIsOpen(){return i()},get errorTypes(){return o()},get onClose(){return u()}}))},e);te(this,Ke,!0),te(this,Bt,t)}unmount(){var e;if(!G(this,Ke))throw new Error("Devtools is not mounted");(e=G(this,Bt))==null||e.call(this),te(this,Ke,!1)}},nt=new WeakMap,kt=new WeakMap,Lt=new WeakMap,Dt=new WeakMap,Ke=new WeakMap,Mt=new WeakMap,rt=new WeakMap,at=new WeakMap,it=new WeakMap,ot=new WeakMap,lt=new WeakMap,ct=new WeakMap,ut=new WeakMap,Bt=new WeakMap,$s);function Fo(e){const t=k.useQueryClient(e.client),n=ce.useRef(null),{buttonPosition:r,position:a,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u}=e,[h]=ce.useState(new Uo({client:t,queryFlavor:"React Query",version:"5",onlineManager:k.onlineManager,buttonPosition:r,position:a,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u}));return ce.useEffect(()=>{h.setClient(t)},[t,h]),ce.useEffect(()=>{r&&h.setButtonPosition(r)},[r,h]),ce.useEffect(()=>{a&&h.setPosition(a)},[a,h]),ce.useEffect(()=>{h.setInitialIsOpen(i||!1)},[i,h]),ce.useEffect(()=>{h.setErrorTypes(o||[])},[o,h]),ce.useEffect(()=>(n.current&&h.mount(n.current),()=>{h.unmount()}),[h]),s.jsx("div",{className:"tsqd-parent-container",ref:n})}function qo(e){const t=k.useQueryClient(e.client),n=ce.useRef(null),{errorTypes:r,styleNonce:a,shadowDOMTarget:i}=e,[o]=ce.useState(new Oo({client:t,queryFlavor:"React Query",version:"5",onlineManager:k.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:r,styleNonce:a,shadowDOMTarget:i,onClose:e.onClose}));return ce.useEffect(()=>{o.setClient(t)},[t,o]),ce.useEffect(()=>{o.setOnClose(e.onClose??(()=>{}))},[e.onClose,o]),ce.useEffect(()=>{o.setErrorTypes(r||[])},[r,o]),ce.useEffect(()=>(n.current&&o.mount(n.current),()=>{o.unmount()}),[o]),s.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var Ho=process.env.NODE_ENV!=="development"?function(){return null}:Fo;process.env.NODE_ENV;rr.loadWebBlocks();Wa();X.registerChaiTopBar(ka);X.registerChaiSaveToLibrary(Dr);X.registerChaiMediaManager(Za);X.registerChaiSidebarPanel("user-info",Xa);const Ko=e=>{const t=y.useRef([]),[n]=Ae(),r=n.get("page"),a=n.get("lang"),{data:i}=we(),{data:o={role:"",permissions:null}}=on(),{data:l}=Ba(),{data:u,isFetching:h}=en(),{blocks:g}=Ma(u),{data:d}=ft(),{data:b}=Ee(),{mutateAsync:v}=Xs(),x=La(),{getUILibraryBlock:w,getUILibraryBlocks:E,onSave:C}=Ga(),{getPartialBlocks:R,getPartialBlockBlocks:j}=Ra(),{aiContext:S,setAiContext:P}=vs(),{mutateAsync:B}=Gr(),[ee,ie]=y.useState(!1),L=y.useMemo(()=>(d==null?void 0:d.fallbackLang)||"en",[d]),{data:H}=tn({pageType:i==null?void 0:i.pageType,lang:a||L});vr(),y.useEffect(()=>{const Q=()=>{document.hidden?ie(!0):ie(!1)};return window.addEventListener("visibilitychange",Q),()=>window.removeEventListener("visibilitychange",Q)},[]),t.current=g;const A=y.useMemo(()=>{const Q={};return o&&(Q.permissions=p.get(o,"permissions",null),Q.role=p.get(o,"role","user")),Q},[o]),F=y.useMemo(()=>l,[l]),se=y.useCallback(async(Q,de)=>await B({pageType:Q,query:de}),[B]),he=y.useMemo(()=>p.get(d,"theme",{})||{},[d]);return s.jsxs(s.Fragment,{children:[h&&s.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/30",children:s.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:s.jsx(T.Loader2,{className:"size-5 animate-spin"})})}),s.jsx(X.ChaiBuilderEditor,{pageExternalData:H,themePresets:e.themePresets??[],pageId:i==null?void 0:i.id,loading:h,fallbackLang:L,languages:(d==null?void 0:d.languages)||[],brandingOptions:(d==null?void 0:d.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!ee&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:j,getPartialBlocks:R,blocks:h?[]:g,theme:p.cloneDeep(he),getUILibraryBlock:w,getUILibraryBlocks:E,uiLibraries:F,pageTypes:b,searchPageTypeItems:se,saveAiContextCallback:async Q=>{if(!r)return!0;const de=t.current,q={_type:"@chai/ai-context",_value:p.isString(Q)?Q:""},pe=[...de,q];return await C({page:r,blocks:pe}),P(Q),!0},aiContext:S,askAiCallBack:x,onSave:async({blocks:Q,theme:de})=>{if(!r)return!0;t.current=Q;const q={_type:"@chai/ai-context",_value:p.isString(S)?S:""},pe=[...Q,q];return await C({page:r,blocks:pe}),t.current=pe,p.isEqual(de,he)||await v({settings:{theme:de}}),!0},themePanelComponent:Vr,...A}),s.jsxs("div",{children:[s.jsx(Sr,{}),s.jsx(wr,{})]})]})},zo=new k.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Vo=e=>{const{isLoggedIn:t}=Fe(),[,n]=Zs(),[r,a]=y.useState(!1);return y.useEffect(()=>(n(p.pick(e,["apiUrl","usersApiUrl","getPreviewUrl","logo","settingComponent","user","onSessionExpired","pageLockComponent"])),setTimeout(()=>{a(!0)},200),()=>{a(!1),n({})}),[e,n]),r?s.jsxs(k.QueryClientProvider,{client:zo,children:[t?s.jsx(Ko,{...e}):s.jsx(Fa,{}),s.jsx(Ho,{})]}):s.jsx("div",{})},$o=e=>{};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Ns;exports.ChaiBuilderPages=Vo;exports.Dynamic=Wi;exports.For=bi;exports.Index=ji;exports.Match=Ni;exports.PermissionChecker=Ne;exports.Portal=$i;exports.Show=Si;exports.Switch=wi;exports.addEventListener=Tn;exports.batch=ni;exports.className=An;exports.clearDelegatedEvents=Gi;exports.convertRemToPixels=Go;exports.createComponent=Cs;exports.createComputed=fn;exports.createContext=ci;exports.createEffect=As;exports.createMemo=be;exports.createRenderEffect=Ue;exports.createRoot=Re;exports.createSignal=ge;exports.createUniqueId=Ei;exports.delegateEvents=Nn;exports.deleteNestedDataByPath=vt;exports.displayValue=_o;exports.getMutationStatusColor=Po;exports.getPreferredColorScheme=Ro;exports.getQueryStatusColor=Co;exports.getQueryStatusColorByLabel=Io;exports.getQueryStatusLabel=Ao;exports.getSidedProp=To;exports.insert=Jt;exports.mergeProps=Ps;exports.mutationSortFns=Bo;exports.on=ri;exports.onCleanup=dt;exports.onMount=gn;exports.registerLoginComponent=$o;exports.serialize=Vn;exports.setAttribute=Zt;exports.sortFns=Do;exports.splitProps=bn;exports.spread=Cn;exports.stringify=No;exports.template=Bi;exports.untrack=xe;exports.updateNestedDataByPath=yt;exports.use=Pn;exports.useChaiUserInfo=gt;exports.useContext=ui;exports.useCurrentPage=we;exports.useFetch=W;exports.useFetchUpload=pr;exports.useLanguagePages=mt;exports.useTransition=li;exports.useUserRoleAndPermissions=on;exports.useWebsitePages=Rt;exports.useWebsiteSetting=ft;