@chaibuilder/pages 0.5.12 → 0.5.13

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 +1,2 @@
1
- "use strict";var Hs=e=>{throw TypeError(e)};var Vs=(e,s,n)=>s.has(e)||Hs("Cannot "+n);var K=(e,s,n)=>(Vs(e,s,"read from private field"),n?n.call(e):s.get(e)),he=(e,s,n)=>s.has(e)?Hs("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),de=(e,s,n,a)=>(Vs(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),x=require("lodash-es"),g=require("react"),Oe=require("jotai"),D=require("@tanstack/react-query"),z=require("sonner"),X=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),N=require("lucide-react"),$t=require("date-fns"),dn=require("@chaibuilder/runtime"),Xt=require("zod"),Ea=require("react-dropzone"),Sa=require("@chaibuilder/sdk/web-blocks");function wa(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const ye=wa(g),Le={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},I={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},q="chaibuilder";let Na=0;function Ks(e,s){const n=`atom${++Na}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Aa,a.write=Ca),s&&(a.write=s),a}function Aa(e){return e(this)}function Ca(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const Ta=Symbol(""),Pa=e=>typeof(e==null?void 0:e.then)=="function";function Ia(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,f;const v=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},y=(f=(h=e())==null?void 0:h.getItem(u))!=null?f:null;return Pa(y)?y.then(v):v(y)},setItem:(u,d)=>{var h;return(h=e())==null?void 0:h.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,h,f)=>u(d,v=>{let y;try{y=JSON.parse(v||"")}catch{y=f}h(y)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=f=>{f.storageArea===e()&&f.key===u&&d(f.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),o&&(i.subscribe=l(o)),i}const _a=Ia();function ka(e,s,n=_a,a){const r=Ks(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Ks(l=>l(r),(l,o,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===Ta?(o(r,s),n.removeItem(e)):d instanceof Promise?d.then(h=>(o(r,h),n.setItem(e,h))):(o(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const hn="__logged_in_user",Da=ka(hn,null),Fe=()=>{const[e,s]=Oe.useAtom(Da),n=g.useCallback(()=>{s(null),localStorage.removeItem(hn)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},mn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),$=()=>{const{user:e,logout:s}=Fe(),n=D.useQueryClient(),a=e==null?void 0:e.accessToken;return g.useCallback(async(r,i,l={})=>{if(!a)return null;try{const o=x.get(i,"action","").toLowerCase(),u=await mn(r+(o?`?action=${o}`:""),i,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[q]}),s(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(o){throw console.error("API request failed:",i,o),o}},[a,s,n])},fn=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[q,I.GET_DRAFT_PAGE]})}})},gn=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||z.toast.success("Website settings updated successfully.")},onError:a=>{z.toast.error("Failed to update website settings",{description:a.message})}})},La=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_DATA]}),z.toast.success("Website data updated successfully.")},onError:a=>{z.toast.error("Failed to update website data",{description:a.message})}})};function Pe(){const[e,s]=g.useState(new URLSearchParams(window.location.search));return g.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Ba=Oe.atom({}),pn=()=>Oe.useAtom(Ba),Ga=()=>{const[e]=Pe(),s=e.get("page"),n=g.useRef(""),{mutate:a}=fn();g.useEffect(()=>{!x.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},qe=(e,s)=>{const[n]=pn();return g.useMemo(()=>x.get(n,e,s),[n,e,s])},ne=()=>qe("apiUrl","/chai/api"),As=()=>qe("usersApiUrl","/chai/users"),Ht=()=>qe("assetsApiUrl","/chai/assets"),et=()=>{const e=ne(),[s]=Pe(),n=s.get("page"),a=$();return D.useQuery({queryKey:[q,I.GET_LANGUAGE_PAGES,n],initialData:[],queryFn:async()=>{if(!n)return null;const r=await a(e,{action:I.GET_LANGUAGE_PAGES,data:{id:n}});return x.reverse(x.sortBy(r,"primaryPage"))},enabled:!!n})},We=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:I.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},xn=e=>{const{fallbackLang:s}=X.useLanguages(),{data:n}=We(),{data:a,isFetching:r}=et(),i=g.useMemo(()=>{const l={[s]:!0};return x.each(x.get(n,"languages"),o=>{const u=x.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||x.isEmpty(e)||e&&i[e]},Cs=()=>{const e=D.useQueryClient(),{data:s}=D.useQuery({queryKey:[q,I.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:g.useCallback(a=>{e.setQueryData([q,I.AI_CONTEXT],a)},[e]),aiContext:s}},Vt=()=>{const e=$(),s=ne();return D.useQuery({queryKey:[q,I.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},Ma=Oe.atom({lastSaved:void 0}),Ts=()=>Oe.useAtom(Ma),Ie=()=>{const[e]=Pe(),s=e.get("page"),[n]=yn(),{data:a,isFetching:r}=Vt();return{data:g.useMemo(()=>({...x.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},Ps=()=>{const[e]=Pe(),s=e.get("lang")??"",{data:n,isFetching:a}=et();return{data:g.useMemo(()=>x.find(n,{lang:s})||{},[n,s]),isFetching:a}},Ua=Oe.atom({}),yn=()=>Oe.useAtom(Ua),tt=e=>{const s=As(),n=$();return D.useQuery({queryKey:[q,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:I.GET_CHAI_USER,data:{userId:e}}),enabled:!x.isEmpty(e)})},Ra=Oe.atom(void 0),Kt=()=>{const[e]=Pe(),s=e.get("page"),{user:n}=Fe(),[a,r]=Oe.useAtom(Ra);return g.useMemo(()=>({isLocked:s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:i=>r(i)}),[n==null?void 0:n.id,a,s,r])},Is=()=>{const{data:e}=We();return g.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},vn=()=>{const[e]=Pe(),s=e.get("page"),n=ne(),{setAiContext:a}=Cs(),{setCurrentEditor:r}=Kt(),[,i]=Ts(),[,l]=yn(),o=$();return D.useQuery({queryKey:[q,I.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await o(n,{action:I.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=x.find(d,{_type:"@chai/ai-context"});return a(x.get(h,"_value","")||""),i(f=>({...f,lastSaved:u.lastSaved})),l(x.get(u,"metadata",{})),d},enabled:!!s})},_s=()=>{const{data:e}=Ie(),s=ne(),n=$(),a=Is();return D.useQuery({queryKey:[q,I.GET_BUILDER_PAGE_DATA,e==null?void 0:e.pageType,(e==null?void 0:e.lang)||a,e==null?void 0:e.dynamic,e==null?void 0:e.slug],initialData:{},queryFn:async()=>n(s,{action:I.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(e==null?void 0:e.lang)||a,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:e==null?void 0:e.slug,searchParams:{}}}}),enabled:!!(e!=null&&e.pageType)})};function Oa({avatar:e,name:s,email:n,onTakeOver:a}){const[r,i]=g.useState(!1),l=()=>{i(!1),a()};return t.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:t.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"w-6 h-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"w-12 h-12 border border-gray-300 rounded-full"}):t.jsx(N.UserIcon,{className:"w-12 h-12 p-2 border border-gray-300 rounded-full"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n})]})]}),t.jsx("div",{className:"text-sm mt-4",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(c.CardFooter,{children:t.jsxs(c.AlertDialog,{open:r,onOpenChange:i,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take Over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(N.AlertTriangleIcon,{className:"w-5 h-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:l,children:"Yes, Take Over"})]})]})]})})]})})}const Fa=()=>{const{isLocked:e,currentEditor:s}=Kt(),{data:n}=tt(s),[a]=Pe(),r=a.get("page"),{mutate:i}=fn(),{isFetching:l}=vn(),o=g.useCallback(()=>{i({id:r})},[r,i]);return!e||l?t.jsx("div",{className:""}):t.jsx(Oa,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",onTakeOver:o})},qa=()=>{const[e,s]=Pe(),n=e.get("lang"),a=xn(n),{setSelectedLang:r}=X.useLanguages(),i=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(o),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=x.get(Le,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-14 bg-black/30 backdrop-blur-sm",children:t.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"w-6 h-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(c.CardFooter,{children:t.jsx(c.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},za=e=>{const s=ne(),n=$();return D.useMutation({mutationFn:async a=>n(s,{action:I.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),z.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},$a=e=>{const s=ne(),n=$();return D.useQuery({queryKey:[q,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:I.GET_LIBRARY_ITEM,data:{id:e}})}catch(a){throw console.error(a),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},Ha=e=>{const s=ne(),n=$();return D.useMutation({mutationFn:async a=>n(s,{action:I.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),z.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},Va=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=g.useState(!1),u=X.useUpdateBlocksPropsRealtime(),d=Ha(()=>{u([e],{_libBlockId:void 0}),z.toast.success("Block deleted successfully"),o(!1),a()}),h=()=>{o(!0),d.mutate(s)},f=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:v=>v.preventDefault(),disabled:l,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:v=>!v&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:i||f}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},Ka=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=g.useState(!1);return t.jsx(Va,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{o(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>o(!0),children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Wa=()=>{const e=ne(),s=$(),n=D.useQueryClient(),{data:a=[],isLoading:r,error:i}=D.useQuery({queryKey:[q,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:o}=D.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return s(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:[q,"library-groups"]}),z.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),z.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:o}},Qa=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),l=g.useRef(null),{groups:o}=Wa(),[u,d]=g.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=g.useMemo(()=>[...o,...u.filter(y=>!o.some(p=>p.id===y.id))],[o,u]),f=()=>{const y=r.trim();if(!y)return;const p={id:y,name:y};d(S=>[...S,p]),s(p.id),i(""),a(!1)};g.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const v=y=>{y.key==="Enter"&&(y.preventDefault(),f())};return g.useEffect(()=>{e&&!h.some(y=>y.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:v}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:f,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!o.some(p=>p.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(N.Plus,{className:"h-4 w-4"})})]})},Ya=10*1024*1024,Xa=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useCallback(u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d){if(d.size>Ya){z.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const f=new FileReader;f.onloadend=()=>{s(f.result),a(!1)},f.readAsDataURL(d)}catch(f){console.error("Error reading file:",f),a(!1),z.toast.error("Failed to process image",{description:f instanceof Error?f.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},o=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},ge={...X.PERMISSIONS,ADD_PAGE:"add_page",EDIT_PAGE:"edit_page",EDIT_SLUG:"edit_slug",DELETE_PAGE:"delete_page",CHANGE_PAGE_TYPE:"change_page_type",PUBLISH_PAGE:"publish_page",UNPUBLISH_PAGE:"unpublish_page",MARK_AS_TEMPLATE:"mark_as_template",UNMARK_AS_TEMPLATE:"unmark_as_template",ADD_PARTIAL:"add_partial",EDIT_PARTIAL:"edit_partial",DELETE_PARTIAL:"delete_partial",PUBLISH_PARTIAL:"publish_partial",UNPUBLISH_PARTIAL:"unpublish_partial",EDIT_SEO:"edit_seo",RESTORE_REVISION:"restore_revision",DELETE_REVISION:"delete_revision",PUBLISH_THEME:"publish_theme",EDIT_SETTINGS:"edit_settings",ADD_LIBRARY_BLOCK:"create_library_block",ADD_LIBRARY_TEMPLATE:"add_library_template",EDIT_LIBRARY_BLOCK:"edit_library_block",EDIT_LIBRARY_TEMPLATE:"edit_library_template",DELETE_LIBRARY_BLOCK:"delete_library_block",DELETE_LIBRARY_TEMPLATE:"delete_library_template",ADD_MEDIA:"add_media",EDIT_MEDIA:"edit_media",DELETE_MEDIA:"delete_media"},Za=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=X.usePartailBlocksStore(),i=s.find(C=>C._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=g.useMemo(()=>s.some(C=>C._type==="PartialBlock"||C._type==="GlobalBlock"),[s]),d=g.useMemo(()=>{let C=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let R=r(M.partialBlockId);M._parent&&(R==null?void 0:R.length)>0&&(R=R.map(T=>(x.isEmpty(T._parent)&&x.set(T,"_parent",M._parent),T))),C=[...C,...R]}else C.push(M);return C},[s,r]),[h,f]=g.useState(""),[v,y]=g.useState(""),[p,S]=g.useState(""),[E,G]=g.useState(""),[w,_]=g.useState({}),[b,B]=g.useState(!1),[O,te]=g.useState(o),[se,U]=g.useState(!1),{hasPermission:L}=X.usePermissions(),H=L(ge.DELETE_LIBRARY_BLOCK),ee=X.useUpdateBlocksPropsRealtime(),ae=()=>{ee([a],{_libBlockId:void 0}),z.toast.success("Block delinked from library"),n()},{data:Z,isLoading:k,isError:V}=$a(l);g.useEffect(()=>{V&&o&&(U(!0),te(!1))},[V,o]),g.useEffect(()=>{Z&&!k&&(f(Z.name||""),y(Z.group||""),S(Z.description||""),G(Z.preview||""),te(!1))},[Z,k]),g.useEffect(()=>{const C=h.trim().length>=2,M=v.trim()!=="";B(C&&M)},[h,v]);const ve=()=>{const C={};return h.trim()?h.length<2&&(C.name="Name must be at least 2 characters"):C.name="Name is required",v||(C.group="Group is required"),_(C),Object.keys(C).length===0},{resetLibrary:we}=X.useLibraryBlocks({id:""}),Be=za(C=>{o||ee([a],{_libBlockId:C.id}),z.toast.success(`Block ${o?"updated":"saved"} successfully`),we(C.library),n()}),j=async C=>{if(C.preventDefault(),!ve())return;const M=d.map(R=>(x.has(R,"_libBlockId")&&delete R._libBlockId,R));Be.mutate({name:h.trim(),group:v,blocks:M,description:p.trim(),...E&&E.startsWith("data:")?{previewImage:E}:{},...o?{id:l}:{}})},m=Be.isPending;return O||k?t.jsx("div",{className:"flex items-center justify-center p-8",children:t.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):se?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:ae,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(N.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:w.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:C=>f(C.target.value),className:w.name?"border-destructive":""}),w.name&&t.jsx("p",{className:"text-xs text-destructive",children:w.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:w.group?"text-destructive":"",children:"Group"}),t.jsx(Qa,{value:v,onChange:y}),w.group&&t.jsx("p",{className:"text-xs text-destructive",children:w.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:C=>S(C.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Xa,{value:E,onChange:G})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&H&&t.jsx(Ka,{blockId:a,libBlockId:l,blockName:h,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:m,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:m||!b,children:m?"Saving...":o?"Update Block":"Save Block"})]})]})]})},Q={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."},Ja={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ne=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:I.GET_PAGE_TYPES})})},er=e=>{const{data:s}=Ne();return g.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},tr=()=>{const e=ne(),s=$();return D.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:I.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},jn=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>await n(e,{action:I.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=x.find(a,{key:i.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";z.toast.success(l)},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:x.get(Ja,r.message,r.message)})}})},ks=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>await n(e,{action:I.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},sr=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>n(e,{action:I.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){z.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},nr=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>n(e,{action:I.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]});const l=x.find(a,{key:i.pageType});z.toast.success(l!=null&&l.hasSlug?Q.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Ds=()=>{const e=ne(),s=$(),n=D.useQueryClient(),{data:a}=Ie();return D.useMutation({mutationFn:async({ids:r})=>s(e,{action:I.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,I.GET_CHANGES]}),n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{z.toast.error("Failed to publish pages.")}})},ar=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>{var r;return s(e,{action:I.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),z.toast.success("Page marked as template successfully.")},onError:()=>{z.toast.error("Failed to mark page as template.")}})},rr=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>s(e,{action:I.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),z.toast.success("Page unmarked as template successfully.")},onError:()=>{z.toast.error("Failed to unmark page as template.")}})},ir=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:I.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{z.toast.success(Q.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]})},onError:()=>{z.toast.error("Failed to change slug")}})};var Ls={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!s.OffscreenCanvas)return!1;var j=new OffscreenCanvas(1,1),m=j.getContext("2d");m.fillRect(0,0,1,1);var C=j.transferToImageBitmap();try{m.createPattern(C,"no-repeat")}catch{return!1}return!0}();function u(){}function d(j){var m=n.exports.Promise,C=m!==void 0?m:s.Promise;return typeof C=="function"?new C(j):(j(u,u),null)}var h=function(j,m){return{transform:function(C){if(j)return C;if(m.has(C))return m.get(C);var M=new OffscreenCanvas(C.width,C.height),R=M.getContext("2d");return R.drawImage(C,0,0),m.set(C,M),M},clear:function(){m.clear()}}}(o,new Map),f=function(){var j=Math.floor(16.666666666666668),m,C,M={},R=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(m=function(T){var Y=Math.random();return M[Y]=requestAnimationFrame(function F(J){R===J||R+j-1<J?(R=J,delete M[Y],T()):M[Y]=requestAnimationFrame(F)}),Y},C=function(T){M[T]&&cancelAnimationFrame(M[T])}):(m=function(T){return setTimeout(T,j)},C=function(T){return clearTimeout(T)}),{frame:m,cancel:C}}(),v=function(){var j,m,C={};function M(R){function T(Y,F){R.postMessage({options:Y||{},callback:F})}R.init=function(F){var J=F.transferControlToOffscreen();R.postMessage({canvas:J},[J])},R.fire=function(F,J,ce){if(m)return T(F,null),m;var pe=Math.random().toString(36).slice(2);return m=d(function(ue){function xe(be){be.data.callback===pe&&(delete C[pe],R.removeEventListener("message",xe),m=null,h.clear(),ce(),ue())}R.addEventListener("message",xe),T(F,pe),C[pe]=xe.bind(null,{data:{callback:pe}})}),m},R.reset=function(){R.postMessage({reset:!0});for(var F in C)C[F](),delete C[F]}}return function(){if(j)return j;if(!a&&i){var R=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
2
- `);try{j=new Worker(URL.createObjectURL(new Blob([R])))}catch(T){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",T),null}M(j)}return j}}(),y={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function p(j,m){return m?m(j):j}function S(j){return j!=null}function E(j,m,C){return p(j&&S(j[m])?j[m]:y[m],C)}function G(j){return j<0?0:Math.floor(j)}function w(j,m){return Math.floor(Math.random()*(m-j))+j}function _(j){return parseInt(j,16)}function b(j){return j.map(B)}function B(j){var m=String(j).replace(/[^0-9a-f]/gi,"");return m.length<6&&(m=m[0]+m[0]+m[1]+m[1]+m[2]+m[2]),{r:_(m.substring(0,2)),g:_(m.substring(2,4)),b:_(m.substring(4,6))}}function O(j){var m=E(j,"origin",Object);return m.x=E(m,"x",Number),m.y=E(m,"y",Number),m}function te(j){j.width=document.documentElement.clientWidth,j.height=document.documentElement.clientHeight}function se(j){var m=j.getBoundingClientRect();j.width=m.width,j.height=m.height}function U(j){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=j,m}function L(j,m,C,M,R,T,Y,F,J){j.save(),j.translate(m,C),j.rotate(T),j.scale(M,R),j.arc(0,0,1,Y,F,J),j.restore()}function H(j){var m=j.angle*(Math.PI/180),C=j.spread*(Math.PI/180);return{x:j.x,y:j.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:j.startVelocity*.5+Math.random()*j.startVelocity,angle2D:-m+(.5*C-Math.random()*C),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:j.color,shape:j.shape,tick:0,totalTicks:j.ticks,decay:j.decay,drift:j.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:j.gravity*3,ovalScalar:.6,scalar:j.scalar,flat:j.flat}}function ee(j,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 C=m.tick++/m.totalTicks,M=m.x+m.random*m.tiltCos,R=m.y+m.random*m.tiltSin,T=m.wobbleX+m.random*m.tiltCos,Y=m.wobbleY+m.random*m.tiltSin;if(j.fillStyle="rgba("+m.color.r+", "+m.color.g+", "+m.color.b+", "+(1-C)+")",j.beginPath(),l&&m.shape.type==="path"&&typeof m.shape.path=="string"&&Array.isArray(m.shape.matrix))j.fill(ve(m.shape.path,m.shape.matrix,m.x,m.y,Math.abs(T-M)*.1,Math.abs(Y-R)*.1,Math.PI/10*m.wobble));else if(m.shape.type==="bitmap"){var F=Math.PI/10*m.wobble,J=Math.abs(T-M)*.1,ce=Math.abs(Y-R)*.1,pe=m.shape.bitmap.width*m.scalar,ue=m.shape.bitmap.height*m.scalar,xe=new DOMMatrix([Math.cos(F)*J,Math.sin(F)*J,-Math.sin(F)*ce,Math.cos(F)*ce,m.x,m.y]);xe.multiplySelf(new DOMMatrix(m.shape.matrix));var be=j.createPattern(h.transform(m.shape.bitmap),"no-repeat");be.setTransform(xe),j.globalAlpha=1-C,j.fillStyle=be,j.fillRect(m.x-pe/2,m.y-ue/2,pe,ue),j.globalAlpha=1}else if(m.shape==="circle")j.ellipse?j.ellipse(m.x,m.y,Math.abs(T-M)*m.ovalScalar,Math.abs(Y-R)*m.ovalScalar,Math.PI/10*m.wobble,0,2*Math.PI):L(j,m.x,m.y,Math.abs(T-M)*m.ovalScalar,Math.abs(Y-R)*m.ovalScalar,Math.PI/10*m.wobble,0,2*Math.PI);else if(m.shape==="star")for(var re=Math.PI/2*3,Ee=4*m.scalar,Ae=8*m.scalar,P=m.x,ie=m.y,A=5,le=Math.PI/A;A--;)P=m.x+Math.cos(re)*Ae,ie=m.y+Math.sin(re)*Ae,j.lineTo(P,ie),re+=le,P=m.x+Math.cos(re)*Ee,ie=m.y+Math.sin(re)*Ee,j.lineTo(P,ie),re+=le;else j.moveTo(Math.floor(m.x),Math.floor(m.y)),j.lineTo(Math.floor(m.wobbleX),Math.floor(R)),j.lineTo(Math.floor(T),Math.floor(Y)),j.lineTo(Math.floor(M),Math.floor(m.wobbleY));return j.closePath(),j.fill(),m.tick<m.totalTicks}function ae(j,m,C,M,R){var T=m.slice(),Y=j.getContext("2d"),F,J,ce=d(function(pe){function ue(){F=J=null,Y.clearRect(0,0,M.width,M.height),h.clear(),R(),pe()}function xe(){a&&!(M.width===r.width&&M.height===r.height)&&(M.width=j.width=r.width,M.height=j.height=r.height),!M.width&&!M.height&&(C(j),M.width=j.width,M.height=j.height),Y.clearRect(0,0,M.width,M.height),T=T.filter(function(be){return ee(Y,be)}),T.length?F=f.frame(xe):ue()}F=f.frame(xe),J=ue});return{addFettis:function(pe){return T=T.concat(pe),ce},canvas:j,promise:ce,reset:function(){F&&f.cancel(F),J&&J()}}}function Z(j,m){var C=!j,M=!!E(m||{},"resize"),R=!1,T=E(m,"disableForReducedMotion",Boolean),Y=i&&!!E(m||{},"useWorker"),F=Y?v():null,J=C?te:se,ce=j&&F?!!j.__confetti_initialized:!1,pe=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,ue;function xe(re,Ee,Ae){for(var P=E(re,"particleCount",G),ie=E(re,"angle",Number),A=E(re,"spread",Number),le=E(re,"startVelocity",Number),De=E(re,"decay",Number),_e=E(re,"gravity",Number),Qe=E(re,"drift",Number),$e=E(re,"colors",b),nt=E(re,"ticks",Number),qs=E(re,"shapes"),ya=E(re,"scalar"),va=!!E(re,"flat"),zs=O(re),$s=P,ds=[],ja=j.width*zs.x,ba=j.height*zs.y;$s--;)ds.push(H({x:ja,y:ba,angle:ie,spread:A,startVelocity:le,color:$e[$s%$e.length],shape:qs[w(0,qs.length)],ticks:nt,decay:De,gravity:_e,drift:Qe,scalar:ya,flat:va}));return ue?ue.addFettis(ds):(ue=ae(j,ds,J,Ee,Ae),ue.promise)}function be(re){var Ee=T||E(re,"disableForReducedMotion",Boolean),Ae=E(re,"zIndex",Number);if(Ee&&pe)return d(function(le){le()});C&&ue?j=ue.canvas:C&&!j&&(j=U(Ae),document.body.appendChild(j)),M&&!ce&&J(j);var P={width:j.width,height:j.height};F&&!ce&&F.init(j),ce=!0,F&&(j.__confetti_initialized=!0);function ie(){if(F){var le={getBoundingClientRect:function(){if(!C)return j.getBoundingClientRect()}};J(le),F.postMessage({resize:{width:le.width,height:le.height}});return}P.width=P.height=null}function A(){ue=null,M&&(R=!1,s.removeEventListener("resize",ie)),C&&j&&(document.body.contains(j)&&document.body.removeChild(j),j=null,ce=!1)}return M&&!R&&(R=!0,s.addEventListener("resize",ie,!1)),F?F.fire(re,P,A):xe(re,P,A)}return be.reset=function(){F&&F.reset(),ue&&ue.reset()},be}var k;function V(){return k||(k=Z(null,{useWorker:!0,resize:!0})),k}function ve(j,m,C,M,R,T,Y){var F=new Path2D(j),J=new Path2D;J.addPath(F,new DOMMatrix(m));var ce=new Path2D;return ce.addPath(J,new DOMMatrix([Math.cos(Y)*R,Math.sin(Y)*R,-Math.sin(Y)*T,Math.cos(Y)*T,C,M])),ce}function we(j){if(!l)throw new Error("path confetti are not supported in this browser");var m,C;typeof j=="string"?m=j:(m=j.path,C=j.matrix);var M=new Path2D(m),R=document.createElement("canvas"),T=R.getContext("2d");if(!C){for(var Y=1e3,F=Y,J=Y,ce=0,pe=0,ue,xe,be=0;be<Y;be+=2)for(var re=0;re<Y;re+=2)T.isPointInPath(M,be,re,"nonzero")&&(F=Math.min(F,be),J=Math.min(J,re),ce=Math.max(ce,be),pe=Math.max(pe,re));ue=ce-F,xe=pe-J;var Ee=10,Ae=Math.min(Ee/ue,Ee/xe);C=[Ae,0,0,Ae,-Math.round(ue/2+F)*Ae,-Math.round(xe/2+J)*Ae]}return{type:"path",path:m,matrix:C}}function Be(j){var m,C=1,M="#000000",R='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof j=="string"?m=j:(m=j.text,C="scalar"in j?j.scalar:C,R="fontFamily"in j?j.fontFamily:R,M="color"in j?j.color:M);var T=10*C,Y=""+T+"px "+R,F=new OffscreenCanvas(T,T),J=F.getContext("2d");J.font=Y;var ce=J.measureText(m),pe=Math.ceil(ce.actualBoundingBoxRight+ce.actualBoundingBoxLeft),ue=Math.ceil(ce.actualBoundingBoxAscent+ce.actualBoundingBoxDescent),xe=2,be=ce.actualBoundingBoxLeft+xe,re=ce.actualBoundingBoxAscent+xe;pe+=xe+xe,ue+=xe+xe,F=new OffscreenCanvas(pe,ue),J=F.getContext("2d"),J.font=Y,J.fillStyle=M,J.fillText(m,be,re);var Ee=1/C;return{type:"bitmap",bitmap:F.transferToImageBitmap(),matrix:[Ee,0,0,Ee,-pe*Ee/2,-ue*Ee/2]}}n.exports=function(){return V().apply(this,arguments)},n.exports.reset=function(){V().reset()},n.exports.create=Z,n.exports.shapeFromPath=we,n.exports.shapeFromText=Be})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Ls,!1);const lr=Ls.exports;Ls.exports.create;const or={particleCount:350,spread:120,origin:{y:.6},angle:90},cr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Jt=e=>{let s=cr[e];s||(s={});const n={...or,...s};lr(n)},ur=()=>{const[e]=X.useTheme(),{mutate:s,isPending:n}=Ds(),{mutateAsync:a,isPending:r}=gn(),i=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{Jt("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(c.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},dr=({page:e,onClose:s})=>{const[n,a]=g.useState(e.slug||""),{mutate:r,isPending:i}=ir(),{data:l}=Ne(),o=x.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Le).some(y=>n===`/${y}`||x.startsWith(n,`/${y}/`))){z.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:h=>{const f=h.target.value;x.startsWith(f,`/${d}`)&&a(f)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!x.startsWith(n,`/${d}`)||x.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})};function bn({page:e,onClose:s}){const[,n]=Pe(),{mutate:a,isPending:r}=sr(),{data:i}=Ne(),l=()=>{a(e,{onSuccess:()=>{e!=null&&e.primaryPage||(window.history.replaceState(null,"","/"),n(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate"))),s()}})},o=i==null?void 0:i.find(u=>u.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",o!=null&&o.hasSlug?(o==null?void 0:o.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:x.get(Le,e.lang,e.lang)})]})]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:r,onClick:l,children:r?"Deleting...":"Delete"})]})]})})}const ke=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=X.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},Bs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=nr(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[Q.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:r,children:a?Q.UPDATING:Q.UNPUBLISH})]})]})})},En=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Ie(),{data:r}=Ne(),[i,l]=g.useState(e.name||""),[o,u]=g.useState(e.edit?e.lang:""),[d,h]=g.useState(e.edit?e.slug:""),{mutate:f,isPending:v}=jn(),{mutate:y,isPending:p}=ks(),S=g.useMemo(()=>r==null?void 0:r.find(_=>_.key===e.pageType),[r,e.pageType]),E=!(S!=null&&S.hasSlug),G=v||p,w=_=>{_.preventDefault();const b={name:i,lang:o,primaryPage:a==null?void 0:a.id,slug:d,pageType:a==null?void 0:a.pageType,tracking:{}};b.pageType=e.pageType,e.edit&&(b.id=e==null?void 0:e.id),e.edit?y(b,{onSuccess:s}):f(b,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:e.edit?Q.EDIT_LANGUAGE:Q.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:Q.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:w,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",className:"text-right",children:Q.LANGUAGE}),t.jsxs("select",{value:o,disabled:e.edit||x.isEmpty(n),onChange:_=>{const b=_.target.value;u(b),!E&&h(`/${b}`)},className:"flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 col-span-3",children:[t.jsx("option",{value:"",disabled:!0,selected:!0,children:e.edit?x.get(Le,e.lang,e.lang):x.isEmpty(n)?Q.ALL_AVAILABLE_LANGUAGE_PAGE:Q.CHOOSE_LANGUAGE}),x.map(n,_=>t.jsx("option",{value:_,children:x.get(Le,_,_)},_))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-right",children:Q.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:i,onChange:_=>l(_.target.value),className:"col-span-3",required:!0,placeholder:Q.ENTER_PAGE_NAME})]}),!E&&t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:[Q.SLUG," ",t.jsx("small",{className:"font-light",children:Q.SLUG_SHOULD_START_WITH})]}),t.jsx(c.Input,{id:"slug",value:d,onChange:_=>{const b=_.target.value;x.startsWith(b,`/${o}`)&&h(x.toLower(x.trim(b)))},className:"col-span-3",required:!0,pattern:"^/.*",disabled:x.isEmpty(o),title:Q.SLUG_MUST_START_WITH,placeholder:x.isEmpty(o)?Q.CHOOSE_LANGUAGE_TO_ADD_SLUG:Q.ENTER_PAGE_SLUG})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:G||!i||!o||!E&&!x.startsWith(d,`/${o}`),children:G?e.edit?Q.UPDATING:Q.ADDING:e.edit?Q.UPDATE:Q.ADD_NEW_LANGUAGE})})]})]})})},hr=()=>{const[e,s]=g.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:r}=X.useLanguages(),{data:i,isFetching:l}=et(),{data:o}=Ie(),[u,d]=g.useState(null),[h,f]=g.useState(null),[v,y]=g.useState(null),{data:p}=We(),S=x.filter(x.get(p,"languages")||["en"],E=>!x.find(i,{lang:E})&&E!==x.get(p,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:l?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):x.map(i,E=>{const G=E.lang,w=E.slug,_=!E.primaryPage,b=G===n;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`text-slate-500 w-full p-2 rounded cursor-pointer flex items-center justify-between ${b?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>r(G),children:[t.jsxs("div",{className:" flex-1 gap-x-3",children:[t.jsxs("div",{className:"text-[13px] text-slate-800 flex items-center gap-x-2",children:[t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${E.online?"bg-green-300":"bg-gray-300"}`}),x.get(Le,_?a:G,G)]}),t.jsxs("div",{children:[w&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium",children:w})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",E.name," "]})]})]})]}),_?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(N.StarIcon,{fill:"orange",className:"w-3 h-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(ke,{permissions:[ge.EDIT_PAGE,ge.DELETE_PAGE,ge.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:B=>B.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[t.jsx(ke,{permissions:[ge.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:B=>{B.stopPropagation(),s({...E,edit:!0})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),Q.EDIT]})}),t.jsx(ke,{permissions:[ge.UNPUBLISH_PAGE],children:(E==null?void 0:E.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:B=>{B.stopPropagation(),f(E)},children:[t.jsx(N.Power,{className:"size-3"}),Q.UNPUBLISH]})}),t.jsx(ke,{permissions:[ge.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:B=>{B.stopPropagation(),d(E)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),Q.DELETE]})})]})]})})})]},E.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(ke,{permissions:[ge.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:x.isEmpty(S),onClick:()=>{s({name:o==null?void 0:o.name,pageType:o==null?void 0:o.pageType,lang:"",slug:"",edit:!1})},children:Q.ADD_NEW_LANGUAGE})})}),e&&t.jsx(En,{languages:S,langProps:e,onClose:()=>s(null)}),u&&t.jsx(bn,{page:u,onClose:()=>d(null)}),h&&t.jsx(Bs,{page:h,onClose:()=>f(null)}),v&&t.jsx(dr,{page:v,onClose:()=>y(null)})]})};function mr({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=g.useState(null),o=g.useRef(null),[u,d]=g.useState(a+e);g.useEffect(()=>{d(a+e)},[e,a]);const h=y=>{const p=y.target.value;if(!p.startsWith(a)){const b=p.replace(a,""),B=a+b;d(B),s(b);return}const E=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),G=(E.match(/\./g)||[]).length,w=G<=1;G>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(w);const _=a+E;d(_),s(E)},f=()=>{if(o.current){const y=o.current;setTimeout(()=>{const p=a.length;y.setSelectionRange(p,p)},0)}},v=y=>{const p=y.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const E=a.length;p.setSelectionRange(E,E)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:o,value:u,onChange:h,onFocus:f,onClick:v,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const fr=e=>{if(!e)return{base:e,extension:null};const s=e.lastIndexOf(".");if(s<=0)return{base:e,extension:null};const n=e.substring(s);return{base:e.substring(0,s),extension:n}},Je=e=>{if(!e)return e;const{base:s}=fr(e);return s},gr=e=>e&&Je(e),Ws=(e,s)=>{const n=Je(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function pr({pages:e,selectedParentId:s,onChange:n,className:a="w-full rounded-md border border-gray-300 px-3 py-2",id:r="parentPage"}){const i=g.useMemo(()=>!e||e.length===0?[]:e.filter(h=>!x.isEmpty(h.slug)).filter(h=>h.slug!=="/").sort((h,f)=>h.slug.localeCompare(f.slug)),[e]),l=d=>Math.max(0,(d.match(/\//g)||[]).length-1),o=d=>"    ".repeat(d),u=d=>{if(d==="/")return"/";const h=d.split("/").filter(Boolean);if(h.length<=1){const y=h[0]||"";return`/${Je(y)}`}const f=h[h.length-1];return`/${Je(f)}`};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),t.jsxs("select",{id:r,value:s||"none",onChange:d=>n(d.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),i.map(d=>{const h=l(d.slug),f=h>0?o(h):"",v=u(d.slug);return t.jsxs("option",{value:d.id,children:[f,d.name," (",v,")"]},d.id)})]})]})}function Sn({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r}){const[i,l]=g.useState(e),[o,u]=g.useState(null);g.useEffect(()=>{l(e)},[e]);const d=h=>{const v=h.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),y=(v.match(/\./g)||[]).length,p=y<=1;y>1?u("Invalid slug. Only one dot (.) is allowed in the slug"):u(null),r&&r(p),l(v),s(v)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"flex items-center mb-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent: ",gr(a)]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{value:i,onChange:d,placeholder:n,className:o?"border-red-500":""}),o&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:o})]})]})}const xr=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=g.useState("");if(g.useEffect(()=>{if(s){const o=e.find(u=>u.id===s);i((o==null?void 0:o.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex items-center justify-center h-fit text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const l={};return e.forEach(o=>{const u=o.libraryName;l[u]||(l[u]=[]),l[u].push(o)}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:o=>n(o.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(l).map(([o,u])=>t.jsx("optgroup",{label:o,children:u.map(d=>t.jsx("option",{value:d.id,children:x.startCase(d.name)},d.id))},o))]}),r&&t.jsxs("div",{className:"mt-3 border rounded overflow-hidden",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:r,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"p-2 text-xs text-gray-500 bg-gray-50 border-t",children:"Template preview"})]})]})},yr=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_LIBRARIES],queryFn:async()=>await s(e,{action:I.GET_LIBRARIES})||[]})},vr=e=>{const s=ne(),n=$();return D.useQuery({queryKey:[q,I.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:I.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?x.filter(a,{pageType:e}):a)||[]}})},jr=e=>{const{data:s=[],isLoading:n}=vr(e),{data:a=[],isLoading:r}=yr(),i=g.useMemo(()=>n||r?[]:s.map(o=>{const u=x.find(a,{id:o.library});return{...o,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=g.useMemo(()=>x.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},Gs=()=>{const[,e]=Pe();return g.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])};function br({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var P,ie;const r=Gs(),i=!!(e!=null&&e.id),{data:l}=Vt(),{mutate:o,isPending:u}=jn(),{mutate:d,isPending:h}=ks(),[f,v]=g.useState(null),[y,p]=g.useState(!0),[S,E]=g.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:G}=X.usePermissions(),w=G(ge.CHANGE_PAGE_TYPE),[_,b]=g.useState(!1),[B,O]=g.useState(""),te=g.useMemo(()=>{const A=s.find(le=>le.key===S);return(A==null?void 0:A.hasSlug)===!1},[S,s]),[se,U]=g.useState((e==null?void 0:e.parent)??""),[L,H]=g.useState((e==null?void 0:e.name)??""),[ee,ae]=g.useState((e==null?void 0:e.dynamic)??!1),[Z,k]=g.useState(ee?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[V,ve]=g.useState((e==null?void 0:e.dynamicSlugCustom)??""),[we,Be]=g.useState(!0),[j,m]=g.useState(""),{data:C,isLoading:M}=jr(S),R=u||h,T=s.find(A=>A.key===S),Y=A=>{if(i&&S!==A){O(A),b(!0);return}E(A)},F=()=>{E(B),b(!1),ae(!1)},J=A=>{ae(A),A?k(""):ve("")},ce=A=>{if(U(A),A&&A!=="none"){const le=l==null?void 0:l.find(_e=>_e.id===A),De=(le==null?void 0:le.slug)||"";if(Z.startsWith(De)){const _e=Z.slice(De.length).replace(/^\/+/,"");k(_e)}else k(Z.replace(/^\/+/,""))}else k(Z?`${Z}`:"")},pe=A=>{m(A)},ue=()=>L.trim()?ee&&!x.isEmpty(Z)?(v("Slug must be empty when using dynamic slug"),!1):ee&&!we?(v("Dynamic slug is invalid"),!1):!0:(z.toast.error("Name is required"),!1),xe=()=>{const A={pageType:T==null?void 0:T.key,name:L,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:L},{onSuccess:()=>{z.toast.success((T==null?void 0:T.name)+" updated successfully"),n()}}):o(A,{onSuccess:le=>{console.log("response",le),n(),r(le.page.id,a)}})},be=(A,le)=>{if(!A.trim()&&!ee)return v("Child page slug is required"),!1;const De=Je(le),_e=Ws(De,A);return Object.keys(Le).some(nt=>_e===`/${nt}`||(_e==null?void 0:_e.startsWith(`/${nt}/`)))?(v("Slugs cannot start with a language code for primary page"),!1):!0},re=(A,le)=>{const De=Je(le),_e=Ws(De,A),Qe={pageType:S,name:L,slug:_e.replace(/\/$/,""),parent:se,dynamic:ee,hasSlug:!0,template:j||void 0,tracking:{}};if(ee&&(Qe.dynamicSlugCustom=V),i)d({id:e==null?void 0:e.id,...Qe},{onSuccess:()=>{z.toast.success("Page updated successfully"),n()}});else{const $e=x.find(s,{key:S});$e!=null&&$e.trackingDefault&&(Qe.tracking=$e.trackingDefault),o(Qe,{onSuccess:nt=>{n(),r(nt.page.id,a)}})}},Ee=()=>{const A={pageType:S,name:L,slug:Z===""?"/":`/${Z.replace(/\/$/,"")}`,template:j||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...A},{onSuccess:()=>{z.toast.success("Page updated successfully"),n()}});else{const le=x.find(s,{key:S});le!=null&&le.trackingDefault&&(A.tracking=le.trackingDefault),o(A,{onSuccess:()=>{n()}})}},Ae=A=>{if(A.preventDefault(),v(null),!!ue()){if(!(T!=null&&T.hasSlug)){xe();return}if(se&&se!=="none"){const le=l==null?void 0:l.find(_e=>_e.id===se),De=(le==null?void 0:le.slug)||"";if(!be(Z,De))return;re(Z,De)}else Ee()}};return T!=null&&T.hasSlug?t.jsxs("form",{onSubmit:Ae,className:"w-full max-w-md mx-auto space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:S,disabled:i&&!w,onChange:A=>Y(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!w?"cursor-not-allowed text-gray-500":""}`,children:i?te?t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})]})}),_&&t.jsxs("div",{className:"mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>b(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:F,children:"Confirm"})]})]})]}),!i&&(T==null?void 0:T.hasSlug)&&C.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"text-sm mb-1 block",children:"Template"}),t.jsx(xr,{templates:C,selectedTemplateId:j,onSelectTemplate:pe,isLoading:M})]}),t.jsx(pr,{pages:l,selectedParentId:se,onChange:ce}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:L,onChange:A=>H(A.target.value),required:!0,"aria-required":"true"})]}),(T==null?void 0:T.dynamicSegments)&&se&&se!=="none"&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("input",{type:"checkbox",id:"useDynamicSlug",checked:ee,onChange:A=>J(A.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ee&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(mr,{value:V,onChange:ve,dynamicPattern:(T==null?void 0:T.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:Be})})})]}),(!(T!=null&&T.dynamicSegments)||!ee)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Sn,{value:Z,onChange:k,placeholder:se&&se!=="none"?"Enter page slug":S==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:se&&se!=="none"?(ie=l==null?void 0:l.find(A=>A.id===se))==null?void 0:ie.slug:void 0,onValidationChange:p}),f&&t.jsx("p",{className:"text-xs text-red-500",children:f})]}),t.jsx(c.Button,{disabled:R||!y&&(!(T!=null&&T.dynamicSegments)||!ee)||ee&&!we,type:"submit",className:"w-full",children:i?R?"Updating...":"Update page":R?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Ae,className:"w-full max-w-md mx-auto space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:S,disabled:i&&!w,onChange:A=>Y(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!w?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})}),_&&t.jsxs("div",{className:"mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>b(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:F,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(P=s.find(A=>A.key===S))==null?void 0:P.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:L,onChange:A=>H(A.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:R,type:"submit",className:"w-full",children:i?R?"Updating...":"Update "+(T==null?void 0:T.name):R?"Creating...":"Create "+(T==null?void 0:T.name)})]})}const Er=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Ne(),r=!!(e!=null&&e.id);return t.jsx(c.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsxs(c.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(c.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(br,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},Sr=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const l={pageId:a,name:r};return i&&(l.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),z.toast.success("Page duplicated successfully")},onError:a=>{z.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},wr=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Sr(),[r,i]=g.useState(null),[l,o]=g.useState(`${e.name} (Copy)`),u=x.isEmpty(e.slug),[d,h]=g.useState(u?"":`${e.slug.split("/").pop()}-copy`),f=u?"":x.initial(e.slug.split("/")).join("/"),[v,y]=g.useState(!1),p=S=>{if(S.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),y(!0);const E={pageId:e.id,name:l};u||(E.slug=`${f}/${d}`),n(E,{onSuccess:()=>{y(!1),s()},onError:G=>{y(!1),G.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):G.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):G.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(G.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Duplicate Page"}),t.jsx(c.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!u&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:S=>o(S.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Sn,{value:d,onChange:S=>h(S),parentSlug:f,onValidationChange:S=>{i(S?null:"Invalid slug")}})]}),r&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:r})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||v,children:a||v?"Duplicating...":"Duplicate"})]})]})]})})},Nr=1*1024*1024,Ar=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),[l,o]=g.useState(""),[u,d]=g.useState(!1),h=g.useRef(null),f=ar(),{data:v}=Ne(),y=v==null?void 0:v.find(_=>_.key===e.pageType),p=(y==null?void 0:y.name)||x.startCase(e.pageType),S=g.useCallback(_=>{var B;const b=(B=_.target.files)==null?void 0:B[0];if(b){if(b.size>Nr){z.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(b.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const O=new FileReader;O.onloadend=()=>{o(O.result),d(!1)},O.readAsDataURL(b)}catch(O){console.error("Error reading file:",O),d(!1),z.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),E=()=>{o(""),h.current&&(h.current.value="")},G=()=>{var _;(_=h.current)==null||_.click()},w=()=>{a(!0),f.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:x.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:_=>i(_.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:h,onChange:S,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:G,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:E,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:_=>{_.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:w,children:"Mark as template"})]})]})})},Cr=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),r=rr(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Unmark as template"}),t.jsx(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},Tr=({currentEditor:e})=>{const{user:s}=Fe(),{data:n}=tt(e);return!n||!e||e===(s==null?void 0:s.id)?null:t.jsx("span",{className:"ml-2 text-xs font-light text-gray-500 flex items-center gap-1",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(N.LockIcon,{className:"w-3 h-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},Pr=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:d})=>{const h=Gs(),{data:f}=Ne(),{hasPermission:v}=X.usePermissions(),[,y]=X.useSidebarActivePanel(),p=g.useMemo(()=>x.find(f,{key:s.pageType}),[f,s.pageType]),S=g.useMemo(()=>{const b=x.get(s,"slug",""),B=e?Je(e):"",O=B?b.replace(B,""):b;return O||"/"},[s,e]),E=!v(ge.EDIT_PAGE)&&!v(ge.DELETE_PAGE)&&!v(ge.UNPUBLISH_PAGE),G=g.useMemo(()=>!!s.isTemplate,[s.isTemplate]),w=g.useMemo(()=>!!(p!=null&&p.hasSlug),[p==null?void 0:p.hasSlug]),_=g.useCallback(()=>{y("outline"),h(x.get(s,"id"),a)},[h,a,s,y]);return t.jsxs("div",{onClick:_,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:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(N.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):p!=null&&p.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:p.icon}}):p!=null&&p.hasSlug?t.jsx(N.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(N.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:s.name}),p!=null&&p.hasSlug?t.jsxs(c.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:[S,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[x.endsWith(S,"/")?`${p==null?void 0:p.dynamicSlug}`:`/${p==null?void 0:p.dynamicSlug}`,s.dynamicSlugCustom]})]}):t.jsx(c.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:p==null?void 0:p.name}),G&&t.jsx(c.Badge,{variant:"outline",className:"ml-2 text-xs py-0 font-normal text-blue-500 border border-blue-200 bg-blue-50",children:"Template"})]}),t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(Tr,{currentEditor:s.currentEditor}),!E&&t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:b=>b.stopPropagation(),children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4 hover:stroke-[3]"})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm",children:[v(ge.ADD_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),d(s)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),v(ge.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),l({...s,global:!(p!=null&&p.hasSlug)})},children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),(s==null?void 0:s.online)&&v(ge.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),r(s)},children:[t.jsx(N.Power,{className:"size-3"}),Q.UNPUBLISH]}),v(ge.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),i(s)},children:[t.jsx(N.Trash,{className:"size-3"}),Q.DELETE]}),v(ge.MARK_AS_TEMPLATE)&&w&&t.jsx(t.Fragment,{children:G?t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),u(s)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),Q.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),o(s)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),Q.MARK_AS_TEMPLATE]})})]})]})]})]})},Ir=({close:e,isOpen:s})=>{const[,n]=g.useState([]),[a,r]=g.useState(null),[i,l]=g.useState(""),[o,u]=g.useState(null),[d,h]=g.useState(null),[f,v]=g.useState(null),[y,p]=g.useState(null),[S,E]=g.useState(null),{data:G,isFetching:w,refetch:_}=Vt(),[b,B]=g.useState(""),{hasPermission:O}=X.usePermissions(),[te,se]=Pe(),U=te.get("page"),{data:L}=Ne(),H=g.useCallback(k=>{var V;return(V=x.find(L,{key:k}))==null?void 0:V.hasSlug},[L]);g.useEffect(()=>{s&&_()},[s,_]),g.useEffect(()=>{if(!x.isEmpty(b))return;const k=sessionStorage.getItem("pageTypeFilter")||"all";!x.isEmpty(L)&&k&&(x.find(L,{key:k})?B(k):B("all"))},[L,b]);const ee=k=>{B(k),sessionStorage.setItem("pageTypeFilter",k)},ae=g.useCallback(k=>{const ve=new URLSearchParams(window.location.search).get("lang"),we=new URLSearchParams({page:k});ve&&we.set("lang",ve),window.history.pushState({},"",`?${we.toString()}`),se(we),window.dispatchEvent(new PopStateEvent("popstate")),e()},[se,e]);g.useEffect(()=>{if(U&&!w){const k=x.find(G,{id:U});k&&(k!=null&&k.pageType)?n(V=>[...V,k==null?void 0:k.pageType]):(window.history.replaceState(null,"","/"),se(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[G,U,w,se]);const Z=g.useMemo(()=>{const k=x.compact(x.filter(G,m=>x.isEmpty(i)?!0:x.includes(x.toLower(m==null?void 0:m.name),x.toLower(i))||x.includes(x.toLower(m==null?void 0:m.slug),x.toLower(i))));if(b!=="all")return x.compact(x.filter(k,{pageType:b}));const V=new Map;k.forEach(m=>{V.set(m.id,{...m,children:[]})});const ve=[];V.forEach(m=>{if(m.parent){const C=V.get(m.parent);C?C.children.push(m):ve.push(m)}else ve.push(m)});const we=m=>(m.sort((C,M)=>C.name.localeCompare(M.name)),m.forEach(C=>{C.children&&C.children.length>0&&we(C.children)}),m);we(ve);const Be=x.filter(ve,m=>H(m.pageType)).sort((m,C)=>m.name.localeCompare(C.name)),j=x.filter(ve,m=>!H(m.pageType));return x.compact([...Be,...j])},[G,H,i,b]);return t.jsxs("div",{className:"flex flex-col justify-between h-full",children:[t.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[t.jsxs("div",{className:"relative flex item-center gap-x-4",children:[t.jsx(N.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:i,onChange:k=>l(k.target.value)}),!x.isEmpty(b)&&t.jsxs(c.Select,{value:b,onValueChange:ee,children:[t.jsx(c.SelectTrigger,{className:`${b==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} min-w-[120px] h-max p-0 py-1 pl-2 pr-1 top-1.5 -mt-px absolute text-gray-600 right-1.5 w-max text-xs whitespace-nowrap ring-0 focus:ring-0 shadow-none`,children:t.jsx(c.SelectValue,{placeholder:"Select page type"})}),t.jsxs(c.SelectContent,{align:"end",children:[t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!x.isEmpty(x.filter(L,k=>k.hasSlug))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Pages"}),x.map([...x.filter(L,k=>k.hasSlug)].sort((k,V)=>x.get(k,"name","").localeCompare(x.get(V,"name",""))),k=>t.jsx(c.SelectItem,{value:x.get(k,"key"),children:x.get(k,"name")},x.get(k,"key")))]}),!x.isEmpty(x.filter(L,k=>!k.hasSlug))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Partials"}),x.map([...x.filter(L,k=>!k.hasSlug)].sort((k,V)=>x.get(k,"name","").localeCompare(x.get(V,"name",""))),k=>t.jsx(c.SelectItem,{value:x.get(k,"key"),children:x.get(k,"name")},x.get(k,"key")))]})]})]})]}),w?t.jsx("div",{className:"space-y-2",children:x.map([...Array(5).keys()],k=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},k))}):x.isEmpty(Z)?t.jsxs("div",{className:"h-[70vh] flex flex-col gap-y-1 items-center justify-center text-slate-500 text-sm font-medium",children:[t.jsx(N.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"text-sm text-slate-700 space-y-2 h-[70vh] overflow-y-auto",children:x.map(Z,k=>t.jsx(wn,{item:k,currentPage:U,close:e,setUnpublishPage:h,setDeletePage:u,setAddEditPage:v,setMarkAsTemplate:p,setUnmarkAsTemplate:E,setDuplicatePage:r,level:0},`page-item-${k.id}`))})]}),O(ge.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex text-sm gap-x-2",onClick:()=>{v({slug:"",name:"",pageType:b==="all"?"page":b})},children:[t.jsx(N.Plus,{className:"w-4 h-4"})," Add New"]}),f&&t.jsx(Er,{closePanel:e,editPage:ae,addEditPage:f,setAddEditPage:v}),o&&t.jsx(bn,{page:o,onClose:()=>u(null)}),d&&t.jsx(Bs,{page:d,onClose:()=>h(null)}),y&&t.jsx(Ar,{page:y,onClose:()=>p(null)}),S&&t.jsx(Cr,{page:S,onClose:()=>E(null)}),a&&t.jsx(wr,{page:a,onClose:()=>r(null)})]})},wn=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const f=!x.isEmpty(e==null?void 0:e.children);return t.jsxs("div",{className:"border-0",children:[t.jsx(Pr,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d}),f&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:x.map(x.get(e,"children",[]),v=>t.jsx(wn,{item:v,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:h+1},v.id||`child-${h}-${v.key}`))})]},e.id||`level-${h}-${e.key}`)},_r=()=>{const e=qe("logo",null);return e?t.jsx("div",{className:"w-full max-h-9 overflow-hidden pr-2",children:g.createElement(e,{})}):null},kr=()=>{const[e]=Pe(),s=e.get("page"),{data:n,isFetching:a}=Ie(),[r,i]=g.useState(!1),{savePage:l}=X.useSavePage(),o=!!s&&!x.isEmpty(n),u=!s||!a&&x.isEmpty(n)||r;return t.jsxs(t.Fragment,{children:[t.jsxs(c.Button,{variant:"secondary",className:"flex items-center w-full space-x-2 py-1",onClick:()=>{l(),i(!0)},children:[t.jsx("div",{children:t.jsx(N.Logs,{className:"h-4 w-4"})}),t.jsxs("span",{className:"truncate leading-tight flex items-center max-w-[200px]",children:[t.jsx("span",{className:"text-slate-600 pr-1 font-light",children:"Editing:"}),a?t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-slate-400 ml-2"}):x.startCase(x.get(n,"name"))??""]})]},"template-viewer"),t.jsx(c.Sheet,{open:u,onOpenChange:d=>!d&&o&&i(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`!max-w-screen-md z-50 border-border w-full ${o?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:"mb-3",children:[t.jsxs(c.SheetTitle,{className:"text-sm flex items-center gap-2 font-semibold",children:[t.jsx("div",{className:"p-2 rounded-md bg-primary text-primary-foreground",children:t.jsx(N.File,{className:"w-6 h-6"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(Ir,{isOpen:u,close:()=>i(!1)})})]})})]})},Dr=()=>{const{fallbackLang:e,languages:s,selectedLang:n,setSelectedLang:a}=X.useLanguages(),r=x.isEmpty(n)?e:n,[,i]=Pe();g.useEffect(()=>{const p=new URLSearchParams(window.location.search),S=p.get("lang");S&&(s.includes(S)?a(S):(p.delete("lang"),i(p),a("")))},[s,i,a]);const[l,o]=g.useState(null),{data:u}=Ie(),{data:d}=We(),{data:h,isFetching:f}=et(),v=g.useMemo(()=>{const p=x.compact(x.map(x.get(d,"languages"),S=>{const E=x.find(h,{lang:S});return{key:S,value:x.get(Le,S,S),isLangPageAdded:!!E}})).filter(Boolean);return[{key:e,value:x.get(Le,e),isLangPageAdded:!0},...p]},[e,h,d]),y=p=>{a(p);const S=new URLSearchParams(window.location.search);p===e?S.delete("lang"):S.set("lang",p);const E=S.toString(),G=`${window.location.pathname}${E?`?${E}`:""}`;window.history.pushState({},"",G),i(S),window.dispatchEvent(new PopStateEvent("popstate"))};return x.isEmpty(s)||f?null:t.jsxs(t.Fragment,{children:[t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Languages,{className:"w-4 h-4"}),x.get(Le,r,r),t.jsx(N.ChevronDown,{className:"w-4 h-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"border-border space-y-1",children:[x.map(v.filter(p=>p.isLangPageAdded),p=>t.jsxs(c.DropdownMenuItem,{className:X.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",p.key===r&&"!bg-gray-200 text-gray-700"),onClick:()=>y(p.key),children:[t.jsx("div",{className:"text-slate-600",children:p.value}),p.key===e&&t.jsxs("small",{className:"text-[9px] flex items-center gap-x-1 text-orange-500 leading-none",children:[t.jsx(N.Star,{fill:"orange",className:"w-2 h-2"}),"Primary"]})]},p.value)),!x.isEmpty(v.filter(p=>!p.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{o({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:[t.jsx(N.Plus,{className:"w-3 h-3 mr-1"})," Add Langauge"]})]})]})]}),l&&t.jsx(En,{languages:s,langProps:l,onClose:()=>o(null)})]})};function Lr(){return t.jsxs("div",{className:"flex relative z-10 items-center justify-end gap-1",children:[t.jsx(_r,{}),t.jsx(kr,{}),t.jsx(Dr,{})]})}function Br(e){const s=ne(),n=$();return D.useQuery({queryKey:[q,"revisions",e],queryFn:async()=>await n(s,{action:I.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Gr=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>await s(e,{action:I.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,"revisions"]})}})},Mr=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:I.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,"revisions"]})}})};function Ur(){const{data:e}=Ie(),{saveState:s}=X.useSavePage(),[n]=Ts();return e?t.jsx("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50 bg-primary/5 mb-4",children:t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:t.jsx("span",{className:"font-bold",children:"Currently editing"})})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:!x.isEmpty(n.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",$t.formatDistanceToNow(new Date(n.lastSaved),{addSuffix:!0})]})}),t.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(N.Edit,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]}),s==="UNSAVED"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(N.Save,{className:"h-3 w-3"}),t.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function Rr(){const[e,s]=ye.useState(!1),[n,a]=ye.useState(null),[r,i]=ye.useState(!1),[l,o]=ye.useState(!1),{data:u}=Ie(),{data:d,isFetching:h,error:f,refetch:v}=Br(u==null?void 0:u.id),{mutate:y,isPending:p}=Gr(),{mutate:S,isPending:E}=Mr(),G=D.useQueryClient(),w=O=>{n&&S({revisionId:n.uid,discardCurrent:O},{onSuccess:()=>{i(!1),a(null),G.invalidateQueries({queryKey:[q,I.GET_DRAFT_PAGE]})}})},_=O=>{a(O),i(!0)},b=O=>{a(O),o(!0)},B=()=>{n&&y(n.uid,{onSuccess:()=>{o(!1),a(null)}})};return g.useEffect(()=>{e&&v()},[e,v]),t.jsxs(t.Fragment,{children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:e,onOpenChange:s,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(N.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(c.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(c.SheetHeader,{className:"pb-2",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(N.History,{className:"h-5 w-5"}),"Revision History"]}),(u==null?void 0:u.createdAt)&&t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Page created on"," ",$t.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(c.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:h?t.jsx(Or,{}):f?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 space-y-2",children:[t.jsx(Ur,{}),d==null?void 0:d.map(O=>t.jsx(Fr,{revision:O,isLatest:O.uid==="current",onRestore:()=>_(O),onDelete:()=>b(O)},O.uid))]})})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(zr,{open:r,onOpenChange:i,revision:n,onRestore:w,isRestoring:E}),t.jsx($r,{open:l,onOpenChange:o,revision:n,onDelete:B,isDeleting:p})]})}function Or(){return t.jsx("div",{className:"space-y-2 mt-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(c.Skeleton,{className:"h-4 w-3/4"}),t.jsx(c.Skeleton,{className:"h-3 w-1/2"}),t.jsx(c.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Fr({revision:e,isLatest:s,onRestore:n,onDelete:a}){const{data:r}=tt(e.currentEditor),i=(r==null?void 0:r.name)||"Unknown";return t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:[e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"font-bold",children:i}),s&&t.jsxs("span",{className:"ml-2 flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:[t.jsxs("span",{className:"mr-1 relative flex h-2 w-2",children:[t.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]}),"Live"]})]})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:t.jsx("span",{children:$t.format(e.createdAt,"MMM d, h:mm a")})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:e.type==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(N.ArrowUpRight,{className:"h-3 w-3"}),t.jsx("span",{children:"Published"})]}):t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(N.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(ke,{permissions:[ge.RESTORE_REVISION,ge.DELETE_REVISION],children:t.jsx(qr,{revision:e,onRestore:n,onDelete:a})})]})}function qr({revision:e,onRestore:s,onDelete:n}){return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(N.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(ke,{permission:ge.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(ke,{permission:ge.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(c.DropdownMenuSeparator,{}),t.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(N.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function zr({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=tt((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Restore Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",$t.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function $r({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=tt((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",$t.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Hr=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_CHANGES],queryFn:async()=>s(e,{action:I.GET_CHANGES})})},Vr=({currentEditor:e})=>{const{data:s}=tt(e);return s==null?void 0:s.name};function Kr({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=g.useState([]),{data:r,isFetching:i}=Hr(),{data:l}=Ne(),o=g.useCallback(b=>{var B;return(B=x.find(l,{key:b}))==null?void 0:B.hasSlug},[l]),u=g.useMemo(()=>x.filter(l,b=>!o(b.key)).map(b=>b.key),[o,l]),d=g.useMemo(()=>x.filter(r,b=>!u.includes(b.pageType)),[r,u]),h=g.useMemo(()=>x.filter(r,b=>u.includes(b.pageType)),[r,u]),f=g.useMemo(()=>x.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:v,isPending:y}=Ds();g.useEffect(()=>{const b=x.map(x.filter(r,{online:!0}),"id");f&&b.push(f==null?void 0:f.id),a(b)},[r,f]);const p=n.length===(r==null?void 0:r.length),S=b=>{a(B=>x.includes(B,b)?x.filter(B,O=>O!==b):x.concat(B,b))},E=()=>{a(p?[]:x.map(r,"id"))},G=()=>{v({ids:x.uniq(n)},{onSuccess:()=>{s(),Jt("CENTER_CENTER")}})},w=b=>{if(b==="theme")return"Theme";const B=x.find(l,{key:b});return B?B==null?void 0:B.name:b},_=g.useMemo(()=>{const b=[{label:"Updated",top:"pt-2"},...x.orderBy(x.filter(d,{online:!0}),"pageType"),...x.orderBy(x.filter(h,{online:!0}),"pageType")].filter(te=>te.pageType!=="theme"),B=[{label:"Offline",top:"pt-6"},...x.orderBy(x.filter(d,{online:!1}),"pageType"),...x.orderBy(x.filter(h,{online:!1}),"pageType")],O=f?[{label:"Theme",top:"pt-6"},f]:[];return[...b,...O,...B]},[d,h,f]);return t.jsx(c.Dialog,{open:e,onOpenChange:y?()=>{}:s,children:t.jsxs(c.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),t.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:i?t.jsxs("div",{className:"px-1 space-y-2",children:[t.jsx("div",{className:"w-full h-6 mt-2 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"})]}):t.jsxs("table",{className:"w-full text-xs text-left text-gray-500 rtl:text-right dark:text-gray-400",children:[t.jsx("thead",{className:"text-gray-700 border-b bg-gray-50 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"px-6 py-3 flex items-center gap-x-2 w-[1 50px]",children:[t.jsx("input",{checked:p,onClick:b=>{b.stopPropagation(),E()},type:"checkbox",className:"mt-1 rounded cursor-pointer focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Language"}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Type"}),t.jsx("th",{scope:"col",className:"px-4 py-3 w-[150px] text-right",children:"Status"})]})}),t.jsx("tbody",{children:x.map(_,b=>b.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${b.top}`,children:[t.jsx("div",{className:"absolute inset-0 flex items-center left-6",children:t.jsx("div",{className:"w-full order-gray-300"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"pr-2 bg-gray-50",children:b.label})})]})},"separator"):t.jsxs("tr",{className:"border-b group hover:bg-gray-50 last:border-b-0",children:[t.jsxs("td",{scope:"row",className:"flex items-center px-6 py-2 text-gray-900 whitespace-nowrap dark:text-white gap-x-1",children:[t.jsx("input",{checked:x.includes(n,b==null?void 0:b.id),onClick:B=>{B.stopPropagation(),S(b==null?void 0:b.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",o(b.pageType)?t.jsx(N.File,{className:"w-4 h-4"}):t.jsx(N.GlobeIcon,{className:"w-4 h-4"}),b.name,b.slug&&t.jsxs("span",{className:"text-xs text-gray-500",children:["(",b.slug,")"]}),b.currentEditor&&t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsxs("span",{className:"flex text-xs font-bold text-gray-500",children:[" ","-"," ",t.jsx(Vr,{currentEditor:b.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:b.lang}),t.jsx("td",{className:"px-2",children:w(b==null?void 0:b.pageType)}),t.jsx("td",{className:"px-4 text-right",children:x.first(b.changes)||""})]},b==null?void 0:b.id))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10",children:[t.jsx(c.Button,{disabled:y,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:y||i||x.isEmpty(r),onClick:G,children:y?"Publishing...":"Publish"})]})]})})}const Wr=()=>{const e=$(),s=ne();return D.useQuery({queryKey:[I.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_DATA,data:{draft:!0}})})};function Qr({onClose:e}){const{data:s,isFetching:n}=Wr(),{mutateAsync:a,isPending:r}=La(),i=qe("settingComponent",null),l=x.debounce(async o=>(await a({data:o}),!0),300);return i?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:g.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function Nn({children:e,content:s}){return t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:e}),t.jsx(c.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const Yr=()=>{const{selectedLang:e,fallbackLang:s}=X.useLanguages(),n=qe("getPreviewUrl",async f=>f),[a,r]=g.useState(""),{data:i}=Ie(),{data:l}=et(),{data:o}=Ne(),u=g.useMemo(()=>{var f;return(f=l==null?void 0:l.find(v=>(v==null?void 0:v.lang)===e))==null?void 0:f.slug},[e,l]),d=g.useCallback(f=>{var v;return(v=x.find(o,{key:f}))==null?void 0:v.hasSlug},[o]),h=e===s?"":e;return g.useEffect(()=>{(async()=>{if(typeof n=="function"){const f=!d(i==null?void 0:i.pageType),v=await n(f?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(v)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,h]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Eye,{className:"w-4 h-4"})," ",Q.PREVIEW]})})})},Xr=()=>{const[e,s]=X.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(Nn,{content:Q.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(N.Palette,{className:"w-4 h-4"})})}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})},Zr=()=>{const[e,s]=g.useState(!1),{isLocked:n}=Kt(),{savePage:a,saveState:r}=X.useSavePage();g.useEffect(()=>{const h=f=>{r==="UNSAVED"&&(f.preventDefault(),f.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=g.useCallback(async()=>{s(!0),await a(!1)},[a]);g.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=g.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:o,buttonClass:u,tooltipContent:d}=g.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:Q.SAVEDRAFT,buttonIcon:t.jsx(N.Save,{className:"w-4 h-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:Q.SAVING,buttonIcon:t.jsx(N.Loader,{className:"w-4 h-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:Q.SAVED,buttonIcon:t.jsx(N.CheckCircle,{className:"w-4 h-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[o," ",d]})},Jr=()=>{const[e,s]=g.useState(!1),[n,a]=g.useState(!1),[r,i]=g.useState(null),{data:l}=Ie(),{mutate:o,isPending:u}=Ds(),{buttonText:d,buttonClassName:h,isPublished:f}=g.useMemo(()=>{const y=l&&(l==null?void 0:l.online);return{buttonClassName:y?"hover:bg-green-600 bg-green-500":"",isPublished:y,buttonText:y?Q.PUBLISHED:Q.PUBLISH}},[l]),v=async()=>{o({ids:[l==null?void 0:l.id]},{onSuccess:()=>Jt("TOP_RIGHT")})};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:v,disabled:u||!(l!=null&&l.id),className:`relative overflow-hidden transition-all duration-300 ease-in-out text-white flex items-center gap-1 rounded-r-none ${h}`,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${n?"-translate-y-10":""}`,children:f?t.jsx(N.Send,{className:"w-4 h-4"}):t.jsx(N.Rocket,{className:"w-4 h-4"})}),t.jsx("span",{className:`absolute inset-0 flex items-center left-3 transition-transform duration-300 ease-in-out ${n?"":"translate-y-10"}`,children:f?t.jsx(N.Rocket,{className:"w-4 h-4"}):t.jsx(N.Send,{className:"w-4 h-4"})}),t.jsx("span",{children:d})]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:u||!(l!=null&&l.id),className:`px-2 text-white border-l border-white/50 rounded-l-none ${h}`,children:t.jsx(N.ChevronDown,{className:"w-4 h-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-36",children:[!f&&t.jsxs(c.DropdownMenuItem,{disabled:u,className:"text-xs cursor-pointer",onClick:()=>o({ids:[l==null?void 0:l.id]},{onSuccess:()=>Jt("TOP_RIGHT")}),children:[Q.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>s(!0),className:"text-xs cursor-pointer",children:[Q.OPEN," publish menu"]}),f&&t.jsxs(c.DropdownMenuItem,{onClick:()=>i(l),className:"text-xs cursor-pointer",children:[Q.UNPUBLISH," page"]})]})]})]}),t.jsx(Kr,{showModal:e,onClose:()=>s(!1)}),r&&t.jsx(Bs,{page:r,onClose:()=>i(null)})]})},ei=()=>{const e=qe("settingComponent",null),[s,n]=g.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{content:Q.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(N.Settings,{className:"w-4 h-4"})})}),s&&t.jsx(Qr,{onClose:()=>n(!1)}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]}):null},ti=()=>{const{data:e}=Ie(),[s,n]=g.useState(""),a=e&&(e==null?void 0:e.online),{data:r}=Ne(),i=qe("getLiveUrl",async v=>v),l=g.useCallback(v=>{var y;return(y=x.find(r,{key:v}))==null?void 0:y.hasSlug},[r]),{selectedLang:o,fallbackLang:u}=X.useLanguages(),d=e==null?void 0:e.id,h=e==null?void 0:e.slug,f=o===u?"":o;return g.useEffect(()=>{(async()=>{if(typeof i=="function"){const v=!l(e==null?void 0:e.pageType),y=await i(v?`${f===""?"":f+"/"}${d}`:h||"");n(y)}else n("")})()},[i,e==null?void 0:e.pageType,l,d,h,f]),t.jsxs(c.Button,{onClick:()=>a&&window.open(s,"_blank"),disabled:!a,variant:"ghost",size:"sm",className:"flex items-center gap-1",children:[t.jsx(N.ExternalLink,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:Q.OPEN})]})};function si(){const{isLocked:e}=Kt(),[s]=Pe(),n=s.get("lang"),a=xn(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Rr,{}),t.jsx(ke,{permission:ge.EDIT_THEME,children:t.jsx(Xr,{})}),t.jsx(ke,{permission:ge.EDIT_SETTINGS,children:t.jsx(ei,{})}),t.jsx(Yr,{}),t.jsx(ke,{permission:ge.SAVE_PAGE,children:t.jsx(Zr,{})}),t.jsx(ke,{permission:ge.PUBLISH_PAGE,children:t.jsx(Jr,{})}),t.jsx(ti,{})]})}const ni=()=>t.jsxs("div",{className:"flex px-2 h-full items-center justify-between w-full",children:[t.jsx(Lr,{}),t.jsx(si,{})]}),ai=()=>{const e=ne(),{aiContext:s}=Cs(),n=$();return g.useCallback(async(a,r,i,l)=>n(e,{action:I.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},ri=(e,s)=>s.map(n=>{if(x.has(e,n._type)){const a=dn.getDefaultBlockProps(n._type);return{...a,...x.pick(n,[...x.keys(a),"_type","_id","_name","_parent","_bindings"]),...x.pickBy(n,(r,i)=>x.endsWith(i,"_attrs")),...n}}return n}),ii=e=>{const s=dn.useRegisteredChaiBlocks();return g.useMemo(()=>{if(!e||x.isEmpty(e))return{blocks:[]};const n=x.filter(e,a=>!x.includes(a==null?void 0:a._type,"@chai/"));return{blocks:ri(s,n)}},[e,s])},Qs={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=x.get(a,"html",""),i=x.get(a,"blocks",[]);return x.isArray(i)?i:X.getBlocksFromHTML(r)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(r=>({...r}))}catch(a){return console.error(a),[]}}},li=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{X.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>Qs.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>Qs.getUILibraryBlock(i,s,e)})}),a}})},An=()=>{const e=As(),s=$(),{user:n}=Fe(),a=n==null?void 0:n.id;return D.useQuery({queryKey:[q,"permissions",a],queryFn:()=>s(e,{action:I.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},oi=()=>{const e=ne(),s=$(),{setCurrentEditor:n}=Kt(),[,a]=Ts();return{onSave:async({page:i,blocks:l})=>{try{const o=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return o.code==="PAGE_LOCKED"?(n(o.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),o)}catch(o){return console.error(o),new Error("Failed to save blocks")}}}},ci=()=>{const{data:e}=Vt(),s=ne(),n=$();return{getPartialBlocks:g.useCallback(async()=>{const a={};for(const r of e??[])x.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:x.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:g.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return x.filter(r.blocks,i=>x.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},Ys=Xt.z.object({email:Xt.z.string().email({message:"Please enter a valid email address"}),password:Xt.z.string().min(6,{message:"Password must be at least 6 characters"})}),ui=()=>{const{setUser:e,logout:s}=Fe(),n=As(),[a,r]=g.useState(""),[i,l]=g.useState(""),[o,u]=g.useState({}),[d,h]=g.useState(!1),[f,v]=g.useState(""),y=D.useMutation({mutationFn:async E=>{v("");const G=await mn(n,{action:"LOGIN",data:E});if(!G.ok){const _=await G.json();throw new Error(_.error||"Login failed")}const w=await G.json();if(x.has(w,"id")&&x.has(w,"email")&&x.has(w,"accessToken")&&x.has(w,"refreshToken"))e(w);else throw s(),new Error("Something went wrong. Please try again.");return w},onSuccess:()=>{u({}),v("")},onError:E=>{u({email:" ",password:" "}),v(E.message||"Something went wrong")}}),p=async E=>{E.preventDefault(),u({});const G={email:a,password:i};try{const w=Ys.parse(G);y.mutate(w)}catch(w){if(w instanceof Xt.z.ZodError){const _=w.errors.reduce((b,B)=>{const O=B.path[0];return b[O]=B.message,b},{});u(_)}}},S=Ys.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:E=>r(E.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:E=>l(E.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:f})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!S||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let ps=ui;const di=()=>g.useMemo(()=>ps,[ps]),hi=e=>{ps=e},mi=()=>{const e=di();return t.jsx(g.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},fi=({isActive:e,show:s})=>{const{data:n}=We();return!x.has(n,"languages")||!x.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},Cn="lang",gi={id:Cn,label:"Languages",position:"top",panel:hr,button:fi,view:"modal",width:400};function Ue({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=ye.useState(!1),[l,o]=ye.useState([]),[u,d]=ye.useState(e);ye.useEffect(()=>{r||o([]),d(e)},[e,r]);const h=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",f=ye.useCallback(p=>{const S=E=>n==="value"?E==="value"||E==="object":n==="array"?E==="array":E===n;p.type==="object"?(o(E=>[...E,p.key]),d(p.value)):S(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),v=ye.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);o(p),d(p.reduce((S,E)=>S[E],e))}},[l,e]),y=ye.useMemo(()=>Object.entries(u).map(([p,S])=>({key:p,value:S,type:h(S)})).filter(p=>n==="value"?p.type==="value"||p.type==="object":n==="array"?p.type==="array"||p.type==="object":n==="object"?p.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(N.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:p=>{try{p.preventDefault();const S=p.currentTarget;S.scrollTop+=p.deltaY}catch{p.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:v,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(p=>t.jsxs(c.CommandItem,{onSelect:()=>f(p),className:"flex items-center justify-between",children:[t.jsx("span",{children:p.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&p.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:S=>{S.stopPropagation(),s([...l,p.key].join(".")),i(!1)},children:"Select"}),(p.type==="object"||p.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(N.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const pi=()=>{const e=Ht(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:I.UPLOAD_ASSET,data:{file:a,folderId:r,name:i,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[q,I.GET_ASSETS]}),z.toast.success("Asset uploaded successfully")},onError:()=>{z.toast.error("Failed to upload asset")}})},xi=()=>{const e=Ht(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[q,I.GET_ASSETS]}),z.toast.success("Asset deleted successfully")},onError:()=>{z.toast.error("Failed to delete asset")}})},yi=()=>{const e=Ht(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[q,I.GET_ASSETS]}),z.toast.success("Asset updated successfully")},onError:()=>{z.toast.error("Failed to update asset")}})},vi=(e={})=>{const s=Ht(),n=$(),{search:a,page:r=1,limit:i=30}=e;return D.useQuery({queryKey:[q,I.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:I.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},ji=e=>{const s=Ht(),n=$();return D.useQuery({queryKey:[q,I.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:I.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function bi(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function Xs(e){if(!e)return"N/A";const s=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(s)}function Zs(e,s){let n=e,a=s==null?void 0:s.description;return(!a||typeof a!="string")&&(a=""),(!n||typeof n!="string")&&(n=""),n!==a}const Ei=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var f,v,y;const{data:i,isLoading:l,isError:o}=ji(e||""),[u,d]=g.useState(""),h=async(p,S)=>{try{await navigator.clipboard.writeText(p),z.toast.success(`${S} copied to clipboard`)}catch(E){z.toast.error(`Failed to copy ${S}`,{description:E==null?void 0:E.message})}};return g.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}):o||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(N.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(N.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(N.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(N.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((f=i.metadata)==null?void 0:f.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((v=i.metadata)==null?void 0:v.format)||i.type,capitalize:!0},{label:"Size",value:bi(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:Xs(i.createdAt)},{label:"Updated",value:Xs(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(p.value,p.label),children:t.jsx(N.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,S)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},S))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>d(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!Zs(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Zs(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},Si=g.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function wi(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}const Ni=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,o]=g.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});g.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=g.useCallback(async y=>new Promise((p,S)=>{const E=y[0],G=new FileReader;G.readAsDataURL(E),G.onload=async()=>{a({file:G.result,folderId:void 0,name:E.name,optimize:l},{onSuccess:w=>{i&&i(w),p(w)},onError:w=>{S(w)}})},G.onerror=w=>S(w)}),[a,l,i]),{getRootProps:h,getInputProps:f,isDragActive:v}=Ea.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},maxSize:n*1024*1024,disabled:e||r});return t.jsx("div",{className:`flex flex-col items-center justify-center w-full border-2 hover:border-black/50 border-dashed p-0 rounded-lg border-slate-300 py-2 h-[60px] ${u?"opacity-90 bg-gray-100 pointer-events-none":"hover:border-black/50 bg-gray-100 hover:bg-gray-100"}`,children:t.jsxs("div",{...h(),className:X.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",v?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...f()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(N.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(N.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange:y=>{o(y)},onClick:y=>{y.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(N.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Tn({close:e,onSelect:s,mode:n="image",assetId:a}){const l=g.useMemo(()=>[n],[n]),[o,u]=g.useState(null),[d,h]=g.useState(null),[f,v]=g.useState(null),[y,p]=g.useState({show:!1,file:""}),[S,E]=g.useState(!1),[G,w]=g.useState(a?"details":"grid"),[_,b]=g.useState(""),[B,O]=g.useState(""),[te,se]=g.useState(1),[U]=g.useState(30),[L,H]=g.useState([]);g.useEffect(()=>{a&&(u(a),w("details"))},[a]),g.useEffect(()=>{const P=setTimeout(()=>{b(B),se(1)},300);return()=>clearTimeout(P)},[B]);const{data:ee,isLoading:ae}=vi({search:_.toLowerCase().trim(),page:te,limit:U}),Z=(ee==null?void 0:ee.assets)||[],k=(ee==null?void 0:ee.total)||0,V=Math.ceil(k/U),ve=te<V,we=te>1,Be=(Z==null?void 0:Z.length)>0,{mutate:j}=xi(),{mutate:m,isPending:C}=pi(),{mutate:M,isPending:R}=yi(),T=g.useCallback(P=>{P>=1&&P<=V&&se(P)},[V]),Y=g.useCallback(()=>{ve&&T(te+1)},[te,ve,T]),F=g.useCallback(()=>{we&&T(te-1)},[te,we,T]),J=P=>{O(P.target.value)},ce=g.useCallback(P=>{H(ie=>x.find(ie,{id:P.id})?[]:[P])},[!1]),pe=g.useCallback(()=>{H([])},[]),ue=P=>{(P==null?void 0:P.length)!==0&&(s(x.pick(x.first(P||L),["id","url","width","height","description"])),e())},xe=async P=>{h(P)},be=async()=>{d&&(v(d==null?void 0:d.id),await j(d.id,{onSuccess:()=>{v(null),h(null)},onError:()=>{v(null)}}),h(null))},re=P=>{u(P.id),w("details")},Ee=async(P,ie)=>{try{const A=localStorage.getItem("chai_optimize_images")!=="false";ie?(await m({file:P,folderId:void 0,name:y.name||"",optimize:A}),p({show:!1,file:""})):(await M({id:y.id||"",file:P}),p({show:!1,file:""}))}catch(A){console.error("Error saving edited image:",A)}},Ae=g.useCallback(P=>{H([P])},[]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"max-w-[1232px] max-h-[1232px] w-[80vw] h-[80vh] space-y-4 flex flex-col",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),G==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Ni,{maxFileSize:10,allowedTypes:l,uploadAsset:m,isUpdatingAsset:R,isUploadingAsset:C,onUploaded:Ae}),t.jsxs("div",{className:"border p-2 rounded-lg flex-1 flex flex-col gap-y-3 overflow-hidden relative",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2 ",children:[t.jsx(N.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${B.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:J,value:B,className:"pl-8"})]}),L.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[L.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>pe(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>ue(L),disabled:L.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:ae?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"})]}):!ae&&!Be?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full border rounded-lg",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(N.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:_.length>0?"No assets found for your search: "+_:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:Z==null?void 0:Z.map(P=>t.jsxs("div",{className:X.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",L.some(ie=>ie.id===P.id)?"border-blue-500":"hover:border-black/90",f&&(d==null?void 0:d.id)===P.id?"opacity-50 pointer-events-none":"",f===P.id?"opacity-50 pointer-events-none":""),onClick:()=>ce(P),onDoubleClick:()=>ue([P]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[f===P.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,P.type==="image"?t.jsx("img",{src:`${P.thumbnailUrl||"/placeholder.svg"}?v=${(P==null?void 0:P.updatedAt)||P.createdAt}`,alt:P.name,className:`object-contain w-full h-full min-h-[80px] ${L.some(ie=>ie.id===P.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(N.Film,{className:"h-12 w-12 text-muted-foreground"}),P.thumbnailUrl&&t.jsx("img",{src:`${P.thumbnailUrl||"/placeholder.svg"}?v=${(P==null?void 0:P.updatedAt)||P.createdAt}`,alt:P.name,className:"absolute inset-0 object-cover w-full h-full"})]})]}),t.jsxs("div",{className:"py-1 px-2 flex items-end justify-between bg-white border-t-[1px] border-black/10",children:[t.jsx("div",{className:"text-xs truncate leading-tight",title:P.name,children:P.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:wi((P==null?void 0:P.size)||0)})})]}),!L.some(ie=>ie.id===P.id)&&t.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),re(P)},children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),navigator.clipboard.writeText(P.url),z.toast.success("Asset URL copied to clipboard")},children:t.jsx(N.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),p({id:P.id,show:!0,file:P.url,name:P.name})},children:t.jsx(N.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),xe(P)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),L.some(ie=>ie.id===P.id)&&t.jsx("div",{className:"absolute top-1 right-1 border border-white h-max rounded-full bg-blue-500 p-1",children:t.jsx(N.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},P.id))})}),V>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:F,disabled:!we,children:"Previous"}),Array.from({length:Math.min(5,V)},(P,ie)=>{const A=ie+1;return t.jsx(c.Button,{variant:te===A?"default":"outline",size:"sm",onClick:()=>T(A),children:A},A)}),V>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(c.Button,{variant:te===V?"default":"outline",size:"sm",onClick:()=>T(V),children:V})]}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:Y,disabled:!ve,children:"Next"})]})})]})]}):t.jsx(Ei,{assetId:o||a||"",onBack:()=>{w("grid"),u(null)},onEdit:P=>{p({id:P.id,show:!0,file:P.url,name:P.name})},onSave:async P=>{if(o){E(!0);try{const ie=Z.find(A=>A.id===o);ie&&await M(x.merge(ie,{description:P}))}finally{E(!1)}}},isSaving:S})]}),y.show&&t.jsx(g.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Si,{imageUrl:y.file,onSave:Ee,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),d&&t.jsx(c.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:be,children:"Delete"})]})]})})]})}const Ai=Object.freeze(Object.defineProperty({__proto__:null,default:Tn},Symbol.toStringTag,{value:"Module"})),Pn=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,o]=g.useState(!1),u=()=>{i||o(!0)},d=()=>{o(!1)},h=v=>{const y=Array.isArray(v)?v[0]:v;y!=null&&y.url&&n(x.pick(y,["url","id"])),o(!1)},f=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:f,disabled:i,children:t.jsx(N.Trash2,{className:"h-4 w-4"})}),t.jsx(c.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${i?"opacity-50 cursor-not-allowed":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(c.Dialog,{open:l,onOpenChange:o,children:t.jsxs(c.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(c.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(Tn,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Ci=()=>{const{selectedLang:e}=X.useLanguages(),{data:s,isFetching:n}=et();return{data:g.useMemo(()=>x.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Ti=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg").forEach(o=>o.remove()),a.querySelectorAll("*").forEach(o=>{Array.from(o.attributes).forEach(u=>o.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(o=>`<${o.tagName.toLowerCase()}>${o.innerHTML}</${o.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},Ye=({onComplete:e,field:s})=>{const n=$(),a=ne(),{selectedLang:r,fallbackLang:i}=X.useLanguages(),l=X.useBuilderProp("aiContext",""),{mutate:o,isPending:u}=D.useMutation({mutationFn:async()=>{const d=Ti();return await n(a,{action:I.GENERATE_SEO_FIELD,data:{pageContext:l,dynamic:!1,field:s,lang:r||i,pageContent:d}})},onSuccess:d=>{e({fieldValue:d.field})},onError:d=>{e({fieldValue:null,error:d.message})}});return t.jsx(c.Button,{disabled:u,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>o(),children:u?t.jsx(N.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(N.Sparkle,{className:"text-yellow-500"})})},Pi=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a);let o=!1;if(n>0&&i.length>0){const p=i.charAt(i.length-1);o=!/[\s.,!?;:()[\]{}]/.test(p)&&p!==""}let u=!1;if(l.length>0){const p=l.charAt(0);u=!/[\s.,!?;:()[\]{}]/.test(p)&&p!==""}const d=o?" ":"",h=u?" ":"",f=`{{${s}}}`,v=i+(o?d:"")+f+(u?h:"")+l,y=n+(o?1:0)+f.length;return{value:v,newCursorPos:y}},In=()=>{const{t:e}=X.useTranslation(),{selectedLang:s,fallbackLang:n,languages:a}=X.useLanguages(),[,r]=X.useSidebarActivePanel(),{data:i}=_s(),{data:l,isFetching:o}=Ci(),u=l==null?void 0:l.seo,d=g.useRef(null),[h,f]=g.useState({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",...u}),v=g.useRef({initial:h,updated:h}),y=s.length?s:n,{mutate:p,isPending:S}=ks(),E=S,{hasPermission:G}=X.usePermissions(),w=G(ge.EDIT_SEO);g.useEffect(()=>{!o&&u&&f({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...u})},[o,u]);const _=async()=>{p({id:l==null?void 0:l.id,seo:h},{onSuccess:()=>{v.current.initial=h,v.current.updated=h,r("outline")}})},b=()=>{f({...h,ogTitle:h.title,ogDescription:h.description})},B=()=>{f({...h,searchTitle:h.ogTitle,searchDescription:h.ogDescription})},O=(U,L)=>{const H=document.getElementById(L);if(H){const{value:ee,newCursorPos:ae}=Pi(H,U);d.current={id:L,position:ae},H.tagName.toLowerCase()==="input"?(H.value=ee,f(V=>({...V,[H.name]:ee})),H.focus(),H.setSelectionRange(ae,ae),[0,10,50,100,200].forEach(V=>{setTimeout(()=>{const ve=document.getElementById(L);ve&&(ve.focus(),ve.setSelectionRange(ae,ae))},V)})):(f(k=>({...k,[H.name]:ee})),requestAnimationFrame(()=>{const k=document.getElementById(L);k&&(k.focus(),k.setSelectionRange(ae,ae),setTimeout(()=>{const V=document.getElementById(L);V&&(V.focus(),V.setSelectionRange(ae,ae))},50))}))}},te=U=>{const L={...h,[U.target.name]:U.target.name==="noIndex"||U.target.name==="noFollow"?U.target.checked:U.target.value};f(L),v.current.updated=L},se=U=>L=>{x.isEmpty(L.fieldValue)||te({target:{name:U,value:L.fieldValue}}),L.error&&z.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:L.error})]}))};return t.jsxs("div",{className:"relative h-full flex flex-col",children:[!w&&t.jsx("div",{className:"absolute inset-0 z-10 backdrop-blur-sm flex items-center justify-center",children:t.jsx(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"flex-grow overflow-y-auto no-scrollbar px-2",children:[t.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,"  ",a.length>0&&t.jsxs("span",{className:"font-semibold text-blue-500",children:["(",x.get(Le,y,y),")"]})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Accordion,{type:"multiple",defaultValue:["page"],children:[t.jsxs(c.AccordionItem,{value:"page",children:[t.jsx(c.AccordionTrigger,{className:"font-semibold text-slate-700",children:e("SEO")}),t.jsx(c.AccordionContent,{className:"pt-2",children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(Ye,{onComplete:se("title"),field:"title"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:h.title,onChange:te,disabled:E||!w,placeholder:e("Enter SEO title"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("description"),field:"description"}),w&&t.jsx(Ue,{data:i??{},onSelect:U=>O(U,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:h.description,onChange:te,disabled:E||!w,placeholder:e("Enter SEO description"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:h.canonicalUrl,onChange:te,disabled:E||!w,placeholder:e("Enter Canonical URL"),readOnly:!w})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:h.noIndex,onChange:te,disabled:E||!w,className:"w-4 h-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light text-gray-400 leading-4",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:h.noFollow,onChange:te,disabled:E||!w,className:"w-4 h-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.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.")})]})]})})]}),t.jsxs(c.AccordionItem,{value:"og",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Open Graph")}),t.jsx(c.AccordionContent,{children:t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:b,disabled:!w,children:e("Copy from SEO Settings")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("ogTitle"),field:"ogTitle"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:h.ogTitle,onChange:te,disabled:E||!w,placeholder:e("Enter OG title"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("ogDescription"),field:"ogDescription"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:h.ogDescription,onChange:te,disabled:E||!w,placeholder:e("Enter OG description"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Pn,{assetId:h.ogImageId,assetUrl:h.ogImage,onChange:U=>{const L={...h,ogImage:U.url,ogImageId:U.id};f(L),v.current.updated=L},disabled:E||!w,placeholder:e("Select OG image"),className:"mb-2"})]})]})})]}),t.jsxs(c.AccordionItem,{value:"search",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Search")}),t.jsx(c.AccordionContent,{children:t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:B,disabled:!w,children:e("Copy from OG Settings")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"searchTitle",children:e("Search Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("searchTitle"),field:"searchTitle"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"searchTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"searchTitle",name:"searchTitle",value:h.searchTitle,onChange:te,disabled:E||!w,placeholder:e("Enter search title"),readOnly:!w}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"searchDescription",children:e("Search Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("searchDescription"),field:"searchDescription"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"searchDescription")})]})]}),t.jsx(c.Textarea,{id:"searchDescription",rows:5,name:"searchDescription",value:h.searchDescription,onChange:te,placeholder:e("Enter search description"),disabled:E||!w,readOnly:!w})]})]})]})})]}),t.jsxs(c.AccordionItem,{value:"jsonLD",className:"border-none",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("JSON-LD")}),t.jsx(c.AccordionContent,{children:t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("jsonLD"),field:"jsonLD"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"jsonLD")})]})]}),t.jsx(c.Textarea,{id:"jsonLD",name:"jsonLD",rows:6,value:h.jsonLD,onChange:te,placeholder:e("Enter JSON-LD"),disabled:E||!w,readOnly:!w})]})})})]})]})})]}),w&&t.jsx("div",{className:"flex-shrink-0 flex items-center justify-end w-full p-4 bg-background border-t",children:t.jsx(c.Button,{size:"lg",variant:"default",onClick:_,disabled:x.isEqual(v.current.initial,h)||E||!w,children:e(S?"Saving...":"Save")})})]})};In.displayName="SeoPanel";const _n="seo",Ii=({isActive:e,show:s})=>{const{data:n}=Ie(),a=er(n==null?void 0:n.pageType);return!x.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"w-4 h-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},_i={id:_n,label:"SEO",panel:In,button:Ii,position:"top",width:600,view:"modal"},ki="user-info",Di=()=>{const{user:e,logout:s}=Fe(),n=D.useQueryClient(),a=qe("onLogout",x.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(N.User,{className:"w-4 h-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[q]}),x.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},Li={id:ki,label:"User Info",button:Di,position:"bottom"},Bi=()=>{X.registerChaiSidebarPanel(_n,_i),X.registerChaiSidebarPanel(Cn,gi),X.registerChaiSidebarPanel("user-info",Li)};var W={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Js(this.context.count)},getNextContextId(){return Js(this.context.count++)}};function Js(e){const s=String(e),n=s.length-1;return W.context.id+(n?String.fromCharCode(96+n):"")+s}function wt(e){W.context=e}var Gi=(e,s)=>e===s,es=Symbol("solid-proxy"),kn=typeof Proxy=="function",Ms=Symbol("solid-track"),ts={equals:Gi},Dn=On,ze=1,ss=2,Ln={owned:null,cleanups:null,context:null,owner:null},hs={},oe=null,ms=null,Mi=null,me=null,Ce=null,Re=null,os=0;function He(e,s){const n=me,a=oe,r=e.length===0,i=s===void 0?a:s,l=r?Ln:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Se(()=>Pt(l)));oe=l,me=null;try{return Me(o,!0)}finally{me=n,oe=a}}function je(e,s){s=s?Object.assign({},ts,s):ts;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Rn(n,r));return[Un.bind(n),a]}function Bn(e,s,n){const a=cs(e,s,!0,ze);St(a)}function Ve(e,s,n){const a=cs(e,s,!1,ze);St(a)}function Us(e,s,n){Dn=Xi;const a=cs(e,s,!1,ze);(!n||!n.render)&&(a.user=!0),Re?Re.push(a):St(a)}function Te(e,s,n){n=n?Object.assign({},ts,n):ts;const a=cs(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,St(a),Un.bind(a)}function Ui(e){return e&&typeof e=="object"&&"then"in e}function Ri(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,o=hs,u=null,d=!1,h="initialValue"in i,f=typeof a=="function"&&Te(a);const v=new Set,[y,p]=(i.storage||je)(i.initialValue),[S,E]=je(void 0),[G,w]=je(void 0,{equals:!1}),[_,b]=je(h?"ready":"unresolved");W.context&&(u=W.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:W.load&&W.has(u)&&(o=W.load(u)));function B(U,L,H,ee){return l===U&&(l=null,ee!==void 0&&(h=!0),(U===o||L===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(ee,{value:L})),o=hs,O(L,H)),L}function O(U,L){Me(()=>{L===void 0&&p(()=>U),b(L!==void 0?"errored":h?"ready":"unresolved"),E(L);for(const H of v.keys())H.decrement();v.clear()},!1)}function te(){const U=Wi,L=y(),H=S();if(H!==void 0&&!l)throw H;return me&&me.user,L}function se(U=!0){if(U!==!1&&d)return;d=!1;const L=f?f():a;if(L==null||L===!1){B(l,Se(y));return}const H=o!==hs?o:Se(()=>r(L,{value:y(),refetching:U}));return Ui(H)?(l=H,"value"in H?(H.status==="success"?B(l,H.value,void 0,L):B(l,void 0,xs(H.value),L),H):(d=!0,queueMicrotask(()=>d=!1),Me(()=>{b(h?"refreshing":"pending"),w()},!1),H.then(ee=>B(H,ee,void 0,L),ee=>B(H,void 0,xs(ee),L)))):(B(l,H,void 0,L),H)}return Object.defineProperties(te,{state:{get:()=>_()},error:{get:()=>S()},loading:{get(){const U=_();return U==="pending"||U==="refreshing"}},latest:{get(){if(!h)return te();const U=S();if(U&&!l)throw U;return y()}}}),f?Bn(()=>se(!1)):se(!1),[te,{refetch:se,mutate:p}]}function Oi(e){return Me(e,!1)}function Se(e){if(me===null)return e();const s=me;me=null;try{return e()}finally{me=s}}function Fi(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let o;if(a){o=Array(e.length);for(let d=0;d<e.length;d++)o[d]=e[d]()}else o=e();if(i)return i=!1,l;const u=Se(()=>s(o,r,l));return r=o,u}}function Gn(e){Us(()=>Se(e))}function bt(e){return oe===null||(oe.cleanups===null?oe.cleanups=[e]:oe.cleanups.push(e)),e}function en(){return oe}function qi(e,s){const n=oe,a=me;oe=e,me=null;try{return Me(s,!0)}catch(r){Rs(r)}finally{oe=n,me=a}}function zi(e){const s=me,n=oe;return Promise.resolve().then(()=>{me=s,oe=n;let a;return Me(e,!1),me=oe=null,a?a.done:void 0})}var[$i,Go]=je(!1);function Hi(){return[$i,zi]}function Vi(e,s){const n=Symbol("context");return{id:n,Provider:Zi(n),defaultValue:e}}function Ki(e){let s;return oe&&oe.context&&(s=oe.context[e.id])!==void 0?s:e.defaultValue}function Mn(e){const s=Te(e),n=Te(()=>ys(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Wi;function Un(){if(this.sources&&this.state)if(this.state===ze)St(this);else{const e=Ce;Ce=null,Me(()=>as(this),!1),Ce=e}if(me){const e=this.observers?this.observers.length:0;me.sources?(me.sources.push(this),me.sourceSlots.push(e)):(me.sources=[this],me.sourceSlots=[e]),this.observers?(this.observers.push(me),this.observerSlots.push(me.sources.length-1)):(this.observers=[me],this.observerSlots=[me.sources.length-1])}return this.value}function Rn(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&Me(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=ms&&ms.running;l&&ms.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Ce.push(i):Re.push(i),i.observers&&Fn(i)),l||(i.state=ze)}if(Ce.length>1e6)throw Ce=[],new Error},!1)),s}function St(e){if(!e.fn)return;Pt(e);const s=os;Qi(e,e.value,s)}function Qi(e,s,n){let a;const r=oe,i=me;me=oe=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=ze,e.owned&&e.owned.forEach(Pt),e.owned=null),e.updatedAt=n+1,Rs(l)}finally{me=i,oe=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Rn(e,a):e.value=a,e.updatedAt=n)}function cs(e,s,n,a=ze,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:oe,context:oe?oe.context:null,pure:n};return oe===null||oe!==Ln&&(oe.owned?oe.owned.push(i):oe.owned=[i]),i}function ns(e){if(e.state===0)return;if(e.state===ss)return as(e);if(e.suspense&&Se(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<os);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===ze)St(e);else if(e.state===ss){const a=Ce;Ce=null,Me(()=>as(e,s[0]),!1),Ce=a}}function Me(e,s){if(Ce)return e();let n=!1;s||(Ce=[]),Re?n=!0:Re=[],os++;try{const a=e();return Yi(n),a}catch(a){n||(Re=null),Ce=null,Rs(a)}}function Yi(e){if(Ce&&(On(Ce),Ce=null),e)return;const s=Re;Re=null,s.length&&Me(()=>Dn(s),!1)}function On(e){for(let s=0;s<e.length;s++)ns(e[s])}function Xi(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:ns(a)}if(W.context){if(W.count){W.effects||(W.effects=[]),W.effects.push(...e.slice(0,n));return}wt()}for(W.effects&&(W.done||!W.count)&&(e=[...W.effects,...e],n+=W.effects.length,delete W.effects),s=0;s<n;s++)ns(e[s])}function as(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===ze?a!==s&&(!a.updatedAt||a.updatedAt<os)&&ns(a):r===ss&&as(a,s)}}}function Fn(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ss,n.pure?Ce.push(n):Re.push(n),n.observers&&Fn(n))}}function Pt(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),l=n.observerSlots.pop();a<r.length&&(i.sourceSlots[l]=a,r[a]=i,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Pt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Pt(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function xs(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Rs(e,s=oe){throw xs(e)}function ys(e){if(typeof e=="function"&&!e.length)return ys(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=ys(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Zi(e,s){return function(a){let r;return Ve(()=>r=Se(()=>(oe.context={...oe.context,[e]:a.value},Mn(()=>a.children))),void 0),r}}var vs=Symbol("fallback");function rs(e){for(let s=0;s<e.length;s++)e[s]()}function Ji(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return bt(()=>rs(i)),()=>{let u=e()||[],d=u.length,h,f;return u[Ms],Se(()=>{let y,p,S,E,G,w,_,b,B;if(d===0)l!==0&&(rs(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[vs],r[0]=He(O=>(i[0]=O,n.fallback())),l=1);else if(l===0){for(r=new Array(d),f=0;f<d;f++)a[f]=u[f],r[f]=He(v);l=d}else{for(S=new Array(d),E=new Array(d),o&&(G=new Array(d)),w=0,_=Math.min(l,d);w<_&&a[w]===u[w];w++);for(_=l-1,b=d-1;_>=w&&b>=w&&a[_]===u[b];_--,b--)S[b]=r[_],E[b]=i[_],o&&(G[b]=o[_]);for(y=new Map,p=new Array(b+1),f=b;f>=w;f--)B=u[f],h=y.get(B),p[f]=h===void 0?-1:h,y.set(B,f);for(h=w;h<=_;h++)B=a[h],f=y.get(B),f!==void 0&&f!==-1?(S[f]=r[h],E[f]=i[h],o&&(G[f]=o[h]),f=p[f],y.set(B,f)):i[h]();for(f=w;f<d;f++)f in S?(r[f]=S[f],i[f]=E[f],o&&(o[f]=G[f],o[f](f))):r[f]=He(v);r=r.slice(0,l=d),a=u.slice(0)}return r});function v(y){if(i[f]=y,o){const[p,S]=je(f);return o[f]=S,s(u[f],p)}return s(u[f])}}}function el(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return bt(()=>rs(i)),()=>{const d=e()||[],h=d.length;return d[Ms],Se(()=>{if(h===0)return o!==0&&(rs(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[vs],r[0]=He(v=>(i[0]=v,n.fallback())),o=1),r;for(a[0]===vs&&(i[0](),i=[],a=[],r=[],o=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=He(f));for(;u<a.length;u++)i[u]();return o=l.length=i.length=h,a=d.slice(0),r=r.slice(0,o)});function f(v){i[u]=v;const[y,p]=je(d[u]);return l[u]=p,s(y,u)}}}function Os(e,s){return Se(()=>e(s||{}))}function Wt(){return!0}var js={get(e,s,n){return s===es?n:e.get(s)},has(e,s){return s===es?!0:e.has(s)},set:Wt,deleteProperty:Wt,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:Wt,deleteProperty:Wt}},ownKeys(e){return e.keys()}};function fs(e){return(e=typeof e=="function"?e():e)?e:{}}function tl(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function Fs(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&es in o,e[l]=typeof o=="function"?(s=!0,Te(o)):o}if(kn&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=fs(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in fs(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(fs(e[o])));return[...new Set(l)]}},js);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const f=Object.getOwnPropertyDescriptor(o,h);if(!a[h])a[h]=f.get?{enumerable:!0,configurable:!0,get:tl.bind(n[h]=[f.get.bind(o)])}:f.value!==void 0?f:void 0;else{const v=n[h];v&&(f.get?v.push(f.get.bind(o)):f.value!==void 0&&v.push(()=>f.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const o=i[l],u=a[o];u&&u.get?Object.defineProperty(r,o,u):r[o]=u?u.value:void 0}return r}function qn(e,...s){if(kn&&es in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(o){return l.includes(o)?e[o]:void 0},has(o){return l.includes(o)&&o in e},keys(){return l.filter(o=>o in e)}},js));return i.push(new Proxy({get(l){return r.has(l)?void 0:e[l]},has(l){return r.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!r.has(l))}},js)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let o=!1,u=0;for(const d of s)d.includes(r)&&(o=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;o||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function zn(e){let s,n;const a=r=>{const i=W.context;if(i){const[o,u]=je();W.count||(W.count=0),W.count++,(n||(n=e())).then(d=>{!W.done&&wt(i),W.count--,u(()=>d.default),wt()}),s=o}else if(!s){const[o]=Ri(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Te(()=>(l=s())?Se(()=>{if(!i||W.done)return l(r);const o=W.context;wt(i);const u=l(r);return wt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var sl=0;function nl(){return W.context?W.getNextContextId():`cl-${sl++}`}var $n=e=>`Stale read from <${e}>.`;function al(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(Ji(()=>e.each,e.children,s||void 0))}function rl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(el(()=>e.each,e.children,s||void 0))}function il(e){const s=e.keyed,n=Te(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Te(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Se(()=>r(s?a:()=>{if(!Se(n))throw $n("Show");return e.when})):r}return e.fallback},void 0,void 0)}function ll(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=Mn(()=>e.children),r=Te(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const o=i[l].when;if(o)return s=!!i[l].keyed,[l,o,i[l]]}return[-1]},void 0,{equals:n});return Te(()=>{const[i,l,o]=r();if(i<0)return e.fallback;const u=o.children;return typeof u=="function"&&u.length>0?Se(()=>u(s?l:()=>{if(Se(r)[0]!==i)throw $n("Match");return o.when})):u},void 0,void 0)}function ol(e){return e}var cl=["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"],ul=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...cl]),dl=new Set(["innerHTML","textContent","innerText","children"]),hl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),ml=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 fl(e,s){const n=ml[e];return typeof n=="object"?n[s]?n.$:void 0:n}var gl=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),pl=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"]),xl={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function yl(e,s,n){let a=n.length,r=s.length,i=a,l=0,o=0,u=s[r-1].nextSibling,d=null;for(;l<r||o<i;){if(s[l]===n[o]){l++,o++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const h=i<a?o?n[o-1].nextSibling:n[i-o]:u;for(;o<i;)e.insertBefore(n[o++],h)}else if(i===o)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[o]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let f=o;for(;f<i;)d.set(n[f],f++)}const h=d.get(s[l]);if(h!=null)if(o<h&&h<i){let f=l,v=1,y;for(;++f<r&&f<i&&!((y=d.get(s[f]))==null||y!==h+v);)v++;if(v>h-o){const p=s[l];for(;o<h;)e.insertBefore(n[o++],p)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var Ct="_$DX_DELEGATE";function Hn(e,s,n,a={}){let r;return He(i=>{r=i,s===document?e():ls(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function vl(e,s,n){let a;const r=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},i=()=>(a||(a=r())).cloneNode(!0);return i.cloneNode=i,i}function Vn(e,s=window.document){const n=s[Ct]||(s[Ct]=new Set);for(let a=0,r=e.length;a<r;a++){const i=e[a];n.has(i)||(n.add(i),s.addEventListener(i,Xn))}}function jl(e=window.document){if(e[Ct]){for(let s of e[Ct].keys())e.removeEventListener(s,Xn);delete e[Ct]}}function is(e,s,n){st(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function bl(e,s,n,a){st(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function El(e,s,n){st(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function Kn(e,s){st(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Wn(e,s,n,a){if(a)Array.isArray(n)?(e[`$$${s}`]=n[0],e[`$$${s}Data`]=n[1]):e[`$$${s}`]=n;else if(Array.isArray(n)){const r=n[0];e.addEventListener(s,n[0]=i=>r.call(e,n[1],i))}else e.addEventListener(s,n,typeof n!="function"&&n)}function Sl(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const o=r[i];!o||o==="undefined"||s[o]||(tn(e,o,!1),delete n[o])}for(i=0,l=a.length;i<l;i++){const o=a[i],u=!!s[o];!o||o==="undefined"||n[o]===u||!u||(tn(e,o,!0),n[o]=u)}return n}function wl(e,s,n){if(!s)return n?is(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function Qn(e,s={},n,a){const r={};return a||Ve(()=>r.children=It(e,s.children,r.children)),Ve(()=>typeof s.ref=="function"&&Yn(s.ref,e)),Ve(()=>Nl(e,s,n,!0,r,!0)),r}function Yn(e,s,n){return Se(()=>e(s,n))}function ls(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return It(e,s,a,n);Ve(r=>It(e,s(),r,n),a)}function Nl(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=sn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=sn(e,l,o,r[l],n,i,s)}}function Al(e){let s,n;return!st()||!(s=W.registry.get(n=Tl()))?e():(W.completed&&W.completed.add(s),W.registry.delete(n),s)}function st(e){return!!W.context&&!W.done&&(!e||e.isConnected)}function Cl(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function tn(e,s,n){const a=s.trim().split(/\s+/);for(let r=0,i=a.length;r<i;r++)e.classList.toggle(a[r],n)}function sn(e,s,n,a,r,i,l){let o,u,d,h,f;if(s==="style")return wl(e,n,a);if(s==="classList")return Sl(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const v=s.slice(3);a&&e.removeEventListener(v,a,typeof a!="function"&&a),n&&e.addEventListener(v,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const v=s.slice(10);a&&e.removeEventListener(v,a,!0),n&&e.addEventListener(v,n,!0)}else if(s.slice(0,2)==="on"){const v=s.slice(2).toLowerCase(),y=gl.has(v);if(!y&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(v,p)}(y||n)&&(Wn(e,v,n,y),y&&Vn([v]))}else if(s.slice(0,5)==="attr:")is(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")El(e,s.slice(5),n);else if((f=s.slice(0,5)==="prop:")||(d=dl.has(s))||!r&&((h=fl(s,e.tagName))||(u=ul.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(f)s=s.slice(5),u=!0;else if(st(e))return n;s==="class"||s==="className"?Kn(e,n):o&&!u&&!d?e[Cl(s)]=n:e[h||s]=n}else{const v=r&&s.indexOf(":")>-1&&xl[s.split(":")[0]];v?bl(e,v,s,n):is(e,hl[s]||s,n)}return n}function Xn(e){if(W.registry&&W.events&&W.events.find(([u,d])=>d===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const d=s[`${n}Data`];if(d!==void 0?u.call(s,d,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},o=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),W.registry&&!W.done&&(W.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,o();break}if(s.parentNode===r)break}}else o();i(a)}function It(e,s,n,a,r){const i=st(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const h=n[d];h.nodeType===8&&h.data.slice(0,2)==="!$"?h.remove():u.push(h)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,o=a!==void 0;if(e=o&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(o){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=at(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(i)return n;n=at(e,n,a)}else{if(l==="function")return Ve(()=>{let u=s();for(;typeof u=="function";)u=u();n=It(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(bs(u,s,n,r))return Ve(()=>n=It(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let h=u[0];if(h.parentNode!==e)return n;const f=[h];for(;(h=h.nextSibling)!==a;)f.push(h);return n=f}if(u.length===0){if(n=at(e,n,a),o)return n}else d?n.length===0?nn(e,u,a):yl(e,n,u):(n&&at(e),nn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=o?[s]:s;if(Array.isArray(n)){if(o)return n=at(e,n,a,s);at(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function bs(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let o=s[i],u=n&&n[e.length],d;if(!(o==null||o===!0||o===!1))if((d=typeof o)=="object"&&o.nodeType)e.push(o);else if(Array.isArray(o))r=bs(e,o,u)||r;else if(d==="function")if(a){for(;typeof o=="function";)o=o();r=bs(e,Array.isArray(o)?o:[o],Array.isArray(u)?u:[u])||r}else e.push(o),r=!0;else{const h=String(o);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function nn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function at(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const o=s[l];if(r!==o){const u=o.parentNode===e;!i&&!l?u?e.replaceChild(r,o):e.insertBefore(r,n):u&&o.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function Tl(){return W.getNextContextId()}var Pl="http://www.w3.org/2000/svg";function Zn(e,s=!1){return s?document.createElementNS(Pl,e):document.createElement(e)}function Il(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=en();let i,l=!!W.context;return Us(()=>{l&&(en().user=l=!1),i||(i=qi(r,()=>Te(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,d]=je(!1),h=()=>d(!0);He(f=>ls(o,()=>u()?f():i(),null)),bt(h)}else{const u=Zn(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),ls(d,i),o.appendChild(u),e.ref&&e.ref(u),bt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function _l(e){const[s,n]=qn(e,["component"]),a=Te(()=>s.component);return Te(()=>{const r=a();switch(typeof r){case"function":return Se(()=>r(n));case"string":const i=pl.has(r),l=W.context?Al():Zn(r,i);return Qn(l,n,i),l}})}var kl=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,s){this.keyToValue.set(e,s),this.valueToKey.set(s,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},Jn=class{constructor(e){this.generateIdentifier=e,this.kv=new kl}register(e,s){this.kv.getByValue(e)||(s||(s=this.generateIdentifier(e)),this.kv.set(s,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},Dl=class extends Jn{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,s){typeof s=="object"?(s.allowProps&&this.classToAllowedProps.set(e,s.allowProps),super.register(e,s.identifier)):super.register(e,s)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function Ll(e){if("values"in Object)return Object.values(e);const s=[];for(const n in e)e.hasOwnProperty(n)&&s.push(e[n]);return s}function Bl(e,s){const n=Ll(e);if("find"in n)return n.find(s);const a=n;for(let r=0;r<a.length;r++){const i=a[r];if(s(i))return i}}function Et(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Zt(e,s){return e.indexOf(s)!==-1}function an(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Gl=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Bl(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Ml=e=>Object.prototype.toString.call(e).slice(8,-1),ea=e=>typeof e>"u",Ul=e=>e===null,_t=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Es=e=>_t(e)&&Object.keys(e).length===0,Ke=e=>Array.isArray(e),Rl=e=>typeof e=="string",Ol=e=>typeof e=="number"&&!isNaN(e),Fl=e=>typeof e=="boolean",ql=e=>e instanceof RegExp,kt=e=>e instanceof Map,Dt=e=>e instanceof Set,ta=e=>Ml(e)==="Symbol",zl=e=>e instanceof Date&&!isNaN(e.valueOf()),$l=e=>e instanceof Error,rn=e=>typeof e=="number"&&isNaN(e),Hl=e=>Fl(e)||Ul(e)||ea(e)||Ol(e)||Rl(e)||ta(e),Vl=e=>typeof e=="bigint",Kl=e=>e===1/0||e===-1/0,Wl=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Ql=e=>e instanceof URL,sa=e=>e.replace(/\./g,"\\."),gs=e=>e.map(String).map(sa).join("."),Tt=e=>{const s=[];let n="";for(let r=0;r<e.length;r++){let i=e.charAt(r);if(i==="\\"&&e.charAt(r+1)==="."){n+=".",r++;continue}if(i==="."){s.push(n),n="";continue}n+=i}const a=n;return s.push(a),s};function Ge(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var na=[Ge(ea,"undefined",()=>null,()=>{}),Ge(Vl,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),Ge(zl,"Date",e=>e.toISOString(),e=>new Date(e)),Ge($l,"Error",(e,s)=>{const n={name:e.name,message:e.message};return s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n},(e,s)=>{const n=new Error(e.message);return n.name=e.name,n.stack=e.stack,s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n}),Ge(ql,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),Ge(Dt,"set",e=>[...e.values()],e=>new Set(e)),Ge(kt,"map",e=>[...e.entries()],e=>new Map(e)),Ge(e=>rn(e)||Kl(e),"number",e=>rn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),Ge(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),Ge(Ql,"URL",e=>e.toString(),e=>new URL(e))];function us(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var aa=us((e,s)=>ta(e)?!!s.symbolRegistry.getIdentifier(e):!1,(e,s)=>["symbol",s.symbolRegistry.getIdentifier(e)],e=>e.description,(e,s,n)=>{const a=n.symbolRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown symbol");return a}),Yl=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),ra=us(Wl,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Yl[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function ia(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var la=us(ia,(e,s)=>["class",s.classRegistry.getIdentifier(e.constructor)],(e,s)=>{const n=s.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};const a={};return n.forEach(r=>{a[r]=e[r]}),a},(e,s,n)=>{const a=n.classRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");return Object.assign(Object.create(a.prototype),e)}),oa=us((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Xl=[la,aa,oa,ra],ln=(e,s)=>{const n=an(Xl,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=an(na,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},ca={};na.forEach(e=>{ca[e.annotation]=e});var Zl=(e,s,n)=>{if(Ke(s))switch(s[0]){case"symbol":return aa.untransform(e,s,n);case"class":return la.untransform(e,s,n);case"custom":return oa.untransform(e,s,n);case"typed-array":return ra.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=ca[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},rt=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function ua(e){if(Zt(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Zt(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Zt(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Jl=(e,s)=>{ua(s);for(let n=0;n<s.length;n++){const a=s[n];if(Dt(e))e=rt(e,+a);else if(kt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=rt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Ss=(e,s,n)=>{if(ua(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Ke(a)){const o=+l;a=a[o]}else if(_t(a))a=a[l];else if(Dt(a)){const o=+l;a=rt(a,o)}else if(kt(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=rt(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(Ke(a)?a[+r]=n(a[+r]):_t(a)&&(a[r]=n(a[r])),Dt(a)){const i=rt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(kt(a)){const i=+s[s.length-2],l=rt(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(l);a.set(u,a.get(l)),u!==l&&a.delete(l);break}case"value":{a.set(l,n(a.get(l)));break}}}return e};function ws(e,s,n=[]){if(!e)return;if(!Ke(e)){Et(e,(i,l)=>ws(i,s,[...n,...Tt(l)]));return}const[a,r]=e;r&&Et(r,(i,l)=>{ws(i,s,[...n,...Tt(l)])}),s(a,n)}function eo(e,s,n){return ws(s,(a,r)=>{e=Ss(e,r,i=>Zl(i,a,n))}),e}function to(e,s){function n(a,r){const i=Jl(e,Tt(r));a.map(Tt).forEach(l=>{e=Ss(e,l,()=>i)})}if(Ke(s)){const[a,r]=s;a.forEach(i=>{e=Ss(e,Tt(i),()=>e)}),r&&Et(r,n)}else Et(s,n);return e}var so=(e,s)=>_t(e)||Ke(e)||kt(e)||Dt(e)||ia(e,s);function no(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function ao(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(o=>o.map(String)).sort((o,u)=>o.length-u.length));const[i,...l]=r;i.length===0?a=l.map(gs):n[gs(i)]=l.map(gs)}),a?Es(n)?[a]:[a,n]:Es(n)?void 0:n}var da=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=Hl(e);if(!o){no(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!so(e,n)){const y=ln(e,n),p=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,p),p}if(Zt(i,e))return{transformedValue:null};const u=ln(e,n),d=(u==null?void 0:u.value)??e,h=Ke(d)?[]:{},f={};Et(d,(y,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const S=da(y,s,n,a,[...r,p],[...i,e],l);h[p]=S.transformedValue,Ke(S.annotations)?f[p]=S.annotations:_t(S.annotations)&&Et(S.annotations,(E,G)=>{f[sa(p)+"."+G]=E})});const v=Es(f)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,f]:f};return o||l.set(e,v),v};function ha(e){return Object.prototype.toString.call(e).slice(8,-1)}function on(e){return ha(e)==="Array"}function ro(e){if(ha(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function io(e,s,n,a,r){const i={}.propertyIsEnumerable.call(a,s)?"enumerable":"nonenumerable";i==="enumerable"&&(e[s]=n),r&&i==="nonenumerable"&&Object.defineProperty(e,s,{value:n,enumerable:!1,writable:!0,configurable:!0})}function Ns(e,s={}){if(on(e))return e.map(r=>Ns(r,s));if(!ro(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(on(s.props)&&!s.props.includes(i))return r;const l=e[i],o=Ns(l,s);return io(r,i,o,e,s.nonenumerable),r},{})}var fe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Dl,this.symbolRegistry=new Jn(s=>s.description??""),this.customTransformerRegistry=new Gl,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=da(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=ao(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=Ns(s);return n!=null&&n.values&&(a=eo(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=to(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};fe.defaultInstance=new fe;fe.serialize=fe.defaultInstance.serialize.bind(fe.defaultInstance);fe.deserialize=fe.defaultInstance.deserialize.bind(fe.defaultInstance);fe.stringify=fe.defaultInstance.stringify.bind(fe.defaultInstance);fe.parse=fe.defaultInstance.parse.bind(fe.defaultInstance);fe.registerClass=fe.defaultInstance.registerClass.bind(fe.defaultInstance);fe.registerSymbol=fe.defaultInstance.registerSymbol.bind(fe.defaultInstance);fe.registerCustom=fe.defaultInstance.registerCustom.bind(fe.defaultInstance);fe.allowErrorProps=fe.defaultInstance.allowErrorProps.bind(fe.defaultInstance);var ma=fe.serialize,lo=fe.stringify;function oo(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function co(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function uo({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function ho({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function mo(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var fo=(e,s=!1)=>{const{json:n}=ma(e);return JSON.stringify(n,null,s?2:void 0)},Qt=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,go=(e,s)=>e.queryHash.localeCompare(s.queryHash),fa=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,po=(e,s)=>Qt(e)===Qt(s)?fa(e,s):Qt(e)>Qt(s)?1:-1,xo={status:po,"query hash":go,"last updated":fa},Yt=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,ga=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,yo=(e,s)=>Yt(e)===Yt(s)?ga(e,s):Yt(e)>Yt(s)?1:-1,vo={status:yo,"last updated":ga},jo=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),bo=()=>{const[e,s]=je("dark");return Gn(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=r=>{s(r.matches?"dark":"light")};n.addEventListener("change",a),bt(()=>n.removeEventListener("change",a))}),e},Nt=(e,s,n)=>{if(s.length===0)return n;if(e instanceof Map){const a=new Map(e);if(s.length===1)return a.set(s[0],n),a;const[r,...i]=s;return a.set(r,Nt(a.get(r),i,n)),a}if(e instanceof Set){const a=Nt(Array.from(e),s,n);return new Set(a)}if(Array.isArray(e)){const a=[...e];if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Nt(a[r],i,n),a}if(e instanceof Object){const a={...e};if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Nt(a[r],i,n),a}return e},At=(e,s)=>{if(e instanceof Map){const n=new Map(e);if(s.length===1)return n.delete(s[0]),n;const[a,...r]=s;return n.set(a,At(n.get(a),r)),n}if(e instanceof Set){const n=At(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,l)=>l.toString()!==s[0]);const[a,...r]=s;return n[a]=At(n[a],r),n}if(e instanceof Object){const n={...e};if(s.length===1)return delete n[s[0]],n;const[a,...r]=s;return n[a]=At(n[a],r),n}return e},pa=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},it,Lt,Bt,Gt,Xe,Mt,lt,ot,ct,ut,dt,ht,Ut,cn,Eo=(cn=class{constructor(e){he(this,it);he(this,Lt);he(this,Bt);he(this,Gt);he(this,Xe,!1);he(this,Mt);he(this,lt);he(this,ot);he(this,ct);he(this,ut);he(this,dt);he(this,ht);he(this,Ut);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;de(this,it,je(s)),de(this,Bt,n),de(this,Gt,a),de(this,Lt,r),de(this,Mt,d),de(this,lt,h),de(this,ot,je(i)),de(this,ct,je(l)),de(this,ut,je(o)),de(this,dt,je(u))}setButtonPosition(e){K(this,ot)[1](e)}setPosition(e){K(this,ct)[1](e)}setInitialIsOpen(e){K(this,ut)[1](e)}setErrorTypes(e){K(this,dt)[1](e)}setClient(e){K(this,it)[1](e)}mount(e){if(K(this,Xe))throw new Error("Devtools is already mounted");const s=Hn(()=>{const n=this,[a]=K(this,ot),[r]=K(this,ct),[i]=K(this,ut),[l]=K(this,dt),[o]=K(this,it);let u;return K(this,ht)?u=K(this,ht):(u=zn(()=>Promise.resolve().then(()=>require("./HO4MOOFI-wJH37hvp.cjs"))),de(this,ht,u)),pa(K(this,Mt),K(this,lt)),Os(u,Fs({get queryFlavor(){return K(n,Bt)},get version(){return K(n,Gt)},get onlineManager(){return K(n,Lt)},get shadowDOMTarget(){return K(n,lt)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);de(this,Xe,!0),de(this,Ut,s)}unmount(){var e;if(!K(this,Xe))throw new Error("Devtools is not mounted");(e=K(this,Ut))==null||e.call(this),de(this,Xe,!1)}},it=new WeakMap,Lt=new WeakMap,Bt=new WeakMap,Gt=new WeakMap,Xe=new WeakMap,Mt=new WeakMap,lt=new WeakMap,ot=new WeakMap,ct=new WeakMap,ut=new WeakMap,dt=new WeakMap,ht=new WeakMap,Ut=new WeakMap,cn),mt,Rt,Ot,Ft,Ze,qt,ft,gt,pt,xt,yt,vt,jt,zt,un,So=(un=class{constructor(e){he(this,mt);he(this,Rt);he(this,Ot);he(this,Ft);he(this,Ze,!1);he(this,qt);he(this,ft);he(this,gt);he(this,pt);he(this,xt);he(this,yt);he(this,vt);he(this,jt);he(this,zt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:f}=e;de(this,mt,je(s)),de(this,Ot,n),de(this,Ft,a),de(this,Rt,r),de(this,qt,d),de(this,ft,h),de(this,gt,je(i)),de(this,pt,je(l)),de(this,xt,je(o)),de(this,yt,je(u)),de(this,vt,je(f))}setButtonPosition(e){K(this,gt)[1](e)}setPosition(e){K(this,pt)[1](e)}setInitialIsOpen(e){K(this,xt)[1](e)}setErrorTypes(e){K(this,yt)[1](e)}setClient(e){K(this,mt)[1](e)}setOnClose(e){K(this,vt)[1](()=>e)}mount(e){if(K(this,Ze))throw new Error("Devtools is already mounted");const s=Hn(()=>{const n=this,[a]=K(this,gt),[r]=K(this,pt),[i]=K(this,xt),[l]=K(this,yt),[o]=K(this,mt),[u]=K(this,vt);let d;return K(this,jt)?d=K(this,jt):(d=zn(()=>Promise.resolve().then(()=>require("./HUY7CZI3-DrGS5qNl.cjs"))),de(this,jt,d)),pa(K(this,qt),K(this,ft)),Os(d,Fs({get queryFlavor(){return K(n,Ot)},get version(){return K(n,Ft)},get onlineManager(){return K(n,Rt)},get shadowDOMTarget(){return K(n,ft)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);de(this,Ze,!0),de(this,zt,s)}unmount(){var e;if(!K(this,Ze))throw new Error("Devtools is not mounted");(e=K(this,zt))==null||e.call(this),de(this,Ze,!1)}},mt=new WeakMap,Rt=new WeakMap,Ot=new WeakMap,Ft=new WeakMap,Ze=new WeakMap,qt=new WeakMap,ft=new WeakMap,gt=new WeakMap,pt=new WeakMap,xt=new WeakMap,yt=new WeakMap,vt=new WeakMap,jt=new WeakMap,zt=new WeakMap,un);function wo(e){const s=D.useQueryClient(e.client),n=ye.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}=e,[d]=ye.useState(new Eo({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}));return ye.useEffect(()=>{d.setClient(s)},[s,d]),ye.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),ye.useEffect(()=>{r&&d.setPosition(r)},[r,d]),ye.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),ye.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),ye.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function No(e){const s=D.useQueryClient(e.client),n=ye.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=ye.useState(new So({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose}));return ye.useEffect(()=>{l.setClient(s)},[s,l]),ye.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),ye.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),ye.useEffect(()=>(n.current&&l.mount(n.current),()=>{l.unmount()}),[l]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var Ao=process.env.NODE_ENV!=="development"?function(){return null}:wo;process.env.NODE_ENV;const Co=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:I.GET_COLLECTIONS})})},To=()=>{const{data:e}=Ie(),{data:s}=Ps(),{data:n}=We(),a=ne(),r=$(),i=g.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return D.useMutation({mutationFn:async({block:l})=>r(a,{action:I.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},xa=()=>{const e=Gs();return g.useCallback(({pageId:s})=>{e(s)},[e])},Po=g.lazy(()=>Promise.resolve().then(()=>Ai));Sa.loadWebBlocks();X.registerChaiTopBar(ni);Bi();X.registerChaiMediaManager(Po);X.registerChaiSaveToLibrary(Za);const Io=e=>{const s=g.useRef([]),[n]=Pe(),a=n.get("page"),{data:r}=Ie(),{data:i={role:"",permissions:null}}=An();li();const{data:l,isFetching:o}=vn(),{blocks:u}=ii(l),{data:d}=Ne(),{mutateAsync:h}=gn(),f=ai(),{onSave:v}=oi(),{getPartialBlocks:y,getPartialBlockBlocks:p}=ci(),{aiContext:S,setAiContext:E}=Cs(),{mutateAsync:G}=tr(),[w,_]=g.useState(!1),{data:b}=We(),B=Is(),{data:O}=_s(),{data:te}=Co(),{mutateAsync:se}=To(),U=xa();Ga(),g.useEffect(()=>{const ae=()=>{document.hidden?_(!0):_(!1)};return window.addEventListener("visibilitychange",ae),()=>window.removeEventListener("visibilitychange",ae)},[]),s.current=u;const L=g.useMemo(()=>{const ae={};return i&&(ae.permissions=x.get(i,"permissions",null),ae.role=x.get(i,"role","user")),ae},[i]),H=g.useCallback(async(ae,Z)=>await G({pageType:ae,query:Z}),[G]),ee=g.useMemo(()=>x.get(b,"theme",{})||{},[b]);return t.jsxs(t.Fragment,{children:[o&&t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/30",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(N.Loader2,{className:"size-5 animate-spin"})})}),t.jsx(X.ChaiBuilderEditor,{gotoPage:U,collections:te??[],getBlockAsyncProps:se,pageExternalData:O,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:B,languages:(b==null?void 0:b.languages)||[],brandingOptions:(b==null?void 0:b.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!w&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:y,blocks:o?[]:u,theme:x.cloneDeep(ee),pageTypes:d,searchPageTypeItems:H,saveAiContextCallback:async ae=>{if(!a)return!0;const Z=s.current,k={_type:"@chai/ai-context",_value:x.isString(ae)?ae:""},V=[...Z,k];return await v({page:a,blocks:V}),E(ae),!0},aiContext:S,askAiCallBack:f,onSave:async({blocks:ae,theme:Z})=>{if(!a)return!0;s.current=ae;const k={_type:"@chai/ai-context",_value:x.isString(S)?S:""},V=[...ae,k];return await v({page:a,blocks:V}),s.current=V,x.isEqual(Z,ee)||await h({settings:{theme:Z}}),!0},themePanelComponent:ur,...L}),t.jsxs("div",{children:[t.jsx(Fa,{}),t.jsx(qa,{})]})]})},_o=new D.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),ko=e=>{const{isLoggedIn:s}=Fe(),[,n]=pn(),[a,r]=g.useState(!1);return g.useEffect(()=>(n(x.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?t.jsxs(D.QueryClientProvider,{client:_o,children:[s?t.jsx(Io,{...e}):t.jsx(mi,{}),t.jsx(Ao,{}),t.jsx(z.Toaster,{richColors:!0})]}):t.jsx("div",{})},Do=()=>{const e=ne(),s=$(),{data:n}=Ps(),a=D.useQueryClient();return D.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:I.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[q,I.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},Lo=()=>{const{user:e,logout:s}=Fe(),n=e==null?void 0:e.accessToken;return g.useCallback(async({url:a,method:r="GET",body:i={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const o=await fetch(a,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(i)});if(o.status===401)return console.log("Session expired",o),await s(),null;if(o.status===400)throw new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",o),o}},[n,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Ms;exports.ChaiBuilderPages=ko;exports.Dynamic=_l;exports.For=al;exports.ImagePicker=Pn;exports.Index=rl;exports.Match=ol;exports.NestedPathSelector=Ue;exports.PermissionChecker=ke;exports.Portal=Il;exports.Show=il;exports.Switch=ll;exports.addEventListener=Wn;exports.batch=Oi;exports.className=Kn;exports.clearDelegatedEvents=jl;exports.convertRemToPixels=jo;exports.createComponent=Os;exports.createComputed=Bn;exports.createContext=Vi;exports.createEffect=Us;exports.createMemo=Te;exports.createRenderEffect=Ve;exports.createRoot=He;exports.createSignal=je;exports.createUniqueId=nl;exports.delegateEvents=Vn;exports.deleteNestedDataByPath=At;exports.displayValue=fo;exports.getMutationStatusColor=ho;exports.getPreferredColorScheme=bo;exports.getQueryStatusColor=uo;exports.getQueryStatusColorByLabel=mo;exports.getQueryStatusLabel=oo;exports.getSidedProp=co;exports.insert=ls;exports.mergeProps=Fs;exports.mutationSortFns=vo;exports.on=Fi;exports.onCleanup=bt;exports.onMount=Gn;exports.registerLoginComponent=hi;exports.serialize=ma;exports.setAttribute=is;exports.sortFns=xo;exports.splitProps=qn;exports.spread=Qn;exports.stringify=lo;exports.template=vl;exports.untrack=Se;exports.updateNestedDataByPath=Nt;exports.use=Yn;exports.useActivePage=Ps;exports.useBuilderPageData=_s;exports.useChaiAuth=Fe;exports.useChaiFetch=Lo;exports.useChaiUserInfo=tt;exports.useContext=Ki;exports.useCurrentPage=Ie;exports.useFallbackLang=Is;exports.useFetch=$;exports.useGotoPage=xa;exports.useLanguagePages=et;exports.usePageTypes=Ne;exports.useTransition=Hi;exports.useUpdateActivePageMetadata=Do;exports.useUserRoleAndPermissions=An;exports.useWebsitePages=Vt;exports.useWebsiteSetting=We;
1
+ "use strict";var Hs=e=>{throw TypeError(e)};var Vs=(e,s,n)=>s.has(e)||Hs("Cannot "+n);var K=(e,s,n)=>(Vs(e,s,"read from private field"),n?n.call(e):s.get(e)),he=(e,s,n)=>s.has(e)?Hs("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),de=(e,s,n,a)=>(Vs(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),x=require("lodash-es"),g=require("react"),Oe=require("jotai"),D=require("@tanstack/react-query"),z=require("sonner"),X=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),N=require("lucide-react"),$t=require("date-fns"),dn=require("@chaibuilder/runtime"),Xt=require("zod"),Ea=require("react-dropzone"),Sa=require("@chaibuilder/sdk/web-blocks");function wa(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const ye=wa(g),Le={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},I={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},q="chaibuilder";let Na=0;function Ks(e,s){const n=`atom${++Na}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Aa,a.write=Ca),s&&(a.write=s),a}function Aa(e){return e(this)}function Ca(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const Ta=Symbol(""),Pa=e=>typeof(e==null?void 0:e.then)=="function";function Ia(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,f;const v=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},y=(f=(h=e())==null?void 0:h.getItem(u))!=null?f:null;return Pa(y)?y.then(v):v(y)},setItem:(u,d)=>{var h;return(h=e())==null?void 0:h.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,h,f)=>u(d,v=>{let y;try{y=JSON.parse(v||"")}catch{y=f}h(y)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=f=>{f.storageArea===e()&&f.key===u&&d(f.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),o&&(i.subscribe=l(o)),i}const _a=Ia();function ka(e,s,n=_a,a){const r=Ks(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Ks(l=>l(r),(l,o,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===Ta?(o(r,s),n.removeItem(e)):d instanceof Promise?d.then(h=>(o(r,h),n.setItem(e,h))):(o(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const hn="__logged_in_user",Da=ka(hn,null),Fe=()=>{const[e,s]=Oe.useAtom(Da),n=g.useCallback(()=>{s(null),localStorage.removeItem(hn)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},mn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),$=()=>{const{user:e,logout:s}=Fe(),n=D.useQueryClient(),a=e==null?void 0:e.accessToken;return g.useCallback(async(r,i,l={})=>{if(!a)return null;try{const o=x.get(i,"action","").toLowerCase(),u=await mn(r+(o?`?action=${o}`:""),i,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[q]}),s(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(o){throw console.error("API request failed:",i,o),o}},[a,s,n])},fn=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[q,I.GET_DRAFT_PAGE]})}})},gn=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||z.toast.success("Website settings updated successfully.")},onError:a=>{z.toast.error("Failed to update website settings",{description:a.message})}})},La=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_DATA]}),z.toast.success("Website data updated successfully.")},onError:a=>{z.toast.error("Failed to update website data",{description:a.message})}})};function Pe(){const[e,s]=g.useState(new URLSearchParams(window.location.search));return g.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Ba=Oe.atom({}),pn=()=>Oe.useAtom(Ba),Ga=()=>{const[e]=Pe(),s=e.get("page"),n=g.useRef(""),{mutate:a}=fn();g.useEffect(()=>{!x.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},qe=(e,s)=>{const[n]=pn();return g.useMemo(()=>x.get(n,e,s),[n,e,s])},ne=()=>qe("apiUrl","/chai/api"),Cs=()=>qe("usersApiUrl","/chai/users"),Ht=()=>qe("assetsApiUrl","/chai/assets"),et=()=>{const e=ne(),[s]=Pe(),n=s.get("page"),a=$();return D.useQuery({queryKey:[q,I.GET_LANGUAGE_PAGES,n],initialData:[],queryFn:async()=>{if(!n)return null;const r=await a(e,{action:I.GET_LANGUAGE_PAGES,data:{id:n}});return x.reverse(x.sortBy(r,"primaryPage"))},enabled:!!n})},We=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:I.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},xn=e=>{const{fallbackLang:s}=X.useLanguages(),{data:n}=We(),{data:a,isFetching:r}=et(),i=g.useMemo(()=>{const l={[s]:!0};return x.each(x.get(n,"languages"),o=>{const u=x.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||x.isEmpty(e)||e&&i[e]},Ts=()=>{const e=D.useQueryClient(),{data:s}=D.useQuery({queryKey:[q,I.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:g.useCallback(a=>{e.setQueryData([q,I.AI_CONTEXT],a)},[e]),aiContext:s}},Vt=()=>{const e=$(),s=ne();return D.useQuery({queryKey:[q,I.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},Ma=Oe.atom({lastSaved:void 0}),Ps=()=>Oe.useAtom(Ma),Ie=()=>{const[e]=Pe(),s=e.get("page"),[n]=yn(),{data:a,isFetching:r}=Vt();return{data:g.useMemo(()=>({...x.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},os=()=>{const[e]=Pe(),s=e.get("lang")??"",{data:n,isFetching:a}=et();return{data:g.useMemo(()=>x.find(n,{lang:s})||{},[n,s]),isFetching:a}},Ua=Oe.atom({}),yn=()=>Oe.useAtom(Ua),tt=e=>{const s=Cs(),n=$();return D.useQuery({queryKey:[q,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:I.GET_CHAI_USER,data:{userId:e}}),enabled:!x.isEmpty(e)})},Ra=Oe.atom(void 0),Kt=()=>{const[e]=Pe(),s=e.get("page"),{user:n}=Fe(),[a,r]=Oe.useAtom(Ra);return g.useMemo(()=>({isLocked:s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:i=>r(i)}),[n==null?void 0:n.id,a,s,r])},Is=()=>{const{data:e}=We();return g.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},vn=()=>{const[e]=Pe(),s=e.get("page"),n=ne(),{setAiContext:a}=Ts(),{setCurrentEditor:r}=Kt(),[,i]=Ps(),[,l]=yn(),o=$();return D.useQuery({queryKey:[q,I.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await o(n,{action:I.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=x.find(d,{_type:"@chai/ai-context"});return a(x.get(h,"_value","")||""),i(f=>({...f,lastSaved:u.lastSaved})),l(x.get(u,"metadata",{})),d},enabled:!!s})},_s=()=>{const{data:e}=Ie(),{data:s}=os(),n=ne(),a=$(),r=Is();return D.useQuery({queryKey:[q,I.GET_BUILDER_PAGE_DATA,s==null?void 0:s.pageType,(s==null?void 0:s.lang)||r,e==null?void 0:e.dynamic,s==null?void 0:s.slug],initialData:{},queryFn:async()=>a(n,{action:I.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(e!=null&&e.pageType)})};function Oa({avatar:e,name:s,email:n,onTakeOver:a}){const[r,i]=g.useState(!1),l=()=>{i(!1),a()};return t.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:t.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"w-6 h-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"w-12 h-12 border border-gray-300 rounded-full"}):t.jsx(N.UserIcon,{className:"w-12 h-12 p-2 border border-gray-300 rounded-full"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n})]})]}),t.jsx("div",{className:"text-sm mt-4",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(c.CardFooter,{children:t.jsxs(c.AlertDialog,{open:r,onOpenChange:i,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take Over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(N.AlertTriangleIcon,{className:"w-5 h-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:l,children:"Yes, Take Over"})]})]})]})})]})})}const Fa=()=>{const{isLocked:e,currentEditor:s}=Kt(),{data:n}=tt(s),[a]=Pe(),r=a.get("page"),{mutate:i}=fn(),{isFetching:l}=vn(),o=g.useCallback(()=>{i({id:r})},[r,i]);return!e||l?t.jsx("div",{className:""}):t.jsx(Oa,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",onTakeOver:o})},qa=()=>{const[e,s]=Pe(),n=e.get("lang"),a=xn(n),{setSelectedLang:r}=X.useLanguages(),i=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(o),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=x.get(Le,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-14 bg-black/30 backdrop-blur-sm",children:t.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"w-6 h-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(c.CardFooter,{children:t.jsx(c.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},za=e=>{const s=ne(),n=$();return D.useMutation({mutationFn:async a=>n(s,{action:I.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),z.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},$a=e=>{const s=ne(),n=$();return D.useQuery({queryKey:[q,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:I.GET_LIBRARY_ITEM,data:{id:e}})}catch(a){throw console.error(a),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},Ha=e=>{const s=ne(),n=$();return D.useMutation({mutationFn:async a=>n(s,{action:I.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),z.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},Va=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=g.useState(!1),u=X.useUpdateBlocksPropsRealtime(),d=Ha(()=>{u([e],{_libBlockId:void 0}),z.toast.success("Block deleted successfully"),o(!1),a()}),h=()=>{o(!0),d.mutate(s)},f=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:v=>v.preventDefault(),disabled:l,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:v=>!v&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:i||f}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},Ka=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=g.useState(!1);return t.jsx(Va,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{o(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>o(!0),children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Wa=()=>{const e=ne(),s=$(),n=D.useQueryClient(),{data:a=[],isLoading:r,error:i}=D.useQuery({queryKey:[q,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:o}=D.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return s(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:[q,"library-groups"]}),z.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),z.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:o}},Qa=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),l=g.useRef(null),{groups:o}=Wa(),[u,d]=g.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=g.useMemo(()=>[...o,...u.filter(y=>!o.some(p=>p.id===y.id))],[o,u]),f=()=>{const y=r.trim();if(!y)return;const p={id:y,name:y};d(S=>[...S,p]),s(p.id),i(""),a(!1)};g.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const v=y=>{y.key==="Enter"&&(y.preventDefault(),f())};return g.useEffect(()=>{e&&!h.some(y=>y.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:v}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:f,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!o.some(p=>p.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(N.Plus,{className:"h-4 w-4"})})]})},Ya=10*1024*1024,Xa=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useCallback(u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d){if(d.size>Ya){z.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const f=new FileReader;f.onloadend=()=>{s(f.result),a(!1)},f.readAsDataURL(d)}catch(f){console.error("Error reading file:",f),a(!1),z.toast.error("Failed to process image",{description:f instanceof Error?f.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},o=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},ge={...X.PERMISSIONS,ADD_PAGE:"add_page",EDIT_PAGE:"edit_page",EDIT_SLUG:"edit_slug",DELETE_PAGE:"delete_page",CHANGE_PAGE_TYPE:"change_page_type",PUBLISH_PAGE:"publish_page",UNPUBLISH_PAGE:"unpublish_page",MARK_AS_TEMPLATE:"mark_as_template",UNMARK_AS_TEMPLATE:"unmark_as_template",ADD_PARTIAL:"add_partial",EDIT_PARTIAL:"edit_partial",DELETE_PARTIAL:"delete_partial",PUBLISH_PARTIAL:"publish_partial",UNPUBLISH_PARTIAL:"unpublish_partial",EDIT_SEO:"edit_seo",RESTORE_REVISION:"restore_revision",DELETE_REVISION:"delete_revision",PUBLISH_THEME:"publish_theme",EDIT_SETTINGS:"edit_settings",ADD_LIBRARY_BLOCK:"create_library_block",ADD_LIBRARY_TEMPLATE:"add_library_template",EDIT_LIBRARY_BLOCK:"edit_library_block",EDIT_LIBRARY_TEMPLATE:"edit_library_template",DELETE_LIBRARY_BLOCK:"delete_library_block",DELETE_LIBRARY_TEMPLATE:"delete_library_template",ADD_MEDIA:"add_media",EDIT_MEDIA:"edit_media",DELETE_MEDIA:"delete_media"},Za=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=X.usePartailBlocksStore(),i=s.find(C=>C._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=g.useMemo(()=>s.some(C=>C._type==="PartialBlock"||C._type==="GlobalBlock"),[s]),d=g.useMemo(()=>{let C=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let R=r(M.partialBlockId);M._parent&&(R==null?void 0:R.length)>0&&(R=R.map(T=>(x.isEmpty(T._parent)&&x.set(T,"_parent",M._parent),T))),C=[...C,...R]}else C.push(M);return C},[s,r]),[h,f]=g.useState(""),[v,y]=g.useState(""),[p,S]=g.useState(""),[E,G]=g.useState(""),[w,_]=g.useState({}),[b,B]=g.useState(!1),[O,te]=g.useState(o),[se,U]=g.useState(!1),{hasPermission:L}=X.usePermissions(),H=L(ge.DELETE_LIBRARY_BLOCK),ee=X.useUpdateBlocksPropsRealtime(),ae=()=>{ee([a],{_libBlockId:void 0}),z.toast.success("Block delinked from library"),n()},{data:Z,isLoading:k,isError:V}=$a(l);g.useEffect(()=>{V&&o&&(U(!0),te(!1))},[V,o]),g.useEffect(()=>{Z&&!k&&(f(Z.name||""),y(Z.group||""),S(Z.description||""),G(Z.preview||""),te(!1))},[Z,k]),g.useEffect(()=>{const C=h.trim().length>=2,M=v.trim()!=="";B(C&&M)},[h,v]);const ve=()=>{const C={};return h.trim()?h.length<2&&(C.name="Name must be at least 2 characters"):C.name="Name is required",v||(C.group="Group is required"),_(C),Object.keys(C).length===0},{resetLibrary:we}=X.useLibraryBlocks({id:""}),Be=za(C=>{o||ee([a],{_libBlockId:C.id}),z.toast.success(`Block ${o?"updated":"saved"} successfully`),we(C.library),n()}),j=async C=>{if(C.preventDefault(),!ve())return;const M=d.map(R=>(x.has(R,"_libBlockId")&&delete R._libBlockId,R));Be.mutate({name:h.trim(),group:v,blocks:M,description:p.trim(),...E&&E.startsWith("data:")?{previewImage:E}:{},...o?{id:l}:{}})},m=Be.isPending;return O||k?t.jsx("div",{className:"flex items-center justify-center p-8",children:t.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):se?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:ae,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(N.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:w.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:C=>f(C.target.value),className:w.name?"border-destructive":""}),w.name&&t.jsx("p",{className:"text-xs text-destructive",children:w.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:w.group?"text-destructive":"",children:"Group"}),t.jsx(Qa,{value:v,onChange:y}),w.group&&t.jsx("p",{className:"text-xs text-destructive",children:w.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:C=>S(C.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Xa,{value:E,onChange:G})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&H&&t.jsx(Ka,{blockId:a,libBlockId:l,blockName:h,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:m,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:m||!b,children:m?"Saving...":o?"Update Block":"Save Block"})]})]})]})},Q={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."},Ja={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ne=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:I.GET_PAGE_TYPES})})},er=e=>{const{data:s}=Ne();return g.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},tr=()=>{const e=ne(),s=$();return D.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:I.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},jn=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>await n(e,{action:I.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=x.find(a,{key:i.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";z.toast.success(l)},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:x.get(Ja,r.message,r.message)})}})},ks=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>await n(e,{action:I.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},sr=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>n(e,{action:I.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){z.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},nr=()=>{const e=ne(),s=D.useQueryClient(),n=$(),{data:a}=Ne();return D.useMutation({mutationFn:async r=>n(e,{action:I.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]});const l=x.find(a,{key:i.pageType});z.toast.success(l!=null&&l.hasSlug?Q.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=x.find(a,{key:i.pageType});z.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Ds=()=>{const e=ne(),s=$(),n=D.useQueryClient(),{data:a}=Ie();return D.useMutation({mutationFn:async({ids:r})=>s(e,{action:I.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,I.GET_CHANGES]}),n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{z.toast.error("Failed to publish pages.")}})},ar=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>{var r;return s(e,{action:I.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),z.toast.success("Page marked as template successfully.")},onError:()=>{z.toast.error("Failed to mark page as template.")}})},rr=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>s(e,{action:I.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),z.toast.success("Page unmarked as template successfully.")},onError:()=>{z.toast.error("Failed to unmark page as template.")}})},ir=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:I.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{z.toast.success(Q.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]})},onError:()=>{z.toast.error("Failed to change slug")}})};var Ls={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!s.OffscreenCanvas)return!1;var j=new OffscreenCanvas(1,1),m=j.getContext("2d");m.fillRect(0,0,1,1);var C=j.transferToImageBitmap();try{m.createPattern(C,"no-repeat")}catch{return!1}return!0}();function u(){}function d(j){var m=n.exports.Promise,C=m!==void 0?m:s.Promise;return typeof C=="function"?new C(j):(j(u,u),null)}var h=function(j,m){return{transform:function(C){if(j)return C;if(m.has(C))return m.get(C);var M=new OffscreenCanvas(C.width,C.height),R=M.getContext("2d");return R.drawImage(C,0,0),m.set(C,M),M},clear:function(){m.clear()}}}(o,new Map),f=function(){var j=Math.floor(16.666666666666668),m,C,M={},R=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(m=function(T){var Y=Math.random();return M[Y]=requestAnimationFrame(function F(J){R===J||R+j-1<J?(R=J,delete M[Y],T()):M[Y]=requestAnimationFrame(F)}),Y},C=function(T){M[T]&&cancelAnimationFrame(M[T])}):(m=function(T){return setTimeout(T,j)},C=function(T){return clearTimeout(T)}),{frame:m,cancel:C}}(),v=function(){var j,m,C={};function M(R){function T(Y,F){R.postMessage({options:Y||{},callback:F})}R.init=function(F){var J=F.transferControlToOffscreen();R.postMessage({canvas:J},[J])},R.fire=function(F,J,ce){if(m)return T(F,null),m;var pe=Math.random().toString(36).slice(2);return m=d(function(ue){function xe(be){be.data.callback===pe&&(delete C[pe],R.removeEventListener("message",xe),m=null,h.clear(),ce(),ue())}R.addEventListener("message",xe),T(F,pe),C[pe]=xe.bind(null,{data:{callback:pe}})}),m},R.reset=function(){R.postMessage({reset:!0});for(var F in C)C[F](),delete C[F]}}return function(){if(j)return j;if(!a&&i){var R=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
2
+ `);try{j=new Worker(URL.createObjectURL(new Blob([R])))}catch(T){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",T),null}M(j)}return j}}(),y={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function p(j,m){return m?m(j):j}function S(j){return j!=null}function E(j,m,C){return p(j&&S(j[m])?j[m]:y[m],C)}function G(j){return j<0?0:Math.floor(j)}function w(j,m){return Math.floor(Math.random()*(m-j))+j}function _(j){return parseInt(j,16)}function b(j){return j.map(B)}function B(j){var m=String(j).replace(/[^0-9a-f]/gi,"");return m.length<6&&(m=m[0]+m[0]+m[1]+m[1]+m[2]+m[2]),{r:_(m.substring(0,2)),g:_(m.substring(2,4)),b:_(m.substring(4,6))}}function O(j){var m=E(j,"origin",Object);return m.x=E(m,"x",Number),m.y=E(m,"y",Number),m}function te(j){j.width=document.documentElement.clientWidth,j.height=document.documentElement.clientHeight}function se(j){var m=j.getBoundingClientRect();j.width=m.width,j.height=m.height}function U(j){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=j,m}function L(j,m,C,M,R,T,Y,F,J){j.save(),j.translate(m,C),j.rotate(T),j.scale(M,R),j.arc(0,0,1,Y,F,J),j.restore()}function H(j){var m=j.angle*(Math.PI/180),C=j.spread*(Math.PI/180);return{x:j.x,y:j.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:j.startVelocity*.5+Math.random()*j.startVelocity,angle2D:-m+(.5*C-Math.random()*C),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:j.color,shape:j.shape,tick:0,totalTicks:j.ticks,decay:j.decay,drift:j.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:j.gravity*3,ovalScalar:.6,scalar:j.scalar,flat:j.flat}}function ee(j,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 C=m.tick++/m.totalTicks,M=m.x+m.random*m.tiltCos,R=m.y+m.random*m.tiltSin,T=m.wobbleX+m.random*m.tiltCos,Y=m.wobbleY+m.random*m.tiltSin;if(j.fillStyle="rgba("+m.color.r+", "+m.color.g+", "+m.color.b+", "+(1-C)+")",j.beginPath(),l&&m.shape.type==="path"&&typeof m.shape.path=="string"&&Array.isArray(m.shape.matrix))j.fill(ve(m.shape.path,m.shape.matrix,m.x,m.y,Math.abs(T-M)*.1,Math.abs(Y-R)*.1,Math.PI/10*m.wobble));else if(m.shape.type==="bitmap"){var F=Math.PI/10*m.wobble,J=Math.abs(T-M)*.1,ce=Math.abs(Y-R)*.1,pe=m.shape.bitmap.width*m.scalar,ue=m.shape.bitmap.height*m.scalar,xe=new DOMMatrix([Math.cos(F)*J,Math.sin(F)*J,-Math.sin(F)*ce,Math.cos(F)*ce,m.x,m.y]);xe.multiplySelf(new DOMMatrix(m.shape.matrix));var be=j.createPattern(h.transform(m.shape.bitmap),"no-repeat");be.setTransform(xe),j.globalAlpha=1-C,j.fillStyle=be,j.fillRect(m.x-pe/2,m.y-ue/2,pe,ue),j.globalAlpha=1}else if(m.shape==="circle")j.ellipse?j.ellipse(m.x,m.y,Math.abs(T-M)*m.ovalScalar,Math.abs(Y-R)*m.ovalScalar,Math.PI/10*m.wobble,0,2*Math.PI):L(j,m.x,m.y,Math.abs(T-M)*m.ovalScalar,Math.abs(Y-R)*m.ovalScalar,Math.PI/10*m.wobble,0,2*Math.PI);else if(m.shape==="star")for(var re=Math.PI/2*3,Ee=4*m.scalar,Ae=8*m.scalar,P=m.x,ie=m.y,A=5,le=Math.PI/A;A--;)P=m.x+Math.cos(re)*Ae,ie=m.y+Math.sin(re)*Ae,j.lineTo(P,ie),re+=le,P=m.x+Math.cos(re)*Ee,ie=m.y+Math.sin(re)*Ee,j.lineTo(P,ie),re+=le;else j.moveTo(Math.floor(m.x),Math.floor(m.y)),j.lineTo(Math.floor(m.wobbleX),Math.floor(R)),j.lineTo(Math.floor(T),Math.floor(Y)),j.lineTo(Math.floor(M),Math.floor(m.wobbleY));return j.closePath(),j.fill(),m.tick<m.totalTicks}function ae(j,m,C,M,R){var T=m.slice(),Y=j.getContext("2d"),F,J,ce=d(function(pe){function ue(){F=J=null,Y.clearRect(0,0,M.width,M.height),h.clear(),R(),pe()}function xe(){a&&!(M.width===r.width&&M.height===r.height)&&(M.width=j.width=r.width,M.height=j.height=r.height),!M.width&&!M.height&&(C(j),M.width=j.width,M.height=j.height),Y.clearRect(0,0,M.width,M.height),T=T.filter(function(be){return ee(Y,be)}),T.length?F=f.frame(xe):ue()}F=f.frame(xe),J=ue});return{addFettis:function(pe){return T=T.concat(pe),ce},canvas:j,promise:ce,reset:function(){F&&f.cancel(F),J&&J()}}}function Z(j,m){var C=!j,M=!!E(m||{},"resize"),R=!1,T=E(m,"disableForReducedMotion",Boolean),Y=i&&!!E(m||{},"useWorker"),F=Y?v():null,J=C?te:se,ce=j&&F?!!j.__confetti_initialized:!1,pe=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,ue;function xe(re,Ee,Ae){for(var P=E(re,"particleCount",G),ie=E(re,"angle",Number),A=E(re,"spread",Number),le=E(re,"startVelocity",Number),De=E(re,"decay",Number),_e=E(re,"gravity",Number),Qe=E(re,"drift",Number),$e=E(re,"colors",b),nt=E(re,"ticks",Number),qs=E(re,"shapes"),ya=E(re,"scalar"),va=!!E(re,"flat"),zs=O(re),$s=P,hs=[],ja=j.width*zs.x,ba=j.height*zs.y;$s--;)hs.push(H({x:ja,y:ba,angle:ie,spread:A,startVelocity:le,color:$e[$s%$e.length],shape:qs[w(0,qs.length)],ticks:nt,decay:De,gravity:_e,drift:Qe,scalar:ya,flat:va}));return ue?ue.addFettis(hs):(ue=ae(j,hs,J,Ee,Ae),ue.promise)}function be(re){var Ee=T||E(re,"disableForReducedMotion",Boolean),Ae=E(re,"zIndex",Number);if(Ee&&pe)return d(function(le){le()});C&&ue?j=ue.canvas:C&&!j&&(j=U(Ae),document.body.appendChild(j)),M&&!ce&&J(j);var P={width:j.width,height:j.height};F&&!ce&&F.init(j),ce=!0,F&&(j.__confetti_initialized=!0);function ie(){if(F){var le={getBoundingClientRect:function(){if(!C)return j.getBoundingClientRect()}};J(le),F.postMessage({resize:{width:le.width,height:le.height}});return}P.width=P.height=null}function A(){ue=null,M&&(R=!1,s.removeEventListener("resize",ie)),C&&j&&(document.body.contains(j)&&document.body.removeChild(j),j=null,ce=!1)}return M&&!R&&(R=!0,s.addEventListener("resize",ie,!1)),F?F.fire(re,P,A):xe(re,P,A)}return be.reset=function(){F&&F.reset(),ue&&ue.reset()},be}var k;function V(){return k||(k=Z(null,{useWorker:!0,resize:!0})),k}function ve(j,m,C,M,R,T,Y){var F=new Path2D(j),J=new Path2D;J.addPath(F,new DOMMatrix(m));var ce=new Path2D;return ce.addPath(J,new DOMMatrix([Math.cos(Y)*R,Math.sin(Y)*R,-Math.sin(Y)*T,Math.cos(Y)*T,C,M])),ce}function we(j){if(!l)throw new Error("path confetti are not supported in this browser");var m,C;typeof j=="string"?m=j:(m=j.path,C=j.matrix);var M=new Path2D(m),R=document.createElement("canvas"),T=R.getContext("2d");if(!C){for(var Y=1e3,F=Y,J=Y,ce=0,pe=0,ue,xe,be=0;be<Y;be+=2)for(var re=0;re<Y;re+=2)T.isPointInPath(M,be,re,"nonzero")&&(F=Math.min(F,be),J=Math.min(J,re),ce=Math.max(ce,be),pe=Math.max(pe,re));ue=ce-F,xe=pe-J;var Ee=10,Ae=Math.min(Ee/ue,Ee/xe);C=[Ae,0,0,Ae,-Math.round(ue/2+F)*Ae,-Math.round(xe/2+J)*Ae]}return{type:"path",path:m,matrix:C}}function Be(j){var m,C=1,M="#000000",R='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof j=="string"?m=j:(m=j.text,C="scalar"in j?j.scalar:C,R="fontFamily"in j?j.fontFamily:R,M="color"in j?j.color:M);var T=10*C,Y=""+T+"px "+R,F=new OffscreenCanvas(T,T),J=F.getContext("2d");J.font=Y;var ce=J.measureText(m),pe=Math.ceil(ce.actualBoundingBoxRight+ce.actualBoundingBoxLeft),ue=Math.ceil(ce.actualBoundingBoxAscent+ce.actualBoundingBoxDescent),xe=2,be=ce.actualBoundingBoxLeft+xe,re=ce.actualBoundingBoxAscent+xe;pe+=xe+xe,ue+=xe+xe,F=new OffscreenCanvas(pe,ue),J=F.getContext("2d"),J.font=Y,J.fillStyle=M,J.fillText(m,be,re);var Ee=1/C;return{type:"bitmap",bitmap:F.transferToImageBitmap(),matrix:[Ee,0,0,Ee,-pe*Ee/2,-ue*Ee/2]}}n.exports=function(){return V().apply(this,arguments)},n.exports.reset=function(){V().reset()},n.exports.create=Z,n.exports.shapeFromPath=we,n.exports.shapeFromText=Be})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Ls,!1);const lr=Ls.exports;Ls.exports.create;const or={particleCount:350,spread:120,origin:{y:.6},angle:90},cr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Jt=e=>{let s=cr[e];s||(s={});const n={...or,...s};lr(n)},ur=()=>{const[e]=X.useTheme(),{mutate:s,isPending:n}=Ds(),{mutateAsync:a,isPending:r}=gn(),i=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{Jt("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(c.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},dr=({page:e,onClose:s})=>{const[n,a]=g.useState(e.slug||""),{mutate:r,isPending:i}=ir(),{data:l}=Ne(),o=x.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Le).some(y=>n===`/${y}`||x.startsWith(n,`/${y}/`))){z.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:h=>{const f=h.target.value;x.startsWith(f,`/${d}`)&&a(f)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!x.startsWith(n,`/${d}`)||x.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})};function bn({page:e,onClose:s}){const[,n]=Pe(),{mutate:a,isPending:r}=sr(),{data:i}=Ne(),l=()=>{a(e,{onSuccess:()=>{e!=null&&e.primaryPage||(window.history.replaceState(null,"","/"),n(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate"))),s()}})},o=i==null?void 0:i.find(u=>u.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",o!=null&&o.hasSlug?(o==null?void 0:o.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:x.get(Le,e.lang,e.lang)})]})]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:r,onClick:l,children:r?"Deleting...":"Delete"})]})]})})}const ke=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=X.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},Bs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=nr(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[Q.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:r,children:a?Q.UPDATING:Q.UNPUBLISH})]})]})})},En=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Ie(),{data:r}=Ne(),[i,l]=g.useState(e.name||""),[o,u]=g.useState(e.edit?e.lang:""),[d,h]=g.useState(e.edit?e.slug:""),{mutate:f,isPending:v}=jn(),{mutate:y,isPending:p}=ks(),S=g.useMemo(()=>r==null?void 0:r.find(_=>_.key===e.pageType),[r,e.pageType]),E=!(S!=null&&S.hasSlug),G=v||p,w=_=>{_.preventDefault();const b={name:i,lang:o,primaryPage:a==null?void 0:a.id,slug:d,pageType:a==null?void 0:a.pageType,tracking:{}};b.pageType=e.pageType,e.edit&&(b.id=e==null?void 0:e.id),e.edit?y(b,{onSuccess:s}):f(b,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:e.edit?Q.EDIT_LANGUAGE:Q.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:Q.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:w,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",className:"text-right",children:Q.LANGUAGE}),t.jsxs("select",{value:o,disabled:e.edit||x.isEmpty(n),onChange:_=>{const b=_.target.value;u(b),!E&&h(`/${b}`)},className:"flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 col-span-3",children:[t.jsx("option",{value:"",disabled:!0,selected:!0,children:e.edit?x.get(Le,e.lang,e.lang):x.isEmpty(n)?Q.ALL_AVAILABLE_LANGUAGE_PAGE:Q.CHOOSE_LANGUAGE}),x.map(n,_=>t.jsx("option",{value:_,children:x.get(Le,_,_)},_))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-right",children:Q.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:i,onChange:_=>l(_.target.value),className:"col-span-3",required:!0,placeholder:Q.ENTER_PAGE_NAME})]}),!E&&t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:[Q.SLUG," ",t.jsx("small",{className:"font-light",children:Q.SLUG_SHOULD_START_WITH})]}),t.jsx(c.Input,{id:"slug",value:d,onChange:_=>{const b=_.target.value;x.startsWith(b,`/${o}`)&&h(x.toLower(x.trim(b)))},className:"col-span-3",required:!0,pattern:"^/.*",disabled:x.isEmpty(o),title:Q.SLUG_MUST_START_WITH,placeholder:x.isEmpty(o)?Q.CHOOSE_LANGUAGE_TO_ADD_SLUG:Q.ENTER_PAGE_SLUG})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:G||!i||!o||!E&&!x.startsWith(d,`/${o}`),children:G?e.edit?Q.UPDATING:Q.ADDING:e.edit?Q.UPDATE:Q.ADD_NEW_LANGUAGE})})]})]})})},hr=()=>{const[e,s]=g.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:r}=X.useLanguages(),{data:i,isFetching:l}=et(),{data:o}=Ie(),[u,d]=g.useState(null),[h,f]=g.useState(null),[v,y]=g.useState(null),{data:p}=We(),S=x.filter(x.get(p,"languages")||["en"],E=>!x.find(i,{lang:E})&&E!==x.get(p,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:l?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):x.map(i,E=>{const G=E.lang,w=E.slug,_=!E.primaryPage,b=G===n;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`text-slate-500 w-full p-2 rounded cursor-pointer flex items-center justify-between ${b?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>r(G),children:[t.jsxs("div",{className:" flex-1 gap-x-3",children:[t.jsxs("div",{className:"text-[13px] text-slate-800 flex items-center gap-x-2",children:[t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${E.online?"bg-green-300":"bg-gray-300"}`}),x.get(Le,_?a:G,G)]}),t.jsxs("div",{children:[w&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium",children:w})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",E.name," "]})]})]})]}),_?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(N.StarIcon,{fill:"orange",className:"w-3 h-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(ke,{permissions:[ge.EDIT_PAGE,ge.DELETE_PAGE,ge.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:B=>B.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[t.jsx(ke,{permissions:[ge.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:B=>{B.stopPropagation(),s({...E,edit:!0})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),Q.EDIT]})}),t.jsx(ke,{permissions:[ge.UNPUBLISH_PAGE],children:(E==null?void 0:E.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:B=>{B.stopPropagation(),f(E)},children:[t.jsx(N.Power,{className:"size-3"}),Q.UNPUBLISH]})}),t.jsx(ke,{permissions:[ge.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:B=>{B.stopPropagation(),d(E)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),Q.DELETE]})})]})]})})})]},E.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(ke,{permissions:[ge.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:x.isEmpty(S),onClick:()=>{s({name:o==null?void 0:o.name,pageType:o==null?void 0:o.pageType,lang:"",slug:"",edit:!1})},children:Q.ADD_NEW_LANGUAGE})})}),e&&t.jsx(En,{languages:S,langProps:e,onClose:()=>s(null)}),u&&t.jsx(bn,{page:u,onClose:()=>d(null)}),h&&t.jsx(Bs,{page:h,onClose:()=>f(null)}),v&&t.jsx(dr,{page:v,onClose:()=>y(null)})]})};function mr({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=g.useState(null),o=g.useRef(null),[u,d]=g.useState(a+e);g.useEffect(()=>{d(a+e)},[e,a]);const h=y=>{const p=y.target.value;if(!p.startsWith(a)){const b=p.replace(a,""),B=a+b;d(B),s(b);return}const E=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),G=(E.match(/\./g)||[]).length,w=G<=1;G>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(w);const _=a+E;d(_),s(E)},f=()=>{if(o.current){const y=o.current;setTimeout(()=>{const p=a.length;y.setSelectionRange(p,p)},0)}},v=y=>{const p=y.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const E=a.length;p.setSelectionRange(E,E)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:o,value:u,onChange:h,onFocus:f,onClick:v,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const fr=e=>{if(!e)return{base:e,extension:null};const s=e.lastIndexOf(".");if(s<=0)return{base:e,extension:null};const n=e.substring(s);return{base:e.substring(0,s),extension:n}},Je=e=>{if(!e)return e;const{base:s}=fr(e);return s},gr=e=>e&&Je(e),Ws=(e,s)=>{const n=Je(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function pr({pages:e,selectedParentId:s,onChange:n,className:a="w-full rounded-md border border-gray-300 px-3 py-2",id:r="parentPage"}){const i=g.useMemo(()=>!e||e.length===0?[]:e.filter(h=>!x.isEmpty(h.slug)).filter(h=>h.slug!=="/").sort((h,f)=>h.slug.localeCompare(f.slug)),[e]),l=d=>Math.max(0,(d.match(/\//g)||[]).length-1),o=d=>"    ".repeat(d),u=d=>{if(d==="/")return"/";const h=d.split("/").filter(Boolean);if(h.length<=1){const y=h[0]||"";return`/${Je(y)}`}const f=h[h.length-1];return`/${Je(f)}`};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),t.jsxs("select",{id:r,value:s||"none",onChange:d=>n(d.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),i.map(d=>{const h=l(d.slug),f=h>0?o(h):"",v=u(d.slug);return t.jsxs("option",{value:d.id,children:[f,d.name," (",v,")"]},d.id)})]})]})}function Sn({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r}){const[i,l]=g.useState(e),[o,u]=g.useState(null);g.useEffect(()=>{l(e)},[e]);const d=h=>{const v=h.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),y=(v.match(/\./g)||[]).length,p=y<=1;y>1?u("Invalid slug. Only one dot (.) is allowed in the slug"):u(null),r&&r(p),l(v),s(v)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"flex items-center mb-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent: ",gr(a)]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{value:i,onChange:d,placeholder:n,className:o?"border-red-500":""}),o&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:o})]})]})}const xr=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=g.useState("");if(g.useEffect(()=>{if(s){const o=e.find(u=>u.id===s);i((o==null?void 0:o.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex items-center justify-center h-fit text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const l={};return e.forEach(o=>{const u=o.libraryName;l[u]||(l[u]=[]),l[u].push(o)}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:o=>n(o.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(l).map(([o,u])=>t.jsx("optgroup",{label:o,children:u.map(d=>t.jsx("option",{value:d.id,children:x.startCase(d.name)},d.id))},o))]}),r&&t.jsxs("div",{className:"mt-3 border rounded overflow-hidden",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:r,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"p-2 text-xs text-gray-500 bg-gray-50 border-t",children:"Template preview"})]})]})},yr=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_LIBRARIES],queryFn:async()=>await s(e,{action:I.GET_LIBRARIES})||[]})},vr=e=>{const s=ne(),n=$();return D.useQuery({queryKey:[q,I.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:I.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?x.filter(a,{pageType:e}):a)||[]}})},jr=e=>{const{data:s=[],isLoading:n}=vr(e),{data:a=[],isLoading:r}=yr(),i=g.useMemo(()=>n||r?[]:s.map(o=>{const u=x.find(a,{id:o.library});return{...o,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=g.useMemo(()=>x.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},Gs=()=>{const[,e]=Pe();return g.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])};function br({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var P,ie;const r=Gs(),i=!!(e!=null&&e.id),{data:l}=Vt(),{mutate:o,isPending:u}=jn(),{mutate:d,isPending:h}=ks(),[f,v]=g.useState(null),[y,p]=g.useState(!0),[S,E]=g.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:G}=X.usePermissions(),w=G(ge.CHANGE_PAGE_TYPE),[_,b]=g.useState(!1),[B,O]=g.useState(""),te=g.useMemo(()=>{const A=s.find(le=>le.key===S);return(A==null?void 0:A.hasSlug)===!1},[S,s]),[se,U]=g.useState((e==null?void 0:e.parent)??""),[L,H]=g.useState((e==null?void 0:e.name)??""),[ee,ae]=g.useState((e==null?void 0:e.dynamic)??!1),[Z,k]=g.useState(ee?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[V,ve]=g.useState((e==null?void 0:e.dynamicSlugCustom)??""),[we,Be]=g.useState(!0),[j,m]=g.useState(""),{data:C,isLoading:M}=jr(S),R=u||h,T=s.find(A=>A.key===S),Y=A=>{if(i&&S!==A){O(A),b(!0);return}E(A)},F=()=>{E(B),b(!1),ae(!1)},J=A=>{ae(A),A?k(""):ve("")},ce=A=>{if(U(A),A&&A!=="none"){const le=l==null?void 0:l.find(_e=>_e.id===A),De=(le==null?void 0:le.slug)||"";if(Z.startsWith(De)){const _e=Z.slice(De.length).replace(/^\/+/,"");k(_e)}else k(Z.replace(/^\/+/,""))}else k(Z?`${Z}`:"")},pe=A=>{m(A)},ue=()=>L.trim()?ee&&!x.isEmpty(Z)?(v("Slug must be empty when using dynamic slug"),!1):ee&&!we?(v("Dynamic slug is invalid"),!1):!0:(z.toast.error("Name is required"),!1),xe=()=>{const A={pageType:T==null?void 0:T.key,name:L,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:L},{onSuccess:()=>{z.toast.success((T==null?void 0:T.name)+" updated successfully"),n()}}):o(A,{onSuccess:le=>{console.log("response",le),n(),r(le.page.id,a)}})},be=(A,le)=>{if(!A.trim()&&!ee)return v("Child page slug is required"),!1;const De=Je(le),_e=Ws(De,A);return Object.keys(Le).some(nt=>_e===`/${nt}`||(_e==null?void 0:_e.startsWith(`/${nt}/`)))?(v("Slugs cannot start with a language code for primary page"),!1):!0},re=(A,le)=>{const De=Je(le),_e=Ws(De,A),Qe={pageType:S,name:L,slug:_e.replace(/\/$/,""),parent:se,dynamic:ee,hasSlug:!0,template:j||void 0,tracking:{}};if(ee&&(Qe.dynamicSlugCustom=V),i)d({id:e==null?void 0:e.id,...Qe},{onSuccess:()=>{z.toast.success("Page updated successfully"),n()}});else{const $e=x.find(s,{key:S});$e!=null&&$e.trackingDefault&&(Qe.tracking=$e.trackingDefault),o(Qe,{onSuccess:nt=>{n(),r(nt.page.id,a)}})}},Ee=()=>{const A={pageType:S,name:L,slug:Z===""?"/":`/${Z.replace(/\/$/,"")}`,template:j||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...A},{onSuccess:()=>{z.toast.success("Page updated successfully"),n()}});else{const le=x.find(s,{key:S});le!=null&&le.trackingDefault&&(A.tracking=le.trackingDefault),o(A,{onSuccess:()=>{n()}})}},Ae=A=>{if(A.preventDefault(),v(null),!!ue()){if(!(T!=null&&T.hasSlug)){xe();return}if(se&&se!=="none"){const le=l==null?void 0:l.find(_e=>_e.id===se),De=(le==null?void 0:le.slug)||"";if(!be(Z,De))return;re(Z,De)}else Ee()}};return T!=null&&T.hasSlug?t.jsxs("form",{onSubmit:Ae,className:"w-full max-w-md mx-auto space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:S,disabled:i&&!w,onChange:A=>Y(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!w?"cursor-not-allowed text-gray-500":""}`,children:i?te?t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})]})}),_&&t.jsxs("div",{className:"mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>b(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:F,children:"Confirm"})]})]})]}),!i&&(T==null?void 0:T.hasSlug)&&C.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"text-sm mb-1 block",children:"Template"}),t.jsx(xr,{templates:C,selectedTemplateId:j,onSelectTemplate:pe,isLoading:M})]}),t.jsx(pr,{pages:l,selectedParentId:se,onChange:ce}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:L,onChange:A=>H(A.target.value),required:!0,"aria-required":"true"})]}),(T==null?void 0:T.dynamicSegments)&&se&&se!=="none"&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("input",{type:"checkbox",id:"useDynamicSlug",checked:ee,onChange:A=>J(A.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ee&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(mr,{value:V,onChange:ve,dynamicPattern:(T==null?void 0:T.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:Be})})})]}),(!(T!=null&&T.dynamicSegments)||!ee)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Sn,{value:Z,onChange:k,placeholder:se&&se!=="none"?"Enter page slug":S==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:se&&se!=="none"?(ie=l==null?void 0:l.find(A=>A.id===se))==null?void 0:ie.slug:void 0,onValidationChange:p}),f&&t.jsx("p",{className:"text-xs text-red-500",children:f})]}),t.jsx(c.Button,{disabled:R||!y&&(!(T!=null&&T.dynamicSegments)||!ee)||ee&&!we,type:"submit",className:"w-full",children:i?R?"Updating...":"Update page":R?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Ae,className:"w-full max-w-md mx-auto space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:S,disabled:i&&!w,onChange:A=>Y(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!w?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})}),_&&t.jsxs("div",{className:"mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>b(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:F,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(P=s.find(A=>A.key===S))==null?void 0:P.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:L,onChange:A=>H(A.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:R,type:"submit",className:"w-full",children:i?R?"Updating...":"Update "+(T==null?void 0:T.name):R?"Creating...":"Create "+(T==null?void 0:T.name)})]})}const Er=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Ne(),r=!!(e!=null&&e.id);return t.jsx(c.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsxs(c.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(c.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(br,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},Sr=()=>{const e=ne(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const l={pageId:a,name:r};return i&&(l.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[q,I.GET_WEBSITE_PAGES]}),z.toast.success("Page duplicated successfully")},onError:a=>{z.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},wr=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Sr(),[r,i]=g.useState(null),[l,o]=g.useState(`${e.name} (Copy)`),u=x.isEmpty(e.slug),[d,h]=g.useState(u?"":`${e.slug.split("/").pop()}-copy`),f=u?"":x.initial(e.slug.split("/")).join("/"),[v,y]=g.useState(!1),p=S=>{if(S.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),y(!0);const E={pageId:e.id,name:l};u||(E.slug=`${f}/${d}`),n(E,{onSuccess:()=>{y(!1),s()},onError:G=>{y(!1),G.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):G.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):G.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(G.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Duplicate Page"}),t.jsx(c.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!u&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:S=>o(S.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Sn,{value:d,onChange:S=>h(S),parentSlug:f,onValidationChange:S=>{i(S?null:"Invalid slug")}})]}),r&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:r})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||v,children:a||v?"Duplicating...":"Duplicate"})]})]})]})})},Nr=1*1024*1024,Ar=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),[l,o]=g.useState(""),[u,d]=g.useState(!1),h=g.useRef(null),f=ar(),{data:v}=Ne(),y=v==null?void 0:v.find(_=>_.key===e.pageType),p=(y==null?void 0:y.name)||x.startCase(e.pageType),S=g.useCallback(_=>{var B;const b=(B=_.target.files)==null?void 0:B[0];if(b){if(b.size>Nr){z.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(b.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const O=new FileReader;O.onloadend=()=>{o(O.result),d(!1)},O.readAsDataURL(b)}catch(O){console.error("Error reading file:",O),d(!1),z.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),E=()=>{o(""),h.current&&(h.current.value="")},G=()=>{var _;(_=h.current)==null||_.click()},w=()=>{a(!0),f.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:x.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:_=>i(_.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:h,onChange:S,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:G,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:E,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:_=>{_.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:w,children:"Mark as template"})]})]})})},Cr=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),r=rr(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Unmark as template"}),t.jsx(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},Tr=({currentEditor:e})=>{const{user:s}=Fe(),{data:n}=tt(e);return!n||!e||e===(s==null?void 0:s.id)?null:t.jsx("span",{className:"ml-2 text-xs font-light text-gray-500 flex items-center gap-1",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(N.LockIcon,{className:"w-3 h-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},Pr=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:d})=>{const h=Gs(),{data:f}=Ne(),{hasPermission:v}=X.usePermissions(),[,y]=X.useSidebarActivePanel(),p=g.useMemo(()=>x.find(f,{key:s.pageType}),[f,s.pageType]),S=g.useMemo(()=>{const b=x.get(s,"slug",""),B=e?Je(e):"",O=B?b.replace(B,""):b;return O||"/"},[s,e]),E=!v(ge.EDIT_PAGE)&&!v(ge.DELETE_PAGE)&&!v(ge.UNPUBLISH_PAGE),G=g.useMemo(()=>!!s.isTemplate,[s.isTemplate]),w=g.useMemo(()=>!!(p!=null&&p.hasSlug),[p==null?void 0:p.hasSlug]),_=g.useCallback(()=>{y("outline"),h(x.get(s,"id"),a)},[h,a,s,y]);return t.jsxs("div",{onClick:_,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:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(N.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):p!=null&&p.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:p.icon}}):p!=null&&p.hasSlug?t.jsx(N.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(N.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:s.name}),p!=null&&p.hasSlug?t.jsxs(c.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:[S,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[x.endsWith(S,"/")?`${p==null?void 0:p.dynamicSlug}`:`/${p==null?void 0:p.dynamicSlug}`,s.dynamicSlugCustom]})]}):t.jsx(c.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:p==null?void 0:p.name}),G&&t.jsx(c.Badge,{variant:"outline",className:"ml-2 text-xs py-0 font-normal text-blue-500 border border-blue-200 bg-blue-50",children:"Template"})]}),t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(Tr,{currentEditor:s.currentEditor}),!E&&t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:b=>b.stopPropagation(),children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4 hover:stroke-[3]"})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm",children:[v(ge.ADD_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),d(s)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),v(ge.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),l({...s,global:!(p!=null&&p.hasSlug)})},children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),(s==null?void 0:s.online)&&v(ge.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),r(s)},children:[t.jsx(N.Power,{className:"size-3"}),Q.UNPUBLISH]}),v(ge.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),i(s)},children:[t.jsx(N.Trash,{className:"size-3"}),Q.DELETE]}),v(ge.MARK_AS_TEMPLATE)&&w&&t.jsx(t.Fragment,{children:G?t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),u(s)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),Q.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:b=>{b.stopPropagation(),o(s)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),Q.MARK_AS_TEMPLATE]})})]})]})]})]})},Ir=({close:e,isOpen:s})=>{const[,n]=g.useState([]),[a,r]=g.useState(null),[i,l]=g.useState(""),[o,u]=g.useState(null),[d,h]=g.useState(null),[f,v]=g.useState(null),[y,p]=g.useState(null),[S,E]=g.useState(null),{data:G,isFetching:w,refetch:_}=Vt(),[b,B]=g.useState(""),{hasPermission:O}=X.usePermissions(),[te,se]=Pe(),U=te.get("page"),{data:L}=Ne(),H=g.useCallback(k=>{var V;return(V=x.find(L,{key:k}))==null?void 0:V.hasSlug},[L]);g.useEffect(()=>{s&&_()},[s,_]),g.useEffect(()=>{if(!x.isEmpty(b))return;const k=sessionStorage.getItem("pageTypeFilter")||"all";!x.isEmpty(L)&&k&&(x.find(L,{key:k})?B(k):B("all"))},[L,b]);const ee=k=>{B(k),sessionStorage.setItem("pageTypeFilter",k)},ae=g.useCallback(k=>{const ve=new URLSearchParams(window.location.search).get("lang"),we=new URLSearchParams({page:k});ve&&we.set("lang",ve),window.history.pushState({},"",`?${we.toString()}`),se(we),window.dispatchEvent(new PopStateEvent("popstate")),e()},[se,e]);g.useEffect(()=>{if(U&&!w){const k=x.find(G,{id:U});k&&(k!=null&&k.pageType)?n(V=>[...V,k==null?void 0:k.pageType]):(window.history.replaceState(null,"","/"),se(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[G,U,w,se]);const Z=g.useMemo(()=>{const k=x.compact(x.filter(G,m=>x.isEmpty(i)?!0:x.includes(x.toLower(m==null?void 0:m.name),x.toLower(i))||x.includes(x.toLower(m==null?void 0:m.slug),x.toLower(i))));if(b!=="all")return x.compact(x.filter(k,{pageType:b}));const V=new Map;k.forEach(m=>{V.set(m.id,{...m,children:[]})});const ve=[];V.forEach(m=>{if(m.parent){const C=V.get(m.parent);C?C.children.push(m):ve.push(m)}else ve.push(m)});const we=m=>(m.sort((C,M)=>C.name.localeCompare(M.name)),m.forEach(C=>{C.children&&C.children.length>0&&we(C.children)}),m);we(ve);const Be=x.filter(ve,m=>H(m.pageType)).sort((m,C)=>m.name.localeCompare(C.name)),j=x.filter(ve,m=>!H(m.pageType));return x.compact([...Be,...j])},[G,H,i,b]);return t.jsxs("div",{className:"flex flex-col justify-between h-full",children:[t.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[t.jsxs("div",{className:"relative flex item-center gap-x-4",children:[t.jsx(N.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:i,onChange:k=>l(k.target.value)}),!x.isEmpty(b)&&t.jsxs(c.Select,{value:b,onValueChange:ee,children:[t.jsx(c.SelectTrigger,{className:`${b==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} min-w-[120px] h-max p-0 py-1 pl-2 pr-1 top-1.5 -mt-px absolute text-gray-600 right-1.5 w-max text-xs whitespace-nowrap ring-0 focus:ring-0 shadow-none`,children:t.jsx(c.SelectValue,{placeholder:"Select page type"})}),t.jsxs(c.SelectContent,{align:"end",children:[t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!x.isEmpty(x.filter(L,k=>k.hasSlug))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Pages"}),x.map([...x.filter(L,k=>k.hasSlug)].sort((k,V)=>x.get(k,"name","").localeCompare(x.get(V,"name",""))),k=>t.jsx(c.SelectItem,{value:x.get(k,"key"),children:x.get(k,"name")},x.get(k,"key")))]}),!x.isEmpty(x.filter(L,k=>!k.hasSlug))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Partials"}),x.map([...x.filter(L,k=>!k.hasSlug)].sort((k,V)=>x.get(k,"name","").localeCompare(x.get(V,"name",""))),k=>t.jsx(c.SelectItem,{value:x.get(k,"key"),children:x.get(k,"name")},x.get(k,"key")))]})]})]})]}),w?t.jsx("div",{className:"space-y-2",children:x.map([...Array(5).keys()],k=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},k))}):x.isEmpty(Z)?t.jsxs("div",{className:"h-[70vh] flex flex-col gap-y-1 items-center justify-center text-slate-500 text-sm font-medium",children:[t.jsx(N.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"text-sm text-slate-700 space-y-2 h-[70vh] overflow-y-auto",children:x.map(Z,k=>t.jsx(wn,{item:k,currentPage:U,close:e,setUnpublishPage:h,setDeletePage:u,setAddEditPage:v,setMarkAsTemplate:p,setUnmarkAsTemplate:E,setDuplicatePage:r,level:0},`page-item-${k.id}`))})]}),O(ge.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex text-sm gap-x-2",onClick:()=>{v({slug:"",name:"",pageType:b==="all"?"page":b})},children:[t.jsx(N.Plus,{className:"w-4 h-4"})," Add New"]}),f&&t.jsx(Er,{closePanel:e,editPage:ae,addEditPage:f,setAddEditPage:v}),o&&t.jsx(bn,{page:o,onClose:()=>u(null)}),d&&t.jsx(Bs,{page:d,onClose:()=>h(null)}),y&&t.jsx(Ar,{page:y,onClose:()=>p(null)}),S&&t.jsx(Cr,{page:S,onClose:()=>E(null)}),a&&t.jsx(wr,{page:a,onClose:()=>r(null)})]})},wn=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const f=!x.isEmpty(e==null?void 0:e.children);return t.jsxs("div",{className:"border-0",children:[t.jsx(Pr,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d}),f&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:x.map(x.get(e,"children",[]),v=>t.jsx(wn,{item:v,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:h+1},v.id||`child-${h}-${v.key}`))})]},e.id||`level-${h}-${e.key}`)},_r=()=>{const e=qe("logo",null);return e?t.jsx("div",{className:"w-full max-h-9 overflow-hidden pr-2",children:g.createElement(e,{})}):null},kr=()=>{const[e]=Pe(),s=e.get("page"),{data:n,isFetching:a}=Ie(),[r,i]=g.useState(!1),{savePage:l}=X.useSavePage(),o=!!s&&!x.isEmpty(n),u=!s||!a&&x.isEmpty(n)||r;return t.jsxs(t.Fragment,{children:[t.jsxs(c.Button,{variant:"secondary",className:"flex items-center w-full space-x-2 py-1",onClick:()=>{l(),i(!0)},children:[t.jsx("div",{children:t.jsx(N.Logs,{className:"h-4 w-4"})}),t.jsxs("span",{className:"truncate leading-tight flex items-center max-w-[200px]",children:[t.jsx("span",{className:"text-slate-600 pr-1 font-light",children:"Editing:"}),a?t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-slate-400 ml-2"}):x.startCase(x.get(n,"name"))??""]})]},"template-viewer"),t.jsx(c.Sheet,{open:u,onOpenChange:d=>!d&&o&&i(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`!max-w-screen-md z-50 border-border w-full ${o?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:"mb-3",children:[t.jsxs(c.SheetTitle,{className:"text-sm flex items-center gap-2 font-semibold",children:[t.jsx("div",{className:"p-2 rounded-md bg-primary text-primary-foreground",children:t.jsx(N.File,{className:"w-6 h-6"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(Ir,{isOpen:u,close:()=>i(!1)})})]})})]})},Dr=()=>{const{fallbackLang:e,languages:s,selectedLang:n,setSelectedLang:a}=X.useLanguages(),r=x.isEmpty(n)?e:n,[,i]=Pe();g.useEffect(()=>{const p=new URLSearchParams(window.location.search),S=p.get("lang");S&&(s.includes(S)?a(S):(p.delete("lang"),i(p),a("")))},[s,i,a]);const[l,o]=g.useState(null),{data:u}=Ie(),{data:d}=We(),{data:h,isFetching:f}=et(),v=g.useMemo(()=>{const p=x.compact(x.map(x.get(d,"languages"),S=>{const E=x.find(h,{lang:S});return{key:S,value:x.get(Le,S,S),isLangPageAdded:!!E}})).filter(Boolean);return[{key:e,value:x.get(Le,e),isLangPageAdded:!0},...p]},[e,h,d]),y=p=>{a(p);const S=new URLSearchParams(window.location.search);p===e?S.delete("lang"):S.set("lang",p);const E=S.toString(),G=`${window.location.pathname}${E?`?${E}`:""}`;window.history.pushState({},"",G),i(S),window.dispatchEvent(new PopStateEvent("popstate"))};return x.isEmpty(s)||f?null:t.jsxs(t.Fragment,{children:[t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Languages,{className:"w-4 h-4"}),x.get(Le,r,r),t.jsx(N.ChevronDown,{className:"w-4 h-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"border-border space-y-1",children:[x.map(v.filter(p=>p.isLangPageAdded),p=>t.jsxs(c.DropdownMenuItem,{className:X.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",p.key===r&&"!bg-gray-200 text-gray-700"),onClick:()=>y(p.key),children:[t.jsx("div",{className:"text-slate-600",children:p.value}),p.key===e&&t.jsxs("small",{className:"text-[9px] flex items-center gap-x-1 text-orange-500 leading-none",children:[t.jsx(N.Star,{fill:"orange",className:"w-2 h-2"}),"Primary"]})]},p.value)),!x.isEmpty(v.filter(p=>!p.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{o({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:[t.jsx(N.Plus,{className:"w-3 h-3 mr-1"})," Add Langauge"]})]})]})]}),l&&t.jsx(En,{languages:s,langProps:l,onClose:()=>o(null)})]})};function Lr(){return t.jsxs("div",{className:"flex relative z-10 items-center justify-end gap-1",children:[t.jsx(_r,{}),t.jsx(kr,{}),t.jsx(Dr,{})]})}function Br(e){const s=ne(),n=$();return D.useQuery({queryKey:[q,"revisions",e],queryFn:async()=>await n(s,{action:I.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Gr=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>await s(e,{action:I.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,"revisions"]})}})},Mr=()=>{const e=ne(),s=$(),n=D.useQueryClient();return D.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:I.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[q,"revisions"]})}})};function Ur(){const{data:e}=Ie(),{saveState:s}=X.useSavePage(),[n]=Ps();return e?t.jsx("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50 bg-primary/5 mb-4",children:t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:t.jsx("span",{className:"font-bold",children:"Currently editing"})})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:!x.isEmpty(n.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",$t.formatDistanceToNow(new Date(n.lastSaved),{addSuffix:!0})]})}),t.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(N.Edit,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]}),s==="UNSAVED"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(N.Save,{className:"h-3 w-3"}),t.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function Rr(){const[e,s]=ye.useState(!1),[n,a]=ye.useState(null),[r,i]=ye.useState(!1),[l,o]=ye.useState(!1),{data:u}=Ie(),{data:d,isFetching:h,error:f,refetch:v}=Br(u==null?void 0:u.id),{mutate:y,isPending:p}=Gr(),{mutate:S,isPending:E}=Mr(),G=D.useQueryClient(),w=O=>{n&&S({revisionId:n.uid,discardCurrent:O},{onSuccess:()=>{i(!1),a(null),G.invalidateQueries({queryKey:[q,I.GET_DRAFT_PAGE]})}})},_=O=>{a(O),i(!0)},b=O=>{a(O),o(!0)},B=()=>{n&&y(n.uid,{onSuccess:()=>{o(!1),a(null)}})};return g.useEffect(()=>{e&&v()},[e,v]),t.jsxs(t.Fragment,{children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:e,onOpenChange:s,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(N.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(c.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(c.SheetHeader,{className:"pb-2",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(N.History,{className:"h-5 w-5"}),"Revision History"]}),(u==null?void 0:u.createdAt)&&t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Page created on"," ",$t.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(c.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:h?t.jsx(Or,{}):f?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 space-y-2",children:[t.jsx(Ur,{}),d==null?void 0:d.map(O=>t.jsx(Fr,{revision:O,isLatest:O.uid==="current",onRestore:()=>_(O),onDelete:()=>b(O)},O.uid))]})})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(zr,{open:r,onOpenChange:i,revision:n,onRestore:w,isRestoring:E}),t.jsx($r,{open:l,onOpenChange:o,revision:n,onDelete:B,isDeleting:p})]})}function Or(){return t.jsx("div",{className:"space-y-2 mt-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(c.Skeleton,{className:"h-4 w-3/4"}),t.jsx(c.Skeleton,{className:"h-3 w-1/2"}),t.jsx(c.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Fr({revision:e,isLatest:s,onRestore:n,onDelete:a}){const{data:r}=tt(e.currentEditor),i=(r==null?void 0:r.name)||"Unknown";return t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:[e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"font-bold",children:i}),s&&t.jsxs("span",{className:"ml-2 flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:[t.jsxs("span",{className:"mr-1 relative flex h-2 w-2",children:[t.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]}),"Live"]})]})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:t.jsx("span",{children:$t.format(e.createdAt,"MMM d, h:mm a")})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:e.type==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(N.ArrowUpRight,{className:"h-3 w-3"}),t.jsx("span",{children:"Published"})]}):t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(N.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(ke,{permissions:[ge.RESTORE_REVISION,ge.DELETE_REVISION],children:t.jsx(qr,{revision:e,onRestore:n,onDelete:a})})]})}function qr({revision:e,onRestore:s,onDelete:n}){return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(N.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(ke,{permission:ge.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(ke,{permission:ge.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(c.DropdownMenuSeparator,{}),t.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(N.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function zr({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=tt((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Restore Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",$t.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function $r({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=tt((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",$t.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Hr=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_CHANGES],queryFn:async()=>s(e,{action:I.GET_CHANGES})})},Vr=({currentEditor:e})=>{const{data:s}=tt(e);return s==null?void 0:s.name};function Kr({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=g.useState([]),{data:r,isFetching:i}=Hr(),{data:l}=Ne(),o=g.useCallback(b=>{var B;return(B=x.find(l,{key:b}))==null?void 0:B.hasSlug},[l]),u=g.useMemo(()=>x.filter(l,b=>!o(b.key)).map(b=>b.key),[o,l]),d=g.useMemo(()=>x.filter(r,b=>!u.includes(b.pageType)),[r,u]),h=g.useMemo(()=>x.filter(r,b=>u.includes(b.pageType)),[r,u]),f=g.useMemo(()=>x.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:v,isPending:y}=Ds();g.useEffect(()=>{const b=x.map(x.filter(r,{online:!0}),"id");f&&b.push(f==null?void 0:f.id),a(b)},[r,f]);const p=n.length===(r==null?void 0:r.length),S=b=>{a(B=>x.includes(B,b)?x.filter(B,O=>O!==b):x.concat(B,b))},E=()=>{a(p?[]:x.map(r,"id"))},G=()=>{v({ids:x.uniq(n)},{onSuccess:()=>{s(),Jt("CENTER_CENTER")}})},w=b=>{if(b==="theme")return"Theme";const B=x.find(l,{key:b});return B?B==null?void 0:B.name:b},_=g.useMemo(()=>{const b=[{label:"Updated",top:"pt-2"},...x.orderBy(x.filter(d,{online:!0}),"pageType"),...x.orderBy(x.filter(h,{online:!0}),"pageType")].filter(te=>te.pageType!=="theme"),B=[{label:"Offline",top:"pt-6"},...x.orderBy(x.filter(d,{online:!1}),"pageType"),...x.orderBy(x.filter(h,{online:!1}),"pageType")],O=f?[{label:"Theme",top:"pt-6"},f]:[];return[...b,...O,...B]},[d,h,f]);return t.jsx(c.Dialog,{open:e,onOpenChange:y?()=>{}:s,children:t.jsxs(c.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),t.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:i?t.jsxs("div",{className:"px-1 space-y-2",children:[t.jsx("div",{className:"w-full h-6 mt-2 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"})]}):t.jsxs("table",{className:"w-full text-xs text-left text-gray-500 rtl:text-right dark:text-gray-400",children:[t.jsx("thead",{className:"text-gray-700 border-b bg-gray-50 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"px-6 py-3 flex items-center gap-x-2 w-[1 50px]",children:[t.jsx("input",{checked:p,onClick:b=>{b.stopPropagation(),E()},type:"checkbox",className:"mt-1 rounded cursor-pointer focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Language"}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Type"}),t.jsx("th",{scope:"col",className:"px-4 py-3 w-[150px] text-right",children:"Status"})]})}),t.jsx("tbody",{children:x.map(_,b=>b.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${b.top}`,children:[t.jsx("div",{className:"absolute inset-0 flex items-center left-6",children:t.jsx("div",{className:"w-full order-gray-300"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"pr-2 bg-gray-50",children:b.label})})]})},"separator"):t.jsxs("tr",{className:"border-b group hover:bg-gray-50 last:border-b-0",children:[t.jsxs("td",{scope:"row",className:"flex items-center px-6 py-2 text-gray-900 whitespace-nowrap dark:text-white gap-x-1",children:[t.jsx("input",{checked:x.includes(n,b==null?void 0:b.id),onClick:B=>{B.stopPropagation(),S(b==null?void 0:b.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",o(b.pageType)?t.jsx(N.File,{className:"w-4 h-4"}):t.jsx(N.GlobeIcon,{className:"w-4 h-4"}),b.name,b.slug&&t.jsxs("span",{className:"text-xs text-gray-500",children:["(",b.slug,")"]}),b.currentEditor&&t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsxs("span",{className:"flex text-xs font-bold text-gray-500",children:[" ","-"," ",t.jsx(Vr,{currentEditor:b.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:b.lang}),t.jsx("td",{className:"px-2",children:w(b==null?void 0:b.pageType)}),t.jsx("td",{className:"px-4 text-right",children:x.first(b.changes)||""})]},b==null?void 0:b.id))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10",children:[t.jsx(c.Button,{disabled:y,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:y||i||x.isEmpty(r),onClick:G,children:y?"Publishing...":"Publish"})]})]})})}const Wr=()=>{const e=$(),s=ne();return D.useQuery({queryKey:[I.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_DATA,data:{draft:!0}})})};function Qr({onClose:e}){const{data:s,isFetching:n}=Wr(),{mutateAsync:a,isPending:r}=La(),i=qe("settingComponent",null),l=x.debounce(async o=>(await a({data:o}),!0),300);return i?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:g.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function Nn({children:e,content:s}){return t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:e}),t.jsx(c.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const Yr=()=>{const{selectedLang:e,fallbackLang:s}=X.useLanguages(),n=qe("getPreviewUrl",async f=>f),[a,r]=g.useState(""),{data:i}=Ie(),{data:l}=et(),{data:o}=Ne(),u=g.useMemo(()=>{var f;return(f=l==null?void 0:l.find(v=>(v==null?void 0:v.lang)===e))==null?void 0:f.slug},[e,l]),d=g.useCallback(f=>{var v;return(v=x.find(o,{key:f}))==null?void 0:v.hasSlug},[o]),h=e===s?"":e;return g.useEffect(()=>{(async()=>{if(typeof n=="function"){const f=!d(i==null?void 0:i.pageType),v=await n(f?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(v)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,h]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Eye,{className:"w-4 h-4"})," ",Q.PREVIEW]})})})},Xr=()=>{const[e,s]=X.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(Nn,{content:Q.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(N.Palette,{className:"w-4 h-4"})})}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})},Zr=()=>{const[e,s]=g.useState(!1),{isLocked:n}=Kt(),{savePage:a,saveState:r}=X.useSavePage();g.useEffect(()=>{const h=f=>{r==="UNSAVED"&&(f.preventDefault(),f.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=g.useCallback(async()=>{s(!0),await a(!1)},[a]);g.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=g.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:o,buttonClass:u,tooltipContent:d}=g.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:Q.SAVEDRAFT,buttonIcon:t.jsx(N.Save,{className:"w-4 h-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:Q.SAVING,buttonIcon:t.jsx(N.Loader,{className:"w-4 h-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:Q.SAVED,buttonIcon:t.jsx(N.CheckCircle,{className:"w-4 h-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[o," ",d]})},Jr=()=>{const[e,s]=g.useState(!1),[n,a]=g.useState(!1),[r,i]=g.useState(null),{data:l}=Ie(),{mutate:o,isPending:u}=Ds(),{buttonText:d,buttonClassName:h,isPublished:f}=g.useMemo(()=>{const y=l&&(l==null?void 0:l.online);return{buttonClassName:y?"hover:bg-green-600 bg-green-500":"",isPublished:y,buttonText:y?Q.PUBLISHED:Q.PUBLISH}},[l]),v=async()=>{o({ids:[l==null?void 0:l.id]},{onSuccess:()=>Jt("TOP_RIGHT")})};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:v,disabled:u||!(l!=null&&l.id),className:`relative overflow-hidden transition-all duration-300 ease-in-out text-white flex items-center gap-1 rounded-r-none ${h}`,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${n?"-translate-y-10":""}`,children:f?t.jsx(N.Send,{className:"w-4 h-4"}):t.jsx(N.Rocket,{className:"w-4 h-4"})}),t.jsx("span",{className:`absolute inset-0 flex items-center left-3 transition-transform duration-300 ease-in-out ${n?"":"translate-y-10"}`,children:f?t.jsx(N.Rocket,{className:"w-4 h-4"}):t.jsx(N.Send,{className:"w-4 h-4"})}),t.jsx("span",{children:d})]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:u||!(l!=null&&l.id),className:`px-2 text-white border-l border-white/50 rounded-l-none ${h}`,children:t.jsx(N.ChevronDown,{className:"w-4 h-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-36",children:[!f&&t.jsxs(c.DropdownMenuItem,{disabled:u,className:"text-xs cursor-pointer",onClick:()=>o({ids:[l==null?void 0:l.id]},{onSuccess:()=>Jt("TOP_RIGHT")}),children:[Q.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>s(!0),className:"text-xs cursor-pointer",children:[Q.OPEN," publish menu"]}),f&&t.jsxs(c.DropdownMenuItem,{onClick:()=>i(l),className:"text-xs cursor-pointer",children:[Q.UNPUBLISH," page"]})]})]})]}),t.jsx(Kr,{showModal:e,onClose:()=>s(!1)}),r&&t.jsx(Bs,{page:r,onClose:()=>i(null)})]})},ei=()=>{const e=qe("settingComponent",null),[s,n]=g.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{content:Q.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(N.Settings,{className:"w-4 h-4"})})}),s&&t.jsx(Qr,{onClose:()=>n(!1)}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]}):null},ti=()=>{const{data:e}=Ie(),[s,n]=g.useState(""),a=e&&(e==null?void 0:e.online),{data:r}=Ne(),i=qe("getLiveUrl",async v=>v),l=g.useCallback(v=>{var y;return(y=x.find(r,{key:v}))==null?void 0:y.hasSlug},[r]),{selectedLang:o,fallbackLang:u}=X.useLanguages(),d=e==null?void 0:e.id,h=e==null?void 0:e.slug,f=o===u?"":o;return g.useEffect(()=>{(async()=>{if(typeof i=="function"){const v=!l(e==null?void 0:e.pageType),y=await i(v?`${f===""?"":f+"/"}${d}`:h||"");n(y)}else n("")})()},[i,e==null?void 0:e.pageType,l,d,h,f]),t.jsxs(c.Button,{onClick:()=>a&&window.open(s,"_blank"),disabled:!a,variant:"ghost",size:"sm",className:"flex items-center gap-1",children:[t.jsx(N.ExternalLink,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:Q.OPEN})]})};function si(){const{isLocked:e}=Kt(),[s]=Pe(),n=s.get("lang"),a=xn(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Rr,{}),t.jsx(ke,{permission:ge.EDIT_THEME,children:t.jsx(Xr,{})}),t.jsx(ke,{permission:ge.EDIT_SETTINGS,children:t.jsx(ei,{})}),t.jsx(Yr,{}),t.jsx(ke,{permission:ge.SAVE_PAGE,children:t.jsx(Zr,{})}),t.jsx(ke,{permission:ge.PUBLISH_PAGE,children:t.jsx(Jr,{})}),t.jsx(ti,{})]})}const ni=()=>t.jsxs("div",{className:"flex px-2 h-full items-center justify-between w-full",children:[t.jsx(Lr,{}),t.jsx(si,{})]}),ai=()=>{const e=ne(),{aiContext:s}=Ts(),n=$();return g.useCallback(async(a,r,i,l)=>n(e,{action:I.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},ri=(e,s)=>s.map(n=>{if(x.has(e,n._type)){const a=dn.getDefaultBlockProps(n._type);return{...a,...x.pick(n,[...x.keys(a),"_type","_id","_name","_parent","_bindings"]),...x.pickBy(n,(r,i)=>x.endsWith(i,"_attrs")),...n}}return n}),ii=e=>{const s=dn.useRegisteredChaiBlocks();return g.useMemo(()=>{if(!e||x.isEmpty(e))return{blocks:[]};const n=x.filter(e,a=>!x.includes(a==null?void 0:a._type,"@chai/"));return{blocks:ri(s,n)}},[e,s])},Qs={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=x.get(a,"html",""),i=x.get(a,"blocks",[]);return x.isArray(i)?i:X.getBlocksFromHTML(r)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(r=>({...r}))}catch(a){return console.error(a),[]}}},li=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{X.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>Qs.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>Qs.getUILibraryBlock(i,s,e)})}),a}})},An=()=>{const e=Cs(),s=$(),{user:n}=Fe(),a=n==null?void 0:n.id;return D.useQuery({queryKey:[q,"permissions",a],queryFn:()=>s(e,{action:I.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},oi=()=>{const e=ne(),s=$(),{setCurrentEditor:n}=Kt(),[,a]=Ps();return{onSave:async({page:i,blocks:l})=>{try{const o=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return o.code==="PAGE_LOCKED"?(n(o.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),o)}catch(o){return console.error(o),new Error("Failed to save blocks")}}}},ci=()=>{const{data:e}=Vt(),s=ne(),n=$();return{getPartialBlocks:g.useCallback(async()=>{const a={};for(const r of e??[])x.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:x.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:g.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return x.filter(r.blocks,i=>x.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},Ys=Xt.z.object({email:Xt.z.string().email({message:"Please enter a valid email address"}),password:Xt.z.string().min(6,{message:"Password must be at least 6 characters"})}),ui=()=>{const{setUser:e,logout:s}=Fe(),n=Cs(),[a,r]=g.useState(""),[i,l]=g.useState(""),[o,u]=g.useState({}),[d,h]=g.useState(!1),[f,v]=g.useState(""),y=D.useMutation({mutationFn:async E=>{v("");const G=await mn(n,{action:"LOGIN",data:E});if(!G.ok){const _=await G.json();throw new Error(_.error||"Login failed")}const w=await G.json();if(x.has(w,"id")&&x.has(w,"email")&&x.has(w,"accessToken")&&x.has(w,"refreshToken"))e(w);else throw s(),new Error("Something went wrong. Please try again.");return w},onSuccess:()=>{u({}),v("")},onError:E=>{u({email:" ",password:" "}),v(E.message||"Something went wrong")}}),p=async E=>{E.preventDefault(),u({});const G={email:a,password:i};try{const w=Ys.parse(G);y.mutate(w)}catch(w){if(w instanceof Xt.z.ZodError){const _=w.errors.reduce((b,B)=>{const O=B.path[0];return b[O]=B.message,b},{});u(_)}}},S=Ys.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:E=>r(E.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:E=>l(E.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:f})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!S||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let xs=ui;const di=()=>g.useMemo(()=>xs,[xs]),hi=e=>{xs=e},mi=()=>{const e=di();return t.jsx(g.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},fi=({isActive:e,show:s})=>{const{data:n}=We();return!x.has(n,"languages")||!x.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},Cn="lang",gi={id:Cn,label:"Languages",position:"top",panel:hr,button:fi,view:"modal",width:400};function Ue({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=ye.useState(!1),[l,o]=ye.useState([]),[u,d]=ye.useState(e);ye.useEffect(()=>{r||o([]),d(e)},[e,r]);const h=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",f=ye.useCallback(p=>{const S=E=>n==="value"?E==="value"||E==="object":n==="array"?E==="array":E===n;p.type==="object"?(o(E=>[...E,p.key]),d(p.value)):S(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),v=ye.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);o(p),d(p.reduce((S,E)=>S[E],e))}},[l,e]),y=ye.useMemo(()=>Object.entries(u).map(([p,S])=>({key:p,value:S,type:h(S)})).filter(p=>n==="value"?p.type==="value"||p.type==="object":n==="array"?p.type==="array"||p.type==="object":n==="object"?p.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(N.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:p=>{try{p.preventDefault();const S=p.currentTarget;S.scrollTop+=p.deltaY}catch{p.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:v,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(p=>t.jsxs(c.CommandItem,{onSelect:()=>f(p),className:"flex items-center justify-between",children:[t.jsx("span",{children:p.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&p.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:S=>{S.stopPropagation(),s([...l,p.key].join(".")),i(!1)},children:"Select"}),(p.type==="object"||p.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(N.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const pi=()=>{const e=Ht(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:I.UPLOAD_ASSET,data:{file:a,folderId:r,name:i,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[q,I.GET_ASSETS]}),z.toast.success("Asset uploaded successfully")},onError:()=>{z.toast.error("Failed to upload asset")}})},xi=()=>{const e=Ht(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[q,I.GET_ASSETS]}),z.toast.success("Asset deleted successfully")},onError:()=>{z.toast.error("Failed to delete asset")}})},yi=()=>{const e=Ht(),s=D.useQueryClient(),n=$();return D.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[q,I.GET_ASSETS]}),z.toast.success("Asset updated successfully")},onError:()=>{z.toast.error("Failed to update asset")}})},vi=(e={})=>{const s=Ht(),n=$(),{search:a,page:r=1,limit:i=30}=e;return D.useQuery({queryKey:[q,I.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:I.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},ji=e=>{const s=Ht(),n=$();return D.useQuery({queryKey:[q,I.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:I.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function bi(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function Xs(e){if(!e)return"N/A";const s=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(s)}function Zs(e,s){let n=e,a=s==null?void 0:s.description;return(!a||typeof a!="string")&&(a=""),(!n||typeof n!="string")&&(n=""),n!==a}const Ei=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var f,v,y;const{data:i,isLoading:l,isError:o}=ji(e||""),[u,d]=g.useState(""),h=async(p,S)=>{try{await navigator.clipboard.writeText(p),z.toast.success(`${S} copied to clipboard`)}catch(E){z.toast.error(`Failed to copy ${S}`,{description:E==null?void 0:E.message})}};return g.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}):o||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(N.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(N.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(N.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(N.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((f=i.metadata)==null?void 0:f.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((v=i.metadata)==null?void 0:v.format)||i.type,capitalize:!0},{label:"Size",value:bi(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:Xs(i.createdAt)},{label:"Updated",value:Xs(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(p.value,p.label),children:t.jsx(N.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,S)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},S))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>d(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!Zs(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Zs(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},Si=g.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function wi(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}const Ni=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,o]=g.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});g.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=g.useCallback(async y=>new Promise((p,S)=>{const E=y[0],G=new FileReader;G.readAsDataURL(E),G.onload=async()=>{a({file:G.result,folderId:void 0,name:E.name,optimize:l},{onSuccess:w=>{i&&i(w),p(w)},onError:w=>{S(w)}})},G.onerror=w=>S(w)}),[a,l,i]),{getRootProps:h,getInputProps:f,isDragActive:v}=Ea.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},maxSize:n*1024*1024,disabled:e||r});return t.jsx("div",{className:`flex flex-col items-center justify-center w-full border-2 hover:border-black/50 border-dashed p-0 rounded-lg border-slate-300 py-2 h-[60px] ${u?"opacity-90 bg-gray-100 pointer-events-none":"hover:border-black/50 bg-gray-100 hover:bg-gray-100"}`,children:t.jsxs("div",{...h(),className:X.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",v?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...f()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(N.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(N.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange:y=>{o(y)},onClick:y=>{y.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(N.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Tn({close:e,onSelect:s,mode:n="image",assetId:a}){const l=g.useMemo(()=>[n],[n]),[o,u]=g.useState(null),[d,h]=g.useState(null),[f,v]=g.useState(null),[y,p]=g.useState({show:!1,file:""}),[S,E]=g.useState(!1),[G,w]=g.useState(a?"details":"grid"),[_,b]=g.useState(""),[B,O]=g.useState(""),[te,se]=g.useState(1),[U]=g.useState(30),[L,H]=g.useState([]);g.useEffect(()=>{a&&(u(a),w("details"))},[a]),g.useEffect(()=>{const P=setTimeout(()=>{b(B),se(1)},300);return()=>clearTimeout(P)},[B]);const{data:ee,isLoading:ae}=vi({search:_.toLowerCase().trim(),page:te,limit:U}),Z=(ee==null?void 0:ee.assets)||[],k=(ee==null?void 0:ee.total)||0,V=Math.ceil(k/U),ve=te<V,we=te>1,Be=(Z==null?void 0:Z.length)>0,{mutate:j}=xi(),{mutate:m,isPending:C}=pi(),{mutate:M,isPending:R}=yi(),T=g.useCallback(P=>{P>=1&&P<=V&&se(P)},[V]),Y=g.useCallback(()=>{ve&&T(te+1)},[te,ve,T]),F=g.useCallback(()=>{we&&T(te-1)},[te,we,T]),J=P=>{O(P.target.value)},ce=g.useCallback(P=>{H(ie=>x.find(ie,{id:P.id})?[]:[P])},[!1]),pe=g.useCallback(()=>{H([])},[]),ue=P=>{(P==null?void 0:P.length)!==0&&(s(x.pick(x.first(P||L),["id","url","width","height","description"])),e())},xe=async P=>{h(P)},be=async()=>{d&&(v(d==null?void 0:d.id),await j(d.id,{onSuccess:()=>{v(null),h(null)},onError:()=>{v(null)}}),h(null))},re=P=>{u(P.id),w("details")},Ee=async(P,ie)=>{try{const A=localStorage.getItem("chai_optimize_images")!=="false";ie?(await m({file:P,folderId:void 0,name:y.name||"",optimize:A}),p({show:!1,file:""})):(await M({id:y.id||"",file:P}),p({show:!1,file:""}))}catch(A){console.error("Error saving edited image:",A)}},Ae=g.useCallback(P=>{H([P])},[]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"max-w-[1232px] max-h-[1232px] w-[80vw] h-[80vh] space-y-4 flex flex-col",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),G==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Ni,{maxFileSize:10,allowedTypes:l,uploadAsset:m,isUpdatingAsset:R,isUploadingAsset:C,onUploaded:Ae}),t.jsxs("div",{className:"border p-2 rounded-lg flex-1 flex flex-col gap-y-3 overflow-hidden relative",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2 ",children:[t.jsx(N.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${B.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:J,value:B,className:"pl-8"})]}),L.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[L.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>pe(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>ue(L),disabled:L.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:ae?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"})]}):!ae&&!Be?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full border rounded-lg",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(N.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:_.length>0?"No assets found for your search: "+_:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:Z==null?void 0:Z.map(P=>t.jsxs("div",{className:X.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",L.some(ie=>ie.id===P.id)?"border-blue-500":"hover:border-black/90",f&&(d==null?void 0:d.id)===P.id?"opacity-50 pointer-events-none":"",f===P.id?"opacity-50 pointer-events-none":""),onClick:()=>ce(P),onDoubleClick:()=>ue([P]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[f===P.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,P.type==="image"?t.jsx("img",{src:`${P.thumbnailUrl||"/placeholder.svg"}?v=${(P==null?void 0:P.updatedAt)||P.createdAt}`,alt:P.name,className:`object-contain w-full h-full min-h-[80px] ${L.some(ie=>ie.id===P.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(N.Film,{className:"h-12 w-12 text-muted-foreground"}),P.thumbnailUrl&&t.jsx("img",{src:`${P.thumbnailUrl||"/placeholder.svg"}?v=${(P==null?void 0:P.updatedAt)||P.createdAt}`,alt:P.name,className:"absolute inset-0 object-cover w-full h-full"})]})]}),t.jsxs("div",{className:"py-1 px-2 flex items-end justify-between bg-white border-t-[1px] border-black/10",children:[t.jsx("div",{className:"text-xs truncate leading-tight",title:P.name,children:P.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:wi((P==null?void 0:P.size)||0)})})]}),!L.some(ie=>ie.id===P.id)&&t.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),re(P)},children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),navigator.clipboard.writeText(P.url),z.toast.success("Asset URL copied to clipboard")},children:t.jsx(N.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),p({id:P.id,show:!0,file:P.url,name:P.name})},children:t.jsx(N.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),xe(P)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),L.some(ie=>ie.id===P.id)&&t.jsx("div",{className:"absolute top-1 right-1 border border-white h-max rounded-full bg-blue-500 p-1",children:t.jsx(N.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},P.id))})}),V>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:F,disabled:!we,children:"Previous"}),Array.from({length:Math.min(5,V)},(P,ie)=>{const A=ie+1;return t.jsx(c.Button,{variant:te===A?"default":"outline",size:"sm",onClick:()=>T(A),children:A},A)}),V>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(c.Button,{variant:te===V?"default":"outline",size:"sm",onClick:()=>T(V),children:V})]}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:Y,disabled:!ve,children:"Next"})]})})]})]}):t.jsx(Ei,{assetId:o||a||"",onBack:()=>{w("grid"),u(null)},onEdit:P=>{p({id:P.id,show:!0,file:P.url,name:P.name})},onSave:async P=>{if(o){E(!0);try{const ie=Z.find(A=>A.id===o);ie&&await M(x.merge(ie,{description:P}))}finally{E(!1)}}},isSaving:S})]}),y.show&&t.jsx(g.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Si,{imageUrl:y.file,onSave:Ee,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),d&&t.jsx(c.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:be,children:"Delete"})]})]})})]})}const Ai=Object.freeze(Object.defineProperty({__proto__:null,default:Tn},Symbol.toStringTag,{value:"Module"})),Pn=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,o]=g.useState(!1),u=()=>{i||o(!0)},d=()=>{o(!1)},h=v=>{const y=Array.isArray(v)?v[0]:v;y!=null&&y.url&&n(x.pick(y,["url","id"])),o(!1)},f=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:f,disabled:i,children:t.jsx(N.Trash2,{className:"h-4 w-4"})}),t.jsx(c.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${i?"opacity-50 cursor-not-allowed":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(c.Dialog,{open:l,onOpenChange:o,children:t.jsxs(c.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(c.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(Tn,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Ci=()=>{const{selectedLang:e}=X.useLanguages(),{data:s,isFetching:n}=et();return{data:g.useMemo(()=>x.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Ti=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg").forEach(o=>o.remove()),a.querySelectorAll("*").forEach(o=>{Array.from(o.attributes).forEach(u=>o.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(o=>`<${o.tagName.toLowerCase()}>${o.innerHTML}</${o.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},Ye=({onComplete:e,field:s})=>{const n=$(),a=ne(),{selectedLang:r,fallbackLang:i}=X.useLanguages(),l=X.useBuilderProp("aiContext",""),{mutate:o,isPending:u}=D.useMutation({mutationFn:async()=>{const d=Ti();return await n(a,{action:I.GENERATE_SEO_FIELD,data:{pageContext:l,dynamic:!1,field:s,lang:r||i,pageContent:d}})},onSuccess:d=>{e({fieldValue:d.field})},onError:d=>{e({fieldValue:null,error:d.message})}});return t.jsx(c.Button,{disabled:u,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>o(),children:u?t.jsx(N.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(N.Sparkle,{className:"text-yellow-500"})})},Pi=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a);let o=!1;if(n>0&&i.length>0){const p=i.charAt(i.length-1);o=!/[\s.,!?;:()[\]{}]/.test(p)&&p!==""}let u=!1;if(l.length>0){const p=l.charAt(0);u=!/[\s.,!?;:()[\]{}]/.test(p)&&p!==""}const d=o?" ":"",h=u?" ":"",f=`{{${s}}}`,v=i+(o?d:"")+f+(u?h:"")+l,y=n+(o?1:0)+f.length;return{value:v,newCursorPos:y}},In=()=>{const{t:e}=X.useTranslation(),{selectedLang:s,fallbackLang:n,languages:a}=X.useLanguages(),[,r]=X.useSidebarActivePanel(),{data:i}=_s(),{data:l,isFetching:o}=Ci(),u=l==null?void 0:l.seo,d=g.useRef(null),[h,f]=g.useState({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",...u}),v=g.useRef({initial:h,updated:h}),y=s.length?s:n,{mutate:p,isPending:S}=ks(),E=S,{hasPermission:G}=X.usePermissions(),w=G(ge.EDIT_SEO);g.useEffect(()=>{!o&&u&&f({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...u})},[o,u]);const _=async()=>{p({id:l==null?void 0:l.id,seo:h},{onSuccess:()=>{v.current.initial=h,v.current.updated=h,r("outline")}})},b=()=>{f({...h,ogTitle:h.title,ogDescription:h.description})},B=()=>{f({...h,searchTitle:h.ogTitle,searchDescription:h.ogDescription})},O=(U,L)=>{const H=document.getElementById(L);if(H){const{value:ee,newCursorPos:ae}=Pi(H,U);d.current={id:L,position:ae},H.tagName.toLowerCase()==="input"?(H.value=ee,f(V=>({...V,[H.name]:ee})),H.focus(),H.setSelectionRange(ae,ae),[0,10,50,100,200].forEach(V=>{setTimeout(()=>{const ve=document.getElementById(L);ve&&(ve.focus(),ve.setSelectionRange(ae,ae))},V)})):(f(k=>({...k,[H.name]:ee})),requestAnimationFrame(()=>{const k=document.getElementById(L);k&&(k.focus(),k.setSelectionRange(ae,ae),setTimeout(()=>{const V=document.getElementById(L);V&&(V.focus(),V.setSelectionRange(ae,ae))},50))}))}},te=U=>{const L={...h,[U.target.name]:U.target.name==="noIndex"||U.target.name==="noFollow"?U.target.checked:U.target.value};f(L),v.current.updated=L},se=U=>L=>{x.isEmpty(L.fieldValue)||te({target:{name:U,value:L.fieldValue}}),L.error&&z.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:L.error})]}))};return t.jsxs("div",{className:"relative h-full flex flex-col",children:[!w&&t.jsx("div",{className:"absolute inset-0 z-10 backdrop-blur-sm flex items-center justify-center",children:t.jsx(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"flex-grow overflow-y-auto no-scrollbar px-2",children:[t.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,"  ",a.length>0&&t.jsxs("span",{className:"font-semibold text-blue-500",children:["(",x.get(Le,y,y),")"]})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Accordion,{type:"multiple",defaultValue:["page"],children:[t.jsxs(c.AccordionItem,{value:"page",children:[t.jsx(c.AccordionTrigger,{className:"font-semibold text-slate-700",children:e("SEO")}),t.jsx(c.AccordionContent,{className:"pt-2",children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(Ye,{onComplete:se("title"),field:"title"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:h.title,onChange:te,disabled:E||!w,placeholder:e("Enter SEO title"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("description"),field:"description"}),w&&t.jsx(Ue,{data:i??{},onSelect:U=>O(U,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:h.description,onChange:te,disabled:E||!w,placeholder:e("Enter SEO description"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:h.canonicalUrl,onChange:te,disabled:E||!w,placeholder:e("Enter Canonical URL"),readOnly:!w})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:h.noIndex,onChange:te,disabled:E||!w,className:"w-4 h-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light text-gray-400 leading-4",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:h.noFollow,onChange:te,disabled:E||!w,className:"w-4 h-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.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.")})]})]})})]}),t.jsxs(c.AccordionItem,{value:"og",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Open Graph")}),t.jsx(c.AccordionContent,{children:t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:b,disabled:!w,children:e("Copy from SEO Settings")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("ogTitle"),field:"ogTitle"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:h.ogTitle,onChange:te,disabled:E||!w,placeholder:e("Enter OG title"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("ogDescription"),field:"ogDescription"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:h.ogDescription,onChange:te,disabled:E||!w,placeholder:e("Enter OG description"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Pn,{assetId:h.ogImageId,assetUrl:h.ogImage,onChange:U=>{const L={...h,ogImage:U.url,ogImageId:U.id};f(L),v.current.updated=L},disabled:E||!w,placeholder:e("Select OG image"),className:"mb-2"})]})]})})]}),t.jsxs(c.AccordionItem,{value:"search",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Search")}),t.jsx(c.AccordionContent,{children:t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:B,disabled:!w,children:e("Copy from OG Settings")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"searchTitle",children:e("Search Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("searchTitle"),field:"searchTitle"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"searchTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"searchTitle",name:"searchTitle",value:h.searchTitle,onChange:te,disabled:E||!w,placeholder:e("Enter search title"),readOnly:!w}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"searchDescription",children:e("Search Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("searchDescription"),field:"searchDescription"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"searchDescription")})]})]}),t.jsx(c.Textarea,{id:"searchDescription",rows:5,name:"searchDescription",value:h.searchDescription,onChange:te,placeholder:e("Enter search description"),disabled:E||!w,readOnly:!w})]})]})]})})]}),t.jsxs(c.AccordionItem,{value:"jsonLD",className:"border-none",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("JSON-LD")}),t.jsx(c.AccordionContent,{children:t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{onComplete:se("jsonLD"),field:"jsonLD"}),w&&t.jsx(Ue,{dataType:"value",data:i??{},onSelect:U=>O(U,"jsonLD")})]})]}),t.jsx(c.Textarea,{id:"jsonLD",name:"jsonLD",rows:6,value:h.jsonLD,onChange:te,placeholder:e("Enter JSON-LD"),disabled:E||!w,readOnly:!w})]})})})]})]})})]}),w&&t.jsx("div",{className:"flex-shrink-0 flex items-center justify-end w-full p-4 bg-background border-t",children:t.jsx(c.Button,{size:"lg",variant:"default",onClick:_,disabled:x.isEqual(v.current.initial,h)||E||!w,children:e(S?"Saving...":"Save")})})]})};In.displayName="SeoPanel";const _n="seo",Ii=({isActive:e,show:s})=>{const{data:n}=Ie(),a=er(n==null?void 0:n.pageType);return!x.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"w-4 h-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},_i={id:_n,label:"SEO",panel:In,button:Ii,position:"top",width:600,view:"modal"},ki="user-info",Di=()=>{const{user:e,logout:s}=Fe(),n=D.useQueryClient(),a=qe("onLogout",x.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(N.User,{className:"w-4 h-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[q]}),x.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},Li={id:ki,label:"User Info",button:Di,position:"bottom"},Bi=()=>{X.registerChaiSidebarPanel(_n,_i),X.registerChaiSidebarPanel(Cn,gi),X.registerChaiSidebarPanel("user-info",Li)};var W={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Js(this.context.count)},getNextContextId(){return Js(this.context.count++)}};function Js(e){const s=String(e),n=s.length-1;return W.context.id+(n?String.fromCharCode(96+n):"")+s}function wt(e){W.context=e}var Gi=(e,s)=>e===s,es=Symbol("solid-proxy"),kn=typeof Proxy=="function",Ms=Symbol("solid-track"),ts={equals:Gi},Dn=On,ze=1,ss=2,Ln={owned:null,cleanups:null,context:null,owner:null},ms={},oe=null,fs=null,Mi=null,me=null,Ce=null,Re=null,cs=0;function He(e,s){const n=me,a=oe,r=e.length===0,i=s===void 0?a:s,l=r?Ln:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Se(()=>Pt(l)));oe=l,me=null;try{return Me(o,!0)}finally{me=n,oe=a}}function je(e,s){s=s?Object.assign({},ts,s):ts;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Rn(n,r));return[Un.bind(n),a]}function Bn(e,s,n){const a=us(e,s,!0,ze);St(a)}function Ve(e,s,n){const a=us(e,s,!1,ze);St(a)}function Us(e,s,n){Dn=Xi;const a=us(e,s,!1,ze);(!n||!n.render)&&(a.user=!0),Re?Re.push(a):St(a)}function Te(e,s,n){n=n?Object.assign({},ts,n):ts;const a=us(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,St(a),Un.bind(a)}function Ui(e){return e&&typeof e=="object"&&"then"in e}function Ri(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,o=ms,u=null,d=!1,h="initialValue"in i,f=typeof a=="function"&&Te(a);const v=new Set,[y,p]=(i.storage||je)(i.initialValue),[S,E]=je(void 0),[G,w]=je(void 0,{equals:!1}),[_,b]=je(h?"ready":"unresolved");W.context&&(u=W.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:W.load&&W.has(u)&&(o=W.load(u)));function B(U,L,H,ee){return l===U&&(l=null,ee!==void 0&&(h=!0),(U===o||L===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(ee,{value:L})),o=ms,O(L,H)),L}function O(U,L){Me(()=>{L===void 0&&p(()=>U),b(L!==void 0?"errored":h?"ready":"unresolved"),E(L);for(const H of v.keys())H.decrement();v.clear()},!1)}function te(){const U=Wi,L=y(),H=S();if(H!==void 0&&!l)throw H;return me&&me.user,L}function se(U=!0){if(U!==!1&&d)return;d=!1;const L=f?f():a;if(L==null||L===!1){B(l,Se(y));return}const H=o!==ms?o:Se(()=>r(L,{value:y(),refetching:U}));return Ui(H)?(l=H,"value"in H?(H.status==="success"?B(l,H.value,void 0,L):B(l,void 0,ys(H.value),L),H):(d=!0,queueMicrotask(()=>d=!1),Me(()=>{b(h?"refreshing":"pending"),w()},!1),H.then(ee=>B(H,ee,void 0,L),ee=>B(H,void 0,ys(ee),L)))):(B(l,H,void 0,L),H)}return Object.defineProperties(te,{state:{get:()=>_()},error:{get:()=>S()},loading:{get(){const U=_();return U==="pending"||U==="refreshing"}},latest:{get(){if(!h)return te();const U=S();if(U&&!l)throw U;return y()}}}),f?Bn(()=>se(!1)):se(!1),[te,{refetch:se,mutate:p}]}function Oi(e){return Me(e,!1)}function Se(e){if(me===null)return e();const s=me;me=null;try{return e()}finally{me=s}}function Fi(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let o;if(a){o=Array(e.length);for(let d=0;d<e.length;d++)o[d]=e[d]()}else o=e();if(i)return i=!1,l;const u=Se(()=>s(o,r,l));return r=o,u}}function Gn(e){Us(()=>Se(e))}function bt(e){return oe===null||(oe.cleanups===null?oe.cleanups=[e]:oe.cleanups.push(e)),e}function en(){return oe}function qi(e,s){const n=oe,a=me;oe=e,me=null;try{return Me(s,!0)}catch(r){Rs(r)}finally{oe=n,me=a}}function zi(e){const s=me,n=oe;return Promise.resolve().then(()=>{me=s,oe=n;let a;return Me(e,!1),me=oe=null,a?a.done:void 0})}var[$i,Go]=je(!1);function Hi(){return[$i,zi]}function Vi(e,s){const n=Symbol("context");return{id:n,Provider:Zi(n),defaultValue:e}}function Ki(e){let s;return oe&&oe.context&&(s=oe.context[e.id])!==void 0?s:e.defaultValue}function Mn(e){const s=Te(e),n=Te(()=>vs(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Wi;function Un(){if(this.sources&&this.state)if(this.state===ze)St(this);else{const e=Ce;Ce=null,Me(()=>as(this),!1),Ce=e}if(me){const e=this.observers?this.observers.length:0;me.sources?(me.sources.push(this),me.sourceSlots.push(e)):(me.sources=[this],me.sourceSlots=[e]),this.observers?(this.observers.push(me),this.observerSlots.push(me.sources.length-1)):(this.observers=[me],this.observerSlots=[me.sources.length-1])}return this.value}function Rn(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&Me(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=fs&&fs.running;l&&fs.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Ce.push(i):Re.push(i),i.observers&&Fn(i)),l||(i.state=ze)}if(Ce.length>1e6)throw Ce=[],new Error},!1)),s}function St(e){if(!e.fn)return;Pt(e);const s=cs;Qi(e,e.value,s)}function Qi(e,s,n){let a;const r=oe,i=me;me=oe=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=ze,e.owned&&e.owned.forEach(Pt),e.owned=null),e.updatedAt=n+1,Rs(l)}finally{me=i,oe=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Rn(e,a):e.value=a,e.updatedAt=n)}function us(e,s,n,a=ze,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:oe,context:oe?oe.context:null,pure:n};return oe===null||oe!==Ln&&(oe.owned?oe.owned.push(i):oe.owned=[i]),i}function ns(e){if(e.state===0)return;if(e.state===ss)return as(e);if(e.suspense&&Se(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<cs);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===ze)St(e);else if(e.state===ss){const a=Ce;Ce=null,Me(()=>as(e,s[0]),!1),Ce=a}}function Me(e,s){if(Ce)return e();let n=!1;s||(Ce=[]),Re?n=!0:Re=[],cs++;try{const a=e();return Yi(n),a}catch(a){n||(Re=null),Ce=null,Rs(a)}}function Yi(e){if(Ce&&(On(Ce),Ce=null),e)return;const s=Re;Re=null,s.length&&Me(()=>Dn(s),!1)}function On(e){for(let s=0;s<e.length;s++)ns(e[s])}function Xi(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:ns(a)}if(W.context){if(W.count){W.effects||(W.effects=[]),W.effects.push(...e.slice(0,n));return}wt()}for(W.effects&&(W.done||!W.count)&&(e=[...W.effects,...e],n+=W.effects.length,delete W.effects),s=0;s<n;s++)ns(e[s])}function as(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===ze?a!==s&&(!a.updatedAt||a.updatedAt<cs)&&ns(a):r===ss&&as(a,s)}}}function Fn(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ss,n.pure?Ce.push(n):Re.push(n),n.observers&&Fn(n))}}function Pt(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),l=n.observerSlots.pop();a<r.length&&(i.sourceSlots[l]=a,r[a]=i,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Pt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Pt(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function ys(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function Rs(e,s=oe){throw ys(e)}function vs(e){if(typeof e=="function"&&!e.length)return vs(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=vs(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Zi(e,s){return function(a){let r;return Ve(()=>r=Se(()=>(oe.context={...oe.context,[e]:a.value},Mn(()=>a.children))),void 0),r}}var js=Symbol("fallback");function rs(e){for(let s=0;s<e.length;s++)e[s]()}function Ji(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return bt(()=>rs(i)),()=>{let u=e()||[],d=u.length,h,f;return u[Ms],Se(()=>{let y,p,S,E,G,w,_,b,B;if(d===0)l!==0&&(rs(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[js],r[0]=He(O=>(i[0]=O,n.fallback())),l=1);else if(l===0){for(r=new Array(d),f=0;f<d;f++)a[f]=u[f],r[f]=He(v);l=d}else{for(S=new Array(d),E=new Array(d),o&&(G=new Array(d)),w=0,_=Math.min(l,d);w<_&&a[w]===u[w];w++);for(_=l-1,b=d-1;_>=w&&b>=w&&a[_]===u[b];_--,b--)S[b]=r[_],E[b]=i[_],o&&(G[b]=o[_]);for(y=new Map,p=new Array(b+1),f=b;f>=w;f--)B=u[f],h=y.get(B),p[f]=h===void 0?-1:h,y.set(B,f);for(h=w;h<=_;h++)B=a[h],f=y.get(B),f!==void 0&&f!==-1?(S[f]=r[h],E[f]=i[h],o&&(G[f]=o[h]),f=p[f],y.set(B,f)):i[h]();for(f=w;f<d;f++)f in S?(r[f]=S[f],i[f]=E[f],o&&(o[f]=G[f],o[f](f))):r[f]=He(v);r=r.slice(0,l=d),a=u.slice(0)}return r});function v(y){if(i[f]=y,o){const[p,S]=je(f);return o[f]=S,s(u[f],p)}return s(u[f])}}}function el(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return bt(()=>rs(i)),()=>{const d=e()||[],h=d.length;return d[Ms],Se(()=>{if(h===0)return o!==0&&(rs(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[js],r[0]=He(v=>(i[0]=v,n.fallback())),o=1),r;for(a[0]===js&&(i[0](),i=[],a=[],r=[],o=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=He(f));for(;u<a.length;u++)i[u]();return o=l.length=i.length=h,a=d.slice(0),r=r.slice(0,o)});function f(v){i[u]=v;const[y,p]=je(d[u]);return l[u]=p,s(y,u)}}}function Os(e,s){return Se(()=>e(s||{}))}function Wt(){return!0}var bs={get(e,s,n){return s===es?n:e.get(s)},has(e,s){return s===es?!0:e.has(s)},set:Wt,deleteProperty:Wt,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:Wt,deleteProperty:Wt}},ownKeys(e){return e.keys()}};function gs(e){return(e=typeof e=="function"?e():e)?e:{}}function tl(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function Fs(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&es in o,e[l]=typeof o=="function"?(s=!0,Te(o)):o}if(kn&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=gs(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in gs(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(gs(e[o])));return[...new Set(l)]}},bs);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const f=Object.getOwnPropertyDescriptor(o,h);if(!a[h])a[h]=f.get?{enumerable:!0,configurable:!0,get:tl.bind(n[h]=[f.get.bind(o)])}:f.value!==void 0?f:void 0;else{const v=n[h];v&&(f.get?v.push(f.get.bind(o)):f.value!==void 0&&v.push(()=>f.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const o=i[l],u=a[o];u&&u.get?Object.defineProperty(r,o,u):r[o]=u?u.value:void 0}return r}function qn(e,...s){if(kn&&es in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(o){return l.includes(o)?e[o]:void 0},has(o){return l.includes(o)&&o in e},keys(){return l.filter(o=>o in e)}},bs));return i.push(new Proxy({get(l){return r.has(l)?void 0:e[l]},has(l){return r.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!r.has(l))}},bs)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let o=!1,u=0;for(const d of s)d.includes(r)&&(o=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;o||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function zn(e){let s,n;const a=r=>{const i=W.context;if(i){const[o,u]=je();W.count||(W.count=0),W.count++,(n||(n=e())).then(d=>{!W.done&&wt(i),W.count--,u(()=>d.default),wt()}),s=o}else if(!s){const[o]=Ri(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Te(()=>(l=s())?Se(()=>{if(!i||W.done)return l(r);const o=W.context;wt(i);const u=l(r);return wt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var sl=0;function nl(){return W.context?W.getNextContextId():`cl-${sl++}`}var $n=e=>`Stale read from <${e}>.`;function al(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(Ji(()=>e.each,e.children,s||void 0))}function rl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Te(el(()=>e.each,e.children,s||void 0))}function il(e){const s=e.keyed,n=Te(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Te(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Se(()=>r(s?a:()=>{if(!Se(n))throw $n("Show");return e.when})):r}return e.fallback},void 0,void 0)}function ll(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=Mn(()=>e.children),r=Te(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const o=i[l].when;if(o)return s=!!i[l].keyed,[l,o,i[l]]}return[-1]},void 0,{equals:n});return Te(()=>{const[i,l,o]=r();if(i<0)return e.fallback;const u=o.children;return typeof u=="function"&&u.length>0?Se(()=>u(s?l:()=>{if(Se(r)[0]!==i)throw $n("Match");return o.when})):u},void 0,void 0)}function ol(e){return e}var cl=["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"],ul=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...cl]),dl=new Set(["innerHTML","textContent","innerText","children"]),hl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),ml=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 fl(e,s){const n=ml[e];return typeof n=="object"?n[s]?n.$:void 0:n}var gl=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),pl=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"]),xl={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function yl(e,s,n){let a=n.length,r=s.length,i=a,l=0,o=0,u=s[r-1].nextSibling,d=null;for(;l<r||o<i;){if(s[l]===n[o]){l++,o++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const h=i<a?o?n[o-1].nextSibling:n[i-o]:u;for(;o<i;)e.insertBefore(n[o++],h)}else if(i===o)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[o]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let f=o;for(;f<i;)d.set(n[f],f++)}const h=d.get(s[l]);if(h!=null)if(o<h&&h<i){let f=l,v=1,y;for(;++f<r&&f<i&&!((y=d.get(s[f]))==null||y!==h+v);)v++;if(v>h-o){const p=s[l];for(;o<h;)e.insertBefore(n[o++],p)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var Ct="_$DX_DELEGATE";function Hn(e,s,n,a={}){let r;return He(i=>{r=i,s===document?e():ls(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function vl(e,s,n){let a;const r=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},i=()=>(a||(a=r())).cloneNode(!0);return i.cloneNode=i,i}function Vn(e,s=window.document){const n=s[Ct]||(s[Ct]=new Set);for(let a=0,r=e.length;a<r;a++){const i=e[a];n.has(i)||(n.add(i),s.addEventListener(i,Xn))}}function jl(e=window.document){if(e[Ct]){for(let s of e[Ct].keys())e.removeEventListener(s,Xn);delete e[Ct]}}function is(e,s,n){st(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function bl(e,s,n,a){st(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function El(e,s,n){st(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function Kn(e,s){st(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Wn(e,s,n,a){if(a)Array.isArray(n)?(e[`$$${s}`]=n[0],e[`$$${s}Data`]=n[1]):e[`$$${s}`]=n;else if(Array.isArray(n)){const r=n[0];e.addEventListener(s,n[0]=i=>r.call(e,n[1],i))}else e.addEventListener(s,n,typeof n!="function"&&n)}function Sl(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const o=r[i];!o||o==="undefined"||s[o]||(tn(e,o,!1),delete n[o])}for(i=0,l=a.length;i<l;i++){const o=a[i],u=!!s[o];!o||o==="undefined"||n[o]===u||!u||(tn(e,o,!0),n[o]=u)}return n}function wl(e,s,n){if(!s)return n?is(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function Qn(e,s={},n,a){const r={};return a||Ve(()=>r.children=It(e,s.children,r.children)),Ve(()=>typeof s.ref=="function"&&Yn(s.ref,e)),Ve(()=>Nl(e,s,n,!0,r,!0)),r}function Yn(e,s,n){return Se(()=>e(s,n))}function ls(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return It(e,s,a,n);Ve(r=>It(e,s(),r,n),a)}function Nl(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=sn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=sn(e,l,o,r[l],n,i,s)}}function Al(e){let s,n;return!st()||!(s=W.registry.get(n=Tl()))?e():(W.completed&&W.completed.add(s),W.registry.delete(n),s)}function st(e){return!!W.context&&!W.done&&(!e||e.isConnected)}function Cl(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function tn(e,s,n){const a=s.trim().split(/\s+/);for(let r=0,i=a.length;r<i;r++)e.classList.toggle(a[r],n)}function sn(e,s,n,a,r,i,l){let o,u,d,h,f;if(s==="style")return wl(e,n,a);if(s==="classList")return Sl(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const v=s.slice(3);a&&e.removeEventListener(v,a,typeof a!="function"&&a),n&&e.addEventListener(v,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const v=s.slice(10);a&&e.removeEventListener(v,a,!0),n&&e.addEventListener(v,n,!0)}else if(s.slice(0,2)==="on"){const v=s.slice(2).toLowerCase(),y=gl.has(v);if(!y&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(v,p)}(y||n)&&(Wn(e,v,n,y),y&&Vn([v]))}else if(s.slice(0,5)==="attr:")is(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")El(e,s.slice(5),n);else if((f=s.slice(0,5)==="prop:")||(d=dl.has(s))||!r&&((h=fl(s,e.tagName))||(u=ul.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(f)s=s.slice(5),u=!0;else if(st(e))return n;s==="class"||s==="className"?Kn(e,n):o&&!u&&!d?e[Cl(s)]=n:e[h||s]=n}else{const v=r&&s.indexOf(":")>-1&&xl[s.split(":")[0]];v?bl(e,v,s,n):is(e,hl[s]||s,n)}return n}function Xn(e){if(W.registry&&W.events&&W.events.find(([u,d])=>d===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const d=s[`${n}Data`];if(d!==void 0?u.call(s,d,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},o=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),W.registry&&!W.done&&(W.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,o();break}if(s.parentNode===r)break}}else o();i(a)}function It(e,s,n,a,r){const i=st(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const h=n[d];h.nodeType===8&&h.data.slice(0,2)==="!$"?h.remove():u.push(h)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,o=a!==void 0;if(e=o&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(o){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=at(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(i)return n;n=at(e,n,a)}else{if(l==="function")return Ve(()=>{let u=s();for(;typeof u=="function";)u=u();n=It(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Es(u,s,n,r))return Ve(()=>n=It(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let h=u[0];if(h.parentNode!==e)return n;const f=[h];for(;(h=h.nextSibling)!==a;)f.push(h);return n=f}if(u.length===0){if(n=at(e,n,a),o)return n}else d?n.length===0?nn(e,u,a):yl(e,n,u):(n&&at(e),nn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=o?[s]:s;if(Array.isArray(n)){if(o)return n=at(e,n,a,s);at(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Es(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let o=s[i],u=n&&n[e.length],d;if(!(o==null||o===!0||o===!1))if((d=typeof o)=="object"&&o.nodeType)e.push(o);else if(Array.isArray(o))r=Es(e,o,u)||r;else if(d==="function")if(a){for(;typeof o=="function";)o=o();r=Es(e,Array.isArray(o)?o:[o],Array.isArray(u)?u:[u])||r}else e.push(o),r=!0;else{const h=String(o);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function nn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function at(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const o=s[l];if(r!==o){const u=o.parentNode===e;!i&&!l?u?e.replaceChild(r,o):e.insertBefore(r,n):u&&o.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function Tl(){return W.getNextContextId()}var Pl="http://www.w3.org/2000/svg";function Zn(e,s=!1){return s?document.createElementNS(Pl,e):document.createElement(e)}function Il(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=en();let i,l=!!W.context;return Us(()=>{l&&(en().user=l=!1),i||(i=qi(r,()=>Te(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,d]=je(!1),h=()=>d(!0);He(f=>ls(o,()=>u()?f():i(),null)),bt(h)}else{const u=Zn(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),ls(d,i),o.appendChild(u),e.ref&&e.ref(u),bt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function _l(e){const[s,n]=qn(e,["component"]),a=Te(()=>s.component);return Te(()=>{const r=a();switch(typeof r){case"function":return Se(()=>r(n));case"string":const i=pl.has(r),l=W.context?Al():Zn(r,i);return Qn(l,n,i),l}})}var kl=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,s){this.keyToValue.set(e,s),this.valueToKey.set(s,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},Jn=class{constructor(e){this.generateIdentifier=e,this.kv=new kl}register(e,s){this.kv.getByValue(e)||(s||(s=this.generateIdentifier(e)),this.kv.set(s,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},Dl=class extends Jn{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,s){typeof s=="object"?(s.allowProps&&this.classToAllowedProps.set(e,s.allowProps),super.register(e,s.identifier)):super.register(e,s)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function Ll(e){if("values"in Object)return Object.values(e);const s=[];for(const n in e)e.hasOwnProperty(n)&&s.push(e[n]);return s}function Bl(e,s){const n=Ll(e);if("find"in n)return n.find(s);const a=n;for(let r=0;r<a.length;r++){const i=a[r];if(s(i))return i}}function Et(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Zt(e,s){return e.indexOf(s)!==-1}function an(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Gl=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Bl(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Ml=e=>Object.prototype.toString.call(e).slice(8,-1),ea=e=>typeof e>"u",Ul=e=>e===null,_t=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Ss=e=>_t(e)&&Object.keys(e).length===0,Ke=e=>Array.isArray(e),Rl=e=>typeof e=="string",Ol=e=>typeof e=="number"&&!isNaN(e),Fl=e=>typeof e=="boolean",ql=e=>e instanceof RegExp,kt=e=>e instanceof Map,Dt=e=>e instanceof Set,ta=e=>Ml(e)==="Symbol",zl=e=>e instanceof Date&&!isNaN(e.valueOf()),$l=e=>e instanceof Error,rn=e=>typeof e=="number"&&isNaN(e),Hl=e=>Fl(e)||Ul(e)||ea(e)||Ol(e)||Rl(e)||ta(e),Vl=e=>typeof e=="bigint",Kl=e=>e===1/0||e===-1/0,Wl=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Ql=e=>e instanceof URL,sa=e=>e.replace(/\./g,"\\."),ps=e=>e.map(String).map(sa).join("."),Tt=e=>{const s=[];let n="";for(let r=0;r<e.length;r++){let i=e.charAt(r);if(i==="\\"&&e.charAt(r+1)==="."){n+=".",r++;continue}if(i==="."){s.push(n),n="";continue}n+=i}const a=n;return s.push(a),s};function Ge(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var na=[Ge(ea,"undefined",()=>null,()=>{}),Ge(Vl,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),Ge(zl,"Date",e=>e.toISOString(),e=>new Date(e)),Ge($l,"Error",(e,s)=>{const n={name:e.name,message:e.message};return s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n},(e,s)=>{const n=new Error(e.message);return n.name=e.name,n.stack=e.stack,s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n}),Ge(ql,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),Ge(Dt,"set",e=>[...e.values()],e=>new Set(e)),Ge(kt,"map",e=>[...e.entries()],e=>new Map(e)),Ge(e=>rn(e)||Kl(e),"number",e=>rn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),Ge(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),Ge(Ql,"URL",e=>e.toString(),e=>new URL(e))];function ds(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var aa=ds((e,s)=>ta(e)?!!s.symbolRegistry.getIdentifier(e):!1,(e,s)=>["symbol",s.symbolRegistry.getIdentifier(e)],e=>e.description,(e,s,n)=>{const a=n.symbolRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown symbol");return a}),Yl=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),ra=ds(Wl,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Yl[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function ia(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var la=ds(ia,(e,s)=>["class",s.classRegistry.getIdentifier(e.constructor)],(e,s)=>{const n=s.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};const a={};return n.forEach(r=>{a[r]=e[r]}),a},(e,s,n)=>{const a=n.classRegistry.getValue(s[1]);if(!a)throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");return Object.assign(Object.create(a.prototype),e)}),oa=ds((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Xl=[la,aa,oa,ra],ln=(e,s)=>{const n=an(Xl,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=an(na,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},ca={};na.forEach(e=>{ca[e.annotation]=e});var Zl=(e,s,n)=>{if(Ke(s))switch(s[0]){case"symbol":return aa.untransform(e,s,n);case"class":return la.untransform(e,s,n);case"custom":return oa.untransform(e,s,n);case"typed-array":return ra.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=ca[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},rt=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function ua(e){if(Zt(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Zt(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Zt(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Jl=(e,s)=>{ua(s);for(let n=0;n<s.length;n++){const a=s[n];if(Dt(e))e=rt(e,+a);else if(kt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=rt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},ws=(e,s,n)=>{if(ua(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Ke(a)){const o=+l;a=a[o]}else if(_t(a))a=a[l];else if(Dt(a)){const o=+l;a=rt(a,o)}else if(kt(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=rt(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(Ke(a)?a[+r]=n(a[+r]):_t(a)&&(a[r]=n(a[r])),Dt(a)){const i=rt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(kt(a)){const i=+s[s.length-2],l=rt(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(l);a.set(u,a.get(l)),u!==l&&a.delete(l);break}case"value":{a.set(l,n(a.get(l)));break}}}return e};function Ns(e,s,n=[]){if(!e)return;if(!Ke(e)){Et(e,(i,l)=>Ns(i,s,[...n,...Tt(l)]));return}const[a,r]=e;r&&Et(r,(i,l)=>{Ns(i,s,[...n,...Tt(l)])}),s(a,n)}function eo(e,s,n){return Ns(s,(a,r)=>{e=ws(e,r,i=>Zl(i,a,n))}),e}function to(e,s){function n(a,r){const i=Jl(e,Tt(r));a.map(Tt).forEach(l=>{e=ws(e,l,()=>i)})}if(Ke(s)){const[a,r]=s;a.forEach(i=>{e=ws(e,Tt(i),()=>e)}),r&&Et(r,n)}else Et(s,n);return e}var so=(e,s)=>_t(e)||Ke(e)||kt(e)||Dt(e)||ia(e,s);function no(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function ao(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(o=>o.map(String)).sort((o,u)=>o.length-u.length));const[i,...l]=r;i.length===0?a=l.map(ps):n[ps(i)]=l.map(ps)}),a?Ss(n)?[a]:[a,n]:Ss(n)?void 0:n}var da=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=Hl(e);if(!o){no(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!so(e,n)){const y=ln(e,n),p=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,p),p}if(Zt(i,e))return{transformedValue:null};const u=ln(e,n),d=(u==null?void 0:u.value)??e,h=Ke(d)?[]:{},f={};Et(d,(y,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const S=da(y,s,n,a,[...r,p],[...i,e],l);h[p]=S.transformedValue,Ke(S.annotations)?f[p]=S.annotations:_t(S.annotations)&&Et(S.annotations,(E,G)=>{f[sa(p)+"."+G]=E})});const v=Ss(f)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,f]:f};return o||l.set(e,v),v};function ha(e){return Object.prototype.toString.call(e).slice(8,-1)}function on(e){return ha(e)==="Array"}function ro(e){if(ha(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function io(e,s,n,a,r){const i={}.propertyIsEnumerable.call(a,s)?"enumerable":"nonenumerable";i==="enumerable"&&(e[s]=n),r&&i==="nonenumerable"&&Object.defineProperty(e,s,{value:n,enumerable:!1,writable:!0,configurable:!0})}function As(e,s={}){if(on(e))return e.map(r=>As(r,s));if(!ro(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(on(s.props)&&!s.props.includes(i))return r;const l=e[i],o=As(l,s);return io(r,i,o,e,s.nonenumerable),r},{})}var fe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Dl,this.symbolRegistry=new Jn(s=>s.description??""),this.customTransformerRegistry=new Gl,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=da(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=ao(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=As(s);return n!=null&&n.values&&(a=eo(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=to(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};fe.defaultInstance=new fe;fe.serialize=fe.defaultInstance.serialize.bind(fe.defaultInstance);fe.deserialize=fe.defaultInstance.deserialize.bind(fe.defaultInstance);fe.stringify=fe.defaultInstance.stringify.bind(fe.defaultInstance);fe.parse=fe.defaultInstance.parse.bind(fe.defaultInstance);fe.registerClass=fe.defaultInstance.registerClass.bind(fe.defaultInstance);fe.registerSymbol=fe.defaultInstance.registerSymbol.bind(fe.defaultInstance);fe.registerCustom=fe.defaultInstance.registerCustom.bind(fe.defaultInstance);fe.allowErrorProps=fe.defaultInstance.allowErrorProps.bind(fe.defaultInstance);var ma=fe.serialize,lo=fe.stringify;function oo(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function co(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function uo({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function ho({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function mo(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var fo=(e,s=!1)=>{const{json:n}=ma(e);return JSON.stringify(n,null,s?2:void 0)},Qt=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,go=(e,s)=>e.queryHash.localeCompare(s.queryHash),fa=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,po=(e,s)=>Qt(e)===Qt(s)?fa(e,s):Qt(e)>Qt(s)?1:-1,xo={status:po,"query hash":go,"last updated":fa},Yt=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,ga=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,yo=(e,s)=>Yt(e)===Yt(s)?ga(e,s):Yt(e)>Yt(s)?1:-1,vo={status:yo,"last updated":ga},jo=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),bo=()=>{const[e,s]=je("dark");return Gn(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=r=>{s(r.matches?"dark":"light")};n.addEventListener("change",a),bt(()=>n.removeEventListener("change",a))}),e},Nt=(e,s,n)=>{if(s.length===0)return n;if(e instanceof Map){const a=new Map(e);if(s.length===1)return a.set(s[0],n),a;const[r,...i]=s;return a.set(r,Nt(a.get(r),i,n)),a}if(e instanceof Set){const a=Nt(Array.from(e),s,n);return new Set(a)}if(Array.isArray(e)){const a=[...e];if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Nt(a[r],i,n),a}if(e instanceof Object){const a={...e};if(s.length===1)return a[s[0]]=n,a;const[r,...i]=s;return a[r]=Nt(a[r],i,n),a}return e},At=(e,s)=>{if(e instanceof Map){const n=new Map(e);if(s.length===1)return n.delete(s[0]),n;const[a,...r]=s;return n.set(a,At(n.get(a),r)),n}if(e instanceof Set){const n=At(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,l)=>l.toString()!==s[0]);const[a,...r]=s;return n[a]=At(n[a],r),n}if(e instanceof Object){const n={...e};if(s.length===1)return delete n[s[0]],n;const[a,...r]=s;return n[a]=At(n[a],r),n}return e},pa=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},it,Lt,Bt,Gt,Xe,Mt,lt,ot,ct,ut,dt,ht,Ut,cn,Eo=(cn=class{constructor(e){he(this,it);he(this,Lt);he(this,Bt);he(this,Gt);he(this,Xe,!1);he(this,Mt);he(this,lt);he(this,ot);he(this,ct);he(this,ut);he(this,dt);he(this,ht);he(this,Ut);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;de(this,it,je(s)),de(this,Bt,n),de(this,Gt,a),de(this,Lt,r),de(this,Mt,d),de(this,lt,h),de(this,ot,je(i)),de(this,ct,je(l)),de(this,ut,je(o)),de(this,dt,je(u))}setButtonPosition(e){K(this,ot)[1](e)}setPosition(e){K(this,ct)[1](e)}setInitialIsOpen(e){K(this,ut)[1](e)}setErrorTypes(e){K(this,dt)[1](e)}setClient(e){K(this,it)[1](e)}mount(e){if(K(this,Xe))throw new Error("Devtools is already mounted");const s=Hn(()=>{const n=this,[a]=K(this,ot),[r]=K(this,ct),[i]=K(this,ut),[l]=K(this,dt),[o]=K(this,it);let u;return K(this,ht)?u=K(this,ht):(u=zn(()=>Promise.resolve().then(()=>require("./HO4MOOFI-DCjFawwp.cjs"))),de(this,ht,u)),pa(K(this,Mt),K(this,lt)),Os(u,Fs({get queryFlavor(){return K(n,Bt)},get version(){return K(n,Gt)},get onlineManager(){return K(n,Lt)},get shadowDOMTarget(){return K(n,lt)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);de(this,Xe,!0),de(this,Ut,s)}unmount(){var e;if(!K(this,Xe))throw new Error("Devtools is not mounted");(e=K(this,Ut))==null||e.call(this),de(this,Xe,!1)}},it=new WeakMap,Lt=new WeakMap,Bt=new WeakMap,Gt=new WeakMap,Xe=new WeakMap,Mt=new WeakMap,lt=new WeakMap,ot=new WeakMap,ct=new WeakMap,ut=new WeakMap,dt=new WeakMap,ht=new WeakMap,Ut=new WeakMap,cn),mt,Rt,Ot,Ft,Ze,qt,ft,gt,pt,xt,yt,vt,jt,zt,un,So=(un=class{constructor(e){he(this,mt);he(this,Rt);he(this,Ot);he(this,Ft);he(this,Ze,!1);he(this,qt);he(this,ft);he(this,gt);he(this,pt);he(this,xt);he(this,yt);he(this,vt);he(this,jt);he(this,zt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:f}=e;de(this,mt,je(s)),de(this,Ot,n),de(this,Ft,a),de(this,Rt,r),de(this,qt,d),de(this,ft,h),de(this,gt,je(i)),de(this,pt,je(l)),de(this,xt,je(o)),de(this,yt,je(u)),de(this,vt,je(f))}setButtonPosition(e){K(this,gt)[1](e)}setPosition(e){K(this,pt)[1](e)}setInitialIsOpen(e){K(this,xt)[1](e)}setErrorTypes(e){K(this,yt)[1](e)}setClient(e){K(this,mt)[1](e)}setOnClose(e){K(this,vt)[1](()=>e)}mount(e){if(K(this,Ze))throw new Error("Devtools is already mounted");const s=Hn(()=>{const n=this,[a]=K(this,gt),[r]=K(this,pt),[i]=K(this,xt),[l]=K(this,yt),[o]=K(this,mt),[u]=K(this,vt);let d;return K(this,jt)?d=K(this,jt):(d=zn(()=>Promise.resolve().then(()=>require("./HUY7CZI3-DJrQ1ujA.cjs"))),de(this,jt,d)),pa(K(this,qt),K(this,ft)),Os(d,Fs({get queryFlavor(){return K(n,Ot)},get version(){return K(n,Ft)},get onlineManager(){return K(n,Rt)},get shadowDOMTarget(){return K(n,ft)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);de(this,Ze,!0),de(this,zt,s)}unmount(){var e;if(!K(this,Ze))throw new Error("Devtools is not mounted");(e=K(this,zt))==null||e.call(this),de(this,Ze,!1)}},mt=new WeakMap,Rt=new WeakMap,Ot=new WeakMap,Ft=new WeakMap,Ze=new WeakMap,qt=new WeakMap,ft=new WeakMap,gt=new WeakMap,pt=new WeakMap,xt=new WeakMap,yt=new WeakMap,vt=new WeakMap,jt=new WeakMap,zt=new WeakMap,un);function wo(e){const s=D.useQueryClient(e.client),n=ye.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}=e,[d]=ye.useState(new Eo({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}));return ye.useEffect(()=>{d.setClient(s)},[s,d]),ye.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),ye.useEffect(()=>{r&&d.setPosition(r)},[r,d]),ye.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),ye.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),ye.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function No(e){const s=D.useQueryClient(e.client),n=ye.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=ye.useState(new So({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose}));return ye.useEffect(()=>{l.setClient(s)},[s,l]),ye.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),ye.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),ye.useEffect(()=>(n.current&&l.mount(n.current),()=>{l.unmount()}),[l]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var Ao=process.env.NODE_ENV!=="development"?function(){return null}:wo;process.env.NODE_ENV;const Co=()=>{const e=ne(),s=$();return D.useQuery({queryKey:[q,I.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:I.GET_COLLECTIONS})})},To=()=>{const{data:e}=Ie(),{data:s}=os(),{data:n}=We(),a=ne(),r=$(),i=g.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return D.useMutation({mutationFn:async({block:l})=>r(a,{action:I.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},xa=()=>{const e=Gs();return g.useCallback(({pageId:s})=>{e(s)},[e])},Po=g.lazy(()=>Promise.resolve().then(()=>Ai));Sa.loadWebBlocks();X.registerChaiTopBar(ni);Bi();X.registerChaiMediaManager(Po);X.registerChaiSaveToLibrary(Za);const Io=e=>{const s=g.useRef([]),[n]=Pe(),a=n.get("page"),{data:r}=Ie(),{data:i={role:"",permissions:null}}=An();li();const{data:l,isFetching:o}=vn(),{blocks:u}=ii(l),{data:d}=Ne(),{mutateAsync:h}=gn(),f=ai(),{onSave:v}=oi(),{getPartialBlocks:y,getPartialBlockBlocks:p}=ci(),{aiContext:S,setAiContext:E}=Ts(),{mutateAsync:G}=tr(),[w,_]=g.useState(!1),{data:b}=We(),B=Is(),{data:O}=_s(),{data:te}=Co(),{mutateAsync:se}=To(),U=xa();Ga(),g.useEffect(()=>{const ae=()=>{document.hidden?_(!0):_(!1)};return window.addEventListener("visibilitychange",ae),()=>window.removeEventListener("visibilitychange",ae)},[]),s.current=u;const L=g.useMemo(()=>{const ae={};return i&&(ae.permissions=x.get(i,"permissions",null),ae.role=x.get(i,"role","user")),ae},[i]),H=g.useCallback(async(ae,Z)=>await G({pageType:ae,query:Z}),[G]),ee=g.useMemo(()=>x.get(b,"theme",{})||{},[b]);return t.jsxs(t.Fragment,{children:[o&&t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/30",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(N.Loader2,{className:"size-5 animate-spin"})})}),t.jsx(X.ChaiBuilderEditor,{gotoPage:U,collections:te??[],getBlockAsyncProps:se,pageExternalData:O,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:B,languages:(b==null?void 0:b.languages)||[],brandingOptions:(b==null?void 0:b.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!w&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:y,blocks:o?[]:u,theme:x.cloneDeep(ee),pageTypes:d,searchPageTypeItems:H,saveAiContextCallback:async ae=>{if(!a)return!0;const Z=s.current,k={_type:"@chai/ai-context",_value:x.isString(ae)?ae:""},V=[...Z,k];return await v({page:a,blocks:V}),E(ae),!0},aiContext:S,askAiCallBack:f,onSave:async({blocks:ae,theme:Z})=>{if(!a)return!0;s.current=ae;const k={_type:"@chai/ai-context",_value:x.isString(S)?S:""},V=[...ae,k];return await v({page:a,blocks:V}),s.current=V,x.isEqual(Z,ee)||await h({settings:{theme:Z}}),!0},themePanelComponent:ur,...L}),t.jsxs("div",{children:[t.jsx(Fa,{}),t.jsx(qa,{})]})]})},_o=new D.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),ko=e=>{const{isLoggedIn:s}=Fe(),[,n]=pn(),[a,r]=g.useState(!1);return g.useEffect(()=>(n(x.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?t.jsxs(D.QueryClientProvider,{client:_o,children:[s?t.jsx(Io,{...e}):t.jsx(mi,{}),t.jsx(Ao,{}),t.jsx(z.Toaster,{richColors:!0})]}):t.jsx("div",{})},Do=()=>{const e=ne(),s=$(),{data:n}=os(),a=D.useQueryClient();return D.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:I.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[q,I.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[q,I.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},Lo=()=>{const{user:e,logout:s}=Fe(),n=e==null?void 0:e.accessToken;return g.useCallback(async({url:a,method:r="GET",body:i={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const o=await fetch(a,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(i)});if(o.status===401)return console.log("Session expired",o),await s(),null;if(o.status===400)throw new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",o),o}},[n,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Ms;exports.ChaiBuilderPages=ko;exports.Dynamic=_l;exports.For=al;exports.ImagePicker=Pn;exports.Index=rl;exports.Match=ol;exports.NestedPathSelector=Ue;exports.PermissionChecker=ke;exports.Portal=Il;exports.Show=il;exports.Switch=ll;exports.addEventListener=Wn;exports.batch=Oi;exports.className=Kn;exports.clearDelegatedEvents=jl;exports.convertRemToPixels=jo;exports.createComponent=Os;exports.createComputed=Bn;exports.createContext=Vi;exports.createEffect=Us;exports.createMemo=Te;exports.createRenderEffect=Ve;exports.createRoot=He;exports.createSignal=je;exports.createUniqueId=nl;exports.delegateEvents=Vn;exports.deleteNestedDataByPath=At;exports.displayValue=fo;exports.getMutationStatusColor=ho;exports.getPreferredColorScheme=bo;exports.getQueryStatusColor=uo;exports.getQueryStatusColorByLabel=mo;exports.getQueryStatusLabel=oo;exports.getSidedProp=co;exports.insert=ls;exports.mergeProps=Fs;exports.mutationSortFns=vo;exports.on=Fi;exports.onCleanup=bt;exports.onMount=Gn;exports.registerLoginComponent=hi;exports.serialize=ma;exports.setAttribute=is;exports.sortFns=xo;exports.splitProps=qn;exports.spread=Qn;exports.stringify=lo;exports.template=vl;exports.untrack=Se;exports.updateNestedDataByPath=Nt;exports.use=Yn;exports.useActivePage=os;exports.useBuilderPageData=_s;exports.useChaiAuth=Fe;exports.useChaiFetch=Lo;exports.useChaiUserInfo=tt;exports.useContext=Ki;exports.useCurrentPage=Ie;exports.useFallbackLang=Is;exports.useFetch=$;exports.useGotoPage=xa;exports.useLanguagePages=et;exports.usePageTypes=Ne;exports.useTransition=Hi;exports.useUpdateActivePageMetadata=Do;exports.useUserRoleAndPermissions=An;exports.useWebsitePages=Vt;exports.useWebsiteSetting=We;