@chaibuilder/pages 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +0,0 @@
1
- "use strict";var rn=e=>{throw TypeError(e)};var ln=(e,s,n)=>s.has(e)||rn("Cannot "+n);var X=(e,s,n)=>(ln(e,s,"read from private field"),n?n.call(e):s.get(e)),ge=(e,s,n)=>s.has(e)?rn("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),fe=(e,s,n,a)=>(ln(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),m=require("lodash-es"),f=require("react"),Re=require("jotai"),B=require("@tanstack/react-query"),W=require("sonner"),Q=require("@chaibuilder/sdk"),o=require("@chaibuilder/sdk/ui"),Ct=require("date-fns"),E=require("lucide-react"),Tn=require("@chaibuilder/runtime"),ls=require("zod"),Wa=require("react-dropzone"),Qa=require("@chaibuilder/sdk/web-blocks");function Ya(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const we=Ya(f),Pe={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},I={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},Y="chaibuilder";let Ja=0;function on(e,s){const n=`atom${++Ja}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Xa,a.write=Za),s&&(a.write=s),a}function Xa(e){return e(this)}function Za(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const er=Symbol(""),tr=e=>typeof(e==null?void 0:e.then)=="function";function sr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,g;const b=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},y=(g=(h=e())==null?void 0:h.getItem(u))!=null?g:null;return tr(y)?y.then(b):b(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,g)=>u(d,b=>{let y;try{y=JSON.parse(b||"")}catch{y=g}h(y)});let c;try{c=(n=e())==null?void 0:n.subscribe}catch{}return!c&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(c=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=g=>{g.storageArea===e()&&g.key===u&&d(g.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),c&&(i.subscribe=l(c)),i}const nr=sr();function Pn(e,s,n=nr,a){const r=on(s);return r.onMount=l=>{l(n.getItem(e,s));let c;return n.subscribe&&(c=n.subscribe(e,l,s)),c},on(l=>l(r),(l,c,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===er?(c(r,s),n.removeItem(e)):d instanceof Promise?d.then(h=>(c(r,h),n.setItem(e,h))):(c(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const kn="__logged_in_user",ar=Pn(kn,null),ze=()=>{const[e,s]=Re.useAtom(ar),n=f.useCallback(()=>{s(null),localStorage.removeItem(kn)},[s]),a=f.useMemo(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const r=Math.floor(Date.now()/1e3);return e.expiresAt-r<=0},[e]);return{isLoggedIn:!!e,isSessionExpired:a,user:e,setUser:s,logout:n}},zs=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),J=()=>{const{user:e,logout:s}=ze(),n=B.useQueryClient(),a=e==null?void 0:e.accessToken;return f.useCallback(async(r,i,l={})=>{if(!a)return null;try{const c=m.get(i,"action","").toLowerCase(),u=await zs(r+(c?`?action=${c}`:""),i,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[Y]}),s(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(c){throw console.error("API request failed:",i,c),c}},[a,s,n])},In=()=>{const e=re(),s=B.useQueryClient(),n=J();return B.useMutation({mutationFn:async a=>n(e,{action:I.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,I.GET_DRAFT_PAGE]})}})},Ln=()=>{const e=re(),s=B.useQueryClient(),n=J();return B.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||W.toast.success("Website settings updated successfully.")},onError:a=>{W.toast.error("Failed to update website settings",{description:a.message})}})},rr=()=>{const e=re(),s=B.useQueryClient(),n=J();return B.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_DATA]}),W.toast.success("Website data updated successfully.")},onError:a=>{W.toast.error("Failed to update website data",{description:a.message})}})};function Ie(){const[e,s]=f.useState(new URLSearchParams(window.location.search));return f.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const ir=Re.atom({}),Dn=()=>Re.useAtom(ir),lr=()=>{const[e]=Ie(),s=e.get("page"),n=f.useRef(""),{mutate:a}=In();f.useEffect(()=>{!m.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Xe=(e,s)=>{const[n]=Dn();return f.useMemo(()=>m.get(n,e,s),[n,e,s])},re=()=>Xe("apiUrl","/chai/api"),js=()=>Xe("usersApiUrl","/chai/users"),Xt=()=>Xe("assetsApiUrl","/chai/assets"),He=e=>{const s=re(),[n]=Ie(),a=e??n.get("page"),r=J();return B.useQuery({queryKey:[Y,I.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:I.GET_LANGUAGE_PAGES,data:{id:a}});return m.reverse(m.sortBy(i,"primaryPage"))},enabled:!!a})},Ze=()=>{const e=re(),s=J();return B.useQuery({queryKey:[Y,I.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:I.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},_n=e=>{const{fallbackLang:s}=Q.useLanguages(),{data:n}=Ze(),{data:a,isFetching:r}=He(),i=f.useMemo(()=>{const l={[s]:!0};return m.each(m.get(n,"languages"),c=>{const u=m.find(a,{lang:c});l[c]=!!u}),l},[s,a,n]);return r||m.isEmpty(e)||e&&i[e]},$s=()=>{const e=B.useQueryClient(),{data:s}=B.useQuery({queryKey:[Y,I.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:f.useCallback(a=>{e.setQueryData([Y,I.AI_CONTEXT],a)},[e]),aiContext:s}},Zt=()=>{const e=J(),s=re();return B.useQuery({queryKey:[Y,I.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},or=Re.atom({lastSaved:void 0}),vs=()=>Re.useAtom(or),Le=()=>{const[e]=Ie(),s=e.get("page"),[n]=Mn(),{data:a,isFetching:r}=Zt();return{data:f.useMemo(()=>({...m.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},At=()=>{const[e]=Ie(),s=e.get("lang")??"",{data:n,isFetching:a}=He();return{data:f.useMemo(()=>m.find(n,{lang:s})||{},[n,s]),isFetching:a}},cr=Re.atom({}),Mn=()=>Re.useAtom(cr),nt=e=>{const s=js(),n=J();return B.useQuery({queryKey:[Y,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:I.GET_CHAI_USER,data:{userId:e}}),enabled:!m.isEmpty(e)})},ur=Re.atom(void 0),es=()=>{const[e]=Ie(),s=e.get("page"),{user:n}=ze(),[a,r]=Re.useAtom(ur);return f.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])},Vs=()=>{const{data:e}=Ze();return f.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},dr=Re.atom(null),Bn=()=>Re.useAtom(dr),Gn=()=>{const[e]=Bn();return(e==null?void 0:e.slug)||""};function mr(e,s){const[n,a]=f.useState(e);return f.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const hr=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=Q.useLanguages(),{data:r}=Le(),i=r==null?void 0:r.pageType,l=re(),c=J(),{data:u,isFetching:d}=B.useQuery({queryKey:[I.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await c(l,{action:I.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[]}),h=f.useMemo(()=>n===""?u.filter(g=>g.lang===""||g.lang===a):u.filter(g=>g.lang===n),[n,a,u]);return{allLangPages:u,data:h,isFetching:d}},fr=()=>{const{selectedLang:e,fallbackLang:s}=Q.useLanguages(),[n,a]=Bn(),[r,i]=f.useState(""),l=mr(r,500),{allLangPages:c,data:u,isFetching:d}=hr({query:l}),h=f.useCallback(y=>a(y),[a]),g=f.useCallback(y=>i(y),[i]),b=f.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),p=e.length===0,w=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,N=c.filter(C=>(C==null?void 0:C.primaryPage)===w||C.id===w).find(C=>p?C.lang===e||C.lang===s:C.lang===e);a(N||n)},[n,e,c,a,s]);return{isPending:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:c,updateDynamicPage:h,updateSearchQuery:g,onChangeLanguage:b}},On=()=>{const[e]=Ie(),s=e.get("page"),n=re(),{setAiContext:a}=$s(),{setCurrentEditor:r}=es(),[,i]=vs(),[,l]=Mn(),c=J();return B.useQuery({queryKey:[Y,I.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await c(n,{action:I.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=m.find(d,{_type:"@chai/ai-context"});return a(m.get(h,"_value","")||""),i(g=>({...g,lastSaved:u.lastSaved})),l(m.get(u,"metadata",{})),d},enabled:!!s})},Hs=()=>{const{data:e}=Le(),{data:s}=At(),n=re(),a=J(),r=Vs(),i=Gn();return B.useQuery({queryKey:[Y,I.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:I.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})};function gr({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r}){const[i,l]=f.useState(!1),c=()=>{l(!1),r()};return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-[50px] bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.LockIcon,{className:"w-6 h-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"w-12 h-12 border border-gray-300 rounded-full"}):t.jsx(E.UserIcon,{className:"w-12 h-12 p-2 border border-gray-300 rounded-full"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n}),a&&t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",Ct.formatDistanceToNow(new Date(a),{addSuffix:!0})]})]})]}),t.jsx("div",{className:"text-sm mt-4",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(o.CardFooter,{children:t.jsxs(o.AlertDialog,{open:i,onOpenChange:l,children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(o.Button,{className:"w-full",variant:"destructive",children:"Take Over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(o.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(o.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(E.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(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:c,children:"Yes, Take Over"})]})]})]})})]})})}const xr=()=>{const{isLocked:e,currentEditor:s}=es(),{data:n}=nt(s),[a]=Ie(),r=a.get("page"),{mutate:i}=In(),{isFetching:l}=On(),[c]=vs(),u=f.useCallback(()=>{i({id:r})},[r,i]);return!e||l?t.jsx("div",{className:""}):t.jsx(gr,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",lastSaved:(c==null?void 0:c.lastSaved)||"",onTakeOver:u})},pr=()=>{const[e,s]=Ie(),n=e.get("lang"),a=_n(n),{setSelectedLang:r}=Q.useLanguages(),i=()=>{const c=new URLSearchParams(window.location.search);c.delete("lang");const u=c.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(c),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=m.get(Pe,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-12 bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.LockIcon,{className:"w-6 h-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(o.CardFooter,{children:t.jsx(o.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},yr=e=>{const s=re(),n=J();return B.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),W.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},jr=e=>{const s=re(),n=J();return B.useQuery({queryKey:[Y,"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})},vr=e=>{const s=re(),n=J();return B.useMutation({mutationFn:async a=>n(s,{action:I.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),W.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},br=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,c]=f.useState(!1),u=Q.useUpdateBlocksPropsRealtime(),d=vr(()=>{u([e],{_libBlockId:void 0}),W.toast.success("Block deleted successfully"),c(!1),a()}),h=()=>{c(!0),d.mutate(s)},g=t.jsxs(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:l,children:[t.jsx(E.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(o.Popover,{open:n,onOpenChange:b=>!b&&a(),children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:i||g}),t.jsx(o.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},wr=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,c]=f.useState(!1);return t.jsx(br,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{c(!1),i()},blockName:n,trigger:t.jsxs(o.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>c(!0),children:[t.jsx(E.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Sr=()=>{const e=re(),s=J(),n=B.useQueryClient(),{data:a=[],isLoading:r,error:i}=B.useQuery({queryKey:[Y,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:c}=B.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return s(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"library-groups"]}),W.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),W.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:c}},Er=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),l=f.useRef(null),{groups:c}=Sr(),[u,d]=f.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=f.useMemo(()=>[...c,...u.filter(y=>!c.some(p=>p.id===y.id))],[c,u]),g=()=>{const y=r.trim();if(!y)return;const p={id:y,name:y};d(w=>[...w,p]),s(p.id),i(""),a(!1)};f.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const b=y=>{y.key==="Enter"&&(y.preventDefault(),g())};return f.useEffect(()=>{e&&!h.some(y=>y.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:b}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(o.Button,{size:"sm",onClick:g,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),c.length>0&&t.jsx("optgroup",{label:"Library Groups",children:c.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=>!c.some(p=>p.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(o.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(E.Plus,{className:"h-4 w-4"})})]})},Nr=10*1024*1024,Cr=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),r=f.useRef(null),i=f.useCallback(u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d){if(d.size>Nr){W.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const g=new FileReader;g.onloadend=()=>{s(g.result),a(!1)},g.readAsDataURL(d)}catch(g){console.error("Error reading file:",g),a(!1),W.toast.error("Failed to process image",{description:g instanceof Error?g.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},c=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:c,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(E.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"})})]})},je={...Q.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"},Ar=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=Q.usePartailBlocksStore(),i=s.find(A=>A._id===a),l=i==null?void 0:i._libBlockId,c=!!l,u=f.useMemo(()=>s.some(A=>A._type==="PartialBlock"||A._type==="GlobalBlock"),[s]),d=f.useMemo(()=>{let A=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let O=r(M.partialBlockId);M._parent&&(O==null?void 0:O.length)>0&&(O=O.map(T=>(m.isEmpty(T._parent)&&m.set(T,"_parent",M._parent),T))),A=[...A,...O]}else A.push(M);return A},[s,r]),[h,g]=f.useState(""),[b,y]=f.useState(""),[p,w]=f.useState(""),[v,N]=f.useState(""),[C,_]=f.useState({}),[S,P]=f.useState(!1),[G,q]=f.useState(c),[z,se]=f.useState(!1),{hasPermission:$}=Q.usePermissions(),V=$(je.DELETE_LIBRARY_BLOCK),te=Q.useUpdateBlocksPropsRealtime(),H=()=>{te([a],{_libBlockId:void 0}),W.toast.success("Block delinked from library"),n()},{data:ne,isLoading:D,isError:U}=jr(l);f.useEffect(()=>{U&&c&&(se(!0),q(!1))},[U,c]),f.useEffect(()=>{ne&&!D&&(g(ne.name||""),y(ne.group||""),w(ne.description||""),N(ne.preview||""),q(!1))},[ne,D]),f.useEffect(()=>{const A=h.trim().length>=2,M=b.trim()!=="";P(A&&M)},[h,b]);const he=()=>{const A={};return h.trim()?h.length<2&&(A.name="Name must be at least 2 characters"):A.name="Name is required",b||(A.group="Group is required"),_(A),Object.keys(A).length===0},{resetLibrary:ye}=Q.useLibraryBlocks({id:""}),ce=yr(A=>{c||te([a],{_libBlockId:A.id}),W.toast.success(`Block ${c?"updated":"saved"} successfully`),ye(A.library),n()}),j=async A=>{if(A.preventDefault(),!he())return;const M=d.map(O=>(m.has(O,"_libBlockId")&&delete O._libBlockId,O));ce.mutate({name:h.trim(),group:b,blocks:M,description:p.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...c?{id:l}:{}})},x=ce.isPending;return G||D?t.jsx("div",{className:"flex items-center justify-center p-8",children:t.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):z?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(o.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(o.Button,{onClick:H,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(E.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:C.name?"text-destructive":"",children:"Name"}),t.jsx(o.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:A=>g(A.target.value),className:C.name?"border-destructive":""}),C.name&&t.jsx("p",{className:"text-xs text-destructive",children:C.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"group",className:C.group?"text-destructive":"",children:"Group"}),t.jsx(Er,{value:b,onChange:y}),C.group&&t.jsx("p",{className:"text-xs text-destructive",children:C.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(o.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:A=>w(A.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Cr,{value:v,onChange:N})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[c&&V&&t.jsx(wr,{blockId:a,libBlockId:l,blockName:h,className:"mr-auto",close:n}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:n,disabled:x,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:x||!S,children:x?"Saving...":c?"Update Block":"Save Block"})]})]})]})},ae={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."},Tr={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Te=()=>{const e=re(),s=J();return B.useQuery({queryKey:[Y,I.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:I.GET_PAGE_TYPES})})},Rn=e=>{const{data:s}=Te();return f.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Pr=()=>{const e=re(),s=J();return B.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),[]}}})},Un=()=>{const e=re(),s=B.useQueryClient(),n=J(),{data:a}=Te();return B.useMutation({mutationFn:async r=>await n(e,{action:I.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var c;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((c=m.find(a,{key:i.pageType}))==null?void 0:c.name)+" added successfully":"New page added successfully";W.toast.success(l)},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});W.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:m.get(Tr,r.message,r.message)})}})},Ks=()=>{const e=re(),s=B.useQueryClient(),n=J(),{data:a}=Te();return B.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:[Y,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});W.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},kr=()=>{const e=re(),s=B.useQueryClient(),n=J(),{data:a}=Te();return B.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"){W.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});W.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Ir=()=>{const e=re(),s=B.useQueryClient(),n=J(),{data:a}=Te();return B.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:[Y,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]});const l=m.find(a,{key:i.pageType});W.toast.success(l!=null&&l.hasSlug?ae.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});W.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Ws=()=>{const e=re(),s=J(),n=B.useQueryClient(),{data:a}=Le();return B.useMutation({mutationFn:async({ids:r})=>s(e,{action:I.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,I.GET_CHANGES]}),n.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[Y,I.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{W.toast.error("Failed to publish pages.")}})},Lr=()=>{const e=re(),s=J(),n=B.useQueryClient();return B.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:[Y,I.GET_WEBSITE_PAGES]}),W.toast.success("Page marked as template successfully.")},onError:()=>{W.toast.error("Failed to mark page as template.")}})},Dr=()=>{const e=re(),s=J(),n=B.useQueryClient();return B.useMutation({mutationFn:async a=>s(e,{action:I.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]}),W.toast.success("Page unmarked as template successfully.")},onError:()=>{W.toast.error("Failed to unmark page as template.")}})},_r=()=>{const e=re(),s=J(),n=B.useQueryClient();return B.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:I.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{W.toast.success(ae.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[Y,I.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]})},onError:()=>{W.toast.error("Failed to change slug")}})};var Qs={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",c=function(){if(!s.OffscreenCanvas)return!1;var j=new OffscreenCanvas(1,1),x=j.getContext("2d");x.fillRect(0,0,1,1);var A=j.transferToImageBitmap();try{x.createPattern(A,"no-repeat")}catch{return!1}return!0}();function u(){}function d(j){var x=n.exports.Promise,A=x!==void 0?x:s.Promise;return typeof A=="function"?new A(j):(j(u,u),null)}var h=function(j,x){return{transform:function(A){if(j)return A;if(x.has(A))return x.get(A);var M=new OffscreenCanvas(A.width,A.height),O=M.getContext("2d");return O.drawImage(A,0,0),x.set(A,M),M},clear:function(){x.clear()}}}(c,new Map),g=function(){var j=Math.floor(16.666666666666668),x,A,M={},O=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(x=function(T){var K=Math.random();return M[K]=requestAnimationFrame(function F(Z){O===Z||O+j-1<Z?(O=Z,delete M[K],T()):M[K]=requestAnimationFrame(F)}),K},A=function(T){M[T]&&cancelAnimationFrame(M[T])}):(x=function(T){return setTimeout(T,j)},A=function(T){return clearTimeout(T)}),{frame:x,cancel:A}}(),b=function(){var j,x,A={};function M(O){function T(K,F){O.postMessage({options:K||{},callback:F})}O.init=function(F){var Z=F.transferControlToOffscreen();O.postMessage({canvas:Z},[Z])},O.fire=function(F,Z,de){if(x)return T(F,null),x;var ve=Math.random().toString(36).slice(2);return x=d(function(oe){function R(be){be.data.callback===ve&&(delete A[ve],O.removeEventListener("message",R),x=null,h.clear(),de(),oe())}O.addEventListener("message",R),T(F,ve),A[ve]=R.bind(null,{data:{callback:ve}})}),x},O.reset=function(){O.postMessage({reset:!0});for(var F in A)A[F](),delete A[F]}}return function(){if(j)return j;if(!a&&i){var O=["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([O])))}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,x){return x?x(j):j}function w(j){return j!=null}function v(j,x,A){return p(j&&w(j[x])?j[x]:y[x],A)}function N(j){return j<0?0:Math.floor(j)}function C(j,x){return Math.floor(Math.random()*(x-j))+j}function _(j){return parseInt(j,16)}function S(j){return j.map(P)}function P(j){var x=String(j).replace(/[^0-9a-f]/gi,"");return x.length<6&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:_(x.substring(0,2)),g:_(x.substring(2,4)),b:_(x.substring(4,6))}}function G(j){var x=v(j,"origin",Object);return x.x=v(x,"x",Number),x.y=v(x,"y",Number),x}function q(j){j.width=document.documentElement.clientWidth,j.height=document.documentElement.clientHeight}function z(j){var x=j.getBoundingClientRect();j.width=x.width,j.height=x.height}function se(j){var x=document.createElement("canvas");return x.style.position="fixed",x.style.top="0px",x.style.left="0px",x.style.pointerEvents="none",x.style.zIndex=j,x}function $(j,x,A,M,O,T,K,F,Z){j.save(),j.translate(x,A),j.rotate(T),j.scale(M,O),j.arc(0,0,1,K,F,Z),j.restore()}function V(j){var x=j.angle*(Math.PI/180),A=j.spread*(Math.PI/180);return{x:j.x,y:j.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:j.startVelocity*.5+Math.random()*j.startVelocity,angle2D:-x+(.5*A-Math.random()*A),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:j.color,shape:j.shape,tick:0,totalTicks:j.ticks,decay:j.decay,drift:j.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:j.gravity*3,ovalScalar:.6,scalar:j.scalar,flat:j.flat}}function te(j,x){x.x+=Math.cos(x.angle2D)*x.velocity+x.drift,x.y+=Math.sin(x.angle2D)*x.velocity+x.gravity,x.velocity*=x.decay,x.flat?(x.wobble=0,x.wobbleX=x.x+10*x.scalar,x.wobbleY=x.y+10*x.scalar,x.tiltSin=0,x.tiltCos=0,x.random=1):(x.wobble+=x.wobbleSpeed,x.wobbleX=x.x+10*x.scalar*Math.cos(x.wobble),x.wobbleY=x.y+10*x.scalar*Math.sin(x.wobble),x.tiltAngle+=.1,x.tiltSin=Math.sin(x.tiltAngle),x.tiltCos=Math.cos(x.tiltAngle),x.random=Math.random()+2);var A=x.tick++/x.totalTicks,M=x.x+x.random*x.tiltCos,O=x.y+x.random*x.tiltSin,T=x.wobbleX+x.random*x.tiltCos,K=x.wobbleY+x.random*x.tiltSin;if(j.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-A)+")",j.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))j.fill(he(x.shape.path,x.shape.matrix,x.x,x.y,Math.abs(T-M)*.1,Math.abs(K-O)*.1,Math.PI/10*x.wobble));else if(x.shape.type==="bitmap"){var F=Math.PI/10*x.wobble,Z=Math.abs(T-M)*.1,de=Math.abs(K-O)*.1,ve=x.shape.bitmap.width*x.scalar,oe=x.shape.bitmap.height*x.scalar,R=new DOMMatrix([Math.cos(F)*Z,Math.sin(F)*Z,-Math.sin(F)*de,Math.cos(F)*de,x.x,x.y]);R.multiplySelf(new DOMMatrix(x.shape.matrix));var be=j.createPattern(h.transform(x.shape.bitmap),"no-repeat");be.setTransform(R),j.globalAlpha=1-A,j.fillStyle=be,j.fillRect(x.x-ve/2,x.y-oe/2,ve,oe),j.globalAlpha=1}else if(x.shape==="circle")j.ellipse?j.ellipse(x.x,x.y,Math.abs(T-M)*x.ovalScalar,Math.abs(K-O)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI):$(j,x.x,x.y,Math.abs(T-M)*x.ovalScalar,Math.abs(K-O)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI);else if(x.shape==="star")for(var ie=Math.PI/2*3,Ne=4*x.scalar,De=8*x.scalar,L=x.x,le=x.y,Ee=5,Oe=Math.PI/Ee;Ee--;)L=x.x+Math.cos(ie)*De,le=x.y+Math.sin(ie)*De,j.lineTo(L,le),ie+=Oe,L=x.x+Math.cos(ie)*Ne,le=x.y+Math.sin(ie)*Ne,j.lineTo(L,le),ie+=Oe;else j.moveTo(Math.floor(x.x),Math.floor(x.y)),j.lineTo(Math.floor(x.wobbleX),Math.floor(O)),j.lineTo(Math.floor(T),Math.floor(K)),j.lineTo(Math.floor(M),Math.floor(x.wobbleY));return j.closePath(),j.fill(),x.tick<x.totalTicks}function H(j,x,A,M,O){var T=x.slice(),K=j.getContext("2d"),F,Z,de=d(function(ve){function oe(){F=Z=null,K.clearRect(0,0,M.width,M.height),h.clear(),O(),ve()}function R(){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&&(A(j),M.width=j.width,M.height=j.height),K.clearRect(0,0,M.width,M.height),T=T.filter(function(be){return te(K,be)}),T.length?F=g.frame(R):oe()}F=g.frame(R),Z=oe});return{addFettis:function(ve){return T=T.concat(ve),de},canvas:j,promise:de,reset:function(){F&&g.cancel(F),Z&&Z()}}}function ne(j,x){var A=!j,M=!!v(x||{},"resize"),O=!1,T=v(x,"disableForReducedMotion",Boolean),K=i&&!!v(x||{},"useWorker"),F=K?b():null,Z=A?q:z,de=j&&F?!!j.__confetti_initialized:!1,ve=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,oe;function R(ie,Ne,De){for(var L=v(ie,"particleCount",N),le=v(ie,"angle",Number),Ee=v(ie,"spread",Number),Oe=v(ie,"startVelocity",Number),Ns=v(ie,"decay",Number),Cs=v(ie,"gravity",Number),ts=v(ie,"drift",Number),rt=v(ie,"colors",S),it=v(ie,"ticks",Number),Pt=v(ie,"shapes"),ss=v(ie,"scalar"),k=!!v(ie,"flat"),ue=G(ie),Me=L,Ce=[],Be=j.width*ue.x,Ue=j.height*ue.y;Me--;)Ce.push(V({x:Be,y:Ue,angle:le,spread:Ee,startVelocity:Oe,color:rt[Me%rt.length],shape:Pt[C(0,Pt.length)],ticks:it,decay:Ns,gravity:Cs,drift:ts,scalar:ss,flat:k}));return oe?oe.addFettis(Ce):(oe=H(j,Ce,Z,Ne,De),oe.promise)}function be(ie){var Ne=T||v(ie,"disableForReducedMotion",Boolean),De=v(ie,"zIndex",Number);if(Ne&&ve)return d(function(Oe){Oe()});A&&oe?j=oe.canvas:A&&!j&&(j=se(De),document.body.appendChild(j)),M&&!de&&Z(j);var L={width:j.width,height:j.height};F&&!de&&F.init(j),de=!0,F&&(j.__confetti_initialized=!0);function le(){if(F){var Oe={getBoundingClientRect:function(){if(!A)return j.getBoundingClientRect()}};Z(Oe),F.postMessage({resize:{width:Oe.width,height:Oe.height}});return}L.width=L.height=null}function Ee(){oe=null,M&&(O=!1,s.removeEventListener("resize",le)),A&&j&&(document.body.contains(j)&&document.body.removeChild(j),j=null,de=!1)}return M&&!O&&(O=!0,s.addEventListener("resize",le,!1)),F?F.fire(ie,L,Ee):R(ie,L,Ee)}return be.reset=function(){F&&F.reset(),oe&&oe.reset()},be}var D;function U(){return D||(D=ne(null,{useWorker:!0,resize:!0})),D}function he(j,x,A,M,O,T,K){var F=new Path2D(j),Z=new Path2D;Z.addPath(F,new DOMMatrix(x));var de=new Path2D;return de.addPath(Z,new DOMMatrix([Math.cos(K)*O,Math.sin(K)*O,-Math.sin(K)*T,Math.cos(K)*T,A,M])),de}function ye(j){if(!l)throw new Error("path confetti are not supported in this browser");var x,A;typeof j=="string"?x=j:(x=j.path,A=j.matrix);var M=new Path2D(x),O=document.createElement("canvas"),T=O.getContext("2d");if(!A){for(var K=1e3,F=K,Z=K,de=0,ve=0,oe,R,be=0;be<K;be+=2)for(var ie=0;ie<K;ie+=2)T.isPointInPath(M,be,ie,"nonzero")&&(F=Math.min(F,be),Z=Math.min(Z,ie),de=Math.max(de,be),ve=Math.max(ve,ie));oe=de-F,R=ve-Z;var Ne=10,De=Math.min(Ne/oe,Ne/R);A=[De,0,0,De,-Math.round(oe/2+F)*De,-Math.round(R/2+Z)*De]}return{type:"path",path:x,matrix:A}}function ce(j){var x,A=1,M="#000000",O='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof j=="string"?x=j:(x=j.text,A="scalar"in j?j.scalar:A,O="fontFamily"in j?j.fontFamily:O,M="color"in j?j.color:M);var T=10*A,K=""+T+"px "+O,F=new OffscreenCanvas(T,T),Z=F.getContext("2d");Z.font=K;var de=Z.measureText(x),ve=Math.ceil(de.actualBoundingBoxRight+de.actualBoundingBoxLeft),oe=Math.ceil(de.actualBoundingBoxAscent+de.actualBoundingBoxDescent),R=2,be=de.actualBoundingBoxLeft+R,ie=de.actualBoundingBoxAscent+R;ve+=R+R,oe+=R+R,F=new OffscreenCanvas(ve,oe),Z=F.getContext("2d"),Z.font=K,Z.fillStyle=M,Z.fillText(x,be,ie);var Ne=1/A;return{type:"bitmap",bitmap:F.transferToImageBitmap(),matrix:[Ne,0,0,Ne,-ve*Ne/2,-oe*Ne/2]}}n.exports=function(){return U().apply(this,arguments)},n.exports.reset=function(){U().reset()},n.exports.create=ne,n.exports.shapeFromPath=ye,n.exports.shapeFromText=ce})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Qs,!1);const Mr=Qs.exports;Qs.exports.create;const Br={particleCount:350,spread:120,origin:{y:.6},angle:90},Gr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},_t=e=>{let s=Gr[e];s||(s={});const n={...Br,...s};Mr(n)},Or=()=>{const[e]=Q.useTheme(),{mutate:s,isPending:n}=Ws(),{mutateAsync:a,isPending:r}=Ln(),i=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{_t("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(o.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(o.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},Rr=({page:e,onClose:s})=>{const[n,a]=f.useState(e.slug||""),{mutate:r,isPending:i}=_r(),{data:l}=Te(),c=m.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Pe).some(y=>n===`/${y}`||m.startsWith(n,`/${y}/`))){W.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Change Slug"}),t.jsx(o.DialogDescription,{className:"text-xs",children:t.jsxs(o.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(E.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(c==null?void 0:c.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(o.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(o.Input,{id:"slug",value:n,onChange:h=>{const g=h.target.value;m.startsWith(g,`/${d}`)&&a(g)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(o.DialogFooter,{children:t.jsx(o.Button,{type:"submit",disabled:i||!m.startsWith(n,`/${d}`)||m.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})};function Ys({page:e,onClose:s}){const[,n]=Ie(),{mutate:a,isPending:r}=kr(),{data:i}=Te(),{setSelectedLang:l,fallbackLang:c}=Q.useLanguages(),[,u]=Q.useSidebarActivePanel(),d=()=>{r||a(e,{onSuccess:()=>{e!=null&&e.primaryPage?(window.history.replaceState({},"",`/?page=${e.primaryPage}`),n(new URLSearchParams({page:e.primaryPage}))):(window.history.replaceState({},"","/"),n(new URLSearchParams)),window.dispatchEvent(new PopStateEvent("popstate")),l(c),u("outline"),s()}})},h=i==null?void 0:i.find(g=>g.key===(e==null?void 0:e.pageType));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(o.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",h!=null&&h.hasSlug?(h==null?void 0:h.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:m.get(Pe,e.lang,e.lang)})]})]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:r,onClick:d,children:r?"Deleting...":"Delete"})]})]})})}const Ge=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=Q.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},bs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Ir(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm action"}),t.jsxs(o.DialogDescription,{children:[ae.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:a,onClick:r,children:a?ae.UPDATING:ae.UNPUBLISH})]})]})})},Ur=e=>{if(!e)return{base:e,extension:null};const s=e.lastIndexOf(".");if(s<=0)return{base:e,extension:null};const n=e.substring(s);return{base:e.substring(0,s),extension:n}},Ve=e=>{if(!e)return e;const{base:s}=Ur(e);return s},Fr=e=>e&&Ve(e),cn=(e,s)=>{const n=Ve(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function Js({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[c,u]=f.useState(e),[d,h]=f.useState(null);f.useEffect(()=>{u(e)},[e]);const g=b=>{const p=b.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),w=(p.match(/\./g)||[]).length,v=w<=1;w>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(v),u(p),s(p)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"flex items-center mb-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:Fr(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{disabled:i,value:c,onChange:g,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:d})]}),l&&t.jsx("div",{className:"flex items-center mt-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const Fn=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Le(),r=a==null?void 0:a.dynamic,{data:i}=Te(),[l,c]=f.useState(e.name||""),[u,d]=f.useState(e.edit?e.lang:""),[h,g]=f.useState(e.edit?e.slug:""),[b,y]=f.useState(!0),[p,w]=f.useState(!0),{mutate:v,isPending:N}=Un(),{mutate:C,isPending:_}=Ks(),{data:S}=He(a==null?void 0:a.parent),{setSelectedLang:P,fallbackLang:G}=Q.useLanguages(),[,q]=Ie(),[,z]=Q.useSidebarActivePanel(),se=f.useMemo(()=>i==null?void 0:i.find(j=>j.key===e.pageType),[i,e.pageType]),$=r||!(se!=null&&se.hasSlug),V=(a==null?void 0:a.slug)==="/",te=N||_,{parentSlug:H,isRootPage:ne}=f.useMemo(()=>{if(V||!u)return{parentSlug:void 0,isRootPage:!(a!=null&&a.parent)};if(!(a!=null&&a.parent))return{parentSlug:p?`/${u}`:void 0,isRootPage:!(a!=null&&a.parent)};const j=S==null?void 0:S.find(x=>x.lang===u);return{parentSlug:j==null?void 0:j.slug,isRootPage:!1}},[a==null?void 0:a.parent,S,p,u,V]);f.useEffect(()=>{if(!e.edit)return;const x=(e.slug||"").split("/").filter(Boolean);let A="";const M=O=>w(O);if(V){const O=x.pop()||"";if(Pe[O])M(!0);else{A=O;const T=x.pop()||"";M(!!Pe[T])}}else if(ne){if(x.length){A=x.pop()||"";const O=x.pop()||"";M(!!Pe[O])}}else x.length&&(A=x.pop()||"");g(A)},[e,V,ne]);const D=f.useMemo(()=>ne?!0:!!(S!=null&&S.find(j=>(j==null?void 0:j.lang)===u)),[u,S,ne]),U=()=>{let j="";return ne?j=`/${p?[u,h].filter(Boolean).join("/"):h}`:j=`${Ve(H)}/${h}`,j.replace(/\/{2,}/g,"/").replace(/\/$/,"")},he=(j,x)=>{const A=new URLSearchParams(window.location.search);x&&j===x?A.delete("lang"):A.set("lang",j);const M=A.toString(),O=`${window.location.pathname}${M?`?${M}`:""}`;window.history.pushState({},"",O),q(A),window.dispatchEvent(new PopStateEvent("popstate"))},ye=j=>{j.preventDefault();const x={name:l,lang:u,primaryPage:a==null?void 0:a.id,slug:U(),pageType:a==null?void 0:a.pageType,tracking:{}};x.pageType=e.pageType,e.edit&&(x.id=e==null?void 0:e.id),e.edit?C(x,{onSuccess:s}):v(x,{onSuccess:()=>{u&&(P(u),he(u,G)),z("outline"),s()}})},ce=te||m.isEmpty(l)||m.isEmpty(u)||($||V&&p?!1:!b||m.isEmpty(h));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:e.edit?ae.EDIT_LANGUAGE:ae.ADD_NEW_LANGUAGE}),t.jsx(o.DialogDescription,{className:"font-light",children:ae.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:ye,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"lang",className:"text-right",children:ae.LANGUAGE}),t.jsxs("select",{value:u,disabled:e.edit||m.isEmpty(n),onChange:j=>{const x=j.target.value;d(x),!e.edit&&m.startsWith(l,e.name)&&c(`${e.name} - ${Pe[x]}`)},className:"flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 col-span-3",children:[t.jsx("option",{value:"",disabled:!0,selected:!0,children:e.edit?m.get(Pe,e.lang,e.lang):m.isEmpty(n)?ae.ALL_AVAILABLE_LANGUAGE_PAGE:ae.CHOOSE_LANGUAGE}),m.map(n,j=>t.jsx("option",{value:j,children:m.get(Pe,j,j)},j))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-right",children:ae.PAGE_NAME}),t.jsx(o.Input,{id:"name",value:u?l:"",onChange:j=>c(j.target.value),className:"col-span-3",required:!0,placeholder:u?ae.ENTER_PAGE_NAME:ae.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!D||!u})]}),!$&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"space-y-1",children:[ne&&u&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:p,onChange:j=>w(j.target.checked),className:"rounded border-gray-300"}),t.jsxs(o.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",u]}),") as slug prefix"]})]}),t.jsxs(o.Label,{htmlFor:"slug",className:"text-right",children:[ae.SLUG," "]}),t.jsx(Js,{disabled:m.isEmpty(u)||!D,value:h,onChange:g,placeholder:m.isEmpty(u)?ae.CHOOSE_LANGUAGE_TO_ADD_SLUG:V&&p?"Leave empty for home page":ae.ENTER_PAGE_SLUG,parentSlug:H,onValidationChange:y,fullSlug:ce?"":U()})]})}),r&&u&&D&&t.jsxs("p",{className:"text-sm pb-2",children:[t.jsx(o.Label,{children:"Dynamic Slug: "})," ",t.jsx("span",{className:"font-mono font-light",children:`${Ve(H)}/${se==null?void 0:se.dynamicSlug}`})]})]}),t.jsx(o.DialogFooter,{children:D?t.jsx(o.Button,{type:"submit",disabled:ce,children:te?e.edit?ae.UPDATING:ae.ADDING:e.edit?ae.UPDATE:ae.ADD_NEW_LANGUAGE}):u&&t.jsx(o.Alert,{variant:"destructive",children:t.jsxs("p",{className:"text-center w-5/6 mx-auto",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:Pe[u]})," page in the parent to add here."]})})})]})]})})},qr=()=>{const[e,s]=f.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:r}=Q.useLanguages(),{data:i,isFetching:l}=He(),{data:c}=Le(),{data:u}=Te(),d=f.useMemo(()=>{const C=u==null?void 0:u.find(_=>_.key===(c==null?void 0:c.pageType));return C==null?void 0:C.dynamicSlug},[u,c==null?void 0:c.pageType]),[h,g]=f.useState(null),[b,y]=f.useState(null),[p,w]=f.useState(null),{data:v}=Ze(),N=m.filter(m.get(v,"languages")||["en"],C=>!m.find(i,{lang:C})&&C!==m.get(v,"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"})]}):m.map(i,C=>{const _=C.lang,S=C.slug,P=!C.primaryPage,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 ${G?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>r(_),children:[t.jsxs("div",{className:" flex-1 gap-x-3",children:[t.jsxs("div",{className:"text-[13px] text-slate-800 flex items-center gap-x-2",children:[t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${C.online?"bg-green-300":"bg-gray-300"}`}),m.get(Pe,P?a:_,_)]}),t.jsxs("div",{children:[S&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium font-mono",children:d?`${S}/${d}`:S})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",C.name," "]})]})]})]}),P?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(E.StarIcon,{fill:"orange",className:"w-3 h-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(Ge,{permissions:[je.EDIT_PAGE,je.DELETE_PAGE,je.UNPUBLISH_PAGE],children:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:q=>q.stopPropagation(),children:t.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(E.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[t.jsx(Ge,{permissions:[je.EDIT_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:q=>{q.stopPropagation(),s({...C,edit:!0})},children:[t.jsx(E.PencilIcon,{className:"size-3"}),ae.EDIT]})}),t.jsx(Ge,{permissions:[je.UNPUBLISH_PAGE],children:(C==null?void 0:C.online)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:q=>{q.stopPropagation(),y(C)},children:[t.jsx(E.Power,{className:"size-3"}),ae.UNPUBLISH]})}),t.jsx(Ge,{permissions:[je.DELETE_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:q=>{q.stopPropagation(),g(C)},children:[t.jsx(E.TrashIcon,{className:"size-3"}),ae.DELETE]})})]})]})})})]},C.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Ge,{permissions:[je.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(o.Button,{variant:"default",size:"sm",disabled:m.isEmpty(N),onClick:()=>{s({name:c==null?void 0:c.name,pageType:c==null?void 0:c.pageType,lang:"",slug:"",edit:!1})},children:ae.ADD_NEW_LANGUAGE})})}),e&&t.jsx(Fn,{languages:N,langProps:e,onClose:()=>s(null)}),h&&t.jsx(Ys,{page:h,onClose:()=>g(null)}),b&&t.jsx(bs,{page:b,onClose:()=>y(null)}),p&&t.jsx(Rr,{page:p,onClose:()=>w(null)})]})};function zr({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=f.useState(null),c=f.useRef(null),[u,d]=f.useState(a+e);f.useEffect(()=>{d(a+e)},[e,a]);const h=y=>{const p=y.target.value;if(!p.startsWith(a)){const S=p.replace(a,""),P=a+S;d(P),s(S);return}const v=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),N=(v.match(/\./g)||[]).length,C=N<=1;N>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(C);const _=a+v;d(_),s(v)},g=()=>{if(c.current){const y=c.current;setTimeout(()=>{const p=a.length;y.setSelectionRange(p,p)},0)}},b=y=>{const p=y.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const v=a.length;p.setSelectionRange(v,v)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(o.Input,{ref:c,value:u,onChange:h,onFocus:g,onClick:b,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const cs=({children:e,onWheel:s,...n})=>{const a=r=>{try{r.preventDefault();const i=r.currentTarget;i.scrollTop+=r.deltaY}catch{r.preventDefault()}s&&s(r)};return t.jsx(o.CommandList,{...n,onWheel:a,children:e})},As=(...e)=>e.filter(Boolean).join(" ");function $r({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage"}){const[i,l]=f.useState(!1),[c,u]=f.useState(""),d=f.useMemo(()=>!e||e.length===0?[]:e.filter(v=>!m.isEmpty(v.slug)).filter(v=>v.slug!=="/").sort((v,N)=>v.slug.localeCompare(N.slug)),[e]),h=f.useMemo(()=>{if(!c.trim())return d;const w=c.toLowerCase();return d.filter(v=>v.name.toLowerCase().includes(w)||v.slug.toLowerCase().includes(w))},[d,c]),g=w=>Math.max(0,(w.match(/\//g)||[]).length-1),b=w=>"    ".repeat(w),y=w=>{if(w==="/")return"/";const v=w.split("/").filter(Boolean);if(v.length<=1){const N=v[0]||"";return`/${Ve(N)}`}return`/${Ve(v[v.length-1])}`},p=()=>{if(!s||s==="none")return"None";const w=d.find(v=>v.id===s);return w?`${w.name} (${y(w.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),t.jsxs(o.Popover,{open:i,onOpenChange:l,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{id:r,variant:"outline",role:"combobox",className:As("w-full justify-between",a),"data-testid":"parent-page-selector",children:[p(),t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"relative border-none py-2",children:t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search pages...",className:"h-8 pl-8 text-xs",value:c,onChange:w=>u(w.target.value)})]})})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No pages found."}),t.jsxs(o.CommandGroup,{children:[t.jsxs(o.CommandItem,{value:"none",onSelect:()=>{n(""),l(!1),u("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(E.Check,{className:As("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),h.map(w=>{const v=b(g(w.slug)),N=y(w.slug),C=t.jsxs("span",{className:"flex items-center text-sm",children:[v,w.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",N,")"]})]});return t.jsxs(o.CommandItem,{value:w.id,onSelect:()=>{n(w.id),l(!1),u("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:C}),t.jsx(E.Check,{className:As("mr-2 h-4 w-4 shrink-0",s===w.id?"opacity-100":"opacity-0")})]},w.id)})]})]})]})})]})]})}const Vr=(...e)=>e.filter(Boolean).join(" "),Hr=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=f.useState(""),[l,c]=f.useState(!1),[u,d]=f.useState("");if(f.useEffect(()=>{if(s){const p=e.find(w=>w.id===s);i((p==null?void 0:p.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex h-fit items-center justify-center text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const h={};e.forEach(p=>{const w=p.libraryName;h[w]||(h[w]=[]),h[w].push(p)});const g=Object.entries(h).reduce((p,[w,v])=>{const N=v.filter(C=>C.name.toLowerCase().includes(u.toLowerCase())||w.toLowerCase().includes(u.toLowerCase()));return N.length>0&&(p[w]=N),p},{}),b=e.find(p=>p.id===s),y=b?m.startCase(b.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[t.jsxs(o.Popover,{open:l,onOpenChange:c,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[y,t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search templates...",className:"h-8 pl-8 text-xs",value:u,onChange:p=>d(p.target.value)})]})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No templates found."}),Object.entries(g).map(([p,w])=>t.jsx(o.CommandGroup,{heading:p,children:w.map(v=>t.jsxs(o.CommandItem,{value:v.id,onSelect:()=>{n(v.id),c(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[m.startCase(v.name),t.jsx(E.Check,{className:Vr("mr-2 h-4 w-4",s===v.id?"opacity-100":"opacity-0")})]},v.id))},p))]})]})})]}),r&&t.jsxs("div",{className:"mt-3 overflow-hidden rounded border",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:r,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"border-t bg-gray-50 p-2 text-xs text-gray-500",children:"Template preview"})]})]})},Kr=()=>{const e=re(),s=J();return B.useQuery({queryKey:[Y,I.GET_LIBRARIES],queryFn:async()=>await s(e,{action:I.GET_LIBRARIES})||[]})},Wr=e=>{const s=re(),n=J();return B.useQuery({queryKey:[Y,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?m.filter(a,{pageType:e}):a)||[]}})},Qr=e=>{const{data:s=[],isLoading:n}=Wr(e),{data:a=[],isLoading:r}=Kr(),i=f.useMemo(()=>n||r?[]:s.map(c=>{const u=m.find(a,{id:c.library});return{...c,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=f.useMemo(()=>m.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},Xs=()=>{const[,e]=Ie();return f.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},us=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:""},jsonLD:{}};e!=null&&e.defaultSeo&&(m.has(e.defaultSeo,s)&&m.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};return e!=null&&e.defaultJSONLD&&(m.has(e.defaultJSONLD,s)&&m.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],m.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,m.set(n,"seo.jsonLD",JSON.stringify(a)))),{seo:n.seo,jsonLD:a}},et=(...e)=>e.filter(Boolean).join(" ");function Yr({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var Pt,ss;const r=Xs(),i=!!(e!=null&&e.id),{data:l}=Zt(),{mutate:c,isPending:u}=Un(),{mutate:d,isPending:h}=Ks(),[g,b]=f.useState(null),[y,p]=f.useState(!0),[w,v]=f.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:N}=Q.usePermissions(),C=N(je.CHANGE_PAGE_TYPE),[_,S]=f.useState(!1),[P,G]=f.useState(""),{selectedLang:q,fallbackLang:z}=Q.useLanguages(),se=q||z,[$,V]=f.useState(""),[te,H]=f.useState(!1),ne=f.useMemo(()=>{const k=s.find(ue=>ue.key===w);return(k==null?void 0:k.hasSlug)===!1},[w,s]),[D,U]=f.useState((e==null?void 0:e.parent)??""),[he,ye]=f.useState((e==null?void 0:e.name)??""),[ce,j]=f.useState((e==null?void 0:e.dynamic)??!1),[x,A]=f.useState(ce?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[M,O]=f.useState((e==null?void 0:e.dynamicSlugCustom)??""),[T,K]=f.useState(!0),[F,Z]=f.useState(""),{data:de,isLoading:ve}=Qr(w),oe=u||h,R=s.find(k=>k.key===w),be=k=>{if(i&&w!==k){G(k),S(!0),V(""),H(!1);return}v(k),V(""),H(!1)},ie=()=>{v(P),S(!1),j(!1)},Ne=k=>{j(k),k?A(""):O("")},De=k=>{if(U(k),k&&k!=="none"){const ue=l==null?void 0:l.find(Ce=>Ce.id===k),Me=(ue==null?void 0:ue.slug)||"";if(x.startsWith(Me)){const Ce=x.slice(Me.length).replace(/^\/+/,"");A(Ce)}else A(x.replace(/^\/+/,""))}else A(x?`${x}`:"")},L=k=>{Z(k)},le=()=>he.trim()?ce&&!m.isEmpty(x)?(b("Slug must be empty when using dynamic slug"),!1):ce&&!T?(b("Dynamic slug is invalid"),!1):!0:(W.toast.error("Name is required"),!1),Ee=()=>{const k={pageType:R==null?void 0:R.key,name:he,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:he},{onSuccess:()=>{W.toast.success((R==null?void 0:R.name)+" updated successfully"),n()}}):c(k,{onSuccess:ue=>{n(),r(ue.page.id,a)}})},Oe=(k,ue)=>{if(!k.trim()&&!ce)return b("Child page slug is required"),!1;const Me=Ve(ue),Ce=cn(Me,k);return Object.keys(Pe).some(ns=>Ce===`/${ns}`||(Ce==null?void 0:Ce.startsWith(`/${ns}/`)))?(b("Slugs cannot start with a language code for primary page"),!1):!0},Ns=(k,ue)=>{const Me=Ve(ue),Ce=cn(Me,k),Be={pageType:w,name:he,slug:Ce.replace(/\/$/,""),parent:D,dynamic:ce,hasSlug:!0,template:F||void 0,tracking:{},seo:{},jsonLD:{}};if(ce&&(Be.dynamicSlugCustom=M),i)d({id:e==null?void 0:e.id,...Be},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}});else{const Ue=m.find(s,{key:w});Ue!=null&&Ue.trackingDefault&&(Be.tracking=Ue.trackingDefault);const{seo:ns,jsonLD:Ha}=us(Ue,se);m.set(Be,"seo",ns),m.set(Be,"jsonLD",Ha),c(Be,{onSuccess:Ka=>{n(),r(Ka.page.id,a)}})}},Cs=()=>{const k={pageType:w,name:he,slug:x===""?"/":`/${x.replace(/\/$/,"")}`,template:F||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...k},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}});else{const ue=m.find(s,{key:w});ue!=null&&ue.trackingDefault&&(k.tracking=ue.trackingDefault);const{seo:Me,jsonLD:Ce}=us(ue,se);m.set(k,"seo",Me),m.set(k,"jsonLD",Ce),c(k,{onSuccess:Be=>{var Ue;(Ue=Be==null?void 0:Be.page)!=null&&Ue.id&&r(Be.page.id,a),n()}})}},ts=k=>{if(k.preventDefault(),b(null),!!le()){if(!(R!=null&&R.hasSlug)){Ee();return}if(D&&D!=="none"){const ue=l==null?void 0:l.find(Ce=>Ce.id===D),Me=(ue==null?void 0:ue.slug)||"";if(!Oe(x,Me))return;Ns(x,Me)}else Cs()}},{pagesType:rt,partialsType:it}=f.useMemo(()=>{const k=ue=>$?ue.name.toLowerCase().includes($.toLowerCase())||ue.key.toLowerCase().includes($.toLowerCase()):!0;return{pagesType:s.filter(ue=>ue.hasSlug!==!1&&k(ue)),partialsType:s.filter(ue=>ue.hasSlug===!1&&k(ue))}},[s,$]);return i&&!(R!=null&&R.hasSlug)?t.jsxs("form",{onSubmit:ts,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsxs(o.Popover,{open:te,onOpenChange:H,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:et("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(R==null?void 0:R.name)||"Select page type",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:$,onChange:k=>V(k.target.value)})]})}),t.jsxs(cs,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>{be(k.key),H(!1)},className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:et("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})})]}),_&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:ie,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(Pt=s.find(k=>k.key===w))==null?void 0:Pt.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:he,onChange:k=>ye(k.target.value),required:!0,"aria-required":"true"})]}),t.jsx(o.Button,{disabled:oe,type:"submit",className:"w-full",children:i?oe?"Updating...":"Update "+(R==null?void 0:R.name):oe?"Creating...":"Create "+(R==null?void 0:R.name)})]}):t.jsxs("form",{onSubmit:ts,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsxs(o.Popover,{open:te,onOpenChange:H,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:et("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(R==null?void 0:R.name)||"Select page type",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:$,onChange:k=>V(k.target.value)})]})}),t.jsxs(cs,{className:"overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),i?ne?t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:et("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsx(o.CommandGroup,{heading:"Pages",children:rt.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:et("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsxs(t.Fragment,{children:[rt.length>0&&t.jsx(o.CommandGroup,{heading:"Pages",children:rt.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:et("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}),it.length>0&&t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:et("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})]})})]}),_&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:ie,children:"Confirm"})]})]})]}),!i&&(R==null?void 0:R.hasSlug)&&de.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(Hr,{templates:de,selectedTemplateId:F,onSelectTemplate:L,isLoading:ve})]}),t.jsx($r,{pages:l,selectedParentId:D,onChange:De}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:he,onChange:k=>ye(k.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(R==null?void 0:R.dynamicSegments)&&D&&D!=="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:ce,onChange:k=>Ne(k.target.checked),className:"rounded border-gray-300"}),t.jsx(o.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ce&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(zr,{value:M,onChange:O,dynamicPattern:(R==null?void 0:R.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:K})})})]}),(!(R!=null&&R.dynamicSegments)||!ce)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Js,{value:x,onChange:A,placeholder:D&&D!=="none"?"Enter page slug":w==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:D&&D!=="none"?(ss=l==null?void 0:l.find(k=>k.id===D))==null?void 0:ss.slug:void 0,onValidationChange:p}),g&&t.jsx("p",{className:"text-xs text-red-500",children:g})]}),t.jsx(o.Button,{disabled:oe||!y&&(!(R!=null&&R.dynamicSegments)||!ce)||ce&&!T,type:"submit",className:"w-full",children:i?oe?"Updating...":"Update page":oe?"Creating...":"Create Page"})]})}const qn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Te(),r=!!(e!=null&&e.id);return t.jsx(o.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsxs(o.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(o.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(Yr,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},Jr=()=>{const e=re(),s=B.useQueryClient(),n=J();return B.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const l={pageId:a,name:r};return i&&(l.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[Y,I.GET_WEBSITE_PAGES]}),W.toast.success("Page duplicated successfully")},onError:a=>{W.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},zn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Jr(),[r,i]=f.useState(null),[l,c]=f.useState(`${e.name} (Copy)`),u=m.isEmpty(e.slug),[d,h]=f.useState(u?"":`${e.slug.split("/").pop()}-copy`),g=u?"":m.initial(e.slug.split("/")).join("/"),[b,y]=f.useState(!1),p=w=>{if(w.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),y(!0);const v={pageId:e.id,name:l};u||(v.slug=`${g}/${d}`),n(v,{onSuccess:()=>{y(!1),s()},onError:N=>{y(!1),N.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):N.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):N.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(N.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Duplicate Page"}),t.jsx(o.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!u&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:l,onChange:w=>c(w.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Js,{value:d,onChange:w=>h(w),parentSlug:g,onValidationChange:w=>{i(w?null:"Invalid slug")}})]}),r&&t.jsxs(o.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(E.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:r})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||b,children:a||b?"Duplicating...":"Duplicate"})]})]})]})})},Xr=1*1024*1024,$n=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),[l,c]=f.useState(""),[u,d]=f.useState(!1),h=f.useRef(null),g=Lr(),{data:b}=Te(),y=b==null?void 0:b.find(_=>_.key===e.pageType),p=(y==null?void 0:y.name)||m.startCase(e.pageType),w=f.useCallback(_=>{var P;const S=(P=_.target.files)==null?void 0:P[0];if(S){if(S.size>Xr){W.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(S.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const G=new FileReader;G.onloadend=()=>{c(G.result),d(!1)},G.readAsDataURL(S)}catch(G){console.error("Error reading file:",G),d(!1),W.toast.error("Failed to process image",{description:G instanceof Error?G.message:"Unknown error"})}}},[]),v=()=>{c(""),h.current&&(h.current.value="")},N=()=>{var _;(_=h.current)==null||_.click()},C=()=>{a(!0),g.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Mark as template"}),t.jsxs(o.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(E.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:m.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(E.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(o.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(o.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:_=>i(_.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Input,{type:"file",id:"previewImage",ref:h,onChange:w,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:N,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:v,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:_=>{_.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:C,children:"Mark as template"})]})]})})},Vn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:c})=>{const{hasPermission:u}=Q.usePermissions(),{data:d}=Te(),h=f.useMemo(()=>m.find(d,{key:e.pageType}),[d,e.pageType]),g=f.useMemo(()=>!!e.isTemplate,[e.isTemplate]),b=f.useMemo(()=>!!(h!=null&&h.hasSlug),[h==null?void 0:h.hasSlug]);return!u(je.EDIT_PAGE)&&!u(je.DELETE_PAGE)&&!u(je.UNPUBLISH_PAGE)||!e?null:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:c}),t.jsxs(o.DropdownMenuContent,{align:"center",className:"text-sm",children:[u(je.ADD_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(E.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),u(je.EDIT_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),n({...e,global:!(h!=null&&h.hasSlug)})},children:[t.jsx(E.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&u(je.UNPUBLISH_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(E.Power,{className:"size-3"}),ae.UNPUBLISH]}),u(je.DELETE_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(E.Trash,{className:"size-3"}),ae.DELETE]}),u(je.MARK_AS_TEMPLATE)&&b&&t.jsx(t.Fragment,{children:g?t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(E.SquareLibrary,{className:"size-3"}),ae.UNMARK_AS_TEMPLATE]}):t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(E.SquareLibrary,{className:"size-3"}),ae.MARK_AS_TEMPLATE]})})]})]})},Hn=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),r=Dr(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Unmark as template"}),t.jsx(o.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},Zr=Pn("expandedPagesState",[]),Zs=e=>m.flatMap(e,s=>[s,...s.children?Zs(s.children):[]]),ei=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const l=[...r,i.id];if(i.id===s)return l;if(i.children&&i.children.length>0){const c=n(i.children,l);if(c)return c}}return null};return n(e)||[]},Kn=(e,s)=>{if(!s)return[];const n=Zs(e),a=m.find(n,r=>r.id===s);if(a){if(a.parent)return[...Kn(e,a.parent),s];const r=ei(e,s);if(!m.isEmpty(r))return r}return[s]},ti=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(c=>s.add(c)),i.children&&!m.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},Wn=e=>{const[s,n]=Re.useAtom(Zr),a=e?m.includes(s,e):!1,r=f.useCallback(()=>{n(d=>a?m.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=f.useCallback((d,h)=>{if(!h||m.isEmpty(d))return;const g=Zs(d),b=Kn(g,h);if(!Array.isArray(b)||m.isEmpty(b))return;const y=b.slice(0,-1);m.isEmpty(y)||n(p=>m.uniq([...p,...y]))},[n]),l=f.useCallback(d=>{if(m.isEmpty(d))return;const h=ti(d);m.isEmpty(h)||n(g=>m.union(g,h))},[n]),c=f.useCallback(d=>{if(m.isEmpty(d))return;const h=m.flatMap(d,g=>{const b=y=>[y.id,...y.children?m.flatMap(y.children,b):[]];return b(g)});n(h)},[n]),u=f.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:c,collapseAll:u}},un=(e,s)=>!e||!Array.isArray(e)?[]:m.isEmpty(s)?e:m.compact(m.filter(e,n=>{const a=m.toLower(s);return m.includes(m.toLower((n==null?void 0:n.name)||""),a)||m.includes(m.toLower((n==null?void 0:n.slug)||""),a)})),si=(e,s)=>{const n=new Set,a=m.keyBy(e,"id");return s.forEach(r=>{let i=r;for(;i.parent&&a[i.parent];)n.add(i.parent),i=a[i.parent]}),Array.from(n).map(r=>a[r])},Ls=(e,s,n)=>m.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?Ls(a.children,s,n):[]};const r=a.children&&a.children.some(i=>m.includes(m.toLower(i.name||""),m.toLower(s))||m.includes(m.toLower(i.slug||""),m.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?Ls(a.children,s,n):[]}}),ni=e=>{if(!e||!e.length)return[];const s={};e.forEach(a=>{s[a.id]={...a,children:[]}});const n=[];return Object.values(s).forEach(a=>{a.parent&&s[a.parent]?s[a.parent].children.push(a):n.push(a)}),n},Qn=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Qn(n.children):[]})),ai=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=m.compact(m.filter(e,{pageType:n}))),m.isEmpty(s))r=un(r,s);else{const h=un(r,s),g=si(e,h);r=m.uniqBy([...h,...g],"id")}const i=Qn(ni(r)),l=Ls(i,s,a),c=m.filter(l,h=>a(h.pageType)).sort((h,g)=>(h.name||"").localeCompare(g.name||"")),u=m.keyBy(m.filter(l,h=>!a(h.pageType)),"pageType"),d=Object.values(m.mapValues(u,(h,g)=>({...h,name:m.startCase(g),isPartialGroup:!0,children:l.filter(b=>b.pageType===g)})));return[...c,...d]},ri=({currentEditor:e})=>{const{user:s}=ze(),{data:n}=nt(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(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{children:t.jsx(E.LockIcon,{className:"w-3 h-3"})}),t.jsx(o.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},ii=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:c,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:h,isExpanded:g,onToggleExpand:b})=>{const y=Xs(),{data:p}=Te(),[,w]=Q.useSidebarActivePanel(),v=f.useMemo(()=>m.find(p,{key:s.pageType}),[p,s.pageType]),N=f.useMemo(()=>{const P=m.get(s,"slug",""),G=e?Ve(e):"",q=G?P.replace(G,""):P;return q||"/"},[s,e]),C=f.useMemo(()=>!!s.isTemplate,[s.isTemplate]),_=f.useCallback(()=>{w("outline"),y(m.get(s,"id"),a)},[y,a,s,w]),S=f.useCallback(P=>{P.stopPropagation(),b()},[b]);return t.jsxs("div",{onClick:_,className:`rounded flex p-1.5 items-center justify-between leading-none cursor-pointer px-3 py-1.5 ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("button",{onClick:S,disabled:!h,className:`flex items-center justify-center w-4 h-5 text-gray-400 hover:text-gray-500 transition-colors ${h?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(E.ChevronRight,{size:16,className:`w-4 h-5 transition-transform duration-200 ${g?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(E.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):v!=null&&v.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:v.icon}}):v!=null&&v.hasSlug?t.jsx(E.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(E.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),!s.isPartialGroup&&t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:s.name}),v!=null&&v.hasSlug?t.jsxs(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:[N,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[m.endsWith(N,"/")?`${v==null?void 0:v.dynamicSlug}`:`/${v==null?void 0:v.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:v==null?void 0:v.name}),C&&t.jsx(o.Badge,{variant:"outline",className:"ml-2 text-xs py-0 font-normal text-blue-500 border border-blue-200 bg-blue-50",children:"Template"})]}),!s.isPartialGroup&&t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(ri,{currentEditor:s.currentEditor}),t.jsx(Vn,{page:s,setDuplicatePage:d,setAddEditPage:l,setUnpublishPage:r,setDeletePage:i,setMarkAsTemplate:c,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"p-0.5 m-0 hover:bg-white rounded duration-100 cursor-pointer",children:t.jsx(E.MoreHorizontal,{className:"w-4 h-4",onClick:P=>P.stopPropagation()})})})]})]})},li=({close:e,isOpen:s})=>{const[,n]=f.useState([]),[a,r]=f.useState(null),[i,l]=f.useState(""),[c,u]=f.useState(""),[d,h]=f.useState(null),g=T=>c?String(m.get(T,"name","")).toLowerCase().includes(c.toLowerCase())||String(m.get(T,"key","")).toLowerCase().includes(c.toLowerCase()):!0,[b,y]=f.useState(null),[p,w]=f.useState(null),[v,N]=f.useState(null),[C,_]=f.useState(null),{data:S,isFetching:P,refetch:G}=Zt(),[q,z]=f.useState(""),{hasPermission:se}=Q.usePermissions(),{updateForSelectedPage:$,expandPagesOnSearch:V,expandAll:te,collapseAll:H}=Wn(null),[ne,D]=Ie(),U=ne.get("page"),he=f.useRef(null),{data:ye}=Te(),ce=f.useCallback(T=>{var K;return(K=m.find(ye,{key:T}))==null?void 0:K.hasSlug},[ye]);f.useEffect(()=>{s&&G()},[s,G]),f.useEffect(()=>{if(!m.isEmpty(q))return;const T=sessionStorage.getItem("pageTypeFilter")||"all";!m.isEmpty(ye)&&T&&(m.find(ye,{key:T})?z(T):z("all"))},[ye,q]);const j=T=>{z(T),sessionStorage.setItem("pageTypeFilter",T),u("")},x=f.useCallback(T=>{const F=new URLSearchParams(window.location.search).get("lang"),Z=new URLSearchParams({page:T});F&&Z.set("lang",F),window.history.pushState({},"",`?${Z.toString()}`),D(Z),window.dispatchEvent(new PopStateEvent("popstate")),e()},[D,e]);f.useEffect(()=>{if(U&&!P){const T=m.find(S,{id:U});T&&(T!=null&&T.pageType)?n(K=>[...K,T==null?void 0:T.pageType]):(window.history.replaceState(null,"","/"),D(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[S,U,P,D]);const A=f.useMemo(()=>S?ai(S,i,q,ce):[],[S,i,q,ce]);f.useEffect(()=>{U&&!P&&!m.isEmpty(A)&&($(A,U),he.current&&he.current.scrollIntoView({behavior:"smooth",block:"end"}))},[U,P,A,$]),f.useEffect(()=>{!m.isEmpty(i)&&!m.isEmpty(A)&&V(A)},[i,A,V]);const M=f.useCallback(()=>{te(A)},[te,A]),O=f.useCallback(()=>{H()},[H]);return t.jsxs("div",{className:"flex flex-col justify-between h-full",children:[t.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[t.jsxs("div",{className:"flex gap-1 items-center justify-between",children:[t.jsxs("div",{className:"relative flex item-center gap-x-4 flex-1",children:[t.jsx(E.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:i,onChange:T=>l(T.target.value)}),!m.isEmpty(q)&&t.jsxs(o.Select,{value:q,onValueChange:j,children:[t.jsx(o.SelectTrigger,{className:`${q==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} min-w-[120px] h-max p-0 py-1 pl-2 pr-1 top-1.5 -mt-px absolute text-gray-600 right-1.5 w-max text-xs whitespace-nowrap ring-0 focus:ring-0 shadow-none`,children:t.jsx(o.SelectValue,{placeholder:"Select page type"})}),t.jsxs(o.SelectContent,{align:"end",children:[t.jsx("div",{className:"px-3 py-2 sticky top-0 bg-white z-10",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"pl-8 h-8 text-xs",value:c,onChange:T=>u(T.target.value),onKeyDown:T=>T.stopPropagation()})]})}),t.jsx(o.SelectItem,{value:"all",children:"All"},"all"),!m.isEmpty(m.filter(ye,T=>T.hasSlug&&g(T)))&&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"}),m.map([...m.filter(ye,T=>T.hasSlug&&g(T))].sort((T,K)=>m.get(T,"name","").localeCompare(m.get(K,"name",""))),T=>t.jsx(o.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),!m.isEmpty(m.filter(ye,T=>!T.hasSlug&&g(T)))&&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"}),m.map([...m.filter(ye,T=>!T.hasSlug&&g(T))].sort((T,K)=>m.get(T,"name","").localeCompare(m.get(K,"name",""))),T=>t.jsx(o.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),m.isEmpty(m.filter(ye,g))&&t.jsx("div",{className:"px-3 py-2 text-sm text-gray-500 text-center",children:"No matching page types found"})]})]})]}),t.jsxs("div",{className:"flex gap-1 ",children:[t.jsx(o.Button,{variant:"outline",size:"icon",onClick:M,className:"p-1 text-gray-500",children:t.jsx(E.ChevronsUpDown,{})}),t.jsx(o.Button,{variant:"outline",size:"icon",onClick:O,className:"p-1 text-gray-500",children:t.jsx(E.ChevronsDownUp,{})})]})]}),P?t.jsx("div",{className:"space-y-2",children:m.map([...Array(5).keys()],T=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},T))}):m.isEmpty(A)?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(E.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:m.map(A,T=>{const K=T.id===U;return t.jsx("div",{ref:K?he:null,children:t.jsx(Yn,{item:T,currentPage:U,close:e,setUnpublishPage:y,setDeletePage:h,setAddEditPage:w,setMarkAsTemplate:N,setUnmarkAsTemplate:_,setDuplicatePage:r,level:0})},`page-item-${T.id}`)})})]}),se(je.ADD_PAGE)&&t.jsxs(o.Button,{className:"flex text-sm gap-x-2",onClick:()=>{w({slug:"",name:"",pageType:q==="all"?"page":q})},children:[t.jsx(E.Plus,{className:"w-4 h-4"})," Add New"]}),p&&t.jsx(qn,{closePanel:e,editPage:x,addEditPage:p,setAddEditPage:w}),d&&t.jsx(Ys,{page:d,onClose:()=>h(null)}),b&&t.jsx(bs,{page:b,onClose:()=>y(null)}),v&&t.jsx($n,{page:v,onClose:()=>N(null)}),C&&t.jsx(Hn,{page:C,onClose:()=>_(null)}),a&&t.jsx(zn,{page:a,onClose:()=>r(null)})]})},Yn=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const g=!m.isEmpty(e==null?void 0:e.children),{isExpanded:b,toggleExpanded:y}=Wn(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(ii,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:g,isExpanded:b,onToggleExpand:y}),g&&b&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:m.map(m.get(e,"children",[]),p=>t.jsx(Yn,{item:p,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:e.slug,level:h+1},p.id||`child-${h}-${p.key}`))})]},e.id||`level-${h}-${e.key}`)},oi=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(o.Input,{type:"text",autoFocus:!0,value:e?s:"",onChange:a=>n(a.target.value),placeholder:e?"Search pages...":"To search select default language",disabled:!e}),ci=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=Q.useLanguages(),c=(i==null?void 0:i.length)===0;return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"ghost",className:"w-max focus:outline-none focus:ring-0 border-[0px] rounded-md py-1 text-sm h-max border border-gray-200 hover:bg-gray-100 pl-4",children:[e?m.get(e,"name"):"Select Page",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"w-96 divide-y shadow-xl p-0 max-h-[75vh]",children:[t.jsx("div",{className:"p-1.5 bg-gray-50/30",children:t.jsx(oi,{isDefaultLang:c,searchQuery:n,setSearchQuery:a})}),(r==null?void 0:r.length)===0?t.jsx("div",{className:"h-24 text-xs flex items-center justify-center",children:"No pages found"}):r==null?void 0:r.map(u=>t.jsx(o.DropdownMenuItem,{onClick:()=>s(u),disabled:c?l!==u.lang:i!==u.lang,className:`flex flex-col justify-start cursor-pointer overflow-x-auto whitespace-nowrap no-scrollbar ${u.id===(e==null?void 0:e.id)?"bg-blue-50":"hover:bg-gray-50"}`,children:t.jsxs("div",{className:"w-full text-xs whitespace-nowrap p-1",children:[t.jsxs("div",{children:["Name : ",t.jsx("span",{className:"font-medium",children:u.name})]}),u.lang&&t.jsxs("div",{children:["Language : ",t.jsx("span",{className:"font-medium",children:Pe[u.lang]})]}),t.jsxs("div",{children:["Slug :",t.jsxs("span",{className:"font-mono font-medium",children:[" ",u.slug]})]})]})},u.id))]})]})},ui=({children:e})=>t.jsx("div",{className:"z-[9999] fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-[50px] bg-black/30 backdrop-blur-sm",children:t.jsx("div",{className:"bg-white rounded-md p-4 shadow-xl min-w-[300px] max-w-[400px] flex flex-col items-center justify-center",children:e})}),di=()=>{const{isPending:e,dynamicPage:s,dynamicPages:n,allLangPages:a,selectedLang:r,searchQuery:i,updateDynamicPage:l,updateSearchQuery:c,onChangeLanguage:u}=fr(),d=f.useRef(void 0);f.useEffect(()=>{d.current!==r&&s&&(u(),d.current=r)},[r,n]);const h=a.length>0;return t.jsxs("div",{className:"relative",children:[!e&&!s&&t.jsxs(ui,{children:[t.jsx("h1",{className:"text-lg font-medium",children:h?"Select a page":"No pages found"}),t.jsx("p",{className:"text-sm text-center text-gray-600 pt-4",children:h?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]}),t.jsx(ci,{dynamicPage:s,setDynamicPage:l,searchQuery:i,setSearchQuery:c,dynamicPages:a})]})},mi=({page:e})=>{const[s,n]=f.useState(null),[a,r]=f.useState(null),[i,l]=f.useState(null),[c,u]=f.useState(null),[d,h]=f.useState(null),[g,b]=f.useState(null);return e?t.jsxs(t.Fragment,{children:[t.jsx(Vn,{page:e,setDuplicatePage:y=>h(y),setAddEditPage:y=>b(y),setUnpublishPage:y=>r(y),setDeletePage:y=>n(y),setMarkAsTemplate:y=>l(y),setUnmarkAsTemplate:y=>u(y),children:t.jsx("div",{className:"p-0 m-0 w-6 h-6 p-1 absolute right-2 top-1/2 -translate-y-1/2 hover:bg-gray-200 rounded duration-100 cursor-pointer",children:t.jsx(E.MoreHorizontal,{className:"w-4 h-4",onClick:y=>y.stopPropagation()})})}),g&&t.jsx(qn,{closePanel:()=>b(null),editPage:()=>{},addEditPage:g,setAddEditPage:b}),s&&t.jsx(Ys,{page:s,onClose:()=>n(null)}),a&&t.jsx(bs,{page:a,onClose:()=>r(null)}),i&&t.jsx($n,{page:i,onClose:()=>l(null)}),c&&t.jsx(Hn,{page:c,onClose:()=>u(null)}),d&&t.jsx(zn,{page:d,onClose:()=>h(null)})]}):null},hi=()=>{const e=Xe("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:f.createElement(e,{})}):null},fi=()=>{const[e]=Ie(),s=e.get("page"),{data:n,isFetching:a}=Le(),[r,i]=f.useState(!1),{savePage:l}=Q.useSavePage(),c=m.get(n,"dynamic",!1),u=!!s&&!m.isEmpty(n),d=!s||!a&&m.isEmpty(n)||r,h=Q.useChaiFeatureFlag("dynamic-page-selector");return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-x-1",children:[t.jsxs("div",{className:"relative",children:[t.jsxs(o.Button,{variant:"outline",className:"flex w-full items-center space-x-2 py-1",onClick:()=>{l(),i(!0)},children:[t.jsx("div",{children:t.jsx(E.Logs,{className:"h-4 w-4"})}),t.jsxs("span",{className:"flex max-w-[200px] items-center truncate leading-tight",children:[t.jsx("span",{className:"pr-1 font-light text-slate-600",children:"Editing:"}),a?t.jsx(E.Loader,{className:"ml-2 h-4 w-4 animate-spin text-slate-400"}):m.startCase(m.get(n,"name"))??""]}),t.jsx("div",{className:`${a?"hidden":"w-2"}`})]},"template-viewer"),!a&&t.jsx(mi,{page:n})]}),c&&!a&&h&&t.jsxs(t.Fragment,{children:[t.jsx(E.ChevronRight,{size:14,className:"text-slate-500"}),t.jsx(di,{})]})]}),t.jsx(o.Sheet,{open:d,onOpenChange:g=>!g&&u&&i(!1),children:t.jsxs(o.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`z-50 w-full !max-w-screen-md border-border ${u?"":"sheet-hide-close-btn"}`,children:[t.jsxs(o.SheetHeader,{className:"mb-3",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("div",{className:"rounded-md bg-primary p-2 text-primary-foreground",children:t.jsx(E.File,{className:"h-6 w-6"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(o.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(li,{isOpen:d,close:()=>i(!1)})})]})})]})},Jn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=Q.useLanguages(),l=m.isEmpty(r)?n:r,[,c]=Ie();f.useEffect(()=>{const v=new URLSearchParams(window.location.search),N=v.get("lang");N&&(a.includes(N)?i(N):(v.delete("lang"),c(v),i("")))},[a,c,i]);const[u,d]=f.useState(null),{data:h}=Le(),{data:g}=Ze(),{data:b,isFetching:y}=He(),p=f.useMemo(()=>{const v=m.compact(m.map(m.get(g,"languages"),N=>{const C=m.find(b,{lang:N});return{key:N,value:m.get(Pe,N,N),isLangPageAdded:!!C}})).filter(Boolean);return[{key:n,value:m.get(Pe,n),isLangPageAdded:!0},...v]},[n,b,g]),w=v=>{i(v);const N=new URLSearchParams(window.location.search);v===n?N.delete("lang"):N.set("lang",v);const C=N.toString(),_=`${window.location.pathname}${C?`?${C}`:""}`;window.history.pushState({},"",_),c(N),window.dispatchEvent(new PopStateEvent("popstate"))};return m.isEmpty(a)||y?null:t.jsxs(t.Fragment,{children:[t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(o.Button,{variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(E.Languages,{className:"h-4 w-4"}),m.get(Pe,l,l),t.jsx(E.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"space-y-1 border-border",children:[m.map(p.filter(v=>v.isLangPageAdded),v=>t.jsxs(o.DropdownMenuItem,{className:Q.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",v.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>w(v.key),children:[t.jsx("div",{className:"text-slate-600",children:v.value}),v.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(E.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},v.value)),e&&!m.isEmpty(p.filter(v=>!v.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(o.Separator,{}),t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:()=>{d({name:h==null?void 0:h.name,pageType:h==null?void 0:h.pageType,lang:"",slug:"",edit:!1})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(E.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]}),u&&t.jsx(Fn,{languages:a,langProps:u,onClose:()=>d(null)})]})};function gi(){return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(hi,{}),t.jsx(fi,{})]})}function xi(e){const s=re(),n=J();return B.useQuery({queryKey:[Y,"revisions",e],queryFn:async()=>await n(s,{action:I.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const pi=()=>{const e=re(),s=J(),n=B.useQueryClient();return B.useMutation({mutationFn:async a=>await s(e,{action:I.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})},yi=()=>{const e=re(),s=J(),n=B.useQueryClient();return B.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:I.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})};function ji(){const{data:e}=Le(),{saveState:s}=Q.useSavePage(),[n]=vs();return e?t.jsx("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50 bg-primary/5 mb-4",children:t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:t.jsx("span",{className:"font-bold",children:"Currently editing"})})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:!m.isEmpty(n.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",Ct.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(E.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(E.Save,{className:"h-3 w-3"}),t.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function vi(){const[e,s]=we.useState(!1),[n,a]=we.useState(null),[r,i]=we.useState(!1),[l,c]=we.useState(!1),{data:u}=Le(),{data:d,isFetching:h,error:g,refetch:b}=xi(u==null?void 0:u.id),{mutate:y,isPending:p}=pi(),{mutate:w,isPending:v}=yi(),N=B.useQueryClient(),C=G=>{n&&w({revisionId:n.uid,discardCurrent:G},{onSuccess:()=>{i(!1),a(null),N.invalidateQueries({queryKey:[Y,I.GET_DRAFT_PAGE]})}})},_=G=>{a(G),i(!0)},S=G=>{a(G),c(!0)},P=()=>{n&&y(n.uid,{onSuccess:()=>{c(!1),a(null)}})};return f.useEffect(()=>{e&&b()},[e,b]),t.jsxs(t.Fragment,{children:[t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsxs(o.Sheet,{open:e,onOpenChange:s,children:[t.jsx(o.SheetTrigger,{asChild:!0,children:t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(o.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(E.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(o.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(o.SheetHeader,{className:"pb-2",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(E.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"," ",Ct.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(o.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:h?t.jsx(bi,{}):g?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 space-y-2",children:[t.jsx(ji,{}),d==null?void 0:d.map(G=>t.jsx(wi,{revision:G,isLatest:G.uid==="current",onRestore:()=>_(G),onDelete:()=>S(G)},G.uid))]})})]})]}),t.jsx(o.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Ei,{open:r,onOpenChange:i,revision:n,onRestore:C,isRestoring:v}),t.jsx(Ni,{open:l,onOpenChange:c,revision:n,onDelete:P,isDeleting:p})]})}function bi(){return t.jsx("div",{className:"space-y-2 mt-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(o.Skeleton,{className:"h-4 w-3/4"}),t.jsx(o.Skeleton,{className:"h-3 w-1/2"}),t.jsx(o.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(o.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function wi({revision:e,isLatest:s,onRestore:n,onDelete:a}){const{data:r}=nt(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:Ct.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(E.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(E.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(Ge,{permissions:[je.RESTORE_REVISION,je.DELETE_REVISION],children:e.uid!=="current"&&t.jsx(Si,{revision:e,onRestore:n,onDelete:a})})]})}function Si({revision:e,onRestore:s,onDelete:n}){return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(E.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Ge,{permission:je.RESTORE_REVISION,children:t.jsxs(o.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(E.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Ge,{permission:je.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(o.DropdownMenuSeparator,{}),t.jsxs(o.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(E.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function Ei({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=nt((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Restore Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",Ct.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(o.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function Ni({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=nt((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",Ct.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Ci=()=>{const e=re(),s=J();return B.useQuery({queryKey:[Y,I.GET_CHANGES],queryFn:async()=>s(e,{action:I.GET_CHANGES})})},Ai=({currentEditor:e})=>{const{data:s}=nt(e);return s==null?void 0:s.name};function Ti({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=f.useState([]),{data:r,isFetching:i}=Ci(),{data:l}=Te(),c=f.useCallback(S=>{var P;return(P=m.find(l,{key:S}))==null?void 0:P.hasSlug},[l]),u=f.useMemo(()=>m.filter(l,S=>!c(S.key)).map(S=>S.key),[c,l]),d=f.useMemo(()=>m.filter(r,S=>!u.includes(S.pageType)),[r,u]),h=f.useMemo(()=>m.filter(r,S=>u.includes(S.pageType)),[r,u]),g=f.useMemo(()=>m.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:b,isPending:y}=Ws();f.useEffect(()=>{const S=m.map(m.filter(r,{online:!0}),"id");g&&S.push(g==null?void 0:g.id),a(S)},[r,g]);const p=n.length===(r==null?void 0:r.length),w=S=>{a(P=>m.includes(P,S)?m.filter(P,G=>G!==S):m.concat(P,S))},v=()=>{a(p?[]:m.map(r,"id"))},N=()=>{b({ids:m.uniq(n)},{onSuccess:()=>{s(),_t("CENTER_CENTER")}})},C=S=>{if(S==="theme")return"Theme";const P=m.find(l,{key:S});return P?P==null?void 0:P.name:S},_=f.useMemo(()=>{const S=[{label:"Updated",top:"pt-2"},...m.orderBy(m.filter(d,{online:!0}),"pageType"),...m.orderBy(m.filter(h,{online:!0}),"pageType")].filter(q=>q.pageType!=="theme"),P=[{label:"Offline",top:"pt-6"},...m.orderBy(m.filter(d,{online:!1}),"pageType"),...m.orderBy(m.filter(h,{online:!1}),"pageType")],G=g?[{label:"Theme",top:"pt-6"},g]:[];return[...S,...G,...P]},[d,h,g]);return t.jsx(o.Dialog,{open:e,onOpenChange:y?()=>{}:s,children:t.jsxs(o.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Publish changes"}),t.jsx(o.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),t.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:i?t.jsxs("div",{className:"px-1 space-y-2",children:[t.jsx("div",{className:"w-full h-6 mt-2 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"})]}):t.jsxs("table",{className:"w-full text-xs text-left text-gray-500 rtl:text-right dark:text-gray-400",children:[t.jsx("thead",{className:"text-gray-700 border-b bg-gray-50 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"px-6 py-3 flex items-center gap-x-2 w-[1 50px]",children:[t.jsx("input",{checked:p,onClick:S=>{S.stopPropagation(),v()},type:"checkbox",className:"mt-1 rounded cursor-pointer focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Language"}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Type"}),t.jsx("th",{scope:"col",className:"px-4 py-3 w-[150px] text-right",children:"Status"})]})}),t.jsx("tbody",{children:m.map(_,S=>S.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${S.top}`,children:[t.jsx("div",{className:"absolute inset-0 flex items-center left-6",children:t.jsx("div",{className:"w-full order-gray-300"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"pr-2 bg-gray-50",children:S.label})})]})},"separator"):t.jsxs("tr",{className:"border-b group hover:bg-gray-50 last:border-b-0",children:[t.jsxs("td",{scope:"row",className:"flex items-center px-6 py-2 text-gray-900 whitespace-nowrap dark:text-white gap-x-1",children:[t.jsx("input",{checked:m.includes(n,S==null?void 0:S.id),onClick:P=>{P.stopPropagation(),w(S==null?void 0:S.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",c(S.pageType)?t.jsx(E.File,{className:"w-4 h-4"}):t.jsx(E.GlobeIcon,{className:"w-4 h-4"}),S.name,S.slug&&t.jsxs("span",{className:"text-xs text-gray-500",children:["(",S.slug,")"]}),S.currentEditor&&t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsxs("span",{className:"flex text-xs font-bold text-gray-500",children:[" ","-"," ",t.jsx(Ai,{currentEditor:S.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:S.lang}),t.jsx("td",{className:"px-2",children:C(S==null?void 0:S.pageType)}),t.jsx("td",{className:"px-4 text-right",children:m.first(S.changes)||""})]},S==null?void 0:S.id))})]})}),t.jsxs(o.DialogFooter,{className:"mt-10",children:[t.jsx(o.Button,{disabled:y,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{disabled:y||i||m.isEmpty(r),onClick:N,children:y?"Publishing...":"Publish"})]})]})})}const Pi=()=>{const e=J(),s=re();return B.useQuery({queryKey:[I.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_DATA,data:{draft:!0}})})};function ki({onClose:e}){const{data:s,isFetching:n}=Pi(),{mutateAsync:a,isPending:r}=rr(),i=Xe("settingComponent",null),l=m.debounce(async c=>(await a({data:c}),!0),300);return i?t.jsx(o.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(o.DialogContent,{className:"w-full",children:[t.jsx(o.DialogHeader,{children:t.jsx(o.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:f.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function Xn({children:e,content:s}){return t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:e}),t.jsx(o.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const Ii=()=>{const{selectedLang:e,fallbackLang:s}=Q.useLanguages(),n=Xe("getPreviewUrl",async g=>g),[a,r]=f.useState(""),{data:i}=Le(),{data:l}=He(),{data:c}=Te(),u=f.useMemo(()=>{var g;return(g=l==null?void 0:l.find(b=>(b==null?void 0:b.lang)===e))==null?void 0:g.slug},[e,l]),d=f.useCallback(g=>{var b;return(b=m.find(c,{key:g}))==null?void 0:b.hasSlug},[c]),h=e===s?"":e;return f.useEffect(()=>{(async()=>{if(typeof n=="function"){const g=!d(i==null?void 0:i.pageType),b=await n(g?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(b)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,h]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(o.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(E.Eye,{className:"h-4 w-4"})," ",ae.PREVIEW]})})})},Li=()=>{const[e,s]=Q.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(Xn,{content:ae.THEME,children:t.jsx(o.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(E.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},Di=()=>{const[e,s]=f.useState(!1),{isLocked:n}=es(),{savePage:a,saveState:r}=Q.useSavePage();f.useEffect(()=>{const h=g=>{r==="UNSAVED"&&(g.preventDefault(),g.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=f.useCallback(async()=>{s(!0),await a(!1)},[a]);f.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=f.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:c,buttonClass:u,tooltipContent:d}=f.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:ae.SAVEDRAFT,buttonIcon:t.jsx(E.Save,{className:"h-4 w-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:ae.SAVING,buttonIcon:t.jsx(E.Loader,{className:"h-4 w-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:ae.SAVED,buttonIcon:t.jsx(E.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[c," ",d]})},_i=()=>{const{selectedLang:e}=Q.useLanguages(),{data:s}=At(),{data:n}=He(),[a,r]=f.useState(!1),[i,l]=f.useState(!1),[c,u]=f.useState(null),{data:d}=Le(),{mutate:h,isPending:g}=Ws(),{buttonText:b,buttonClassName:y,isPublished:p}=f.useMemo(()=>{const N=d&&(d==null?void 0:d.online);return{buttonClassName:N?"hover:bg-green-600 bg-green-500":"",isPublished:N,buttonText:N?ae.PUBLISHED:ae.PUBLISH}},[d]),w=async()=>{const N=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];h({ids:m.compact(N)},{onSuccess:()=>_t("TOP_RIGHT")})},v=f.useMemo(()=>m.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(o.Button,{size:"sm",onClick:w,disabled:g||!(d!=null&&d.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${y}`,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${i?"-translate-y-10":""}`,children:p?t.jsx(E.Send,{className:"h-4 w-4"}):t.jsx(E.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:p?t.jsx(E.Rocket,{className:"h-4 w-4"}):t.jsx(E.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:b}),e?`(${m.upperCase(e)})`:""]}),t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",disabled:g||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${y}`,children:t.jsx(E.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(o.DropdownMenuItem,{disabled:g,className:"cursor-pointer text-xs",onClick:()=>h({ids:v},{onSuccess:()=>_t("TOP_RIGHT")}),children:[ae.PUBLISH," with translation pages"]}),!p&&t.jsxs(o.DropdownMenuItem,{disabled:g,className:"cursor-pointer text-xs",onClick:()=>h({ids:[d==null?void 0:d.id]},{onSuccess:()=>_t("TOP_RIGHT")}),children:[ae.PUBLISH," page"]}),t.jsxs(o.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[ae.OPEN," publish menu"]}),p&&t.jsxs(o.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[ae.UNPUBLISH," page ",e?`(${m.upperCase(e)})`:""]})]})]})]}),t.jsx(Ti,{showModal:a,onClose:()=>r(!1)}),c&&t.jsx(bs,{page:c,onClose:()=>u(null)})]})},Mi=()=>{const e=Xe("settingComponent",null),[s,n]=f.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(Xn,{content:ae.WEBSITEDATA,children:t.jsx(o.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(E.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(ki,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Bi(){const{isLocked:e}=es(),[s]=Ie(),n=s.get("lang"),a=_n(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(vi,{}),t.jsx(Ge,{permission:je.EDIT_THEME,children:t.jsx(Li,{})}),t.jsx(Ge,{permission:je.EDIT_SETTINGS,children:t.jsx(Mi,{})}),t.jsx(Ii,{}),t.jsx(Ge,{permission:je.SAVE_PAGE,children:t.jsx(Di,{})}),t.jsx(Ge,{permission:je.PUBLISH_PAGE,children:t.jsx(_i,{})})]})}function Gi(e){const s=window.location.host,n=e?e.endsWith("/")?e.slice(0,-1):e:"";let a="";if(n.length>=60)a="..."+n.slice(-60);else if(s.length+n.length>60){const r=60-n.length-3;a=(r>0?"..."+s.slice(s.length-r):"...")+n}else a=s+n;return a}const Oi=()=>{const{data:e}=At(),s=Gn(),n=e==null?void 0:e.slug,a=!n;let r=window.location.origin+(n?n.endsWith("/")?n.slice(0,-1):n:"");s&&(r+=s);const l=(a?`Partial: ${e==null?void 0:e.name} `:Gi(s?`${n}${s}`:n)).replace(window.location.host,"");return t.jsxs("div",{className:"flex h-8 w-auto max-w-[600px] items-center rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800"+(a?" pr-2":""),children:[t.jsx(Jn,{}),t.jsx("div",{className:"flex w-full items-center overflow-hidden",children:t.jsx("div",{className:`w-full overflow-hidden overflow-ellipsis whitespace-nowrap pl-1 font-mono text-xs ${a?"italic text-gray-400":"text-gray-500"}`,children:l===""?"/(Homepage)":l})}),!a&&t.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:t.jsx("div",{className:"ml-2 mr-px flex-shrink-0 rounded-sm p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(E.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})},Ri=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(gi,{}),t.jsx(Oi,{}),t.jsx(Bi,{})]}),Ui=()=>{const e=re(),{aiContext:s}=$s(),n=J();return f.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])},Fi=(e,s)=>s.map(n=>{if(m.has(e,n._type)){const a=Tn.getDefaultBlockProps(n._type);return{...a,...m.pick(n,[...m.keys(a),"_type","_id","_name","_parent","_bindings"]),...m.pickBy(n,(r,i)=>m.endsWith(i,"_attrs")),...n}}return n}),qi=e=>{const s=Tn.useRegisteredChaiBlocks();return f.useMemo(()=>{if(!e||m.isEmpty(e))return{blocks:[]};const n=m.filter(e,a=>!m.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Fi(s,n)}},[e,s])},dn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=m.get(a,"html",""),i=m.get(a,"blocks",[]);return m.isArray(i)?i:Q.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),[]}}},zi=()=>{const e=re(),s=J();return B.useQuery({queryKey:[Y,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{Q.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>dn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>dn.getUILibraryBlock(i,s,e)})}),a}})},Zn=()=>{const e=js(),s=J(),{user:n}=ze(),a=n==null?void 0:n.id;return B.useQuery({queryKey:[Y,"permissions",a],queryFn:()=>s(e,{action:I.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},$i=()=>{const e=re(),s=J(),{setCurrentEditor:n}=es(),[,a]=vs();return{onSave:async({page:i,blocks:l})=>{try{const c=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return c.code==="PAGE_LOCKED"?(n(c.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),c)}catch(c){return console.error(c),new Error("Failed to save blocks")}}}},Vi=()=>{const{data:e}=Zt(),s=re(),n=J();return{getPartialBlocks:f.useCallback(async()=>{const a={};for(const r of e??[])m.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:m.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:f.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return m.filter(r.blocks,i=>m.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},mn=ls.z.object({email:ls.z.string().email({message:"Please enter a valid email address"}),password:ls.z.string().min(6,{message:"Password must be at least 6 characters"})}),Hi=()=>{const{setUser:e,logout:s}=ze(),n=js(),[a,r]=f.useState(""),[i,l]=f.useState(""),[c,u]=f.useState({}),[d,h]=f.useState(!1),[g,b]=f.useState(""),y=B.useMutation({mutationFn:async v=>{b("");const N=await zs(n,{action:"LOGIN",data:v});if(!N.ok){const _=await N.json();throw new Error(_.error||"Login failed")}const C=await N.json();if(m.has(C,"id")&&m.has(C,"email")&&m.has(C,"accessToken")&&m.has(C,"refreshToken"))e(C);else throw s(),new Error("Something went wrong. Please try again.");return C},onSuccess:()=>{u({}),b("")},onError:v=>{u({email:" ",password:" "}),b(v.message||"Something went wrong")}}),p=async v=>{v.preventDefault(),u({});const N={email:a,password:i};try{const C=mn.parse(N);y.mutate(C)}catch(C){if(C instanceof ls.z.ZodError){const _=C.errors.reduce((S,P)=>{const G=P.path[0];return S[G]=P.message,S},{});u(_)}}},w=mn.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(o.Card,{className:"w-full max-w-md",children:[t.jsxs(o.CardHeader,{children:[t.jsx(o.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(o.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(o.CardContent,{children:t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"email",children:"Email"}),t.jsx(o.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:v=>r(v.target.value),className:c.email?"border-destructive":""}),c.email&&t.jsx("p",{className:"text-sm text-destructive",children:c.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:v=>l(v.target.value),className:c.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(E.EyeOff,{className:"h-4 w-4"}):t.jsx(E.Eye,{className:"h-4 w-4"})})]}),c.password&&t.jsx("p",{className:"text-sm text-destructive",children:c.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:g})}),t.jsx(o.Button,{type:"submit",className:"w-full",disabled:!w||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(E.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(o.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let Ds=Hi;const Ki=()=>f.useMemo(()=>Ds,[Ds]),Wi=e=>{Ds=e},Qi=()=>{const e=Ki();return t.jsx(f.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},Yi=({isActive:e,show:s})=>{const{data:n}=Ze();return!m.has(n,"languages")||!m.get(n,"languages",[]).length?null:t.jsx(o.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(E.LanguagesIcon,{className:"w-4 h-4"})})},ea="lang",Ji={id:ea,label:"Languages",position:"top",panel:qr,button:Yi,view:"modal",width:400};function We({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=we.useState(!1),[l,c]=we.useState([]),[u,d]=we.useState(e);we.useEffect(()=>{r||c([]),d(e)},[e,r]);const h=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",g=we.useCallback(p=>{const w=v=>n==="value"?v==="value"||v==="object":n==="array"?v==="array":v===n;p.type==="object"?(c(v=>[...v,p.key]),d(p.value)):w(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),b=we.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);c(p),d(p.reduce((w,v)=>w[v],e))}},[l,e]),y=we.useMemo(()=>Object.entries(u).map(([p,w])=>({key:p,value:w,type:h(w)})).filter(p=>n==="value"?p.type==="value"||p.type==="object":n==="array"?p.type==="array"||p.type==="object":n==="object"?p.type==="object":!0),[u,n]);return t.jsxs(o.Popover,{open:r,onOpenChange:i,children:[t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(E.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(o.TooltipContent,{children:"Add field"})]}),t.jsx(o.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(o.Command,{children:[t.jsx(o.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(o.CommandList,{onWheel:p=>{try{p.preventDefault();const w=p.currentTarget;w.scrollTop+=p.deltaY}catch{p.preventDefault()}},children:[t.jsx(o.CommandEmpty,{children:"No option found."}),t.jsxs(o.CommandGroup,{children:[l.length>0&&t.jsxs(o.CommandItem,{onSelect:b,className:"flex items-center text-sm",children:[t.jsx(E.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(p=>t.jsxs(o.CommandItem,{onSelect:()=>g(p),className:"flex items-center justify-between",children:[t.jsx("span",{children:p.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&p.type==="object"&&t.jsx(o.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:w=>{w.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(E.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const Xi=()=>{const{selectedLang:e}=Q.useLanguages(),{data:s,isFetching:n}=He();return{data:f.useMemo(()=>m.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Zi=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg").forEach(c=>c.remove()),a.querySelectorAll("*").forEach(c=>{Array.from(c.attributes).forEach(u=>c.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(c=>`<${c.tagName.toLowerCase()}>${c.innerHTML}</${c.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},kt=({keyword:e,onComplete:s,field:n})=>{const a=J(),r=re(),{selectedLang:i,fallbackLang:l}=Q.useLanguages(),c=Q.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=B.useMutation({mutationFn:async()=>{const h=Zi();return await a(r,{action:I.GENERATE_SEO_FIELD,data:{pageContext:c,dynamic:!1,field:n,lang:i||l,pageContent:h,keyword:e}})},onSuccess:h=>{s({fieldValue:h.field})},onError:h=>{s({fieldValue:null,error:h.message})}});return t.jsx(o.Button,{disabled:d,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:d?t.jsx(E.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(E.Sparkle,{className:"text-yellow-500"})})},el=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),hn=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,c=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:c,position:l}),a=a.replace(i,c)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,c=l.message.match(/position (\d+)/),u=c?parseInt(c[1]):void 0;let d,h;if(u!==void 0){const g=a.substring(0,u).split(`
3
- `);d=g.length,h=g[g.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:d,column:h,position:u}}}},tl=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,c=new RegExp(el(l),"g");a=a.replace(c,r)}),a},sl=(e,s)=>{if(!e)return"";let n=JSON.stringify(e,null,2);const a=/{{([^{}]+)}}/g;let r;for(;(r=a.exec(n))!==null;){const i=r[1],l=m.get(s,i,null);n=n.replace(r[0],l)}return n},nl=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:l="json-input",pageData:c={},handleFieldInsert:u})=>{const[d,h]=f.useState("edit"),[g,b]=f.useState(null),[y,p]=f.useState(""),w=f.useRef(null),v=S=>{if(a)return;const P=S.target.value;s(P)},N=S=>{if(S.key==="Tab"){S.preventDefault();const P=S.currentTarget,G=P.selectionStart,q=P.selectionEnd;if(G!==q){const se=e.substring(G,q).split(`
4
- `);if(S.shiftKey){const V=se.map(H=>H.startsWith(" ")?H.substring(2):H).join(`
5
- `),te=e.substring(0,G)+V+e.substring(q);s(te),setTimeout(()=>{P.selectionStart=G,P.selectionEnd=G+V.length},0)}else{const V=se.map(H=>` ${H}`).join(`
6
- `),te=e.substring(0,G)+V+e.substring(q);s(te),setTimeout(()=>{P.selectionStart=G,P.selectionEnd=G+V.length},0)}}else{const z=e.substring(0,G)+" "+e.substring(q);s(z),setTimeout(()=>{P.selectionStart=P.selectionEnd=G+2},0)}}};f.useEffect(()=>{const S=hn(e);if(S.isValid)if(b(null),S.parsed){const P=sl(S.parsed,c);p(P)}else p("");else b(S.error),p("")},[e,c]);const C=()=>{const S=hn(e);if(S.isValid&&S.parsed){const P=tl(S.parsed,S.placeholders);s(P)}},_=()=>{g!=null&&g.position&&w.current&&(w.current.focus(),w.current.setSelectionRange(g.position,g.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(o.Tabs,{value:d,onValueChange:h,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(o.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(o.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(E.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(o.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||g!==null,children:[t.jsx(E.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),d==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(We,{dataType:"value",data:c??{},onSelect:S=>u&&u(S,"jsonLD")}),t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:!e.trim()||n||g!==null,children:"Format"})]})]}),t.jsxs(o.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(o.Textarea,{ref:w,id:l,name:l,className:`rounded-md border border-input text-xs ${g?"border-red-500":""}`,onChange:v,onKeyDown:N,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),g&&t.jsxs(o.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(E.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(o.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:g.message}),g.line&&g.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",g.line,", column ",g.column]}),t.jsx(o.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:_,children:"Show position"})]})]})]}),t.jsxs(o.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(o.Textarea,{rows:i,value:y,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]})]})})},fn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},al=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),c=`{{${s}}}`,u=i+""+c+l,d=n+0+c.length;return{value:u,newCursorPos:d}},ta=()=>{const{t:e}=Q.useTranslation(),[,s]=Q.useSidebarActivePanel(),{data:n}=Le(),{data:a}=Hs(),{data:r,isFetching:i}=Xi(),l=r==null?void 0:r.seo,c=f.useRef(null),u=n==null?void 0:n.pageType,d=Rn(u),{selectedLang:h,fallbackLang:g}=Q.useLanguages(),b=h||g,[y,p]=f.useState(!1),[w,v]=f.useState(!1),[N,C]=f.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),_=f.useRef({initial:N,updated:N}),{mutate:S,isPending:P}=Ks(),G=P||y||w,{hasPermission:q}=Q.usePermissions(),z=q(je.EDIT_SEO);f.useEffect(()=>{!i&&l&&C({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const se=async()=>{if(!(!d||!b))try{p(!0);const D=us(d,b),U={...N,keyword:m.get(D,"seo.keyword",""),title:m.get(D,"seo.title",""),description:m.get(D,"seo.description",""),cononicalUrl:m.get(D,"seo.canonicalUrl",""),noIndex:m.get(D,"seo.noIndex",!1),noFollow:m.get(D,"seo.noFollow",!1),ogTitle:m.get(D,"seo.ogTitle",""),ogDescription:m.get(D,"seo.ogDescription","")};C(U),_.current.updated=U,W.toast.success(e("SEO fields reset to defaults"))}catch(D){W.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",D)}finally{p(!1)}},$=async()=>{if(!(!d||!b))try{v(!0);const D=us(d,b),U={...N,jsonLD:m.get(D,"seo.jsonLD","")};C(U),_.current.updated=U,W.toast.success(e("JSON-LD reset to default"))}catch(D){W.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",D)}finally{v(!1)}},V=async()=>{S({id:r==null?void 0:r.id,seo:N},{onSuccess:()=>{_.current.initial=N,_.current.updated=N,s("outline"),W.toast.success("SEO & JSON-LD updated successfully")}})},te=(D,U)=>{const he=document.getElementById(U);if(he){const{value:ye,newCursorPos:ce}=al(he,D);c.current={id:U,position:ce},he.tagName.toLowerCase()==="input"?(he.value=ye,C(A=>({...A,[he.name]:ye})),he.focus(),he.setSelectionRange(ce,ce),[0,10,50,100,200].forEach(A=>{setTimeout(()=>{const M=document.getElementById(U);M&&(M.focus(),M.setSelectionRange(ce,ce))},A)})):(C(x=>({...x,[he.name]:ye})),requestAnimationFrame(()=>{const x=document.getElementById(U);x&&(x.focus(),x.setSelectionRange(ce,ce),setTimeout(()=>{const A=document.getElementById(U);A&&(A.focus(),A.setSelectionRange(ce,ce))},50))}))}},H=D=>{const U={...N,[D.target.name]:D.target.name==="noIndex"||D.target.name==="noFollow"?D.target.checked:D.target.value};C(U),_.current.updated=U},ne=D=>U=>{m.isEmpty(U.fieldValue)||H({target:{name:D,value:typeof U.fieldValue=="string"?U.fieldValue.replace(/^"(.*)"$/,"$1"):U.fieldValue}}),U.error&&W.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:U.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col",children:[!z&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm",children:t.jsx(o.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(o.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"no-scrollbar flex-grow overflow-y-auto px-2 pb-20",children:[t.jsxs("div",{className:"mb-4 flex w-full items-center justify-between rounded-md bg-gray-100 p-2 text-left text-sm font-bold",children:[t.jsxs("span",{children:[r==null?void 0:r.name," ",t.jsx("br",{}),t.jsx("span",{className:"text-xs text-gray-500",children:r==null?void 0:r.slug})]}),t.jsx(Jn,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(o.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(o.TabsList,{className:"mb-4 grid w-full grid-cols-2",children:[t.jsx(o.TabsTrigger,{value:"seo",children:e("SEO Fields")}),t.jsx(o.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(o.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[z&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:se,disabled:G||!z||!d,children:e(y?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),z&&t.jsx(We,{dataType:"value",data:a??{},onSelect:D=>te(D,"keyword")})]}),t.jsx(o.Input,{type:"text",id:"keyword",name:"keyword",value:N.keyword,onChange:H,disabled:G||!z,placeholder:e("Enter keyword"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("title"),field:"title"}),z&&t.jsx(We,{dataType:"value",data:a??{},onSelect:D=>te(D,"title")})]})]}),t.jsx(o.Input,{type:"text",id:"title",name:"title",value:N.title,onChange:H,disabled:G||!z,placeholder:e("Enter SEO title"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("description"),field:"description"}),z&&t.jsx(We,{data:a??{},onSelect:D=>te(D,"description")})]})]}),t.jsx(o.Textarea,{id:"description",name:"description",rows:5,value:N.description,onChange:H,disabled:G||!z,placeholder:e("Enter SEO description"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),z&&t.jsx(We,{dataType:"value",data:a??{},onSelect:D=>te(D,"canonicalUrl")})]}),t.jsx(o.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:N.canonicalUrl,onChange:H,disabled:G||!z,placeholder:e("Enter Canonical URL"),readOnly:!z})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(o.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:N.noIndex,onChange:H,disabled:G||!z,className:"h-4 w-4"}),t.jsx(o.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(o.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:N.noFollow,onChange:H,disabled:G||!z,className:"h-4 w-4"}),t.jsx(o.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to follow links on this page.")})]}),t.jsxs("div",{children:[t.jsx("h3",{className:"mb-4 font-semibold text-slate-700",children:e("Open Graph")}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("ogTitle"),field:"ogTitle"}),z&&t.jsx(We,{dataType:"value",data:a??{},onSelect:D=>te(D,"ogTitle")})]})]}),t.jsx(o.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:N.ogTitle,onChange:H,disabled:G||!z,placeholder:e("Enter OG title"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("ogDescription"),field:"ogDescription"}),z&&t.jsx(We,{dataType:"value",data:a??{},onSelect:D=>te(D,"ogDescription")})]})]}),t.jsx(o.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:N.ogDescription,onChange:H,disabled:G||!z,placeholder:e("Enter OG description"),readOnly:!z})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(o.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Va,{assetId:N.ogImageId,assetUrl:N.ogImage,onChange:D=>{C({...N,ogImage:D.url,ogImageId:D.id})},disabled:G||!z,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(o.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[z&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{variant:"outline",size:"sm",type:"button",onClick:$,disabled:G||!z||!d,children:e(w?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(kt,{keyword:N.keyword,onComplete:ne("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(nl,{id:"jsonLD",value:N.jsonLD,onChange:D=>{H({target:{name:"jsonLD",value:D}})},placeholder:e("Enter JSON-LD"),disabled:G||!z,readOnly:!z,pageData:a||{},rows:12,handleFieldInsert:te})]})]})})]})})]}),z&&t.jsxs("div",{className:"fixed bottom-0 left-0 right-0 flex w-full flex-shrink-0 items-center justify-between border-t bg-background p-4",children:[fn(N.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:e("Invalid JSON. Please check.")}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(o.Button,{onClick:V,disabled:!fn(N==null?void 0:N.jsonLD)||m.isEqual(_.current.initial,N)||G||!z,children:e(P?"Saving...":"Save")}),t.jsx(o.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]})]})};ta.displayName="SeoPanel";const sa="seo",rl=({isActive:e,show:s})=>{const{data:n}=Le(),a=Rn(n==null?void 0:n.pageType);return!m.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(o.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},il={id:sa,label:"SEO & JSON-LD",panel:ta,button:rl,position:"top",width:600,view:"modal"},ll="user-info",ol=()=>{const{user:e,logout:s}=ze(),n=B.useQueryClient(),a=Xe("onLogout",m.noop);return e?t.jsxs(o.HoverCard,{children:[t.jsx(o.HoverCardTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(E.User,{className:"w-4 h-4"})})}),t.jsxs(o.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(o.AlertDialog,{children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(o.AlertDialogContent,{children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(o.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[Y]}),m.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},cl={id:ll,label:"User Info",button:ol,position:"bottom"},ul=()=>{Q.registerChaiSidebarPanel(sa,il),Q.registerChaiSidebarPanel(ea,Ji),Q.registerChaiSidebarPanel("user-info",cl)};var ee={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return gn(this.context.count)},getNextContextId(){return gn(this.context.count++)}};function gn(e){const s=String(e),n=s.length-1;return ee.context.id+(n?String.fromCharCode(96+n):"")+s}function It(e){ee.context=e}var dl=(e,s)=>e===s,ds=Symbol("solid-proxy"),na=typeof Proxy=="function",en=Symbol("solid-track"),ms={equals:dl},aa=da,Ke=1,hs=2,ra={owned:null,cleanups:null,context:null,owner:null},Ts={},me=null,Ps=null,ml=null,xe=null,ke=null,$e=null,ws=0;function Qe(e,s){const n=xe,a=me,r=e.length===0,i=s===void 0?a:s,l=r?ra:{owned:null,cleanups:null,context:i?i.context:null,owner:i},c=r?e:()=>e(()=>Ae(()=>Gt(l)));me=l,xe=null;try{return qe(c,!0)}finally{xe=n,me=a}}function Se(e,s){s=s?Object.assign({},ms,s):ms;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),ua(n,r));return[ca.bind(n),a]}function ia(e,s,n){const a=Ss(e,s,!0,Ke);Tt(a)}function Ye(e,s,n){const a=Ss(e,s,!1,Ke);Tt(a)}function tn(e,s,n){aa=Cl;const a=Ss(e,s,!1,Ke);(!n||!n.render)&&(a.user=!0),$e?$e.push(a):Tt(a)}function _e(e,s,n){n=n?Object.assign({},ms,n):ms;const a=Ss(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Tt(a),ca.bind(a)}function hl(e){return e&&typeof e=="object"&&"then"in e}function fl(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,c=Ts,u=null,d=!1,h="initialValue"in i,g=typeof a=="function"&&_e(a);const b=new Set,[y,p]=(i.storage||Se)(i.initialValue),[w,v]=Se(void 0),[N,C]=Se(void 0,{equals:!1}),[_,S]=Se(h?"ready":"unresolved");ee.context&&(u=ee.getNextContextId(),i.ssrLoadFrom==="initial"?c=i.initialValue:ee.load&&ee.has(u)&&(c=ee.load(u)));function P(se,$,V,te){return l===se&&(l=null,te!==void 0&&(h=!0),(se===c||$===c)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(te,{value:$})),c=Ts,G($,V)),$}function G(se,$){qe(()=>{$===void 0&&p(()=>se),S($!==void 0?"errored":h?"ready":"unresolved"),v($);for(const V of b.keys())V.decrement();b.clear()},!1)}function q(){const se=Sl,$=y(),V=w();if(V!==void 0&&!l)throw V;return xe&&xe.user,$}function z(se=!0){if(se!==!1&&d)return;d=!1;const $=g?g():a;if($==null||$===!1){P(l,Ae(y));return}const V=c!==Ts?c:Ae(()=>r($,{value:y(),refetching:se}));return hl(V)?(l=V,"value"in V?(V.status==="success"?P(l,V.value,void 0,$):P(l,void 0,_s(V.value),$),V):(d=!0,queueMicrotask(()=>d=!1),qe(()=>{S(h?"refreshing":"pending"),C()},!1),V.then(te=>P(V,te,void 0,$),te=>P(V,void 0,_s(te),$)))):(P(l,V,void 0,$),V)}return Object.defineProperties(q,{state:{get:()=>_()},error:{get:()=>w()},loading:{get(){const se=_();return se==="pending"||se==="refreshing"}},latest:{get(){if(!h)return q();const se=w();if(se&&!l)throw se;return y()}}}),g?ia(()=>z(!1)):z(!1),[q,{refetch:z,mutate:p}]}function gl(e){return qe(e,!1)}function Ae(e){if(xe===null)return e();const s=xe;xe=null;try{return e()}finally{xe=s}}function xl(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let c;if(a){c=Array(e.length);for(let d=0;d<e.length;d++)c[d]=e[d]()}else c=e();if(i)return i=!1,l;const u=Ae(()=>s(c,r,l));return r=c,u}}function la(e){tn(()=>Ae(e))}function Et(e){return me===null||(me.cleanups===null?me.cleanups=[e]:me.cleanups.push(e)),e}function xn(){return me}function pl(e,s){const n=me,a=xe;me=e,xe=null;try{return qe(s,!0)}catch(r){sn(r)}finally{me=n,xe=a}}function yl(e){const s=xe,n=me;return Promise.resolve().then(()=>{xe=s,me=n;let a;return qe(e,!1),xe=me=null,a?a.done:void 0})}var[jl,Nc]=Se(!1);function vl(){return[jl,yl]}function bl(e,s){const n=Symbol("context");return{id:n,Provider:Al(n),defaultValue:e}}function wl(e){let s;return me&&me.context&&(s=me.context[e.id])!==void 0?s:e.defaultValue}function oa(e){const s=_e(e),n=_e(()=>Ms(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Sl;function ca(){if(this.sources&&this.state)if(this.state===Ke)Tt(this);else{const e=ke;ke=null,qe(()=>gs(this),!1),ke=e}if(xe){const e=this.observers?this.observers.length:0;xe.sources?(xe.sources.push(this),xe.sourceSlots.push(e)):(xe.sources=[this],xe.sourceSlots=[e]),this.observers?(this.observers.push(xe),this.observerSlots.push(xe.sources.length-1)):(this.observers=[xe],this.observerSlots=[xe.sources.length-1])}return this.value}function ua(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&qe(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=Ps&&Ps.running;l&&Ps.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?ke.push(i):$e.push(i),i.observers&&ma(i)),l||(i.state=Ke)}if(ke.length>1e6)throw ke=[],new Error},!1)),s}function Tt(e){if(!e.fn)return;Gt(e);const s=ws;El(e,e.value,s)}function El(e,s,n){let a;const r=me,i=xe;xe=me=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Ke,e.owned&&e.owned.forEach(Gt),e.owned=null),e.updatedAt=n+1,sn(l)}finally{xe=i,me=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?ua(e,a):e.value=a,e.updatedAt=n)}function Ss(e,s,n,a=Ke,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:me,context:me?me.context:null,pure:n};return me===null||me!==ra&&(me.owned?me.owned.push(i):me.owned=[i]),i}function fs(e){if(e.state===0)return;if(e.state===hs)return gs(e);if(e.suspense&&Ae(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<ws);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Ke)Tt(e);else if(e.state===hs){const a=ke;ke=null,qe(()=>gs(e,s[0]),!1),ke=a}}function qe(e,s){if(ke)return e();let n=!1;s||(ke=[]),$e?n=!0:$e=[],ws++;try{const a=e();return Nl(n),a}catch(a){n||($e=null),ke=null,sn(a)}}function Nl(e){if(ke&&(da(ke),ke=null),e)return;const s=$e;$e=null,s.length&&qe(()=>aa(s),!1)}function da(e){for(let s=0;s<e.length;s++)fs(e[s])}function Cl(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:fs(a)}if(ee.context){if(ee.count){ee.effects||(ee.effects=[]),ee.effects.push(...e.slice(0,n));return}It()}for(ee.effects&&(ee.done||!ee.count)&&(e=[...ee.effects,...e],n+=ee.effects.length,delete ee.effects),s=0;s<n;s++)fs(e[s])}function gs(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===Ke?a!==s&&(!a.updatedAt||a.updatedAt<ws)&&fs(a):r===hs&&gs(a,s)}}}function ma(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=hs,n.pure?ke.push(n):$e.push(n),n.observers&&ma(n))}}function Gt(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--)Gt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Gt(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 _s(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function sn(e,s=me){throw _s(e)}function Ms(e){if(typeof e=="function"&&!e.length)return Ms(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Ms(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Al(e,s){return function(a){let r;return Ye(()=>r=Ae(()=>(me.context={...me.context,[e]:a.value},oa(()=>a.children))),void 0),r}}var Bs=Symbol("fallback");function xs(e){for(let s=0;s<e.length;s++)e[s]()}function Tl(e,s,n={}){let a=[],r=[],i=[],l=0,c=s.length>1?[]:null;return Et(()=>xs(i)),()=>{let u=e()||[],d=u.length,h,g;return u[en],Ae(()=>{let y,p,w,v,N,C,_,S,P;if(d===0)l!==0&&(xs(i),i=[],a=[],r=[],l=0,c&&(c=[])),n.fallback&&(a=[Bs],r[0]=Qe(G=>(i[0]=G,n.fallback())),l=1);else if(l===0){for(r=new Array(d),g=0;g<d;g++)a[g]=u[g],r[g]=Qe(b);l=d}else{for(w=new Array(d),v=new Array(d),c&&(N=new Array(d)),C=0,_=Math.min(l,d);C<_&&a[C]===u[C];C++);for(_=l-1,S=d-1;_>=C&&S>=C&&a[_]===u[S];_--,S--)w[S]=r[_],v[S]=i[_],c&&(N[S]=c[_]);for(y=new Map,p=new Array(S+1),g=S;g>=C;g--)P=u[g],h=y.get(P),p[g]=h===void 0?-1:h,y.set(P,g);for(h=C;h<=_;h++)P=a[h],g=y.get(P),g!==void 0&&g!==-1?(w[g]=r[h],v[g]=i[h],c&&(N[g]=c[h]),g=p[g],y.set(P,g)):i[h]();for(g=C;g<d;g++)g in w?(r[g]=w[g],i[g]=v[g],c&&(c[g]=N[g],c[g](g))):r[g]=Qe(b);r=r.slice(0,l=d),a=u.slice(0)}return r});function b(y){if(i[g]=y,c){const[p,w]=Se(g);return c[g]=w,s(u[g],p)}return s(u[g])}}}function Pl(e,s,n={}){let a=[],r=[],i=[],l=[],c=0,u;return Et(()=>xs(i)),()=>{const d=e()||[],h=d.length;return d[en],Ae(()=>{if(h===0)return c!==0&&(xs(i),i=[],a=[],r=[],c=0,l=[]),n.fallback&&(a=[Bs],r[0]=Qe(b=>(i[0]=b,n.fallback())),c=1),r;for(a[0]===Bs&&(i[0](),i=[],a=[],r=[],c=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=Qe(g));for(;u<a.length;u++)i[u]();return c=l.length=i.length=h,a=d.slice(0),r=r.slice(0,c)});function g(b){i[u]=b;const[y,p]=Se(d[u]);return l[u]=p,s(y,u)}}}function nn(e,s){return Ae(()=>e(s||{}))}function as(){return!0}var Gs={get(e,s,n){return s===ds?n:e.get(s)},has(e,s){return s===ds?!0:e.has(s)},set:as,deleteProperty:as,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:as,deleteProperty:as}},ownKeys(e){return e.keys()}};function ks(e){return(e=typeof e=="function"?e():e)?e:{}}function kl(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function an(...e){let s=!1;for(let l=0;l<e.length;l++){const c=e[l];s=s||!!c&&ds in c,e[l]=typeof c=="function"?(s=!0,_e(c)):c}if(na&&s)return new Proxy({get(l){for(let c=e.length-1;c>=0;c--){const u=ks(e[c])[l];if(u!==void 0)return u}},has(l){for(let c=e.length-1;c>=0;c--)if(l in ks(e[c]))return!0;return!1},keys(){const l=[];for(let c=0;c<e.length;c++)l.push(...Object.keys(ks(e[c])));return[...new Set(l)]}},Gs);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const c=e[l];if(!c)continue;const u=Object.getOwnPropertyNames(c);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const g=Object.getOwnPropertyDescriptor(c,h);if(!a[h])a[h]=g.get?{enumerable:!0,configurable:!0,get:kl.bind(n[h]=[g.get.bind(c)])}:g.value!==void 0?g:void 0;else{const b=n[h];b&&(g.get?b.push(g.get.bind(c)):g.value!==void 0&&b.push(()=>g.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const c=i[l],u=a[c];u&&u.get?Object.defineProperty(r,c,u):r[c]=u?u.value:void 0}return r}function ha(e,...s){if(na&&ds in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(c){return l.includes(c)?e[c]:void 0},has(c){return l.includes(c)&&c in e},keys(){return l.filter(c=>c in e)}},Gs));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))}},Gs)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let c=!1,u=0;for(const d of s)d.includes(r)&&(c=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;c||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function fa(e){let s,n;const a=r=>{const i=ee.context;if(i){const[c,u]=Se();ee.count||(ee.count=0),ee.count++,(n||(n=e())).then(d=>{!ee.done&&It(i),ee.count--,u(()=>d.default),It()}),s=c}else if(!s){const[c]=fl(()=>(n||(n=e())).then(u=>u.default));s=c}let l;return _e(()=>(l=s())?Ae(()=>{if(!i||ee.done)return l(r);const c=ee.context;It(i);const u=l(r);return It(c),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Il=0;function Ll(){return ee.context?ee.getNextContextId():`cl-${Il++}`}var ga=e=>`Stale read from <${e}>.`;function Dl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return _e(Tl(()=>e.each,e.children,s||void 0))}function _l(e){const s="fallback"in e&&{fallback:()=>e.fallback};return _e(Pl(()=>e.each,e.children,s||void 0))}function Ml(e){const s=e.keyed,n=_e(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return _e(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Ae(()=>r(s?a:()=>{if(!Ae(n))throw ga("Show");return e.when})):r}return e.fallback},void 0,void 0)}function Bl(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=oa(()=>e.children),r=_e(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const c=i[l].when;if(c)return s=!!i[l].keyed,[l,c,i[l]]}return[-1]},void 0,{equals:n});return _e(()=>{const[i,l,c]=r();if(i<0)return e.fallback;const u=c.children;return typeof u=="function"&&u.length>0?Ae(()=>u(s?l:()=>{if(Ae(r)[0]!==i)throw ga("Match");return c.when})):u},void 0,void 0)}function Gl(e){return e}var Ol=["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"],Rl=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...Ol]),Ul=new Set(["innerHTML","textContent","innerText","children"]),Fl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),ql=Object.assign(Object.create(null),{class:"className",formnovalidate:{$:"formNoValidate",BUTTON:1,INPUT:1},ismap:{$:"isMap",IMG:1},nomodule:{$:"noModule",SCRIPT:1},playsinline:{$:"playsInline",VIDEO:1},readonly:{$:"readOnly",INPUT:1,TEXTAREA:1}});function zl(e,s){const n=ql[e];return typeof n=="object"?n[s]?n.$:void 0:n}var $l=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Vl=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"]),Hl={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function Kl(e,s,n){let a=n.length,r=s.length,i=a,l=0,c=0,u=s[r-1].nextSibling,d=null;for(;l<r||c<i;){if(s[l]===n[c]){l++,c++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const h=i<a?c?n[c-1].nextSibling:n[i-c]:u;for(;c<i;)e.insertBefore(n[c++],h)}else if(i===c)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[c]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[c++],s[l++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let g=c;for(;g<i;)d.set(n[g],g++)}const h=d.get(s[l]);if(h!=null)if(c<h&&h<i){let g=l,b=1,y;for(;++g<r&&g<i&&!((y=d.get(s[g]))==null||y!==h+b);)b++;if(b>h-c){const p=s[l];for(;c<h;)e.insertBefore(n[c++],p)}else e.replaceChild(n[c++],s[l++])}else l++;else s[l++].remove()}}}var Mt="_$DX_DELEGATE";function xa(e,s,n,a={}){let r;return Qe(i=>{r=i,s===document?e():ys(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function Wl(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 pa(e,s=window.document){const n=s[Mt]||(s[Mt]=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,wa))}}function Ql(e=window.document){if(e[Mt]){for(let s of e[Mt].keys())e.removeEventListener(s,wa);delete e[Mt]}}function ps(e,s,n){at(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function Yl(e,s,n,a){at(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function Jl(e,s,n){at(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function ya(e,s){at(e)||(s==null?e.removeAttribute("class"):e.className=s)}function ja(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 Xl(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const c=r[i];!c||c==="undefined"||s[c]||(pn(e,c,!1),delete n[c])}for(i=0,l=a.length;i<l;i++){const c=a[i],u=!!s[c];!c||c==="undefined"||n[c]===u||!u||(pn(e,c,!0),n[c]=u)}return n}function Zl(e,s,n){if(!s)return n?ps(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function va(e,s={},n,a){const r={};return a||Ye(()=>r.children=Ot(e,s.children,r.children)),Ye(()=>typeof s.ref=="function"&&ba(s.ref,e)),Ye(()=>eo(e,s,n,!0,r,!0)),r}function ba(e,s,n){return Ae(()=>e(s,n))}function ys(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Ot(e,s,a,n);Ye(r=>Ot(e,s(),r,n),a)}function eo(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=yn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const c=s[l];r[l]=yn(e,l,c,r[l],n,i,s)}}function to(e){let s,n;return!at()||!(s=ee.registry.get(n=no()))?e():(ee.completed&&ee.completed.add(s),ee.registry.delete(n),s)}function at(e){return!!ee.context&&!ee.done&&(!e||e.isConnected)}function so(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function pn(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 yn(e,s,n,a,r,i,l){let c,u,d,h,g;if(s==="style")return Zl(e,n,a);if(s==="classList")return Xl(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const b=s.slice(3);a&&e.removeEventListener(b,a,typeof a!="function"&&a),n&&e.addEventListener(b,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const b=s.slice(10);a&&e.removeEventListener(b,a,!0),n&&e.addEventListener(b,n,!0)}else if(s.slice(0,2)==="on"){const b=s.slice(2).toLowerCase(),y=$l.has(b);if(!y&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(b,p)}(y||n)&&(ja(e,b,n,y),y&&pa([b]))}else if(s.slice(0,5)==="attr:")ps(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")Jl(e,s.slice(5),n);else if((g=s.slice(0,5)==="prop:")||(d=Ul.has(s))||!r&&((h=zl(s,e.tagName))||(u=Rl.has(s)))||(c=e.nodeName.includes("-")||"is"in l)){if(g)s=s.slice(5),u=!0;else if(at(e))return n;s==="class"||s==="className"?ya(e,n):c&&!u&&!d?e[so(s)]=n:e[h||s]=n}else{const b=r&&s.indexOf(":")>-1&&Hl[s.split(":")[0]];b?Yl(e,b,s,n):ps(e,Fl[s]||s,n)}return n}function wa(e){if(ee.registry&&ee.events&&ee.events.find(([u,d])=>d===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const d=s[`${n}Data`];if(d!==void 0?u.call(s,d,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},c=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),ee.registry&&!ee.done&&(ee.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,c();break}if(s.parentNode===r)break}}else c();i(a)}function Ot(e,s,n,a,r){const i=at(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,c=a!==void 0;if(e=c&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(c){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=lt(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=lt(e,n,a)}else{if(l==="function")return Ye(()=>{let u=s();for(;typeof u=="function";)u=u();n=Ot(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Os(u,s,n,r))return Ye(()=>n=Ot(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 g=[h];for(;(h=h.nextSibling)!==a;)g.push(h);return n=g}if(u.length===0){if(n=lt(e,n,a),c)return n}else d?n.length===0?jn(e,u,a):Kl(e,n,u):(n&&lt(e),jn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=c?[s]:s;if(Array.isArray(n)){if(c)return n=lt(e,n,a,s);lt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Os(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let c=s[i],u=n&&n[e.length],d;if(!(c==null||c===!0||c===!1))if((d=typeof c)=="object"&&c.nodeType)e.push(c);else if(Array.isArray(c))r=Os(e,c,u)||r;else if(d==="function")if(a){for(;typeof c=="function";)c=c();r=Os(e,Array.isArray(c)?c:[c],Array.isArray(u)?u:[u])||r}else e.push(c),r=!0;else{const h=String(c);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function jn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function lt(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const c=s[l];if(r!==c){const u=c.parentNode===e;!i&&!l?u?e.replaceChild(r,c):e.insertBefore(r,n):u&&c.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function no(){return ee.getNextContextId()}var ao="http://www.w3.org/2000/svg";function Sa(e,s=!1){return s?document.createElementNS(ao,e):document.createElement(e)}function ro(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=xn();let i,l=!!ee.context;return tn(()=>{l&&(xn().user=l=!1),i||(i=pl(r,()=>_e(()=>e.children)));const c=a();if(c instanceof HTMLHeadElement){const[u,d]=Se(!1),h=()=>d(!0);Qe(g=>ys(c,()=>u()?g():i(),null)),Et(h)}else{const u=Sa(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),ys(d,i),c.appendChild(u),e.ref&&e.ref(u),Et(()=>c.removeChild(u))}},void 0,{render:!l}),n}function io(e){const[s,n]=ha(e,["component"]),a=_e(()=>s.component);return _e(()=>{const r=a();switch(typeof r){case"function":return Ae(()=>r(n));case"string":const i=Vl.has(r),l=ee.context?to():Sa(r,i);return va(l,n,i),l}})}var lo=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()}},Ea=class{constructor(e){this.generateIdentifier=e,this.kv=new lo}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)}},oo=class extends Ea{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 co(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 uo(e,s){const n=co(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 Nt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function os(e,s){return e.indexOf(s)!==-1}function vn(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var mo=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return uo(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},ho=e=>Object.prototype.toString.call(e).slice(8,-1),Na=e=>typeof e>"u",fo=e=>e===null,Rt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Rs=e=>Rt(e)&&Object.keys(e).length===0,Je=e=>Array.isArray(e),go=e=>typeof e=="string",xo=e=>typeof e=="number"&&!isNaN(e),po=e=>typeof e=="boolean",yo=e=>e instanceof RegExp,Ut=e=>e instanceof Map,Ft=e=>e instanceof Set,Ca=e=>ho(e)==="Symbol",jo=e=>e instanceof Date&&!isNaN(e.valueOf()),vo=e=>e instanceof Error,bn=e=>typeof e=="number"&&isNaN(e),bo=e=>po(e)||fo(e)||Na(e)||xo(e)||go(e)||Ca(e),wo=e=>typeof e=="bigint",So=e=>e===1/0||e===-1/0,Eo=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),No=e=>e instanceof URL,Aa=e=>e.replace(/\./g,"\\."),Is=e=>e.map(String).map(Aa).join("."),Bt=e=>{const s=[];let n="";for(let r=0;r<e.length;r++){let i=e.charAt(r);if(i==="\\"&&e.charAt(r+1)==="."){n+=".",r++;continue}if(i==="."){s.push(n),n="";continue}n+=i}const a=n;return s.push(a),s};function Fe(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Ta=[Fe(Na,"undefined",()=>null,()=>{}),Fe(wo,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),Fe(jo,"Date",e=>e.toISOString(),e=>new Date(e)),Fe(vo,"Error",(e,s)=>{const n={name:e.name,message:e.message};return s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n},(e,s)=>{const n=new Error(e.message);return n.name=e.name,n.stack=e.stack,s.allowedErrorProps.forEach(a=>{n[a]=e[a]}),n}),Fe(yo,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),Fe(Ft,"set",e=>[...e.values()],e=>new Set(e)),Fe(Ut,"map",e=>[...e.entries()],e=>new Map(e)),Fe(e=>bn(e)||So(e),"number",e=>bn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),Fe(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),Fe(No,"URL",e=>e.toString(),e=>new URL(e))];function Es(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Pa=Es((e,s)=>Ca(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}),Co=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),ka=Es(Eo,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Co[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=Es(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)}),Da=Es((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Ao=[La,Pa,Da,ka],wn=(e,s)=>{const n=vn(Ao,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=vn(Ta,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},_a={};Ta.forEach(e=>{_a[e.annotation]=e});var To=(e,s,n)=>{if(Je(s))switch(s[0]){case"symbol":return Pa.untransform(e,s,n);case"class":return La.untransform(e,s,n);case"custom":return Da.untransform(e,s,n);case"typed-array":return ka.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=_a[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},ot=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function Ma(e){if(os(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(os(e,"prototype"))throw new Error("prototype is not allowed as a property");if(os(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Po=(e,s)=>{Ma(s);for(let n=0;n<s.length;n++){const a=s[n];if(Ft(e))e=ot(e,+a);else if(Ut(e)){const r=+a,i=+s[++n]==0?"key":"value",l=ot(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Us=(e,s,n)=>{if(Ma(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Je(a)){const c=+l;a=a[c]}else if(Rt(a))a=a[l];else if(Ft(a)){const c=+l;a=ot(a,c)}else if(Ut(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=ot(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(Je(a)?a[+r]=n(a[+r]):Rt(a)&&(a[r]=n(a[r])),Ft(a)){const i=ot(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Ut(a)){const i=+s[s.length-2],l=ot(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 Fs(e,s,n=[]){if(!e)return;if(!Je(e)){Nt(e,(i,l)=>Fs(i,s,[...n,...Bt(l)]));return}const[a,r]=e;r&&Nt(r,(i,l)=>{Fs(i,s,[...n,...Bt(l)])}),s(a,n)}function ko(e,s,n){return Fs(s,(a,r)=>{e=Us(e,r,i=>To(i,a,n))}),e}function Io(e,s){function n(a,r){const i=Po(e,Bt(r));a.map(Bt).forEach(l=>{e=Us(e,l,()=>i)})}if(Je(s)){const[a,r]=s;a.forEach(i=>{e=Us(e,Bt(i),()=>e)}),r&&Nt(r,n)}else Nt(s,n);return e}var Lo=(e,s)=>Rt(e)||Je(e)||Ut(e)||Ft(e)||Ia(e,s);function Do(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function _o(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(c=>c.map(String)).sort((c,u)=>c.length-u.length));const[i,...l]=r;i.length===0?a=l.map(Is):n[Is(i)]=l.map(Is)}),a?Rs(n)?[a]:[a,n]:Rs(n)?void 0:n}var Ba=(e,s,n,a,r=[],i=[],l=new Map)=>{const c=bo(e);if(!c){Do(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!Lo(e,n)){const y=wn(e,n),p=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return c||l.set(e,p),p}if(os(i,e))return{transformedValue:null};const u=wn(e,n),d=(u==null?void 0:u.value)??e,h=Je(d)?[]:{},g={};Nt(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 w=Ba(y,s,n,a,[...r,p],[...i,e],l);h[p]=w.transformedValue,Je(w.annotations)?g[p]=w.annotations:Rt(w.annotations)&&Nt(w.annotations,(v,N)=>{g[Aa(p)+"."+N]=v})});const b=Rs(g)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,g]:g};return c||l.set(e,b),b};function Ga(e){return Object.prototype.toString.call(e).slice(8,-1)}function Sn(e){return Ga(e)==="Array"}function Mo(e){if(Ga(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Bo(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 qs(e,s={}){if(Sn(e))return e.map(r=>qs(r,s));if(!Mo(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(Sn(s.props)&&!s.props.includes(i))return r;const l=e[i],c=qs(l,s);return Bo(r,i,c,e,s.nonenumerable),r},{})}var pe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new oo,this.symbolRegistry=new Ea(s=>s.description??""),this.customTransformerRegistry=new mo,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Ba(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=_o(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=qs(s);return n!=null&&n.values&&(a=ko(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Io(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};pe.defaultInstance=new pe;pe.serialize=pe.defaultInstance.serialize.bind(pe.defaultInstance);pe.deserialize=pe.defaultInstance.deserialize.bind(pe.defaultInstance);pe.stringify=pe.defaultInstance.stringify.bind(pe.defaultInstance);pe.parse=pe.defaultInstance.parse.bind(pe.defaultInstance);pe.registerClass=pe.defaultInstance.registerClass.bind(pe.defaultInstance);pe.registerSymbol=pe.defaultInstance.registerSymbol.bind(pe.defaultInstance);pe.registerCustom=pe.defaultInstance.registerCustom.bind(pe.defaultInstance);pe.allowErrorProps=pe.defaultInstance.allowErrorProps.bind(pe.defaultInstance);var Oa=pe.serialize,Go=pe.stringify;function Oo(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function Ro(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 Fo({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function qo(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var zo=(e,s=!1)=>{const{json:n}=Oa(e);return JSON.stringify(n,null,s?2:void 0)},rs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,$o=(e,s)=>e.queryHash.localeCompare(s.queryHash),Ra=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,Vo=(e,s)=>rs(e)===rs(s)?Ra(e,s):rs(e)>rs(s)?1:-1,Ho={status:Vo,"query hash":$o,"last updated":Ra},is=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Ua=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,Ko=(e,s)=>is(e)===is(s)?Ua(e,s):is(e)>is(s)?1:-1,Wo={status:Ko,"last updated":Ua},Qo=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),Yo=()=>{const[e,s]=Se("dark");return la(()=>{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),Et(()=>n.removeEventListener("change",a))}),e},Lt=(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,Lt(a.get(r),i,n)),a}if(e instanceof Set){const a=Lt(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]=Lt(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]=Lt(a[r],i,n),a}return e},Dt=(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,Dt(n.get(a),r)),n}if(e instanceof Set){const n=Dt(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]=Dt(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]=Dt(n[a],r),n}return e},Fa=(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)},ct,qt,zt,$t,tt,Vt,ut,dt,mt,ht,ft,gt,Ht,Cn,Jo=(Cn=class{constructor(e){ge(this,ct);ge(this,qt);ge(this,zt);ge(this,$t);ge(this,tt,!1);ge(this,Vt);ge(this,ut);ge(this,dt);ge(this,mt);ge(this,ht);ge(this,ft);ge(this,gt);ge(this,Ht);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;fe(this,ct,Se(s)),fe(this,zt,n),fe(this,$t,a),fe(this,qt,r),fe(this,Vt,d),fe(this,ut,h),fe(this,dt,Se(i)),fe(this,mt,Se(l)),fe(this,ht,Se(c)),fe(this,ft,Se(u))}setButtonPosition(e){X(this,dt)[1](e)}setPosition(e){X(this,mt)[1](e)}setInitialIsOpen(e){X(this,ht)[1](e)}setErrorTypes(e){X(this,ft)[1](e)}setClient(e){X(this,ct)[1](e)}mount(e){if(X(this,tt))throw new Error("Devtools is already mounted");const s=xa(()=>{const n=this,[a]=X(this,dt),[r]=X(this,mt),[i]=X(this,ht),[l]=X(this,ft),[c]=X(this,ct);let u;return X(this,gt)?u=X(this,gt):(u=fa(()=>Promise.resolve().then(()=>require("./HO4MOOFI-CH7D1iEj.cjs"))),fe(this,gt,u)),Fa(X(this,Vt),X(this,ut)),nn(u,an({get queryFlavor(){return X(n,zt)},get version(){return X(n,$t)},get onlineManager(){return X(n,qt)},get shadowDOMTarget(){return X(n,ut)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);fe(this,tt,!0),fe(this,Ht,s)}unmount(){var e;if(!X(this,tt))throw new Error("Devtools is not mounted");(e=X(this,Ht))==null||e.call(this),fe(this,tt,!1)}},ct=new WeakMap,qt=new WeakMap,zt=new WeakMap,$t=new WeakMap,tt=new WeakMap,Vt=new WeakMap,ut=new WeakMap,dt=new WeakMap,mt=new WeakMap,ht=new WeakMap,ft=new WeakMap,gt=new WeakMap,Ht=new WeakMap,Cn),xt,Kt,Wt,Qt,st,Yt,pt,yt,jt,vt,bt,wt,St,Jt,An,Xo=(An=class{constructor(e){ge(this,xt);ge(this,Kt);ge(this,Wt);ge(this,Qt);ge(this,st,!1);ge(this,Yt);ge(this,pt);ge(this,yt);ge(this,jt);ge(this,vt);ge(this,bt);ge(this,wt);ge(this,St);ge(this,Jt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:g}=e;fe(this,xt,Se(s)),fe(this,Wt,n),fe(this,Qt,a),fe(this,Kt,r),fe(this,Yt,d),fe(this,pt,h),fe(this,yt,Se(i)),fe(this,jt,Se(l)),fe(this,vt,Se(c)),fe(this,bt,Se(u)),fe(this,wt,Se(g))}setButtonPosition(e){X(this,yt)[1](e)}setPosition(e){X(this,jt)[1](e)}setInitialIsOpen(e){X(this,vt)[1](e)}setErrorTypes(e){X(this,bt)[1](e)}setClient(e){X(this,xt)[1](e)}setOnClose(e){X(this,wt)[1](()=>e)}mount(e){if(X(this,st))throw new Error("Devtools is already mounted");const s=xa(()=>{const n=this,[a]=X(this,yt),[r]=X(this,jt),[i]=X(this,vt),[l]=X(this,bt),[c]=X(this,xt),[u]=X(this,wt);let d;return X(this,St)?d=X(this,St):(d=fa(()=>Promise.resolve().then(()=>require("./HUY7CZI3-BLLp9Jcz.cjs"))),fe(this,St,d)),Fa(X(this,Yt),X(this,pt)),nn(d,an({get queryFlavor(){return X(n,Wt)},get version(){return X(n,Qt)},get onlineManager(){return X(n,Kt)},get shadowDOMTarget(){return X(n,pt)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);fe(this,st,!0),fe(this,Jt,s)}unmount(){var e;if(!X(this,st))throw new Error("Devtools is not mounted");(e=X(this,Jt))==null||e.call(this),fe(this,st,!1)}},xt=new WeakMap,Kt=new WeakMap,Wt=new WeakMap,Qt=new WeakMap,st=new WeakMap,Yt=new WeakMap,pt=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,Jt=new WeakMap,An);function Zo(e){const s=B.useQueryClient(e.client),n=we.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}=e,[d]=we.useState(new Jo({client:s,queryFlavor:"React Query",version:"5",onlineManager:B.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}));return we.useEffect(()=>{d.setClient(s)},[s,d]),we.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),we.useEffect(()=>{r&&d.setPosition(r)},[r,d]),we.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),we.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),we.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function ec(e){const s=B.useQueryClient(e.client),n=we.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=we.useState(new Xo({client:s,queryFlavor:"React Query",version:"5",onlineManager:B.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose}));return we.useEffect(()=>{l.setClient(s)},[s,l]),we.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),we.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),we.useEffect(()=>(n.current&&l.mount(n.current),()=>{l.unmount()}),[l]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var tc=process.env.NODE_ENV!=="development"?function(){return null}:Zo;process.env.NODE_ENV;const qa=()=>t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/40",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(E.Loader2,{className:"size-5 animate-spin"})})}),sc=()=>{Q.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"})},nc=()=>{const e=re(),s=J();return B.useQuery({queryKey:[Y,I.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:I.GET_COLLECTIONS})})},ac=()=>{const{data:e}=Le(),{data:s}=At(),{data:n}=Ze(),a=re(),r=J(),i=f.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return B.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}}})})},za=()=>{const e=Xs();return f.useCallback(({pageId:s})=>{e(s)},[e])},rc=60*5;function ic(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:r}=ze(),i=js(),l=f.useRef(null),c=f.useCallback(async()=>{if(!(!m.has(e,"expiresAt")||!m.has(e,"accessToken")||!m.has(e,"refreshToken")))try{const u=await zs(i,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!u.ok){n();return}const d=await u.json();m.has(d,"id")&&m.has(d,"email")&&m.has(d,"accessToken")&&m.has(d,"refreshToken")?s(d):n()}catch{n()}},[e,n,s,i]);return f.useEffect(()=>{a&&r&&c()},[r,a,c]),f.useEffect(()=>{if(!a||!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken"))return;const u=Math.floor(Date.now()/1e3),d=e.expiresAt-u;d<rc&&d>0&&c()},1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[a,e==null?void 0:e.expiresAt,e==null?void 0:e.refreshToken,e==null?void 0:e.accessToken,i]),null}const lc=f.lazy(()=>Promise.resolve().then(()=>wc));sc();Qa.loadWebBlocks();Q.registerChaiTopBar(Ri);ul();Q.registerChaiMediaManager(lc);Q.registerChaiSaveToLibrary(Ar);const oc=e=>{const s=f.useRef([]),[n]=Ie(),a=n.get("page"),{data:r}=Le(),{data:i={role:"",permissions:null}}=Zn();zi();const{data:l,isFetching:c}=On(),{blocks:u}=qi(l),{data:d}=Te(),{mutateAsync:h}=Ln(),g=Ui(),{onSave:b}=$i(),{getPartialBlocks:y,getPartialBlockBlocks:p}=Vi(),{aiContext:w,setAiContext:v}=$s(),{mutateAsync:N}=Pr(),[C,_]=f.useState(!1),{data:S}=Ze(),P=Vs(),{data:G}=Hs(),{data:q}=nc(),{mutateAsync:z}=ac(),se=za();lr(),f.useEffect(()=>{const H=()=>{document.hidden?_(!0):_(!1)};return window.addEventListener("visibilitychange",H),()=>window.removeEventListener("visibilitychange",H)},[]),s.current=u;const $=f.useMemo(()=>{const H={};return i&&(H.permissions=m.get(i,"permissions",null),H.role=m.get(i,"role","user")),H},[i]),V=f.useCallback(async(H,ne)=>await N({pageType:H,query:ne}),[N]),te=f.useMemo(()=>m.get(S,"theme",{})||{},[S]);return t.jsxs(t.Fragment,{children:[c&&t.jsx(qa,{}),t.jsx(Q.ChaiBuilderEditor,{gotoPage:se,collections:q??[],getBlockAsyncProps:z,pageExternalData:G,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:c,fallbackLang:P,languages:(S==null?void 0:S.languages)||[],brandingOptions:(S==null?void 0:S.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!C&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:y,blocks:c?[]:u,theme:m.cloneDeep(te),pageTypes:d,searchPageTypeItems:V,saveAiContextCallback:async H=>{if(!a)return!0;const ne=s.current,D={_type:"@chai/ai-context",_value:m.isString(H)?H:""},U=[...ne,D];return await b({page:a,blocks:U}),v(H),!0},aiContext:w,askAiCallBack:g,onSave:async({blocks:H,theme:ne})=>{if(!a)return!0;s.current=H;const D={_type:"@chai/ai-context",_value:m.isString(w)?w:""},U=[...H,D];return await b({page:a,blocks:U}),s.current=U,m.isEqual(ne,te)||await h({settings:{theme:ne}}),!0},themePanelComponent:Or,...$}),t.jsxs("div",{children:[t.jsx(xr,{}),t.jsx(pr,{})]})]})},cc=new B.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),uc=e=>{ic();const{isLoggedIn:s,isSessionExpired:n}=ze(),[,a]=Dn(),[r,i]=f.useState(!1);return f.useEffect(()=>(a(m.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout"])),setTimeout(()=>{i(!0)},200),()=>{i(!1),a({})}),[e,a]),r?t.jsxs(B.QueryClientProvider,{client:cc,children:[s?n?t.jsx(qa,{}):t.jsx(oc,{...e}):t.jsx(Qi,{}),t.jsx(tc,{}),t.jsx(W.Toaster,{richColors:!0})]}):t.jsx("div",{})},dc=()=>{const e=re(),s=J(),{data:n}=At(),a=B.useQueryClient();return B.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:[Y,I.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[Y,I.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},mc=()=>{const e=Xt(),s=B.useQueryClient(),n=J();return B.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:[Y,I.GET_ASSETS]}),W.toast.success("Asset uploaded successfully")},onError:()=>{W.toast.error("Failed to upload asset")}})},hc=()=>{const e=Xt(),s=B.useQueryClient(),n=J();return B.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:[Y,I.GET_ASSETS]}),W.toast.success("Asset deleted successfully")},onError:()=>{W.toast.error("Failed to delete asset")}})},fc=()=>{const e=Xt(),s=B.useQueryClient(),n=J();return B.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:[Y,I.GET_ASSETS]}),W.toast.success("Asset updated successfully")},onError:()=>{W.toast.error("Failed to update asset")}})},gc=(e={})=>{const s=Xt(),n=J(),{search:a,page:r=1,limit:i=30}=e;return B.useQuery({queryKey:[Y,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})},xc=e=>{const s=Xt(),n=J();return B.useQuery({queryKey:[Y,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 pc(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 En(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 Nn(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 yc=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var g,b,y;const{data:i,isLoading:l,isError:c}=xc(e||""),[u,d]=f.useState(""),h=async(p,w)=>{try{await navigator.clipboard.writeText(p),W.toast.success(`${w} copied to clipboard`)}catch(v){W.toast.error(`Failed to copy ${w}`,{description:v==null?void 0:v.message})}};return f.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin"})}):c||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(E.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:c?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),c&&t.jsx(o.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(o.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(E.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(o.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(o.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(E.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(o.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(E.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((g=i.metadata)==null?void 0:g.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(o.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((b=i.metadata)==null?void 0:b.format)||i.type,capitalize:!0},{label:"Size",value:pc(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:En(i.createdAt)},{label:"Updated",value:En(((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(o.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(o.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(p.value,p.label),children:t.jsx(E.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(o.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,w)=>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,")"]})]},w))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(o.Label,{className:"w-full text-center",children:"Description"}),t.jsx(o.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>d(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!Nn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Nn(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(E.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},jc=f.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function vc(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 bc=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,c]=f.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});f.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=f.useCallback(async y=>new Promise((p,w)=>{const v=y[0],N=new FileReader;N.readAsDataURL(v),N.onload=async()=>{a({file:N.result,folderId:void 0,name:v.name,optimize:l},{onSuccess:C=>{i&&i(C),p(C)},onError:C=>{w(C)}})},N.onerror=C=>w(C)}),[a,l,i]),{getRootProps:h,getInputProps:g,isDragActive:b}=Wa.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:Q.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",b?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...g()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(E.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(E.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(o.Switch,{checked:l,onCheckedChange:y=>{c(y)},onClick:y=>{y.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(E.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(o.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function $a({close:e,onSelect:s,mode:n="image",assetId:a}){const l=f.useMemo(()=>[n],[n]),[c,u]=f.useState(null),[d,h]=f.useState(null),[g,b]=f.useState(null),[y,p]=f.useState({show:!1,file:""}),[w,v]=f.useState(!1),[N,C]=f.useState(a?"details":"grid"),[_,S]=f.useState(""),[P,G]=f.useState(""),[q,z]=f.useState(1),[se]=f.useState(30),[$,V]=f.useState([]);f.useEffect(()=>{a&&(u(a),C("details"))},[a]),f.useEffect(()=>{const L=setTimeout(()=>{S(P),z(1)},300);return()=>clearTimeout(L)},[P]);const{data:te,isLoading:H}=gc({search:_.toLowerCase().trim(),page:q,limit:se}),ne=(te==null?void 0:te.assets)||[],D=(te==null?void 0:te.total)||0,U=Math.ceil(D/se),he=q<U,ye=q>1,ce=(ne==null?void 0:ne.length)>0,{mutate:j}=hc(),{mutate:x,isPending:A}=mc(),{mutate:M,isPending:O}=fc(),T=f.useCallback(L=>{L>=1&&L<=U&&z(L)},[U]),K=f.useCallback(()=>{he&&T(q+1)},[q,he,T]),F=f.useCallback(()=>{ye&&T(q-1)},[q,ye,T]),Z=L=>{G(L.target.value)},de=f.useCallback(L=>{V(le=>m.find(le,{id:L.id})?[]:[L])},[!1]),ve=f.useCallback(()=>{V([])},[]),oe=L=>{(L==null?void 0:L.length)!==0&&(s(m.pick(m.first(L||$),["id","url","width","height","description"])),e())},R=async L=>{h(L)},be=async()=>{d&&(b(d==null?void 0:d.id),await j(d.id,{onSuccess:()=>{b(null),h(null)},onError:()=>{b(null)}}),h(null))},ie=L=>{u(L.id),C("details")},Ne=async(L,le)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";le?(await x({file:L,folderId:void 0,name:y.name||"",optimize:Ee}),p({show:!1,file:""})):(await M({id:y.id||"",file:L}),p({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},De=f.useCallback(L=>{V([L])},[]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"max-w-[1232px] max-h-[1232px] w-[80vw] h-[80vh] space-y-4 flex flex-col",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),N==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(bc,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:O,isUploadingAsset:A,onUploaded:De}),t.jsxs("div",{className:"border p-2 rounded-lg flex-1 flex flex-col gap-y-3 overflow-hidden relative",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2 ",children:[t.jsx(E.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${P.length>0?"text-indigo-800":""}`}),t.jsx(o.Input,{placeholder:"Search assets...",onChange:Z,value:P,className:"pl-8"})]}),$.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[$.length>0&&t.jsx(t.Fragment,{children:t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>ve(),title:"Clear selection",children:"Clear"})}),t.jsx(o.Button,{size:"sm",onClick:()=>oe($),disabled:$.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:H?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"})]}):!H&&!ce?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(E.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:ne==null?void 0:ne.map(L=>t.jsxs("div",{className:Q.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",$.some(le=>le.id===L.id)?"border-blue-500":"hover:border-black/90",g&&(d==null?void 0:d.id)===L.id?"opacity-50 pointer-events-none":"",g===L.id?"opacity-50 pointer-events-none":""),onClick:()=>de(L),onDoubleClick:()=>oe([L]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[g===L.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,L.type==="image"?t.jsx("img",{src:`${L.thumbnailUrl||"/placeholder.svg"}?v=${(L==null?void 0:L.updatedAt)||L.createdAt}`,alt:L.name,className:`object-contain w-full h-full min-h-[80px] ${$.some(le=>le.id===L.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(E.Film,{className:"h-12 w-12 text-muted-foreground"}),L.thumbnailUrl&&t.jsx("img",{src:`${L.thumbnailUrl||"/placeholder.svg"}?v=${(L==null?void 0:L.updatedAt)||L.createdAt}`,alt:L.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:L.name,children:L.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:vc((L==null?void 0:L.size)||0)})})]}),!$.some(le=>le.id===L.id)&&t.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),ie(L)},children:t.jsx(E.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),navigator.clipboard.writeText(L.url),W.toast.success("Asset URL copied to clipboard")},children:t.jsx(E.Copy,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),p({id:L.id,show:!0,file:L.url,name:L.name})},children:t.jsx(E.Edit,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),R(L)},children:t.jsx(E.Trash2,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),$.some(le=>le.id===L.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(E.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},L.id))})}),U>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:F,disabled:!ye,children:"Previous"}),Array.from({length:Math.min(5,U)},(L,le)=>{const Ee=le+1;return t.jsx(o.Button,{variant:q===Ee?"default":"outline",size:"sm",onClick:()=>T(Ee),children:Ee},Ee)}),U>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(o.Button,{variant:q===U?"default":"outline",size:"sm",onClick:()=>T(U),children:U})]}),t.jsx(o.Button,{variant:"outline",size:"sm",onClick:K,disabled:!he,children:"Next"})]})})]})]}):t.jsx(yc,{assetId:c||a||"",onBack:()=>{C("grid"),u(null)},onEdit:L=>{p({id:L.id,show:!0,file:L.url,name:L.name})},onSave:async L=>{if(c){v(!0);try{const le=ne.find(Ee=>Ee.id===c);le&&await M(m.merge(le,{description:L}))}finally{v(!1)}}},isSaving:w})]}),y.show&&t.jsx(f.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(jc,{imageUrl:y.file,onSave:Ne,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),d&&t.jsx(o.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Asset"}),t.jsxs(o.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(o.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(o.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",onClick:be,children:"Delete"})]})]})})]})}const wc=Object.freeze(Object.defineProperty({__proto__:null,default:$a},Symbol.toStringTag,{value:"Module"})),Va=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,c]=f.useState(!1),u=()=>{i||c(!0)},d=()=>{c(!1)},h=b=>{const y=Array.isArray(b)?b[0]:b;y!=null&&y.url&&n(m.pick(y,["url","id"])),c(!1)},g=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(o.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:g,disabled:i,children:t.jsx(E.Trash2,{className:"h-4 w-4"})}),t.jsx(o.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(E.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(E.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(o.Dialog,{open:l,onOpenChange:c,children:t.jsxs(o.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(o.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(o.DialogTitle,{children:"Select Image"}),t.jsx(o.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx($a,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Sc=()=>{const{user:e,logout:s}=ze(),n=e==null?void 0:e.accessToken;return f.useCallback(async({url:a,method:r="GET",body:i={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const c=await fetch(a,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(i)});if(c.status===401)return console.log("Session expired",c),await s(),null;if(c.status===400)throw new Error((await c.json()).error);return await c.json()}catch(c){throw console.log("Something went wrong",c),c}},[n,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=en;exports.ChaiBuilderPages=uc;exports.Dynamic=io;exports.For=Dl;exports.ImagePicker=Va;exports.Index=_l;exports.Match=Gl;exports.NestedPathSelector=We;exports.PermissionChecker=Ge;exports.Portal=ro;exports.Show=Ml;exports.Switch=Bl;exports.addEventListener=ja;exports.batch=gl;exports.className=ya;exports.clearDelegatedEvents=Ql;exports.convertRemToPixels=Qo;exports.createComponent=nn;exports.createComputed=ia;exports.createContext=bl;exports.createEffect=tn;exports.createMemo=_e;exports.createRenderEffect=Ye;exports.createRoot=Qe;exports.createSignal=Se;exports.createUniqueId=Ll;exports.delegateEvents=pa;exports.deleteNestedDataByPath=Dt;exports.displayValue=zo;exports.getMutationStatusColor=Fo;exports.getPreferredColorScheme=Yo;exports.getQueryStatusColor=Uo;exports.getQueryStatusColorByLabel=qo;exports.getQueryStatusLabel=Oo;exports.getSidedProp=Ro;exports.insert=ys;exports.mergeProps=an;exports.mutationSortFns=Wo;exports.on=xl;exports.onCleanup=Et;exports.onMount=la;exports.registerLoginComponent=Wi;exports.serialize=Oa;exports.setAttribute=ps;exports.sortFns=Ho;exports.splitProps=ha;exports.spread=va;exports.stringify=Go;exports.template=Wl;exports.untrack=Ae;exports.updateNestedDataByPath=Lt;exports.use=ba;exports.useActivePage=At;exports.useBuilderPageData=Hs;exports.useChaiAuth=ze;exports.useChaiFetch=Sc;exports.useChaiUserInfo=nt;exports.useContext=wl;exports.useCurrentPage=Le;exports.useFallbackLang=Vs;exports.useFetch=J;exports.useGotoPage=za;exports.useLanguagePages=He;exports.usePageTypes=Te;exports.useTransition=vl;exports.useUpdateActivePageMetadata=dc;exports.useUserRoleAndPermissions=Zn;exports.useWebsitePages=Zt;exports.useWebsiteSetting=Ze;