@chaibuilder/pages 0.6.2 → 0.6.3

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.
@@ -0,0 +1,2 @@
1
+ "use strict";var Qs=e=>{throw TypeError(e)};var Ys=(e,s,n)=>s.has(e)||Qs("Cannot "+n);var K=(e,s,n)=>(Ys(e,s,"read from private field"),n?n.call(e):s.get(e)),me=(e,s,n)=>s.has(e)?Qs("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),he=(e,s,n,a)=>(Ys(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),g=require("lodash-es"),m=require("react"),Re=require("jotai"),D=require("@tanstack/react-query"),$=require("sonner"),W=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),St=require("date-fns"),N=require("lucide-react"),pn=require("@chaibuilder/runtime"),Xt=require("zod"),Da=require("react-dropzone"),Ma=require("@chaibuilder/sdk/web-blocks");function Ba(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 je=Ba(m),ke={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},k={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},z="chaibuilder";let Ga=0;function Xs(e,s){const n=`atom${++Ga}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Ua,a.write=Ra),s&&(a.write=s),a}function Ua(e){return e(this)}function Ra(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const Oa=Symbol(""),Fa=e=>typeof(e==null?void 0:e.then)=="function";function qa(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,i;const r={getItem:(u,d)=>{var h,f;const j=x=>{if(x=x||"",a!==x){try{i=JSON.parse(x,s==null?void 0:s.reviver)}catch{return d}a=x}return i},y=(f=(h=e())==null?void 0:h.getItem(u))!=null?f:null;return Fa(y)?y.then(j):j(y)},setItem:(u,d)=>{var h;return(h=e())==null?void 0:h.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,h,f)=>u(d,j=>{let y;try{y=JSON.parse(j||"")}catch{y=f}h(y)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=f=>{f.storageArea===e()&&f.key===u&&d(f.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),o&&(r.subscribe=l(o)),r}const za=qa();function xn(e,s,n=za,a){const i=Xs(s);return i.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Xs(l=>l(i),(l,o,u)=>{const d=typeof u=="function"?u(l(i)):u;return d===Oa?(o(i,s),n.removeItem(e)):d instanceof Promise?d.then(h=>(o(i,h),n.setItem(e,h))):(o(i,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const yn="__logged_in_user",$a=xn(yn,null),Oe=()=>{const[e,s]=Re.useAtom($a),n=m.useCallback(()=>{s(null),localStorage.removeItem(yn)},[s]),a=m.useMemo(()=>{if(!e||!(e!=null&&e.refreshToken))return!0;const i=Math.floor(Date.now()/1e3);return e.expiresAt-i<=0},[e]);return{isLoggedIn:!!e,isSessionExpired:a,user:e,setUser:s,logout:n}},ks=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),H=()=>{const{user:e,logout:s}=Oe(),n=D.useQueryClient(),a=e==null?void 0:e.accessToken;return m.useCallback(async(i,r,l={})=>{if(!a)return null;try{const o=g.get(r,"action","").toLowerCase(),u=await ks(i+(o?`?action=${o}`:""),r,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[z]}),s(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(o){throw console.error("API request failed:",r,o),o}},[a,s,n])},vn=()=>{const e=ae(),s=D.useQueryClient(),n=H();return D.useMutation({mutationFn:async a=>n(e,{action:k.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[z,k.GET_DRAFT_PAGE]})}})},jn=()=>{const e=ae(),s=D.useQueryClient(),n=H();return D.useMutation({mutationFn:async a=>n(e,{action:k.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,i)=>{var r;s.invalidateQueries({queryKey:[z,k.GET_WEBSITE_DRAFT_SETTINGS]}),(r=i==null?void 0:i.settings)!=null&&r.theme||$.toast.success("Website settings updated successfully.")},onError:a=>{$.toast.error("Failed to update website settings",{description:a.message})}})},Ha=()=>{const e=ae(),s=D.useQueryClient(),n=H();return D.useMutation({mutationFn:async a=>n(e,{action:k.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[z,k.GET_WEBSITE_DATA]}),$.toast.success("Website data updated successfully.")},onError:a=>{$.toast.error("Failed to update website data",{description:a.message})}})};function _e(){const[e,s]=m.useState(new URLSearchParams(window.location.search));return m.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Va=Re.atom({}),bn=()=>Re.useAtom(Va),Ka=()=>{const[e]=_e(),s=e.get("page"),n=m.useRef(""),{mutate:a}=vn();m.useEffect(()=>{!g.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},qe=(e,s)=>{const[n]=bn();return m.useMemo(()=>g.get(n,e,s),[n,e,s])},ae=()=>qe("apiUrl","/chai/api"),os=()=>qe("usersApiUrl","/chai/users"),Ht=()=>qe("assetsApiUrl","/chai/assets"),Qe=e=>{const s=ae(),[n]=_e(),a=e??n.get("page"),i=H();return D.useQuery({queryKey:[z,k.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const r=await i(s,{action:k.GET_LANGUAGE_PAGES,data:{id:a}});return g.reverse(g.sortBy(r,"primaryPage"))},enabled:!!a})},Ye=()=>{const e=ae(),s=H();return D.useQuery({queryKey:[z,k.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:k.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},En=e=>{const{fallbackLang:s}=W.useLanguages(),{data:n}=Ye(),{data:a,isFetching:i}=Qe(),r=m.useMemo(()=>{const l={[s]:!0};return g.each(g.get(n,"languages"),o=>{const u=g.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return i||g.isEmpty(e)||e&&r[e]},Is=()=>{const e=D.useQueryClient(),{data:s}=D.useQuery({queryKey:[z,k.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:m.useCallback(a=>{e.setQueryData([z,k.AI_CONTEXT],a)},[e]),aiContext:s}},Vt=()=>{const e=H(),s=ae();return D.useQuery({queryKey:[z,k.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:k.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},Wa=Re.atom({lastSaved:void 0}),cs=()=>Re.useAtom(Wa),De=()=>{const[e]=_e(),s=e.get("page"),[n]=Sn(),{data:a,isFetching:i}=Vt();return{data:m.useMemo(()=>({...g.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:i}},us=()=>{const[e]=_e(),s=e.get("lang")??"",{data:n,isFetching:a}=Qe();return{data:m.useMemo(()=>g.find(n,{lang:s})||{},[n,s]),isFetching:a}},Qa=Re.atom({}),Sn=()=>Re.useAtom(Qa),tt=e=>{const s=os(),n=H();return D.useQuery({queryKey:[z,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:k.GET_CHAI_USER,data:{userId:e}}),enabled:!g.isEmpty(e)})},Ya=Re.atom(void 0),Kt=()=>{const[e]=_e(),s=e.get("page"),{user:n}=Oe(),[a,i]=Re.useAtom(Ya);return m.useMemo(()=>({isLocked:s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:r=>i(r)}),[n==null?void 0:n.id,a,s,i])},_s=()=>{const{data:e}=Ye();return m.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},wn=()=>{const[e]=_e(),s=e.get("page"),n=ae(),{setAiContext:a}=Is(),{setCurrentEditor:i}=Kt(),[,r]=cs(),[,l]=Sn(),o=H();return D.useQuery({queryKey:[z,k.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{i("");const u=await o(n,{action:k.GET_DRAFT_PAGE,data:{id:s,draft:!0}});i(u.currentEditor);const d=u.blocks??[],h=g.find(d,{_type:"@chai/ai-context"});return a(g.get(h,"_value","")||""),r(f=>({...f,lastSaved:u.lastSaved})),l(g.get(u,"metadata",{})),d},enabled:!!s})},Ls=()=>{const{data:e}=De(),{data:s}=us(),n=ae(),a=H(),i=_s();return D.useQuery({queryKey:[z,k.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id],initialData:{},queryFn:async()=>(console.log(s,e),a(n,{action:k.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||i,dynamic:e==null?void 0:e.dynamic,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}}})),enabled:!!(s!=null&&s.pageType)})};function Xa({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:i}){const[r,l]=m.useState(!1),o=()=>{l(!1),i()};return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-[50px] bg-black/30 backdrop-blur-sm",children:t.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"w-6 h-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"w-12 h-12 border border-gray-300 rounded-full"}):t.jsx(N.UserIcon,{className:"w-12 h-12 p-2 border border-gray-300 rounded-full"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n}),a&&t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",St.formatDistanceToNow(new Date(a),{addSuffix:!0})]})]})]}),t.jsx("div",{className:"text-sm mt-4",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(c.CardFooter,{children:t.jsxs(c.AlertDialog,{open:r,onOpenChange:l,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take Over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(N.AlertTriangleIcon,{className:"w-5 h-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:o,children:"Yes, Take Over"})]})]})]})})]})})}const Za=()=>{const{isLocked:e,currentEditor:s}=Kt(),{data:n}=tt(s),[a]=_e(),i=a.get("page"),{mutate:r}=vn(),{isFetching:l}=wn(),[o]=cs(),u=m.useCallback(()=>{r({id:i})},[i,r]);return!e||l?t.jsx("div",{className:""}):t.jsx(Xa,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",lastSaved:(o==null?void 0:o.lastSaved)||"",onTakeOver:u})},Ja=()=>{const[e,s]=_e(),n=e.get("lang"),a=En(n),{setSelectedLang:i}=W.useLanguages(),r=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(o),i(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=g.get(ke,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-12 bg-black/30 backdrop-blur-sm",children:t.jsxs(c.Card,{className:"w-full max-w-md mx-auto",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"w-6 h-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(c.CardFooter,{children:t.jsx(c.Button,{onClick:r,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},er=e=>{const s=ae(),n=H();return D.useMutation({mutationFn:async a=>n(s,{action:k.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),$.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},tr=e=>{const s=ae(),n=H();return D.useQuery({queryKey:[z,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:k.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})},sr=e=>{const s=ae(),n=H();return D.useMutation({mutationFn:async a=>n(s,{action:k.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),$.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},nr=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:i,trigger:r})=>{const[l,o]=m.useState(!1),u=W.useUpdateBlocksPropsRealtime(),d=sr(()=>{u([e],{_libBlockId:void 0}),$.toast.success("Block deleted successfully"),o(!1),a()}),h=()=>{o(!0),d.mutate(s)},f=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:j=>j.preventDefault(),disabled:l,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:j=>!j&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:r||f}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',i,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},ar=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:i="",close:r})=>{const[l,o]=m.useState(!1);return t.jsx(nr,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{o(!1),r()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:i,onClick:()=>o(!0),children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},rr=()=>{const e=ae(),s=H(),n=D.useQueryClient(),{data:a=[],isLoading:i,error:r}=D.useQuery({queryKey:[z,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:o}=D.useMutation({mutationFn:async u=>{if(!u.trim())throw new Error("Group name is required");return s(e,{action:"CREATE_BLOCK_GROUP",data:{name:u}})},onSuccess:()=>{n.invalidateQueries({queryKey:[z,"library-groups"]}),$.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),$.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:i,error:r,createGroup:l,isCreating:o}},ir=({value:e,onChange:s})=>{const[n,a]=m.useState(!1),[i,r]=m.useState(""),l=m.useRef(null),{groups:o}=rr(),[u,d]=m.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=m.useMemo(()=>[...o,...u.filter(y=>!o.some(x=>x.id===y.id))],[o,u]),f=()=>{const y=i.trim();if(!y)return;const x={id:y,name:y};d(E=>[...E,x]),s(x.id),r(""),a(!1)};m.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const j=y=>{y.key==="Enter"&&(y.preventDefault(),f())};return m.useEffect(()=>{e&&!h.some(y=>y.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:i,onChange:y=>r(y.target.value),onKeyDown:j}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:f,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!o.some(x=>x.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(N.Plus,{className:"h-4 w-4"})})]})},lr=10*1024*1024,or=({value:e,onChange:s})=>{const[n,a]=m.useState(!1),i=m.useRef(null),r=m.useCallback(u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d){if(d.size>lr){$.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),i.current&&(i.current.value="");return}try{a(!0);const f=new FileReader;f.onloadend=()=>{s(f.result),a(!1)},f.readAsDataURL(d)}catch(f){console.error("Error reading file:",f),a(!1),$.toast.error("Failed to process image",{description:f instanceof Error?f.message:"Unknown error"})}}},[s]),l=()=>{s(""),i.current&&(i.current.value="")},o=()=>{var u;(u=i.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:i,onChange:r,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},pe={...W.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"},cr=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:i}=W.usePartailBlocksStore(),r=s.find(T=>T._id===a),l=r==null?void 0:r._libBlockId,o=!!l,u=m.useMemo(()=>s.some(T=>T._type==="PartialBlock"||T._type==="GlobalBlock"),[s]),d=m.useMemo(()=>{let T=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let R=i(M.partialBlockId);M._parent&&(R==null?void 0:R.length)>0&&(R=R.map(C=>(g.isEmpty(C._parent)&&g.set(C,"_parent",M._parent),C))),T=[...T,...R]}else T.push(M);return T},[s,i]),[h,f]=m.useState(""),[j,y]=m.useState(""),[x,E]=m.useState(""),[b,U]=m.useState(""),[w,B]=m.useState({}),[S,_]=m.useState(!1),[O,V]=m.useState(o),[ne,G]=m.useState(!1),{hasPermission:L}=W.usePermissions(),F=L(pe.DELETE_LIBRARY_BLOCK),Y=W.useUpdateBlocksPropsRealtime(),Q=()=>{Y([a],{_libBlockId:void 0}),$.toast.success("Block delinked from library"),n()},{data:X,isLoading:le,isError:I}=tr(l);m.useEffect(()=>{I&&o&&(G(!0),V(!1))},[I,o]),m.useEffect(()=>{X&&!le&&(f(X.name||""),y(X.group||""),E(X.description||""),U(X.preview||""),V(!1))},[X,le]),m.useEffect(()=>{const T=h.trim().length>=2,M=j.trim()!=="";_(T&&M)},[h,j]);const xe=()=>{const T={};return h.trim()?h.length<2&&(T.name="Name must be at least 2 characters"):T.name="Name is required",j||(T.group="Group is required"),B(T),Object.keys(T).length===0},{resetLibrary:Te}=W.useLibraryBlocks({id:""}),Z=er(T=>{o||Y([a],{_libBlockId:T.id}),$.toast.success(`Block ${o?"updated":"saved"} successfully`),Te(T.library),n()}),v=async T=>{if(T.preventDefault(),!xe())return;const M=d.map(R=>(g.has(R,"_libBlockId")&&delete R._libBlockId,R));Z.mutate({name:h.trim(),group:j,blocks:M,description:x.trim(),...b&&b.startsWith("data:")?{previewImage:b}:{},...o?{id:l}:{}})},p=Z.isPending;return O||le?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"})}):ne?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:Q,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(N.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:v,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:w.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:T=>f(T.target.value),className:w.name?"border-destructive":""}),w.name&&t.jsx("p",{className:"text-xs text-destructive",children:w.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:w.group?"text-destructive":"",children:"Group"}),t.jsx(ir,{value:j,onChange:y}),w.group&&t.jsx("p",{className:"text-xs text-destructive",children:w.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:x,onChange:T=>E(T.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(or,{value:b,onChange:U})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&F&&t.jsx(ar,{blockId:a,libBlockId:l,blockName:h,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:p,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:p||!S,children:p?"Saving...":o?"Update Block":"Save Block"})]})]})]})},te={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},ur={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ne=()=>{const e=ae(),s=H();return D.useQuery({queryKey:[z,k.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:k.GET_PAGE_TYPES})})},dr=e=>{const{data:s}=Ne();return m.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},hr=()=>{const e=ae(),s=H();return D.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:k.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(i){return console.error(i),[]}}})},Nn=()=>{const e=ae(),s=D.useQueryClient(),n=H(),{data:a}=Ne();return D.useMutation({mutationFn:async i=>await n(e,{action:k.CREATE_PAGE,data:i}),onSuccess:(i,r)=>{var o;r&&(r!=null&&r.primaryPage)?s.invalidateQueries({queryKey:[z,k.GET_LANGUAGE_PAGES,r==null?void 0:r.primaryPage]}):s.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]});const l=r.template?`Page created from "${r.template.name}" template`:r.hasSlug===!1?"New "+((o=g.find(a,{key:r.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";$.toast.success(l)},onError:(i,r)=>{const l=g.find(a,{key:r.pageType});$.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:g.get(ur,i.message,i.message)})}})},Ds=()=>{const e=ae(),s=D.useQueryClient(),n=H(),{data:a}=Ne();return D.useMutation({mutationFn:async i=>await n(e,{action:k.UPDATE_PAGE,data:i}),onSuccess:(i,r)=>{r&&(r!=null&&r.primaryPage||r!=null&&r.seo)?s.invalidateQueries({queryKey:[z,k.GET_LANGUAGE_PAGES,r==null?void 0:r.primaryPage]}):s.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]})},onError:(i,r)=>{const l=g.find(a,{key:r.pageType});$.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:i.message})}})},mr=()=>{const e=ae(),s=D.useQueryClient(),n=H(),{data:a}=Ne();return D.useMutation({mutationFn:async i=>n(e,{action:k.DELETE_PAGE,data:{id:i==null?void 0:i.id}}),onSuccess:(i,r)=>{if(i.code==="PAGE_LOCKED"){$.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}r&&(r!=null&&r.primaryPage)?s.invalidateQueries({queryKey:[z,k.GET_LANGUAGE_PAGES,r==null?void 0:r.primaryPage]}):s.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]})},onError:(i,r)=>{const l=g.find(a,{key:r.pageType});$.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:i.message})}})},fr=()=>{const e=ae(),s=D.useQueryClient(),n=H(),{data:a}=Ne();return D.useMutation({mutationFn:async i=>n(e,{action:k.TAKE_OFFLINE,data:{id:i==null?void 0:i.id}}),onSuccess:(i,r)=>{r&&(r!=null&&r.primaryPage)?s.invalidateQueries({queryKey:[z,k.GET_LANGUAGE_PAGES,r==null?void 0:r.primaryPage]}):s.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]});const l=g.find(a,{key:r.pageType});$.toast.success(l!=null&&l.hasSlug?te.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(i,r)=>{const l=g.find(a,{key:r.pageType});$.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:i.message})}})},Ms=()=>{const e=ae(),s=H(),n=D.useQueryClient(),{data:a}=De();return D.useMutation({mutationFn:async({ids:i})=>s(e,{action:k.PUBLISH_CHANGES,data:{ids:i}}),onSuccess:()=>{n.invalidateQueries({queryKey:[z,k.GET_CHANGES]}),n.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[z,k.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{$.toast.error("Failed to publish pages.")}})},gr=()=>{const e=ae(),s=H(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>{var i;return s(e,{action:k.MARK_AS_TEMPLATE,data:{id:(i=a.page)==null?void 0:i.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]}),$.toast.success("Page marked as template successfully.")},onError:()=>{$.toast.error("Failed to mark page as template.")}})},pr=()=>{const e=ae(),s=H(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>s(e,{action:k.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]}),$.toast.success("Page unmarked as template successfully.")},onError:()=>{$.toast.error("Failed to unmark page as template.")}})},xr=()=>{const e=ae(),s=H(),n=D.useQueryClient();return D.useMutation({mutationFn:async({id:a,slug:i})=>s(e,{action:k.CHANGE_SLUG,data:{id:a,slug:i}}),onSuccess:(a,{primaryPage:i})=>{$.toast.success(te.SLUG_CHANGE_SUCCESS),i?n.invalidateQueries({queryKey:[z,k.GET_LANGUAGE_PAGES,i]}):n.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]})},onError:()=>{$.toast.error("Failed to change slug")}})};var Bs={};(function e(s,n,a,i){var r=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!s.OffscreenCanvas)return!1;var v=new OffscreenCanvas(1,1),p=v.getContext("2d");p.fillRect(0,0,1,1);var T=v.transferToImageBitmap();try{p.createPattern(T,"no-repeat")}catch{return!1}return!0}();function u(){}function d(v){var p=n.exports.Promise,T=p!==void 0?p:s.Promise;return typeof T=="function"?new T(v):(v(u,u),null)}var h=function(v,p){return{transform:function(T){if(v)return T;if(p.has(T))return p.get(T);var M=new OffscreenCanvas(T.width,T.height),R=M.getContext("2d");return R.drawImage(T,0,0),p.set(T,M),M},clear:function(){p.clear()}}}(o,new Map),f=function(){var v=Math.floor(16.666666666666668),p,T,M={},R=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(p=function(C){var ee=Math.random();return M[ee]=requestAnimationFrame(function q(se){R===se||R+v-1<se?(R=se,delete M[ee],C()):M[ee]=requestAnimationFrame(q)}),ee},T=function(C){M[C]&&cancelAnimationFrame(M[C])}):(p=function(C){return setTimeout(C,v)},T=function(C){return clearTimeout(C)}),{frame:p,cancel:T}}(),j=function(){var v,p,T={};function M(R){function C(ee,q){R.postMessage({options:ee||{},callback:q})}R.init=function(q){var se=q.transferControlToOffscreen();R.postMessage({canvas:se},[se])},R.fire=function(q,se,ue){if(p)return C(q,null),p;var ye=Math.random().toString(36).slice(2);return p=d(function(de){function ve(Ee){Ee.data.callback===ye&&(delete T[ye],R.removeEventListener("message",ve),p=null,h.clear(),ue(),de())}R.addEventListener("message",ve),C(q,ye),T[ye]=ve.bind(null,{data:{callback:ye}})}),p},R.reset=function(){R.postMessage({reset:!0});for(var q in T)T[q](),delete T[q]}}return function(){if(v)return v;if(!a&&r){var R=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
2
+ `);try{v=new Worker(URL.createObjectURL(new Blob([R])))}catch(C){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",C),null}M(v)}return v}}(),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 x(v,p){return p?p(v):v}function E(v){return v!=null}function b(v,p,T){return x(v&&E(v[p])?v[p]:y[p],T)}function U(v){return v<0?0:Math.floor(v)}function w(v,p){return Math.floor(Math.random()*(p-v))+v}function B(v){return parseInt(v,16)}function S(v){return v.map(_)}function _(v){var p=String(v).replace(/[^0-9a-f]/gi,"");return p.length<6&&(p=p[0]+p[0]+p[1]+p[1]+p[2]+p[2]),{r:B(p.substring(0,2)),g:B(p.substring(2,4)),b:B(p.substring(4,6))}}function O(v){var p=b(v,"origin",Object);return p.x=b(p,"x",Number),p.y=b(p,"y",Number),p}function V(v){v.width=document.documentElement.clientWidth,v.height=document.documentElement.clientHeight}function ne(v){var p=v.getBoundingClientRect();v.width=p.width,v.height=p.height}function G(v){var p=document.createElement("canvas");return p.style.position="fixed",p.style.top="0px",p.style.left="0px",p.style.pointerEvents="none",p.style.zIndex=v,p}function L(v,p,T,M,R,C,ee,q,se){v.save(),v.translate(p,T),v.rotate(C),v.scale(M,R),v.arc(0,0,1,ee,q,se),v.restore()}function F(v){var p=v.angle*(Math.PI/180),T=v.spread*(Math.PI/180);return{x:v.x,y:v.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:v.startVelocity*.5+Math.random()*v.startVelocity,angle2D:-p+(.5*T-Math.random()*T),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:v.color,shape:v.shape,tick:0,totalTicks:v.ticks,decay:v.decay,drift:v.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:v.gravity*3,ovalScalar:.6,scalar:v.scalar,flat:v.flat}}function Y(v,p){p.x+=Math.cos(p.angle2D)*p.velocity+p.drift,p.y+=Math.sin(p.angle2D)*p.velocity+p.gravity,p.velocity*=p.decay,p.flat?(p.wobble=0,p.wobbleX=p.x+10*p.scalar,p.wobbleY=p.y+10*p.scalar,p.tiltSin=0,p.tiltCos=0,p.random=1):(p.wobble+=p.wobbleSpeed,p.wobbleX=p.x+10*p.scalar*Math.cos(p.wobble),p.wobbleY=p.y+10*p.scalar*Math.sin(p.wobble),p.tiltAngle+=.1,p.tiltSin=Math.sin(p.tiltAngle),p.tiltCos=Math.cos(p.tiltAngle),p.random=Math.random()+2);var T=p.tick++/p.totalTicks,M=p.x+p.random*p.tiltCos,R=p.y+p.random*p.tiltSin,C=p.wobbleX+p.random*p.tiltCos,ee=p.wobbleY+p.random*p.tiltSin;if(v.fillStyle="rgba("+p.color.r+", "+p.color.g+", "+p.color.b+", "+(1-T)+")",v.beginPath(),l&&p.shape.type==="path"&&typeof p.shape.path=="string"&&Array.isArray(p.shape.matrix))v.fill(xe(p.shape.path,p.shape.matrix,p.x,p.y,Math.abs(C-M)*.1,Math.abs(ee-R)*.1,Math.PI/10*p.wobble));else if(p.shape.type==="bitmap"){var q=Math.PI/10*p.wobble,se=Math.abs(C-M)*.1,ue=Math.abs(ee-R)*.1,ye=p.shape.bitmap.width*p.scalar,de=p.shape.bitmap.height*p.scalar,ve=new DOMMatrix([Math.cos(q)*se,Math.sin(q)*se,-Math.sin(q)*ue,Math.cos(q)*ue,p.x,p.y]);ve.multiplySelf(new DOMMatrix(p.shape.matrix));var Ee=v.createPattern(h.transform(p.shape.bitmap),"no-repeat");Ee.setTransform(ve),v.globalAlpha=1-T,v.fillStyle=Ee,v.fillRect(p.x-ye/2,p.y-de/2,ye,de),v.globalAlpha=1}else if(p.shape==="circle")v.ellipse?v.ellipse(p.x,p.y,Math.abs(C-M)*p.ovalScalar,Math.abs(ee-R)*p.ovalScalar,Math.PI/10*p.wobble,0,2*Math.PI):L(v,p.x,p.y,Math.abs(C-M)*p.ovalScalar,Math.abs(ee-R)*p.ovalScalar,Math.PI/10*p.wobble,0,2*Math.PI);else if(p.shape==="star")for(var re=Math.PI/2*3,Se=4*p.scalar,Ce=8*p.scalar,P=p.x,ie=p.y,A=5,oe=Math.PI/A;A--;)P=p.x+Math.cos(re)*Ce,ie=p.y+Math.sin(re)*Ce,v.lineTo(P,ie),re+=oe,P=p.x+Math.cos(re)*Se,ie=p.y+Math.sin(re)*Se,v.lineTo(P,ie),re+=oe;else v.moveTo(Math.floor(p.x),Math.floor(p.y)),v.lineTo(Math.floor(p.wobbleX),Math.floor(R)),v.lineTo(Math.floor(C),Math.floor(ee)),v.lineTo(Math.floor(M),Math.floor(p.wobbleY));return v.closePath(),v.fill(),p.tick<p.totalTicks}function Q(v,p,T,M,R){var C=p.slice(),ee=v.getContext("2d"),q,se,ue=d(function(ye){function de(){q=se=null,ee.clearRect(0,0,M.width,M.height),h.clear(),R(),ye()}function ve(){a&&!(M.width===i.width&&M.height===i.height)&&(M.width=v.width=i.width,M.height=v.height=i.height),!M.width&&!M.height&&(T(v),M.width=v.width,M.height=v.height),ee.clearRect(0,0,M.width,M.height),C=C.filter(function(Ee){return Y(ee,Ee)}),C.length?q=f.frame(ve):de()}q=f.frame(ve),se=de});return{addFettis:function(ye){return C=C.concat(ye),ue},canvas:v,promise:ue,reset:function(){q&&f.cancel(q),se&&se()}}}function X(v,p){var T=!v,M=!!b(p||{},"resize"),R=!1,C=b(p,"disableForReducedMotion",Boolean),ee=r&&!!b(p||{},"useWorker"),q=ee?j():null,se=T?V:ne,ue=v&&q?!!v.__confetti_initialized:!1,ye=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,de;function ve(re,Se,Ce){for(var P=b(re,"particleCount",U),ie=b(re,"angle",Number),A=b(re,"spread",Number),oe=b(re,"startVelocity",Number),Pe=b(re,"decay",Number),Ae=b(re,"gravity",Number),Xe=b(re,"drift",Number),$e=b(re,"colors",S),nt=b(re,"ticks",Number),Vs=b(re,"shapes"),ka=b(re,"scalar"),Ia=!!b(re,"flat"),Ks=O(re),Ws=P,gs=[],_a=v.width*Ks.x,La=v.height*Ks.y;Ws--;)gs.push(F({x:_a,y:La,angle:ie,spread:A,startVelocity:oe,color:$e[Ws%$e.length],shape:Vs[w(0,Vs.length)],ticks:nt,decay:Pe,gravity:Ae,drift:Xe,scalar:ka,flat:Ia}));return de?de.addFettis(gs):(de=Q(v,gs,se,Se,Ce),de.promise)}function Ee(re){var Se=C||b(re,"disableForReducedMotion",Boolean),Ce=b(re,"zIndex",Number);if(Se&&ye)return d(function(oe){oe()});T&&de?v=de.canvas:T&&!v&&(v=G(Ce),document.body.appendChild(v)),M&&!ue&&se(v);var P={width:v.width,height:v.height};q&&!ue&&q.init(v),ue=!0,q&&(v.__confetti_initialized=!0);function ie(){if(q){var oe={getBoundingClientRect:function(){if(!T)return v.getBoundingClientRect()}};se(oe),q.postMessage({resize:{width:oe.width,height:oe.height}});return}P.width=P.height=null}function A(){de=null,M&&(R=!1,s.removeEventListener("resize",ie)),T&&v&&(document.body.contains(v)&&document.body.removeChild(v),v=null,ue=!1)}return M&&!R&&(R=!0,s.addEventListener("resize",ie,!1)),q?q.fire(re,P,A):ve(re,P,A)}return Ee.reset=function(){q&&q.reset(),de&&de.reset()},Ee}var le;function I(){return le||(le=X(null,{useWorker:!0,resize:!0})),le}function xe(v,p,T,M,R,C,ee){var q=new Path2D(v),se=new Path2D;se.addPath(q,new DOMMatrix(p));var ue=new Path2D;return ue.addPath(se,new DOMMatrix([Math.cos(ee)*R,Math.sin(ee)*R,-Math.sin(ee)*C,Math.cos(ee)*C,T,M])),ue}function Te(v){if(!l)throw new Error("path confetti are not supported in this browser");var p,T;typeof v=="string"?p=v:(p=v.path,T=v.matrix);var M=new Path2D(p),R=document.createElement("canvas"),C=R.getContext("2d");if(!T){for(var ee=1e3,q=ee,se=ee,ue=0,ye=0,de,ve,Ee=0;Ee<ee;Ee+=2)for(var re=0;re<ee;re+=2)C.isPointInPath(M,Ee,re,"nonzero")&&(q=Math.min(q,Ee),se=Math.min(se,re),ue=Math.max(ue,Ee),ye=Math.max(ye,re));de=ue-q,ve=ye-se;var Se=10,Ce=Math.min(Se/de,Se/ve);T=[Ce,0,0,Ce,-Math.round(de/2+q)*Ce,-Math.round(ve/2+se)*Ce]}return{type:"path",path:p,matrix:T}}function Z(v){var p,T=1,M="#000000",R='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof v=="string"?p=v:(p=v.text,T="scalar"in v?v.scalar:T,R="fontFamily"in v?v.fontFamily:R,M="color"in v?v.color:M);var C=10*T,ee=""+C+"px "+R,q=new OffscreenCanvas(C,C),se=q.getContext("2d");se.font=ee;var ue=se.measureText(p),ye=Math.ceil(ue.actualBoundingBoxRight+ue.actualBoundingBoxLeft),de=Math.ceil(ue.actualBoundingBoxAscent+ue.actualBoundingBoxDescent),ve=2,Ee=ue.actualBoundingBoxLeft+ve,re=ue.actualBoundingBoxAscent+ve;ye+=ve+ve,de+=ve+ve,q=new OffscreenCanvas(ye,de),se=q.getContext("2d"),se.font=ee,se.fillStyle=M,se.fillText(p,Ee,re);var Se=1/T;return{type:"bitmap",bitmap:q.transferToImageBitmap(),matrix:[Se,0,0,Se,-ye*Se/2,-de*Se/2]}}n.exports=function(){return I().apply(this,arguments)},n.exports.reset=function(){I().reset()},n.exports.create=X,n.exports.shapeFromPath=Te,n.exports.shapeFromText=Z})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Bs,!1);const yr=Bs.exports;Bs.exports.create;const vr={particleCount:350,spread:120,origin:{y:.6},angle:90},jr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Jt=e=>{let s=jr[e];s||(s={});const n={...vr,...s};yr(n)},br=()=>{const[e]=W.useTheme(),{mutate:s,isPending:n}=Ms(),{mutateAsync:a,isPending:i}=jn(),r=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{Jt("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||i,onClick:r,children:"Save draft"}),t.jsx(c.Button,{size:"sm",disabled:n||i,onClick:l,children:"Publish"})]})},Er=({page:e,onClose:s})=>{const[n,a]=m.useState(e.slug||""),{mutate:i,isPending:r}=xr(),{data:l}=Ne(),o=g.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(ke).some(y=>n===`/${y}`||g.startsWith(n,`/${y}/`))){$.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}i({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:h=>{const f=h.target.value;g.startsWith(f,`/${d}`)&&a(f)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:r||!g.startsWith(n,`/${d}`)||g.isEqual(e==null?void 0:e.slug,n),children:r?"Changing...":"Change Slug"})})]})]})})};function Gs({page:e,onClose:s}){const[,n]=_e(),{mutate:a,isPending:i}=mr(),{data:r}=Ne(),{setSelectedLang:l,fallbackLang:o}=W.useLanguages(),[,u]=W.useSidebarActivePanel(),d=()=>{i||a(e,{onSuccess:()=>{e!=null&&e.primaryPage?(window.history.replaceState({},"",`/?page=${e.primaryPage}`),n(new URLSearchParams({page:e.primaryPage}))):(window.history.replaceState({},"","/"),n(new URLSearchParams)),window.dispatchEvent(new PopStateEvent("popstate")),l(o),u("outline"),s()}})},h=r==null?void 0:r.find(f=>f.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",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:g.get(ke,e.lang,e.lang)})]})]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:i,onClick:d,children:i?"Deleting...":"Delete"})]})]})})}const Me=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:i}=W.usePermissions();return e&&!i(e)||s&&!s.some(r=>i(r))?a:n},ds=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=fr(),i=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[te.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:i,children:a?te.UPDATING:te.UNPUBLISH})]})]})})},Sr=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}},Ke=e=>{if(!e)return e;const{base:s}=Sr(e);return s},wr=e=>e&&Ke(e),Zs=(e,s)=>{const n=Ke(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function Us({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:i,disabled:r=!1,fullSlug:l}){const[o,u]=m.useState(e),[d,h]=m.useState(null);m.useEffect(()=>{u(e)},[e]);const f=j=>{const x=j.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),E=(x.match(/\./g)||[]).length,b=E<=1;E>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),i&&i(b),u(x),s(x)};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:wr(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:r,value:o,onChange:f,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:d})]}),l&&t.jsx("div",{className:"flex items-center mt-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const An=({langProps:e,onClose:s,languages:n})=>{const{data:a}=De(),{data:i}=Ne(),[r,l]=m.useState(e.name||""),[o,u]=m.useState(e.edit?e.lang:""),[d,h]=m.useState(e.edit?e.slug:""),[f,j]=m.useState(!0),[y,x]=m.useState(!0),{mutate:E,isPending:b}=Nn(),{mutate:U,isPending:w}=Ds(),{data:B}=Qe(a==null?void 0:a.parent),{setSelectedLang:S,fallbackLang:_}=W.useLanguages(),[,O]=_e(),[,V]=W.useSidebarActivePanel(),ne=m.useMemo(()=>i==null?void 0:i.find(Z=>Z.key===e.pageType),[i,e.pageType]),G=!(ne!=null&&ne.hasSlug),L=(a==null?void 0:a.slug)==="/",F=b||w,{parentSlug:Y,isRootPage:Q}=m.useMemo(()=>{if(L||!o)return{parentSlug:void 0,isRootPage:!(a!=null&&a.parent)};if(!(a!=null&&a.parent))return{parentSlug:y?`/${o}`:void 0,isRootPage:!(a!=null&&a.parent)};const Z=B==null?void 0:B.find(v=>v.lang===o);return{parentSlug:Z==null?void 0:Z.slug,isRootPage:!1}},[a==null?void 0:a.parent,B,y,o,L]);m.useEffect(()=>{if(!e.edit)return;const v=(e.slug||"").split("/").filter(Boolean);let p="";const T=M=>x(M);if(L){const M=v.pop()||"";if(ke[M])T(!0);else{p=M;const R=v.pop()||"";T(!!ke[R])}}else if(Q){if(v.length){p=v.pop()||"";const M=v.pop()||"";T(!!ke[M])}}else v.length&&(p=v.pop()||"");h(p)},[e,L,Q]);const X=m.useMemo(()=>Q?!0:!!(B!=null&&B.find(Z=>(Z==null?void 0:Z.lang)===o)),[o,B,Q]),le=()=>{let Z="";return Q?Z=`/${y?[o,d].filter(Boolean).join("/"):d}`:Z=`${Ke(Y)}/${d}`,Z.replace(/\/{2,}/g,"/")},I=(Z,v)=>{const p=new URLSearchParams(window.location.search);v&&Z===v?p.delete("lang"):p.set("lang",Z);const T=p.toString(),M=`${window.location.pathname}${T?`?${T}`:""}`;window.history.pushState({},"",M),O(p),window.dispatchEvent(new PopStateEvent("popstate"))},xe=Z=>{Z.preventDefault();const v={name:r,lang:o,primaryPage:a==null?void 0:a.id,slug:le(),pageType:a==null?void 0:a.pageType,tracking:{}};v.pageType=e.pageType,e.edit&&(v.id=e==null?void 0:e.id),e.edit?U(v,{onSuccess:s}):E(v,{onSuccess:()=>{o&&(S(o),I(o,_)),V("outline"),s()}})},Te=F||g.isEmpty(r)||g.isEmpty(o)||(G||L&&y?!1:!f||g.isEmpty(d));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:e.edit?te.EDIT_LANGUAGE:te.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:te.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:xe,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",className:"text-right",children:te.LANGUAGE}),t.jsxs("select",{value:o,disabled:e.edit||g.isEmpty(n),onChange:Z=>{const v=Z.target.value;u(v),!e.edit&&g.startsWith(r,e.name)&&l(`${e.name} - ${ke[v]}`)},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?g.get(ke,e.lang,e.lang):g.isEmpty(n)?te.ALL_AVAILABLE_LANGUAGE_PAGE:te.CHOOSE_LANGUAGE}),g.map(n,Z=>t.jsx("option",{value:Z,children:g.get(ke,Z,Z)},Z))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-right",children:te.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:o?r:"",onChange:Z=>l(Z.target.value),className:"col-span-3",required:!0,placeholder:o?te.ENTER_PAGE_NAME:te.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!X||!o})]}),!G&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"space-y-1",children:[Q&&o&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:y,onChange:Z=>x(Z.target.checked),className:"rounded border-gray-300"}),t.jsxs(c.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",o]}),") as slug prefix"]})]}),t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:[te.SLUG," "]}),t.jsx(Us,{disabled:g.isEmpty(o)||!X,value:d,onChange:h,placeholder:g.isEmpty(o)?te.CHOOSE_LANGUAGE_TO_ADD_SLUG:L&&y?"Leave empty for home page":te.ENTER_PAGE_SLUG,parentSlug:Y,onValidationChange:j,fullSlug:Te?"":le()})]})})]}),t.jsx(c.DialogFooter,{children:X?t.jsx(c.Button,{type:"submit",disabled:Te,children:F?e.edit?te.UPDATING:te.ADDING:e.edit?te.UPDATE:te.ADD_NEW_LANGUAGE}):o&&t.jsx(c.Alert,{variant:"destructive",children:t.jsxs("p",{className:"text-center w-5/6 mx-auto",children:["You need to create the"," ",t.jsx("span",{className:"font-medium",children:ke[o]})," page in the parent to add here."]})})})]})]})})},Nr=()=>{const[e,s]=m.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:i}=W.useLanguages(),{data:r,isFetching:l}=Qe(),{data:o}=De(),[u,d]=m.useState(null),[h,f]=m.useState(null),[j,y]=m.useState(null),{data:x}=Ye(),E=g.filter(g.get(x,"languages")||["en"],b=>!g.find(r,{lang:b})&&b!==g.get(x,"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"})]}):g.map(r,b=>{const U=b.lang,w=b.slug,B=!b.primaryPage,S=U===n;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`text-slate-500 w-full p-2 rounded cursor-pointer flex items-center justify-between ${S?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>i(U),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 ${b.online?"bg-green-300":"bg-gray-300"}`}),g.get(ke,B?a:U,U)]}),t.jsxs("div",{children:[w&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium",children:w})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",b.name," "]})]})]})]}),B?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(N.StarIcon,{fill:"orange",className:"w-3 h-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(Me,{permissions:[pe.EDIT_PAGE,pe.DELETE_PAGE,pe.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:_=>_.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[t.jsx(Me,{permissions:[pe.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:_=>{_.stopPropagation(),s({...b,edit:!0})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),te.EDIT]})}),t.jsx(Me,{permissions:[pe.UNPUBLISH_PAGE],children:(b==null?void 0:b.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:_=>{_.stopPropagation(),f(b)},children:[t.jsx(N.Power,{className:"size-3"}),te.UNPUBLISH]})}),t.jsx(Me,{permissions:[pe.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:_=>{_.stopPropagation(),d(b)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),te.DELETE]})})]})]})})})]},b.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Me,{permissions:[pe.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:g.isEmpty(E),onClick:()=>{s({name:o==null?void 0:o.name,pageType:o==null?void 0:o.pageType,lang:"",slug:"",edit:!1})},children:te.ADD_NEW_LANGUAGE})})}),e&&t.jsx(An,{languages:E,langProps:e,onClose:()=>s(null)}),u&&t.jsx(Gs,{page:u,onClose:()=>d(null)}),h&&t.jsx(ds,{page:h,onClose:()=>f(null)}),j&&t.jsx(Er,{page:j,onClose:()=>y(null)})]})};function Ar({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:i}){const[r,l]=m.useState(null),o=m.useRef(null),[u,d]=m.useState(a+e);m.useEffect(()=>{d(a+e)},[e,a]);const h=y=>{const x=y.target.value;if(!x.startsWith(a)){const S=x.replace(a,""),_=a+S;d(_),s(S);return}const b=x.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),U=(b.match(/\./g)||[]).length,w=U<=1;U>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),i&&i(w);const B=a+b;d(B),s(b)},f=()=>{if(o.current){const y=o.current;setTimeout(()=>{const x=a.length;y.setSelectionRange(x,x)},0)}},j=y=>{const x=y.currentTarget;(x.selectionStart||0)<=a.length&&setTimeout(()=>{const b=a.length;x.setSelectionRange(b,b)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:o,value:u,onChange:h,onFocus:f,onClick:j,placeholder:n,className:r?"border-red-500":""}),r&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:r})]})})}function Tr({pages:e,selectedParentId:s,onChange:n,className:a="w-full rounded-md border border-gray-300 px-3 py-2",id:i="parentPage"}){const r=m.useMemo(()=>!e||e.length===0?[]:e.filter(h=>!g.isEmpty(h.slug)).filter(h=>h.slug!=="/").sort((h,f)=>h.slug.localeCompare(f.slug)),[e]),l=d=>Math.max(0,(d.match(/\//g)||[]).length-1),o=d=>"    ".repeat(d),u=d=>{if(d==="/")return"/";const h=d.split("/").filter(Boolean);if(h.length<=1){const y=h[0]||"";return`/${Ke(y)}`}const f=h[h.length-1];return`/${Ke(f)}`};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:i,className:"text-sm",children:"Parent"}),t.jsxs("select",{id:i,value:s||"none",onChange:d=>n(d.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),r.map(d=>{const h=l(d.slug),f=h>0?o(h):"",j=u(d.slug);return t.jsxs("option",{value:d.id,children:[f,d.name," (",j,")"]},d.id)})]})]})}const Cr=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[i,r]=m.useState("");if(m.useEffect(()=>{if(s){const o=e.find(u=>u.id===s);r((o==null?void 0:o.preview)||"")}else r("")},[s,e]),a)return t.jsx("div",{className:"flex items-center justify-center h-fit text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const l={};return e.forEach(o=>{const u=o.libraryName;l[u]||(l[u]=[]),l[u].push(o)}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:o=>n(o.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(l).map(([o,u])=>t.jsx("optgroup",{label:o,children:u.map(d=>t.jsx("option",{value:d.id,children:g.startCase(d.name)},d.id))},o))]}),i&&t.jsxs("div",{className:"mt-3 border rounded overflow-hidden",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:i,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"p-2 text-xs text-gray-500 bg-gray-50 border-t",children:"Template preview"})]})]})},Pr=()=>{const e=ae(),s=H();return D.useQuery({queryKey:[z,k.GET_LIBRARIES],queryFn:async()=>await s(e,{action:k.GET_LIBRARIES})||[]})},kr=e=>{const s=ae(),n=H();return D.useQuery({queryKey:[z,k.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:k.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?g.filter(a,{pageType:e}):a)||[]}})},Ir=e=>{const{data:s=[],isLoading:n}=kr(e),{data:a=[],isLoading:i}=Pr(),r=m.useMemo(()=>n||i?[]:s.map(o=>{const u=g.find(a,{id:o.library});return{...o,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,i]),l=m.useMemo(()=>g.groupBy(r,"libraryName"),[r]);return{data:r,groupedData:l,isLoading:n||i}},Rs=()=>{const[,e]=_e();return m.useCallback((s,n)=>{const i=new URLSearchParams(window.location.search).get("lang"),r=new URLSearchParams({page:s});i&&r.set("lang",i),window.history.pushState({},"",`?${r.toString()}`),e(r),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])};function _r({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var P,ie;const i=Rs(),r=!!(e!=null&&e.id),{data:l}=Vt(),{mutate:o,isPending:u}=Nn(),{mutate:d,isPending:h}=Ds(),[f,j]=m.useState(null),[y,x]=m.useState(!0),[E,b]=m.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:U}=W.usePermissions(),w=U(pe.CHANGE_PAGE_TYPE),[B,S]=m.useState(!1),[_,O]=m.useState(""),V=m.useMemo(()=>{const A=s.find(oe=>oe.key===E);return(A==null?void 0:A.hasSlug)===!1},[E,s]),[ne,G]=m.useState((e==null?void 0:e.parent)??""),[L,F]=m.useState((e==null?void 0:e.name)??""),[Y,Q]=m.useState((e==null?void 0:e.dynamic)??!1),[X,le]=m.useState(Y?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[I,xe]=m.useState((e==null?void 0:e.dynamicSlugCustom)??""),[Te,Z]=m.useState(!0),[v,p]=m.useState(""),{data:T,isLoading:M}=Ir(E),R=u||h,C=s.find(A=>A.key===E),ee=A=>{if(r&&E!==A){O(A),S(!0);return}b(A)},q=()=>{b(_),S(!1),Q(!1)},se=A=>{Q(A),A?le(""):xe("")},ue=A=>{if(G(A),A&&A!=="none"){const oe=l==null?void 0:l.find(Ae=>Ae.id===A),Pe=(oe==null?void 0:oe.slug)||"";if(X.startsWith(Pe)){const Ae=X.slice(Pe.length).replace(/^\/+/,"");le(Ae)}else le(X.replace(/^\/+/,""))}else le(X?`${X}`:"")},ye=A=>{p(A)},de=()=>L.trim()?Y&&!g.isEmpty(X)?(j("Slug must be empty when using dynamic slug"),!1):Y&&!Te?(j("Dynamic slug is invalid"),!1):!0:($.toast.error("Name is required"),!1),ve=()=>{const A={pageType:C==null?void 0:C.key,name:L,slug:"",hasSlug:!1};r?d({id:e==null?void 0:e.id,name:L},{onSuccess:()=>{$.toast.success((C==null?void 0:C.name)+" updated successfully"),n()}}):o(A,{onSuccess:oe=>{console.log("response",oe),n(),i(oe.page.id,a)}})},Ee=(A,oe)=>{if(!A.trim()&&!Y)return j("Child page slug is required"),!1;const Pe=Ke(oe),Ae=Zs(Pe,A);return Object.keys(ke).some(nt=>Ae===`/${nt}`||(Ae==null?void 0:Ae.startsWith(`/${nt}/`)))?(j("Slugs cannot start with a language code for primary page"),!1):!0},re=(A,oe)=>{const Pe=Ke(oe),Ae=Zs(Pe,A),Xe={pageType:E,name:L,slug:Ae.replace(/\/$/,""),parent:ne,dynamic:Y,hasSlug:!0,template:v||void 0,tracking:{}};if(Y&&(Xe.dynamicSlugCustom=I),r)d({id:e==null?void 0:e.id,...Xe},{onSuccess:()=>{$.toast.success("Page updated successfully"),n()}});else{const $e=g.find(s,{key:E});$e!=null&&$e.trackingDefault&&(Xe.tracking=$e.trackingDefault),o(Xe,{onSuccess:nt=>{n(),i(nt.page.id,a)}})}},Se=()=>{const A={pageType:E,name:L,slug:X===""?"/":`/${X.replace(/\/$/,"")}`,template:v||void 0,parent:null,tracking:{}};if(r)d({id:e==null?void 0:e.id,...A},{onSuccess:()=>{$.toast.success("Page updated successfully"),n()}});else{const oe=g.find(s,{key:E});oe!=null&&oe.trackingDefault&&(A.tracking=oe.trackingDefault),o(A,{onSuccess:Pe=>{var Ae;(Ae=Pe==null?void 0:Pe.page)!=null&&Ae.id&&i(Pe.page.id,a),n()}})}},Ce=A=>{if(A.preventDefault(),j(null),!!de()){if(!(C!=null&&C.hasSlug)){ve();return}if(ne&&ne!=="none"){const oe=l==null?void 0:l.find(Ae=>Ae.id===ne),Pe=(oe==null?void 0:oe.slug)||"";if(!Ee(X,Pe))return;re(X,Pe)}else Se()}};return r&&!(C!=null&&C.hasSlug)?t.jsxs("form",{onSubmit:Ce,className:"w-full max-w-md mx-auto space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:E,disabled:r&&!w,onChange:A=>ee(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${r&&!w?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})}),B&&t.jsxs("div",{className:"mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:q,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(P=s.find(A=>A.key===E))==null?void 0:P.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:L,onChange:A=>F(A.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:R,type:"submit",className:"w-full",children:r?R?"Updating...":"Update "+(C==null?void 0:C.name):R?"Creating...":"Create "+(C==null?void 0:C.name)})]}):t.jsxs("form",{onSubmit:Ce,className:"w-full max-w-md mx-auto space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsx("select",{id:"pageType",value:E,disabled:r&&!w,onChange:A=>ee(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${r&&!w?"cursor-not-allowed text-gray-500":""}`,children:r?V?t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})]})}),B&&t.jsxs("div",{className:"mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:q,children:"Confirm"})]})]})]}),!r&&(C==null?void 0:C.hasSlug)&&T.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"text-sm mb-1 block",children:"Template"}),t.jsx(Cr,{templates:T,selectedTemplateId:v,onSelectTemplate:ye,isLoading:M})]}),t.jsx(Tr,{pages:l,selectedParentId:ne,onChange:ue}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:L,onChange:A=>F(A.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(C==null?void 0:C.dynamicSegments)&&ne&&ne!=="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:Y,onChange:A=>se(A.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),Y&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(Ar,{value:I,onChange:xe,dynamicPattern:(C==null?void 0:C.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:Z})})})]}),(!(C!=null&&C.dynamicSegments)||!Y)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Us,{value:X,onChange:le,placeholder:ne&&ne!=="none"?"Enter page slug":E==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:ne&&ne!=="none"?(ie=l==null?void 0:l.find(A=>A.id===ne))==null?void 0:ie.slug:void 0,onValidationChange:x}),f&&t.jsx("p",{className:"text-xs text-red-500",children:f})]}),t.jsx(c.Button,{disabled:R||!y&&(!(C!=null&&C.dynamicSegments)||!Y)||Y&&!Te,type:"submit",className:"w-full",children:r?R?"Updating...":"Update page":R?"Creating...":"Create Page"})]})}const Tn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Ne(),i=!!(e!=null&&e.id);return t.jsx(c.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsxs(c.DialogTitle,{children:[i?"Edit":"Add New"," "]}),t.jsx(c.DialogDescription,{children:i?"Update your page name":"Enter details to create a new page"})]}),t.jsx(_r,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},Lr=()=>{const e=ae(),s=D.useQueryClient(),n=H();return D.useMutation({mutationFn:async({pageId:a,name:i,slug:r})=>{const l={pageId:a,name:i};return r&&(l.slug=r),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[z,k.GET_WEBSITE_PAGES]}),$.toast.success("Page duplicated successfully")},onError:a=>{$.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Cn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Lr(),[i,r]=m.useState(null),[l,o]=m.useState(`${e.name} (Copy)`),u=g.isEmpty(e.slug),[d,h]=m.useState(u?"":`${e.slug.split("/").pop()}-copy`),f=u?"":g.initial(e.slug.split("/")).join("/"),[j,y]=m.useState(!1),x=E=>{if(E.preventDefault(),!l.trim()){r("Name is required");return}if(!u&&!d.trim()){r("Slug is required");return}r(null),y(!0);const b={pageId:e.id,name:l};u||(b.slug=`${f}/${d}`),n(b,{onSuccess:()=>{y(!1),s()},onError:U=>{y(!1),U.code==="SLUG_EXISTS"?r("A page with this slug already exists. Please choose a different slug."):U.code==="INVALID_SLUG"?r("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):U.code==="PERMISSION_DENIED"?r("You don't have permission to duplicate this page."):r(U.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Duplicate Page"}),t.jsx(c.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!u&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:x,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:E=>o(E.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Us,{value:d,onChange:E=>h(E),parentSlug:f,onValidationChange:E=>{r(E?null:"Invalid slug")}})]}),i&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:i})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||j,children:a||j?"Duplicating...":"Duplicate"})]})]})]})})},Dr=1*1024*1024,Pn=({page:e,onClose:s})=>{const[n,a]=m.useState(!1),[i,r]=m.useState(""),[l,o]=m.useState(""),[u,d]=m.useState(!1),h=m.useRef(null),f=gr(),{data:j}=Ne(),y=j==null?void 0:j.find(B=>B.key===e.pageType),x=(y==null?void 0:y.name)||g.startCase(e.pageType),E=m.useCallback(B=>{var _;const S=(_=B.target.files)==null?void 0:_[0];if(S){if(S.size>Dr){$.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 O=new FileReader;O.onloadend=()=>{o(O.result),d(!1)},O.readAsDataURL(S)}catch(O){console.error("Error reading file:",O),d(!1),$.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),b=()=>{o(""),h.current&&(h.current.value="")},U=()=>{var B;(B=h.current)==null||B.click()},w=()=>{a(!0),f.mutate({page:e,name:e.name,description:i.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:g.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:x})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:i,onChange:B=>r(B.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:h,onChange:E,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:U,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:b,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:B=>{B.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:w,children:"Mark as template"})]})]})})},kn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:i,setMarkAsTemplate:r,setUnmarkAsTemplate:l,children:o})=>{const{hasPermission:u}=W.usePermissions(),{data:d}=Ne(),h=m.useMemo(()=>g.find(d,{key:e.pageType}),[d,e.pageType]),f=m.useMemo(()=>!!e.isTemplate,[e.isTemplate]),j=m.useMemo(()=>!!(h!=null&&h.hasSlug),[h==null?void 0:h.hasSlug]);return!u(pe.EDIT_PAGE)&&!u(pe.DELETE_PAGE)&&!u(pe.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:x=>x.stopPropagation(),children:o}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[u(pe.ADD_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:x=>{x.stopPropagation(),s(e)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),u(pe.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:x=>{x.stopPropagation(),n({...e,global:!(h!=null&&h.hasSlug)})},children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&u(pe.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:x=>{x.stopPropagation(),a(e)},children:[t.jsx(N.Power,{className:"size-3"}),te.UNPUBLISH]}),u(pe.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:x=>{x.stopPropagation(),i(e)},children:[t.jsx(N.Trash,{className:"size-3"}),te.DELETE]}),u(pe.MARK_AS_TEMPLATE)&&j&&t.jsx(t.Fragment,{children:f?t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:x=>{x.stopPropagation(),l(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),te.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:x=>{x.stopPropagation(),r(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),te.MARK_AS_TEMPLATE]})})]})]})},In=({page:e,onClose:s})=>{const[n,a]=m.useState(!1),i=pr(),r=()=>{a(!0),i.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Unmark as template"}),t.jsx(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:r,children:"Unmark as template"})]})]})})},Mr=xn("expandedPagesState",[]),Os=e=>g.flatMap(e,s=>[s,...s.children?Os(s.children):[]]),Br=(e,s)=>{const n=(a,i=[])=>{for(const r of a){const l=[...i,r.id];if(r.id===s)return l;if(r.children&&r.children.length>0){const o=n(r.children,l);if(o)return o}}return null};return n(e)||[]},_n=(e,s)=>{if(!s)return[];const n=Os(e),a=g.find(n,i=>i.id===s);if(a){if(a.parent)return[..._n(e,a.parent),s];const i=Br(e,s);if(!g.isEmpty(i))return i}return[s]},Ln=e=>{const[s,n]=Re.useAtom(Mr),a=e?g.includes(s,e):!1,i=m.useCallback(()=>{n(l=>a?g.filter(l,o=>o!==e):[...l,e])},[n,a,e]),r=m.useCallback((l,o)=>{if(!o||g.isEmpty(l))return;const u=Os(l),d=_n(u,o);if(!Array.isArray(d)||g.isEmpty(d))return;const h=d.slice(0,-1);g.isEmpty(h)||n(f=>g.uniq([...f,...h]))},[n]);return{isExpanded:a,toggleExpanded:i,updateForSelectedPage:r,expandedPages:s}},Gr=(e,s)=>!e||!Array.isArray(e)?[]:g.isEmpty(s)?e:g.compact(g.filter(e,n=>{const a=g.toLower(s);return g.includes(g.toLower((n==null?void 0:n.name)||""),a)||g.includes(g.toLower((n==null?void 0:n.slug)||""),a)})),Ur=e=>{if(!e||!e.length)return[];const s=new Map;e.forEach(a=>{s.set(a.id,{...a,children:[]})});const n=[];return s.forEach(a=>{if(a.parent){const i=s.get(a.parent);i?i.children.push(a):n.push(a)}else n.push(a)}),n},Dn=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Dn(n.children):[]})),Rr=(e,s,n,a)=>{if(!e||!e.length)return[];const i=Gr(e,s);if(n!=="all")return g.compact(g.filter(i,{pageType:n}));const r=Dn(Ur(i)),l=g.filter(r,d=>a(d.pageType)).sort((d,h)=>(d.name||"").localeCompare(h.name||"")),o=[],u=new Set;for(const d of r)!a(d.pageType)&&!u.has(d.pageType)&&(u.add(d.pageType),o.push({...d,name:g.startCase(d.pageType),isPartialGroup:!0,children:r.filter(h=>h.pageType===d.pageType)}));return[...l,...o]},Or=({currentEditor:e})=>{const{user:s}=Oe(),{data:n}=tt(e);return!n||!e||e===(s==null?void 0:s.id)?null:t.jsx("span",{className:"ml-2 text-xs font-light text-gray-500 flex items-center gap-1",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(N.LockIcon,{className:"w-3 h-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},Fr=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:i,setDeletePage:r,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:h,isExpanded:f,onToggleExpand:j})=>{const y=Rs(),{data:x}=Ne(),[,E]=W.useSidebarActivePanel(),b=m.useMemo(()=>g.find(x,{key:s.pageType}),[x,s.pageType]),U=m.useMemo(()=>{const _=g.get(s,"slug",""),O=e?Ke(e):"",V=O?_.replace(O,""):_;return V||"/"},[s,e]),w=m.useMemo(()=>!!s.isTemplate,[s.isTemplate]),B=m.useCallback(()=>{E("outline"),y(g.get(s,"id"),a)},[y,a,s,E]),S=m.useCallback(_=>{_.stopPropagation(),j()},[j]);return t.jsxs("div",{onClick:B,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(N.ChevronRight,{size:16,className:`w-4 h-5 transition-transform duration-200 ${f?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(N.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):b!=null&&b.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:b.icon}}):b!=null&&b.hasSlug?t.jsx(N.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(N.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),!s.isPartialGroup&&t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:s.name}),b!=null&&b.hasSlug?t.jsxs(c.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:[U,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[g.endsWith(U,"/")?`${b==null?void 0:b.dynamicSlug}`:`/${b==null?void 0:b.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(c.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:b==null?void 0:b.name}),w&&t.jsx(c.Badge,{variant:"outline",className:"ml-2 text-xs py-0 font-normal text-blue-500 border border-blue-200 bg-blue-50",children:"Template"})]}),!s.isPartialGroup&&t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(Or,{currentEditor:s.currentEditor}),t.jsx(kn,{page:s,setDuplicatePage:d,setAddEditPage:l,setUnpublishPage:i,setDeletePage:r,setMarkAsTemplate:o,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"p-0.5 m-0 hover:bg-white rounded duration-100 cursor-pointer",children:t.jsx(N.MoreHorizontal,{className:"w-4 h-4",onClick:_=>_.stopPropagation()})})})]})]})},qr=({close:e,isOpen:s})=>{const[,n]=m.useState([]),[a,i]=m.useState(null),[r,l]=m.useState(""),[o,u]=m.useState(null),[d,h]=m.useState(null),[f,j]=m.useState(null),[y,x]=m.useState(null),[E,b]=m.useState(null),{data:U,isFetching:w,refetch:B}=Vt(),[S,_]=m.useState(""),{hasPermission:O}=W.usePermissions(),{updateForSelectedPage:V}=Ln(null),[ne,G]=_e(),L=ne.get("page"),{data:F}=Ne(),Y=m.useCallback(I=>{var xe;return(xe=g.find(F,{key:I}))==null?void 0:xe.hasSlug},[F]);m.useEffect(()=>{s&&B()},[s,B]),m.useEffect(()=>{if(!g.isEmpty(S))return;const I=sessionStorage.getItem("pageTypeFilter")||"all";!g.isEmpty(F)&&I&&(g.find(F,{key:I})?_(I):_("all"))},[F,S]);const Q=I=>{_(I),sessionStorage.setItem("pageTypeFilter",I)},X=m.useCallback(I=>{const Te=new URLSearchParams(window.location.search).get("lang"),Z=new URLSearchParams({page:I});Te&&Z.set("lang",Te),window.history.pushState({},"",`?${Z.toString()}`),G(Z),window.dispatchEvent(new PopStateEvent("popstate")),e()},[G,e]);m.useEffect(()=>{if(L&&!w){const I=g.find(U,{id:L});I&&(I!=null&&I.pageType)?n(xe=>[...xe,I==null?void 0:I.pageType]):(window.history.replaceState(null,"","/"),G(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[U,L,w,G]);const le=m.useMemo(()=>U?Rr(U,r,S,Y):[],[U,r,S,Y]);return m.useEffect(()=>{L&&!w&&!g.isEmpty(le)&&V(le,L)},[L,w,le,V]),t.jsxs("div",{className:"flex flex-col justify-between h-full",children:[t.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[t.jsxs("div",{className:"relative flex item-center gap-x-4",children:[t.jsx(N.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:r,onChange:I=>l(I.target.value)}),!g.isEmpty(S)&&t.jsxs(c.Select,{value:S,onValueChange:Q,children:[t.jsx(c.SelectTrigger,{className:`${S==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} min-w-[120px] h-max p-0 py-1 pl-2 pr-1 top-1.5 -mt-px absolute text-gray-600 right-1.5 w-max text-xs whitespace-nowrap ring-0 focus:ring-0 shadow-none`,children:t.jsx(c.SelectValue,{placeholder:"Select page type"})}),t.jsxs(c.SelectContent,{align:"end",children:[t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!g.isEmpty(g.filter(F,I=>I.hasSlug))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Pages"}),g.map([...g.filter(F,I=>I.hasSlug)].sort((I,xe)=>g.get(I,"name","").localeCompare(g.get(xe,"name",""))),I=>t.jsx(c.SelectItem,{value:g.get(I,"key"),children:g.get(I,"name")},g.get(I,"key")))]}),!g.isEmpty(g.filter(F,I=>!I.hasSlug))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Partials"}),g.map([...g.filter(F,I=>!I.hasSlug)].sort((I,xe)=>g.get(I,"name","").localeCompare(g.get(xe,"name",""))),I=>t.jsx(c.SelectItem,{value:g.get(I,"key"),children:g.get(I,"name")},g.get(I,"key")))]})]})]})]}),w?t.jsx("div",{className:"space-y-2",children:g.map([...Array(5).keys()],I=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},I))}):g.isEmpty(le)?t.jsxs("div",{className:"h-[70vh] flex flex-col gap-y-1 items-center justify-center text-slate-500 text-sm font-medium",children:[t.jsx(N.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"text-sm text-slate-700 space-y-2 h-[70vh] overflow-y-auto",children:g.map(le,I=>t.jsx(Mn,{item:I,currentPage:L,close:e,setUnpublishPage:h,setDeletePage:u,setAddEditPage:j,setMarkAsTemplate:x,setUnmarkAsTemplate:b,setDuplicatePage:i,level:0},`page-item-${I.id}`))})]}),O(pe.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex text-sm gap-x-2",onClick:()=>{j({slug:"",name:"",pageType:S==="all"?"page":S})},children:[t.jsx(N.Plus,{className:"w-4 h-4"})," Add New"]}),f&&t.jsx(Tn,{closePanel:e,editPage:X,addEditPage:f,setAddEditPage:j}),o&&t.jsx(Gs,{page:o,onClose:()=>u(null)}),d&&t.jsx(ds,{page:d,onClose:()=>h(null)}),y&&t.jsx(Pn,{page:y,onClose:()=>x(null)}),E&&t.jsx(In,{page:E,onClose:()=>b(null)}),a&&t.jsx(Cn,{page:a,onClose:()=>i(null)})]})},Mn=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:i,setAddEditPage:r,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const f=!g.isEmpty(e==null?void 0:e.children),{isExpanded:j,toggleExpanded:y}=Ln(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(Fr,{closePanel:n,setUnpublishPage:a,setDeletePage:i,setAddEditPage:r,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:f,isExpanded:j,onToggleExpand:y}),f&&j&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:g.map(g.get(e,"children",[]),x=>t.jsx(Mn,{item:x,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:i,setAddEditPage:r,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:h+1},x.id||`child-${h}-${x.key}`))})]},e.id||`level-${h}-${e.key}`)},zr=({page:e})=>{const[s,n]=m.useState(null),[a,i]=m.useState(null),[r,l]=m.useState(null),[o,u]=m.useState(null),[d,h]=m.useState(null),[f,j]=m.useState(null);return e?t.jsxs(t.Fragment,{children:[t.jsx(kn,{page:e,setDuplicatePage:y=>h(y),setAddEditPage:y=>j(y),setUnpublishPage:y=>i(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(N.MoreHorizontal,{className:"w-4 h-4",onClick:y=>y.stopPropagation()})})}),f&&t.jsx(Tn,{closePanel:()=>j(null),editPage:()=>{},addEditPage:f,setAddEditPage:j}),s&&t.jsx(Gs,{page:s,onClose:()=>n(null)}),a&&t.jsx(ds,{page:a,onClose:()=>i(null)}),r&&t.jsx(Pn,{page:r,onClose:()=>l(null)}),o&&t.jsx(In,{page:o,onClose:()=>u(null)}),d&&t.jsx(Cn,{page:d,onClose:()=>h(null)})]}):null},$r=()=>{const e=qe("logo",null);return e?t.jsx("div",{className:"w-full max-h-9 overflow-hidden pr-2",children:m.createElement(e,{})}):null},Hr=()=>{const[e]=_e(),s=e.get("page"),{data:n,isFetching:a}=De(),[i,r]=m.useState(!1),{savePage:l}=W.useSavePage(),o=!!s&&!g.isEmpty(n),u=!s||!a&&g.isEmpty(n)||i;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"relative",children:[t.jsxs(c.Button,{variant:"outline",className:"flex items-center w-full space-x-2 py-1",onClick:()=>{l(),r(!0)},children:[t.jsx("div",{children:t.jsx(N.Logs,{className:"h-4 w-4"})}),t.jsxs("span",{className:"truncate leading-tight flex items-center max-w-[200px]",children:[t.jsx("span",{className:"text-slate-600 pr-1 font-light",children:"Editing:"}),a?t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-slate-400 ml-2"}):g.startCase(g.get(n,"name"))??""]}),t.jsx("div",{className:`${a?"hidden":"w-2"}`})]},"template-viewer"),!a&&t.jsx(zr,{page:n})]}),t.jsx(c.Sheet,{open:u,onOpenChange:d=>!d&&o&&r(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`!max-w-screen-md z-50 border-border w-full ${o?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:"mb-3",children:[t.jsxs(c.SheetTitle,{className:"text-sm flex items-center gap-2 font-semibold",children:[t.jsx("div",{className:"p-2 rounded-md bg-primary text-primary-foreground",children:t.jsx(N.File,{className:"w-6 h-6"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(qr,{isOpen:u,close:()=>r(!1)})})]})})]})},Vr=()=>{const{fallbackLang:e,languages:s,selectedLang:n,setSelectedLang:a}=W.useLanguages(),i=g.isEmpty(n)?e:n,[,r]=_e();m.useEffect(()=>{const x=new URLSearchParams(window.location.search),E=x.get("lang");E&&(s.includes(E)?a(E):(x.delete("lang"),r(x),a("")))},[s,r,a]);const[l,o]=m.useState(null),{data:u}=De(),{data:d}=Ye(),{data:h,isFetching:f}=Qe(),j=m.useMemo(()=>{const x=g.compact(g.map(g.get(d,"languages"),E=>{const b=g.find(h,{lang:E});return{key:E,value:g.get(ke,E,E),isLangPageAdded:!!b}})).filter(Boolean);return[{key:e,value:g.get(ke,e),isLangPageAdded:!0},...x]},[e,h,d]),y=x=>{a(x);const E=new URLSearchParams(window.location.search);x===e?E.delete("lang"):E.set("lang",x);const b=E.toString(),U=`${window.location.pathname}${b?`?${b}`:""}`;window.history.pushState({},"",U),r(E),window.dispatchEvent(new PopStateEvent("popstate"))};return g.isEmpty(s)||f?null:t.jsxs(t.Fragment,{children:[t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Languages,{className:"w-4 h-4"}),g.get(ke,i,i),t.jsx(N.ChevronDown,{className:"w-4 h-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"border-border space-y-1",children:[g.map(j.filter(x=>x.isLangPageAdded),x=>t.jsxs(c.DropdownMenuItem,{className:W.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",x.key===i&&"!bg-gray-200 text-gray-700"),onClick:()=>y(x.key),children:[t.jsx("div",{className:"text-slate-600",children:x.value}),x.key===e&&t.jsxs("small",{className:"text-[9px] flex items-center gap-x-1 text-orange-500 leading-none",children:[t.jsx(N.Star,{fill:"orange",className:"w-2 h-2"}),"Primary"]})]},x.value)),!g.isEmpty(j.filter(x=>!x.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{o({name:u==null?void 0:u.name,pageType:u==null?void 0:u.pageType,lang:"",slug:"",edit:!1})},className:"hover:bg-slate-300 duration-200 font-normal text-xs hover:text-slate-800",children:[t.jsx(N.Plus,{className:"w-3 h-3 mr-1"})," Add Langauge"]})]})]})]}),l&&t.jsx(An,{languages:s,langProps:l,onClose:()=>o(null)})]})};function Kr(){return t.jsxs("div",{className:"flex relative z-10 items-center justify-end gap-1",children:[t.jsx($r,{}),t.jsx(Hr,{}),t.jsx(Vr,{})]})}function Wr(e){const s=ae(),n=H();return D.useQuery({queryKey:[z,"revisions",e],queryFn:async()=>await n(s,{action:k.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Qr=()=>{const e=ae(),s=H(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>await s(e,{action:k.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[z,"revisions"]})}})},Yr=()=>{const e=ae(),s=H(),n=D.useQueryClient();return D.useMutation({mutationFn:async({revisionId:a,discardCurrent:i})=>await s(e,{action:k.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:i}}),onSuccess:()=>{n.invalidateQueries({queryKey:[z,"revisions"]})}})};function Xr(){const{data:e}=De(),{saveState:s}=W.useSavePage(),[n]=cs();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:!g.isEmpty(n.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",St.formatDistanceToNow(new Date(n.lastSaved),{addSuffix:!0})]})}),t.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(N.Edit,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]}),s==="UNSAVED"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(N.Save,{className:"h-3 w-3"}),t.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function Zr(){const[e,s]=je.useState(!1),[n,a]=je.useState(null),[i,r]=je.useState(!1),[l,o]=je.useState(!1),{data:u}=De(),{data:d,isFetching:h,error:f,refetch:j}=Wr(u==null?void 0:u.id),{mutate:y,isPending:x}=Qr(),{mutate:E,isPending:b}=Yr(),U=D.useQueryClient(),w=O=>{n&&E({revisionId:n.uid,discardCurrent:O},{onSuccess:()=>{r(!1),a(null),U.invalidateQueries({queryKey:[z,k.GET_DRAFT_PAGE]})}})},B=O=>{a(O),r(!0)},S=O=>{a(O),o(!0)},_=()=>{n&&y(n.uid,{onSuccess:()=>{o(!1),a(null)}})};return m.useEffect(()=>{e&&j()},[e,j]),t.jsxs(t.Fragment,{children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:e,onOpenChange:s,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(N.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(c.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(c.SheetHeader,{className:"pb-2",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(N.History,{className:"h-5 w-5"}),"Revision History"]}),(u==null?void 0:u.createdAt)&&t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Page created on"," ",St.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(c.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:h?t.jsx(Jr,{}):f?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 space-y-2",children:[t.jsx(Xr,{}),d==null?void 0:d.map(O=>t.jsx(ei,{revision:O,isLatest:O.uid==="current",onRestore:()=>B(O),onDelete:()=>S(O)},O.uid))]})})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(si,{open:i,onOpenChange:r,revision:n,onRestore:w,isRestoring:b}),t.jsx(ni,{open:l,onOpenChange:o,revision:n,onDelete:_,isDeleting:x})]})}function Jr(){return t.jsx("div",{className:"space-y-2 mt-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(c.Skeleton,{className:"h-4 w-3/4"}),t.jsx(c.Skeleton,{className:"h-3 w-1/2"}),t.jsx(c.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function ei({revision:e,isLatest:s,onRestore:n,onDelete:a}){const{data:i}=tt(e.currentEditor),r=(i==null?void 0:i.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:r}),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:St.format(e.createdAt,"MMM d, h:mm a")})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:e.type==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(N.ArrowUpRight,{className:"h-3 w-3"}),t.jsx("span",{children:"Published"})]}):t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(N.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(Me,{permissions:[pe.RESTORE_REVISION,pe.DELETE_REVISION],children:t.jsx(ti,{revision:e,onRestore:n,onDelete:a})})]})}function ti({revision:e,onRestore:s,onDelete:n}){return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(N.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Me,{permission:pe.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Me,{permission:pe.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(c.DropdownMenuSeparator,{}),t.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(N.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function si({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:i}){const{data:r}=tt((n==null?void 0:n.currentEditor)||""),l=(r==null?void 0:r.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{i||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Restore Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",St.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:i,children:i?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:i,children:i?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function ni({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:i}){const{data:r}=tt((n==null?void 0:n.currentEditor)||""),l=(r==null?void 0:r.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{i||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",St.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:i,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:i,children:i?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const ai=()=>{const e=ae(),s=H();return D.useQuery({queryKey:[z,k.GET_CHANGES],queryFn:async()=>s(e,{action:k.GET_CHANGES})})},ri=({currentEditor:e})=>{const{data:s}=tt(e);return s==null?void 0:s.name};function ii({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=m.useState([]),{data:i,isFetching:r}=ai(),{data:l}=Ne(),o=m.useCallback(S=>{var _;return(_=g.find(l,{key:S}))==null?void 0:_.hasSlug},[l]),u=m.useMemo(()=>g.filter(l,S=>!o(S.key)).map(S=>S.key),[o,l]),d=m.useMemo(()=>g.filter(i,S=>!u.includes(S.pageType)),[i,u]),h=m.useMemo(()=>g.filter(i,S=>u.includes(S.pageType)),[i,u]),f=m.useMemo(()=>g.find(i,{pageType:"theme",id:"THEME"}),[i]),{mutate:j,isPending:y}=Ms();m.useEffect(()=>{const S=g.map(g.filter(i,{online:!0}),"id");f&&S.push(f==null?void 0:f.id),a(S)},[i,f]);const x=n.length===(i==null?void 0:i.length),E=S=>{a(_=>g.includes(_,S)?g.filter(_,O=>O!==S):g.concat(_,S))},b=()=>{a(x?[]:g.map(i,"id"))},U=()=>{j({ids:g.uniq(n)},{onSuccess:()=>{s(),Jt("CENTER_CENTER")}})},w=S=>{if(S==="theme")return"Theme";const _=g.find(l,{key:S});return _?_==null?void 0:_.name:S},B=m.useMemo(()=>{const S=[{label:"Updated",top:"pt-2"},...g.orderBy(g.filter(d,{online:!0}),"pageType"),...g.orderBy(g.filter(h,{online:!0}),"pageType")].filter(V=>V.pageType!=="theme"),_=[{label:"Offline",top:"pt-6"},...g.orderBy(g.filter(d,{online:!1}),"pageType"),...g.orderBy(g.filter(h,{online:!1}),"pageType")],O=f?[{label:"Theme",top:"pt-6"},f]:[];return[...S,...O,..._]},[d,h,f]);return t.jsx(c.Dialog,{open:e,onOpenChange:y?()=>{}:s,children:t.jsxs(c.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),t.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:r?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:x,onClick:S=>{S.stopPropagation(),b()},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:g.map(B,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:g.includes(n,S==null?void 0:S.id),onClick:_=>{_.stopPropagation(),E(S==null?void 0:S.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",o(S.pageType)?t.jsx(N.File,{className:"w-4 h-4"}):t.jsx(N.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(ri,{currentEditor:S.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:S.lang}),t.jsx("td",{className:"px-2",children:w(S==null?void 0:S.pageType)}),t.jsx("td",{className:"px-4 text-right",children:g.first(S.changes)||""})]},S==null?void 0:S.id))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10",children:[t.jsx(c.Button,{disabled:y,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:y||r||g.isEmpty(i),onClick:U,children:y?"Publishing...":"Publish"})]})]})})}const li=()=>{const e=H(),s=ae();return D.useQuery({queryKey:[k.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:k.GET_WEBSITE_DATA,data:{draft:!0}})})};function oi({onClose:e}){const{data:s,isFetching:n}=li(),{mutateAsync:a,isPending:i}=Ha(),r=qe("settingComponent",null),l=g.debounce(async o=>(await a({data:o}),!0),300);return r?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:m.createElement(r,{data:s||{},onSave:i?()=>{}:l,cancel:i?()=>{}:e})})]})}):null}function Bn({children:e,content:s}){return t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:e}),t.jsx(c.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const ci=()=>{const{selectedLang:e,fallbackLang:s}=W.useLanguages(),n=qe("getPreviewUrl",async f=>f),[a,i]=m.useState(""),{data:r}=De(),{data:l}=Qe(),{data:o}=Ne(),u=m.useMemo(()=>{var f;return(f=l==null?void 0:l.find(j=>(j==null?void 0:j.lang)===e))==null?void 0:f.slug},[e,l]),d=m.useCallback(f=>{var j;return(j=g.find(o,{key:f}))==null?void 0:j.hasSlug},[o]),h=e===s?"":e;return m.useEffect(()=>{(async()=>{if(typeof n=="function"){const f=!d(r==null?void 0:r.pageType),j=await n(f?`${h!==""?h+"/":""}${r==null?void 0:r.id}`:u||"");i(j)}else i("")})()},[n,u,r==null?void 0:r.pageType,d,r==null?void 0:r.id,h]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Eye,{className:"w-4 h-4"})," ",te.PREVIEW]})})})},ui=()=>{const[e,s]=W.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(Bn,{content:te.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(N.Palette,{className:"w-4 h-4"})})}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})},di=()=>{const[e,s]=m.useState(!1),{isLocked:n}=Kt(),{savePage:a,saveState:i}=W.useSavePage();m.useEffect(()=>{const h=f=>{i==="UNSAVED"&&(f.preventDefault(),f.returnValue=!1)};return i==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[i]);const r=m.useCallback(async()=>{s(!0),await a(!1)},[a]);m.useEffect(()=>{i==="SAVED"&&s(!1)},[i]);const l=m.useMemo(()=>{if(i==="SAVED"||i==="UNSAVED")return i;if(i==="SAVING")return e?i:"SAVED"},[e,i]),{buttonIcon:o,buttonClass:u,tooltipContent:d}=m.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:te.SAVEDRAFT,buttonIcon:t.jsx(N.Save,{className:"w-4 h-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:te.SAVING,buttonIcon:t.jsx(N.Loader,{className:"w-4 h-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:te.SAVED,buttonIcon:t.jsx(N.CheckCircle,{className:"w-4 h-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:r,className:u,children:[o," ",d]})},hi=()=>{const[e,s]=m.useState(!1),[n,a]=m.useState(!1),[i,r]=m.useState(null),{data:l}=De(),{mutate:o,isPending:u}=Ms(),{buttonText:d,buttonClassName:h,isPublished:f}=m.useMemo(()=>{const y=l&&(l==null?void 0:l.online);return{buttonClassName:y?"hover:bg-green-600 bg-green-500":"",isPublished:y,buttonText:y?te.PUBLISHED:te.PUBLISH}},[l]),j=async()=>{o({ids:[l==null?void 0:l.id]},{onSuccess:()=>Jt("TOP_RIGHT")})};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:j,disabled:u||!(l!=null&&l.id),className:`relative overflow-hidden transition-all duration-300 ease-in-out text-white flex items-center gap-1 rounded-r-none ${h}`,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${n?"-translate-y-10":""}`,children:f?t.jsx(N.Send,{className:"w-4 h-4"}):t.jsx(N.Rocket,{className:"w-4 h-4"})}),t.jsx("span",{className:`absolute inset-0 flex items-center left-3 transition-transform duration-300 ease-in-out ${n?"":"translate-y-10"}`,children:f?t.jsx(N.Rocket,{className:"w-4 h-4"}):t.jsx(N.Send,{className:"w-4 h-4"})}),t.jsx("span",{children:d})]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:u||!(l!=null&&l.id),className:`px-2 text-white border-l border-white/50 rounded-l-none ${h}`,children:t.jsx(N.ChevronDown,{className:"w-4 h-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-36",children:[!f&&t.jsxs(c.DropdownMenuItem,{disabled:u,className:"text-xs cursor-pointer",onClick:()=>o({ids:[l==null?void 0:l.id]},{onSuccess:()=>Jt("TOP_RIGHT")}),children:[te.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>s(!0),className:"text-xs cursor-pointer",children:[te.OPEN," publish menu"]}),f&&t.jsxs(c.DropdownMenuItem,{onClick:()=>r(l),className:"text-xs cursor-pointer",children:[te.UNPUBLISH," page"]})]})]})]}),t.jsx(ii,{showModal:e,onClose:()=>s(!1)}),i&&t.jsx(ds,{page:i,onClose:()=>r(null)})]})},mi=()=>{const e=qe("settingComponent",null),[s,n]=m.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(Bn,{content:te.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(N.Settings,{className:"w-4 h-4"})})}),s&&t.jsx(oi,{onClose:()=>n(!1)}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]}):null},fi=()=>{const{data:e}=De(),[s,n]=m.useState(""),a=e&&(e==null?void 0:e.online),{data:i}=Ne(),r=qe("getLiveUrl",async j=>j),l=m.useCallback(j=>{var y;return(y=g.find(i,{key:j}))==null?void 0:y.hasSlug},[i]),{selectedLang:o,fallbackLang:u}=W.useLanguages(),d=e==null?void 0:e.id,h=e==null?void 0:e.slug,f=o===u?"":o;return m.useEffect(()=>{(async()=>{if(typeof r=="function"){const j=!l(e==null?void 0:e.pageType),y=await r(j?`${f===""?"":f+"/"}${d}`:h||"");n(y)}else n("")})()},[r,e==null?void 0:e.pageType,l,d,h,f]),t.jsxs(c.Button,{onClick:()=>a&&window.open(s,"_blank"),disabled:!a,variant:"ghost",size:"sm",className:"flex items-center gap-1",children:[t.jsx(N.ExternalLink,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:te.OPEN})]})};function gi(){const{isLocked:e}=Kt(),[s]=_e(),n=s.get("lang"),a=En(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Zr,{}),t.jsx(Me,{permission:pe.EDIT_THEME,children:t.jsx(ui,{})}),t.jsx(Me,{permission:pe.EDIT_SETTINGS,children:t.jsx(mi,{})}),t.jsx(ci,{}),t.jsx(Me,{permission:pe.SAVE_PAGE,children:t.jsx(di,{})}),t.jsx(Me,{permission:pe.PUBLISH_PAGE,children:t.jsx(hi,{})}),t.jsx(fi,{})]})}const pi=()=>t.jsxs("div",{className:"flex px-2 h-full items-center justify-between w-full",children:[t.jsx(Kr,{}),t.jsx(gi,{})]}),xi=()=>{const e=ae(),{aiContext:s}=Is(),n=H();return m.useCallback(async(a,i,r,l)=>n(e,{action:k.ASK_AI,data:{type:a,prompt:i,blocks:r,context:s,lang:l}}),[e,s,n])},yi=(e,s)=>s.map(n=>{if(g.has(e,n._type)){const a=pn.getDefaultBlockProps(n._type);return{...a,...g.pick(n,[...g.keys(a),"_type","_id","_name","_parent","_bindings"]),...g.pickBy(n,(i,r)=>g.endsWith(r,"_attrs")),...n}}return n}),vi=e=>{const s=pn.useRegisteredChaiBlocks();return m.useMemo(()=>{if(!e||g.isEmpty(e))return{blocks:[]};const n=g.filter(e,a=>!g.includes(a==null?void 0:a._type,"@chai/"));return{blocks:yi(s,n)}},[e,s])},Js={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),i=g.get(a,"html",""),r=g.get(a,"blocks",[]);return g.isArray(r)?r:W.getBlocksFromHTML(i)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(i=>({...i}))}catch(a){return console.error(a),[]}}},ji=()=>{const e=ae(),s=H();return D.useQuery({queryKey:[z,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(i=>({...i}));return a.forEach(i=>{W.registerChaiLibrary(i.id,{name:i.name,description:i.description,getBlocksList:r=>Js.getUILibraryBlocks(r,s,e),getBlock:({block:r})=>Js.getUILibraryBlock(r,s,e)})}),a}})},Gn=()=>{const e=os(),s=H(),{user:n}=Oe(),a=n==null?void 0:n.id;return D.useQuery({queryKey:[z,"permissions",a],queryFn:()=>s(e,{action:k.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},bi=()=>{const e=ae(),s=H(),{setCurrentEditor:n}=Kt(),[,a]=cs();return{onSave:async({page:r,blocks:l})=>{try{const o=await s(e,{action:"UPDATE_PAGE",data:{id:r,blocks:l}});return o.code==="PAGE_LOCKED"?(n(o.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),o)}catch(o){return console.error(o),new Error("Failed to save blocks")}}}},Ei=()=>{const{data:e}=Vt(),s=ae(),n=H();return{getPartialBlocks:m.useCallback(async()=>{const a={};for(const i of e??[])g.isEmpty(i==null?void 0:i.slug)&&(a[i.id]={type:i.pageType,name:g.startCase(i.name??i.slug),description:""});return a},[e]),getPartialBlockBlocks:m.useCallback(async a=>{if(!a)return[];try{const i=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return g.filter(i.blocks,r=>g.has(r,"_id"))}catch(i){return console.error(i),[]}},[n,s])}},en=Xt.z.object({email:Xt.z.string().email({message:"Please enter a valid email address"}),password:Xt.z.string().min(6,{message:"Password must be at least 6 characters"})}),Si=()=>{const{setUser:e,logout:s}=Oe(),n=os(),[a,i]=m.useState(""),[r,l]=m.useState(""),[o,u]=m.useState({}),[d,h]=m.useState(!1),[f,j]=m.useState(""),y=D.useMutation({mutationFn:async b=>{j("");const U=await ks(n,{action:"LOGIN",data:b});if(!U.ok){const B=await U.json();throw new Error(B.error||"Login failed")}const w=await U.json();if(g.has(w,"id")&&g.has(w,"email")&&g.has(w,"accessToken")&&g.has(w,"refreshToken"))e(w);else throw s(),new Error("Something went wrong. Please try again.");return w},onSuccess:()=>{u({}),j("")},onError:b=>{u({email:" ",password:" "}),j(b.message||"Something went wrong")}}),x=async b=>{b.preventDefault(),u({});const U={email:a,password:r};try{const w=en.parse(U);y.mutate(w)}catch(w){if(w instanceof Xt.z.ZodError){const B=w.errors.reduce((S,_)=>{const O=_.path[0];return S[O]=_.message,S},{});u(B)}}},E=en.safeParse({email:a,password:r}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:x,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:b=>i(b.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:r,onChange:b=>l(b.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:f})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!E||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let js=Si;const wi=()=>m.useMemo(()=>js,[js]),Ni=e=>{js=e},Ai=()=>{const e=wi();return t.jsx(m.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},Ti=({isActive:e,show:s})=>{const{data:n}=Ye();return!g.has(n,"languages")||!g.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},Un="lang",Ci={id:Un,label:"Languages",position:"top",panel:Nr,button:Ti,view:"modal",width:400};function Ge({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[i,r]=je.useState(!1),[l,o]=je.useState([]),[u,d]=je.useState(e);je.useEffect(()=>{i||o([]),d(e)},[e,i]);const h=x=>Array.isArray(x)?"array":typeof x=="object"&&x!==null?"object":"value",f=je.useCallback(x=>{const E=b=>n==="value"?b==="value"||b==="object":n==="array"?b==="array":b===n;x.type==="object"?(o(b=>[...b,x.key]),d(x.value)):E(x.type)&&(s([...l,x.key].join(".")),r(!1))},[l,s,n]),j=je.useCallback(()=>{if(l.length>0){const x=l.slice(0,-1);o(x),d(x.reduce((E,b)=>E[b],e))}},[l,e]),y=je.useMemo(()=>Object.entries(u).map(([x,E])=>({key:x,value:E,type:h(E)})).filter(x=>n==="value"?x.type==="value"||x.type==="object":n==="array"?x.type==="array"||x.type==="object":n==="object"?x.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:i,onOpenChange:r,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":i,disabled:a,children:t.jsx(N.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:x=>{try{x.preventDefault();const E=x.currentTarget;E.scrollTop+=x.deltaY}catch{x.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:j,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(x=>t.jsxs(c.CommandItem,{onSelect:()=>f(x),className:"flex items-center justify-between",children:[t.jsx("span",{children:x.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&x.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:E=>{E.stopPropagation(),s([...l,x.key].join(".")),r(!1)},children:"Select"}),(x.type==="object"||x.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(N.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},x.key))]})]})]})})]})}const Pi=()=>{const e=Ht(),s=D.useQueryClient(),n=H();return D.useMutation({mutationFn:async({file:a,folderId:i,name:r,optimize:l=!0})=>n(e,{action:k.UPLOAD_ASSET,data:{file:a,folderId:i,name:r,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[z,k.GET_ASSETS]}),$.toast.success("Asset uploaded successfully")},onError:()=>{$.toast.error("Failed to upload asset")}})},ki=()=>{const e=Ht(),s=D.useQueryClient(),n=H();return D.useMutation({mutationFn:async a=>n(e,{action:k.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[z,k.GET_ASSETS]}),$.toast.success("Asset deleted successfully")},onError:()=>{$.toast.error("Failed to delete asset")}})},Ii=()=>{const e=Ht(),s=D.useQueryClient(),n=H();return D.useMutation({mutationFn:async a=>n(e,{action:k.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[z,k.GET_ASSETS]}),$.toast.success("Asset updated successfully")},onError:()=>{$.toast.error("Failed to update asset")}})},_i=(e={})=>{const s=Ht(),n=H(),{search:a,page:i=1,limit:r=30}=e;return D.useQuery({queryKey:[z,k.GET_ASSETS,a,i,r],queryFn:async()=>{const l=await n(s,{action:k.GET_ASSETS,data:{search:a,page:i,limit:r}});return l.page=i,l.limit=r,l},staleTime:1e3*60*5,retry:1})},Li=e=>{const s=Ht(),n=H();return D.useQuery({queryKey:[z,k.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:k.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Di(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 tn(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 sn(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 Mi=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:i})=>{var f,j,y;const{data:r,isLoading:l,isError:o}=Li(e||""),[u,d]=m.useState(""),h=async(x,E)=>{try{await navigator.clipboard.writeText(x),$.toast.success(`${E} copied to clipboard`)}catch(b){$.toast.error(`Failed to copy ${E}`,{description:b==null?void 0:b.message})}};return m.useEffect(()=>{r!=null&&r.description&&d(r.description)},[r]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}):o||!(r!=null&&r.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(N.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:i,children:[t.jsx(N.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>h(r.url,"Asset URL"),disabled:i,children:[t.jsx(N.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(r),disabled:i,children:[t.jsx(N.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${r.url}?v=${((f=r.metadata)==null?void 0:f.updatedAt)||r.createdAt}`,alt:r.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:r.name},{label:"Type",value:r.type,capitalize:!0},{label:"Format",value:((j=r.metadata)==null?void 0:j.format)||r.type,capitalize:!0},{label:"Size",value:Di(r.size)},{label:"Dimensions",value:`${r.width||0} × ${r.height||0}`},{label:"Created",value:tn(r.createdAt)},{label:"Updated",value:tn(((y=r.metadata)==null?void 0:y.updatedAt)||r.createdAt)},{label:"URL",value:r.url,copyable:!0}].map(x=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:x.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(x.capitalize?" capitalize":""),children:x.value}),x.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(x.value,x.label),children:t.jsx(N.Link,{className:"h-3 w-3"})})]})]},x.label))})]}),r.usedOn&&r.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:r.usedOn.map((x,E)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:x.name}),t.jsxs("div",{className:"text-gray-500",children:["(",x.slug,")"]})]},E))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:x=>d(x.target.value),rows:3,disabled:i,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:i||!sn(u,r),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${i||!sn(u,r)?"opacity-50 cursor-not-allowed":""}`,children:i?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},Bi=m.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function Gi(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 Ui=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:i,onUploaded:r})=>{const[l,o]=m.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});m.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||i,d=m.useCallback(async y=>new Promise((x,E)=>{const b=y[0],U=new FileReader;U.readAsDataURL(b),U.onload=async()=>{a({file:U.result,folderId:void 0,name:b.name,optimize:l},{onSuccess:w=>{r&&r(w),x(w)},onError:w=>{E(w)}})},U.onerror=w=>E(w)}),[a,l,r]),{getRootProps:h,getInputProps:f,isDragActive:j}=Da.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},maxSize:n*1024*1024,disabled:e||i});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:W.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",j?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...f()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(N.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(N.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange:y=>{o(y)},onClick:y=>{y.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(N.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Rn({close:e,onSelect:s,mode:n="image",assetId:a}){const l=m.useMemo(()=>[n],[n]),[o,u]=m.useState(null),[d,h]=m.useState(null),[f,j]=m.useState(null),[y,x]=m.useState({show:!1,file:""}),[E,b]=m.useState(!1),[U,w]=m.useState(a?"details":"grid"),[B,S]=m.useState(""),[_,O]=m.useState(""),[V,ne]=m.useState(1),[G]=m.useState(30),[L,F]=m.useState([]);m.useEffect(()=>{a&&(u(a),w("details"))},[a]),m.useEffect(()=>{const P=setTimeout(()=>{S(_),ne(1)},300);return()=>clearTimeout(P)},[_]);const{data:Y,isLoading:Q}=_i({search:B.toLowerCase().trim(),page:V,limit:G}),X=(Y==null?void 0:Y.assets)||[],le=(Y==null?void 0:Y.total)||0,I=Math.ceil(le/G),xe=V<I,Te=V>1,Z=(X==null?void 0:X.length)>0,{mutate:v}=ki(),{mutate:p,isPending:T}=Pi(),{mutate:M,isPending:R}=Ii(),C=m.useCallback(P=>{P>=1&&P<=I&&ne(P)},[I]),ee=m.useCallback(()=>{xe&&C(V+1)},[V,xe,C]),q=m.useCallback(()=>{Te&&C(V-1)},[V,Te,C]),se=P=>{O(P.target.value)},ue=m.useCallback(P=>{F(ie=>g.find(ie,{id:P.id})?[]:[P])},[!1]),ye=m.useCallback(()=>{F([])},[]),de=P=>{(P==null?void 0:P.length)!==0&&(s(g.pick(g.first(P||L),["id","url","width","height","description"])),e())},ve=async P=>{h(P)},Ee=async()=>{d&&(j(d==null?void 0:d.id),await v(d.id,{onSuccess:()=>{j(null),h(null)},onError:()=>{j(null)}}),h(null))},re=P=>{u(P.id),w("details")},Se=async(P,ie)=>{try{const A=localStorage.getItem("chai_optimize_images")!=="false";ie?(await p({file:P,folderId:void 0,name:y.name||"",optimize:A}),x({show:!1,file:""})):(await M({id:y.id||"",file:P}),x({show:!1,file:""}))}catch(A){console.error("Error saving edited image:",A)}},Ce=m.useCallback(P=>{F([P])},[]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"max-w-[1232px] max-h-[1232px] w-[80vw] h-[80vh] space-y-4 flex flex-col",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),U==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(Ui,{maxFileSize:10,allowedTypes:l,uploadAsset:p,isUpdatingAsset:R,isUploadingAsset:T,onUploaded:Ce}),t.jsxs("div",{className:"border p-2 rounded-lg flex-1 flex flex-col gap-y-3 overflow-hidden relative",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2 ",children:[t.jsx(N.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${_.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:se,value:_,className:"pl-8"})]}),L.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[L.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>ye(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>de(L),disabled:L.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:Q?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"})]}):!Q&&!Z?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full border rounded-lg",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(N.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:B.length>0?"No assets found for your search: "+B:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:X==null?void 0:X.map(P=>t.jsxs("div",{className:W.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",L.some(ie=>ie.id===P.id)?"border-blue-500":"hover:border-black/90",f&&(d==null?void 0:d.id)===P.id?"opacity-50 pointer-events-none":"",f===P.id?"opacity-50 pointer-events-none":""),onClick:()=>ue(P),onDoubleClick:()=>de([P]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[f===P.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,P.type==="image"?t.jsx("img",{src:`${P.thumbnailUrl||"/placeholder.svg"}?v=${(P==null?void 0:P.updatedAt)||P.createdAt}`,alt:P.name,className:`object-contain w-full h-full min-h-[80px] ${L.some(ie=>ie.id===P.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(N.Film,{className:"h-12 w-12 text-muted-foreground"}),P.thumbnailUrl&&t.jsx("img",{src:`${P.thumbnailUrl||"/placeholder.svg"}?v=${(P==null?void 0:P.updatedAt)||P.createdAt}`,alt:P.name,className:"absolute inset-0 object-cover w-full h-full"})]})]}),t.jsxs("div",{className:"py-1 px-2 flex items-end justify-between bg-white border-t-[1px] border-black/10",children:[t.jsx("div",{className:"text-xs truncate leading-tight",title:P.name,children:P.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:Gi((P==null?void 0:P.size)||0)})})]}),!L.some(ie=>ie.id===P.id)&&t.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),re(P)},children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),navigator.clipboard.writeText(P.url),$.toast.success("Asset URL copied to clipboard")},children:t.jsx(N.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),x({id:P.id,show:!0,file:P.url,name:P.name})},children:t.jsx(N.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:ie=>{ie.stopPropagation(),ve(P)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),L.some(ie=>ie.id===P.id)&&t.jsx("div",{className:"absolute top-1 right-1 border border-white h-max rounded-full bg-blue-500 p-1",children:t.jsx(N.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},P.id))})}),I>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:q,disabled:!Te,children:"Previous"}),Array.from({length:Math.min(5,I)},(P,ie)=>{const A=ie+1;return t.jsx(c.Button,{variant:V===A?"default":"outline",size:"sm",onClick:()=>C(A),children:A},A)}),I>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(c.Button,{variant:V===I?"default":"outline",size:"sm",onClick:()=>C(I),children:I})]}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:ee,disabled:!xe,children:"Next"})]})})]})]}):t.jsx(Mi,{assetId:o||a||"",onBack:()=>{w("grid"),u(null)},onEdit:P=>{x({id:P.id,show:!0,file:P.url,name:P.name})},onSave:async P=>{if(o){b(!0);try{const ie=X.find(A=>A.id===o);ie&&await M(g.merge(ie,{description:P}))}finally{b(!1)}}},isSaving:E})]}),y.show&&t.jsx(m.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Bi,{imageUrl:y.file,onSave:Se,onClose:()=>x({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),d&&t.jsx(c.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:Ee,children:"Delete"})]})]})})]})}const Ri=Object.freeze(Object.defineProperty({__proto__:null,default:Rn},Symbol.toStringTag,{value:"Module"})),On=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:i="Select an image",disabled:r=!1})=>{const[l,o]=m.useState(!1),u=()=>{r||o(!0)},d=()=>{o(!1)},h=j=>{const y=Array.isArray(j)?j[0]:j;y!=null&&y.url&&n(g.pick(y,["url","id"])),o(!1)},f=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:f,disabled:r,children:t.jsx(N.Trash2,{className:"h-4 w-4"})}),t.jsx(c.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:r,children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${r?"opacity-50 cursor-not-allowed":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:i})]})}),t.jsx(c.Dialog,{open:l,onOpenChange:o,children:t.jsxs(c.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(c.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(Rn,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Oi=()=>{const{selectedLang:e}=W.useLanguages(),{data:s,isFetching:n}=Qe();return{data:m.useMemo(()=>g.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Fi=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg").forEach(o=>o.remove()),a.querySelectorAll("*").forEach(o=>{Array.from(o.attributes).forEach(u=>o.removeAttribute(u.name))});const i=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(i).map(o=>`<${o.tagName.toLowerCase()}>${o.innerHTML}</${o.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},Ze=({keyword:e,onComplete:s,field:n})=>{const a=H(),i=ae(),{selectedLang:r,fallbackLang:l}=W.useLanguages(),o=W.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=D.useMutation({mutationFn:async()=>{const h=Fi();return await a(i,{action:k.GENERATE_SEO_FIELD,data:{pageContext:o,dynamic:!1,field:n,lang:r||l,pageContent:h,keyword:e}})},onSuccess:h=>{s({fieldValue:h.field})},onError:h=>{s({fieldValue:null,error:h.message})}});return t.jsx(c.Button,{disabled:d,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:d?t.jsx(N.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(N.Sparkle,{className:"text-yellow-500"})})},nn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},qi=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,i=e.value,r=i.substring(0,n),l=i.substring(a);let o=!1;if(n>0&&r.length>0){const x=r.charAt(r.length-1);o=!/[\s.,!?;:()[\]{}]/.test(x)&&x!==""}let u=!1;if(l.length>0){const x=l.charAt(0);u=!/[\s.,!?;:()[\]{}]/.test(x)&&x!==""}const d=o?" ":"",h=u?" ":"",f=`{{${s}}}`,j=r+(o?d:"")+f+(u?h:"")+l,y=n+(o?1:0)+f.length;return{value:j,newCursorPos:y}},Fn=()=>{const{t:e}=W.useTranslation(),{selectedLang:s,fallbackLang:n,languages:a}=W.useLanguages(),[,i]=W.useSidebarActivePanel(),{data:r}=Ls(),{data:l,isFetching:o}=Oi(),u=l==null?void 0:l.seo,d=m.useRef(null),[h,f]=m.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",...u}),j=m.useRef({initial:h,updated:h}),y=s.length?s:n,{mutate:x,isPending:E}=Ds(),b=E,{hasPermission:U}=W.usePermissions(),w=U(pe.EDIT_SEO);m.useEffect(()=>{!o&&u&&f({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...u})},[o,u]);const B=async()=>{x({id:l==null?void 0:l.id,seo:h},{onSuccess:()=>{j.current.initial=h,j.current.updated=h,i("outline")}})},S=()=>{f({...h,ogTitle:h.title,ogDescription:h.description})},_=()=>{f({...h,searchTitle:h.ogTitle,searchDescription:h.ogDescription})},O=(G,L)=>{const F=document.getElementById(L);if(F){const{value:Y,newCursorPos:Q}=qi(F,G);d.current={id:L,position:Q},F.tagName.toLowerCase()==="input"?(F.value=Y,f(I=>({...I,[F.name]:Y})),F.focus(),F.setSelectionRange(Q,Q),[0,10,50,100,200].forEach(I=>{setTimeout(()=>{const xe=document.getElementById(L);xe&&(xe.focus(),xe.setSelectionRange(Q,Q))},I)})):(f(le=>({...le,[F.name]:Y})),requestAnimationFrame(()=>{const le=document.getElementById(L);le&&(le.focus(),le.setSelectionRange(Q,Q),setTimeout(()=>{const I=document.getElementById(L);I&&(I.focus(),I.setSelectionRange(Q,Q))},50))}))}},V=G=>{const L={...h,[G.target.name]:G.target.name==="noIndex"||G.target.name==="noFollow"?G.target.checked:G.target.value};f(L),j.current.updated=L},ne=G=>L=>{g.isEmpty(L.fieldValue)||V({target:{name:G,value:L.fieldValue}}),L.error&&$.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:L.error})]}))};return t.jsxs("div",{className:"relative h-full flex flex-col",children:[!w&&t.jsx("div",{className:"absolute inset-0 z-10 backdrop-blur-sm flex items-center justify-center",children:t.jsx(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"flex-grow overflow-y-auto no-scrollbar px-2",children:[t.jsxs("div",{className:"p-2 text-xs text-left bg-gray-100 rounded-md mb-4",children:[e("Slug"),": ",l==null?void 0:l.slug,"  ",a.length>0&&t.jsxs("span",{className:"font-semibold text-blue-500",children:["(",g.get(ke,y,y),")"]})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Accordion,{type:"multiple",defaultValue:["page"],children:[t.jsxs(c.AccordionItem,{value:"page",children:[t.jsx(c.AccordionTrigger,{className:"font-semibold text-slate-700",children:e("SEO")}),t.jsx(c.AccordionContent,{className:"pt-2",children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Keyword")}),t.jsx("div",{className:"flex items-center justify-end gap-2",children:w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"keyword")})})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:h.keyword,onChange:V,disabled:b||!w,placeholder:e("Enter keyword"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(Ze,{keyword:h.keyword,onComplete:ne("title"),field:"title"}),w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:h.title,onChange:V,disabled:b||!w,placeholder:e("Enter SEO title"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ze,{keyword:h.keyword,onComplete:ne("description"),field:"description"}),w&&t.jsx(Ge,{data:r??{},onSelect:G=>O(G,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:h.description,onChange:V,disabled:b||!w,placeholder:e("Enter SEO description"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:h.canonicalUrl,onChange:V,disabled:b||!w,placeholder:e("Enter Canonical URL"),readOnly:!w})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:h.noIndex,onChange:V,disabled:b||!w,className:"w-4 h-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light text-gray-400 leading-4",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:h.noFollow,onChange:V,disabled:b||!w,className:"w-4 h-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light text-gray-400 leading-4",children:e("Check this if you don't want search engines to follow links on this page.")})]})]})})]}),t.jsxs(c.AccordionItem,{value:"og",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Open Graph")}),t.jsx(c.AccordionContent,{children:t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:!w,children:e("Copy from SEO Settings")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ze,{keyword:h.keyword,onComplete:ne("ogTitle"),field:"ogTitle"}),w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:h.ogTitle,onChange:V,disabled:b||!w,placeholder:e("Enter OG title"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ze,{keyword:h.keyword,onComplete:ne("ogDescription"),field:"ogDescription"}),w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:h.ogDescription,onChange:V,disabled:b||!w,placeholder:e("Enter OG description"),readOnly:!w})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(On,{assetId:h.ogImageId,assetUrl:h.ogImage,onChange:G=>{const L={...h,ogImage:G.url,ogImageId:G.id};f(L),j.current.updated=L},disabled:b||!w,placeholder:e("Select OG image"),className:"mb-2"})]})]})})]}),t.jsxs(c.AccordionItem,{value:"search",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("Search")}),t.jsx(c.AccordionContent,{children:t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:_,disabled:!w,children:e("Copy from OG Settings")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"searchTitle",children:e("Search Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ze,{keyword:h.keyword,onComplete:ne("searchTitle"),field:"searchTitle"}),w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"searchTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"searchTitle",name:"searchTitle",value:h.searchTitle,onChange:V,disabled:b||!w,placeholder:e("Enter search title"),readOnly:!w}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"searchDescription",children:e("Search Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ze,{keyword:h.keyword,onComplete:ne("searchDescription"),field:"searchDescription"}),w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"searchDescription")})]})]}),t.jsx(c.Textarea,{id:"searchDescription",rows:5,name:"searchDescription",value:h.searchDescription,onChange:V,placeholder:e("Enter search description"),disabled:b||!w,readOnly:!w})]})]})]})})]}),t.jsxs(c.AccordionItem,{value:"jsonLD",className:"border-none",children:[t.jsx(c.AccordionTrigger,{className:"font-bold text-slate-700",children:e("JSON-LD")}),t.jsx(c.AccordionContent,{children:t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ze,{keyword:h.keyword,onComplete:ne("jsonLD"),field:"jsonLD"}),w&&t.jsx(Ge,{dataType:"value",data:r??{},onSelect:G=>O(G,"jsonLD")})]})]}),t.jsx(c.Textarea,{id:"jsonLD",name:"jsonLD",rows:6,value:h.jsonLD,onChange:V,placeholder:e("Enter JSON-LD"),disabled:b||!w,readOnly:!w})]})})})]})]})})]}),w&&t.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between w-full p-4 bg-background border-t",children:[nn(h.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:"Invalid JSON. Please check."}),t.jsx(c.Button,{size:"lg",variant:"default",onClick:B,disabled:!nn(h==null?void 0:h.jsonLD)||g.isEqual(j.current.initial,h)||b||!w,children:e(E?"Saving...":"Save")})]})]})};Fn.displayName="SeoPanel";const qn="seo",zi=({isActive:e,show:s})=>{const{data:n}=De(),a=dr(n==null?void 0:n.pageType);return!g.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"w-4 h-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},$i={id:qn,label:"SEO",panel:Fn,button:zi,position:"top",width:600,view:"modal"},Hi="user-info",Vi=()=>{const{user:e,logout:s}=Oe(),n=D.useQueryClient(),a=qe("onLogout",g.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(N.User,{className:"w-4 h-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[z]}),g.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},Ki={id:Hi,label:"User Info",button:Vi,position:"bottom"},Wi=()=>{W.registerChaiSidebarPanel(qn,$i),W.registerChaiSidebarPanel(Un,Ci),W.registerChaiSidebarPanel("user-info",Ki)};var J={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return an(this.context.count)},getNextContextId(){return an(this.context.count++)}};function an(e){const s=String(e),n=s.length-1;return J.context.id+(n?String.fromCharCode(96+n):"")+s}function Nt(e){J.context=e}var Qi=(e,s)=>e===s,es=Symbol("solid-proxy"),zn=typeof Proxy=="function",Fs=Symbol("solid-track"),ts={equals:Qi},$n=Xn,ze=1,ss=2,Hn={owned:null,cleanups:null,context:null,owner:null},ps={},ce=null,xs=null,Yi=null,fe=null,Ie=null,Fe=null,hs=0;function He(e,s){const n=fe,a=ce,i=e.length===0,r=s===void 0?a:s,l=i?Hn:{owned:null,cleanups:null,context:r?r.context:null,owner:r},o=i?e:()=>e(()=>we(()=>kt(l)));ce=l,fe=null;try{return Ue(o,!0)}finally{fe=n,ce=a}}function be(e,s){s=s?Object.assign({},ts,s):ts;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=i=>(typeof i=="function"&&(i=i(n.value)),Yn(n,i));return[Qn.bind(n),a]}function Vn(e,s,n){const a=ms(e,s,!0,ze);wt(a)}function Ve(e,s,n){const a=ms(e,s,!1,ze);wt(a)}function qs(e,s,n){$n=ul;const a=ms(e,s,!1,ze);(!n||!n.render)&&(a.user=!0),Fe?Fe.push(a):wt(a)}function Le(e,s,n){n=n?Object.assign({},ts,n):ts;const a=ms(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,wt(a),Qn.bind(a)}function Xi(e){return e&&typeof e=="object"&&"then"in e}function Zi(e,s,n){let a,i,r;arguments.length===1?(a=!0,i=e,r={}):(a=e,i=s,r={});let l=null,o=ps,u=null,d=!1,h="initialValue"in r,f=typeof a=="function"&&Le(a);const j=new Set,[y,x]=(r.storage||be)(r.initialValue),[E,b]=be(void 0),[U,w]=be(void 0,{equals:!1}),[B,S]=be(h?"ready":"unresolved");J.context&&(u=J.getNextContextId(),r.ssrLoadFrom==="initial"?o=r.initialValue:J.load&&J.has(u)&&(o=J.load(u)));function _(G,L,F,Y){return l===G&&(l=null,Y!==void 0&&(h=!0),(G===o||L===o)&&r.onHydrated&&queueMicrotask(()=>r.onHydrated(Y,{value:L})),o=ps,O(L,F)),L}function O(G,L){Ue(()=>{L===void 0&&x(()=>G),S(L!==void 0?"errored":h?"ready":"unresolved"),b(L);for(const F of j.keys())F.decrement();j.clear()},!1)}function V(){const G=ll,L=y(),F=E();if(F!==void 0&&!l)throw F;return fe&&fe.user,L}function ne(G=!0){if(G!==!1&&d)return;d=!1;const L=f?f():a;if(L==null||L===!1){_(l,we(y));return}const F=o!==ps?o:we(()=>i(L,{value:y(),refetching:G}));return Xi(F)?(l=F,"value"in F?(F.status==="success"?_(l,F.value,void 0,L):_(l,void 0,bs(F.value),L),F):(d=!0,queueMicrotask(()=>d=!1),Ue(()=>{S(h?"refreshing":"pending"),w()},!1),F.then(Y=>_(F,Y,void 0,L),Y=>_(F,void 0,bs(Y),L)))):(_(l,F,void 0,L),F)}return Object.defineProperties(V,{state:{get:()=>B()},error:{get:()=>E()},loading:{get(){const G=B();return G==="pending"||G==="refreshing"}},latest:{get(){if(!h)return V();const G=E();if(G&&!l)throw G;return y()}}}),f?Vn(()=>ne(!1)):ne(!1),[V,{refetch:ne,mutate:x}]}function Ji(e){return Ue(e,!1)}function we(e){if(fe===null)return e();const s=fe;fe=null;try{return e()}finally{fe=s}}function el(e,s,n){const a=Array.isArray(e);let i,r=n&&n.defer;return l=>{let o;if(a){o=Array(e.length);for(let d=0;d<e.length;d++)o[d]=e[d]()}else o=e();if(r)return r=!1,l;const u=we(()=>s(o,i,l));return i=o,u}}function Kn(e){qs(()=>we(e))}function bt(e){return ce===null||(ce.cleanups===null?ce.cleanups=[e]:ce.cleanups.push(e)),e}function rn(){return ce}function tl(e,s){const n=ce,a=fe;ce=e,fe=null;try{return Ue(s,!0)}catch(i){zs(i)}finally{ce=n,fe=a}}function sl(e){const s=fe,n=ce;return Promise.resolve().then(()=>{fe=s,ce=n;let a;return Ue(e,!1),fe=ce=null,a?a.done:void 0})}var[nl,Xo]=be(!1);function al(){return[nl,sl]}function rl(e,s){const n=Symbol("context");return{id:n,Provider:dl(n),defaultValue:e}}function il(e){let s;return ce&&ce.context&&(s=ce.context[e.id])!==void 0?s:e.defaultValue}function Wn(e){const s=Le(e),n=Le(()=>Es(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var ll;function Qn(){if(this.sources&&this.state)if(this.state===ze)wt(this);else{const e=Ie;Ie=null,Ue(()=>as(this),!1),Ie=e}if(fe){const e=this.observers?this.observers.length:0;fe.sources?(fe.sources.push(this),fe.sourceSlots.push(e)):(fe.sources=[this],fe.sourceSlots=[e]),this.observers?(this.observers.push(fe),this.observerSlots.push(fe.sources.length-1)):(this.observers=[fe],this.observerSlots=[fe.sources.length-1])}return this.value}function Yn(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&Ue(()=>{for(let i=0;i<e.observers.length;i+=1){const r=e.observers[i],l=xs&&xs.running;l&&xs.disposed.has(r),(l?!r.tState:!r.state)&&(r.pure?Ie.push(r):Fe.push(r),r.observers&&Zn(r)),l||(r.state=ze)}if(Ie.length>1e6)throw Ie=[],new Error},!1)),s}function wt(e){if(!e.fn)return;kt(e);const s=hs;ol(e,e.value,s)}function ol(e,s,n){let a;const i=ce,r=fe;fe=ce=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=ze,e.owned&&e.owned.forEach(kt),e.owned=null),e.updatedAt=n+1,zs(l)}finally{fe=r,ce=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Yn(e,a):e.value=a,e.updatedAt=n)}function ms(e,s,n,a=ze,i){const r={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:ce,context:ce?ce.context:null,pure:n};return ce===null||ce!==Hn&&(ce.owned?ce.owned.push(r):ce.owned=[r]),r}function ns(e){if(e.state===0)return;if(e.state===ss)return as(e);if(e.suspense&&we(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<hs);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===ze)wt(e);else if(e.state===ss){const a=Ie;Ie=null,Ue(()=>as(e,s[0]),!1),Ie=a}}function Ue(e,s){if(Ie)return e();let n=!1;s||(Ie=[]),Fe?n=!0:Fe=[],hs++;try{const a=e();return cl(n),a}catch(a){n||(Fe=null),Ie=null,zs(a)}}function cl(e){if(Ie&&(Xn(Ie),Ie=null),e)return;const s=Fe;Fe=null,s.length&&Ue(()=>$n(s),!1)}function Xn(e){for(let s=0;s<e.length;s++)ns(e[s])}function ul(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:ns(a)}if(J.context){if(J.count){J.effects||(J.effects=[]),J.effects.push(...e.slice(0,n));return}Nt()}for(J.effects&&(J.done||!J.count)&&(e=[...J.effects,...e],n+=J.effects.length,delete J.effects),s=0;s<n;s++)ns(e[s])}function as(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const i=a.state;i===ze?a!==s&&(!a.updatedAt||a.updatedAt<hs)&&ns(a):i===ss&&as(a,s)}}}function Zn(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ss,n.pure?Ie.push(n):Fe.push(n),n.observers&&Zn(n))}}function kt(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),i=n.observers;if(i&&i.length){const r=i.pop(),l=n.observerSlots.pop();a<i.length&&(r.sourceSlots[l]=a,i[a]=r,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)kt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)kt(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 bs(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function zs(e,s=ce){throw bs(e)}function Es(e){if(typeof e=="function"&&!e.length)return Es(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Es(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function dl(e,s){return function(a){let i;return Ve(()=>i=we(()=>(ce.context={...ce.context,[e]:a.value},Wn(()=>a.children))),void 0),i}}var Ss=Symbol("fallback");function rs(e){for(let s=0;s<e.length;s++)e[s]()}function hl(e,s,n={}){let a=[],i=[],r=[],l=0,o=s.length>1?[]:null;return bt(()=>rs(r)),()=>{let u=e()||[],d=u.length,h,f;return u[Fs],we(()=>{let y,x,E,b,U,w,B,S,_;if(d===0)l!==0&&(rs(r),r=[],a=[],i=[],l=0,o&&(o=[])),n.fallback&&(a=[Ss],i[0]=He(O=>(r[0]=O,n.fallback())),l=1);else if(l===0){for(i=new Array(d),f=0;f<d;f++)a[f]=u[f],i[f]=He(j);l=d}else{for(E=new Array(d),b=new Array(d),o&&(U=new Array(d)),w=0,B=Math.min(l,d);w<B&&a[w]===u[w];w++);for(B=l-1,S=d-1;B>=w&&S>=w&&a[B]===u[S];B--,S--)E[S]=i[B],b[S]=r[B],o&&(U[S]=o[B]);for(y=new Map,x=new Array(S+1),f=S;f>=w;f--)_=u[f],h=y.get(_),x[f]=h===void 0?-1:h,y.set(_,f);for(h=w;h<=B;h++)_=a[h],f=y.get(_),f!==void 0&&f!==-1?(E[f]=i[h],b[f]=r[h],o&&(U[f]=o[h]),f=x[f],y.set(_,f)):r[h]();for(f=w;f<d;f++)f in E?(i[f]=E[f],r[f]=b[f],o&&(o[f]=U[f],o[f](f))):i[f]=He(j);i=i.slice(0,l=d),a=u.slice(0)}return i});function j(y){if(r[f]=y,o){const[x,E]=be(f);return o[f]=E,s(u[f],x)}return s(u[f])}}}function ml(e,s,n={}){let a=[],i=[],r=[],l=[],o=0,u;return bt(()=>rs(r)),()=>{const d=e()||[],h=d.length;return d[Fs],we(()=>{if(h===0)return o!==0&&(rs(r),r=[],a=[],i=[],o=0,l=[]),n.fallback&&(a=[Ss],i[0]=He(j=>(r[0]=j,n.fallback())),o=1),i;for(a[0]===Ss&&(r[0](),r=[],a=[],i=[],o=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(i[u]=He(f));for(;u<a.length;u++)r[u]();return o=l.length=r.length=h,a=d.slice(0),i=i.slice(0,o)});function f(j){r[u]=j;const[y,x]=be(d[u]);return l[u]=x,s(y,u)}}}function $s(e,s){return we(()=>e(s||{}))}function Wt(){return!0}var ws={get(e,s,n){return s===es?n:e.get(s)},has(e,s){return s===es?!0:e.has(s)},set:Wt,deleteProperty:Wt,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:Wt,deleteProperty:Wt}},ownKeys(e){return e.keys()}};function ys(e){return(e=typeof e=="function"?e():e)?e:{}}function fl(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function Hs(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&es in o,e[l]=typeof o=="function"?(s=!0,Le(o)):o}if(zn&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=ys(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in ys(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(ys(e[o])));return[...new Set(l)]}},ws);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const f=Object.getOwnPropertyDescriptor(o,h);if(!a[h])a[h]=f.get?{enumerable:!0,configurable:!0,get:fl.bind(n[h]=[f.get.bind(o)])}:f.value!==void 0?f:void 0;else{const j=n[h];j&&(f.get?j.push(f.get.bind(o)):f.value!==void 0&&j.push(()=>f.value))}}}const i={},r=Object.keys(a);for(let l=r.length-1;l>=0;l--){const o=r[l],u=a[o];u&&u.get?Object.defineProperty(i,o,u):i[o]=u?u.value:void 0}return i}function Jn(e,...s){if(zn&&es in e){const i=new Set(s.length>1?s.flat():s[0]),r=s.map(l=>new Proxy({get(o){return l.includes(o)?e[o]:void 0},has(o){return l.includes(o)&&o in e},keys(){return l.filter(o=>o in e)}},ws));return r.push(new Proxy({get(l){return i.has(l)?void 0:e[l]},has(l){return i.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!i.has(l))}},ws)),r}const n={},a=s.map(()=>({}));for(const i of Object.getOwnPropertyNames(e)){const r=Object.getOwnPropertyDescriptor(e,i),l=!r.get&&!r.set&&r.enumerable&&r.writable&&r.configurable;let o=!1,u=0;for(const d of s)d.includes(i)&&(o=!0,l?a[u][i]=r.value:Object.defineProperty(a[u],i,r)),++u;o||(l?n[i]=r.value:Object.defineProperty(n,i,r))}return[...a,n]}function ea(e){let s,n;const a=i=>{const r=J.context;if(r){const[o,u]=be();J.count||(J.count=0),J.count++,(n||(n=e())).then(d=>{!J.done&&Nt(r),J.count--,u(()=>d.default),Nt()}),s=o}else if(!s){const[o]=Zi(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Le(()=>(l=s())?we(()=>{if(!r||J.done)return l(i);const o=J.context;Nt(r);const u=l(i);return Nt(o),u}):"")};return a.preload=()=>n||((n=e()).then(i=>s=()=>i.default),n),a}var gl=0;function pl(){return J.context?J.getNextContextId():`cl-${gl++}`}var ta=e=>`Stale read from <${e}>.`;function xl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Le(hl(()=>e.each,e.children,s||void 0))}function yl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Le(ml(()=>e.each,e.children,s||void 0))}function vl(e){const s=e.keyed,n=Le(()=>e.when,void 0,{equals:(a,i)=>s?a===i:!a==!i});return Le(()=>{const a=n();if(a){const i=e.children;return typeof i=="function"&&i.length>0?we(()=>i(s?a:()=>{if(!we(n))throw ta("Show");return e.when})):i}return e.fallback},void 0,void 0)}function jl(e){let s=!1;const n=(r,l)=>(s?r[1]===l[1]:!r[1]==!l[1])&&r[2]===l[2],a=Wn(()=>e.children),i=Le(()=>{let r=a();Array.isArray(r)||(r=[r]);for(let l=0;l<r.length;l++){const o=r[l].when;if(o)return s=!!r[l].keyed,[l,o,r[l]]}return[-1]},void 0,{equals:n});return Le(()=>{const[r,l,o]=i();if(r<0)return e.fallback;const u=o.children;return typeof u=="function"&&u.length>0?we(()=>u(s?l:()=>{if(we(i)[0]!==r)throw ta("Match");return o.when})):u},void 0,void 0)}function bl(e){return e}var El=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","hidden","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected"],Sl=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...El]),wl=new Set(["innerHTML","textContent","innerText","children"]),Nl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Al=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 Tl(e,s){const n=Al[e];return typeof n=="object"?n[s]?n.$:void 0:n}var Cl=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Pl=new Set(["altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","hkern","image","line","linearGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tref","tspan","use","view","vkern"]),kl={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function Il(e,s,n){let a=n.length,i=s.length,r=a,l=0,o=0,u=s[i-1].nextSibling,d=null;for(;l<i||o<r;){if(s[l]===n[o]){l++,o++;continue}for(;s[i-1]===n[r-1];)i--,r--;if(i===l){const h=r<a?o?n[o-1].nextSibling:n[r-o]:u;for(;o<r;)e.insertBefore(n[o++],h)}else if(r===o)for(;l<i;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[r-1]&&n[o]===s[i-1]){const h=s[--i].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--r],h),s[i]=n[r]}else{if(!d){d=new Map;let f=o;for(;f<r;)d.set(n[f],f++)}const h=d.get(s[l]);if(h!=null)if(o<h&&h<r){let f=l,j=1,y;for(;++f<i&&f<r&&!((y=d.get(s[f]))==null||y!==h+j);)j++;if(j>h-o){const x=s[l];for(;o<h;)e.insertBefore(n[o++],x)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var Ct="_$DX_DELEGATE";function sa(e,s,n,a={}){let i;return He(r=>{i=r,s===document?e():ls(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{i(),s.textContent=""}}function _l(e,s,n){let a;const i=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},r=()=>(a||(a=i())).cloneNode(!0);return r.cloneNode=r,r}function na(e,s=window.document){const n=s[Ct]||(s[Ct]=new Set);for(let a=0,i=e.length;a<i;a++){const r=e[a];n.has(r)||(n.add(r),s.addEventListener(r,oa))}}function Ll(e=window.document){if(e[Ct]){for(let s of e[Ct].keys())e.removeEventListener(s,oa);delete e[Ct]}}function is(e,s,n){st(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function Dl(e,s,n,a){st(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function Ml(e,s,n){st(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function aa(e,s){st(e)||(s==null?e.removeAttribute("class"):e.className=s)}function ra(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 i=n[0];e.addEventListener(s,n[0]=r=>i.call(e,n[1],r))}else e.addEventListener(s,n,typeof n!="function"&&n)}function Bl(e,s,n={}){const a=Object.keys(s||{}),i=Object.keys(n);let r,l;for(r=0,l=i.length;r<l;r++){const o=i[r];!o||o==="undefined"||s[o]||(ln(e,o,!1),delete n[o])}for(r=0,l=a.length;r<l;r++){const o=a[r],u=!!s[o];!o||o==="undefined"||n[o]===u||!u||(ln(e,o,!0),n[o]=u)}return n}function Gl(e,s,n){if(!s)return n?is(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let i,r;for(r in n)s[r]==null&&a.removeProperty(r),delete n[r];for(r in s)i=s[r],i!==n[r]&&(a.setProperty(r,i),n[r]=i);return n}function ia(e,s={},n,a){const i={};return a||Ve(()=>i.children=It(e,s.children,i.children)),Ve(()=>typeof s.ref=="function"&&la(s.ref,e)),Ve(()=>Ul(e,s,n,!0,i,!0)),i}function la(e,s,n){return we(()=>e(s,n))}function ls(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return It(e,s,a,n);Ve(i=>It(e,s(),i,n),a)}function Ul(e,s,n,a,i={},r=!1){s||(s={});for(const l in i)if(!(l in s)){if(l==="children")continue;i[l]=on(e,l,null,i[l],n,r,s)}for(const l in s){if(l==="children")continue;const o=s[l];i[l]=on(e,l,o,i[l],n,r,s)}}function Rl(e){let s,n;return!st()||!(s=J.registry.get(n=Fl()))?e():(J.completed&&J.completed.add(s),J.registry.delete(n),s)}function st(e){return!!J.context&&!J.done&&(!e||e.isConnected)}function Ol(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function ln(e,s,n){const a=s.trim().split(/\s+/);for(let i=0,r=a.length;i<r;i++)e.classList.toggle(a[i],n)}function on(e,s,n,a,i,r,l){let o,u,d,h,f;if(s==="style")return Gl(e,n,a);if(s==="classList")return Bl(e,n,a);if(n===a)return a;if(s==="ref")r||n(e);else if(s.slice(0,3)==="on:"){const j=s.slice(3);a&&e.removeEventListener(j,a,typeof a!="function"&&a),n&&e.addEventListener(j,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const j=s.slice(10);a&&e.removeEventListener(j,a,!0),n&&e.addEventListener(j,n,!0)}else if(s.slice(0,2)==="on"){const j=s.slice(2).toLowerCase(),y=Cl.has(j);if(!y&&a){const x=Array.isArray(a)?a[0]:a;e.removeEventListener(j,x)}(y||n)&&(ra(e,j,n,y),y&&na([j]))}else if(s.slice(0,5)==="attr:")is(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")Ml(e,s.slice(5),n);else if((f=s.slice(0,5)==="prop:")||(d=wl.has(s))||!i&&((h=Tl(s,e.tagName))||(u=Sl.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(f)s=s.slice(5),u=!0;else if(st(e))return n;s==="class"||s==="className"?aa(e,n):o&&!u&&!d?e[Ol(s)]=n:e[h||s]=n}else{const j=i&&s.indexOf(":")>-1&&kl[s.split(":")[0]];j?Dl(e,j,s,n):is(e,Nl[s]||s,n)}return n}function oa(e){if(J.registry&&J.events&&J.events.find(([u,d])=>d===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,i=e.currentTarget,r=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)&&r(s.host),!0},o=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),J.registry&&!J.done&&(J.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();r(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,o();break}if(s.parentNode===i)break}}else o();r(a)}function It(e,s,n,a,i){const r=st(e);if(r){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const h=n[d];h.nodeType===8&&h.data.slice(0,2)==="!$"?h.remove():u.push(h)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,o=a!==void 0;if(e=o&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(r||l==="number"&&(s=s.toString(),s===n))return n;if(o){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=at(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(r)return n;n=at(e,n,a)}else{if(l==="function")return Ve(()=>{let u=s();for(;typeof u=="function";)u=u();n=It(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Ns(u,s,n,i))return Ve(()=>n=It(e,u,n,a,!0)),()=>n;if(r){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let h=u[0];if(h.parentNode!==e)return n;const f=[h];for(;(h=h.nextSibling)!==a;)f.push(h);return n=f}if(u.length===0){if(n=at(e,n,a),o)return n}else d?n.length===0?cn(e,u,a):Il(e,n,u):(n&&at(e),cn(e,u));n=u}else if(s.nodeType){if(r&&s.parentNode)return n=o?[s]:s;if(Array.isArray(n)){if(o)return n=at(e,n,a,s);at(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Ns(e,s,n,a){let i=!1;for(let r=0,l=s.length;r<l;r++){let o=s[r],u=n&&n[e.length],d;if(!(o==null||o===!0||o===!1))if((d=typeof o)=="object"&&o.nodeType)e.push(o);else if(Array.isArray(o))i=Ns(e,o,u)||i;else if(d==="function")if(a){for(;typeof o=="function";)o=o();i=Ns(e,Array.isArray(o)?o:[o],Array.isArray(u)?u:[u])||i}else e.push(o),i=!0;else{const h=String(o);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return i}function cn(e,s,n=null){for(let a=0,i=s.length;a<i;a++)e.insertBefore(s[a],n)}function at(e,s,n,a){if(n===void 0)return e.textContent="";const i=a||document.createTextNode("");if(s.length){let r=!1;for(let l=s.length-1;l>=0;l--){const o=s[l];if(i!==o){const u=o.parentNode===e;!r&&!l?u?e.replaceChild(i,o):e.insertBefore(i,n):u&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}function Fl(){return J.getNextContextId()}var ql="http://www.w3.org/2000/svg";function ca(e,s=!1){return s?document.createElementNS(ql,e):document.createElement(e)}function zl(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,i=rn();let r,l=!!J.context;return qs(()=>{l&&(rn().user=l=!1),r||(r=tl(i,()=>Le(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,d]=be(!1),h=()=>d(!0);He(f=>ls(o,()=>u()?f():r(),null)),bt(h)}else{const u=ca(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),ls(d,r),o.appendChild(u),e.ref&&e.ref(u),bt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function $l(e){const[s,n]=Jn(e,["component"]),a=Le(()=>s.component);return Le(()=>{const i=a();switch(typeof i){case"function":return we(()=>i(n));case"string":const r=Pl.has(i),l=J.context?Rl():ca(i,r);return ia(l,n,r),l}})}var Hl=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()}},ua=class{constructor(e){this.generateIdentifier=e,this.kv=new Hl}register(e,s){this.kv.getByValue(e)||(s||(s=this.generateIdentifier(e)),this.kv.set(s,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},Vl=class extends ua{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 Kl(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 Wl(e,s){const n=Kl(e);if("find"in n)return n.find(s);const a=n;for(let i=0;i<a.length;i++){const r=a[i];if(s(r))return r}}function Et(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function Zt(e,s){return e.indexOf(s)!==-1}function un(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var Ql=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return Wl(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},Yl=e=>Object.prototype.toString.call(e).slice(8,-1),da=e=>typeof e>"u",Xl=e=>e===null,_t=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,As=e=>_t(e)&&Object.keys(e).length===0,We=e=>Array.isArray(e),Zl=e=>typeof e=="string",Jl=e=>typeof e=="number"&&!isNaN(e),eo=e=>typeof e=="boolean",to=e=>e instanceof RegExp,Lt=e=>e instanceof Map,Dt=e=>e instanceof Set,ha=e=>Yl(e)==="Symbol",so=e=>e instanceof Date&&!isNaN(e.valueOf()),no=e=>e instanceof Error,dn=e=>typeof e=="number"&&isNaN(e),ao=e=>eo(e)||Xl(e)||da(e)||Jl(e)||Zl(e)||ha(e),ro=e=>typeof e=="bigint",io=e=>e===1/0||e===-1/0,lo=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),oo=e=>e instanceof URL,ma=e=>e.replace(/\./g,"\\."),vs=e=>e.map(String).map(ma).join("."),Pt=e=>{const s=[];let n="";for(let i=0;i<e.length;i++){let r=e.charAt(i);if(r==="\\"&&e.charAt(i+1)==="."){n+=".",i++;continue}if(r==="."){s.push(n),n="";continue}n+=r}const a=n;return s.push(a),s};function Be(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var fa=[Be(da,"undefined",()=>null,()=>{}),Be(ro,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),Be(so,"Date",e=>e.toISOString(),e=>new Date(e)),Be(no,"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}),Be(to,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),Be(Dt,"set",e=>[...e.values()],e=>new Set(e)),Be(Lt,"map",e=>[...e.entries()],e=>new Map(e)),Be(e=>dn(e)||io(e),"number",e=>dn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),Be(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),Be(oo,"URL",e=>e.toString(),e=>new URL(e))];function fs(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var ga=fs((e,s)=>ha(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),{}),pa=fs(lo,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 xa(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var ya=fs(xa,(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(i=>{a[i]=e[i]}),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)}),va=fs((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)}),uo=[ya,ga,va,pa],hn=(e,s)=>{const n=un(uo,i=>i.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=un(fa,i=>i.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},ja={};fa.forEach(e=>{ja[e.annotation]=e});var ho=(e,s,n)=>{if(We(s))switch(s[0]){case"symbol":return ga.untransform(e,s,n);case"class":return ya.untransform(e,s,n);case"custom":return va.untransform(e,s,n);case"typed-array":return pa.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=ja[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},rt=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function ba(e){if(Zt(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Zt(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Zt(e,"constructor"))throw new Error("constructor is not allowed as a property")}var mo=(e,s)=>{ba(s);for(let n=0;n<s.length;n++){const a=s[n];if(Dt(e))e=rt(e,+a);else if(Lt(e)){const i=+a,r=+s[++n]==0?"key":"value",l=rt(e,i);switch(r){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Ts=(e,s,n)=>{if(ba(s),s.length===0)return n(e);let a=e;for(let r=0;r<s.length-1;r++){const l=s[r];if(We(a)){const o=+l;a=a[o]}else if(_t(a))a=a[l];else if(Dt(a)){const o=+l;a=rt(a,o)}else if(Lt(a)){if(r===s.length-2)break;const u=+l,d=+s[++r]==0?"key":"value",h=rt(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const i=s[s.length-1];if(We(a)?a[+i]=n(a[+i]):_t(a)&&(a[i]=n(a[i])),Dt(a)){const r=rt(a,+i),l=n(r);r!==l&&(a.delete(r),a.add(l))}if(Lt(a)){const r=+s[s.length-2],l=rt(a,r);switch(+i==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 Cs(e,s,n=[]){if(!e)return;if(!We(e)){Et(e,(r,l)=>Cs(r,s,[...n,...Pt(l)]));return}const[a,i]=e;i&&Et(i,(r,l)=>{Cs(r,s,[...n,...Pt(l)])}),s(a,n)}function fo(e,s,n){return Cs(s,(a,i)=>{e=Ts(e,i,r=>ho(r,a,n))}),e}function go(e,s){function n(a,i){const r=mo(e,Pt(i));a.map(Pt).forEach(l=>{e=Ts(e,l,()=>r)})}if(We(s)){const[a,i]=s;a.forEach(r=>{e=Ts(e,Pt(r),()=>e)}),i&&Et(i,n)}else Et(s,n);return e}var po=(e,s)=>_t(e)||We(e)||Lt(e)||Dt(e)||xa(e,s);function xo(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function yo(e,s){const n={};let a;return e.forEach(i=>{if(i.length<=1)return;s||(i=i.map(o=>o.map(String)).sort((o,u)=>o.length-u.length));const[r,...l]=i;r.length===0?a=l.map(vs):n[vs(r)]=l.map(vs)}),a?As(n)?[a]:[a,n]:As(n)?void 0:n}var Ea=(e,s,n,a,i=[],r=[],l=new Map)=>{const o=ao(e);if(!o){xo(e,i,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!po(e,n)){const y=hn(e,n),x=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,x),x}if(Zt(r,e))return{transformedValue:null};const u=hn(e,n),d=(u==null?void 0:u.value)??e,h=We(d)?[]:{},f={};Et(d,(y,x)=>{if(x==="__proto__"||x==="constructor"||x==="prototype")throw new Error(`Detected property ${x}. This is a prototype pollution risk, please remove it from your object.`);const E=Ea(y,s,n,a,[...i,x],[...r,e],l);h[x]=E.transformedValue,We(E.annotations)?f[x]=E.annotations:_t(E.annotations)&&Et(E.annotations,(b,U)=>{f[ma(x)+"."+U]=b})});const j=As(f)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,f]:f};return o||l.set(e,j),j};function Sa(e){return Object.prototype.toString.call(e).slice(8,-1)}function mn(e){return Sa(e)==="Array"}function vo(e){if(Sa(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function jo(e,s,n,a,i){const r={}.propertyIsEnumerable.call(a,s)?"enumerable":"nonenumerable";r==="enumerable"&&(e[s]=n),i&&r==="nonenumerable"&&Object.defineProperty(e,s,{value:n,enumerable:!1,writable:!0,configurable:!0})}function Ps(e,s={}){if(mn(e))return e.map(i=>Ps(i,s));if(!vo(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((i,r)=>{if(mn(s.props)&&!s.props.includes(r))return i;const l=e[r],o=Ps(l,s);return jo(i,r,o,e,s.nonenumerable),i},{})}var ge=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Vl,this.symbolRegistry=new ua(s=>s.description??""),this.customTransformerRegistry=new Ql,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Ea(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const i=yo(s,this.dedupe);return i&&(a.meta={...a.meta,referentialEqualities:i}),a}deserialize(e){const{json:s,meta:n}=e;let a=Ps(s);return n!=null&&n.values&&(a=fo(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=go(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)}};ge.defaultInstance=new ge;ge.serialize=ge.defaultInstance.serialize.bind(ge.defaultInstance);ge.deserialize=ge.defaultInstance.deserialize.bind(ge.defaultInstance);ge.stringify=ge.defaultInstance.stringify.bind(ge.defaultInstance);ge.parse=ge.defaultInstance.parse.bind(ge.defaultInstance);ge.registerClass=ge.defaultInstance.registerClass.bind(ge.defaultInstance);ge.registerSymbol=ge.defaultInstance.registerSymbol.bind(ge.defaultInstance);ge.registerCustom=ge.defaultInstance.registerCustom.bind(ge.defaultInstance);ge.allowErrorProps=ge.defaultInstance.allowErrorProps.bind(ge.defaultInstance);var wa=ge.serialize,bo=ge.stringify;function Eo(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function So(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function wo({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function No({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function Ao(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var To=(e,s=!1)=>{const{json:n}=wa(e);return JSON.stringify(n,null,s?2:void 0)},Qt=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,Co=(e,s)=>e.queryHash.localeCompare(s.queryHash),Na=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,Po=(e,s)=>Qt(e)===Qt(s)?Na(e,s):Qt(e)>Qt(s)?1:-1,ko={status:Po,"query hash":Co,"last updated":Na},Yt=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Aa=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,Io=(e,s)=>Yt(e)===Yt(s)?Aa(e,s):Yt(e)>Yt(s)?1:-1,_o={status:Io,"last updated":Aa},Lo=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),Do=()=>{const[e,s]=be("dark");return Kn(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=i=>{s(i.matches?"dark":"light")};n.addEventListener("change",a),bt(()=>n.removeEventListener("change",a))}),e},At=(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[i,...r]=s;return a.set(i,At(a.get(i),r,n)),a}if(e instanceof Set){const a=At(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[i,...r]=s;return a[i]=At(a[i],r,n),a}if(e instanceof Object){const a={...e};if(s.length===1)return a[s[0]]=n,a;const[i,...r]=s;return a[i]=At(a[i],r,n),a}return e},Tt=(e,s)=>{if(e instanceof Map){const n=new Map(e);if(s.length===1)return n.delete(s[0]),n;const[a,...i]=s;return n.set(a,Tt(n.get(a),i)),n}if(e instanceof Set){const n=Tt(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((r,l)=>l.toString()!==s[0]);const[a,...i]=s;return n[a]=Tt(n[a],i),n}if(e instanceof Object){const n={...e};if(s.length===1)return delete n[s[0]],n;const[a,...i]=s;return n[a]=Tt(n[a],i),n}return e},Ta=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),i=document.createTextNode("");a.appendChild(i),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},it,Mt,Bt,Gt,Je,Ut,lt,ot,ct,ut,dt,ht,Rt,fn,Mo=(fn=class{constructor(e){me(this,it);me(this,Mt);me(this,Bt);me(this,Gt);me(this,Je,!1);me(this,Ut);me(this,lt);me(this,ot);me(this,ct);me(this,ut);me(this,dt);me(this,ht);me(this,Rt);const{client:s,queryFlavor:n,version:a,onlineManager:i,buttonPosition:r,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;he(this,it,be(s)),he(this,Bt,n),he(this,Gt,a),he(this,Mt,i),he(this,Ut,d),he(this,lt,h),he(this,ot,be(r)),he(this,ct,be(l)),he(this,ut,be(o)),he(this,dt,be(u))}setButtonPosition(e){K(this,ot)[1](e)}setPosition(e){K(this,ct)[1](e)}setInitialIsOpen(e){K(this,ut)[1](e)}setErrorTypes(e){K(this,dt)[1](e)}setClient(e){K(this,it)[1](e)}mount(e){if(K(this,Je))throw new Error("Devtools is already mounted");const s=sa(()=>{const n=this,[a]=K(this,ot),[i]=K(this,ct),[r]=K(this,ut),[l]=K(this,dt),[o]=K(this,it);let u;return K(this,ht)?u=K(this,ht):(u=ea(()=>Promise.resolve().then(()=>require("./HO4MOOFI-JAlxWmFC.cjs"))),he(this,ht,u)),Ta(K(this,Ut),K(this,lt)),$s(u,Hs({get queryFlavor(){return K(n,Bt)},get version(){return K(n,Gt)},get onlineManager(){return K(n,Mt)},get shadowDOMTarget(){return K(n,lt)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return i()},get initialIsOpen(){return r()},get errorTypes(){return l()}}))},e);he(this,Je,!0),he(this,Rt,s)}unmount(){var e;if(!K(this,Je))throw new Error("Devtools is not mounted");(e=K(this,Rt))==null||e.call(this),he(this,Je,!1)}},it=new WeakMap,Mt=new WeakMap,Bt=new WeakMap,Gt=new WeakMap,Je=new WeakMap,Ut=new WeakMap,lt=new WeakMap,ot=new WeakMap,ct=new WeakMap,ut=new WeakMap,dt=new WeakMap,ht=new WeakMap,Rt=new WeakMap,fn),mt,Ot,Ft,qt,et,zt,ft,gt,pt,xt,yt,vt,jt,$t,gn,Bo=(gn=class{constructor(e){me(this,mt);me(this,Ot);me(this,Ft);me(this,qt);me(this,et,!1);me(this,zt);me(this,ft);me(this,gt);me(this,pt);me(this,xt);me(this,yt);me(this,vt);me(this,jt);me(this,$t);const{client:s,queryFlavor:n,version:a,onlineManager:i,buttonPosition:r,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:f}=e;he(this,mt,be(s)),he(this,Ft,n),he(this,qt,a),he(this,Ot,i),he(this,zt,d),he(this,ft,h),he(this,gt,be(r)),he(this,pt,be(l)),he(this,xt,be(o)),he(this,yt,be(u)),he(this,vt,be(f))}setButtonPosition(e){K(this,gt)[1](e)}setPosition(e){K(this,pt)[1](e)}setInitialIsOpen(e){K(this,xt)[1](e)}setErrorTypes(e){K(this,yt)[1](e)}setClient(e){K(this,mt)[1](e)}setOnClose(e){K(this,vt)[1](()=>e)}mount(e){if(K(this,et))throw new Error("Devtools is already mounted");const s=sa(()=>{const n=this,[a]=K(this,gt),[i]=K(this,pt),[r]=K(this,xt),[l]=K(this,yt),[o]=K(this,mt),[u]=K(this,vt);let d;return K(this,jt)?d=K(this,jt):(d=ea(()=>Promise.resolve().then(()=>require("./HUY7CZI3-DNp5yuiu.cjs"))),he(this,jt,d)),Ta(K(this,zt),K(this,ft)),$s(d,Hs({get queryFlavor(){return K(n,Ft)},get version(){return K(n,qt)},get onlineManager(){return K(n,Ot)},get shadowDOMTarget(){return K(n,ft)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return i()},get initialIsOpen(){return r()},get errorTypes(){return l()},get onClose(){return u()}}))},e);he(this,et,!0),he(this,$t,s)}unmount(){var e;if(!K(this,et))throw new Error("Devtools is not mounted");(e=K(this,$t))==null||e.call(this),he(this,et,!1)}},mt=new WeakMap,Ot=new WeakMap,Ft=new WeakMap,qt=new WeakMap,et=new WeakMap,zt=new WeakMap,ft=new WeakMap,gt=new WeakMap,pt=new WeakMap,xt=new WeakMap,yt=new WeakMap,vt=new WeakMap,jt=new WeakMap,$t=new WeakMap,gn);function Go(e){const s=D.useQueryClient(e.client),n=je.useRef(null),{buttonPosition:a,position:i,initialIsOpen:r,errorTypes:l,styleNonce:o,shadowDOMTarget:u}=e,[d]=je.useState(new Mo({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:a,position:i,initialIsOpen:r,errorTypes:l,styleNonce:o,shadowDOMTarget:u}));return je.useEffect(()=>{d.setClient(s)},[s,d]),je.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),je.useEffect(()=>{i&&d.setPosition(i)},[i,d]),je.useEffect(()=>{d.setInitialIsOpen(r||!1)},[r,d]),je.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),je.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function Uo(e){const s=D.useQueryClient(e.client),n=je.useRef(null),{errorTypes:a,styleNonce:i,shadowDOMTarget:r}=e,[l]=je.useState(new Bo({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:i,shadowDOMTarget:r,onClose:e.onClose}));return je.useEffect(()=>{l.setClient(s)},[s,l]),je.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),je.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),je.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 Ro=process.env.NODE_ENV!=="development"?function(){return null}:Go;process.env.NODE_ENV;const Oo=()=>{const e=ae(),s=H();return D.useQuery({queryKey:[z,k.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:k.GET_COLLECTIONS})})},Fo=()=>{const{data:e}=De(),{data:s}=us(),{data:n}=Ye(),a=ae(),i=H(),r=m.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return D.useMutation({mutationFn:async({block:l})=>i(a,{action:k.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||r,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},Ca=()=>{const e=Rs();return m.useCallback(({pageId:s})=>{e(s)},[e])},qo=60*5;function zo(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:i}=Oe(),r=os(),l=m.useRef(null),o=m.useCallback(async()=>{if(!(!g.has(e,"accessToken")||!g.has(e,"refreshToken")))try{const u=await ks(r,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!u.ok){n();return}const d=await u.json();g.has(d,"id")&&g.has(d,"email")&&g.has(d,"accessToken")&&g.has(d,"refreshToken")?s(d):n()}catch{n()}},[e,n,s,r]);return m.useEffect(()=>{a&&i&&o()},[i,a,o]),m.useEffect(()=>{if(!a||!g.has(e,"expiresAt")||!g.has(e,"refreshToken")||!g.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!g.has(e,"expiresAt"))return;const u=Math.floor(Date.now()/1e3),d=e.expiresAt-u;d<qo&&d>0&&o()},1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[a,e==null?void 0:e.expiresAt,e==null?void 0:e.refreshToken,e==null?void 0:e.accessToken,r]),null}const Pa=()=>t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/40",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(N.Loader2,{className:"size-5 animate-spin"})})}),$o=m.lazy(()=>Promise.resolve().then(()=>Ri));Ma.loadWebBlocks();W.registerChaiTopBar(pi);Wi();W.registerChaiMediaManager($o);W.registerChaiSaveToLibrary(cr);const Ho=e=>{const s=m.useRef([]),[n]=_e(),a=n.get("page"),{data:i}=De(),{data:r={role:"",permissions:null}}=Gn();ji();const{data:l,isFetching:o}=wn(),{blocks:u}=vi(l),{data:d}=Ne(),{mutateAsync:h}=jn(),f=xi(),{onSave:j}=bi(),{getPartialBlocks:y,getPartialBlockBlocks:x}=Ei(),{aiContext:E,setAiContext:b}=Is(),{mutateAsync:U}=hr(),[w,B]=m.useState(!1),{data:S}=Ye(),_=_s(),{data:O}=Ls(),{data:V}=Oo(),{mutateAsync:ne}=Fo(),G=Ca();Ka(),m.useEffect(()=>{const Q=()=>{document.hidden?B(!0):B(!1)};return window.addEventListener("visibilitychange",Q),()=>window.removeEventListener("visibilitychange",Q)},[]),s.current=u;const L=m.useMemo(()=>{const Q={};return r&&(Q.permissions=g.get(r,"permissions",null),Q.role=g.get(r,"role","user")),Q},[r]),F=m.useCallback(async(Q,X)=>await U({pageType:Q,query:X}),[U]),Y=m.useMemo(()=>g.get(S,"theme",{})||{},[S]);return t.jsxs(t.Fragment,{children:[o&&t.jsx(Pa,{}),t.jsx(W.ChaiBuilderEditor,{gotoPage:G,collections:V??[],getBlockAsyncProps:ne,pageExternalData:O,themePresets:e.themePresets??[],pageId:i==null?void 0:i.id,loading:o,fallbackLang:_,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:!w&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:x,getPartialBlocks:y,blocks:o?[]:u,theme:g.cloneDeep(Y),pageTypes:d,searchPageTypeItems:F,saveAiContextCallback:async Q=>{if(!a)return!0;const X=s.current,le={_type:"@chai/ai-context",_value:g.isString(Q)?Q:""},I=[...X,le];return await j({page:a,blocks:I}),b(Q),!0},aiContext:E,askAiCallBack:f,onSave:async({blocks:Q,theme:X})=>{if(!a)return!0;s.current=Q;const le={_type:"@chai/ai-context",_value:g.isString(E)?E:""},I=[...Q,le];return await j({page:a,blocks:I}),s.current=I,g.isEqual(X,Y)||await h({settings:{theme:X}}),!0},themePanelComponent:br,...L}),t.jsxs("div",{children:[t.jsx(Za,{}),t.jsx(Ja,{})]})]})},Vo=new D.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Ko=e=>{zo();const{isLoggedIn:s,isSessionExpired:n}=Oe(),[,a]=bn(),[i,r]=m.useState(!1);return m.useEffect(()=>(a(g.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),a({})}),[e,a]),i?t.jsxs(D.QueryClientProvider,{client:Vo,children:[s?n?t.jsx(Pa,{}):t.jsx(Ho,{...e}):t.jsx(Ai,{}),t.jsx(Ro,{}),t.jsx($.Toaster,{richColors:!0})]}):t.jsx("div",{})},Wo=()=>{const e=ae(),s=H(),{data:n}=us(),a=D.useQueryClient();return D.useMutation({mutationFn:async i=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:k.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:i}})},onSuccess:()=>{a.invalidateQueries({queryKey:[z,k.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[z,k.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},Qo=()=>{const{user:e,logout:s}=Oe(),n=e==null?void 0:e.accessToken;return m.useCallback(async({url:a,method:i="GET",body:r={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const o=await fetch(a,{method:i,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(r)});if(o.status===401)return console.log("Session expired",o),await s(),null;if(o.status===400)throw new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",o),o}},[n,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=Fs;exports.ChaiBuilderPages=Ko;exports.Dynamic=$l;exports.For=xl;exports.ImagePicker=On;exports.Index=yl;exports.Match=bl;exports.NestedPathSelector=Ge;exports.PermissionChecker=Me;exports.Portal=zl;exports.Show=vl;exports.Switch=jl;exports.addEventListener=ra;exports.batch=Ji;exports.className=aa;exports.clearDelegatedEvents=Ll;exports.convertRemToPixels=Lo;exports.createComponent=$s;exports.createComputed=Vn;exports.createContext=rl;exports.createEffect=qs;exports.createMemo=Le;exports.createRenderEffect=Ve;exports.createRoot=He;exports.createSignal=be;exports.createUniqueId=pl;exports.delegateEvents=na;exports.deleteNestedDataByPath=Tt;exports.displayValue=To;exports.getMutationStatusColor=No;exports.getPreferredColorScheme=Do;exports.getQueryStatusColor=wo;exports.getQueryStatusColorByLabel=Ao;exports.getQueryStatusLabel=Eo;exports.getSidedProp=So;exports.insert=ls;exports.mergeProps=Hs;exports.mutationSortFns=_o;exports.on=el;exports.onCleanup=bt;exports.onMount=Kn;exports.registerLoginComponent=Ni;exports.serialize=wa;exports.setAttribute=is;exports.sortFns=ko;exports.splitProps=Jn;exports.spread=ia;exports.stringify=bo;exports.template=_l;exports.untrack=we;exports.updateNestedDataByPath=At;exports.use=la;exports.useActivePage=us;exports.useBuilderPageData=Ls;exports.useChaiAuth=Oe;exports.useChaiFetch=Qo;exports.useChaiUserInfo=tt;exports.useContext=il;exports.useCurrentPage=De;exports.useFallbackLang=_s;exports.useFetch=H;exports.useGotoPage=Ca;exports.useLanguagePages=Qe;exports.usePageTypes=Ne;exports.useTransition=al;exports.useUpdateActivePageMetadata=Wo;exports.useUserRoleAndPermissions=Gn;exports.useWebsitePages=Vt;exports.useWebsiteSetting=Ye;