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